code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
-- | -- Module : Algebra.Closure.Set.BreadthFirst -- Copyright : (c) Joseph Abrahamson 2013 -- License : MIT -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable -- -- Depth-first closed sets. For a particular endomorphism @(p :: a -> -- a)@ a 'Closed' set is a set where if some element @x@ is in the set -- then so is @p x@. Unlike "Algebra.Closure.Set.DepthFirst", this -- algorithm computes the closure in a breadth-first manner and thus can -- be useful for computing infinite closures. -- -- It's reasonable to think of a breadth-first 'Closed' set as the -- process of generating a depth-first -- 'Algebra.Closure.Set.DepthFirst.Closed' set frozen in time. This -- retains information about the number of iterations required for -- stability and allows us to return answers that depend only upon -- partial information even if the closure itself is unbounded. module Algebra.Closure.Set.BreadthFirst ( -- * Closed sets Closed, seenBy, seen, -- ** Operations memberWithin', memberWithin, member', member, -- ** Creation close, ) where import Prelude hiding (foldr) import Control.Applicative import Data.HashSet (HashSet) import Data.Hashable import Data.Foldable (Foldable, foldr, toList) import qualified Data.HashSet as Set -- | A closed set @Closed a@, given an endomorphism @(p :: a -> a)@, -- is a set where if some element @x@ is in the set then so is @p x@. data Closed a = Closed Int (a -> a) (ClosedF a) data ClosedF a = Unchanging (HashSet a) | ClosedF (HashSet a) (ClosedF a) -- | (Internal) Get the immediate HashSet setOf :: ClosedF a -> HashSet a setOf (Unchanging set ) = set setOf (ClosedF set _) = set data Omega a = A a | O deriving ( Eq, Ord ) opred :: Enum a => Omega a -> Omega a opred O = O opred (A a) = A (pred a) instance Functor Omega where fmap f O = O fmap f (A a) = A (f a) instance Applicative Omega where pure = A O <*> _ = O _ <*> O = O A f <*> A x = A $ f x instance Num a => Num (Omega a) where (+) = liftA2 (+) (-) = liftA2 (-) (*) = liftA2 (*) abs = fmap abs negate = fmap negate signum = fmap signum fromInteger = pure . fromInteger -- | @seenBy n@ converts a 'Closed' set into its underlying set, -- approximated by at least @n@ iterations. seenByG :: Omega Int -> Closed a -> HashSet a seenByG n (Closed m _ closef) | n - A m < 0 = setOf closef | otherwise = seenByI (n - A m) closef where seenByI 0 closef = setOf closef seenByI n (Unchanging set) = set seenByI n (ClosedF _ next) = seenByI (opred n) next -- | @seenBy n@ converts a 'Closed' set into its underlying set, -- approximated by at least @n@ iterations. seenBy :: Int -> Closed a -> HashSet a seenBy n = seenByG (A n) -- | Converts a 'Closed' set into its underlying set. If the 'Closed' -- set is unbounded then this operation is undefined (see -- 'seenBy'). It's reasonable to think of this operation as -- -- @ -- let omega = succ omega in seenBy omega -- @ seen :: Closed a -> HashSet a seen = seenByG O memberWithinG' :: (Hashable a, Eq a) => Omega Int -> a -> Closed a -> (Bool, Closed a) memberWithinG' n a closed@(Closed m iter closef) | n - A m < 0 = (Set.member a (setOf closef), closed) | otherwise = memberWithinI (n - A m) 0 closef where memberWithinI 0 up closef = -- We KNOW that 'n' cannot be 'O' here since it was able to be -- decremented to 0. case n of O -> error "Algebra.Closure.Set.BreadthFirst: Impossible" (A n') -> (Set.member a (setOf closef), Closed n' iter closef) memberWithinI dn up closef@(ClosedF set next) | Set.member a set = (True, Closed (m + up) iter closef) | otherwise = memberWithinI (opred dn) (succ up) next -- | @memberWithin' n a@ checks to see whether an element is within a -- 'Closed' set after @n@ improvements (but does not guarantee the @n@ -- is the minimal number needed). The 'Closed' set returned is a -- compressed, memoized 'Closed' set which may be faster to query. memberWithin' :: (Hashable a, Eq a) => Int -> a -> Closed a -> (Bool, Closed a) memberWithin' n = memberWithinG' (A n) -- | @memberWithin' n a@ checks to see whether an element is within a -- 'Closed' set after @n@ improvements. memberWithin :: (Hashable a, Eq a) => Int -> a -> Closed a -> Bool memberWithin n a = fst . memberWithin' n a -- | Determines whether a particular element is in the 'Closed' -- set. If the element is in the set, this operation is always -- defined. If it is not and the set is unbounded, this operation is -- undefined (see 'memberWithin'). It's reasonable to think of this -- operation as -- -- @ -- let omega = succ omega in memberWithin omega -- @ -- The 'Closed' set returned is a compressed, memoized 'Closed' set -- which may be faster to query. member' :: (Hashable a, Eq a) => a -> Closed a -> (Bool, Closed a) member' = memberWithinG' O -- | Determines whether a particular element is in the 'Closed' -- set. If the element is in the set, this operation is always -- defined. If it is not and the set is unbounded, this operation is -- undefined (see 'memberWithin'). It's reasonable to think of this -- operation as -- -- @ -- let omega = succ omega in memberWithin omega -- @ member :: (Hashable a, Eq a) => a -> Closed a -> Bool member a = fst . member' a -- | Converts any 'Foldable' container into the 'Closed' set of its -- contents. close :: (Hashable a, Eq a, Foldable t) => (a -> a) -> t a -> Closed a close iter = Closed 0 iter . build Set.empty . toList where inserter :: (Hashable a, Eq a) => a -> (HashSet a, [a]) -> (HashSet a, [a]) inserter a (set, fresh) | Set.member a set = (set, fresh) | otherwise = (Set.insert a set, a:fresh) build curr [] = Unchanging curr build curr as = ClosedF curr $ step (foldr inserter (curr, []) as) step (set, added) = build set (map iter added) -- insert :: a -> Closed a -> Closed a -- insert a Unchanging = -- insert a (Closed n iter set next) =
tel/closure
src/Algebra/Closure/Set/BreadthFirst.hs
mit
6,074
0
13
1,380
1,500
801
699
74
3
module Chapter4Spec (spec) where import Test.Hspec import Chapter4 spec :: Spec spec = do describe "4.1: Convert numbers to words" $ do it "should convert numbers to words" $ do convert 23 `shouldBe` "twenty-three" convert 123 `shouldBe` "one hundred and twenty-three" convert 308000 `shouldBe` "three hundred and eight thousand" convert 369027 `shouldBe` "three hundred and sixty-nine thousand and twenty-seven" convert 369401 `shouldBe` "three hundred and sixty-nine thousand four hundred and one" it "should convert numbers to words and adds full stop at the end" $ do convertWithFullStop 23 `shouldBe` "twenty-three." convertWithFullStop 123 `shouldBe` "one hundred and twenty-three." convertWithFullStop 308000 `shouldBe` "three hundred and eight thousand." convertWithFullStop 369027 `shouldBe` "three hundred and sixty-nine thousand and twenty-seven." convertWithFullStop 369401 `shouldBe` "three hundred and sixty-nine thousand four hundred and one." it "should convert numbers to words up to one billion exclusive" $ do pending -- convertWithFullStop 3080000 `shouldBe` "three million and eighty thousand." -- convertWithFullStop 3690270 `shouldBe` "three million six hundred and ninety hundred thousand and two hundred and seventy." -- convertWithFullStop 369270000 `shouldBe` "three hundred and sixty-nine million and two hundred and sixty-nine thousand." it "should convert negative numbers to words" $ do convertNatural (-23) `shouldBe` "minus twenty-three." convertNatural (-123) `shouldBe` "minus one hundred and twenty-three." convertNatural (-308000) `shouldBe` "minus three hundred and eight thousand." it "should convert a whole number of pence into words" $ do convertMoney 3649 `shouldBe` "thirty-six pounds and forty-nine pence" convertMoney 3600049 `shouldBe` "thirty-six thousand pounds and forty-nine pence" it "should convert words to numbers" $ do numToNum 6 `shouldBe` 6 numToNum 13 `shouldBe` 13 numToNum 23 `shouldBe` 23 numToNum 123 `shouldBe` 123 numToNum 1023 `shouldBe` 1023 numToNum 1123 `shouldBe` 1123 numToNum 308000 `shouldBe` 308000 numToNum 369027 `shouldBe` 369027 numToNum 369401 `shouldBe` 369401 where numToNum x = reverseConvert . convert $ x
futtetennista/IntroductionToFunctionalProgramming
test/Chapter4Spec.hs
mit
2,499
0
16
605
424
211
213
40
1
module Main where import ArExp (Term (..), evalAll) main :: IO () main = do let e = evalAll (TmIsZero (TmIf TmZero (TmSucc TmZero) TmZero)) print e
ysukhoverkhov/taplic4
app/04/Main.hs
mit
164
0
16
43
74
39
35
6
1
--this program checks if this is a palyndrome main = interact respondPalindromes respondPalindromes contents = unlines (map (\xs -> if isPalindrome xs then "palindrome" else "not a palindrome") (lines contents)) where isPalindrome xs = xs == reverse xs
luisgepeto/HaskellLearning
09 Input and Output/02_files_and_streams_2.hs
mit
258
0
11
43
71
36
35
3
2
-- Interpolation Phalanx -- http://www.codewars.com/kata/543cb1d8f6b726292d0000d7/ module Phalanx where import Data.Monoid import Data.String import Control.Monad (liftM, liftM2) type Name = String data Phalanx = Literal String | Empty | Join Phalanx Phalanx | Repeat Int Phalanx | Lookup Name instance IsString Phalanx where fromString = Literal instance Monoid Phalanx where mempty = Empty mappend = Join rep :: Int -> Phalanx -> Phalanx rep = Repeat l :: Name -> Phalanx l = Lookup interp :: (Name -> Maybe String) -> Phalanx -> Maybe String interp f Empty = Just "" interp f (Literal s) = Just s interp f (Join p1 p2) = liftM2 (++) (interp f p1) (interp f p2) interp f (Repeat n p) = liftM (concat . replicate n) (interp f p) interp f (Lookup name) = f name
gafiatulin/codewars
src/6 kyu/Phalanx.hs
mit
794
0
8
164
290
155
135
26
1
{-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module HsToCoq.Util.GHC.DynFlags (module DynFlags) where import DynFlags import Control.Monad.Trans import qualified Control.Monad.Trans.Identity as I import qualified Control.Monad.Trans.Writer.Strict as WS import qualified Control.Monad.Trans.State.Strict as SS import qualified Control.Monad.Trans.State.Lazy as SL import qualified Control.Monad.Trans.RWS.Strict as RWSS import qualified Control.Monad.Trans.RWS.Lazy as RWSL import qualified Control.Monad.Trans.Cont as C import qualified Control.Monad.Trans.Counter as C -- Existing instances: Reader, lazy Writer, Maybe, and Except instance HasDynFlags m => HasDynFlags (I.IdentityT m) where getDynFlags = I.IdentityT getDynFlags instance (HasDynFlags m, Functor m, Monoid w) => HasDynFlags (WS.WriterT w m) where getDynFlags = WS.WriterT $ (,mempty) <$> getDynFlags instance (HasDynFlags m, Functor m) => HasDynFlags (SS.StateT s m) where getDynFlags = SS.StateT $ \s -> (,s) <$> getDynFlags instance (HasDynFlags m, Functor m) => HasDynFlags (SL.StateT s m) where getDynFlags = SL.StateT $ \s -> (,s) <$> getDynFlags instance (HasDynFlags m, Functor m, Monoid w) => HasDynFlags (RWSS.RWST r w s m) where getDynFlags = RWSS.RWST $ \_ s -> (,s,mempty) <$> getDynFlags instance (HasDynFlags m, Functor m, Monoid w) => HasDynFlags (RWSL.RWST r w s m) where getDynFlags = RWSL.RWST $ \_ s -> (,s,mempty) <$> getDynFlags instance (HasDynFlags m, Monad m) => HasDynFlags (C.ContT r m) where getDynFlags = C.ContT (getDynFlags >>=) instance (HasDynFlags m, Monad m) => HasDynFlags (C.CounterT m) where getDynFlags = lift getDynFlags
antalsz/hs-to-coq
src/lib/HsToCoq/Util/GHC/DynFlags.hs
mit
1,751
0
9
318
546
320
226
29
0
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} -- | -- Module: TestCase.Network.SIP.Serialization.Uri -- Description: Test of the URI serialization. -- Copyright: Copyright (c) 2015-2016 Jan Sipr -- License: MIT module TestCase.Network.SIP.Serialization.Uri (tests) where import Data.ByteString (ByteString) import Data.Function (($), (.)) import Data.Maybe (Maybe(Just, Nothing)) import Test.Framework.Providers.HUnit (testCase) import Test.Framework (Test, testGroup) import Test.HUnit.Base (Assertion, (@=?)) import Network.SIP.Serialization.Uri (serializeUri) import Network.SIP.Type.Uri (Uri(Uri), Scheme(SIP, SIPS)) testUri :: ByteString -> Uri -> Assertion testUri r uri = r @=? serializeUri uri tests :: [Test] tests = [ testGroup "URI serialization tests" [ testCase "URI with no user and port" . testUri "sip:10.10.10.10" $ Uri SIP Nothing "10.10.10.10" Nothing , testCase "URI with user and port" . testUri "sips:[email protected]:1234" $ Uri SIPS (Just "user") "10.10.10.10" (Just 1234) , testCase "URI with no user and with port" . testUri "sips:10.10.10.10:1234" $ Uri SIPS Nothing "10.10.10.10" (Just 1234) , testCase "URI with user and with no port" . testUri "sips:[email protected]" $ Uri SIPS (Just "user") "10.10.10.10" Nothing ] ]
Siprj/ragnarok
test/TestCase/Network/SIP/Serialization/Uri.hs
mit
1,427
0
11
318
321
186
135
27
1
module Data.OneOrMore ( module Data.OneOrMore.Definition ) where import Data.OneOrMore.Definition
thinkpad20/oneormore
src/Data/OneOrMore.hs
mit
102
0
5
13
21
14
7
3
0
{-# LANGUAGE OverloadedStrings #-} module UserSpec (spec) where import Test.Hspec (Spec, describe, it, shouldBe) import AppContext (HasDbConn(..)) import qualified User as U spec :: HasDbConn a => a -> Spec spec context = describe "User" $ do let conn = getDbConn context it "can find by id" $ do user <- U.create conn "user" "email" found <- U.runUserFindQuery conn $ U.findQuery (U._userId user) found `shouldBe` Just user it "returns nothing if id not found" $ do found <- U.runUserFindQuery conn $ U.findQuery (U.UserId 0) found `shouldBe` Nothing
robertjlooby/scotty-story-board
test/models/UserSpec.hs
mit
629
0
16
164
205
104
101
15
1
import Data.Char import Data.Bits import Data.List import Data.Ord toStr xs = concat $ map (\x -> (chr x):"") xs frequency s = map (\x->([head x], length x)) . group . sort $ s frequencySorted s = reverse . sortBy (comparing snd) $ frequency s every n xs = case drop (n-1) xs of (y:ys) -> y : every n ys [] -> [] every3 n xs = every 3 (drop n ([0,0] ++ xs)) mapXor s1 s2 = map (\(x,y) -> x `xor` y) $ zip s1 s2 cycleKey str key = let key' = take (length str) (cycle key) in mapXor str key' testKey key = do dat <- readFile "p059_cipher.txt" let nums = read ("[" ++ dat ++ "]") :: [Int] let dec = cycleKey nums key putStrLn $ toStr dec getValue str = sum $ map ord str main = do dat <- readFile "p059_cipher.txt" let nums = read ("[" ++ dat ++ "]") :: [Int] let f1 = frequencySorted $ every3 0 nums let f2 = frequencySorted $ every3 1 nums let f3 = frequencySorted $ every3 2 nums putStrLn $ show f3 let dec = cycleKey nums [103,111,100] putStrLn $ toStr dec putStrLn $ show $ getValue (toStr dec) --putStrLn $ show $ every3 0 nums
stefan-j/ProjectEuler
q58.hs
mit
1,140
2
13
320
561
276
285
30
2
module GHCJS.DOM.SVGAnimatedString ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/SVGAnimatedString.hs
mit
47
0
3
7
10
7
3
1
0
module Main where main = print $ myButLast [1,2,3,4,5,6,7] --myLast :: Integer -> Integer --myButLast [x] = x myButLast (x:(_:[])) = x myButLast (x:xs) = myButLast x
Rsgm/Haskell-problems
2.hs
mit
173
0
10
34
81
47
34
5
1
{-# LANGUAGE RankNTypes #-} -- | Higher-level functions to interact with the elements of a stream. Most of -- these are based on list functions. -- -- Note that these functions all deal with individual elements of a stream as a -- sort of \"black box\", where there is no introspection of the contained -- elements. Values such as @ByteString@ and @Text@ will likely need to be -- treated specially to deal with their contents properly (@Word8@ and @Char@, -- respectively). See the "Data.Conduit.Binary" and "Data.Conduit.Text" -- modules. module Data.Conduit.List ( -- * Sources sourceList , sourceNull , unfold , enumFromTo , iterate -- * Sinks -- ** Pure , fold , foldMap , take , drop , head , peek , consume , sinkNull -- ** Monadic , foldMapM , foldM , mapM_ -- * Conduits -- ** Pure , map , mapMaybe , mapFoldable , catMaybes , concat , concatMap , concatMapAccum , scanl , groupBy , isolate , filter -- ** Monadic , mapM , iterM , scanlM , mapMaybeM , mapFoldableM , concatMapM , concatMapAccumM -- * Misc , sequence ) where import qualified Prelude import Prelude ( ($), return, (==), (-), Int , (.), id, Maybe (..), Monad , Bool (..) , (>>) , (>>=) , seq , otherwise , Enum (succ), Eq , maybe , either ) import Data.Monoid (Monoid, mempty, mappend) import qualified Data.Foldable as F import Data.Conduit import Control.Monad (when, (<=<), liftM) import Control.Monad.Trans.Class (lift) -- | Generate a source from a seed value. -- -- Since 0.4.2 unfold :: Monad m => (b -> Maybe (a, b)) -> b -> Producer m a unfold f = go where go seed = case f seed of Just (a, seed') -> yield a >> go seed' Nothing -> return () sourceList :: Monad m => [a] -> Producer m a sourceList = Prelude.mapM_ yield -- | Enumerate from a value to a final value, inclusive, via 'succ'. -- -- This is generally more efficient than using @Prelude@\'s @enumFromTo@ and -- combining with @sourceList@ since this avoids any intermediate data -- structures. -- -- Since 0.4.2 enumFromTo :: (Enum a, Eq a, Monad m) => a -> a -> Producer m a enumFromTo start stop = go start where go i | i == stop = yield i | otherwise = yield i >> go (succ i) -- | Produces an infinite stream of repeated applications of f to x. iterate :: Monad m => (a -> a) -> a -> Producer m a iterate f = go where go a = yield a >> go (f a) -- | A strict left fold. -- -- Since 0.3.0 fold :: Monad m => (b -> a -> b) -> b -> Consumer a m b fold f = loop where loop accum = await >>= maybe (return accum) go where go a = let accum' = f accum a in accum' `seq` loop accum' -- | A monadic strict left fold. -- -- Since 0.3.0 foldM :: Monad m => (b -> a -> m b) -> b -> Consumer a m b foldM f = loop where loop accum = do await >>= maybe (return accum) go where go a = do accum' <- lift $ f accum a accum' `seq` loop accum' -- | A monoidal strict left fold. -- -- Since 0.5.3 foldMap :: (Monad m, Monoid b) => (a -> b) -> Consumer a m b foldMap f = fold combiner mempty where combiner accum = mappend accum . f -- | A monoidal strict left fold in a Monad. -- -- Since 1.0.8 foldMapM :: (Monad m, Monoid b) => (a -> m b) -> Consumer a m b foldMapM f = foldM combiner mempty where combiner accum = liftM (mappend accum) . f -- | Apply the action to all values in the stream. -- -- Since 0.3.0 mapM_ :: Monad m => (a -> m ()) -> Consumer a m () mapM_ f = awaitForever $ lift . f -- | Ignore a certain number of values in the stream. This function is -- semantically equivalent to: -- -- > drop i = take i >> return () -- -- However, @drop@ is more efficient as it does not need to hold values in -- memory. -- -- Since 0.3.0 drop :: Monad m => Int -> Consumer a m () drop = loop where loop 0 = return () loop count = await >>= maybe (return ()) (\_ -> loop (count - 1)) -- | Take some values from the stream and return as a list. If you want to -- instead create a conduit that pipes data to another sink, see 'isolate'. -- This function is semantically equivalent to: -- -- > take i = isolate i =$ consume -- -- Since 0.3.0 take :: Monad m => Int -> Consumer a m [a] take = loop id where loop front 0 = return $ front [] loop front count = await >>= maybe (return $ front []) (\x -> loop (front .(x:)) (count - 1)) -- | Take a single value from the stream, if available. -- -- Since 0.3.0 head :: Monad m => Consumer a m (Maybe a) head = await -- | Look at the next value in the stream, if available. This function will not -- change the state of the stream. -- -- Since 0.3.0 peek :: Monad m => Consumer a m (Maybe a) peek = await >>= maybe (return Nothing) (\x -> leftover x >> return (Just x)) -- | Apply a transformation to all values in a stream. -- -- Since 0.3.0 map :: Monad m => (a -> b) -> Conduit a m b map f = awaitForever $ yield . f {- It might be nice to include these rewrite rules, but they may have subtle differences based on leftovers. {-# RULES "map-to-mapOutput pipeL" forall f src. pipeL src (map f) = mapOutput f src #-} {-# RULES "map-to-mapOutput $=" forall f src. src $= (map f) = mapOutput f src #-} {-# RULES "map-to-mapOutput pipe" forall f src. pipe src (map f) = mapOutput f src #-} {-# RULES "map-to-mapOutput >+>" forall f src. src >+> (map f) = mapOutput f src #-} {-# RULES "map-to-mapInput pipeL" forall f sink. pipeL (map f) sink = mapInput f (Prelude.const Prelude.Nothing) sink #-} {-# RULES "map-to-mapInput =$" forall f sink. map f =$ sink = mapInput f (Prelude.const Prelude.Nothing) sink #-} {-# RULES "map-to-mapInput pipe" forall f sink. pipe (map f) sink = mapInput f (Prelude.const Prelude.Nothing) sink #-} {-# RULES "map-to-mapInput >+>" forall f sink. map f >+> sink = mapInput f (Prelude.const Prelude.Nothing) sink #-} {-# RULES "map-to-mapOutput =$=" forall f con. con =$= map f = mapOutput f con #-} {-# RULES "map-to-mapInput =$=" forall f con. map f =$= con = mapInput f (Prelude.const Prelude.Nothing) con #-} {-# INLINE [1] map #-} -} -- | Apply a monadic transformation to all values in a stream. -- -- If you do not need the transformed values, and instead just want the monadic -- side-effects of running the action, see 'mapM_'. -- -- Since 0.3.0 mapM :: Monad m => (a -> m b) -> Conduit a m b mapM f = awaitForever $ yield <=< lift . f -- | Apply a monadic action on all values in a stream. -- -- This @Conduit@ can be used to perform a monadic side-effect for every -- value, whilst passing the value through the @Conduit@ as-is. -- -- > iterM f = mapM (\a -> f a >>= \() -> return a) -- -- Since 0.5.6 iterM :: Monad m => (a -> m ()) -> Conduit a m a iterM f = awaitForever $ \a -> lift (f a) >> yield a -- | Apply a transformation that may fail to all values in a stream, discarding -- the failures. -- -- Since 0.5.1 mapMaybe :: Monad m => (a -> Maybe b) -> Conduit a m b mapMaybe f = awaitForever $ maybe (return ()) yield . f -- | Apply a monadic transformation that may fail to all values in a stream, -- discarding the failures. -- -- Since 0.5.1 mapMaybeM :: Monad m => (a -> m (Maybe b)) -> Conduit a m b mapMaybeM f = awaitForever $ maybe (return ()) yield <=< lift . f -- | Filter the @Just@ values from a stream, discarding the @Nothing@ values. -- -- Since 0.5.1 catMaybes :: Monad m => Conduit (Maybe a) m a catMaybes = awaitForever $ maybe (return ()) yield -- | Generalization of 'catMaybes'. It puts all values from -- 'F.Foldable' into stream. -- -- Since 1.0.6 concat :: (Monad m, F.Foldable f) => Conduit (f a) m a concat = awaitForever $ F.mapM_ yield -- | Apply a transformation to all values in a stream, concatenating the output -- values. -- -- Since 0.3.0 concatMap :: Monad m => (a -> [b]) -> Conduit a m b concatMap f = awaitForever $ sourceList . f -- | Apply a monadic transformation to all values in a stream, concatenating -- the output values. -- -- Since 0.3.0 concatMapM :: Monad m => (a -> m [b]) -> Conduit a m b concatMapM f = awaitForever $ sourceList <=< lift . f -- | 'concatMap' with an accumulator. -- -- Since 0.3.0 concatMapAccum :: Monad m => (a -> accum -> (accum, [b])) -> accum -> Conduit a m b concatMapAccum f x0 = scanl f x0 =$= concat -- | Analog of 'Prelude.scanl' for lists. -- -- Since 1.0.6 scanl :: Monad m => (a -> s -> (s,b)) -> s -> Conduit a m b scanl f = loop where loop s = await >>= F.mapM_ go where go a = case f a s of (s',b) -> yield b >> loop s' -- | Monadic scanl. -- -- Since 1.0.6 scanlM :: Monad m => (a -> s -> m (s,b)) -> s -> Conduit a m b scanlM f = loop where loop s = await >>= F.mapM_ go where go a = do (s',b) <- lift $ f a s yield b >> loop s' -- | 'concatMapM' with an accumulator. -- -- Since 0.3.0 concatMapAccumM :: Monad m => (a -> accum -> m (accum, [b])) -> accum -> Conduit a m b concatMapAccumM f x0 = scanlM f x0 =$= concat -- | Generalization of 'mapMaybe' and 'concatMap'. It applies function -- to all values in a stream and send values inside resulting -- 'Foldable' downstream. -- -- Since 1.0.6 mapFoldable :: (Monad m, F.Foldable f) => (a -> f b) -> Conduit a m b mapFoldable f = awaitForever $ F.mapM_ yield . f -- | Monadic variant of 'mapFoldable'. -- -- Since 1.0.6 mapFoldableM :: (Monad m, F.Foldable f) => (a -> m (f b)) -> Conduit a m b mapFoldableM f = awaitForever $ F.mapM_ yield <=< lift . f -- | Consume all values from the stream and return as a list. Note that this -- will pull all values into memory. For a lazy variant, see -- "Data.Conduit.Lazy". -- -- Since 0.3.0 consume :: Monad m => Consumer a m [a] consume = loop id where loop front = await >>= maybe (return $ front []) (\x -> loop $ front . (x:)) -- | Grouping input according to an equality function. -- -- Since 0.3.0 groupBy :: Monad m => (a -> a -> Bool) -> Conduit a m [a] groupBy f = start where start = await >>= maybe (return ()) (loop id) loop rest x = await >>= maybe (yield (x : rest [])) go where go y | f x y = loop (rest . (y:)) x | otherwise = yield (x : rest []) >> loop id y -- | Ensure that the inner sink consumes no more than the given number of -- values. Note this this does /not/ ensure that the sink consumes all of those -- values. To get the latter behavior, combine with 'sinkNull', e.g.: -- -- > src $$ do -- > x <- isolate count =$ do -- > x <- someSink -- > sinkNull -- > return x -- > someOtherSink -- > ... -- -- Since 0.3.0 isolate :: Monad m => Int -> Conduit a m a isolate = loop where loop 0 = return () loop count = await >>= maybe (return ()) (\x -> yield x >> loop (count - 1)) -- | Keep only values in the stream passing a given predicate. -- -- Since 0.3.0 filter :: Monad m => (a -> Bool) -> Conduit a m a filter f = awaitForever $ \i -> when (f i) (yield i) -- | Ignore the remainder of values in the source. Particularly useful when -- combined with 'isolate'. -- -- Since 0.3.0 sinkNull :: Monad m => Consumer a m () sinkNull = awaitForever $ \_ -> return () -- | A source that outputs no values. Note that this is just a type-restricted -- synonym for 'mempty'. -- -- Since 0.3.0 sourceNull :: Monad m => Producer m a sourceNull = return () -- | Run a @Pipe@ repeatedly, and output its result value downstream. Stops -- when no more input is available from upstream. -- -- Since 0.5.0 sequence :: Monad m => Consumer i m o -- ^ @Pipe@ to run repeatedly -> Conduit i m o sequence sink = self where self = awaitForever $ \i -> leftover i >> sink >>= yield
moonKimura/conduit-1.0.8
Data/Conduit/List.hs
mit
12,112
1
15
3,204
3,009
1,621
1,388
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE GADTs #-} module Ringo.Generator.Internal where import qualified Data.Map as Map import qualified Data.Text as Text import Database.HsSqlPpp.Syntax (ScalarExpr) import Data.List (find) import Data.Monoid ((<>)) import Data.Text (Text) import Ringo.Generator.Sql import Ringo.Types coalesceColumn :: TypeDefaults -> TableName -> Column -> ScalarExpr coalesceColumn defaults tName Column{..} = if columnNullable == Null then app "coalesce" [fqColName, num $ defVal columnType] else fqColName where fqColName = eqi tName columnName defVal colType = maybe (error $ "Default value not known for column type: " ++ Text.unpack colType) snd . find (\(k, _) -> k `Text.isPrefixOf` colType) . Map.toList $ defaults suffixTableName :: TablePopulationMode -> Text -> TableName -> TableName suffixTableName popMode suffix tableName = case popMode of FullPopulation -> tableName <> suffix IncrementalPopulation -> tableName
abhin4v/ringo
ringo-core/src/Ringo/Generator/Internal.hs
mit
1,096
0
14
235
274
155
119
27
2
import Command.Log ( gtLog ) import Git ( commitLog, commitOid ) import Data.Tagged ( untag ) import qualified Data.Text as Text main :: IO () main = gtLog >>= mapM_ printCommit where printCommit c = putStrLn $ unwords [ take 7 $ show $ untag $ commitOid c , Text.unpack $ head $ Text.lines $ commitLog c ]
cblp/gt
Command/LogMain.hs
gpl-2.0
366
0
13
117
122
65
57
9
1
#!/usr/bin/env runhaskell -- | Counting DNA Nucleotides -- Usage: DNA <dataset.txt> import System.Environment(getArgs) import Data.List(intercalate) import qualified Data.ByteString.Char8 as C main = do (file:_) <- getArgs dna <- C.readFile file display . counts . head . C.lines $ dna where display = putStrLn . intercalate " " . map show counts = map C.length . C.group . C.sort
kerkomen/rosalind-haskell
stronghold/DNA.hs
gpl-2.0
395
0
10
72
128
68
60
9
1
-- xmonad: Personal module: Hook Layout -- Author: Simon L. J. Robin | https://sljrobin.org -------------------------------------------------------------------------------- module Hook_Layout where -------------------------------------------------------------------------------- -- * `Appearance` -> Loads colors, dimensions and fonts -- * `XMonad.Hooks.ManageDocks` -> Provide tools to manage docks -- * `XMonad.Layout.Grid` -> Puts windows in a grid -- * `XMonad.Layout.LayoutCombinators` -> Combines multiple layouts -- * `XMonad.Layout.Minimize` -> Allows to minimize a window -- * `XMonad.Layout.NoBorders` -> Detects smart borders -- * `XMonad.Layout.ResizableTile` -> Allows to change window dimensions -- * `XMonad.Layout.SimplestFloat` -> Allows window to be simplest float -- * `XMonad.Layout.Spiral` -> Puts windows in a spiral -- * `XMonad.Layout.Tabbed` -> Puts windows in several tabs -- * `XMonad.Layout.ThreeColumns` -> Puts windows in three columns -- * `XMonad` -> Main library -------------------------------------------------------------------------------- import XMonad hiding ((|||)) import XMonad.Layout.Grid import XMonad.Layout.LayoutCombinators import XMonad.Layout.Minimize import XMonad.Layout.NoBorders import XMonad.Layout.ResizableTile import XMonad.Layout.SimplestFloat import XMonad.Layout.Spiral import XMonad.Layout.Tabbed import XMonad.Layout.ThreeColumns import XMonad.Hooks.ManageDocks import Appearance -------------------------------------------------------------------------------- -- Hook Layout -------------------------------------------------------------------------------- -- * `lay_float` -> SimplestFloat -- * `lay_full` -> Full -- * `lay_grid` -> Grid -- * `lay_min` -> Minimize -- * `lay_spiral` -> Spiral -- * `lay_tabbed` -> Tabbed -- * `lay_threecol` -> Three Columns -- * `lay_tiled` -> Tiled -------------------------------------------------------------------------------- myLayoutHook = smartBorders . avoidStrutsOn [U,D] $ myLayouts where myLayouts = (lay_tiled ||| lay_grid ||| lay_tabbed ||| lay_threecol ||| lay_spiral ||| lay_full ||| lay_min ||| lay_float) -- Layouts lay_float = simplestFloat lay_full = Full lay_grid = Grid lay_min = minimize (Tall 1 (3/100) (1/2)) lay_spiral = spiral (toRational (2/(1+sqrt(5)::Double))) lay_tabbed = minimize $ tabbed shrinkText myThemeLayoutTabbed lay_threecol = ThreeColMid 1 (3/100) (1/2) lay_tiled = ResizableTall 1 (3/100) (1/2) []
sljrobin/dotfiles
xmonad/.xmonad/lib/Hook_Layout.hs
gpl-2.0
2,861
0
15
688
322
198
124
30
1
-- http://conal.net/papers/push-pull-frp/push-pull-frp.pdf import Control.Monad import Control.Applicative import Data.Monoid type Time = Double infinity = 1.0 / 0.0::Time nagInfinity = -1.0 / 0.0 :: Time type B a = Time -> a type E a = [(Time, a)] newtype Behavior a = Behavior { at :: B a } newtype Event a = Event { occs :: E a } time::Behavior Time time = Behavior id instance Functor Behavior where fmap f ba = Behavior $ fmap f (at ba) instance Applicative Behavior where pure a = Behavior (const a) (<*>) fab fa = Behavior $ (at fab) <*> (at fa) lift2 :: (a1 -> a2 -> b) -> Behavior a1 -> Behavior a2 -> Behavior b lift2 f ba1 ba2 = f <$> ba1 <*> ba2 lift3 :: (a1 -> a2 -> a3 -> b) -> Behavior a1 -> Behavior a2 -> Behavior a3 -> Behavior b lift3 f ba1 ba2 ba3 = (lift2 f ba1 ba2) <*> ba3 merge :: E a -> E a -> E a merge [] rs = rs merge ls [] = ls merge ((t0,a0):xs) ((t1,a1):ys) | t0 <= t1 = (t0,a0):(merge xs ((t1,a1):ys)) | otherwise = (t1,a1):(merge ((t0,a0):xs) ys) instance Monoid (Event a) where mempty = Event [] mappend l r = Event $ merge (occs l) (occs r) instance Functor Event where fmap f ea = Event $ map (\(t, a) -> (t, f a)) (occs ea) delayOccs :: (Time, Event a) -> E a delayOccs (t, e) = [(max t ta, a) | (ta, a) <- occs e] joinE :: Event (Event a) -> Event a joinE ee = Event $ foldr merge [] $ map delayOccs (occs ee) instance Monad Event where return a = Event [(nagInfinity, a)] (>>=) ea f = joinE $ fmap f ea instance Applicative Event where pure = return (<*>) = ap before :: E a -> Time -> [a] before os t = [a | (ta, a) <- os, ta < t] switcher :: Behavior a -> Event (Behavior a) -> Behavior a switcher b0 e = Behavior (\t -> at (last (b0 : before (occs e) t)) t) stepper :: a -> Event a -> Behavior a stepper a0 e = switcher (pure a0) (pure <$> e)
FiveEye/playground
lang/frp.hs
gpl-2.0
1,846
0
15
435
992
521
471
52
1
{- ----------------------------------------------------------------------------- ZDCPU16 is a DCPU-16 emulator. Copyright (C) 2012 Luis Cabellos This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- -} {-# LANGUAGE GeneralizedNewtypeDeriving, OverloadedStrings #-} module ZDCpu16.Render( -- * Types RenderState, Render, TextSpan(..), Rectangle(..), -- * Functions io, newRenderState, runRender, clearScreen, renderRectangle, renderText, -- * Colors black, white, red, green, blue, lightblue ) where -- ----------------------------------------------------------------------------- import Control.Monad.IO.Class( MonadIO, liftIO ) import Control.Monad.State( MonadState, StateT, runStateT, get ) import Data.Text( Text, unpack ) import Data.Word( Word8 ) import qualified Graphics.UI.SDL as SDL( Surface, Color(..), Rect(..), flip, blitSurface, mapRGB, fillRect, surfaceGetPixelFormat, getVideoSurface ) import qualified Graphics.UI.SDL.TTF as SDLTTF( Font, renderTextBlended, textSize ) -- ----------------------------------------------------------------------------- data TextSpan = TextSpan { txtX :: ! Int , txtY :: ! Int , txtColor :: !(Word8, Word8, Word8) , txtData :: ! Text } -- ----------------------------------------------------------------------------- data Rectangle = Rectangle { rectX :: ! Int , rectY :: ! Int , rectW :: ! Int , rectH :: ! Int , rectColor :: !(Word8, Word8, Word8) } -- ----------------------------------------------------------------------------- black, white, red, green, blue, lightblue :: (Word8, Word8, Word8) black = (0,0,0) white = (255,255,255) red = (255,0,0) green = (0,255,0) blue = (0,0,255) lightblue = (173,216,230) -- ----------------------------------------------------------------------------- data RenderState = RS { renderFont :: !SDLTTF.Font } -- ----------------------------------------------------------------------------- newRenderState :: SDLTTF.Font -> RenderState newRenderState = RS -- ----------------------------------------------------------------------------- newtype Render a = Render { runR :: StateT RenderState IO a } deriving( Functor, Monad, MonadIO , MonadState RenderState ) -- ----------------------------------------------------------------------------- runRender :: MonadIO m => Render a -> RenderState -> m (a, RenderState) runRender renderf rs = liftIO $ do v <- runStateT (runR renderf) rs screen <- SDL.getVideoSurface SDL.flip screen return v -- ----------------------------------------------------------------------------- io :: IO a -> Render a io = liftIO -- ----------------------------------------------------------------------------- getMainBuffer :: Render (SDL.Surface) getMainBuffer = io SDL.getVideoSurface -- ----------------------------------------------------------------------------- getMainFont :: Render (SDLTTF.Font) getMainFont = fmap renderFont get -- ----------------------------------------------------------------------------- clearScreen :: Render () clearScreen = do screen <- getMainBuffer pixel <- io $ SDL.mapRGB (SDL.surfaceGetPixelFormat screen) 0 20 0 _ <- io $ SDL.fillRect screen Nothing pixel return () -- ----------------------------------------------------------------------------- renderRectangle :: Rectangle -> Render () renderRectangle (Rectangle x y w h (r,g,b)) = do screen <- getMainBuffer pixel <- io $ SDL.mapRGB (SDL.surfaceGetPixelFormat screen) r g b _ <- io $ SDL.fillRect screen (Just $ SDL.Rect x y w h) pixel return () -- ----------------------------------------------------------------------------- renderText :: TextSpan -> Render () renderText (TextSpan x y (r,g,b) txt) = do screen <- getMainBuffer font <- getMainFont let str = unpack txt (w,h) <- io $ SDLTTF.textSize font str txtBuff <- io $ SDLTTF.renderTextBlended font str (SDL.Color r g b) _ <- io $ SDL.blitSurface txtBuff Nothing screen (Just $ SDL.Rect x y w h) return () -- -----------------------------------------------------------------------------
zhensydow/zdcpu16
src/ZDCpu16/Render.hs
gpl-3.0
4,869
14
13
829
1,033
584
449
92
1
module L.Eval.Pure where import qualified S.Type as S import System.Timeout ( timeout ) import Control.Exception ( evaluate ) import Data.Maybe ( isJust ) -- | example due to Barendregt (NF size approx 10^6) check1 = eval $ read "(ststs)" -- | huge and quick (guess the size of the NF before evaluating!) check2 = eval $ read "(t a (s (s t s t s)))" -- | size of beta-normal form -- (will not return if there is no nf) eval :: S.T -> Integer eval t = measure $ build t eval_musec :: Int -> S.T -> IO (Maybe Integer) eval_musec mu t = timeout mu $ evaluate $ eval t build t = case t of S.S {} -> s S.J {} -> j S.App {S.fun = f, S.arg = a} -> app (build f) (build a) s = Fun $ \ x -> Fun $ \ y -> Fun $ \ z -> app (app x z) (app y z) j = Fun $ \ a -> Fun $ \ b -> Fun $ \ c -> Fun $ \ d -> app (app a b) (app (app a d) c) -- | the Val type represents semantics for (head?) normal forms: data Val = Fun (Val -> Val ) -- ^ a normal form of shape (\ x -> b) | Val Integer -- ^ a normal form of shape (Var .. .. ..) app :: Val -> Val -> Val app (Fun f) a = f a -- size: ( where the application operator is not counted ) app (Val s) a = Val $ s + measure a -- depth: -- app (Val s) a = Val $ succ $ max s $ measure a -- | the size of a term. -- to evaluate the size of an abstraction, -- we apply it (its semantics) -- to (a semantics object that represents) a variable. measure :: Val -> Integer measure (Val s) = s measure (Fun f) = succ -- this counts 1 for the lambda $ measure $ f (Val 1) -- this counts one for the variable
jwaldmann/s
L/Eval/Pure.hs
gpl-3.0
1,605
0
17
438
496
267
229
28
3
module HLinear.NormalForm ( module Import ) where import HLinear.NormalForm.PLE as Import import HLinear.NormalForm.PLH as Import import HLinear.NormalForm.RREF as Import
martinra/hlinear
src/HLinear/NormalForm.hs
gpl-3.0
178
0
4
26
36
26
10
5
0
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Blogger.Users.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets one user by user_id. -- -- /See:/ <https://developers.google.com/blogger/docs/3.0/getting_started Blogger API v3 Reference> for @blogger.users.get@. module Network.Google.Resource.Blogger.Users.Get ( -- * REST Resource UsersGetResource -- * Creating a Request , usersGet , UsersGet -- * Request Lenses , ugXgafv , ugUploadProtocol , ugAccessToken , ugUploadType , ugUserId , ugCallback ) where import Network.Google.Blogger.Types import Network.Google.Prelude -- | A resource alias for @blogger.users.get@ method which the -- 'UsersGet' request conforms to. type UsersGetResource = "v3" :> "users" :> Capture "userId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] User -- | Gets one user by user_id. -- -- /See:/ 'usersGet' smart constructor. data UsersGet = UsersGet' { _ugXgafv :: !(Maybe Xgafv) , _ugUploadProtocol :: !(Maybe Text) , _ugAccessToken :: !(Maybe Text) , _ugUploadType :: !(Maybe Text) , _ugUserId :: !Text , _ugCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UsersGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ugXgafv' -- -- * 'ugUploadProtocol' -- -- * 'ugAccessToken' -- -- * 'ugUploadType' -- -- * 'ugUserId' -- -- * 'ugCallback' usersGet :: Text -- ^ 'ugUserId' -> UsersGet usersGet pUgUserId_ = UsersGet' { _ugXgafv = Nothing , _ugUploadProtocol = Nothing , _ugAccessToken = Nothing , _ugUploadType = Nothing , _ugUserId = pUgUserId_ , _ugCallback = Nothing } -- | V1 error format. ugXgafv :: Lens' UsersGet (Maybe Xgafv) ugXgafv = lens _ugXgafv (\ s a -> s{_ugXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ugUploadProtocol :: Lens' UsersGet (Maybe Text) ugUploadProtocol = lens _ugUploadProtocol (\ s a -> s{_ugUploadProtocol = a}) -- | OAuth access token. ugAccessToken :: Lens' UsersGet (Maybe Text) ugAccessToken = lens _ugAccessToken (\ s a -> s{_ugAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ugUploadType :: Lens' UsersGet (Maybe Text) ugUploadType = lens _ugUploadType (\ s a -> s{_ugUploadType = a}) ugUserId :: Lens' UsersGet Text ugUserId = lens _ugUserId (\ s a -> s{_ugUserId = a}) -- | JSONP ugCallback :: Lens' UsersGet (Maybe Text) ugCallback = lens _ugCallback (\ s a -> s{_ugCallback = a}) instance GoogleRequest UsersGet where type Rs UsersGet = User type Scopes UsersGet = '["https://www.googleapis.com/auth/blogger", "https://www.googleapis.com/auth/blogger.readonly"] requestClient UsersGet'{..} = go _ugUserId _ugXgafv _ugUploadProtocol _ugAccessToken _ugUploadType _ugCallback (Just AltJSON) bloggerService where go = buildClient (Proxy :: Proxy UsersGetResource) mempty
brendanhay/gogol
gogol-blogger/gen/Network/Google/Resource/Blogger/Users/Get.hs
mpl-2.0
4,130
0
16
1,025
700
408
292
100
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- Module : Network.AWS.DynamoDB.GetItem -- Copyright : (c) 2013-2014 Brendan Hay <[email protected]> -- License : This Source Code Form is subject to the terms of -- the Mozilla Public License, v. 2.0. -- A copy of the MPL can be found in the LICENSE file or -- you can obtain it at http://mozilla.org/MPL/2.0/. -- Maintainer : Brendan Hay <[email protected]> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | The /GetItem/ operation returns a set of attributes for the item with the given -- primary key. If there is no matching item, /GetItem/ does not return any data. -- -- /GetItem/ provides an eventually consistent read by default. If your -- application requires a strongly consistent read, set /ConsistentRead/ to 'true'. -- Although a strongly consistent read might take more time than an eventually -- consistent read, it always returns the last updated value. -- -- <http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_GetItem.html> module Network.AWS.DynamoDB.GetItem ( -- * Request GetItem -- ** Request constructor , getItem -- ** Request lenses , giAttributesToGet , giConsistentRead , giExpressionAttributeNames , giKey , giProjectionExpression , giReturnConsumedCapacity , giTableName -- * Response , GetItemResponse -- ** Response constructor , getItemResponse -- ** Response lenses , girConsumedCapacity , girItem ) where import Network.AWS.Prelude import Network.AWS.Request.JSON import Network.AWS.DynamoDB.Types import qualified GHC.Exts data GetItem = GetItem { _giAttributesToGet :: List1 "AttributesToGet" Text , _giConsistentRead :: Maybe Bool , _giExpressionAttributeNames :: Map Text Text , _giKey :: Map Text AttributeValue , _giProjectionExpression :: Maybe Text , _giReturnConsumedCapacity :: Maybe ReturnConsumedCapacity , _giTableName :: Text } deriving (Eq, Read, Show) -- | 'GetItem' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'giAttributesToGet' @::@ 'NonEmpty' 'Text' -- -- * 'giConsistentRead' @::@ 'Maybe' 'Bool' -- -- * 'giExpressionAttributeNames' @::@ 'HashMap' 'Text' 'Text' -- -- * 'giKey' @::@ 'HashMap' 'Text' 'AttributeValue' -- -- * 'giProjectionExpression' @::@ 'Maybe' 'Text' -- -- * 'giReturnConsumedCapacity' @::@ 'Maybe' 'ReturnConsumedCapacity' -- -- * 'giTableName' @::@ 'Text' -- getItem :: Text -- ^ 'giTableName' -> NonEmpty Text -- ^ 'giAttributesToGet' -> GetItem getItem p1 p2 = GetItem { _giTableName = p1 , _giAttributesToGet = withIso _List1 (const id) p2 , _giKey = mempty , _giConsistentRead = Nothing , _giReturnConsumedCapacity = Nothing , _giProjectionExpression = Nothing , _giExpressionAttributeNames = mempty } -- | There is a newer parameter available. Use /ProjectionExpression/ instead. Note -- that if you use /AttributesToGet/ and /ProjectionExpression/ at the same time, -- DynamoDB will return a /ValidationException/ exception. -- -- This parameter allows you to retrieve attributes of type List or Map; -- however, it cannot retrieve individual elements within a List or a Map. -- -- The names of one or more attributes to retrieve. If no attribute names are -- provided, then all attributes will be returned. If any of the requested -- attributes are not found, they will not appear in the result. -- -- Note that /AttributesToGet/ has no effect on provisioned throughput -- consumption. DynamoDB determines capacity units consumed based on item size, -- not on the amount of data that is returned to an application. giAttributesToGet :: Lens' GetItem (NonEmpty Text) giAttributesToGet = lens _giAttributesToGet (\s a -> s { _giAttributesToGet = a }) . _List1 -- | A value that if set to 'true', then the operation uses strongly consistent -- reads; otherwise, eventually consistent reads are used. giConsistentRead :: Lens' GetItem (Maybe Bool) giConsistentRead = lens _giConsistentRead (\s a -> s { _giConsistentRead = a }) -- | One or more substitution tokens for attribute names in an expression. The -- following are some use cases for using /ExpressionAttributeNames/: -- -- To access an attribute whose name conflicts with a DynamoDB reserved word. -- -- To create a placeholder for repeating occurrences of an attribute name in -- an expression. -- -- To prevent special characters in an attribute name from being -- misinterpreted in an expression. -- -- Use the # character in an expression to dereference an attribute name. For -- example, consider the following attribute name: -- -- 'Percentile' -- -- The name of this attribute conflicts with a reserved word, so it cannot be -- used directly in an expression. (For the complete list of reserved words, go -- to <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html Reserved Words> in the /Amazon DynamoDB Developer Guide/). To work around -- this, you could specify the following for /ExpressionAttributeNames/: -- -- '{"#P":"Percentile"}' -- -- You could then use this substitution in an expression, as in this example: -- -- '#P = :val' -- -- Tokens that begin with the : character are /expression attribute values/, -- which are placeholders for the actual value at runtime. -- -- For more information on expression attribute names, go to <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html Accessing ItemAttributes> in the /Amazon DynamoDB Developer Guide/. giExpressionAttributeNames :: Lens' GetItem (HashMap Text Text) giExpressionAttributeNames = lens _giExpressionAttributeNames (\s a -> s { _giExpressionAttributeNames = a }) . _Map -- | A map of attribute names to /AttributeValue/ objects, representing the primary -- key of the item to retrieve. -- -- For the primary key, you must provide all of the attributes. For example, -- with a hash type primary key, you only need to provide the hash attribute. -- For a hash-and-range type primary key, you must provide both the hash -- attribute and the range attribute. giKey :: Lens' GetItem (HashMap Text AttributeValue) giKey = lens _giKey (\s a -> s { _giKey = a }) . _Map -- | A string that identifies one or more attributes to retrieve from the table. -- These attributes can include scalars, sets, or elements of a JSON document. -- The attributes in the expression must be separated by commas. -- -- If no attribute names are specified, then all attributes will be returned. -- If any of the requested attributes are not found, they will not appear in the -- result. -- -- For more information, go to <http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.AccessingItemAttributes.html Accessing Item Attributes> in the /Amazon DynamoDBDeveloper Guide/. giProjectionExpression :: Lens' GetItem (Maybe Text) giProjectionExpression = lens _giProjectionExpression (\s a -> s { _giProjectionExpression = a }) giReturnConsumedCapacity :: Lens' GetItem (Maybe ReturnConsumedCapacity) giReturnConsumedCapacity = lens _giReturnConsumedCapacity (\s a -> s { _giReturnConsumedCapacity = a }) -- | The name of the table containing the requested item. giTableName :: Lens' GetItem Text giTableName = lens _giTableName (\s a -> s { _giTableName = a }) data GetItemResponse = GetItemResponse { _girConsumedCapacity :: Maybe ConsumedCapacity , _girItem :: Map Text AttributeValue } deriving (Eq, Read, Show) -- | 'GetItemResponse' constructor. -- -- The fields accessible through corresponding lenses are: -- -- * 'girConsumedCapacity' @::@ 'Maybe' 'ConsumedCapacity' -- -- * 'girItem' @::@ 'HashMap' 'Text' 'AttributeValue' -- getItemResponse :: GetItemResponse getItemResponse = GetItemResponse { _girItem = mempty , _girConsumedCapacity = Nothing } girConsumedCapacity :: Lens' GetItemResponse (Maybe ConsumedCapacity) girConsumedCapacity = lens _girConsumedCapacity (\s a -> s { _girConsumedCapacity = a }) -- | A map of attribute names to /AttributeValue/ objects, as specified by /AttributesToGet/. girItem :: Lens' GetItemResponse (HashMap Text AttributeValue) girItem = lens _girItem (\s a -> s { _girItem = a }) . _Map instance ToPath GetItem where toPath = const "/" instance ToQuery GetItem where toQuery = const mempty instance ToHeaders GetItem instance ToJSON GetItem where toJSON GetItem{..} = object [ "TableName" .= _giTableName , "Key" .= _giKey , "AttributesToGet" .= _giAttributesToGet , "ConsistentRead" .= _giConsistentRead , "ReturnConsumedCapacity" .= _giReturnConsumedCapacity , "ProjectionExpression" .= _giProjectionExpression , "ExpressionAttributeNames" .= _giExpressionAttributeNames ] instance AWSRequest GetItem where type Sv GetItem = DynamoDB type Rs GetItem = GetItemResponse request = post "GetItem" response = jsonResponse instance FromJSON GetItemResponse where parseJSON = withObject "GetItemResponse" $ \o -> GetItemResponse <$> o .:? "ConsumedCapacity" <*> o .:? "Item" .!= mempty
dysinger/amazonka
amazonka-dynamodb/gen/Network/AWS/DynamoDB/GetItem.hs
mpl-2.0
9,992
0
12
2,074
1,054
644
410
107
1
module Hastistics.Distributions where import Hastistics.Types hiding ((/), (+)) import Hastistics.Fields header :: [String] header = ["k", "p"] data BinominalTable = BinominalTable Integer Double instance HSTable BinominalTable where headersOf _ = header dataOf (BinominalTable n p) = [toHSRow k (binopdf k n p) | k <- [0..n]] lookup "k" (HSInteger k) (BinominalTable n p) = [toHSRow k (binopdf k n p)] lookup _ _ _ = [] instance Show BinominalTable where show = showTable data HypergeometricTable = HypergeometricTable Integer Integer Integer instance HSTable HypergeometricTable where headersOf _ = header dataOf (HypergeometricTable m r n) = [toHSRow k (hygepdf k m r n) | k <- [0..r]] lookup "k" (HSInteger k) (HypergeometricTable m r n) = [toHSRow k (hygepdf k m r n)] lookup _ _ _ = [] instance Show HypergeometricTable where show = showTable data PoissonTable = PoissonTable Integer Double instance HSTable PoissonTable where headersOf _ = header dataOf (PoissonTable k l) = [toHSRow x (poisspdf x l) | x <- [0..k]] lookup "k" (HSInteger x) (PoissonTable _ l) = [toHSRow x (poisspdf x l)] lookup _ _ _ = [] instance Show PoissonTable where show = showTable toHSRow :: Integer -> Double -> HSRow toHSRow n p = HSValueRow header [pack(HSStaticField(HSInteger n)), pack(HSStaticField(HSDouble p))] factorial :: Integer-> Double factorial n | n < 0 = error "negative input" | n == 0 = 1 | otherwise = fromIntegral(product[1..n]) choose :: Integer -> Integer -> Double n `choose` k | k > n = 0 | otherwise = factorial(n) / (factorial(k) Prelude.* factorial(n Prelude.- k)) {-| Returns the probability of the binominal distribution. -} binopdf :: Integer -> Integer -> Double -> Double binopdf k n p | k < 0 || k > n = 0 | n == 0 = 1 | otherwise = (n `choose` k) Prelude.* p^k Prelude.* (1 Prelude.- p)^(n Prelude.- k) {-| Returns the comulative binomial distribution. -} binocdf :: Integer -> Integer -> Double -> Double binocdf k n p | k < 0 = 0 | k >= n = 1 | otherwise = sum [binopdf x n p | x <- [0..k]] {-| Returns the probability of the hypergeometric distribution. -} hygepdf :: Integer -> Integer -> Integer -> Integer -> Double hygepdf k m r n | n == 0 = 0 | otherwise = ((r `choose` k) Prelude.* ((m Prelude.- r) `choose` (n Prelude.- k))) / (m `choose` n) {-| Returns the comulative hypergeometric distribution. -} hygecdf :: Integer -> Integer -> Integer -> Integer -> Double hygecdf k m r n = sum [hygepdf x m r n | x <- [0..k]] {-| Returns the probability of the normal distribution. -} normpdf :: Double -> Double -> Double -> Double normpdf x mu sigma = 1 / (sqrt(2 Prelude.* pi) Prelude.* sigma) Prelude.* exp(1) ** ((-((x Prelude.- mu) ** 2) / (2 Prelude.* sigma ** 2))) {-| Returns the probability of the poisson distribution. -} poisspdf :: Integer -> Double -> Double poisspdf k l = (l ^ k) / (factorial k) Prelude.* (exp(1) ** (-l)) {-| Returns the comulative poisson distribution. -} poisscdf :: Integer -> Double -> Double poisscdf k l = sum [poisspdf x l | x <- [0..k]]
fluescher/hastistics
src/Hastistics/Distributions.hs
lgpl-3.0
3,378
34
13
915
1,342
696
646
57
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module CabalNew.Cabal ( cabal_ , cabalInit , cabalSandbox_ , setMainIs , sandbox , cabalProject ) where import ClassyPrelude hiding (FilePath) import qualified Data.Char as C import qualified Data.Text as T import qualified Filesystem.Path.CurrentOS as FS import Shelly import CabalNew.Files import CabalNew.Git import CabalNew.Templates import CabalNew.Types import CabalNew.Utils cabalCmd :: CabalNew -> FilePath cabalCmd c | projectTarget c == GhcJs = "cabal-js" | otherwise = "cabal" cabal_ :: CabalNew -> T.Text -> [T.Text] -> Sh () cabal_ c = command1_ (cabalCmd c) [] cabalInit :: CabalNew -> Sh () cabalInit c@CabalNew{..} = cabal_ c "init" $ catMaybes [ Just "--non-interactive" , Just "--is-library" , Just "--main-is=Main.hs" , ifSet "license" projectLicense , ifSet "email" projectEmail , ifSet "synopsis" projectSynopsis ] cabalSandbox_ :: CabalNew -> T.Text -> [T.Text] -> Sh () cabalSandbox_ c cmdName args = command1_ (cabalCmd c) [] "sandbox" $ cmdName : args setMainIs :: FilePath -> String -> Sh () setMainIs cabalPath mainFile = sed cabalPath $ \line -> if "-- main-is:" `T.isInfixOf` line then takeWhile C.isSpace line <> "main-is: " <> T.pack mainFile else line sandbox :: CabalNew -> Sh () sandbox c = do cabalSandbox_ c "init" [] cabal_ c "install" ["-j", "--only-dependencies", "--enable-tests"] cabal_ c "configure" ["--enable-tests"] cabalProject :: CabalNew -> FilePath -> Sh (Sh ()) cabalProject config@CabalNew{..} _projectDir = do let mainFile = "Main.hs" projectExecutable = projectTarget == Executable withCommit projectGitLevel "cabal init" $ cabalInit config stubProgram projectGitLevel projectExecutable projectName mainFile when (projectTarget == GhcJs) $ copyDataFile "templates/ghcjs.cabal.config" "cabal.config" return $ do copyDataFile "templates/ghci" ".ghci" unless (projectGitLevel == Gitless) $ copyDataFile "templates/gitignore" ".gitignore" mkdir_p "specs" copyDataFile "templates/Specs.hs" "specs/Specs.hs" when (projectTarget == Executable) $ appendTemplate config "templates/executable.cabal.mustache" cabalFile appendTemplate config "templates/specs.cabal.mustache" cabalFile where cabalFile = FS.decodeString projectName FS.<.> "cabal"
erochest/cabal-new
CabalNew/Cabal.hs
apache-2.0
2,849
0
13
852
684
347
337
65
2
-- Problem 117 import Data.Ratio ((%)) import Data.List (sort) -- Assume (x,y) \in [0,1)^2. circles (x,y) = takeWhile (<= 81 % 1) $ sort [distance (x, y) (a, b) | a <- [-10..10], b <- [-10..10]] distance (x, y) (a, b) = delX + delY where delX | a == 0 = 0 | a > 0 = (a - x)^2 | a < 0 = (x - 1 - a)^2 delY | b == 0 = 0 | b > 0 = (b - y)^2 | b < 0 = (y - 1 - b)^2 histogram [] = [] histogram (a:as) = recurse 1 a as where recurse c x [] = [c] recurse c x (y:ys) | x == y = recurse (c + 1) x ys | otherwise = c : recurse 1 y ys
peterokagey/haskellOEIS
src/Sandbox/GridCircles.hs
apache-2.0
574
0
11
187
385
200
185
18
2
{-# LANGUAGE OverloadedStrings #-} module Data.Avro.Parser (AvroType(..), parse ) where import qualified Data.Attoparsec.ByteString as P import qualified Data.ByteString.Char8 as B data AvroType = ANull | AInt | ABoolean | ALong | AFloat | ADouble | ABytes | AString | ARecord { name :: String } deriving (Show,Eq) primitiveTypes :: [P.Parser AvroType] primitiveTypes = map f [ "null", "boolean", "int", "long", "float", "double", "bytes", "string"] where f :: String -> P.Parser AvroType f s = do ps <- P.string . B.pack $ s return (typeRepToType ps) typeRepToType "null" = ANull typeRepToType "boolean" = ABoolean typeRepToType "int" = AInt typeRepToType "long" = ALong typeRepToType "float" = AFloat typeRepToType "double" = ADouble typeRepToType "bytes" = ABytes typeRepToType "string" = AString avroParser = P.choice primitiveTypes parse :: B.ByteString -> P.Result AvroType parse = P.parse avroParser
tonicebrian/avro-haskell
Data/Avro/Parser.hs
apache-2.0
1,111
0
12
335
290
163
127
33
1
----------------------------------------------------------------------------- -- Copyright 2012 Microsoft Corporation. -- -- This is free software; you can redistribute it and/or modify it under the -- terms of the Apache License, Version 2.0. A copy of the License can be -- found in the file "license.txt" at the root of this distribution. ----------------------------------------------------------------------------- {- | Pretty print helpers for messages. -} module Common.Message( -- * Pretty print helpers table, tablex, ppRange -- * Source from range , docFromRange, docsFromRanges ) where import Data.Char ( isSpace ) import Lib.PPrint import Common.Failure (failure) import Common.Range import Common.ColorScheme {-------------------------------------------------------------------------- Pretty print helpers --------------------------------------------------------------------------} ppRange :: Bool -> ColorScheme -> Range -> Doc ppRange endToo colors r = color (colorRange colors) (text (showRange endToo r)) table :: [(Doc,Doc)] -> Doc table xs = tablex 1 xs tablex n xs = let (headers,docs) = unzip xs headerwidth = maximum (map (length . show) headers) in indent n $ if (headerwidth <= 0) then vcat (map snd xs) else vcat [fill headerwidth header <> colon <+> align doc | (header,doc) <- xs] {-------------------------------------------------------------------------- Source from range --------------------------------------------------------------------------} sourceFromRanges :: [Range] -> [String] sourceFromRanges ranges = [sourceFromRange range | range <- ranges] docsFromRanges :: ColorScheme -> [Range] -> [Doc] docsFromRanges colors ranges = map (docFromRange colors) ranges docFromRange :: ColorScheme -> Range -> Doc docFromRange colors range = case map (limitLineLen 55) (limitLines 3 (lines (sourceFromRange range))) of [] -> empty src -> color (colorSource colors) (align (vcat (map text src))) where limitLineLen n line = if (length line <= n) then line else let n2 = div n 2 (x,y) = splitAt n2 line pre = reverse (dropWhile (not . isSpace) (reverse x)) post = dropWhile (not . isSpace) (reverse (take (n2-5) (reverse y))) in pre ++ " ... " ++ post limitLines n ls = if (length ls <= n) then removeIndent ls else if (n <= 2) then failure "Message.docFromRange.limitLines: illegal n" else let n2 = div n 2 pre = take n2 ls post = reverse (take n2 (reverse ls)) prepost = removeIndent (pre ++ post) in take n2 prepost ++ ["..."] ++ drop n2 prepost where removeIndent ls = let i = minimum (map (length . takeWhile isSpace) ls) in map (drop i) ls
lpeterse/koka
src/Common/Message.hs
apache-2.0
3,043
0
18
837
788
412
376
53
5
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {- | Template haskell tools for reading DOT files at build time for the purposes of including the contents of those files in Eureka metadata readable by the `cartographer-server` program. -} module Network.Eureka.Cartographer.TH ( addCartographerMetadata ) where import Data.GraphViz (parseDotGraph, DotGraph) import Data.Map (insert) import Data.Text.Lazy (Text, pack) import Language.Haskell.TH (Dec(FunD), Exp(LitE, LetE, VarE, RecUpdE, AppE), Lit(StringL), Q, runIO, newName, Clause(Clause), Pat(AsP, RecP, VarP), Body(NormalB)) import Network.Eureka (InstanceConfig(InstanceConfig, instanceMetadata)) readDot :: FilePath -> Q Exp readDot filename = runIO $ do dotStr <- readFile filename let parsedGraph :: DotGraph Text parsedGraph = parseDotGraph (pack dotStr) {- verify that the dot graph parses without error -} parsedGraph `seq` (return . LitE . StringL) dotStr {- | This function takes a filename that contains a dot graph and produces a template haskell expression which defines a function of the type: @InstanceConfig -> InstanceConfig@. The purpose of the returned function is to insert the content of the dot graph into the appropriate Eureka metadata for this instance. usage: @$(addCartographerMetadata "cartography.dot") myInstanceConfig@ -} addCartographerMetadata :: FilePath -> Q Exp addCartographerMetadata filename = do dotStr <- readDot filename addMetadata <- newName "addMetadata" instanceConfig <- newName "instanceConfig" metadata <- newName "metadata" {- Build and return a let expression that looks like this: let addMetadata instanceConfig@InstanceConfig { instanceMetadata = metadata } = instanceConfig { instanceMetadata = insert "cartography" dotStr metadata } in addMetadata -} return $ LetE [ FunD addMetadata [Clause [AsP instanceConfig (RecP 'InstanceConfig [('instanceMetadata, VarP metadata)]) ] (NormalB ( RecUpdE (VarE instanceConfig) [('instanceMetadata, AppE (AppE (AppE (VarE 'insert) (LitE (StringL "cartography"))) dotStr ) (VarE metadata) )] )) [] ] ] (VarE addMetadata)
SumAll/haskell-cartographer-lib
src/Network/Eureka/Cartographer/TH.hs
apache-2.0
2,452
0
27
640
430
243
187
36
1
{-| Module : Text.ABNF Description : Top-level module Copyright : (c) Martin Zeller, 2016 License : BSD2 Maintainer : Martin Zeller <[email protected]> Stability : experimental Portability : non-portable -} module Text.ABNF ( module Text.ABNF.ABNF , module Text.ABNF.Document ) where import Text.ABNF.ABNF import Text.ABNF.Document
Xandaros/abnf
src/Text/ABNF.hs
bsd-2-clause
367
0
5
71
35
24
11
5
0
----------------------------------------------------------------------------- -- | -- Module : System.Ext2.FSChecks -- Copyright : (C) 2014 Ricky Elrod -- License : BSD2 (see LICENSE file) -- Maintainer : Ricky Elrod <[email protected]> -- Stability : experimental -- Portability : lens -- -- This module contains several checks for testing the integrity of an ext2 -- filesystem. ---------------------------------------------------------------------------- module System.Ext2.FSChecks ( sbMagicValid , sbConsistency , bgdtConsistency ) where import Control.Lens import System.Ext2.Tables import System.Ext2.Lens -- | Given a superblock, ensure that its magic number is as-expected. sbMagicValid :: Superblock -> Bool sbMagicValid sb = (sb ^. magic) == 0xEF53 -- | Given two superblocks, ensure they are consistent. We get this for free -- by deriving Eq. sbConsistency :: Superblock -> Superblock -> Bool sbConsistency = (==) -- | Given two BGDTs, ensure they are consistent. We get this for free -- by deriving Eq. bgdtConsistency :: BlockGroupDescriptorTable -> BlockGroupDescriptorTable -> Bool bgdtConsistency = (==)
relrod/ext2
src/System/Ext2/FSChecks.hs
bsd-2-clause
1,139
0
7
169
120
79
41
13
1
twice :: Integer -> (Integer -> Integer) -> Integer twice x f = f x + f x square :: Integer -> Integer square x = x * x -- main = twice 5 square
capello/Haskell_Premier
Square.hs
bsd-2-clause
146
0
8
36
63
32
31
4
1
{-# LANGUAGE OverloadedStrings #-} {-| Module : Web.Lightning.Session Description : Session management. Copyright : (c) Connor Moreside, 2016 License : BSD-3 Maintainer : [email protected] Stability : experimental Portability : POSIX Defines interactions with the session endpoint. -} module Web.Lightning.Session ( -- * Session Functions createSession , module Web.Lightning.Types.Session ) where -------------------------------------------------------------------------------- import Data.Maybe import qualified Data.Text as T import Network.API.Builder hiding (runRoute) import Web.Lightning.Types.Lightning import Web.Lightning.Types.Session -------------------------------------------------------------------------------- -- | Session endpoint. createSessionRoute :: Maybe T.Text -- ^ An optional name for the session -> Route -- ^ The lightning-viz session endpoint createSessionRoute n = Route ["sessions"] ["name" =. fromMaybe "" n] "POST" -- | Creates a new session with an optional name. createSession :: Monad m => Maybe T.Text -- ^ An optional session name -> LightningT m Session -- ^ Returns the LightningT transformer stack createSession n = receiveRoute $ createSessionRoute n
cmoresid/lightning-haskell
src/Web/Lightning/Session.hs
bsd-3-clause
1,500
0
8
451
155
93
62
18
1
----------------------------------------------------------------------------- -- | -- Module : XMonad.Layout.IndependentScreens -- Copyright : (c) 2009 Daniel Wagner -- License : BSD3 -- -- Maintainer : <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Utility functions for simulating independent sets of workspaces on -- each screen (like dwm's workspace model), using internal tags to -- distinguish workspaces associated with each screen. ----------------------------------------------------------------------------- module XMonad.Layout.IndependentScreens ( -- * Usage -- $usage VirtualWorkspace, PhysicalWorkspace, workspaces', withScreens, onCurrentScreen, marshallPP, whenCurrentOn, countScreens, -- * Converting between virtual and physical workspaces -- $converting marshall, unmarshall, unmarshallS, unmarshallW, marshallWindowSpace, unmarshallWindowSpace ) where -- for the screen stuff import Control.Applicative((<*), liftA2) import Control.Arrow hiding ((|||)) import Control.Monad import Data.List (nub, genericLength) import Graphics.X11.Xinerama import XMonad import XMonad.StackSet hiding (filter, workspaces) import XMonad.Hooks.DynamicLog -- $usage -- You can use this module with the following in your @~\/.xmonad\/xmonad.hs@: -- -- > import XMonad.Layout.IndependentScreens -- -- You can define your workspaces by calling @withScreens@: -- -- > myConfig = def { workspaces = withScreens 2 ["web", "email", "irc"] } -- -- This will create \"physical\" workspaces with distinct internal names for -- each (screen, virtual workspace) pair. -- -- Then edit any keybindings that use the list of workspaces or refer -- to specific workspace names. In the default configuration, only -- the keybindings for changing workspace do this: -- -- > keyBindings conf = let m = modMask conf in fromList $ -- > {- lots of other keybindings -} -- > [((m .|. modm, k), windows $ f i) -- > | (i, k) <- zip (XMonad.workspaces conf) [xK_1 .. xK_9] -- > , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] -- -- This should change to -- -- > keyBindings conf = let m = modMask conf in fromList $ -- > {- lots of other keybindings -} -- > [((m .|. modm, k), windows $ onCurrentScreen f i) -- > | (i, k) <- zip (workspaces' conf) [xK_1 .. xK_9] -- > , (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]] -- -- In particular, the analogue of @XMonad.workspaces@ is -- @workspaces'@, and you can use @onCurrentScreen@ to convert functions -- of virtual workspaces to functions of physical workspaces, which work -- by marshalling the virtual workspace name and the currently focused -- screen into a physical workspace name. -- -- A complete example abusing many of the functions below is available in the -- "XMonad.Config.Dmwit" module. type VirtualWorkspace = WorkspaceId type PhysicalWorkspace = WorkspaceId -- $converting -- You shouldn't need to use the functions below very much. They are used -- internally. However, in some cases, they may be useful, and so are exported -- just in case. In general, the \"marshall\" functions convert the convenient -- form (like \"web\") you would like to use in your configuration file to the -- inconvenient form (like \"2_web\") that xmonad uses internally. Similarly, -- the \"unmarshall\" functions convert in the other direction. marshall :: ScreenId -> VirtualWorkspace -> PhysicalWorkspace marshall (S sc) vws = show sc ++ '_':vws unmarshall :: PhysicalWorkspace -> (ScreenId, VirtualWorkspace) unmarshallS :: PhysicalWorkspace -> ScreenId unmarshallW :: PhysicalWorkspace -> VirtualWorkspace unmarshall = ((S . read) *** drop 1) . break (=='_') unmarshallS = fst . unmarshall unmarshallW = snd . unmarshall workspaces' :: XConfig l -> [VirtualWorkspace] workspaces' = nub . map (snd . unmarshall) . workspaces withScreens :: ScreenId -- ^ The number of screens to make workspaces for -> [VirtualWorkspace] -- ^ The desired virtual workspace names -> [PhysicalWorkspace] -- ^ A list of all internal physical workspace names withScreens n vws = [marshall sc pws | pws <- vws, sc <- [0..n-1]] onCurrentScreen :: (VirtualWorkspace -> WindowSet -> a) -> (PhysicalWorkspace -> WindowSet -> a) onCurrentScreen f vws = screen . current >>= f . flip marshall vws -- | In case you don't know statically how many screens there will be, you can call this in main before starting xmonad. For example, part of my config reads -- -- > main = do -- > nScreens <- countScreens -- > xmonad $ def { -- > ... -- > workspaces = withScreens nScreens (workspaces def), -- > ... -- > } -- countScreens :: (MonadIO m, Integral i) => m i countScreens = liftM genericLength . liftIO $ openDisplay "" >>= liftA2 (<*) getScreenInfo closeDisplay -- | This turns a naive pretty-printer into one that is aware of the -- independent screens. That is, you can write your pretty printer to behave -- the way you want on virtual workspaces; this function will convert that -- pretty-printer into one that first filters out physical workspaces on other -- screens, then converts all the physical workspaces on this screen to their -- virtual names. -- -- For example, if you have handles @hLeft@ and @hRight@ for bars on the left and right screens, respectively, and @pp@ is a pretty-printer function that takes a handle, you could write -- -- > logHook = let log screen handle = dynamicLogWithPP . marshallPP screen . pp $ handle -- > in log 0 hLeft >> log 1 hRight marshallPP :: ScreenId -> PP -> PP marshallPP s pp = pp { ppCurrent = ppCurrent pp . snd . unmarshall, ppVisible = ppVisible pp . snd . unmarshall, ppHidden = ppHidden pp . snd . unmarshall, ppHiddenNoWindows = ppHiddenNoWindows pp . snd . unmarshall, ppUrgent = ppUrgent pp . snd . unmarshall, ppSort = fmap (marshallSort s) (ppSort pp) } -- | Take a pretty-printer and turn it into one that only runs when the current -- workspace is one associated with the given screen. The way this works is a -- bit hacky, so beware: the 'ppOutput' field of the input will not be invoked -- if either of the following conditions is met: -- -- 1. The 'ppSort' of the input returns an empty list (when not given one). -- -- 2. The 'ppOrder' of the input returns the exact string @\"\\0\"@. -- -- For example, you can use this to create a pipe which tracks the title of the -- window currently focused on a given screen (even if the screen is not -- current) by doing something like this: -- -- > ppFocus s = whenCurrentOn s def -- > { ppOrder = \(_:_:title:_) -> [title] -- > , ppOutput = appendFile ("focus" ++ show s) . (++ "\n") -- > } -- -- Sequence a few of these pretty-printers to get a log hook that keeps each -- screen's title up-to-date. whenCurrentOn :: ScreenId -> PP -> PP whenCurrentOn s pp = pp { ppSort = do sort <- ppSort pp return $ \xs -> case xs of x:_ | unmarshallS (tag x) == s -> sort xs _ -> [] , ppOrder = \i@(wss:_) -> case wss of "" -> ["\0"] -- we got passed no workspaces; this is the signal from ppSort that this is a boring case _ -> ppOrder pp i , ppOutput = \out -> case out of "\0" -> return () -- we got passed the signal from ppOrder that this is a boring case _ -> ppOutput pp out } marshallSort :: ScreenId -> ([WindowSpace] -> [WindowSpace]) -> ([WindowSpace] -> [WindowSpace]) marshallSort s vSort = pScreens . vSort . vScreens where onScreen ws = unmarshallS (tag ws) == s vScreens = map unmarshallWindowSpace . filter onScreen pScreens = map (marshallWindowSpace s) -- | Convert the tag of the 'WindowSpace' from a 'VirtualWorkspace' to a 'PhysicalWorkspace'. marshallWindowSpace :: ScreenId -> WindowSpace -> WindowSpace -- | Convert the tag of the 'WindowSpace' from a 'PhysicalWorkspace' to a 'VirtualWorkspace'. unmarshallWindowSpace :: WindowSpace -> WindowSpace marshallWindowSpace s ws = ws { tag = marshall s (tag ws) } unmarshallWindowSpace ws = ws { tag = unmarshallW (tag ws) }
eb-gh-cr/XMonadContrib1
XMonad/Layout/IndependentScreens.hs
bsd-3-clause
8,282
0
20
1,737
1,084
639
445
67
4
{-# LANGUAGE GADTs, TypeSynonymInstances #-} import Control.Applicative import Control.Monad import Data.Traversable import Debug.Trace class Monad m => MonadSuspend m where suspend :: String -> m Int data Program instr a where Return :: a -> Program instr a Ap :: Program instr (a -> b) -> Program instr a -> Program instr b Bind :: Program instr b -> (b -> Program instr a) -> Program instr a Instr :: instr a -> Program instr a instance Applicative (Program instr) where pure = return (<*>) = Ap instance Functor (Program instr) where fmap = liftM instance Monad (Program instr) where return = Return (>>=) = Bind data ProgramView instr a where ReturnView :: a -> ProgramView instr a BindView :: instr b -> (b -> Program instr a ) -> ProgramView instr a view :: Program instr a -> ProgramView instr a view (Return x) = ReturnView x view ((Return f) `Ap` g) = view (g x) view (()) view ((Return x) `Bind` g) = view (g x) view ((m `Bind` g) `Bind` h) = view (m `Bind` (\x -> g x `Bind` h)) view ((Instr i) `Bind` g) = i `BindView` g view (Instr i) = i `BindView` Return -- newtype JumpM a = -- -- instance Functor JumpM where -- fmap = liftM -- -- instance Applicative JumpM where -- pure = return -- mf <*> mx = ... -- -- instance Monad JumpM where -- return = ... -- mx >>= fxmy = ... data JumpI a where Suspend :: String -> JumpI Int type JumpM = Program JumpI instance MonadSuspend JumpM where suspend = Instr . Suspend runJumpM :: JumpM a -> a runJumpM = go id where go = undefined -- go :: [(Int -> )] -> (a -> b) -> JumpM a -> b -- go others k (Return x) = k x -- go others k (mf `Ap` mx) = go (\f -> go (\x -> k (f x)) mx) mf -- go others k (mx `Bind` fxmy) = go (go k . fxmy) mx -- go others k (Instr (Suspend s)) = trace s $ k 1 bitsToNumber :: [Bool] -> Int bitsToNumber = foldr (\b acc -> acc * 2 + if b then 1 else 0) 0 tHRESHOLD :: Int tHRESHOLD = 4 tree :: (Applicative m, MonadSuspend m) => [Bool] -> m Int tree n | length n > tHRESHOLD = return 1 | otherwise = suspend ("Suspension point: " ++ show (bitsToNumber n)) >>= \_ -> traverse tree [False : n, True : n] >>= \[n1, n2] -> return (n1 + n2) main :: IO () main = print $ runJumpM $ tree [True]
batterseapower/haskell-kata
OperationalSearchApplicative.hs
bsd-3-clause
2,391
0
12
670
805
436
369
-1
-1
{-# LANGUAGE MultiParamTypeClasses #-} module TermTest where import Control.Exception (ErrorCall(ErrorCall), evaluate) import Test.HUnit import Test.HUnit.Tools (assertRaises) import Term data Sort = D | F | G deriving (Show, Eq) data Fun = M | P | One | Zero | INV deriving (Show, Eq) instance Signature Sort Fun where dom M = [D, D] dom P = [D, D] dom One = [] dom Zero = [] dom INV = [D] cod _ = D x *. y = FunApp M [x,y] x +. y = FunApp P [x,y] msg = "Discrepancy \"x\":=\"D and F\"\n" erroneous = (Var "x" D) *. (Var "x" F) *. (Var "x" G) tTest :: Test tTest = TestCase $ assertEqual "Wrong sorts" (Left msg) (varsCheckT erroneous)
esengie/algebraic-checker
test/TermTest.hs
bsd-3-clause
685
0
8
170
291
161
130
23
1
{-# LANGUAGE OverloadedStrings #-} module Evalso.Cruncher.Base64Spec where import qualified Evalso.Cruncher.FinalResult as FR import Evalso.Cruncher.Request import qualified Evalso.Cruncher.SandboxResult as SR import Evalso.Cruncher.SELinux import qualified Data.Map as Map import Test.Hspec spec :: Spec spec = parallel $ do describe "An output file produced by an evaluation" $ do it "is decodable from valid base64" $ do finalResult <- runRequest $ Request "ruby" "File.open('output/run/foobar', 'w').tap{|x|x.write('I am decoded!')}.flush" Nothing False Nothing let (Just x) = FR.run finalResult Map.member "foobar" (SR.outputFiles x) `shouldBe` True let (Just y) = Map.lookup "foobar" (SR.outputFiles x) y `shouldBe` "SSBhbSBkZWNvZGVkIQ=="
eval-so/cruncher
tests/Evalso/Cruncher/Base64Spec.hs
bsd-3-clause
784
0
20
129
192
103
89
17
1
module Protocol_test where import Test.HUnit import Protocol import qualified Data.ByteString.Lazy.Char8 as BL tests = TestList [TestLabel "Parsing input" parse_input_test, TestLabel "All input label" label_all_test] t_input1 = "[\"done\",[[0,\"ok\",0,[[0,\"disco://localhost/ddfs/vol0/blob/b\"]]]]]" all_input = "[\"done\",[[0,\"ok\",\"all\",[[0,\"disco://localhost/ddfs/vol0/blob/b\"]]]]]" bad_input = "[\"done\",[[0,\"ok\",\"bad\",[[0,\"disco://localhost/ddfs/vol0/blob/b\"]]]]]" t_input5 = "[\"done\",[[0,\"ok\",0,[[0,\"disco://0\"]]],[1,\"ok\",0,[[0,\"disco://1\"]]],[2,\"ok\",0,[[0,\"disco://2\"]]],[3,\"ok\",0,[[0,\"disco://3\"]]],[4,\"ok\",0,[[0,\"disco://4\"]]]]]" inpt_msg ="[\"done\",[[0,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3107\"]]],[1,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3152\"]]],[2,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3147\"]]],[3,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3142\"]]],[4,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3137\"]]],[5,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3132\"]]],[6,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3127\"]]],[7,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3122\"]]],[8,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3117\"]]],[9,\"ok\",0,[[0,\"disco://localhost/disco/localhost/47/gojob@57d:39dd6:926/map_out_3112\"]]]]]" parse_input_test = TestCase (do p1 <- process_master_msg "INPUT" t_input1 p5 <- process_master_msg "INPUT" t_input5 assertEqual "1 input parsing type" (M_task_input (Task_input {input_flag = Done, inputs = [Input {input_id = 0, status = Ok, input_label = Protocol.Label 0, replicas = [Replica {replica_id = 0, replica_location = "disco://localhost/ddfs/vol0/blob/b"}]}]})) p1 let M_task_input t1 = p1 let [rep1] = (replicas . head . inputs) t1 let rep_loc1 = replica_location rep1 assertEqual "1 input parsing replica location" "disco://localhost/ddfs/vol0/blob/b" rep_loc1 let M_task_input t5 = p5 let len5 = length $ inputs t5 assertEqual "5 input parsing" 5 len5 M_task_input t_mult <- process_master_msg "INPUT" inpt_msg let len_mult = length $ inputs t_mult assertEqual "Multiple input parsing" 10 len_mult) label_all_test = TestCase (do M_task_input all <- process_master_msg "INPUT" all_input let inpt = (head . inputs) all let bad = process_master_msg "INPUT" bad_input :: Maybe Master_msg assertEqual "All input label" All (input_label inpt) assertEqual "Bad input label" Nothing bad) main = runTestTT tests
zuzia/haskell_worker
tests/Protocol_test.hs
bsd-3-clause
2,852
0
20
298
431
214
217
32
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} module Agon.APIConstructors where import Agon.Types import Agon.Agon import Control.Monad.Trans.Either import Servant type ServantM = EitherT ServantErr IO type AppM = AgonM ServantM type AuthToken = Maybe String type AAuth = Header "A-Auth" String type ReadAPI e = ListAPI e :<|> GetAPI e type ReadDependentAPI e = ListDependentAPI e :<|> GetAPI e type CreateUpdateAPI e = CreateAPI e :<|> UpdateAPI e type ListAPI e = AAuth :> Get '[JSON] [e] type ListDependentAPI e = AAuth :> "childrenof" :> Capture "id" ID :> Get '[JSON] [e] type GetAPI e = AAuth :> Capture "id" String :> Get '[JSON] e type CreateAPI e = AAuth :> ReqBody '[JSON] e :> Put '[JSON] e type UpdateAPI e = AAuth :> ReqBody '[JSON] e :> Post '[JSON] e type DeleteAPI = AAuth :> Capture "id" ID :> Capture "rev" ID :> Delete '[JSON] ()
Feeniks/Agon
app/Agon/APIConstructors.hs
bsd-3-clause
940
0
10
169
322
178
144
22
0
----------------------------------------------------------------------------- -- | -- Module : Geometry -- Copyright : (c) 2011-2017 diagrams team (see LICENSE) -- License : BSD-style (see LICENSE) -- Maintainer : [email protected] -- -- This module reexports the geometry library. Constructors that are -- not safe to use directly are not reexported from here but the -- constructors are available by importing the module they are defined -- in. -- ----------------------------------------------------------------------------- module Geometry ( module Geometry.Angle , module Geometry.BoundingBox , module Geometry.Combinators , module Geometry.CubicSpline , module Geometry.Direction , module Geometry.Envelope , module Geometry.HasOrigin , module Geometry.Juxtapose , module Geometry.Located , module Geometry.Parametric , module Geometry.Path , module Geometry.Points , module Geometry.Query , module Geometry.Segment , module Geometry.Size , module Geometry.Space , module Geometry.Trace , module Geometry.Trail , module Geometry.Transform -- * TwoD , module Geometry.TwoD.Arc , module Geometry.TwoD.Combinators , module Geometry.TwoD.Curvature , module Geometry.TwoD.Ellipse , module Geometry.TwoD.Path , module Geometry.TwoD.Points , module Geometry.TwoD.Polygons , module Geometry.TwoD.Segment , module Geometry.TwoD.Size , module Geometry.TwoD.Shapes , module Geometry.TwoD.Transform , module Geometry.TwoD.Types , module Geometry.TwoD.Vector -- * ThreeD , module Geometry.ThreeD.Camera , module Geometry.ThreeD.Combinators , module Geometry.ThreeD.Size , module Geometry.ThreeD.Shapes , module Geometry.ThreeD.Transform , module Geometry.ThreeD.Vector , module Geometry.ThreeD.Types ) where import Geometry.Angle import Geometry.BoundingBox hiding (BoundingBox (..)) import Geometry.BoundingBox (BoundingBox) import Geometry.Combinators import Geometry.CubicSpline import Geometry.Direction hiding (Direction (..)) import Geometry.Direction (Direction) import Geometry.Envelope hiding (Envelope (..)) import Geometry.Envelope (Envelope) import Geometry.HasOrigin import Geometry.Juxtapose import Geometry.Located import Geometry.Parametric import Geometry.Path hiding (pathPoints) import Geometry.Points import Geometry.Query import Geometry.Segment import Geometry.Size hiding (SizeSpec (..)) import Geometry.Size (SizeSpec) import Geometry.Space import Geometry.ThreeD.Camera import Geometry.ThreeD.Combinators import Geometry.ThreeD.Shapes import Geometry.ThreeD.Size import Geometry.ThreeD.Transform import Geometry.ThreeD.Types import Geometry.ThreeD.Vector import Geometry.Trace hiding (Trace (..)) import Geometry.Trace (Trace) import Geometry.Trail hiding (linePoints, loopPoints, trailPoints) import Geometry.Transform hiding (Transformation (..)) import Geometry.Transform (Transformation) import Geometry.TwoD.Arc import Geometry.TwoD.Combinators import Geometry.TwoD.Curvature import Geometry.TwoD.Ellipse import Geometry.TwoD.Path import Geometry.TwoD.Points import Geometry.TwoD.Polygons import Geometry.TwoD.Segment import Geometry.TwoD.Shapes import Geometry.TwoD.Size import Geometry.TwoD.Transform import Geometry.TwoD.Types import Geometry.TwoD.Vector hiding (e)
cchalmers/geometry
src/Geometry.hs
bsd-3-clause
3,971
0
6
1,077
634
426
208
86
0
{-# LANGUAGE FlexibleContexts, TypeFamilies #-} module Facebook.Gen.Environment where import Control.Monad import Control.Lens hiding (coerce) import qualified Data.Map.Strict as Map import Data.Vector hiding (map, length, head, tail, (++), concat) import qualified Data.Vector as V import Data.Text hiding (map, length, head, tail, concat) import qualified Data.Text as T import Data.Coerce import Data.Maybe import qualified Prelude as P import Prelude import Facebook.Gen.Csv import Facebook.Gen.Types import Debug.Trace -- mapping from FB types to Haskell types typesMap :: Map.Map Text Text typesMap = Map.fromList [("string", "Text") , ("unsigned int32", "Int") , ("int32", "Int") , ("int", "Integer") , ("float", "Float") , ("boolean", "Bool") , ("bool", "Bool") , ("datetime", "UTCTime") -- ??? , ("numeric string", "Text") , ("UTF-8 encoded string", "BS.ByteString") , ("numeric string or integer", "Text") -- ??? , ("integer", "Integer") , ("list<unsigned int32>", "Vector Int") , ("list<string>", "Vector Text") , ("list<numeric string>", "Vector Text") , ("list<numeric string or integer>", "Vector Text") , ("list<ExecOption>", "Vector ExecOption") , ("ISO 4217 Currency Code", "Text") , ("map<string, int32>", "Map.Map Text Int") , ("ConfigureStatus", "ConfigureStatusADT") , ("CustomAudienceDataSource", "CustomAudienceDataSource") , ("CustomAudienceStatus", "CustomAudienceStatus") , ("CustomAudienceSubtypeADT", "CustomAudienceSubtypeADT") , ("LookalikeSpecADT", "LookalikeSpecADT") , ("EffectiveStatus", "EffectiveStatusADT") , ("ConfiguredAdStatus", "ConfiguredAdStatus") , ("EffectiveAdStatus", "EffectiveAdStatus") , ("OptGoal", "OptGoal") , ("Targeting object", "TargetingSpecs") , ("Targeting", "TargetingSpecs") , ("BidType", "BidTypeADT") , ("ObjectType", "ObjectTypeADT") , ("DeleteStrategy", "DeleteStrategyADT") , ("Objective", "ObjectiveADT") , ("BuyingType", "BuyingTypeADT") , ("BillingEvent", "BillingEventADT") , ("AdCreativeObjectStorySpec", "ObjectStorySpecADT") , ("CallActionType", "CallToActionTypeADT") , ("URL", "Text") , ("post id", "Text") , ("Post ID", "Text") , ("post_id", "Text") , ("id", "Text") , ("AdAccount", "AdAccount") -- FIXME , ("AdCreativeId", "AdCreativeADT") , ("RunStatus", "RunStatusADT") , ("map<string, int32>", "Map.Map Text Int") , ("map<string, unsigned int32>", "Map.Map Text Int") , ("dictionary", "A.Value") -- ??? , ("Object", "A.Value") -- ??? , ("videoId", "VideoId") ] type ModeFieldInfoMap = Map.Map InteractionMode (Vector FieldInfo) type EntityModeMap = Map.Map Entity ModeFieldInfoMap newtype Env = Env EntityModeMap deriving Show envsToMaps :: Vector Env -> Vector EntityModeMap envsToMaps = coerce buildEnv :: Vector (Vector CsvLine) -> Env buildEnv csvs = do --let csvs' = join csvs :: Vector CsvLine let ignore = V.fromList $ ["rf_spec", "account_groups", "agency_client_declaration", "funding_source_details", "owner_business", "business", "failed_delivery_checks", "permitted_roles", "access_type", "end_advertiser", "currency"] -- Ad AccountA ++ ["adlabels"] -- Campaign ++ ["adset_schedule", "object_type", "promoted_object", "campaign", "product_ad_behavior", "rf_prediction_id", "pacing_type"] ++ ["copy_from", "bytes", "zipbytes"] -- AdImage Create ++ ["capabilities", "tos_accepted", "line_numbers", "bid_info"] ++ ["image_crops", "applink_treatment", "tracking_specs", "adset", "conversion_specs", "ad_review_feedback"] ++ ["custom_event_type"] ++ ["type", "dynamic_ad_voice", "annotations", "info_fields"] ++ ["account"] let csvs'' = V.filter (\(CsvLine _ _ (FieldInfo name _ _ _ _)) -> not $ V.elem name ignore) (join csvs :: Vector CsvLine) let envs = V.map buildEnvCsv csvs'' let merged = merge envs unify merged merge :: V.Vector Env -> Env -- Types Env and unified env -- this should be easier... merge envs = go Map.empty $ envsToMaps envs where -- only Left if there is a name/type-clash... TODO go acc maps | V.null maps = Env acc | otherwise = let map = V.head maps in go (merge2 acc map) $ V.tail maps merge2 acc entToModeMap | length (Map.keys entToModeMap) == 1 -- since every line in the CSV file is turned into an Env = let key = head $ Map.keys entToModeMap in case acc ^.at key of -- is current entity elem of final env? Nothing -> acc & at key ?~ (fromJust $ entToModeMap ^.at key) Just acc' -> let modeMap = updateModeMap acc' $ fromJust $ entToModeMap ^.at key in acc & at key ?~ modeMap | otherwise = error "merge2" updateModeMap :: ModeFieldInfoMap -> ModeFieldInfoMap -> ModeFieldInfoMap updateModeMap acc modeMap | length (Map.keys modeMap) == 1 = let key = head $ Map.keys modeMap val = case acc ^.at key of Nothing -> fromJust $ modeMap ^.at key -- mode is not in map Just fis -> mergeFieldInfo fis $ fromJust $ modeMap ^.at key in acc & at key ?~ val | otherwise = error "updateModeMap" -- mergeFieldInfo :: V n Fi -> V 1 Fi -> V (n+1) Fi mergeFieldInfo :: Vector FieldInfo -> Vector FieldInfo -> Vector FieldInfo mergeFieldInfo fis fiV = fiV V.++ fis delFromEnv :: Env -> V.Vector FieldInfo -> Env delFromEnv (Env env) del = Env $ Map.map (\mode -> Map.map (\fis -> V.filter (\fi -> not $ V.elem fi del) fis) mode) env unify :: Env -> Env unify env = let fis = collectFieldInfos env dups = findDups fis unified = uni dups in if V.null unified then env else addTypesEnv env unified collectFieldInfos :: Env -> V.Vector FieldInfo collectFieldInfos (Env env) = P.foldl mergeFieldInfo V.empty $ concat $ Map.elems $ Map.map (\ent -> Map.elems ent) env collectFieldInfosMode :: ModeFieldInfoMap -> V.Vector FieldInfo collectFieldInfosMode mode = P.foldl mergeFieldInfo V.empty $ Map.elems mode addTypesEnv :: Env -> Vector FieldInfo -> Env addTypesEnv (Env env) types = Env $ Map.insert (Entity "Types") (Map.insert Types types Map.empty) env -- returns the FieldInfos to be updated to use the fully-qualified, globally defined types -- instead of defining the same types all over locally. uni :: [V.Vector FieldInfo] -> V.Vector FieldInfo uni dups = V.fromList $ go dups [] where go [] acc = acc go (ds:dss) acc = let cur = V.head ds in if V.all (\fi -> type_ fi == type_ cur) ds then go dss $ cur:acc else go dss acc -- returns all duplicate FieldInfos findDups :: V.Vector FieldInfo -> [V.Vector FieldInfo] findDups fis = go fis [] where go fis acc | V.null fis = acc | otherwise = let fi = V.head fis tail = V.tail fis dupInds = V.findIndices (==fi) tail in if V.null dupInds then go tail acc else let dups = V.cons fi $ V.map (\idx -> unsafeIndex tail idx) dupInds tail' = V.ifilter (\idx _ -> not $ V.elem idx dupInds) tail in go tail' $ dups:acc removeNameTypeDups :: V.Vector FieldInfo -> V.Vector FieldInfo removeNameTypeDups fi = removeDups fi (\cur e -> e == cur && type_ e == type_ cur) removeNameDups :: V.Vector FieldInfo -> V.Vector FieldInfo removeNameDups fi = removeDups fi (\cur e -> e == cur) removeDups :: V.Vector FieldInfo -> (FieldInfo -> FieldInfo -> Bool) -> V.Vector FieldInfo removeDups fis pred = V.reverse $ V.fromList $ go fis [] where go fis acc | V.null fis = acc | otherwise = let fi = V.head fis tail = V.tail fis dupInds = V.findIndices (pred fi) tail in if V.null dupInds then go tail $ fi:acc else let dups = V.cons fi $ V.map (\idx -> unsafeIndex tail idx) dupInds tail' = V.ifilter (\idx _ -> not $ V.elem idx dupInds) tail in go tail' $ fi:acc buildEnvCsv :: CsvLine -> Env buildEnvCsv (CsvLine (Entity ent) mode info) = let ent' = (Entity $ T.concat $ splitOn " " ent) info' = insertHsType info (Entity ent) mode in Env $ Map.insert ent' (Map.insert mode (V.singleton info') Map.empty) Map.empty insertHsType :: FieldInfo -> Entity -> InteractionMode -> FieldInfo insertHsType fi ent mode = let fiType = type_ fi err = error $ "Could not find Haskell type for " ++ unpack fiType ++ " for field " ++ unpack (name fi) ++ " in " ++ show ent ++ ", mode " ++ show mode in fi {type_ = Map.findWithDefault err fiType typesMap}
BeautifulDestinations/fb
gen/src/Facebook/Gen/Environment.hs
bsd-3-clause
10,099
0
20
3,405
2,708
1,450
1,258
192
3
{-# LANGUAGE CPP #-} module Main where import Control.Monad.State (evalState, put, get) import Data.Chimera import Gauge.Main import System.Random #ifdef MIN_VERSION_ral import qualified Data.RAList as RAL #endif sizes :: Num a => [a] sizes = [100, 200, 500, 1000] main :: IO () main = defaultMain [ bgroup "read/Chimera" (map benchReadChimera sizes) , bgroup "read/List" (map benchReadList sizes) #ifdef MIN_VERSION_ral , bgroup "read/RAL" (map benchReadRAL sizes) #endif ] randomChimera :: UChimera Int randomChimera = flip evalState (mkStdGen 42) $ tabulateM $ const $ do g <- get let (x, g') = random g put g' pure x randomList :: [Int] randomList = randoms (mkStdGen 42) #ifdef MIN_VERSION_ral randomRAL :: RAL.RAList Int randomRAL = RAL.fromList $ take (maximum sizes) $ randoms (mkStdGen 42) #endif randomIndicesWord :: [Word] randomIndicesWord = randoms (mkStdGen 42) randomIndicesInt :: [Int] randomIndicesInt = randoms (mkStdGen 42) benchReadChimera :: Word -> Benchmark benchReadChimera n = bench (show n) $ nf (sum . map (index randomChimera)) $ map (`rem` n) $ take (fromIntegral n) randomIndicesWord benchReadList :: Int -> Benchmark benchReadList n = bench (show n) $ nf (sum . map (randomList !!)) $ map (`mod` n) $ take n randomIndicesInt #ifdef MIN_VERSION_ral benchReadRAL :: Int -> Benchmark benchReadRAL n = bench (show n) $ nf (sum . map (randomRAL RAL.!)) $ map (`mod` n) $ take n randomIndicesInt #endif
Bodigrim/bit-stream
bench/Bench.hs
bsd-3-clause
1,495
0
13
287
551
293
258
36
1
----------------------------------------------------------------------------- -- | Command Line Config Options -------------------------------------------- ----------------------------------------------------------------------------- {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module Language.Haskell.Liquid.UX.Config ( -- * Configuration Options Config (..) ) where import Data.Serialize ( Serialize ) import Language.Fixpoint.Types.Config hiding (Config) import Data.Typeable (Typeable) import Data.Generics (Data) import GHC.Generics -- NOTE: adding strictness annotations breaks the help message data Config = Config { files :: [FilePath] -- ^ source files to check , idirs :: [FilePath] -- ^ path to directory for including specs , newcheck :: Bool -- ^ new liquid-fixpoint sort check , diffcheck :: Bool -- ^ check subset of binders modified (+ dependencies) since last check , real :: Bool -- ^ supports real number arithmetic , fullcheck :: Bool -- ^ check all binders (overrides diffcheck) , extSolver :: Bool -- ^ use external (OCaml) fixpoint constraint solver , binders :: [String] -- ^ set of binders to check , noCheckUnknown :: Bool -- ^ whether to complain about specifications for unexported and unused values , notermination :: Bool -- ^ disable termination check , autoproofs :: Bool -- ^ automatically construct proofs from axioms , nowarnings :: Bool -- ^ disable warnings output (only show errors) , trustinternals :: Bool -- ^ type all internal variables with true , nocaseexpand :: Bool -- ^ disable case expand , strata :: Bool -- ^ enable strata analysis , notruetypes :: Bool -- ^ disable truing top level types , totality :: Bool -- ^ check totality in definitions , noPrune :: Bool -- ^ disable prunning unsorted Refinements , cores :: Maybe Int -- ^ number of cores used to solve constraints , minPartSize :: Int -- ^ Minimum size of a partition , maxPartSize :: Int -- ^ Maximum size of a partition. Overrides minPartSize , maxParams :: Int -- ^ the maximum number of parameters to accept when mining qualifiers , smtsolver :: Maybe SMTSolver -- ^ name of smtsolver to use [default: try z3, cvc4, mathsat in order] , shortNames :: Bool -- ^ drop module qualifers from pretty-printed names. , shortErrors :: Bool -- ^ don't show subtyping errors and contexts. , cabalDir :: Bool -- ^ find and use .cabal file to include paths to sources for imported modules , ghcOptions :: [String] -- ^ command-line options to pass to GHC , cFiles :: [String] -- ^ .c files to compile and link against (for GHC) , eliminate :: Bool , port :: Int -- ^ port at which lhi should listen , exactDC :: Bool -- ^ Automatically generate singleton types for data constructors } deriving (Generic, Data, Typeable, Show, Eq) instance Serialize SMTSolver instance Serialize Config
abakst/liquidhaskell
src/Language/Haskell/Liquid/UX/Config.hs
bsd-3-clause
3,216
0
9
852
356
239
117
44
0
{- | Left-biased finite automata -} module FST.LBFA ( module FST.Automaton, -- * Types LBFA, -- * Functions on LBFA initial, compileToLBFA, compileToAutomaton ) where import Control.Monad.State import FST.RegTypes import FST.Automaton import FST.Deterministic import FST.Complete import FST.Utils (remove,merge) import Data.List (delete,nub,(\\)) -- | Data type for LBFA (left-biased finite automata) data LBFA a = LBFA { trans :: [(StateTy, Transitions a)], initS :: StateTy, finalS :: [StateTy], alpha :: Sigma a, lastS :: StateTy } instance AutomatonFunctions LBFA where -- | Get the states of a LBFA states lbfa = map fst (trans lbfa) -- | Check if a state is a final state. isFinal lbfa s = elem s (finals lbfa) -- | Get the initial states of a LBFA initials lbfa = [(initS lbfa)] -- | Get the final states of a LBFA finals = finalS -- | Get the transition table transitionTable = trans -- | Get the transitions of a state transitionList lbfa s = case lookup s (trans lbfa) of Just tl -> tl _ -> [] -- | Get the transitions of a state and a symbol transitions lbfa (s, a) = [ st | (b, st) <- transitionList lbfa s, a == b ] -- | firstState = minimum . states -- | Get the max state of a LBFA lastState = lastS -- | Get the alphabet of a LBFA alphabet = alpha -- | Get the initial state of a LBFA initial :: LBFA a -> StateTy initial = initS -- | Does the LBFA accept epsilon? acceptEpsilon :: LBFA a -> Bool acceptEpsilon lbfa = isFinal lbfa (initial lbfa) -- | Compile a regular expression to a LBFA compileToLBFA :: Ord a => Reg a -> Sigma a -> StateTy -> LBFA a compileToLBFA reg sigma = evalState $ build reg $ nub $ sigma ++ symbols reg -- | Compile a regular expression to an minimal, useful and -- deterministic automaton, using the LBFA algorithm while building. compileToAutomaton :: Ord a => Reg a -> Sigma a -> StateTy -> Automaton a compileToAutomaton reg sigma s = encode (compileToLBFA reg sigma s) fetchState :: State StateTy StateTy fetchState = do state <- get put (state + 1) return state -- | Build a LBFA from a regular expression build :: Ord a => Reg a -> Sigma a -> State StateTy (LBFA a) build Empty sigma = do s <- fetchState return $ LBFA { trans = [(s, [])], initS = s, finalS = [], alpha = sigma, lastS = s } build Epsilon sigma = do s <- fetchState return LBFA { trans = [(s, [])], initS = s, finalS = [s], alpha = sigma, lastS = s } build (Symbol a) sigma = do s1 <- fetchState s2 <- fetchState return LBFA { trans = [(s1, [(a, s2)]), (s2, [])], initS = s1, finalS = [s2], alpha = sigma, lastS = s2 } build All sigma = build (allToSymbols sigma) sigma build (r1 :.: r2) sigma = do lbfa1 <- build r1 sigma lbfa2 <- build r2 sigma s <- fetchState let transUnion = (remove (initial lbfa1) (trans lbfa1)) ++ (remove (initial lbfa2) (trans lbfa2)) transConc = let t = transitionList lbfa2 (initial lbfa2) in [ (f,t) | f <- finals lbfa1 ] transInit = [(s, transitionList lbfa1 (initial lbfa1) ++ listEps lbfa1 (transitionList lbfa2 (initial lbfa2)))] fs = finals lbfa2 ++ listEps lbfa2 (finals lbfa1) ++ [ s | acceptEpsilon lbfa1 && acceptEpsilon lbfa2 ] return $ LBFA { trans = transInit ++ merge transConc transUnion, finalS = fs \\ [(initial lbfa1), (initial lbfa2)], alpha = sigma, initS = s, lastS = s } build (r1 :|: r2) sigma = do lbfa1 <- build r1 sigma lbfa2 <- build r2 sigma s <- fetchState let transUnion = (remove (initial lbfa1) (trans lbfa1)) ++ (remove (initial lbfa2) (trans lbfa2)) transInit = [(s, transitionList lbfa1 (initial lbfa1) ++ transitionList lbfa2 (initial lbfa2))] fs = finals lbfa1 ++ finals lbfa2 ++ [ s | acceptEpsilon lbfa1 || acceptEpsilon lbfa2 ] return $ LBFA { trans = transInit ++ transUnion, finalS = fs \\ [(initial lbfa1),(initial lbfa2)], alpha = sigma, initS = s, lastS = s } build (Star r1) sigma = do lbfa1 <- build r1 sigma s <- fetchState let transUnion = remove (initial lbfa1) (trans lbfa1) transLoop = let t = transitionList lbfa1 (initial lbfa1) in (s,t) : [ (f,t) | f <- finals lbfa1 ] return $ LBFA { trans = merge transLoop transUnion, finalS = s:(delete (initial lbfa1) (finals lbfa1)), alpha = sigma, initS = s, lastS = s } build (Complement r1) sigma = do lbfa <- build r1 sigma let lbfa1 = decode $ determinize $ complete $ encode lbfa put (lastState lbfa1 + 1) return $ LBFA { trans = trans lbfa1, finalS = states lbfa1 \\ finals lbfa1, alpha = sigma, initS = initial lbfa1, lastS = lastState lbfa1 } build (r1 :&: r2) sigma = do lbfa1 <- build r1 sigma lbfa2 <- build r2 sigma let minS1 = firstState lbfa1 minS2 = firstState lbfa2 name (s1,s2) = (lastState lbfa2 - minS2 +1) * (s1 - minS1) + s2 - minS2 + minS1 nS = name (lastState lbfa1,lastState lbfa2) +1 transInit = (nS, [ (a, name (s1, s2)) | (a,s1) <- transitionList lbfa1 (initial lbfa1) , (b,s2) <- transitionList lbfa2 (initial lbfa2) , a == b]) transTable = [(name (s1, s2), [(a, name (s3, s4)) | (a,s3) <- tl1 , (b,s4) <- tl2, a == b ]) | (s1,tl1) <- trans lbfa1 , (s2,tl2) <- trans lbfa2 , s1 /= initial lbfa1 || s2 /= initial lbfa2 ] transUnion = transInit:transTable fs = [ nS | acceptEpsilon lbfa1 && acceptEpsilon lbfa2 ] ++ [ name (f1,f2) | f1 <- finals lbfa1, f2 <- finals lbfa2 ] put (nS + 1) return LBFA { trans = merge [ (s, []) | s <- fs ] transUnion, finalS = fs, alpha = sigma, initS = nS, lastS = nS } instance Convertable LBFA where encode lbfa = construct (firstState lbfa,lastState lbfa) (trans lbfa) (alphabet lbfa) (initials lbfa) (finals lbfa) decode auto = LBFA { trans = transitionTable auto, initS = head (initials auto), finalS = finals auto, alpha = alphabet auto, lastS = lastState auto } instance (Eq a,Show a) => Show (LBFA a) where show auto = unlines [ "Transitions:", aux (trans auto), "Number of States => " ++ show countStates, "Initial => " ++ show (initial auto), "Finals => " ++ show (finals auto) ] where aux xs = unlines [show s ++" => " ++ show tl | (s, tl) <- xs ] countStates = length $ nub $ map fst (trans auto) ++ finals auto -- | If the LBFA accepts epsilon, return second argument listEps :: LBFA a -> [b] -> [b] listEps lbfa xs | acceptEpsilon lbfa = xs | otherwise = []
johnjcamilleri/fst
FST/LBFA.hs
bsd-3-clause
7,326
0
17
2,403
2,564
1,349
1,215
181
1
{-# LANGUAGE OverloadedStrings #-} import Data.Text import Data.Text.Encoding (encodeUtf8) import Pipes import Pipes.Prelude (discard) import Pipes.ByteString (writeHandle) import Pipes.Parse (unwrap, wrap) import Pipes.Tar import Data.Time (getCurrentTime) import System.IO (withFile, IOMode(WriteMode)) main :: IO () main = withFile "hello.tar" WriteMode $ \h -> runEffect $ (wrap . tarEntries >-> writeTar >-> forever . writeHandle h >-> discard) () where tarEntries () = do now <- lift getCurrentTime writeDirectoryEntry "text" 0 0 0 now writeFileEntry "text/hello" 0 0 0 now <-< (wrap . const (respond (encodeUtf8 "Hello!"))) $ ()
ocharles/pipes-tar
examples/writer.hs
bsd-3-clause
666
0
17
117
232
123
109
-1
-1
module DX200 where data DXVoiceParameters = DXVoiceParameters { voice1 :: Voice , voice2 :: Voice , voice3 :: Voice , voice4 :: Voice , voice5 :: Voice , voice6 :: Voice , pitchEnvelope :: EnvelopeGenerator , algorithm :: Int , feedbackLevel :: Int , oscPhaseInit :: OnOff , pitchModulationDepth :: Int , amplitudeModulationDepth :: Int , lfo :: LFO , transpose :: Note , name :: String } data DXVoiceAdditionalParameters = DXVoiceAdditionalParameters { op1AmplitudeModulationSensitivity :: Int , op2AmplitudeModulationSensitivity :: Int , op3AmplitudeModulationSensitivity :: Int , op4AmplitudeModulationSensitivity :: Int , op5AmplitudeModulationSensitivity :: Int , op6AmplitudeModulationSensitivity :: Int , pitchEnvelopeRange :: PitchEnvelopeRange , lfoKeyTrigger :: LfoKeyTrigger , pitchEnvelopeByVelocitySwitch :: OnOff , polyMonoUnison :: (PolyOrMono, OnOff) , pitchBendRange :: Int , pitchBendStep :: Int , randomPitchFluctuation :: Int , portamentoMode :: PortamentoMode , portamentoStep :: Int , portamentoTime :: Int , pitchEnvelopeRateScalingDepth :: Int , unisonDetuneDepth :: Int } data LFO = LFO { speed :: Int , delayTime :: Int , keySync :: Int , wave :: LFOWave , pitchModulationSensitivity :: Int } deriving (Show, Eq) data LFOWave = Triangle | SawDown | SawUp | Square | Sine | SampleAndHold deriving (Show, Eq) data Voice = Voice { envelope :: EnvelopeGenerator , keyboardScaling :: KeyboardScaling , amplitudeModulationSensitivity :: Int , touchSensitivity :: Int , totalLevel :: Int , frequencyMode :: FrequencyMode , frequencyCourse :: Int , frequencyFine :: Int , detune :: Int , enabled :: OnOff } deriving (Show, Eq) data EnvelopeGenerator = EnvelopeGenerator { rate1 :: Int , level1 :: Int , rate2 :: Int , level2 :: Int , rate3 :: Int , level3 :: Int , rate4 :: Int , level4 :: Int } deriving (Show, Eq) data KeyboardScaling = KeyboardScaling { breakPoint :: Note , leftDepth :: Int , leftCurve :: ScalingCurve , rightDepth :: Int , rightCurve :: Int , rateScaling :: Int } deriving (Show, Eq) type Note = Int data ScalingCurve = NegLin | NegExp | PosExp | PosLin deriving (Show, Eq) data FrequencyMode = Ratio | Fixed deriving (Show, Eq) data OnOff = On | Off deriving (Show, Eq) data PitchEnvelopeRange = EightOctaves | TwoOctaves | OneOctave | HalfOctave deriving (Show, Eq) data LfoKeyTrigger = Single | Multi deriving (Show, Eq) data PolyOrMono = Poly | Mono deriving (Show, Eq) data PortamentoMode = Return | Fingered deriving (Show, Eq)
rumblesan/dx200-programmer
src/DX200.hs
bsd-3-clause
2,628
0
9
540
678
425
253
82
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} module Network.QiitaTest where import Network.Qiita import Control.Monad.State import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as LB import qualified Data.ByteString.Char8 as C8 import qualified Data.ByteString.Lazy.Char8 as LC {- ------------------------------------------ - withAuthentication利用例. - 実行したら - 1. ユーザ名を入力してEnter - 2. パスワードを入力してEnter - とすると、先の処理が実行されます. ------------------------------------------- -} run :: IO () run = do putStrLn "ユーザ名を入力してEnter、次にパスワードを入力してEnterを押すこと!" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runCore ctx) -- 認証OK後の処理 {- ------------------------------------------ - Qiitaにアクセスする、主処理. - QiitaContextにいつでもアクセス出来るように、StateTという型を使う. - StateT QiitaContext m n という型に対して - getを呼ぶとQiitaContextを取得することが出来る. ------------------------------------------- -} runCore :: StateT QiitaContext IO () runCore = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" ctx1 <- get liftIO $ putStrLn ("Pre: " ++ (show ctx1)) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" user <- getLoginUserInformation liftIO $ print user ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" user' <- liftIO $ getUserInformation "jabaraster" liftIO $ print user' ctx3 <- get liftIO $ putStrLn ("Post: " ++ (show ctx3)) liftIO $ putStrLn "" liftIO $ putStrLn "- 4. -----------------------------" tags <- getTagsAFirstPage liftIO $ mapM_ (\page -> print $ (++) " >>>> " (show page)) (pagenation tags) ctx4 <- get liftIO $ putStrLn "" liftIO $ putStrLn "- 5. -----------------------------" tags' <- getTagsAWithPage (pagenation tags !! 0) liftIO $ mapM_ print (list tags') liftIO $ mapM_ print (pagenation tags') runPostItem :: StateT QiitaContext IO () runPostItem = do let newItem = PostItem { post_item_title = "Qiita API on Haskell" , post_item_body = "Qiita API on Haskell" , post_item_tags = [ PostTag "Haskell" [] ] , post_item_private = True , post_item_gist = False , post_item_tweet = False } item <- postItem newItem liftIO $ print item runGetItems :: IO () runGetItems = do putStrLn "Input your User Id and Enter、then password and Enter" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runGetItemsCore ctx) -- 認証OK後の処理 -- 認証なし実行 runGetItemsCore2 runGetItemsCore :: StateT QiitaContext IO () runGetItemsCore = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" items <- getItemsAFirstPage liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" items <- getItemsAFirstPage' 2 liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" items <- getItemsAWithPage (pagenation items !! 0) liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) runGetItemsCore2 :: IO () runGetItemsCore2 = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" items <- getItemsFirstPage liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" items <- getItemsFirstPage' 5 liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" items <- getItemsWithPage (pagenation items !! 0) liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) runGetStocks :: IO () runGetStocks = do putStrLn "Input your User Id and Enter、then password and Enter" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runGetStocksCore ctx) -- 認証OK後の処理 runGetStocksCore :: StateT QiitaContext IO () runGetStocksCore = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" items <- getStocksAFirstPage liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" items <- getStocksAFirstPage' 2 liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" items <- getStocksAWithPage (pagenation items !! 0) liftIO $ mapM_ (\l -> print $ l) (list items) liftIO $ mapM_ (\l -> print $ l) (pagenation items) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) runGetUserFollowingTags :: IO () runGetUserFollowingTags = do putStrLn "Input your User Id and Enter、then password and Enter" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runGetUserFollowingTagsCore ctx) -- 認証OK後の処理 -- 認証なし実行 runGetUserFollowingTagsCore2 runGetUserFollowingTagsCore :: StateT QiitaContext IO () runGetUserFollowingTagsCore = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" tagList1 <- liftIO $ getUserFollowingTagsAFirstPage "jabaraster" let tags1 = fst tagList1 liftIO $ mapM_ (\l -> print $ l) (list tags1) liftIO $ mapM_ (\l -> print $ l) (pagenation tags1) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" tagList2 <- liftIO $ getUserFollowingTagsAFirstPage' "jabaraster" 2 let tags2 = fst tagList2 liftIO $ mapM_ (\l -> print $ l) (list tags2) liftIO $ mapM_ (\l -> print $ l) (pagenation tags2) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" tagList3 <- liftIO $ getUserFollowingTagsAWithPage (pagenation tags2 !! 0) let tags3 = fst tagList3 liftIO $ mapM_ (\l -> print $ l) (list tags3) liftIO $ mapM_ (\l -> print $ l) (pagenation tags3) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) runGetUserFollowingTagsCore2 :: IO () runGetUserFollowingTagsCore2 = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" tagList1 <- liftIO $ getUserFollowingTagsFirstPage "jabaraster" let tags1 = fst tagList1 liftIO $ mapM_ (\l -> print $ l) (list tags1) liftIO $ mapM_ (\l -> print $ l) (pagenation tags1) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" tagList2 <- liftIO $ getUserFollowingTagsFirstPage' "jabaraster" 2 let tags2 = fst tagList2 liftIO $ mapM_ (\l -> print $ l) (list tags2) liftIO $ mapM_ (\l -> print $ l) (pagenation tags2) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" tagList3 <- liftIO $ getUserFollowingTagsWithPage (pagenation tags2 !! 0) let tags3 = fst tagList3 liftIO $ mapM_ (\l -> print $ l) (list tags3) liftIO $ mapM_ (\l -> print $ l) (pagenation tags3) runGetUserFollowingUsers :: IO () runGetUserFollowingUsers = do putStrLn "Input your User Id and Enter、then password and Enter" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runGetUserFollowingUsersCore ctx) -- 認証OK後の処理 -- 認証なし実行 runGetUserFollowingUsersCore2 runGetUserFollowingUsersCore :: StateT QiitaContext IO () runGetUserFollowingUsersCore = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" userList1 <- liftIO $ getUserFollowingUsersAFirstPage "jabaraster" let users1 = fst userList1 liftIO $ mapM_ (\l -> print $ l) (list users1) liftIO $ mapM_ (\l -> print $ l) (pagenation users1) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" userList2 <- liftIO $ getUserFollowingUsersAFirstPage' "jabaraster" 2 let users2 = fst userList2 liftIO $ mapM_ (\l -> print $ l) (list users2) liftIO $ mapM_ (\l -> print $ l) (pagenation users2) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" userList3 <- liftIO $ getUserFollowingUsersAWithPage (pagenation users2 !! 0) let users3 = fst userList3 liftIO $ mapM_ (\l -> print $ l) (list users3) liftIO $ mapM_ (\l -> print $ l) (pagenation users3) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) runGetUserFollowingUsersCore2 :: IO () runGetUserFollowingUsersCore2 = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" userList1 <- liftIO $ getUserFollowingUsersFirstPage "jabaraster" let users1 = fst userList1 liftIO $ mapM_ (\l -> print $ l) (list users1) liftIO $ mapM_ (\l -> print $ l) (pagenation users1) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" userList2 <- liftIO $ getUserFollowingUsersFirstPage' "jabaraster" 2 let users2 = fst userList2 liftIO $ mapM_ (\l -> print $ l) (list users2) liftIO $ mapM_ (\l -> print $ l) (pagenation users2) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" userList3 <- liftIO $ getUserFollowingUsersWithPage (pagenation users2 !! 0) let users3 = fst userList3 liftIO $ mapM_ (\l -> print $ l) (list users3) liftIO $ mapM_ (\l -> print $ l) (pagenation users3) runGetUserStocks :: IO () runGetUserStocks = do putStrLn "Input your User Id and Enter、then password and Enter" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runGetUserStocksCore ctx) -- 認証OK後の処理 -- 認証なし実行 runGetUserStocksCore2 runGetUserStocksCore :: StateT QiitaContext IO () runGetUserStocksCore = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" itemList1 <- liftIO $ getUserStocksAFirstPage "matscity@github" let items1 = fst itemList1 liftIO $ mapM_ (\l -> print $ l) (list items1) liftIO $ mapM_ (\l -> print $ l) (pagenation items1) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" itemList2 <- liftIO $ getUserStocksAFirstPage' "matscity@github" 2 let items2 = fst itemList2 liftIO $ mapM_ (\l -> print $ l) (list items2) liftIO $ mapM_ (\l -> print $ l) (pagenation items2) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" itemList3 <- liftIO $ getUserStocksAWithPage (pagenation items2 !! 0) let items3 = fst itemList3 liftIO $ mapM_ (\l -> print $ l) (list items3) liftIO $ mapM_ (\l -> print $ l) (pagenation items3) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) runGetUserStocksCore2 :: IO () runGetUserStocksCore2 = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" itemList1 <- liftIO $ getUserStocksFirstPage "jabaraster" let items1 = fst itemList1 liftIO $ mapM_ (\l -> print $ l) (list items1) liftIO $ mapM_ (\l -> print $ l) (pagenation items1) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" itemList2 <- liftIO $ getUserStocksFirstPage' "jabaraster" 2 let items2 = fst itemList2 liftIO $ mapM_ (\l -> print $ l) (list items2) liftIO $ mapM_ (\l -> print $ l) (pagenation items2) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" itemList3 <- liftIO $ getUserStocksWithPage (pagenation items2 !! 0) let items3 = fst itemList3 liftIO $ mapM_ (\l -> print $ l) (list items3) liftIO $ mapM_ (\l -> print $ l) (pagenation items3) runGetUserItems :: IO () runGetUserItems = do putStrLn "Input your User Id and Enter、then password and Enter" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runGetUserItemsCore ctx) -- 認証OK後の処理 -- 認証なし実行 runGetUserItemsCore2 runGetUserItemsCore :: StateT QiitaContext IO () runGetUserItemsCore = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" itemList1 <- liftIO $ getUserItemsAFirstPage "jabaraster" let items1 = fst itemList1 liftIO $ mapM_ (\l -> print $ l) (list items1) liftIO $ mapM_ (\l -> print $ l) (pagenation items1) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" itemList2 <- liftIO $ getUserItemsAFirstPage' "jabaraster" 2 let items2 = fst itemList2 liftIO $ mapM_ (\l -> print $ l) (list items2) liftIO $ mapM_ (\l -> print $ l) (pagenation items2) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" itemList3 <- liftIO $ getUserItemsAWithPage (pagenation items2 !! 0) let items3 = fst itemList3 liftIO $ mapM_ (\l -> print $ l) (list items3) liftIO $ mapM_ (\l -> print $ l) (pagenation items3) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) runGetUserItemsCore2 :: IO () runGetUserItemsCore2 = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" itemList1 <- liftIO $ getUserItemsFirstPage "jabaraster" let items1 = fst itemList1 liftIO $ mapM_ (\l -> print $ l) (list items1) liftIO $ mapM_ (\l -> print $ l) (pagenation items1) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" itemList2 <- liftIO $ getUserItemsFirstPage' "jabaraster" 2 let items2 = fst itemList2 liftIO $ mapM_ (\l -> print $ l) (list items2) liftIO $ mapM_ (\l -> print $ l) (pagenation items2) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" itemList3 <- liftIO $ getUserItemsWithPage (pagenation items2 !! 0) let items3 = fst itemList3 liftIO $ mapM_ (\l -> print $ l) (list items3) liftIO $ mapM_ (\l -> print $ l) (pagenation items3) runSearchItems :: IO () runSearchItems = do putStrLn "Input your User Id and Enter、then password and Enter" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runSearchItemsCore ctx) -- 認証OK後の処理 -- 認証なし実行 runSearchItemsCore2 runSearchItemsCore :: StateT QiitaContext IO () runSearchItemsCore = do liftIO $ putStrLn "" liftIO $ putStrLn "- 0. -----------------------------" items0 <- searchStockedItemsAFirstPage "java" liftIO $ mapM_ (\l -> print $ l) (list items0) liftIO $ mapM_ (\l -> print $ l) (pagenation items0) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" itemList1 <- liftIO $ searchItemsAFirstPage "ruby emacs" let items1 = fst itemList1 liftIO $ mapM_ (\l -> print $ l) (list items1) liftIO $ mapM_ (\l -> print $ l) (pagenation items1) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" itemList2 <- liftIO $ searchItemsAFirstPage' "ruby emacs" 2 let items2 = fst itemList2 liftIO $ mapM_ (\l -> print $ l) (list items2) liftIO $ mapM_ (\l -> print $ l) (pagenation items2) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" itemList3 <- liftIO $ searchItemsAWithPage (pagenation items2 !! 0) let items3 = fst itemList3 liftIO $ mapM_ (\l -> print $ l) (list items3) liftIO $ mapM_ (\l -> print $ l) (pagenation items3) ctx2 <- get liftIO $ putStrLn ("Post: " ++ (show ctx2)) runSearchItemsCore2 :: IO () runSearchItemsCore2 = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" itemList1 <- liftIO $ searchItemsFirstPage "haskell" let items1 = fst itemList1 liftIO $ mapM_ (\l -> print $ l) (list items1) liftIO $ mapM_ (\l -> print $ l) (pagenation items1) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" itemList2 <- liftIO $ searchItemsFirstPage' "haskell" 2 let items2 = fst itemList2 liftIO $ mapM_ (\l -> print $ l) (list items2) liftIO $ mapM_ (\l -> print $ l) (pagenation items2) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" itemList3 <- liftIO $ searchItemsWithPage (pagenation items2 !! 0) let items3 = fst itemList3 liftIO $ mapM_ (\l -> print $ l) (list items3) liftIO $ mapM_ (\l -> print $ l) (pagenation items3) runGetTagItems :: StateT QiitaContext IO () runGetTagItems = do liftIO $ putStrLn "" liftIO $ putStrLn "- 1. -----------------------------" itemList1 <- liftIO $ getTagItemsFirstPage "Haskell" let items1 = fst itemList1 liftIO $ mapM_ print (list items1) liftIO $ mapM_ print (pagenation items1) liftIO $ putStrLn "" liftIO $ putStrLn "- 2. -----------------------------" itemList2 <- liftIO $ getTagItemsFirstPage' "Haskell" 10 let items2 = fst itemList2 liftIO $ mapM_ print (list items2) liftIO $ mapM_ print (pagenation items2) liftIO $ putStrLn "" liftIO $ putStrLn "- 3. -----------------------------" itemList3 <- liftIO $ getTagItemsWithPage (pagenation items2 !! 0) let items3 = fst itemList3 liftIO $ mapM_ print (list items3) liftIO $ mapM_ print (pagenation items3) runUpdateItem :: IO () runUpdateItem = do putStrLn "ユーザ名を入力してEnter、次にパスワードを入力してEnterを押すこと!" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT runUpdateItemCore ctx) -- 認証OK後の処理 runUpdateItemCore :: StateT QiitaContext IO () runUpdateItemCore = do let newItem = PostItem { post_item_title = "Qiita API on Haskell" , post_item_body = "Qiita API on Haskell" , post_item_tags = [ PostTag "Haskell" [] ] , post_item_private = True , post_item_gist = False , post_item_tweet = False } postedS <- postItem newItem case postedS of Left err -> liftIO $ print err Right posted -> do let updated = itemToUpdateItem posted updatedS <- updateItem updated { update_item_title = "Updated Item." } liftIO $ print updatedS runDeleteItem :: IO () runDeleteItem = do putStrLn "ユーザ名を入力してEnter、次にパスワードを入力してEnter、最後に削除したい投稿のUUIDを入力してEnterを押すこと!" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 let uuid = C8.pack $ lines !! 2 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT (runDeleteItemCore uuid) ctx) -- 認証OK後の処理 runDeleteItemCore :: B.ByteString -> StateT QiitaContext IO () runDeleteItemCore uuid = do deleteItem uuid return () runStockItem :: IO () runStockItem = do putStrLn "ユーザ名を入力してEnter、次にパスワードを入力してEnter、最後にストックしたい投稿のUUIDを入力してEnterを押すこと!" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 let uuid = C8.pack $ lines !! 2 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT (runStockItemCore uuid) ctx) -- 認証OK後の処理 runStockItemCore :: ItemUuid -> StateT QiitaContext IO () runStockItemCore uuid = do stockItem uuid return () runUnstockItem :: IO () runUnstockItem = do putStrLn "ユーザ名を入力してEnter、次にパスワードを入力してEnter、最後にストック解除したい投稿のUUIDを入力してEnterを押すこと!" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 let uuid = C8.pack $ lines !! 2 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT (runUnstockItemCore uuid) ctx) -- 認証OK後の処理 runUnstockItemCore :: ItemUuid -> StateT QiitaContext IO () runUnstockItemCore uuid = do unstockItem uuid return () runGetItem :: IO () runGetItem = do putStrLn "ユーザ名を入力してEnter、次にパスワードを入力してEnter、最後に取得したい投稿のUUIDを入力してEnterを押すこと!" input <- getContents lines <- return $ lines input let user = C8.pack $ lines !! 0 let pass = C8.pack $ lines !! 1 let uuid = C8.pack $ lines !! 2 withAuthentication user pass (\err limit -> print err >> print limit) -- 認証エラー時の処理 (\ctx -> evalStateT (runGetItemCore uuid) ctx) -- 認証OK後の処理 runGetItemCore :: ItemUuid -> StateT QiitaContext IO () runGetItemCore uuid = do item <- liftIO $ getItem uuid liftIO $ print item
jabaraster/network-qiita
src/Network/QiitaTest.hs
bsd-3-clause
23,942
0
15
4,927
8,002
3,777
4,225
539
2
module Hearthstone where import qualified System.Random.Shuffle as Rand import Data.List(sort) import Control.Monad.Random type Card = Int type Deck = [Card] type Hand = [Card] type Health = Int type Mana = Int data Player = Player Health Mana Hand Deck fullDeck :: [Card] fullDeck = [0,0,1,1,2,2,2,3,3,3,3,4,4,4,5,5,6,6,7,8] makeDeck :: (MonadRandom m) => m Deck makeDeck = Rand.shuffleM fullDeck playHand :: (Player, Player) -> (Player, Player) playHand ((Player health1 mana1 cards1 d1), (Player health2 p2m p2c d2)) = let newCard = head d1 newDeck = drop 1 d1 (totalDamage, handLeft, manaLeft) = foldr (\card (dam, hand, mana) -> if (card <= mana) then (dam+card, hand, mana-card) else (dam, card:hand,mana)) (0, [], mana1) (sort (newCard:cards1)) p2 = Player (health2 - totalDamage) p2m p2c d2 p1 = Player health1 manaLeft handLeft newDeck in (p2, p1) playRound :: (Player, Player) -> (Player, Player) playRound a = let (p2, p1) = playHand a (p1a, p2a) = playHand (p2,p1) in (p1a, p2a) main :: IO () main = do a <- makeDeck b <- makeDeck putStrLn $ show a putStrLn $ show b
steveshogren/haskell-katas
src/Hearthstone.hs
bsd-3-clause
1,213
0
14
310
540
310
230
40
2
module Moodle.Translator (toLatex) where import Data.List (intercalate) import Data.Scientific (floatingOrInteger) import Moodle.Types (MoodleVal(..)) group :: String -> String group s = '{':s ++ "}" -- TODO: Use printf instead of string concatenation -- | Convert a 'MoodleVal' value into a Latex string. toLatex :: MoodleVal -> String toLatex (Number n) | n >= 0 = formatted | otherwise = group formatted where formatted = either show show $ floatingOrInteger n toLatex (Variable v) = "\\mathrm" ++ group v -- TODO: make interpolation possible toLatex (Op op a b) = case op of "*" -> toLatex a ++ "\\cdot" ++ toLatex b "/" -> "\\frac" ++ group (toLatex a) ++ group (toLatex b) _ -> group (toLatex a) ++ op ++ group (toLatex b) toLatex (Function "pi" []) = "\\pi" toLatex (Function "sqrt" [n]) = "\\sqrt" ++ group (toLatex n) toLatex (Function "sqrt" [n, r]) = "\\sqrt[" ++ toLatex r ++ "]" ++ group (toLatex n) toLatex (Function "pow" [a, b]) = group (toLatex a) ++ "^" ++ group (toLatex b) toLatex (Function name xs) = name ++ "(" ++ args ++ ")" where args = intercalate ", " $ map toLatex xs
rubik/moodle-to-latex
src/Moodle/Translator.hs
bsd-3-clause
1,156
0
12
252
455
229
226
24
3
{-# OPTIONS_GHC -fno-warn-orphans #-} module Monad( ServerEnv(..) , ServerM , newServerEnv , runServerM , runServerMIO , serverMtoHandler , AuthM(..) , runAuth ) where import Control.Monad.Base import Control.Monad.Catch (MonadCatch, MonadThrow) import Control.Monad.Except import Control.Monad.Logger import Control.Monad.Reader import Control.Monad.Trans.Control import Data.Acid import Data.Monoid import Data.Text (unpack) import Servant.Server import Servant.Server.Auth.Token.Acid as A import Servant.Server.Auth.Token.Config import Servant.Server.Auth.Token.Model import Config import DB -- | Server private environment data ServerEnv = ServerEnv { -- | Configuration used to create the server envConfig :: !ServerConfig -- | Configuration of auth server , envAuthConfig :: !AuthConfig -- | DB state , envDB :: !(AcidState DB) } -- | Create new server environment newServerEnv :: MonadIO m => ServerConfig -> m ServerEnv newServerEnv cfg = do let authConfig = defaultAuthConfig db <- liftIO $ openLocalStateFrom (unpack $ serverDbPath cfg) newDB -- ensure default admin if missing one _ <- runAcidBackendT authConfig db $ ensureAdmin 17 "admin" "123456" "admin@localhost" let env = ServerEnv { envConfig = cfg , envAuthConfig = authConfig , envDB = db } return env -- | Server monad that holds internal environment newtype ServerM a = ServerM { unServerM :: ReaderT ServerEnv (LoggingT Handler) a } deriving (Functor, Applicative, Monad, MonadIO, MonadBase IO, MonadReader ServerEnv , MonadLogger, MonadLoggerIO, MonadThrow, MonadCatch, MonadError ServantErr) newtype StMServerM a = StMServerM { unStMServerM :: StM (ReaderT ServerEnv (LoggingT Handler)) a } instance MonadBaseControl IO ServerM where type StM ServerM a = StMServerM a liftBaseWith f = ServerM $ liftBaseWith $ \q -> f (fmap StMServerM . q . unServerM) restoreM = ServerM . restoreM . unStMServerM -- | Lift servant monad to server monad liftHandler :: Handler a -> ServerM a liftHandler = ServerM . lift . lift -- | Execution of 'ServerM' runServerM :: ServerEnv -> ServerM a -> Handler a runServerM e = runStdoutLoggingT . flip runReaderT e . unServerM -- | Execution of 'ServerM' in IO monad runServerMIO :: ServerEnv -> ServerM a -> IO a runServerMIO env m = do ea <- runExceptT $ runServerM env m case ea of Left e -> fail $ "runServerMIO: " <> show e Right a -> return a -- | Transformation to Servant 'Handler' serverMtoHandler :: ServerEnv -> ServerM :~> Handler serverMtoHandler e = Nat (runServerM e) -- Derive HasStorage for 'AcidBackendT' with your 'DB' deriveAcidHasStorage ''DB -- | Special monad for authorisation actions newtype AuthM a = AuthM { unAuthM :: AcidBackendT DB IO a } deriving (Functor, Applicative, Monad, MonadIO, MonadError ServantErr, HasAuthConfig, HasStorage) -- | Execution of authorisation actions that require 'AuthHandler' context runAuth :: AuthM a -> ServerM a runAuth m = do cfg <- asks envAuthConfig db <- asks envDB liftHandler $ ExceptT $ runAcidBackendT cfg db $ unAuthM m
ivan-m/servant-auth-token
example/acid/src/Monad.hs
bsd-3-clause
3,126
0
12
580
811
437
374
-1
-1
{-#LANGUAGE DeriveDataTypeable#-} module Tc.TcDecl where import Control.Monad import Control.Monad.Trans import Data.Generics import Data.List (partition,union, intersect,(\\), nub) import Language.Haskell.Exts hiding (name) import BuiltIn.BuiltInTypes import Tc.Assumption import {-# SOURCE #-}Tc.TcExp import Tc.TcMonad import Tc.TcPat import Tc.TcSubst import Tc.TcWellformed import Tc.TcAlphaEq import Tc.TcSimplify import Utils.ErrMsg import Utils.Nameable import Utils.DependencyAnalysis import Utils.Id -- type inference for declarations -- the first list of declarations: non-overloaded binds -- the second list of declarations: class / instance methods tcDecls :: [Decl] -> [Decl] -> TcM [Assumption] tcDecls ds is = do let (bs,as) = bindsFrom ds (si,ib) = partition isTypeSig is si' = map sig2Assump si bs' = dependencyAnalysis TypeAnalysis (bs ++ map Method ib) (_, as') <- extendGamma (as ++ si') (tcBindGroups True bs') return (as ++ as' ++ si') -- Boolean: Is a top level declaration? tcDecl :: Bool -> Decl -> TcM (Context, [Assumption]) tcDecl b f@(FunBind ms) = withDiagnostic f $ do rs <- mapM (tcMatch b) ms let ctx = concatMap fst3 rs ts = map snd3 rs as = concatMap trd3 rs n = name f v <- newFreshVar mapM_ (unify v) ts s <- getSubst let a = toScheme n ctx (apply s v) return (ctx, [a]) tcDecl b f@(PatBind _ p _ rhs bs) = withDiagnostic f $ do let n = name f (ctx, as) <- tcBinds False bs (ctx', as', t) <- tcPat p (ctx'',t', as'') <- extendGamma (as ++ as') (tcRhs rhs) s <- unify t t' let ctx1 = apply s (concat [ctx, ctx', ctx'']) a = toScheme n ctx' (apply s t) let af = if b then [a] else a : (apply s as') return (ctx1, af) tcDecl _ x = typeDeclErrorPanic "Tc.TcDecl.tcDecl" x -- here we return the local assumptions for the -- use in the satisfiability test algorithm, because -- when we test sat, lambda-bound variables aren't in -- context, because they're removed by extendGamma. tcMatch :: Bool -> Match -> TcM (Context, Type, [Assumption]) tcMatch _ m@(Match _ _ ps _ rhs wbs) = do (ctx, as, ts) <- tcPats ps (ctx', as') <- extendGamma as (tcBinds False wbs) (ctx'', t, as'') <- extendGamma (as ++ as') (tcRhs rhs) s <- getSubst let t' = foldr TyFun t ts a = apply s (concat [ctx,ctx',ctx'']) b = apply s t' ass = concat [as,as',as''] return (a,b, ass) tcRhs :: Rhs -> TcM (Context, Type, [Assumption]) tcRhs (UnGuardedRhs e) = do (ctx,t) <- tcExp e return (ctx,t,[]) tcRhs x@(GuardedRhss grs) = do rs <- mapM tcGuardedRhs grs let ts = map snd3 rs ctx = concatMap fst3 rs as = concatMap trd3 rs v <- newFreshVar mapM_ (unify v) ts s <- getSubst let a = apply s ctx b = apply s v as' = apply s as return (a,b,as') tcGuardedRhs :: GuardedRhs -> TcM (Context, Type, [Assumption]) tcGuardedRhs (GuardedRhs _ [s] e) = do (ctx, as, Just t) <- tcStmt s unify t tBool (ctx', t) <- extendGamma as (tcExp e) s <- getSubst let a = apply s (ctx ++ ctx') b = apply s t as' = apply s as' return (a,b,as') tcGuardedRhs x = unsupportedExpErrMsg x -- types and functions for typing binds type Sig = Decl -- INVARIANT: holds only type signatures -- a data type to represent implicit and explicit typed binds data BindKind = Impl Decl | Expl Sig Decl | Method Decl deriving (Eq, Ord, Show, Data, Typeable) tcBinds :: Bool -> Binds -> TcM (Context, [Assumption]) tcBinds b (BDecls ds) = do let (bs,as) = bindsFrom ds bs' = dependencyAnalysis TypeAnalysis bs (ctx, as') <- tcBindGroups b bs' return (ctx, as ++ as') tcBinds _ (IPBinds x) = unsupportedDeclMsg (head x) tcBindGroups :: Bool -> [[BindKind]] -> TcM (Context, [Assumption]) tcBindGroups b bs = do rs <- tcSeq (tcBindGroup b) bs return (fst rs, snd rs) tcBindGroup :: Bool -> [BindKind] -> TcM (Context, [Assumption]) tcBindGroup b bs = do let (es, is) = partition isExpl bs as = map assumpFrom es ias <- mapM (\i -> liftM (name i :>:) newFreshVar) is as' <- extendGamma (as ++ ias) (tcSeq (tcBindKind b) is) _ <- extendGamma (as ++ (snd as')) (tcSeq (tcBindKind b) es) return (fst as', (snd as') ++ as) tcBindKind :: Bool -> BindKind -> TcM (Context, [Assumption]) tcBindKind b (Method d) = withDiagnostic d $ do let n = name d y <- lookupGamma n ann@(_:>: ta) <- freshInst y (ctx, x) <- tcDecl b d inf@(_:>: ti) <- freshInst (head x) cond <- subsumes n ta ti unless cond (typeMostGeneralThanExpectedError (head x) y) return (ctx, []) tcBindKind b (Impl d) = withDiagnostic d $ do (ctx, as) <- tcDecl b d let i@(n :>: (TyForall Nothing c' t')) = head as (ds,rs) <- split (c' ++ ctx) s <- getSubst m <- quantifyAssump (toScheme n rs t') liftIO (print m) a' <- wfAssump (toScheme n rs t') a1 <- quantifyAssump a' return (ds, if b then [a1] else a1 : tail as) tcBindKind b (Expl ty d) = withDiagnostic d $ do let ann = sig2Assump ty a@(_ :>: (TyForall Nothing c t)) <- freshInst ann (ctx, x) <- tcDecl b d let i@(n :>: (TyForall Nothing c' t')) = head x (ds,rs) <- split (c' ++ ctx) s <- getSubst i'@(_ :>: ti) <- wfAssump (toScheme n rs t') let a'@(_ :>: ta) = apply s a a'' <- quantifyAssump a' i'' <- quantifyAssump i' condition <- subsumes n ti ta unless condition (typeMostGeneralThanExpectedError i'' a'') return (ds, if b then [ann] else ann : tail x) -- a function to reduce the set of infered constraints. It -- returns a pair of contexts: -- 1 - Constraints defered to next scope level -- 2 - Constraints retained in this level. Must be included on the -- type split :: Context -> TcM (Context, Context) split ctx = do s <- getSubst ctx' <- reduce (apply s ctx) vs <- ftvM return (partition (all (`elem` vs) . fv) ctx') -- subsumption test for type anotations subsumes :: Id -> Type -> Type -> TcM Bool subsumes i inf ann = do let (ctxi,ti) = splitType inf (ctxa,ta) = splitType ann s <- match ti ta wfAssump (toScheme i (apply s ctxi) ta) return True -- builds a list of implict / explicit binds form a list -- of declarations bindsFrom :: [Decl] -> ([BindKind], [Assumption]) bindsFrom ds = (foldr step [] bs, map sig2Assump st) where (ts,bs) = partition isTypeSig ds ns = map (\t -> (name t, t)) ts nbs = map (\b -> name b) bs st = foldr go [] ts go t ac = if (name t) `elem` nbs then ac else t : ac step b ac = case lookup (name b) ns of Just t -> Expl t b : ac Nothing -> Impl b : ac -- needed instances for dependency analysis of local declarations instance Nameable BindKind where name (Impl d) = name d name (Expl t _) = name t name (Method d) = name d instance Referenceable BindKind where kindRefNames _ = [] typeRefNames (Impl d) = typeRefNames d typeRefNames (Expl _ d) = typeRefNames d typeRefNames (Method d) = typeRefNames d -- some auxiliar functions isTypeSig :: Decl -> Bool isTypeSig (TypeSig _ _ _) = True isTypeSig _ = False sig2Assump (TypeSig _ [n] t) = toId n :>: f t where f x@(TyForall _ _ _) = x f x = TyForall Nothing [] x assumpFrom :: BindKind -> Assumption assumpFrom (Expl ty _) = sig2Assump ty isExpl (Expl _ _) = True isExpl _ = False tcSeq tc [] = return ([],[]) tcSeq tc (bs:bss) = do (ctx,as) <- tc bs (ctx', as') <- extendGamma as (tcSeq tc bss) return (ctx ++ ctx', as ++ as') quantifyAssump(i :>: t) = liftM (i :>:) (uncurry quantify (splitType t)) fst3 (a,_,_) = a snd3 (_,b,_) = b trd3 (_,_,c) = c
rodrigogribeiro/mptc
src/Tc/TcDecl.hs
bsd-3-clause
8,622
4
16
2,816
3,338
1,701
1,637
227
3
-- | Simple textual diffing of JavaScript programs for inspecting test -- failures module Language.ECMAScript3.SourceDiff where import Data.Algorithm.Diff import Data.Algorithm.DiffOutput import Language.ECMAScript3.Syntax import Language.ECMAScript3.PrettyPrint import Data.List (intersperse, intercalate) jsDiff :: JavaScript a -> JavaScript a -> String jsDiff js1 js2 = let plines = lines . show . prettyPrint diff = getGroupedDiff (plines js1) (plines js2) in ppDiff diff
sinelaw/language-ecmascript
src/Language/ECMAScript3/SourceDiff.hs
bsd-3-clause
489
0
11
72
119
66
53
11
1
module Lib.Binary (runGet, runPut, encode, decode) where import Data.Binary (Binary, Get, Put) import Lib.ByteString (strictify, lazify) import qualified Data.Binary as Binary import qualified Data.Binary.Get as Get import qualified Data.Binary.Put as Put import qualified Data.ByteString as BS {-# INLINE runGet #-} runGet :: Get a -> BS.ByteString -> a runGet x = Get.runGet x . lazify {-# INLINE runPut #-} runPut :: Put -> BS.ByteString runPut = strictify . Put.runPut {-# INLINE decode #-} decode :: Binary a => BS.ByteString -> a decode = Binary.decode . lazify {-# INLINE encode #-} encode :: Binary a => a -> BS.ByteString encode = strictify . Binary.encode
sinelaw/buildsome
src/Lib/Binary.hs
gpl-2.0
671
0
7
108
202
120
82
19
1
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1998 This module contains definitions for the IdInfo for things that have a standard form, namely: - data constructors - record selectors - method and superclass selectors - primitive operations -} {-# LANGUAGE CPP #-} module MkId ( mkDictFunId, mkDictFunTy, mkDictSelId, mkDictSelRhs, mkPrimOpId, mkFCallId, wrapNewTypeBody, unwrapNewTypeBody, wrapFamInstBody, unwrapFamInstScrut, wrapTypeFamInstBody, wrapTypeUnbranchedFamInstBody, unwrapTypeFamInstScrut, unwrapTypeUnbranchedFamInstScrut, DataConBoxer(..), mkDataConRep, mkDataConWorkId, -- And some particular Ids; see below for why they are wired in wiredInIds, ghcPrimIds, unsafeCoerceName, unsafeCoerceId, realWorldPrimId, voidPrimId, voidArgId, nullAddrId, seqId, lazyId, lazyIdKey, coercionTokenId, magicDictId, coerceId, proxyHashId, -- Re-export error Ids module PrelRules ) where #include "HsVersions.h" import Rules import TysPrim import TysWiredIn import PrelRules import Type import FamInstEnv import Coercion import TcType import MkCore import CoreUtils ( exprType, mkCast ) import CoreUnfold import Literal import TyCon import CoAxiom import Class import NameSet import VarSet import Name import PrimOp import ForeignCall import DataCon import Id import IdInfo import Demand import CoreSyn import Unique import UniqSupply import PrelNames import BasicTypes hiding ( SuccessFlag(..) ) import Util import Pair import DynFlags import Outputable import FastString import ListSetOps import Data.Maybe ( maybeToList ) {- ************************************************************************ * * \subsection{Wired in Ids} * * ************************************************************************ Note [Wired-in Ids] ~~~~~~~~~~~~~~~~~~~ There are several reasons why an Id might appear in the wiredInIds: (1) The ghcPrimIds are wired in because they can't be defined in Haskell at all, although the can be defined in Core. They have compulsory unfoldings, so they are always inlined and they have no definition site. Their home module is GHC.Prim, so they also have a description in primops.txt.pp, where they are called 'pseudoops'. (2) The 'error' function, eRROR_ID, is wired in because we don't yet have a way to express in an interface file that the result type variable is 'open'; that is can be unified with an unboxed type [The interface file format now carry such information, but there's no way yet of expressing at the definition site for these error-reporting functions that they have an 'open' result type. -- sof 1/99] (3) Other error functions (rUNTIME_ERROR_ID) are wired in (a) because the desugarer generates code that mentiones them directly, and (b) for the same reason as eRROR_ID (4) lazyId is wired in because the wired-in version overrides the strictness of the version defined in GHC.Base In cases (2-4), the function has a definition in a library module, and can be called; but the wired-in version means that the details are never read from that module's interface file; instead, the full definition is right here. -} wiredInIds :: [Id] wiredInIds = [lazyId, dollarId, oneShotId] ++ errorIds -- Defined in MkCore ++ ghcPrimIds -- These Ids are exported from GHC.Prim ghcPrimIds :: [Id] ghcPrimIds = [ -- These can't be defined in Haskell, but they have -- perfectly reasonable unfoldings in Core realWorldPrimId, voidPrimId, unsafeCoerceId, nullAddrId, seqId, magicDictId, coerceId, proxyHashId ] {- ************************************************************************ * * \subsection{Data constructors} * * ************************************************************************ The wrapper for a constructor is an ordinary top-level binding that evaluates any strict args, unboxes any args that are going to be flattened, and calls the worker. We're going to build a constructor that looks like: data (Data a, C b) => T a b = T1 !a !Int b T1 = /\ a b -> \d1::Data a, d2::C b -> \p q r -> case p of { p -> case q of { q -> Con T1 [a,b] [p,q,r]}} Notice that * d2 is thrown away --- a context in a data decl is used to make sure one *could* construct dictionaries at the site the constructor is used, but the dictionary isn't actually used. * We have to check that we can construct Data dictionaries for the types a and Int. Once we've done that we can throw d1 away too. * We use (case p of q -> ...) to evaluate p, rather than "seq" because all that matters is that the arguments are evaluated. "seq" is very careful to preserve evaluation order, which we don't need to be here. You might think that we could simply give constructors some strictness info, like PrimOps, and let CoreToStg do the let-to-case transformation. But we don't do that because in the case of primops and functions strictness is a *property* not a *requirement*. In the case of constructors we need to do something active to evaluate the argument. Making an explicit case expression allows the simplifier to eliminate it in the (common) case where the constructor arg is already evaluated. Note [Wrappers for data instance tycons] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the case of data instances, the wrapper also applies the coercion turning the representation type into the family instance type to cast the result of the wrapper. For example, consider the declarations data family Map k :: * -> * data instance Map (a, b) v = MapPair (Map a (Pair b v)) The tycon to which the datacon MapPair belongs gets a unique internal name of the form :R123Map, and we call it the representation tycon. In contrast, Map is the family tycon (accessible via tyConFamInst_maybe). A coercion allows you to move between representation and family type. It is accessible from :R123Map via tyConFamilyCoercion_maybe and has kind Co123Map a b v :: {Map (a, b) v ~ :R123Map a b v} The wrapper and worker of MapPair get the types -- Wrapper $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v $WMapPair a b v = MapPair a b v `cast` sym (Co123Map a b v) -- Worker MapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v This coercion is conditionally applied by wrapFamInstBody. It's a bit more complicated if the data instance is a GADT as well! data instance T [a] where T1 :: forall b. b -> T [Maybe b] Hence we translate to -- Wrapper $WT1 :: forall b. b -> T [Maybe b] $WT1 b v = T1 (Maybe b) b (Maybe b) v `cast` sym (Co7T (Maybe b)) -- Worker T1 :: forall c b. (c ~ Maybe b) => b -> :R7T c -- Coercion from family type to representation type Co7T a :: T [a] ~ :R7T a Note [Newtype datacons] ~~~~~~~~~~~~~~~~~~~~~~~ The "data constructor" for a newtype should always be vanilla. At one point this wasn't true, because the newtype arising from class C a => D a looked like newtype T:D a = D:D (C a) so the data constructor for T:C had a single argument, namely the predicate (C a). But now we treat that as an ordinary argument, not part of the theta-type, so all is well. ************************************************************************ * * \subsection{Dictionary selectors} * * ************************************************************************ Selecting a field for a dictionary. If there is just one field, then there's nothing to do. Dictionary selectors may get nested forall-types. Thus: class Foo a where op :: forall b. Ord b => a -> b -> b Then the top-level type for op is op :: forall a. Foo a => forall b. Ord b => a -> b -> b This is unlike ordinary record selectors, which have all the for-alls at the outside. When dealing with classes it's very convenient to recover the original type signature from the class op selector. -} mkDictSelId :: Name -- Name of one of the *value* selectors -- (dictionary superclass or method) -> Class -> Id mkDictSelId name clas = mkGlobalId (ClassOpId clas) name sel_ty info where tycon = classTyCon clas sel_names = map idName (classAllSelIds clas) new_tycon = isNewTyCon tycon [data_con] = tyConDataCons tycon tyvars = dataConUnivTyVars data_con arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses val_index = assoc "MkId.mkDictSelId" (sel_names `zip` [0..]) name sel_ty = mkForAllTys tyvars (mkFunTy (mkClassPred clas (mkTyVarTys tyvars)) (getNth arg_tys val_index)) base_info = noCafIdInfo `setArityInfo` 1 `setStrictnessInfo` strict_sig info | new_tycon = base_info `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkInlineUnfolding (Just 1) (mkDictSelRhs clas val_index) -- See Note [Single-method classes] in TcInstDcls -- for why alwaysInlinePragma | otherwise = base_info `setSpecInfo` mkSpecInfo [rule] -- Add a magic BuiltinRule, but no unfolding -- so that the rule is always available to fire. -- See Note [ClassOp/DFun selection] in TcInstDcls n_ty_args = length tyvars -- This is the built-in rule that goes -- op (dfT d1 d2) ---> opT d1 d2 rule = BuiltinRule { ru_name = fsLit "Class op " `appendFS` occNameFS (getOccName name) , ru_fn = name , ru_nargs = n_ty_args + 1 , ru_try = dictSelRule val_index n_ty_args } -- The strictness signature is of the form U(AAAVAAAA) -> T -- where the V depends on which item we are selecting -- It's worth giving one, so that absence info etc is generated -- even if the selector isn't inlined strict_sig = mkClosedStrictSig [arg_dmd] topRes arg_dmd | new_tycon = evalDmd | otherwise = mkManyUsedDmd $ mkProdDmd [ if name == sel_name then evalDmd else absDmd | sel_name <- sel_names ] mkDictSelRhs :: Class -> Int -- 0-indexed selector among (superclasses ++ methods) -> CoreExpr mkDictSelRhs clas val_index = mkLams tyvars (Lam dict_id rhs_body) where tycon = classTyCon clas new_tycon = isNewTyCon tycon [data_con] = tyConDataCons tycon tyvars = dataConUnivTyVars data_con arg_tys = dataConRepArgTys data_con -- Includes the dictionary superclasses the_arg_id = getNth arg_ids val_index pred = mkClassPred clas (mkTyVarTys tyvars) dict_id = mkTemplateLocal 1 pred arg_ids = mkTemplateLocalsNum 2 arg_tys rhs_body | new_tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id) | otherwise = Case (Var dict_id) dict_id (idType the_arg_id) [(DataAlt data_con, arg_ids, varToCoreExpr the_arg_id)] -- varToCoreExpr needed for equality superclass selectors -- sel a b d = case x of { MkC _ (g:a~b) _ -> CO g } dictSelRule :: Int -> Arity -> RuleFun -- Tries to persuade the argument to look like a constructor -- application, using exprIsConApp_maybe, and then selects -- from it -- sel_i t1..tk (D t1..tk op1 ... opm) = opi -- dictSelRule val_index n_ty_args _ id_unf _ args | (dict_arg : _) <- drop n_ty_args args , Just (_, _, con_args) <- exprIsConApp_maybe id_unf dict_arg = Just (getNth con_args val_index) | otherwise = Nothing {- ************************************************************************ * * Data constructors * * ************************************************************************ -} mkDataConWorkId :: Name -> DataCon -> Id mkDataConWorkId wkr_name data_con | isNewTyCon tycon = mkGlobalId (DataConWrapId data_con) wkr_name nt_wrap_ty nt_work_info | otherwise = mkGlobalId (DataConWorkId data_con) wkr_name alg_wkr_ty wkr_info where tycon = dataConTyCon data_con ----------- Workers for data types -------------- alg_wkr_ty = dataConRepType data_con wkr_arity = dataConRepArity data_con wkr_info = noCafIdInfo `setArityInfo` wkr_arity `setStrictnessInfo` wkr_sig `setUnfoldingInfo` evaldUnfolding -- Record that it's evaluated, -- even if arity = 0 wkr_sig = mkClosedStrictSig (replicate wkr_arity topDmd) (dataConCPR data_con) -- Note [Data-con worker strictness] -- Notice that we do *not* say the worker is strict -- even if the data constructor is declared strict -- e.g. data T = MkT !(Int,Int) -- Why? Because the *wrapper* is strict (and its unfolding has case -- expresssions that do the evals) but the *worker* itself is not. -- If we pretend it is strict then when we see -- case x of y -> $wMkT y -- the simplifier thinks that y is "sure to be evaluated" (because -- $wMkT is strict) and drops the case. No, $wMkT is not strict. -- -- When the simplifer sees a pattern -- case e of MkT x -> ... -- it uses the dataConRepStrictness of MkT to mark x as evaluated; -- but that's fine... dataConRepStrictness comes from the data con -- not from the worker Id. ----------- Workers for newtypes -------------- (nt_tvs, _, nt_arg_tys, _) = dataConSig data_con res_ty_args = mkTyVarTys nt_tvs nt_wrap_ty = dataConUserType data_con nt_work_info = noCafIdInfo -- The NoCaf-ness is set by noCafIdInfo `setArityInfo` 1 -- Arity 1 `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` newtype_unf id_arg1 = mkTemplateLocal 1 (head nt_arg_tys) newtype_unf = ASSERT2( isVanillaDataCon data_con && isSingleton nt_arg_tys, ppr data_con ) -- Note [Newtype datacons] mkCompulsoryUnfolding $ mkLams nt_tvs $ Lam id_arg1 $ wrapNewTypeBody tycon res_ty_args (Var id_arg1) dataConCPR :: DataCon -> DmdResult dataConCPR con | isDataTyCon tycon -- Real data types only; that is, -- not unboxed tuples or newtypes , null (dataConExTyVars con) -- No existentials , wkr_arity > 0 , wkr_arity <= mAX_CPR_SIZE = if is_prod then vanillaCprProdRes (dataConRepArity con) else cprSumRes (dataConTag con) | otherwise = topRes where is_prod = isProductTyCon tycon tycon = dataConTyCon con wkr_arity = dataConRepArity con mAX_CPR_SIZE :: Arity mAX_CPR_SIZE = 10 -- We do not treat very big tuples as CPR-ish: -- a) for a start we get into trouble because there aren't -- "enough" unboxed tuple types (a tiresome restriction, -- but hard to fix), -- b) more importantly, big unboxed tuples get returned mainly -- on the stack, and are often then allocated in the heap -- by the caller. So doing CPR for them may in fact make -- things worse. {- ------------------------------------------------- -- Data constructor representation -- -- This is where we decide how to wrap/unwrap the -- constructor fields -- -------------------------------------------------- -} type Unboxer = Var -> UniqSM ([Var], CoreExpr -> CoreExpr) -- Unbox: bind rep vars by decomposing src var data Boxer = UnitBox | Boxer (TvSubst -> UniqSM ([Var], CoreExpr)) -- Box: build src arg using these rep vars newtype DataConBoxer = DCB ([Type] -> [Var] -> UniqSM ([Var], [CoreBind])) -- Bind these src-level vars, returning the -- rep-level vars to bind in the pattern mkDataConRep :: DynFlags -> FamInstEnvs -> Name -> DataCon -> UniqSM DataConRep mkDataConRep dflags fam_envs wrap_name data_con | not wrapper_reqd = return NoDataConRep | otherwise = do { wrap_args <- mapM newLocal wrap_arg_tys ; wrap_body <- mk_rep_app (wrap_args `zip` dropList eq_spec unboxers) initial_wrap_app ; let wrap_id = mkGlobalId (DataConWrapId data_con) wrap_name wrap_ty wrap_info wrap_info = noCafIdInfo `setArityInfo` wrap_arity -- It's important to specify the arity, so that partial -- applications are treated as values `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` wrap_unf `setStrictnessInfo` wrap_sig -- We need to get the CAF info right here because TidyPgm -- does not tidy the IdInfo of implicit bindings (like the wrapper) -- so it not make sure that the CAF info is sane wrap_sig = mkClosedStrictSig wrap_arg_dmds (dataConCPR data_con) wrap_arg_dmds = map mk_dmd (dropList eq_spec wrap_bangs) mk_dmd str | isBanged str = evalDmd | otherwise = topDmd -- The Cpr info can be important inside INLINE rhss, where the -- wrapper constructor isn't inlined. -- And the argument strictness can be important too; we -- may not inline a contructor when it is partially applied. -- For example: -- data W = C !Int !Int !Int -- ...(let w = C x in ...(w p q)...)... -- we want to see that w is strict in its two arguments wrap_unf = mkInlineUnfolding (Just wrap_arity) wrap_rhs wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs wrap_rhs = mkLams wrap_tvs $ mkLams wrap_args $ wrapFamInstBody tycon res_ty_args $ wrap_body ; return (DCR { dcr_wrap_id = wrap_id , dcr_boxer = mk_boxer boxers , dcr_arg_tys = rep_tys , dcr_stricts = rep_strs , dcr_bangs = dropList ev_tys wrap_bangs }) } where (univ_tvs, ex_tvs, eq_spec, theta, orig_arg_tys, _) = dataConFullSig data_con res_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs tycon = dataConTyCon data_con -- The representation TyCon (not family) wrap_ty = dataConUserType data_con ev_tys = eqSpecPreds eq_spec ++ theta all_arg_tys = ev_tys ++ orig_arg_tys orig_bangs = map mk_pred_strict_mark ev_tys ++ dataConSrcBangs data_con wrap_arg_tys = theta ++ orig_arg_tys wrap_arity = length wrap_arg_tys -- The wrap_args are the arguments *other than* the eq_spec -- Because we are going to apply the eq_spec args manually in the -- wrapper (wrap_bangs, rep_tys_w_strs, wrappers) = unzip3 (zipWith (dataConArgRep dflags fam_envs) all_arg_tys orig_bangs) (unboxers, boxers) = unzip wrappers (rep_tys, rep_strs) = unzip (concat rep_tys_w_strs) wrapper_reqd = not (isNewTyCon tycon) -- Newtypes have only a worker && (any isBanged orig_bangs -- Some forcing/unboxing -- (includes eq_spec) || isFamInstTyCon tycon) -- Cast result initial_wrap_app = Var (dataConWorkId data_con) `mkTyApps` res_ty_args `mkVarApps` ex_tvs `mkCoApps` map (mkReflCo Nominal . snd) eq_spec -- Dont box the eq_spec coercions since they are -- marked as HsUnpack by mk_dict_strict_mark mk_boxer :: [Boxer] -> DataConBoxer mk_boxer boxers = DCB (\ ty_args src_vars -> do { let ex_vars = takeList ex_tvs src_vars subst1 = mkTopTvSubst (univ_tvs `zip` ty_args) subst2 = extendTvSubstList subst1 ex_tvs (mkTyVarTys ex_vars) ; (rep_ids, binds) <- go subst2 boxers (dropList ex_tvs src_vars) ; return (ex_vars ++ rep_ids, binds) } ) go _ [] src_vars = ASSERT2( null src_vars, ppr data_con ) return ([], []) go subst (UnitBox : boxers) (src_var : src_vars) = do { (rep_ids2, binds) <- go subst boxers src_vars ; return (src_var : rep_ids2, binds) } go subst (Boxer boxer : boxers) (src_var : src_vars) = do { (rep_ids1, arg) <- boxer subst ; (rep_ids2, binds) <- go subst boxers src_vars ; return (rep_ids1 ++ rep_ids2, NonRec src_var arg : binds) } go _ (_:_) [] = pprPanic "mk_boxer" (ppr data_con) mk_rep_app :: [(Id,Unboxer)] -> CoreExpr -> UniqSM CoreExpr mk_rep_app [] con_app = return con_app mk_rep_app ((wrap_arg, unboxer) : prs) con_app = do { (rep_ids, unbox_fn) <- unboxer wrap_arg ; expr <- mk_rep_app prs (mkVarApps con_app rep_ids) ; return (unbox_fn expr) } ------------------------- newLocal :: Type -> UniqSM Var newLocal ty = do { uniq <- getUniqueM ; return (mkSysLocal (fsLit "dt") uniq ty) } ------------------------- dataConArgRep :: DynFlags -> FamInstEnvs -> Type -> HsSrcBang -- For DataCons defined in this module, this is the -- bang/unpack annotation that the programmer wrote -- For DataCons imported from an interface file, this -- is the HsImplBang implementation decision taken -- by the compiler in the defining module; just follow -- it slavishly, so that we make the same decision as -- in the defining module -> ( HsImplBang -- Implementation decision about unpack strategy , [(Type, StrictnessMark)] -- Rep types , (Unboxer, Boxer) ) dataConArgRep _ _ arg_ty HsNoBang = (HsNoBang, [(arg_ty, NotMarkedStrict)], (unitUnboxer, unitBoxer)) dataConArgRep _ _ arg_ty (HsSrcBang _ _ False) -- No '!' = (HsNoBang, [(arg_ty, NotMarkedStrict)], (unitUnboxer, unitBoxer)) dataConArgRep dflags fam_envs arg_ty (HsSrcBang _ unpk_prag True) -- {-# UNPACK #-} ! | not (gopt Opt_OmitInterfacePragmas dflags) -- Don't unpack if -fomit-iface-pragmas -- Don't unpack if we aren't optimising; rather arbitrarily, -- we use -fomit-iface-pragmas as the indication , let mb_co = topNormaliseType_maybe fam_envs arg_ty -- Unwrap type families and newtypes arg_ty' = case mb_co of { Just (_,ty) -> ty; Nothing -> arg_ty } , isUnpackableType fam_envs arg_ty' , (rep_tys, wrappers) <- dataConArgUnpack arg_ty' , case unpk_prag of Nothing -> gopt Opt_UnboxStrictFields dflags || (gopt Opt_UnboxSmallStrictFields dflags && length rep_tys <= 1) -- See Note [Unpack one-wide fields] Just unpack_me -> unpack_me = case mb_co of Nothing -> (HsUnpack Nothing, rep_tys, wrappers) Just (co,rep_ty) -> (HsUnpack (Just co), rep_tys, wrapCo co rep_ty wrappers) | otherwise -- Record the strict-but-no-unpack decision = strict_but_not_unpacked arg_ty dataConArgRep _ _ arg_ty HsStrict = strict_but_not_unpacked arg_ty dataConArgRep _ _ arg_ty (HsUnpack Nothing) | (rep_tys, wrappers) <- dataConArgUnpack arg_ty = (HsUnpack Nothing, rep_tys, wrappers) dataConArgRep _ _ _ (HsUnpack (Just co)) | let co_rep_ty = pSnd (coercionKind co) , (rep_tys, wrappers) <- dataConArgUnpack co_rep_ty = (HsUnpack (Just co), rep_tys, wrapCo co co_rep_ty wrappers) strict_but_not_unpacked :: Type -> (HsImplBang, [(Type,StrictnessMark)], (Unboxer, Boxer)) strict_but_not_unpacked arg_ty = (HsStrict, [(arg_ty, MarkedStrict)], (seqUnboxer, unitBoxer)) ------------------------- wrapCo :: Coercion -> Type -> (Unboxer, Boxer) -> (Unboxer, Boxer) wrapCo co rep_ty (unbox_rep, box_rep) -- co :: arg_ty ~ rep_ty = (unboxer, boxer) where unboxer arg_id = do { rep_id <- newLocal rep_ty ; (rep_ids, rep_fn) <- unbox_rep rep_id ; let co_bind = NonRec rep_id (Var arg_id `Cast` co) ; return (rep_ids, Let co_bind . rep_fn) } boxer = Boxer $ \ subst -> do { (rep_ids, rep_expr) <- case box_rep of UnitBox -> do { rep_id <- newLocal (TcType.substTy subst rep_ty) ; return ([rep_id], Var rep_id) } Boxer boxer -> boxer subst ; let sco = substCo (tvCvSubst subst) co ; return (rep_ids, rep_expr `Cast` mkSymCo sco) } ------------------------ seqUnboxer :: Unboxer seqUnboxer v = return ([v], \e -> Case (Var v) v (exprType e) [(DEFAULT, [], e)]) unitUnboxer :: Unboxer unitUnboxer v = return ([v], \e -> e) unitBoxer :: Boxer unitBoxer = UnitBox ------------------------- dataConArgUnpack :: Type -> ( [(Type, StrictnessMark)] -- Rep types , (Unboxer, Boxer) ) dataConArgUnpack arg_ty | Just (tc, tc_args) <- splitTyConApp_maybe arg_ty , Just con <- tyConSingleAlgDataCon_maybe tc -- NB: check for an *algebraic* data type -- A recursive newtype might mean that -- 'arg_ty' is a newtype , let rep_tys = dataConInstArgTys con tc_args = ASSERT( isVanillaDataCon con ) ( rep_tys `zip` dataConRepStrictness con ,( \ arg_id -> do { rep_ids <- mapM newLocal rep_tys ; let unbox_fn body = Case (Var arg_id) arg_id (exprType body) [(DataAlt con, rep_ids, body)] ; return (rep_ids, unbox_fn) } , Boxer $ \ subst -> do { rep_ids <- mapM (newLocal . TcType.substTy subst) rep_tys ; return (rep_ids, Var (dataConWorkId con) `mkTyApps` (substTys subst tc_args) `mkVarApps` rep_ids ) } ) ) | otherwise = pprPanic "dataConArgUnpack" (ppr arg_ty) -- An interface file specified Unpacked, but we couldn't unpack it isUnpackableType :: FamInstEnvs -> Type -> Bool -- True if we can unpack the UNPACK the argument type -- See Note [Recursive unboxing] -- We look "deeply" inside rather than relying on the DataCons -- we encounter on the way, because otherwise we might well -- end up relying on ourselves! isUnpackableType fam_envs ty | Just (tc, _) <- splitTyConApp_maybe ty , Just con <- tyConSingleAlgDataCon_maybe tc , isVanillaDataCon con = ok_con_args (unitNameSet (getName tc)) con | otherwise = False where ok_arg tcs (ty, bang) = not (attempt_unpack bang) || ok_ty tcs norm_ty where norm_ty = topNormaliseType fam_envs ty ok_ty tcs ty | Just (tc, _) <- splitTyConApp_maybe ty , let tc_name = getName tc = not (tc_name `elemNameSet` tcs) && case tyConSingleAlgDataCon_maybe tc of Just con | isVanillaDataCon con -> ok_con_args (tcs `extendNameSet` getName tc) con _ -> True | otherwise = True ok_con_args tcs con = all (ok_arg tcs) (dataConOrigArgTys con `zip` dataConSrcBangs con) -- NB: dataConSrcBangs gives the *user* request; -- We'd get a black hole if we used dataConImplBangs attempt_unpack (HsUnpack {}) = True attempt_unpack (HsSrcBang _ (Just unpk) bang) = bang && unpk attempt_unpack (HsSrcBang _ Nothing bang) = bang -- Be conservative attempt_unpack HsStrict = False attempt_unpack HsNoBang = False {- Note [Unpack one-wide fields] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The flag UnboxSmallStrictFields ensures that any field that can (safely) be unboxed to a word-sized unboxed field, should be so unboxed. For example: data A = A Int# newtype B = B A data C = C !B data D = D !C data E = E !() data F = F !D data G = G !F !F All of these should have an Int# as their representation, except G which should have two Int#s. However data T = T !(S Int) data S = S !a Here we can represent T with an Int#. Note [Recursive unboxing] ~~~~~~~~~~~~~~~~~~~~~~~~~ Consider data R = MkR {-# UNPACK #-} !S Int data S = MkS {-# UNPACK #-} !Int The representation arguments of MkR are the *representation* arguments of S (plus Int); the rep args of MkS are Int#. This is all fine. But be careful not to try to unbox this! data T = MkT {-# UNPACK #-} !T Int Because then we'd get an infinite number of arguments. Here is a more complicated case: data S = MkS {-# UNPACK #-} !T Int data T = MkT {-# UNPACK #-} !S Int Each of S and T must decide independendently whether to unpack and they had better not both say yes. So they must both say no. Also behave conservatively when there is no UNPACK pragma data T = MkS !T Int with -funbox-strict-fields or -funbox-small-strict-fields we need to behave as if there was an UNPACK pragma there. But it's the *argument* type that matters. This is fine: data S = MkS S !Int because Int is non-recursive. Note [Unpack equality predicates] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we have a GADT with a contructor C :: (a~[b]) => b -> T a we definitely want that equality predicate *unboxed* so that it takes no space at all. This is easily done: just give it an UNPACK pragma. The rest of the unpack/repack code does the heavy lifting. This one line makes every GADT take a word less space for each equality predicate, so it's pretty important! -} mk_pred_strict_mark :: PredType -> HsSrcBang mk_pred_strict_mark pred | isEqPred pred = HsUnpack Nothing -- Note [Unpack equality predicates] | otherwise = HsNoBang {- ************************************************************************ * * Wrapping and unwrapping newtypes and type families * * ************************************************************************ -} wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr -- The wrapper for the data constructor for a newtype looks like this: -- newtype T a = MkT (a,Int) -- MkT :: forall a. (a,Int) -> T a -- MkT = /\a. \(x:(a,Int)). x `cast` sym (CoT a) -- where CoT is the coercion TyCon assoicated with the newtype -- -- The call (wrapNewTypeBody T [a] e) returns the -- body of the wrapper, namely -- e `cast` (CoT [a]) -- -- If a coercion constructor is provided in the newtype, then we use -- it, otherwise the wrap/unwrap are both no-ops -- -- If the we are dealing with a newtype *instance*, we have a second coercion -- identifying the family instance with the constructor of the newtype -- instance. This coercion is applied in any case (ie, composed with the -- coercion constructor of the newtype or applied by itself). wrapNewTypeBody tycon args result_expr = ASSERT( isNewTyCon tycon ) wrapFamInstBody tycon args $ mkCast result_expr (mkSymCo co) where co = mkUnbranchedAxInstCo Representational (newTyConCo tycon) args -- When unwrapping, we do *not* apply any family coercion, because this will -- be done via a CoPat by the type checker. We have to do it this way as -- computing the right type arguments for the coercion requires more than just -- a spliting operation (cf, TcPat.tcConPat). unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr unwrapNewTypeBody tycon args result_expr = ASSERT( isNewTyCon tycon ) mkCast result_expr (mkUnbranchedAxInstCo Representational (newTyConCo tycon) args) -- If the type constructor is a representation type of a data instance, wrap -- the expression into a cast adjusting the expression type, which is an -- instance of the representation type, to the corresponding instance of the -- family instance type. -- See Note [Wrappers for data instance tycons] wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr wrapFamInstBody tycon args body | Just co_con <- tyConFamilyCoercion_maybe tycon = mkCast body (mkSymCo (mkUnbranchedAxInstCo Representational co_con args)) | otherwise = body -- Same as `wrapFamInstBody`, but for type family instances, which are -- represented by a `CoAxiom`, and not a `TyCon` wrapTypeFamInstBody :: CoAxiom br -> Int -> [Type] -> CoreExpr -> CoreExpr wrapTypeFamInstBody axiom ind args body = mkCast body (mkSymCo (mkAxInstCo Representational axiom ind args)) wrapTypeUnbranchedFamInstBody :: CoAxiom Unbranched -> [Type] -> CoreExpr -> CoreExpr wrapTypeUnbranchedFamInstBody axiom = wrapTypeFamInstBody axiom 0 unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr unwrapFamInstScrut tycon args scrut | Just co_con <- tyConFamilyCoercion_maybe tycon = mkCast scrut (mkUnbranchedAxInstCo Representational co_con args) -- data instances only | otherwise = scrut unwrapTypeFamInstScrut :: CoAxiom br -> Int -> [Type] -> CoreExpr -> CoreExpr unwrapTypeFamInstScrut axiom ind args scrut = mkCast scrut (mkAxInstCo Representational axiom ind args) unwrapTypeUnbranchedFamInstScrut :: CoAxiom Unbranched -> [Type] -> CoreExpr -> CoreExpr unwrapTypeUnbranchedFamInstScrut axiom = unwrapTypeFamInstScrut axiom 0 {- ************************************************************************ * * \subsection{Primitive operations} * * ************************************************************************ -} mkPrimOpId :: PrimOp -> Id mkPrimOpId prim_op = id where (tyvars,arg_tys,res_ty, arity, strict_sig) = primOpSig prim_op ty = mkForAllTys tyvars (mkFunTys arg_tys res_ty) name = mkWiredInName gHC_PRIM (primOpOcc prim_op) (mkPrimOpIdUnique (primOpTag prim_op)) (AnId id) UserSyntax id = mkGlobalId (PrimOpId prim_op) name ty info info = noCafIdInfo `setSpecInfo` mkSpecInfo (maybeToList $ primOpRules name prim_op) `setArityInfo` arity `setStrictnessInfo` strict_sig `setInlinePragInfo` neverInlinePragma -- We give PrimOps a NOINLINE pragma so that we don't -- get silly warnings from Desugar.dsRule (the inline_shadows_rule -- test) about a RULE conflicting with a possible inlining -- cf Trac #7287 -- For each ccall we manufacture a separate CCallOpId, giving it -- a fresh unique, a type that is correct for this particular ccall, -- and a CCall structure that gives the correct details about calling -- convention etc. -- -- The *name* of this Id is a local name whose OccName gives the full -- details of the ccall, type and all. This means that the interface -- file reader can reconstruct a suitable Id mkFCallId :: DynFlags -> Unique -> ForeignCall -> Type -> Id mkFCallId dflags uniq fcall ty = ASSERT( isEmptyVarSet (tyVarsOfType ty) ) -- A CCallOpId should have no free type variables; -- when doing substitutions won't substitute over it mkGlobalId (FCallId fcall) name ty info where occ_str = showSDoc dflags (braces (ppr fcall <+> ppr ty)) -- The "occurrence name" of a ccall is the full info about the -- ccall; it is encoded, but may have embedded spaces etc! name = mkFCallName uniq occ_str info = noCafIdInfo `setArityInfo` arity `setStrictnessInfo` strict_sig (_, tau) = tcSplitForAllTys ty (arg_tys, _) = tcSplitFunTys tau arity = length arg_tys strict_sig = mkClosedStrictSig (replicate arity evalDmd) topRes {- ************************************************************************ * * \subsection{DictFuns and default methods} * * ************************************************************************ Note [Dict funs and default methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Dict funs and default methods are *not* ImplicitIds. Their definition involves user-written code, so we can't figure out their strictness etc based on fixed info, as we can for constructors and record selectors (say). NB: See also Note [Exported LocalIds] in Id -} mkDictFunId :: Name -- Name to use for the dict fun; -> [TyVar] -> ThetaType -> Class -> [Type] -> Id -- Implements the DFun Superclass Invariant (see TcInstDcls) -- See Note [Dict funs and default methods] mkDictFunId dfun_name tvs theta clas tys = mkExportedLocalId (DFunId is_nt) dfun_name dfun_ty where is_nt = isNewTyCon (classTyCon clas) dfun_ty = mkDictFunTy tvs theta clas tys mkDictFunTy :: [TyVar] -> ThetaType -> Class -> [Type] -> Type mkDictFunTy tvs theta clas tys = mkSigmaTy tvs theta (mkClassPred clas tys) {- ************************************************************************ * * \subsection{Un-definable} * * ************************************************************************ These Ids can't be defined in Haskell. They could be defined in unfoldings in the wired-in GHC.Prim interface file, but we'd have to ensure that they were definitely, definitely inlined, because there is no curried identifier for them. That's what mkCompulsoryUnfolding does. If we had a way to get a compulsory unfolding from an interface file, we could do that, but we don't right now. unsafeCoerce# isn't so much a PrimOp as a phantom identifier, that just gets expanded into a type coercion wherever it occurs. Hence we add it as a built-in Id with an unfolding here. The type variables we use here are "open" type variables: this means they can unify with both unlifted and lifted types. Hence we provide another gun with which to shoot yourself in the foot. -} lazyIdName, unsafeCoerceName, nullAddrName, seqName, realWorldName, voidPrimIdName, coercionTokenName, magicDictName, coerceName, proxyName, dollarName, oneShotName :: Name unsafeCoerceName = mkWiredInIdName gHC_PRIM (fsLit "unsafeCoerce#") unsafeCoerceIdKey unsafeCoerceId nullAddrName = mkWiredInIdName gHC_PRIM (fsLit "nullAddr#") nullAddrIdKey nullAddrId seqName = mkWiredInIdName gHC_PRIM (fsLit "seq") seqIdKey seqId realWorldName = mkWiredInIdName gHC_PRIM (fsLit "realWorld#") realWorldPrimIdKey realWorldPrimId voidPrimIdName = mkWiredInIdName gHC_PRIM (fsLit "void#") voidPrimIdKey voidPrimId lazyIdName = mkWiredInIdName gHC_MAGIC (fsLit "lazy") lazyIdKey lazyId coercionTokenName = mkWiredInIdName gHC_PRIM (fsLit "coercionToken#") coercionTokenIdKey coercionTokenId magicDictName = mkWiredInIdName gHC_PRIM (fsLit "magicDict") magicDictKey magicDictId coerceName = mkWiredInIdName gHC_PRIM (fsLit "coerce") coerceKey coerceId proxyName = mkWiredInIdName gHC_PRIM (fsLit "proxy#") proxyHashKey proxyHashId dollarName = mkWiredInIdName gHC_BASE (fsLit "$") dollarIdKey dollarId oneShotName = mkWiredInIdName gHC_MAGIC (fsLit "oneShot") oneShotKey oneShotId dollarId :: Id -- Note [dollarId magic] dollarId = pcMiscPrelId dollarName ty (noCafIdInfo `setUnfoldingInfo` unf) where fun_ty = mkFunTy alphaTy openBetaTy ty = mkForAllTys [alphaTyVar, openBetaTyVar] $ mkFunTy fun_ty fun_ty unf = mkInlineUnfolding (Just 2) rhs [f,x] = mkTemplateLocals [fun_ty, alphaTy] rhs = mkLams [alphaTyVar, openBetaTyVar, f, x] $ App (Var f) (Var x) ------------------------------------------------ -- proxy# :: forall a. Proxy# a proxyHashId :: Id proxyHashId = pcMiscPrelId proxyName ty (noCafIdInfo `setUnfoldingInfo` evaldUnfolding) -- Note [evaldUnfoldings] where ty = mkForAllTys [kv, tv] (mkProxyPrimTy k t) kv = kKiVar k = mkTyVarTy kv tv:_ = tyVarList k t = mkTyVarTy tv ------------------------------------------------ -- unsafeCoerce# :: forall a b. a -> b unsafeCoerceId :: Id unsafeCoerceId = pcMiscPrelId unsafeCoerceName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs ty = mkForAllTys [openAlphaTyVar,openBetaTyVar] (mkFunTy openAlphaTy openBetaTy) [x] = mkTemplateLocals [openAlphaTy] rhs = mkLams [openAlphaTyVar,openBetaTyVar,x] $ Cast (Var x) (mkUnsafeCo openAlphaTy openBetaTy) ------------------------------------------------ nullAddrId :: Id -- nullAddr# :: Addr# -- The reason is is here is because we don't provide -- a way to write this literal in Haskell. nullAddrId = pcMiscPrelId nullAddrName addrPrimTy info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding (Lit nullAddrLit) ------------------------------------------------ seqId :: Id -- See Note [seqId magic] seqId = pcMiscPrelId seqName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs `setSpecInfo` mkSpecInfo [seq_cast_rule] ty = mkForAllTys [alphaTyVar,betaTyVar] (mkFunTy alphaTy (mkFunTy betaTy betaTy)) -- NB argBetaTyVar; see Note [seqId magic] [x,y] = mkTemplateLocals [alphaTy, betaTy] rhs = mkLams [alphaTyVar,betaTyVar,x,y] (Case (Var x) x betaTy [(DEFAULT, [], Var y)]) -- See Note [Built-in RULES for seq] seq_cast_rule = BuiltinRule { ru_name = fsLit "seq of cast" , ru_fn = seqName , ru_nargs = 4 , ru_try = match_seq_of_cast } match_seq_of_cast :: RuleFun -- See Note [Built-in RULES for seq] match_seq_of_cast _ _ _ [Type _, Type res_ty, Cast scrut co, expr] = Just (Var seqId `mkApps` [Type (pFst (coercionKind co)), Type res_ty, scrut, expr]) match_seq_of_cast _ _ _ _ = Nothing ------------------------------------------------ lazyId :: Id -- See Note [lazyId magic] lazyId = pcMiscPrelId lazyIdName ty info where info = noCafIdInfo ty = mkForAllTys [alphaTyVar] (mkFunTy alphaTy alphaTy) oneShotId :: Id -- See Note [The oneShot function] oneShotId = pcMiscPrelId oneShotName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs ty = mkForAllTys [alphaTyVar, betaTyVar] (mkFunTy fun_ty fun_ty) fun_ty = mkFunTy alphaTy betaTy [body, x] = mkTemplateLocals [fun_ty, alphaTy] x' = setOneShotLambda x rhs = mkLams [alphaTyVar, betaTyVar, body, x'] $ Var body `App` Var x -------------------------------------------------------------------------------- magicDictId :: Id -- See Note [magicDictId magic] magicDictId = pcMiscPrelId magicDictName ty info where info = noCafIdInfo `setInlinePragInfo` neverInlinePragma ty = mkForAllTys [alphaTyVar] alphaTy -------------------------------------------------------------------------------- coerceId :: Id coerceId = pcMiscPrelId coerceName ty info where info = noCafIdInfo `setInlinePragInfo` alwaysInlinePragma `setUnfoldingInfo` mkCompulsoryUnfolding rhs eqRTy = mkTyConApp coercibleTyCon [liftedTypeKind, alphaTy, betaTy] eqRPrimTy = mkTyConApp eqReprPrimTyCon [liftedTypeKind, alphaTy, betaTy] ty = mkForAllTys [alphaTyVar, betaTyVar] $ mkFunTys [eqRTy, alphaTy] betaTy [eqR,x,eq] = mkTemplateLocals [eqRTy, alphaTy, eqRPrimTy] rhs = mkLams [alphaTyVar, betaTyVar, eqR, x] $ mkWildCase (Var eqR) eqRTy betaTy $ [(DataAlt coercibleDataCon, [eq], Cast (Var x) (CoVarCo eq))] {- Note [dollarId magic] ~~~~~~~~~~~~~~~~~~~~~ The only reason that ($) is wired in is so that its type can be forall (a:*, b:Open). (a->b) -> a -> b That is, the return type can be unboxed. E.g. this is OK foo $ True where foo :: Bool -> Int# because ($) doesn't inspect or move the result of the call to foo. See Trac #8739. There is a special typing rule for ($) in TcExpr, so the type of ($) isn't looked at there, BUT Lint subsequently (and rightly) complains if sees ($) applied to Int# (say), unless we give it a wired-in type as we do here. Note [Unsafe coerce magic] ~~~~~~~~~~~~~~~~~~~~~~~~~~ We define a *primitive* GHC.Prim.unsafeCoerce# and then in the base library we define the ordinary function Unsafe.Coerce.unsafeCoerce :: forall (a:*) (b:*). a -> b unsafeCoerce x = unsafeCoerce# x Notice that unsafeCoerce has a civilized (albeit still dangerous) polymorphic type, whose type args have kind *. So you can't use it on unboxed values (unsafeCoerce 3#). In contrast unsafeCoerce# is even more dangerous because you *can* use it on unboxed things, (unsafeCoerce# 3#) :: Int. Its type is forall (a:OpenKind) (b:OpenKind). a -> b Note [seqId magic] ~~~~~~~~~~~~~~~~~~ 'GHC.Prim.seq' is special in several ways. a) Its second arg can have an unboxed type x `seq` (v +# w) Hence its second type variable has ArgKind b) Its fixity is set in LoadIface.ghcPrimIface c) It has quite a bit of desugaring magic. See DsUtils.hs Note [Desugaring seq (1)] and (2) and (3) d) There is some special rule handing: Note [User-defined RULES for seq] e) See Note [Typing rule for seq] in TcExpr. Note [User-defined RULES for seq] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Roman found situations where he had case (f n) of _ -> e where he knew that f (which was strict in n) would terminate if n did. Notice that the result of (f n) is discarded. So it makes sense to transform to case n of _ -> e Rather than attempt some general analysis to support this, I've added enough support that you can do this using a rewrite rule: RULE "f/seq" forall n. seq (f n) e = seq n e You write that rule. When GHC sees a case expression that discards its result, it mentally transforms it to a call to 'seq' and looks for a RULE. (This is done in Simplify.rebuildCase.) As usual, the correctness of the rule is up to you. To make this work, we need to be careful that the magical desugaring done in Note [seqId magic] item (c) is *not* done on the LHS of a rule. Or rather, we arrange to un-do it, in DsBinds.decomposeRuleLhs. Note [Built-in RULES for seq] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We also have the following built-in rule for seq seq (x `cast` co) y = seq x y This eliminates unnecessary casts and also allows other seq rules to match more often. Notably, seq (f x `cast` co) y --> seq (f x) y and now a user-defined rule for seq (see Note [User-defined RULES for seq]) may fire. Note [lazyId magic] ~~~~~~~~~~~~~~~~~~~ lazy :: forall a?. a? -> a? (i.e. works for unboxed types too) Used to lazify pseq: pseq a b = a `seq` lazy b Also, no strictness: by being a built-in Id, all the info about lazyId comes from here, not from GHC.Base.hi. This is important, because the strictness analyser will spot it as strict! Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep. It's very important to do this inlining *after* unfoldings are exposed in the interface file. Otherwise, the unfolding for (say) pseq in the interface file will not mention 'lazy', so if we inline 'pseq' we'll totally miss the very thing that 'lazy' was there for in the first place. See Trac #3259 for a real world example. lazyId is defined in GHC.Base, so we don't *have* to inline it. If it appears un-applied, we'll end up just calling it. Note [The oneShot function] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ In the context of making left-folds fuse somewhat okish (see ticket #7994 and Note [Left folds via right fold]) it was determined that it would be useful if library authors could explicitly tell the compiler that a certain lambda is called at most once. The oneShot function allows that. Like most magic functions it has a compulsary unfolding, so there is no need for a real definition somewhere. We have one in GHC.Magic for the convenience of putting the documentation there. It uses `setOneShotLambda` on the lambda's binder. That is the whole magic: A typical call looks like oneShot (\y. e) after unfolding the definition `oneShot = \f \x[oneshot]. f x` we get (\f \x[oneshot]. f x) (\y. e) --> \x[oneshot]. ((\y.e) x) --> \x[oneshot] e[x/y] which is what we want. It is only effective if the one-shot info survives as long as possible; in particular it must make it into the interface in unfoldings. See Note [Preserve OneShotInfo] in CoreTidy. Also see https://ghc.haskell.org/trac/ghc/wiki/OneShot. Note [magicDictId magic] ~~~~~~~~~~~~~~~~~~~~~~~~~ The identifier `magicDict` is just a place-holder, which is used to implement a primitve that we cannot define in Haskell but we can write in Core. It is declared with a place-holder type: magicDict :: forall a. a The intention is that the identifier will be used in a very specific way, to create dictionaries for classes with a single method. Consider a class like this: class C a where f :: T a We are going to use `magicDict`, in conjunction with a built-in Prelude rule, to cast values of type `T a` into dictionaries for `C a`. To do this, we define a function like this in the library: data WrapC a b = WrapC (C a => Proxy a -> b) withT :: (C a => Proxy a -> b) -> T a -> Proxy a -> b withT f x y = magicDict (WrapC f) x y The purpose of `WrapC` is to avoid having `f` instantiated. Also, it avoids impredicativity, because `magicDict`'s type cannot be instantiated with a forall. The field of `WrapC` contains a `Proxy` parameter which is used to link the type of the constraint, `C a`, with the type of the `Wrap` value being made. Next, we add a built-in Prelude rule (see prelude/PrelRules.hs), which will replace the RHS of this definition with the appropriate definition in Core. The rewrite rule works as follows: magicDict@t (wrap@a@b f) x y ----> f (x `cast` co a) y The `co` coercion is the newtype-coercion extracted from the type-class. The type class is obtain by looking at the type of wrap. ------------------------------------------------------------- @realWorld#@ used to be a magic literal, \tr{void#}. If things get nasty as-is, change it back to a literal (@Literal@). voidArgId is a Local Id used simply as an argument in functions where we just want an arg to avoid having a thunk of unlifted type. E.g. x = \ void :: Void# -> (# p, q #) This comes up in strictness analysis Note [evaldUnfoldings] ~~~~~~~~~~~~~~~~~~~~~~ The evaldUnfolding makes it look that some primitive value is evaluated, which in turn makes Simplify.interestingArg return True, which in turn makes INLINE things applied to said value likely to be inlined. -} realWorldPrimId :: Id -- :: State# RealWorld realWorldPrimId = pcMiscPrelId realWorldName realWorldStatePrimTy (noCafIdInfo `setUnfoldingInfo` evaldUnfolding -- Note [evaldUnfoldings] `setOneShotInfo` stateHackOneShot) voidPrimId :: Id -- Global constant :: Void# voidPrimId = pcMiscPrelId voidPrimIdName voidPrimTy (noCafIdInfo `setUnfoldingInfo` evaldUnfolding) -- Note [evaldUnfoldings] voidArgId :: Id -- Local lambda-bound :: Void# voidArgId = mkSysLocal (fsLit "void") voidArgIdKey voidPrimTy coercionTokenId :: Id -- :: () ~ () coercionTokenId -- Used to replace Coercion terms when we go to STG = pcMiscPrelId coercionTokenName (mkTyConApp eqPrimTyCon [liftedTypeKind, unitTy, unitTy]) noCafIdInfo pcMiscPrelId :: Name -> Type -> IdInfo -> Id pcMiscPrelId name ty info = mkVanillaGlobalWithInfo name ty info -- We lie and say the thing is imported; otherwise, we get into -- a mess with dependency analysis; e.g., core2stg may heave in -- random calls to GHCbase.unpackPS__. If GHCbase is the module -- being compiled, then it's just a matter of luck if the definition -- will be in "the right place" to be in scope.
christiaanb/ghc
compiler/basicTypes/MkId.hs
bsd-3-clause
54,371
0
21
14,929
7,040
3,839
3,201
549
6
{-# LANGUAGE CPP, ForeignFunctionInterface #-} #include "ghcconfig.h" ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow, 2004 -- -- runghc program, for invoking from a #! line in a script. For example: -- -- script.lhs: -- #!/usr/bin/env /usr/bin/runghc -- > main = putStrLn "hello!" -- -- runghc accepts one flag: -- -- -f <path> specify the path -- -- ----------------------------------------------------------------------------- module Main (main) where import Control.Exception import Data.Monoid import System.Directory import System.Environment import System.Exit import System.FilePath import System.IO import System.Process #if defined(mingw32_HOST_OS) import Foreign import Foreign.C.String #endif #if defined(mingw32_HOST_OS) # if defined(i386_HOST_ARCH) # define WINDOWS_CCONV stdcall # elif defined(x86_64_HOST_ARCH) # define WINDOWS_CCONV ccall # else # error Unknown mingw32 arch # endif #endif main :: IO () main = do args <- getArgs case parseRunGhcFlags args of (Help, _) -> printUsage (ShowVersion, _) -> printVersion (RunGhcFlags (Just ghc), args') -> uncurry (doIt ghc) $ getGhcArgs args' (RunGhcFlags Nothing, args') -> do mbPath <- getExecPath case mbPath of Nothing -> dieProg ("cannot find ghc") Just path -> let ghc = takeDirectory (normalise path) </> "ghc" in uncurry (doIt ghc) $ getGhcArgs args' data RunGhcFlags = RunGhcFlags (Maybe FilePath) -- GHC location | Help -- Print help text | ShowVersion -- Print version info instance Monoid RunGhcFlags where mempty = RunGhcFlags Nothing Help `mappend` _ = Help _ `mappend` Help = Help ShowVersion `mappend` _ = ShowVersion _ `mappend` ShowVersion = ShowVersion RunGhcFlags _ `mappend` right@(RunGhcFlags (Just _)) = right left@(RunGhcFlags _) `mappend` RunGhcFlags Nothing = left parseRunGhcFlags :: [String] -> (RunGhcFlags, [String]) parseRunGhcFlags = f mempty where f flags ("-f" : ghc : args) = f (flags `mappend` RunGhcFlags (Just ghc)) args f flags (('-' : 'f' : ghc) : args) = f (flags `mappend` RunGhcFlags (Just ghc)) args f flags ("--help" : args) = f (flags `mappend` Help) args f flags ("--version" : args) = f (flags `mappend` ShowVersion) args -- If you need the first GHC flag to be a -f flag then -- you can pass -- first f flags ("--" : args) = (flags, args) f flags args = (flags, args) printVersion :: IO () printVersion = do putStrLn ("runghc " ++ VERSION) printUsage :: IO () printUsage = do putStrLn "Usage: runghc [runghc flags] [GHC flags] module [program args]" putStrLn "" putStrLn "The runghc flags are" putStrLn " -f /path/to/ghc Tell runghc where GHC is" putStrLn " --help Print this usage information" putStrLn " --version Print version number" doIt :: String -- ^ path to GHC -> [String] -- ^ GHC args -> [String] -- ^ rest of the args -> IO () doIt ghc ghc_args rest = do case rest of [] -> do -- behave like typical perl, python, ruby interpreters: -- read from stdin tmpdir <- getTemporaryDirectory bracket (openTempFile tmpdir "runghcXXXX.hs") (\(filename,h) -> do hClose h; removeFile filename) $ \(filename,h) -> do getContents >>= hPutStr h hClose h doIt ghc ghc_args [filename] filename : prog_args -> do -- If the file exists, and is not a .lhs file, then we -- want to treat it as a .hs file. -- -- If the file doesn't exist then GHC is going to look for -- filename.hs and filename.lhs, and use the appropriate -- type. exists <- doesFileExist filename let xflag = if exists && (takeExtension filename /= ".lhs") then ["-x", "hs"] else [] c1 = ":set prog " ++ show filename c2 = ":main " ++ show prog_args res <- rawSystem ghc (["-ignore-dot-ghci"] ++ xflag ++ ghc_args ++ [ "-e", c1, "-e", c2, filename]) exitWith res getGhcArgs :: [String] -> ([String], [String]) getGhcArgs args = let (ghcArgs, otherArgs) = case break pastArgs args of (xs, "--":ys) -> (xs, ys) (xs, ys) -> (xs, ys) in (map unescape ghcArgs, otherArgs) where unescape ('-':'-':'g':'h':'c':'-':'a':'r':'g':'=':arg) = case arg of -- Bug #8601: allow --ghc-arg=--ghc-arg= as a prefix as well for backwards compatibility ('-':'-':'g':'h':'c':'-':'a':'r':'g':'=':arg') -> arg' _ -> arg unescape arg = arg pastArgs :: String -> Bool -- You can use -- to mark the end of the flags, in case you need to use -- a file called -foo.hs for some reason. You almost certainly shouldn't, -- though. pastArgs "--" = True pastArgs ('-':_) = False pastArgs _ = True dieProg :: String -> IO a dieProg msg = do p <- getProgName hPutStrLn stderr (p ++ ": " ++ msg) exitWith (ExitFailure 1) -- usage :: String -- usage = "syntax: runghc [-f GHC-PATH | --] [GHC-ARGS] [--] FILE ARG..." getExecPath :: IO (Maybe String) #if defined(mingw32_HOST_OS) getExecPath = try_size 2048 -- plenty, PATH_MAX is 512 under Win32. where try_size size = allocaArray (fromIntegral size) $ \buf -> do ret <- c_GetModuleFileName nullPtr buf size case ret of 0 -> return Nothing _ | ret < size -> fmap Just $ peekCWString buf | otherwise -> try_size (size * 2) foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW" c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32 #else getExecPath = return Nothing #endif
lukexi/ghc-7.8-arm64
utils/runghc/runghc.hs
bsd-3-clause
6,273
10
25
1,944
1,523
801
722
105
6
module System.Taffybar.DBus ( module System.Taffybar.DBus.Toggle , appendHook , startTaffyLogServer , withLogServer , withToggleServer ) where import Control.Monad.Trans.Class import Control.Monad.Trans.Reader import System.Log.DBus.Server import System.Taffybar.Context import System.Taffybar.DBus.Toggle startTaffyLogServer :: TaffyIO () startTaffyLogServer = asks sessionDBusClient >>= lift . startLogServer withLogServer :: TaffybarConfig -> TaffybarConfig withLogServer = appendHook startTaffyLogServer withToggleServer :: TaffybarConfig -> TaffybarConfig withToggleServer = handleDBusToggles
teleshoes/taffybar
src/System/Taffybar/DBus.hs
bsd-3-clause
616
0
7
72
120
74
46
18
1
module MediaWiki.API.Query.ImageInfo.Import where import MediaWiki.API.Types import MediaWiki.API.Utils import MediaWiki.API.Query.ImageInfo import Text.XML.Light.Types import Control.Monad import Data.Maybe stringXml :: String -> Either (String,[{-Error msg-}String]) ImageInfoResponse stringXml s = parseDoc xml s xml :: Element -> Maybe ImageInfoResponse xml e = do guard (elName e == nsName "api") let es1 = children e p <- pNode "query" es1 >>= (pNode "pages").children let es = children p ps <- fmap (mapMaybe xmlPage) (fmap children $ pNode "page" es) let cont = pNode "query-continue" es1 >>= xmlContinue "imageinfo" "iistart" return emptyImageInfoResponse{iiPages=ps,iiContinue=cont} xmlPage :: Element -> Maybe (PageTitle,[ImageInfo]) xmlPage e = do guard (elName e == nsName "page") let es = children e p <- pNode "imageinfo" es let es1 = children p cs <- fmap (mapMaybe (xmlII "ii")) (fmap children $ pNode "ii" es1) let ns = fromMaybe "0" $ pAttr "ns" p let tit = fromMaybe "" $ pAttr "title" p let mbpid = pAttr "pageid" p let miss = isJust (pAttr "missing" p) let rep = pAttr "imagerepository" p return (emptyPageTitle{pgNS=ns,pgTitle=tit,pgMbId=mbpid}, cs) xmlII :: String -> Element -> Maybe ImageInfo xmlII tg p = do guard (elName p == nsName tg) let ts = fromMaybe nullTimestamp (pAttr "timestamp" p) let us = fromMaybe nullUser (pAttr "user" p) let wi = pAttr "width" p >>= readI let he = pAttr "height" p >>= readI let si = pAttr "size" p >>= readI let ur = pAttr "url" p let co = pAttr "comment" p let sh = pAttr "sha1" p let ar = pAttr "archivename" p let bi = pAttr "bitdepth" p >>= readI let mi = pAttr "mime" p return emptyImageInfo { iiTimestamp = ts , iiUser = us , iiWidth = wi , iiHeight = he , iiSize = si , iiURL = ur , iiComment = co , iiSHA1 = sh , iiArchive = ar , iiBitDepth = bi , iiMime = mi } readI :: String -> Maybe Int readI s = case reads s of ((v,_):_) -> Just v _ -> Nothing
neobrain/neobot
mediawiki/MediaWiki/API/Query/ImageInfo/Import.hs
bsd-3-clause
2,128
0
12
541
850
419
431
62
2
{-# LANGUAGE TypeFamilies #-} module OverDirectThisModA (C, D) where import Data.Kind (Type) data family C a b :: Type type family D a b :: Type
sdiehl/ghc
testsuite/tests/indexed-types/should_fail/OverDirectThisModA.hs
bsd-3-clause
149
0
5
30
42
29
13
-1
-1
-- !!! Tests the various character classifications for a selection of Unicode -- characters. module Main where import Data.Char main = do putStrLn (" " ++ concat (map (++" ") strs)) mapM putStrLn (map do_char chars) where do_char char = s ++ (take (12-length s) (repeat ' ')) ++ concat (map f bs) where s = show char bs = map ($char) functions f True = "X " f False = " " strs = ["upper","lower","alpha","alnum","digit","print","space","cntrl"] functions = [isUpper,isLower,isAlpha,isAlphaNum,isDigit,isPrint,isSpace,isControl] chars = [backspace,tab,space,zero,lower_a,upper_a,delete, right_pointing_double_angle_quotation_mark, greek_capital_letter_alpha, bengali_digit_zero, en_space, gothic_letter_ahsa, monospaced_digit_zero ] backspace = '\x08' tab = '\t' space = ' ' zero = '0' lower_a = 'a' upper_a = 'A' delete = '\x7f' right_pointing_double_angle_quotation_mark = '\xBB' latin_small_letter_i_with_caron = '\x1D0' combining_acute_accent = '\x301' greek_capital_letter_alpha = '\x0391' bengali_digit_zero = '\x09E6' en_space = '\x2002' gothic_letter_ahsa = '\x10330' monospaced_digit_zero = '\x1D7F6'
ezyang/ghc
libraries/base/tests/unicode001.hs
bsd-3-clause
1,369
0
13
395
330
190
140
34
2
module T10618 where foo = Just $ Nothing <> Nothing
urbanslug/ghc
testsuite/tests/rename/should_fail/T10618.hs
bsd-3-clause
53
0
6
11
17
10
7
2
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : System.IO.Error -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Standard IO Errors. -- ----------------------------------------------------------------------------- module System.IO.Error ( -- * I\/O errors IOError, userError, mkIOError, annotateIOError, -- ** Classifying I\/O errors isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError, isFullError, isEOFError, isIllegalOperation, isPermissionError, isUserError, -- ** Attributes of I\/O errors ioeGetErrorType, ioeGetLocation, ioeGetErrorString, ioeGetHandle, ioeGetFileName, ioeSetErrorType, ioeSetErrorString, ioeSetLocation, ioeSetHandle, ioeSetFileName, -- * Types of I\/O error IOErrorType, -- abstract alreadyExistsErrorType, doesNotExistErrorType, alreadyInUseErrorType, fullErrorType, eofErrorType, illegalOperationErrorType, permissionErrorType, userErrorType, -- ** 'IOErrorType' predicates isAlreadyExistsErrorType, isDoesNotExistErrorType, isAlreadyInUseErrorType, isFullErrorType, isEOFErrorType, isIllegalOperationErrorType, isPermissionErrorType, isUserErrorType, -- * Throwing and catching I\/O errors ioError, catchIOError, tryIOError, modifyIOError, ) where import Control.Exception.Base import Data.Either import Data.Maybe import GHC.Base import GHC.IO import GHC.IO.Exception import GHC.IO.Handle.Types import Text.Show -- | The construct 'tryIOError' @comp@ exposes IO errors which occur within a -- computation, and which are not fully handled. -- -- Non-I\/O exceptions are not caught by this variant; to catch all -- exceptions, use 'Control.Exception.try' from "Control.Exception". -- -- @since 4.4.0.0 tryIOError :: IO a -> IO (Either IOError a) tryIOError f = catch (do r <- f return (Right r)) (return . Left) -- ----------------------------------------------------------------------------- -- Constructing an IOError -- | Construct an 'IOError' of the given type where the second argument -- describes the error location and the third and fourth argument -- contain the file handle and file path of the file involved in the -- error if applicable. mkIOError :: IOErrorType -> String -> Maybe Handle -> Maybe FilePath -> IOError mkIOError t location maybe_hdl maybe_filename = IOError{ ioe_type = t, ioe_location = location, ioe_description = "", ioe_errno = Nothing, ioe_handle = maybe_hdl, ioe_filename = maybe_filename } -- ----------------------------------------------------------------------------- -- IOErrorType -- | An error indicating that an 'IO' operation failed because -- one of its arguments already exists. isAlreadyExistsError :: IOError -> Bool isAlreadyExistsError = isAlreadyExistsErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- one of its arguments does not exist. isDoesNotExistError :: IOError -> Bool isDoesNotExistError = isDoesNotExistErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- one of its arguments is a single-use resource, which is already -- being used (for example, opening the same file twice for writing -- might give this error). isAlreadyInUseError :: IOError -> Bool isAlreadyInUseError = isAlreadyInUseErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- the device is full. isFullError :: IOError -> Bool isFullError = isFullErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- the end of file has been reached. isEOFError :: IOError -> Bool isEOFError = isEOFErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- the operation was not possible. -- Any computation which returns an 'IO' result may fail with -- 'isIllegalOperation'. In some cases, an implementation will not be -- able to distinguish between the possible error causes. In this case -- it should fail with 'isIllegalOperation'. isIllegalOperation :: IOError -> Bool isIllegalOperation = isIllegalOperationErrorType . ioeGetErrorType -- | An error indicating that an 'IO' operation failed because -- the user does not have sufficient operating system privilege -- to perform that operation. isPermissionError :: IOError -> Bool isPermissionError = isPermissionErrorType . ioeGetErrorType -- | A programmer-defined error value constructed using 'userError'. isUserError :: IOError -> Bool isUserError = isUserErrorType . ioeGetErrorType -- ----------------------------------------------------------------------------- -- IOErrorTypes -- | I\/O error where the operation failed because one of its arguments -- already exists. alreadyExistsErrorType :: IOErrorType alreadyExistsErrorType = AlreadyExists -- | I\/O error where the operation failed because one of its arguments -- does not exist. doesNotExistErrorType :: IOErrorType doesNotExistErrorType = NoSuchThing -- | I\/O error where the operation failed because one of its arguments -- is a single-use resource, which is already being used. alreadyInUseErrorType :: IOErrorType alreadyInUseErrorType = ResourceBusy -- | I\/O error where the operation failed because the device is full. fullErrorType :: IOErrorType fullErrorType = ResourceExhausted -- | I\/O error where the operation failed because the end of file has -- been reached. eofErrorType :: IOErrorType eofErrorType = EOF -- | I\/O error where the operation is not possible. illegalOperationErrorType :: IOErrorType illegalOperationErrorType = IllegalOperation -- | I\/O error where the operation failed because the user does not -- have sufficient operating system privilege to perform that operation. permissionErrorType :: IOErrorType permissionErrorType = PermissionDenied -- | I\/O error that is programmer-defined. userErrorType :: IOErrorType userErrorType = UserError -- ----------------------------------------------------------------------------- -- IOErrorType predicates -- | I\/O error where the operation failed because one of its arguments -- already exists. isAlreadyExistsErrorType :: IOErrorType -> Bool isAlreadyExistsErrorType AlreadyExists = True isAlreadyExistsErrorType _ = False -- | I\/O error where the operation failed because one of its arguments -- does not exist. isDoesNotExistErrorType :: IOErrorType -> Bool isDoesNotExistErrorType NoSuchThing = True isDoesNotExistErrorType _ = False -- | I\/O error where the operation failed because one of its arguments -- is a single-use resource, which is already being used. isAlreadyInUseErrorType :: IOErrorType -> Bool isAlreadyInUseErrorType ResourceBusy = True isAlreadyInUseErrorType _ = False -- | I\/O error where the operation failed because the device is full. isFullErrorType :: IOErrorType -> Bool isFullErrorType ResourceExhausted = True isFullErrorType _ = False -- | I\/O error where the operation failed because the end of file has -- been reached. isEOFErrorType :: IOErrorType -> Bool isEOFErrorType EOF = True isEOFErrorType _ = False -- | I\/O error where the operation is not possible. isIllegalOperationErrorType :: IOErrorType -> Bool isIllegalOperationErrorType IllegalOperation = True isIllegalOperationErrorType _ = False -- | I\/O error where the operation failed because the user does not -- have sufficient operating system privilege to perform that operation. isPermissionErrorType :: IOErrorType -> Bool isPermissionErrorType PermissionDenied = True isPermissionErrorType _ = False -- | I\/O error that is programmer-defined. isUserErrorType :: IOErrorType -> Bool isUserErrorType UserError = True isUserErrorType _ = False -- ----------------------------------------------------------------------------- -- Miscellaneous ioeGetErrorType :: IOError -> IOErrorType ioeGetErrorString :: IOError -> String ioeGetLocation :: IOError -> String ioeGetHandle :: IOError -> Maybe Handle ioeGetFileName :: IOError -> Maybe FilePath ioeGetErrorType ioe = ioe_type ioe ioeGetErrorString ioe | isUserErrorType (ioe_type ioe) = ioe_description ioe | otherwise = show (ioe_type ioe) ioeGetLocation ioe = ioe_location ioe ioeGetHandle ioe = ioe_handle ioe ioeGetFileName ioe = ioe_filename ioe ioeSetErrorType :: IOError -> IOErrorType -> IOError ioeSetErrorString :: IOError -> String -> IOError ioeSetLocation :: IOError -> String -> IOError ioeSetHandle :: IOError -> Handle -> IOError ioeSetFileName :: IOError -> FilePath -> IOError ioeSetErrorType ioe errtype = ioe{ ioe_type = errtype } ioeSetErrorString ioe str = ioe{ ioe_description = str } ioeSetLocation ioe str = ioe{ ioe_location = str } ioeSetHandle ioe hdl = ioe{ ioe_handle = Just hdl } ioeSetFileName ioe filename = ioe{ ioe_filename = Just filename } -- | Catch any 'IOError' that occurs in the computation and throw a -- modified version. modifyIOError :: (IOError -> IOError) -> IO a -> IO a modifyIOError f io = catch io (\e -> ioError (f e)) -- ----------------------------------------------------------------------------- -- annotating an IOError -- | Adds a location description and maybe a file path and file handle -- to an 'IOError'. If any of the file handle or file path is not given -- the corresponding value in the 'IOError' remains unaltered. annotateIOError :: IOError -> String -> Maybe Handle -> Maybe FilePath -> IOError annotateIOError ioe loc hdl path = ioe{ ioe_handle = hdl `mplus` ioe_handle ioe, ioe_location = loc, ioe_filename = path `mplus` ioe_filename ioe } -- | The 'catchIOError' function establishes a handler that receives any -- 'IOError' raised in the action protected by 'catchIOError'. -- An 'IOError' is caught by -- the most recent handler established by one of the exception handling -- functions. These handlers are -- not selective: all 'IOError's are caught. Exception propagation -- must be explicitly provided in a handler by re-raising any unwanted -- exceptions. For example, in -- -- > f = catchIOError g (\e -> if IO.isEOFError e then return [] else ioError e) -- -- the function @f@ returns @[]@ when an end-of-file exception -- (cf. 'System.IO.Error.isEOFError') occurs in @g@; otherwise, the -- exception is propagated to the next outer handler. -- -- When an exception propagates outside the main program, the Haskell -- system prints the associated 'IOError' value and exits the program. -- -- Non-I\/O exceptions are not caught by this variant; to catch all -- exceptions, use 'Control.Exception.catch' from "Control.Exception". -- -- @since 4.4.0.0 catchIOError :: IO a -> (IOError -> IO a) -> IO a catchIOError = catch
tolysz/prepare-ghcjs
spec-lts8/base/System/IO/Error.hs
bsd-3-clause
11,609
0
11
2,369
1,342
791
551
156
1
{-# LANGUAGE ForeignFunctionInterface #-} module Foo where foreign export ccall foo :: Int -> IO Int foo :: Int -> IO Int foo n = return (length (f n)) f :: Int -> [Int] f 0 = [] f n = n:(f (n-1))
urbanslug/ghc
testsuite/tests/ffi/should_run/ffi002.hs
bsd-3-clause
201
0
9
47
104
55
49
8
1
{-# LANGUAGE OverloadedStrings #-} module Text.Dot.Attributes ( module Text.Dot.Attributes -- * Arrows , module Text.Dot.Attributes.Arrows -- * Styles , module Text.Dot.Attributes.Styles ) where import Text.Dot.Attributes.Arrows import Text.Dot.Attributes.Styles import Text.Dot.Types.Internal -- * Attribute Names label :: AttributeName label = "label" compound :: AttributeName compound = "compound" shape :: AttributeName shape = "shape" color :: AttributeName color = "color" dir :: AttributeName dir = "dir" width :: AttributeName width = "width" height :: AttributeName height = "height" -- * Attribute values true :: AttributeValue true = "true" false :: AttributeValue false = "false" none :: AttributeValue none = "none"
NorfairKing/haphviz
src/Text/Dot/Attributes.hs
mit
799
0
5
166
158
103
55
28
1
-- | SDL2 OpenGL contexts for Caramia. -- -- This module provides functions to initialize SDL2 and use it to provide an -- OpenGL context to Caramia library. -- {-# LANGUAGE DeriveDataTypeable, OverloadedStrings #-} module Caramia.SDL2Context ( -- * Running contexts runSDL2Context , ContextCreation(..) , simpleContext -- * Capturing mouse , setMouseCapture -- * Swapping , swapBuffers -- * Exceptions , SDLError(..) , Sizing(..) ) where import Caramia.Context import Caramia.Internal.Error import Control.Exception import Control.Concurrent import Control.Monad import Foreign.Ptr import Foreign.C.String import Data.Typeable import Data.Bits import System.Environment import Graphics.UI.SDL import qualified Graphics.UI.SDL as SDL import qualified Data.Text as T (??) :: (a -> b -> c) -> (b -> a -> c) (??) = flip -- | Specifies the resolution and window/fullscreen mode. data Sizing = Fullscreen !Int !Int -- ^ Fullscreen with specific size. | FullscreenNativeRes -- ^ Fullscreen with native resolution. | Windowed !Int !Int -- ^ Windowed with specific size. deriving ( Eq, Ord, Show, Read, Typeable ) -- | Specifies some details on how you want your initialization to be. data ContextCreation = ContextCreation { sizing :: Sizing -- ^ Desired sizing of the application window. , allowResizing :: Bool -- ^ Allow resizing the window by user after context creation? Resizing can -- still be done afterwards. , title :: T.Text -- ^ Window title. Pick one that will strike fear into the hearts of your -- puny users. } deriving ( Eq, Ord, Show, Read, Typeable ) newtype SDLContextLocal = SDLContextLocal SDL.Window deriving ( Typeable ) -- | Simple, windowed context. Resolution is set to 800x600. simpleContext :: ContextCreation simpleContext = ContextCreation { sizing = Windowed 800 600 , allowResizing = False , title = "Caramia SDL2" } -- | Runs a Caramia context with OpenGL context created by the SDL2 library. -- -- This initializes the SDL2 library (SDL_Init()) and then quits it after -- action is done (SDL_Quit()). -- -- If something goes wrong, `SDLError` exception is thrown. runSDL2Context :: ContextCreation -> IO a -> IO a runSDL2Context creation action = mask $ \restore -> runInBoundThread $ do is_it_zero <- SDL.init initFlagEverything unless (is_it_zero == 0) $ throwSDLError finally ?? SDL.quit $ do -- Set the OpenGL attributes; we need them. _ <- glSetAttribute glAttrContextMajorVersion 3 _ <- glSetAttribute glAttrContextMinorVersion 2 _ <- glSetAttribute glAttrContextProfileMask glProfileCore maybe (return ()) (\_ -> void $ glSetAttribute glAttrContextFlags glContextFlagDebug) =<< lookupEnv "CARAMIA_OPENGL_DEBUG" window <- withCString (T.unpack (title creation)) $ \cstr -> createWindow cstr windowPosUndefined windowPosUndefined (fromIntegral w) (fromIntegral h) (windowFlagOpenGL .|. windowFlagShown .|. moreFlags) when (nullPtr == window) throwSDLError finally ?? SDL.destroyWindow window $ do context <- glCreateContext window when (nullPtr == context) throwSDLError finally ?? glDeleteContext context $ giveContext $ do storeContextLocalData (SDLContextLocal window) restore action where moreFlags = (case sizing creation of Fullscreen _ _ -> windowFlagFullscreen FullscreenNativeRes -> windowFlagFullscreenDesktop Windowed _ _ -> 0) .|. (if allowResizing creation then windowFlagResizable else 0) (w, h) = case sizing creation of Fullscreen w h -> (w, h) Windowed w h -> (w, h) FullscreenNativeRes -> (1, 1) -- | Swaps buffers in the current context. -- -- This also runs pending finalizers `Caramia.Context.runPendingFinalizers`. swapBuffers :: IO () swapBuffers = do _ <- currentContextID -- check that we are in a context runPendingFinalizers SDLContextLocal window <- retrieveContextLocalData (error "impossible") glSwapWindow window -- | Capture or release the mouse. setMouseCapture :: Bool -- ^ Set to true if you want to capture the mouse, -- false if you want to release it. -> IO () setMouseCapture do_grab = do _ <- currentContextID void $ setRelativeMouseMode do_grab
Noeda/caramia-sdl2
src/Caramia/SDL2Context.hs
mit
4,787
0
21
1,357
881
476
405
102
6
{-# LANGUAGE Arrows #-} {-# LANGUAGE ScopedTypeVariables #-} module SynthMain where import Prelude hiding (id, (.)) import Control.Arrow import FRP.Yampa import Graphics.Gloss import qualified Graphics.Gloss.Interface.IO.Game as G import Buttons import GlossInterface import Mealy (stateTrans) mainSF :: SF (Event G.Event) Picture mainSF = proc c -> do rec --the state of the mealy machine (one big rec) d' <- iPre 0 -< d p' <- iPre 0 -< p s' <- iPre 0 -< s v' <- iPre 0 -< v --c' -< iPre 0 <- c (click is in input stream) --the updates (one big arr) (p,v,s,d) <- arr stateTrans -< (p',v',c,s',d') returnA -< renderUI s p playGame :: IO () playGame = do playYampa (InWindow "Yampa Example" (320, 240) (800, 600)) white 30 mainSF
santolucito/Euterpea_Projects
QuantumArt/SynthMain.hs
mit
829
1
12
225
254
140
114
30
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} module Main where import Protolude import Pipes import Pipes.Concurrent import ServerInputParser import Console import RemoteConsole import Logger import Drifter import Event import CommandExecutor import Mapper import Person import Pipes.Safe import qualified Pipes.Concurrent as PC import System.IO import System.Directory import Control.Concurrent.Timer import Control.Concurrent.Suspend.Lifted import World main :: IO () main = runDrifter runDrifter :: IO () runDrifter = do currentDir <- getCurrentDirectory world <- liftIO $ loadWorld currentDir evtLog <- openFile "evt.log" WriteMode toConsoleBox <- spawn $ newest 100 toRemoteConsoleBox <- spawn $ newest 100 toServerInputLoggerBox <- spawn $ newest 100 toEvtLoggerBox <- spawn $ newest 100 toDrifterBox <- spawn $ newest 100 let commonOutput = (fst toConsoleBox) `mappend` (fst toRemoteConsoleBox) `mappend` (fst toServerInputLoggerBox) `mappend` (fst toEvtLoggerBox) readConsoleInput = runEffect $ runSafeP $ consoleInput `catchP` onUserInputException >-> toOutput (fst toDrifterBox) printConsoleOutput = runEffect $ (printWorldStats world >> fromInput (snd toConsoleBox)) >-> consoleOutput runDrifter = runEffect $ runSafeP $ fromInput (snd toDrifterBox) >-> drifter world >-> commandExecutor (fst toDrifterBox) >-> (toOutput commonOutput) emitPulseEvery = atomically $ PC.send (fst toDrifterBox) PulseEvent >> return () onUserInputException (SomeException e) = yield UserInputIOException {-onUserInputException (SomeException e) = liftIO $ do hFlush serverInputLog hClose serverInputLog hFlush evtLog hClose evtLog-} async $ runServerInputLogger (snd toServerInputLoggerBox) async $ runEvtLogger (snd toEvtLoggerBox) evtLog async $ printConsoleOutput async $ runDrifter async $ runRemoteConsole (fst toDrifterBox, snd toRemoteConsoleBox) repeatedTimer emitPulseEvery (sDelay 1) readConsoleInput
tort/mud-drifter
app/Main.hs
mit
2,485
0
16
787
519
264
255
46
1
{-# LANGUAGE OverloadedStrings #-} module Geometry.Point where import Data.Aeson ((.=), ToJSON, toJSON) import qualified Data.Aeson as J data Point a = P a a deriving (Eq, Ord) instance (Show a) => Show (Point a) where show (P x y) = "(P " ++ show x ++ " " ++ show y ++ ")" instance (ToJSON a) => ToJSON (Point a) where toJSON (P x y) = J.object ["x" .= x, "y" .= y] -- Rotate point 90° clockwise about the origin rotatePoint90c :: (Num a) => Point a -> Point a rotatePoint90c (P x y) = P y (-x) -- Rotate point 180° clockwise about the origin rotatePoint180c :: (Num a) => Point a -> Point a rotatePoint180c (P x y) = P (-x) (-y) -- Rotate point 270° clockwise about the origin rotatePoint270c :: (Num a) => Point a -> Point a rotatePoint270c (P x y) = P (-y) x -- Reflect point about the line x = -y reflectPointXMinusY :: (Num a) => Point a -> Point a reflectPointXMinusY (P x y) = P (-y) (-x) -- Reflect point about the x axis reflectPointXAxis :: (Num a) => Point a -> Point a reflectPointXAxis (P x y) = P x (-y)
mietek/map-cutter
src/Geometry/Point.hs
mit
1,060
0
10
241
440
232
208
25
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.HTMLKeygenElement (js_checkValidity, checkValidity, js_setCustomValidity, setCustomValidity, js_setAutofocus, setAutofocus, js_getAutofocus, getAutofocus, js_setChallenge, setChallenge, js_getChallenge, getChallenge, js_setDisabled, setDisabled, js_getDisabled, getDisabled, js_getForm, getForm, js_setKeytype, setKeytype, js_getKeytype, getKeytype, js_setName, setName, js_getName, getName, js_getType, getType, js_getWillValidate, getWillValidate, js_getValidity, getValidity, js_getValidationMessage, getValidationMessage, js_getLabels, getLabels, HTMLKeygenElement, castToHTMLKeygenElement, gTypeHTMLKeygenElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "($1[\"checkValidity\"]() ? 1 : 0)" js_checkValidity :: JSRef HTMLKeygenElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.checkValidity Mozilla HTMLKeygenElement.checkValidity documentation> checkValidity :: (MonadIO m) => HTMLKeygenElement -> m Bool checkValidity self = liftIO (js_checkValidity (unHTMLKeygenElement self)) foreign import javascript unsafe "$1[\"setCustomValidity\"]($2)" js_setCustomValidity :: JSRef HTMLKeygenElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.setCustomValidity Mozilla HTMLKeygenElement.setCustomValidity documentation> setCustomValidity :: (MonadIO m, ToJSString error) => HTMLKeygenElement -> Maybe error -> m () setCustomValidity self error = liftIO (js_setCustomValidity (unHTMLKeygenElement self) (toMaybeJSString error)) foreign import javascript unsafe "$1[\"autofocus\"] = $2;" js_setAutofocus :: JSRef HTMLKeygenElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.autofocus Mozilla HTMLKeygenElement.autofocus documentation> setAutofocus :: (MonadIO m) => HTMLKeygenElement -> Bool -> m () setAutofocus self val = liftIO (js_setAutofocus (unHTMLKeygenElement self) val) foreign import javascript unsafe "($1[\"autofocus\"] ? 1 : 0)" js_getAutofocus :: JSRef HTMLKeygenElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.autofocus Mozilla HTMLKeygenElement.autofocus documentation> getAutofocus :: (MonadIO m) => HTMLKeygenElement -> m Bool getAutofocus self = liftIO (js_getAutofocus (unHTMLKeygenElement self)) foreign import javascript unsafe "$1[\"challenge\"] = $2;" js_setChallenge :: JSRef HTMLKeygenElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.challenge Mozilla HTMLKeygenElement.challenge documentation> setChallenge :: (MonadIO m, ToJSString val) => HTMLKeygenElement -> val -> m () setChallenge self val = liftIO (js_setChallenge (unHTMLKeygenElement self) (toJSString val)) foreign import javascript unsafe "$1[\"challenge\"]" js_getChallenge :: JSRef HTMLKeygenElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.challenge Mozilla HTMLKeygenElement.challenge documentation> getChallenge :: (MonadIO m, FromJSString result) => HTMLKeygenElement -> m result getChallenge self = liftIO (fromJSString <$> (js_getChallenge (unHTMLKeygenElement self))) foreign import javascript unsafe "$1[\"disabled\"] = $2;" js_setDisabled :: JSRef HTMLKeygenElement -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.disabled Mozilla HTMLKeygenElement.disabled documentation> setDisabled :: (MonadIO m) => HTMLKeygenElement -> Bool -> m () setDisabled self val = liftIO (js_setDisabled (unHTMLKeygenElement self) val) foreign import javascript unsafe "($1[\"disabled\"] ? 1 : 0)" js_getDisabled :: JSRef HTMLKeygenElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.disabled Mozilla HTMLKeygenElement.disabled documentation> getDisabled :: (MonadIO m) => HTMLKeygenElement -> m Bool getDisabled self = liftIO (js_getDisabled (unHTMLKeygenElement self)) foreign import javascript unsafe "$1[\"form\"]" js_getForm :: JSRef HTMLKeygenElement -> IO (JSRef HTMLFormElement) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.form Mozilla HTMLKeygenElement.form documentation> getForm :: (MonadIO m) => HTMLKeygenElement -> m (Maybe HTMLFormElement) getForm self = liftIO ((js_getForm (unHTMLKeygenElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"keytype\"] = $2;" js_setKeytype :: JSRef HTMLKeygenElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.keytype Mozilla HTMLKeygenElement.keytype documentation> setKeytype :: (MonadIO m, ToJSString val) => HTMLKeygenElement -> val -> m () setKeytype self val = liftIO (js_setKeytype (unHTMLKeygenElement self) (toJSString val)) foreign import javascript unsafe "$1[\"keytype\"]" js_getKeytype :: JSRef HTMLKeygenElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.keytype Mozilla HTMLKeygenElement.keytype documentation> getKeytype :: (MonadIO m, FromJSString result) => HTMLKeygenElement -> m result getKeytype self = liftIO (fromJSString <$> (js_getKeytype (unHTMLKeygenElement self))) foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName :: JSRef HTMLKeygenElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.name Mozilla HTMLKeygenElement.name documentation> setName :: (MonadIO m, ToJSString val) => HTMLKeygenElement -> val -> m () setName self val = liftIO (js_setName (unHTMLKeygenElement self) (toJSString val)) foreign import javascript unsafe "$1[\"name\"]" js_getName :: JSRef HTMLKeygenElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.name Mozilla HTMLKeygenElement.name documentation> getName :: (MonadIO m, FromJSString result) => HTMLKeygenElement -> m result getName self = liftIO (fromJSString <$> (js_getName (unHTMLKeygenElement self))) foreign import javascript unsafe "$1[\"type\"]" js_getType :: JSRef HTMLKeygenElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.type Mozilla HTMLKeygenElement.type documentation> getType :: (MonadIO m, FromJSString result) => HTMLKeygenElement -> m result getType self = liftIO (fromJSString <$> (js_getType (unHTMLKeygenElement self))) foreign import javascript unsafe "($1[\"willValidate\"] ? 1 : 0)" js_getWillValidate :: JSRef HTMLKeygenElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.willValidate Mozilla HTMLKeygenElement.willValidate documentation> getWillValidate :: (MonadIO m) => HTMLKeygenElement -> m Bool getWillValidate self = liftIO (js_getWillValidate (unHTMLKeygenElement self)) foreign import javascript unsafe "$1[\"validity\"]" js_getValidity :: JSRef HTMLKeygenElement -> IO (JSRef ValidityState) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.validity Mozilla HTMLKeygenElement.validity documentation> getValidity :: (MonadIO m) => HTMLKeygenElement -> m (Maybe ValidityState) getValidity self = liftIO ((js_getValidity (unHTMLKeygenElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"validationMessage\"]" js_getValidationMessage :: JSRef HTMLKeygenElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.validationMessage Mozilla HTMLKeygenElement.validationMessage documentation> getValidationMessage :: (MonadIO m, FromJSString result) => HTMLKeygenElement -> m result getValidationMessage self = liftIO (fromJSString <$> (js_getValidationMessage (unHTMLKeygenElement self))) foreign import javascript unsafe "$1[\"labels\"]" js_getLabels :: JSRef HTMLKeygenElement -> IO (JSRef NodeList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLKeygenElement.labels Mozilla HTMLKeygenElement.labels documentation> getLabels :: (MonadIO m) => HTMLKeygenElement -> m (Maybe NodeList) getLabels self = liftIO ((js_getLabels (unHTMLKeygenElement self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/HTMLKeygenElement.hs
mit
9,391
120
11
1,402
1,909
1,033
876
139
1
module P04 where -- | Length of list -- >>> myLength [123, 456, 789] -- 3 -- >>> myLength "Hello, world!" -- 13 myLength :: [a] -> Int myLength [] = 0 myLength (_:xs) = 1 + myLength xs
briancavalier/h99
p04.hs
mit
186
0
7
40
53
31
22
4
1
import Data.Char (intToDigit) import Numeric (showIntAtBase) toBinary :: Int -> String toBinary x = showIntAtBase 2 intToDigit x "" doubleBasePalindromes :: Int -> Int doubleBasePalindromes limit = sum [ x | x <- [0..limit], let y = show x, let b = toBinary x, y == reverse y, b == reverse b] -- doubleBasePalindromes 1000000 == 872187
samidarko/euler
problem036.hs
mit
373
0
11
94
130
66
64
11
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} module TT.Example where import TT.Operator import TT.Judge import TT.Context import TT.Monad import Abt.Concrete.LocallyNameless import Abt.Class import Control.Monad hiding (void) import Control.Monad.Trans import Data.Monoid import Prelude hiding (pi) printTerm ∷ ( MonadIO m , MonadVar Var m ) ⇒ Tm0 Op → m () printTerm = toString >=> liftIO . print main ∷ IO () main = do runMT $ do printTerm =<< checkType mempty unit ax x ← fresh let f = lam (x \\ var x) g = lam (x \\ ax) ty = pi unit (x \\ unit) printTerm =<< checkType mempty (eq ty ty f g) (refl ty f) z ← fresh do let plus α β = sg bool $ x \\ if' (z \\ univ) (var x) (var α) (var β) inl m = pair tt m inr m = pair ff m α ← fresh β ← fresh m ← fresh let γ = mempty >: (α, univ) >: (β, univ) printTerm =<< isType γ (plus α β) printTerm =<< checkType (γ >: (m, var α)) (plus α β) (inl (var m)) printTerm =<< checkType (γ >: (m, var β)) (plus α β) (inr (var m))
jonsterling/tt-singletons
src/TT/Example.hs
mit
1,254
0
18
374
515
262
253
-1
-1
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Betfair.StreamingAPI.API.Context ( Context(..) , initializeContext ) where import Data.String.Conversions (cs) import Data.Time import GHC.Show import Network.Connection import Protolude hiding (show) import qualified Protolude import Betfair.APING (AppKey) import Betfair.StreamingAPI.API.Response import Betfair.StreamingAPI.Requests.MarketSubscriptionMessage import Betfair.StreamingAPI.API.StreamingState data Context = Context { cConnection :: Connection , cLogger :: Text -> IO () , cOnResponse :: ByteString -> Response -> Context -> IO (Maybe MarketSubscriptionMessage, Context) , cOnConnection :: Context -> IO (Context) , cState :: StreamingState } -- Should I pass through the ResponsException to the cOnResponse? initializeContext :: AppKey -> SessionToken -> UTCTime -> Context initializeContext a s t = Context { cConnection = undefined , cLogger = putStrLn , cOnResponse = \_ r c -> print r >> return (Nothing, c) , cOnConnection = return , cState = (defaultStreamingState t) {ssAppKey = a, ssSessionToken = s} } instance Show (Context) where show = cs . showContext showContext :: Context -> Text showContext c = "Context: " <> Protolude.show (cState c) -- <> ", " <> (cShowUserState c) (cUserState c)
joe9/streaming-betfair-api
src/Betfair/StreamingAPI/API/Context.hs
mit
1,472
0
14
297
336
200
136
35
1
{-# OPTIONS_GHC -fno-warn-unused-do-bind #-} -- | Sound support for the Spectrum 48k. -- Largely based on this post: https://chuntey.wordpress.com/2013/02/28/how-to-write-zx-spectrum-games-chapter-3/. -- | Most of the stuff in here uses (at least) the HL, BC, DE, and IX registers. If you are -- making use of any of these, save them to the stack before calling these routines! module ZXSpectrum.Sound ( Note (..) , note , pitchCode , play , playSeq , pitchBend ) where import Z80 import ZXSpectrum.Rom48 import Data.Word data Note = C_ | CS_ | D_ | DS_ | E_ | F_ | FS_ | G_ | GS_ | A_ | AS_ | B_ deriving (Eq, Show) raiseOctave :: Float -> Word8 -> Float raiseOctave freq octave = iterate (*2) freq !! fromIntegral octave note :: Note -- ^ The musical note we're interested in -> Word8 -- ^ The octave (in scientific pitch notation) -> Float -- ^ The frequency of that note at that octave note C_ oct = 16.352 `raiseOctave` oct note CS_ oct = 17.324 `raiseOctave` oct note D_ oct = 18.354 `raiseOctave` oct note DS_ oct = 19.445 `raiseOctave` oct note E_ oct = 20.602 `raiseOctave` oct note F_ oct = 21.827 `raiseOctave` oct note FS_ oct = 23.125 `raiseOctave` oct note G_ oct = 24.500 `raiseOctave` oct note GS_ oct = 25.957 `raiseOctave` oct note A_ oct = 27.500 `raiseOctave` oct note AS_ oct = 29.135 `raiseOctave` oct note B_ oct = 30.868 `raiseOctave` oct pitchCode :: Float -> Word16 pitchCode freq = round $ 437500 / freq - 30.125 play :: Float -- ^ Frequency -> Float -- ^ Duration -> Z80ASM play f duration = do ld HL $ pitchCode f ld DE . round $ f * duration call BEEPER playSeq :: [(Float, Float)] -- ^ (Frequency, Duration) -> Z80ASM playSeq = sequence_ . map (uncurry play) pitchBend :: Float -> Word8 -> Z80ASM pitchBend startingFreq iterations = do ld HL (pitchCode startingFreq) -- starting pitch. decLoopB iterations $ do push BC push HL -- store pitch. ld DE 1 -- very short duration. call BEEPER -- ROM beeper routine. pop HL -- restore pitch. dec HL -- pitch going up. pop BC
dpwright/zxspectrum
src/ZXSpectrum/Sound.hs
mit
2,173
0
10
537
571
311
260
54
1
module FreeTracker.Api.TH ( deriveJSONPrefixed )where import Data.Aeson.TH import Data.Char import Data.List.Split import Language.Haskell.TH.Syntax deriveJSONPrefixed :: Name -> Q [Dec] deriveJSONPrefixed name = deriveJSON (jsonOptions . length . last . splitOn "." . show $ name) name jsonOptions :: Int -- ^ Length of the field prefix -> Options jsonOptions pl = defaultOptions { fieldLabelModifier = jsonFieldLabelModifier pl, allNullaryToStringTag = True, omitNothingFields = True } jsonFieldLabelModifier :: Int -> String -> String jsonFieldLabelModifier pl ls = let (h:ts) = drop pl ls in toLower h : ts
sirius94/free-tracker
free-tracker-server/src/FreeTracker/Api/TH.hs
gpl-3.0
819
0
11
294
185
101
84
17
1
{-# LANGUAGE TemplateHaskell, FlexibleInstances #-} module Prolog.Quote (t,ts,c,pl) where import Import hiding(lift) import Language.Haskell.TH (listE, varE, viewP, mkName, Q, Exp, Pat) import Language.Haskell.TH.Syntax (Lift(lift)) import Language.Haskell.TH.Lift (deriveLiftMany) import Language.Haskell.TH.Quote (QuasiQuoter(..)) import Text.Parsec (parse, eof, ParsecT) import Data.Generics (extQ, typeOf, Data) import Prolog ( Term(..), VariableName, Clause(..), Goal , term, terms, clause, program, whitespace ) $(deriveLiftMany [''Term, ''VariableName, ''Clause]) instance Lift ([Term] -> [Goal]) where lift _ = fail "Clauses using Haskell functions can't be lifted." t,ts,c,pl :: QuasiQuoter t = prologQuasiQuoter term "term" ts = prologQuasiQuoter terms "term list" c = prologQuasiQuoter clause "clause" pl = prologQuasiQuoter program "program" prologQuasiQuoter parser name = QuasiQuoter { quoteExp = parsePrologExp parser name , quotePat = parsePrologPat parser name , quoteType = fail ("Prolog "++ name ++"s can't be Haskell types!") , quoteDec = fail ("Prolog "++ name ++"s can't be Haskell declarations!") } parsePrologExp :: (Data a, Lift a) => ParsecT [Char] () Identity a -> String -> String -> Q Exp parsePrologExp parser name str = do case parse (whitespace >> parser <* eof) ("(Prolog " ++ name ++ " expression)") str of Right x -> const (fail $ "Quasi-quoted expressions of type " ++ show (typeOf x) ++ " are not implemented.") `extQ` unquote -- Term `extQ` (listE . map unquote) -- [Term] `extQ` unquoteClause -- Clause `extQ` (listE . map unquoteClause) -- [Clause] $ x Left e -> fail (show e) where unquote (Struct "$" [Struct var []]) = [e| Struct (show $(varE (mkName var))) [] |] unquote (Struct "$" _) = fail "Found '$' with non-unquotable arguments" unquote (Struct a ts) = [e| Struct a $(listE $ map unquote ts) |] unquote t = lift t unquoteClause (Clause lhs rhs) = [e| Clause $(unquote lhs) $(listE $ map unquote rhs) |] unquoteClause (ClauseFn _ _) = fail "Clauses using Haskell functions are not quasi-quotable." parsePrologPat :: (Data a, Lift a) => ParsecT [Char] () Identity a -> String -> String -> Q Pat parsePrologPat parser name str = do case parse (whitespace >> parser <* eof) ("(Prolog " ++ name ++ " pattern)") str of Right x -> viewP [e| (== $(lift x)) |] [p| True |]
nishiuramakoto/logiku
prolog/Prolog/Quote.hs
gpl-3.0
2,622
0
21
667
800
449
351
47
6
{-# LANGUAGE OverloadedStrings #-} import SecondTransfer( CoherentWorker , DataAndConclusion , tlsServeWithALPN , http2Attendant , enableConsoleLogging ) import SecondTransfer.Http2( makeSessionsContext , defaultSessionsConfig ) import Data.Conduit import Data.ByteString.Char8 (pack) -- import Data.IORef -- import Control.Applicative import Control.Concurrent.MVar import Control.Monad.IO.Class (liftIO) saysHello :: Int -> MVar ComPoint -> Int -> DataAndConclusion saysHello who_speaks commpoint repeats = if repeats > 0 then do -- The following if puts the two streams in a lock-step. -- That's probably not much of an ordeal, given that there -- are independent control threads pulling data, but anyways... if (who_speaks `rem` 3) /= 0 then do liftIO $ takeMVar commpoint return () else liftIO $ putMVar commpoint ComPoint yield . pack . ( (++) "\nlong line and block with ordinal number ") . show $ who_speaks saysHello who_speaks commpoint (repeats-1) else return [] data ComPoint = ComPoint interlockedWorker :: MVar Int -> MVar ComPoint -> CoherentWorker interlockedWorker counters mvar _ = do my_num <- takeMVar counters putMVar counters (my_num+1) return ( [ (":status", "200"), ("server", "lock_step_transfer") ], [], -- No pushed streams saysHello my_num mvar 100 ) -- For this program to work, it should be run from the top of -- the developement directory. main :: IO () main = do enableConsoleLogging sessions_context <- makeSessionsContext defaultSessionsConfig counters <- newMVar 0 can_talk <- newEmptyMVar let http2_attendant = http2Attendant sessions_context $ interlockedWorker counters can_talk tlsServeWithALPN "cert.pem" -- Server certificate "privkey.pem" -- Certificate private key "127.0.0.1" -- On which interface to bind [ ("h2-14", http2_attendant), -- Protocols present in the ALPN negotiation ("h2", http2_attendant) -- they may be slightly different, but for this -- test it doesn't matter. ] 8443
alcidesv/lock_step_transfer
hs-src/Main.hs
gpl-3.0
2,434
2
12
772
433
232
201
54
3
import Control.Monad import Data.Char main = do colors <- forM [1..5] (\a -> do putStrLn $ show a ++ "?" color <- getLine return color) mapM_ putStrLn colors
prannayk/conj
Learning/control_monad.hs
gpl-3.0
175
0
15
45
76
36
40
8
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Classroom.Courses.Students.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Returns a student of a course. This method returns the following error -- codes: * \`PERMISSION_DENIED\` if the requesting user is not permitted -- to view students of this course or for access errors. * \`NOT_FOUND\` if -- no student of this course has the requested ID or if the course does not -- exist. -- -- /See:/ <https://developers.google.com/classroom/ Google Classroom API Reference> for @classroom.courses.students.get@. module Network.Google.Resource.Classroom.Courses.Students.Get ( -- * REST Resource CoursesStudentsGetResource -- * Creating a Request , coursesStudentsGet , CoursesStudentsGet -- * Request Lenses , csgXgafv , csgUploadProtocol , csgCourseId , csgAccessToken , csgUploadType , csgUserId , csgCallback ) where import Network.Google.Classroom.Types import Network.Google.Prelude -- | A resource alias for @classroom.courses.students.get@ method which the -- 'CoursesStudentsGet' request conforms to. type CoursesStudentsGetResource = "v1" :> "courses" :> Capture "courseId" Text :> "students" :> Capture "userId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Student -- | Returns a student of a course. This method returns the following error -- codes: * \`PERMISSION_DENIED\` if the requesting user is not permitted -- to view students of this course or for access errors. * \`NOT_FOUND\` if -- no student of this course has the requested ID or if the course does not -- exist. -- -- /See:/ 'coursesStudentsGet' smart constructor. data CoursesStudentsGet = CoursesStudentsGet' { _csgXgafv :: !(Maybe Xgafv) , _csgUploadProtocol :: !(Maybe Text) , _csgCourseId :: !Text , _csgAccessToken :: !(Maybe Text) , _csgUploadType :: !(Maybe Text) , _csgUserId :: !Text , _csgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CoursesStudentsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'csgXgafv' -- -- * 'csgUploadProtocol' -- -- * 'csgCourseId' -- -- * 'csgAccessToken' -- -- * 'csgUploadType' -- -- * 'csgUserId' -- -- * 'csgCallback' coursesStudentsGet :: Text -- ^ 'csgCourseId' -> Text -- ^ 'csgUserId' -> CoursesStudentsGet coursesStudentsGet pCsgCourseId_ pCsgUserId_ = CoursesStudentsGet' { _csgXgafv = Nothing , _csgUploadProtocol = Nothing , _csgCourseId = pCsgCourseId_ , _csgAccessToken = Nothing , _csgUploadType = Nothing , _csgUserId = pCsgUserId_ , _csgCallback = Nothing } -- | V1 error format. csgXgafv :: Lens' CoursesStudentsGet (Maybe Xgafv) csgXgafv = lens _csgXgafv (\ s a -> s{_csgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). csgUploadProtocol :: Lens' CoursesStudentsGet (Maybe Text) csgUploadProtocol = lens _csgUploadProtocol (\ s a -> s{_csgUploadProtocol = a}) -- | Identifier of the course. This identifier can be either the -- Classroom-assigned identifier or an alias. csgCourseId :: Lens' CoursesStudentsGet Text csgCourseId = lens _csgCourseId (\ s a -> s{_csgCourseId = a}) -- | OAuth access token. csgAccessToken :: Lens' CoursesStudentsGet (Maybe Text) csgAccessToken = lens _csgAccessToken (\ s a -> s{_csgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). csgUploadType :: Lens' CoursesStudentsGet (Maybe Text) csgUploadType = lens _csgUploadType (\ s a -> s{_csgUploadType = a}) -- | Identifier of the student to return. The identifier can be one of the -- following: * the numeric identifier for the user * the email address of -- the user * the string literal \`\"me\"\`, indicating the requesting user csgUserId :: Lens' CoursesStudentsGet Text csgUserId = lens _csgUserId (\ s a -> s{_csgUserId = a}) -- | JSONP csgCallback :: Lens' CoursesStudentsGet (Maybe Text) csgCallback = lens _csgCallback (\ s a -> s{_csgCallback = a}) instance GoogleRequest CoursesStudentsGet where type Rs CoursesStudentsGet = Student type Scopes CoursesStudentsGet = '["https://www.googleapis.com/auth/classroom.profile.emails", "https://www.googleapis.com/auth/classroom.profile.photos", "https://www.googleapis.com/auth/classroom.rosters", "https://www.googleapis.com/auth/classroom.rosters.readonly"] requestClient CoursesStudentsGet'{..} = go _csgCourseId _csgUserId _csgXgafv _csgUploadProtocol _csgAccessToken _csgUploadType _csgCallback (Just AltJSON) classroomService where go = buildClient (Proxy :: Proxy CoursesStudentsGetResource) mempty
brendanhay/gogol
gogol-classroom/gen/Network/Google/Resource/Classroom/Courses/Students/Get.hs
mpl-2.0
5,949
0
18
1,370
798
470
328
117
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.RegionURLMaps.Validate -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Runs static validation for the UrlMap. In particular, the tests of the -- provided UrlMap will be run. Calling this method does NOT create the -- UrlMap. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.regionUrlMaps.validate@. module Network.Google.Resource.Compute.RegionURLMaps.Validate ( -- * REST Resource RegionURLMapsValidateResource -- * Creating a Request , regionURLMapsValidate , RegionURLMapsValidate -- * Request Lenses , rumvURLMap , rumvProject , rumvPayload , rumvRegion ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.regionUrlMaps.validate@ method which the -- 'RegionURLMapsValidate' request conforms to. type RegionURLMapsValidateResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "regions" :> Capture "region" Text :> "urlMaps" :> Capture "urlMap" Text :> "validate" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] RegionURLMapsValidateRequest :> Post '[JSON] URLMapsValidateResponse -- | Runs static validation for the UrlMap. In particular, the tests of the -- provided UrlMap will be run. Calling this method does NOT create the -- UrlMap. -- -- /See:/ 'regionURLMapsValidate' smart constructor. data RegionURLMapsValidate = RegionURLMapsValidate' { _rumvURLMap :: !Text , _rumvProject :: !Text , _rumvPayload :: !RegionURLMapsValidateRequest , _rumvRegion :: !Text } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'RegionURLMapsValidate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rumvURLMap' -- -- * 'rumvProject' -- -- * 'rumvPayload' -- -- * 'rumvRegion' regionURLMapsValidate :: Text -- ^ 'rumvURLMap' -> Text -- ^ 'rumvProject' -> RegionURLMapsValidateRequest -- ^ 'rumvPayload' -> Text -- ^ 'rumvRegion' -> RegionURLMapsValidate regionURLMapsValidate pRumvURLMap_ pRumvProject_ pRumvPayload_ pRumvRegion_ = RegionURLMapsValidate' { _rumvURLMap = pRumvURLMap_ , _rumvProject = pRumvProject_ , _rumvPayload = pRumvPayload_ , _rumvRegion = pRumvRegion_ } -- | Name of the UrlMap resource to be validated as. rumvURLMap :: Lens' RegionURLMapsValidate Text rumvURLMap = lens _rumvURLMap (\ s a -> s{_rumvURLMap = a}) -- | Project ID for this request. rumvProject :: Lens' RegionURLMapsValidate Text rumvProject = lens _rumvProject (\ s a -> s{_rumvProject = a}) -- | Multipart request metadata. rumvPayload :: Lens' RegionURLMapsValidate RegionURLMapsValidateRequest rumvPayload = lens _rumvPayload (\ s a -> s{_rumvPayload = a}) -- | Name of the region scoping this request. rumvRegion :: Lens' RegionURLMapsValidate Text rumvRegion = lens _rumvRegion (\ s a -> s{_rumvRegion = a}) instance GoogleRequest RegionURLMapsValidate where type Rs RegionURLMapsValidate = URLMapsValidateResponse type Scopes RegionURLMapsValidate = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient RegionURLMapsValidate'{..} = go _rumvProject _rumvRegion _rumvURLMap (Just AltJSON) _rumvPayload computeService where go = buildClient (Proxy :: Proxy RegionURLMapsValidateResource) mempty
brendanhay/gogol
gogol-compute/gen/Network/Google/Resource/Compute/RegionURLMaps/Validate.hs
mpl-2.0
4,510
0
18
1,071
551
328
223
90
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AppEngine.Apps.Services.Versions.Instances.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Lists the instances of a version.Tip: To aggregate details about -- instances over time, see the Stackdriver Monitoring API -- (https:\/\/cloud.google.com\/monitoring\/api\/ref_v3\/rest\/v3\/projects.timeSeries\/list). -- -- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ App Engine Admin API Reference> for @appengine.apps.services.versions.instances.list@. module Network.Google.Resource.AppEngine.Apps.Services.Versions.Instances.List ( -- * REST Resource AppsServicesVersionsInstancesListResource -- * Creating a Request , appsServicesVersionsInstancesList , AppsServicesVersionsInstancesList -- * Request Lenses , asvilXgafv , asvilUploadProtocol , asvilAccessToken , asvilUploadType , asvilVersionsId , asvilAppsId , asvilPageToken , asvilServicesId , asvilPageSize , asvilCallback ) where import Network.Google.AppEngine.Types import Network.Google.Prelude -- | A resource alias for @appengine.apps.services.versions.instances.list@ method which the -- 'AppsServicesVersionsInstancesList' request conforms to. type AppsServicesVersionsInstancesListResource = "v1" :> "apps" :> Capture "appsId" Text :> "services" :> Capture "servicesId" Text :> "versions" :> Capture "versionsId" Text :> "instances" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "pageToken" Text :> QueryParam "pageSize" (Textual Int32) :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] ListInstancesResponse -- | Lists the instances of a version.Tip: To aggregate details about -- instances over time, see the Stackdriver Monitoring API -- (https:\/\/cloud.google.com\/monitoring\/api\/ref_v3\/rest\/v3\/projects.timeSeries\/list). -- -- /See:/ 'appsServicesVersionsInstancesList' smart constructor. data AppsServicesVersionsInstancesList = AppsServicesVersionsInstancesList' { _asvilXgafv :: !(Maybe Xgafv) , _asvilUploadProtocol :: !(Maybe Text) , _asvilAccessToken :: !(Maybe Text) , _asvilUploadType :: !(Maybe Text) , _asvilVersionsId :: !Text , _asvilAppsId :: !Text , _asvilPageToken :: !(Maybe Text) , _asvilServicesId :: !Text , _asvilPageSize :: !(Maybe (Textual Int32)) , _asvilCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AppsServicesVersionsInstancesList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asvilXgafv' -- -- * 'asvilUploadProtocol' -- -- * 'asvilAccessToken' -- -- * 'asvilUploadType' -- -- * 'asvilVersionsId' -- -- * 'asvilAppsId' -- -- * 'asvilPageToken' -- -- * 'asvilServicesId' -- -- * 'asvilPageSize' -- -- * 'asvilCallback' appsServicesVersionsInstancesList :: Text -- ^ 'asvilVersionsId' -> Text -- ^ 'asvilAppsId' -> Text -- ^ 'asvilServicesId' -> AppsServicesVersionsInstancesList appsServicesVersionsInstancesList pAsvilVersionsId_ pAsvilAppsId_ pAsvilServicesId_ = AppsServicesVersionsInstancesList' { _asvilXgafv = Nothing , _asvilUploadProtocol = Nothing , _asvilAccessToken = Nothing , _asvilUploadType = Nothing , _asvilVersionsId = pAsvilVersionsId_ , _asvilAppsId = pAsvilAppsId_ , _asvilPageToken = Nothing , _asvilServicesId = pAsvilServicesId_ , _asvilPageSize = Nothing , _asvilCallback = Nothing } -- | V1 error format. asvilXgafv :: Lens' AppsServicesVersionsInstancesList (Maybe Xgafv) asvilXgafv = lens _asvilXgafv (\ s a -> s{_asvilXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). asvilUploadProtocol :: Lens' AppsServicesVersionsInstancesList (Maybe Text) asvilUploadProtocol = lens _asvilUploadProtocol (\ s a -> s{_asvilUploadProtocol = a}) -- | OAuth access token. asvilAccessToken :: Lens' AppsServicesVersionsInstancesList (Maybe Text) asvilAccessToken = lens _asvilAccessToken (\ s a -> s{_asvilAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). asvilUploadType :: Lens' AppsServicesVersionsInstancesList (Maybe Text) asvilUploadType = lens _asvilUploadType (\ s a -> s{_asvilUploadType = a}) -- | Part of \`parent\`. See documentation of \`appsId\`. asvilVersionsId :: Lens' AppsServicesVersionsInstancesList Text asvilVersionsId = lens _asvilVersionsId (\ s a -> s{_asvilVersionsId = a}) -- | Part of \`parent\`. Name of the parent Version resource. Example: -- apps\/myapp\/services\/default\/versions\/v1. asvilAppsId :: Lens' AppsServicesVersionsInstancesList Text asvilAppsId = lens _asvilAppsId (\ s a -> s{_asvilAppsId = a}) -- | Continuation token for fetching the next page of results. asvilPageToken :: Lens' AppsServicesVersionsInstancesList (Maybe Text) asvilPageToken = lens _asvilPageToken (\ s a -> s{_asvilPageToken = a}) -- | Part of \`parent\`. See documentation of \`appsId\`. asvilServicesId :: Lens' AppsServicesVersionsInstancesList Text asvilServicesId = lens _asvilServicesId (\ s a -> s{_asvilServicesId = a}) -- | Maximum results to return per page. asvilPageSize :: Lens' AppsServicesVersionsInstancesList (Maybe Int32) asvilPageSize = lens _asvilPageSize (\ s a -> s{_asvilPageSize = a}) . mapping _Coerce -- | JSONP asvilCallback :: Lens' AppsServicesVersionsInstancesList (Maybe Text) asvilCallback = lens _asvilCallback (\ s a -> s{_asvilCallback = a}) instance GoogleRequest AppsServicesVersionsInstancesList where type Rs AppsServicesVersionsInstancesList = ListInstancesResponse type Scopes AppsServicesVersionsInstancesList = '["https://www.googleapis.com/auth/appengine.admin", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only"] requestClient AppsServicesVersionsInstancesList'{..} = go _asvilAppsId _asvilServicesId _asvilVersionsId _asvilXgafv _asvilUploadProtocol _asvilAccessToken _asvilUploadType _asvilPageToken _asvilPageSize _asvilCallback (Just AltJSON) appEngineService where go = buildClient (Proxy :: Proxy AppsServicesVersionsInstancesListResource) mempty
brendanhay/gogol
gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Services/Versions/Instances/List.hs
mpl-2.0
7,703
0
23
1,782
1,053
610
443
160
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.TaskQueue.Tasks.List -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- List Tasks in a TaskQueue -- -- /See:/ <https://developers.google.com/appengine/docs/python/taskqueue/rest TaskQueue API Reference> for @taskqueue.tasks.list@. module Network.Google.Resource.TaskQueue.Tasks.List ( -- * REST Resource TasksListResource -- * Creating a Request , tasksList , TasksList -- * Request Lenses , tTaskQueue , tProject ) where import Network.Google.Prelude import Network.Google.TaskQueue.Types -- | A resource alias for @taskqueue.tasks.list@ method which the -- 'TasksList' request conforms to. type TasksListResource = "taskqueue" :> "v1beta2" :> "projects" :> Capture "project" Text :> "taskqueues" :> Capture "taskqueue" Text :> "tasks" :> QueryParam "alt" AltJSON :> Get '[JSON] Tasks2 -- | List Tasks in a TaskQueue -- -- /See:/ 'tasksList' smart constructor. data TasksList = TasksList' { _tTaskQueue :: !Text , _tProject :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TasksList' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tTaskQueue' -- -- * 'tProject' tasksList :: Text -- ^ 'tTaskQueue' -> Text -- ^ 'tProject' -> TasksList tasksList pTTaskQueue_ pTProject_ = TasksList' { _tTaskQueue = pTTaskQueue_ , _tProject = pTProject_ } -- | The id of the taskqueue to list tasks from. tTaskQueue :: Lens' TasksList Text tTaskQueue = lens _tTaskQueue (\ s a -> s{_tTaskQueue = a}) -- | The project under which the queue lies. tProject :: Lens' TasksList Text tProject = lens _tProject (\ s a -> s{_tProject = a}) instance GoogleRequest TasksList where type Rs TasksList = Tasks2 type Scopes TasksList = '["https://www.googleapis.com/auth/taskqueue", "https://www.googleapis.com/auth/taskqueue.consumer"] requestClient TasksList'{..} = go _tProject _tTaskQueue (Just AltJSON) taskQueueService where go = buildClient (Proxy :: Proxy TasksListResource) mempty
rueshyna/gogol
gogol-taskqueue/gen/Network/Google/Resource/TaskQueue/Tasks/List.hs
mpl-2.0
3,009
0
15
745
388
233
155
62
1
lucky :: (Integral a) => a -> String lucky 7 = "Lucky Number Seven!" lucky x = "Sorry pal, you're out of luck!" sayMe :: (Integral a) => a -> String sayMe 1 = "One!" sayMe 2 = "Two!" sayMe 3 = "Three!" sayMe 4 = "Four!" sayMe 5 = "Five!" sayMe x = "Not between 1 and 5" --this seems as bad as if statements but whatever factorial :: (Integral a) => a -> a factorial 0 = 1 --functions apparently bind tighter than operators factorial n = n * factorial (n - 1) charName :: Char -> String charName 'a' = "Albert" charName 'b' = "Broseph" charName 'c' = "Cecil" --pattern matching can fail if we don't cover all cases addVectors :: (Num a) => (a, a) -> (a, a) -> (a, a) --since the arguments are tuples, we can use fst and snd to get the respective values --the constraints here specify that all the tuples have the same type; to be more general, we could probably do (Num a, Num b) => (a, b) -> (a, b) -> (a, b)? --addVectors a b = (fst a + fst b, snd a + snd b) --can use pattern matching in function definition: addVectors (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) first :: (a, b, c) -> a --underscores will match but won't bind values first (x, _, _) = x second :: (a, b, c) -> b second (_, y, _) = y third :: (a, b, c) -> c third (_, _, z) = z head' :: [a] -> a --head' [] = error "Can't call head on an empty list!" --head' (x:_) = x --using case expression in place of pattern matching; pattern matching is actually syntactic sugar for case expressions head' xs = case xs of [] -> error "Can't call head on an empty list" (x:_) -> x tell :: (Show a) => [a] -> String tell [] = "The list is empty" tell (x:[]) = "The list has one element: " ++ show x tell (x:y:[]) = "The list has two elements: " ++ show x ++ " and " ++ show y tell (x:y:_) = "The list is long. The first two elements are: " ++ show x ++ " and " ++ show y length' :: [a] -> Int length' [] = 0 length' (_:xs) = 1 + length' xs sum' :: (Num a) => [a] -> a sum' [] = 0 sum' (x:xs) = x + sum' xs capital :: String -> String capital "" = "Empty string, whoops!" --using name@(expression) is an _as pattern_ --as patterns are one way to reduce repeated calculations capital all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x] --RealFloat is a typeclass that encompasses real floating point numbers, e.g. Float and Double --bmiTell :: (RealFloat a) => a -> String --introduction of the guard pattern. used when behaviour is conditional on the _value_ of a variable rather than its pattern --bmiTell bmi -- | bmi <= 18.5 = "You're underweight" -- | bmi <= 25.0 = "You're normal" -- | bmi <= 30.0 = "You're fat" -- | otherwise = "You're a whale" --bmiTell :: (RealFloat a) => a -> a -> String --bmiTell weight height -- | weight / height ^ 2 <= 18.5 = "You're underweight" -- | weight / height ^ 2 <= 25.0 = "You're supposedly normal" -- | weight / height ^ 2 <= 30.0 = "You're fat" -- | otherwise = "You're a whale" bmiTell :: (RealFloat a) => a -> a -> String bmiTell weight height | bmi <= 18.5 = "You're underweight" | bmi <= 25.0 = "You're supposedly normal" | bmi <= 30.0 = "You're fat" | otherwise = "You're a whale" --where statements are another way to avoid repeated calculation where bmi = weight / height ^ 2 --excessive version --bmiTell weight height -- | bmi <= skinny = "You're underweight, you emo, you!" -- | bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!" -- | bmi <= fat = "You're fat! Lose some weight, fatty!" -- | otherwise = "You're a whale, congratulations!" -- where bmi = weight / height ^ 2 -- skinny = 18.5 -- normal = 25.0 -- fat = 30.0 --pattern matching in where statement! --bmiTell weight height -- | bmi <= skinny = "You're underweight, you emo, you!" -- | bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!" -- | bmi <= fat = "You're fat! Lose some weight, fatty!" -- | otherwise = "You're a whale, congratulations!" -- where bmi = weight / height ^ 2 -- (skinny, normal, fat) = (18.5, 25.0, 30.0) max' :: (Ord a) => a -> a -> a max' a b | a > b = a | otherwise = b --guards written inline; ugly. --max' a b | a > b = a | otherwise = b compare' :: (Ord a) => a -> a -> Ordering a `compare'` b | a > b = GT | a == b = EQ | a < b = LT initials :: String -> String -> String --initials firstname lastname = [f] ++ ". " ++ [l] ++ "." -- where (f:_) = firstname -- (l:_) = lastname --this is also the same as: --initials firstname lastname -- | True = [f] ++ ". " ++ [l] ++ "." -- where (f:_) = firstname -- (l:_) = lastname initials (f:_) (l:_) = [f] ++ ". " ++ [l] ++ "." calcBmis :: (RealFloat a) => [(a, a)] -> [a] --calcBmis xs = [bmi w h | (w, h) <- xs] -- where bmi weight height = weight / height ^ 2 --redone with let expression --calcBmis xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2] --the let expression is visible to the output expression (because there is no followup _in_; this makes its scope the one it is currently in) and everything that comes after it calcBmis xs = [bmi | (w, h) <- xs, let bmi = w / h ^ 2, bmi >= 25.0] cylinder :: (RealFloat a) => a -> a -> a cylinder r h = let sideArea = 2 * pi * r * h topArea = pi * r ^ 2 in sideArea + 2 * topArea describeList :: [a] -> String --case expressions allow pattern matching to be done anywhere --describeList xs = "The list is " ++ case xs of [] -> "empty." -- [x] -> "a singleton list" -- xs -> "a longer list" --describeList xs = "The list is " ++ what xs -- where what [] = "empty." -- what [x] = "a singleton list" -- what xs = "a longer list" describeList xs = "The list is " ++ what where what = case xs of [] -> "empty" [x] -> "a singleton list" xs -> "a longer list" --alternatively, normal pattern matching incurs repetition of most of the sentence: --describeList [] = "The list is empty" --describeList [x] -> "The list is a singleton list" --describeList xs -> "The list is a longer list"
alexliew/learn_you_a_haskell
3_syntax_in_functions.hs
unlicense
6,224
6
11
1,626
1,247
695
552
72
3
import System.Random import Data.List import Control.Applicative import Control.Monad import Graphics.GD import Data.Function import System.Environment import System.Exit type Polygon = [Point] type Site = (Point, Color) imgsize = (600, 400) numpoints = 20 sitecolor = rgb 0 0 0 -- black outlinecolor = rgb 255 0 0 -- red sitediam = 3 outlinediam = 5 main = do args <- getArgs let norm | args == [] = norm2 | head args == "i" = normI | n >= 1 = normL n | otherwise = error $ show n ++ " is less than 1: Not a valid norm." where n = read $ head args sites <- randomSites numpoints im <- newImage imgsize plotRegions im (closest norm sites) plotSites im sites savePngFile "voronoi.png" im where closest norm sites query = fst $ minimumBy (compare `on` snd) (map (\(p, c) -> ((p, c), norm (p `sub` query))) sites) -- Plotting functions plotRegions :: Image -> (Point -> Site) -> IO () plotRegions im closestTo = do mapM_ (\(p, c) -> setPixel p c im) cpoints return () where points = [(x, y) | x <- [0..fst imgsize - 1], y <- [0..snd imgsize - 1]] cpoints = map (\p -> (p, snd (closestTo p))) points plotSites :: Image -> [Site] -> IO () plotSites im sites = do mapM_ (\(p, c) -> makeDot p) sites return () where makeDot p = do antiAliased (drawFilledEllipse p (outlinediam, outlinediam)) outlinecolor im antiAliased (drawFilledEllipse p (sitediam, sitediam)) sitecolor im -- Point-generating functions randomList :: Random a => a -> a -> IO [a] randomList a b = randomRs (a,b) <$> newStdGen randomSites :: Int -> IO [Site] randomSites n = do xs <- randomList 0 (fst imgsize - 1) ys <- randomList 0 (snd imgsize - 1) cs <- randomList 0 255 return $ take n $ zip (zip xs ys) (map (uncurry3 rgb) (trips cs)) -- Math-related functions -- l2 (Euclidian) norm norm2 :: Point -> Double norm2 p = sqrt (fromIntegral (dx^2 + dy^2)) where (dx, dy) = p -- Other norms. Eg. l1 is the "Manhattan" or "taxicab" norm. -- Defined only for n >= 1. normL :: Double -> Point -> Double normL n p | n == 1 = abs dx + abs dy | n > 1 = ((abs dx ** n) + (abs dy ** n)) ** (1 / n) where (dxi, dyi) = p (dx, dy) = (fromIntegral dxi, fromIntegral dyi) -- l-inf. norm normI :: Point -> Double normI p = fromIntegral $ max (abs dx) (abs dy) where (dx, dy) = p sub :: Point -> Point -> Point (m, n) `sub` (p, q) = (m-p, n-q) -- Utility functions pairs :: [a] -> [(a, a)] pairs (x:y:xs) = (x, y) : pairs xs pairs _ = [] trips :: [a] -> [(a, a, a)] trips (x:y:z:xs) = (x, y, z) : trips xs trips _ = [] uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d uncurry3 f (a, b, c) = f a b c --minimumBy :: Ord a => [b] -> (b -> a) -> b --minimumBy f [] = error "minimumBy: empty list" --minimumBy f (x:[]) = x --minimumBy f (x:y:xs) = if ((f x) < (f y)) -- then minimumBy f x:xs -- else minimumBy f y:xs
yshklarov/voronoi
voronoi.hs
unlicense
3,072
1
14
867
1,311
687
624
75
1
module Graham.A300518 (a300518) where import HelperSequences.A006530 (a006530) import HelperSequences.A007913 (a007913) a300518 :: Integer -> Integer a300518 = a006530 . a007913
peterokagey/haskellOEIS
src/Graham/A300518.hs
apache-2.0
179
0
5
21
49
29
20
5
1
{- | Module : Lambda.Name Description : Binding name. Copyright : (c) Paweł Nowak License : Apache v2.0 Maintainer : [email protected] Stability : experimental Portability : portable -} module Lambda.Name where import Data.String import Data.Text.Lazy (Text, pack) -- Use a simple text for now. newtype Name = Name Text deriving (Eq, Ord, Show, Read) instance IsString Name where fromString = Name . pack -- | A name that cannot occur in any program and is reserved for the compiler. -- This is used eg. unnamed function parameters. reservedName :: Name reservedName = "\0"
pawel-n/lambda
Lambda/Name.hs
apache-2.0
612
0
6
129
83
50
33
9
1
module Main where import Options.Applicative import Data.Monoid import Util.Test import Util.DiffParser main :: IO () main = do op <- execParser optsHelper case op of Conflict f -> processConflictFolder f >> return () Patch s d j _ -> patchFiles s d j Preprocess f -> runMinify f data Opts = Conflict { folder :: String } | Patch { srcFile :: String , dstFile :: String , jsonOutput :: Maybe String , printAll :: Bool } | Preprocess { prepFolder :: String } opts :: Parser Opts opts = ( Patch <$> strOption ( long "source" <> short 's' <> metavar "SRC_TARGET" <> help "Source file" ) <*> strOption ( long "destination" <> short 'd' <> metavar "DST_TARGET" <> help "Destination file" ) <*> optional (strOption ( long "json-output" <> short 'j' <> metavar "OUT_TARGET" <> help "Output file" )) <*> switch ( long "all" <> short 'a' <> help "Print all patches") ) <|> ( Conflict <$> strOption ( long "folder" <> short 'f' <> metavar "FOLDER" <> help "Folder to process" ) ) <|> ( Preprocess <$> strOption ( long "preprocess" <> short 'p' <> metavar "PREPROCESS" <> help "Folder to preprocess" ) ) optsHelper :: ParserInfo Opts optsHelper = info (helper <*> opts) ( fullDesc <> progDesc "Clojure parser in Haskell" )
nazrhom/vcs-clojure
app/Main.hs
bsd-3-clause
1,411
0
17
415
437
215
222
59
3
-- -- (c) The University of Glasgow -- module Avail ( Avails, AvailInfo(..), IsPatSyn(..), avail, patSynAvail, availsToNameSet, availsToNameSetWithSelectors, availsToNameEnv, availName, availNames, availNonFldNames, availNamesWithSelectors, availFlds, stableAvailCmp ) where import Name import NameEnv import NameSet import FieldLabel import Binary import Outputable import Util import Data.Function -- ----------------------------------------------------------------------------- -- The AvailInfo type -- | Records what things are "available", i.e. in scope data AvailInfo = Avail IsPatSyn Name -- ^ An ordinary identifier in scope | AvailTC Name [Name] [FieldLabel] -- ^ A type or class in scope. Parameters: -- -- 1) The name of the type or class -- 2) The available pieces of type or class, -- excluding field selectors. -- 3) The record fields of the type -- (see Note [Representing fields in AvailInfo]). -- -- The AvailTC Invariant: -- * If the type or class is itself -- to be in scope, it must be -- *first* in this list. Thus, -- typically: @AvailTC Eq [Eq, ==, \/=]@ deriving( Eq ) -- Equality used when deciding if the -- interface has changed data IsPatSyn = NotPatSyn | IsPatSyn deriving Eq -- | A collection of 'AvailInfo' - several things that are \"available\" type Avails = [AvailInfo] {- Note [Representing fields in AvailInfo] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When -XDuplicateRecordFields is disabled (the normal case), a datatype like data T = MkT { foo :: Int } gives rise to the AvailInfo AvailTC T [T, MkT] [FieldLabel "foo" False foo], whereas if -XDuplicateRecordFields is enabled it gives AvailTC T [T, MkT] [FieldLabel "foo" True $sel:foo:MkT] since the label does not match the selector name. The labels in a field list are not necessarily unique: data families allow the same parent (the family tycon) to have multiple distinct fields with the same label. For example, data family F a data instance F Int = MkFInt { foo :: Int } data instance F Bool = MkFBool { foo :: Bool} gives rise to AvailTC F [F, MkFInt, MkFBool] [FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" True $sel:foo:MkFBool]. Moreover, note that the flIsOverloaded flag need not be the same for all the elements of the list. In the example above, this occurs if the two data instances are defined in different modules, one with `-XDuplicateRecordFields` enabled and one with it disabled. Thus it is possible to have AvailTC F [F, MkFInt, MkFBool] [FieldLabel "foo" True $sel:foo:MkFInt, FieldLabel "foo" False foo]. If the two data instances are defined in different modules, both without `-XDuplicateRecordFields`, it will be impossible to export them from the same module (even with `-XDuplicateRecordfields` enabled), because they would be represented identically. The workaround here is to enable `-XDuplicateRecordFields` on the defining modules. -} -- | Compare lexicographically stableAvailCmp :: AvailInfo -> AvailInfo -> Ordering stableAvailCmp (Avail _ n1) (Avail _ n2) = n1 `stableNameCmp` n2 stableAvailCmp (Avail {}) (AvailTC {}) = LT stableAvailCmp (AvailTC n ns nfs) (AvailTC m ms mfs) = (n `stableNameCmp` m) `thenCmp` (cmpList stableNameCmp ns ms) `thenCmp` (cmpList (stableNameCmp `on` flSelector) nfs mfs) stableAvailCmp (AvailTC {}) (Avail {}) = GT patSynAvail :: Name -> AvailInfo patSynAvail n = Avail IsPatSyn n avail :: Name -> AvailInfo avail n = Avail NotPatSyn n -- ----------------------------------------------------------------------------- -- Operations on AvailInfo availsToNameSet :: [AvailInfo] -> NameSet availsToNameSet avails = foldr add emptyNameSet avails where add avail set = extendNameSetList set (availNames avail) availsToNameSetWithSelectors :: [AvailInfo] -> NameSet availsToNameSetWithSelectors avails = foldr add emptyNameSet avails where add avail set = extendNameSetList set (availNamesWithSelectors avail) availsToNameEnv :: [AvailInfo] -> NameEnv AvailInfo availsToNameEnv avails = foldr add emptyNameEnv avails where add avail env = extendNameEnvList env (zip (availNames avail) (repeat avail)) -- | Just the main name made available, i.e. not the available pieces -- of type or class brought into scope by the 'GenAvailInfo' availName :: AvailInfo -> Name availName (Avail _ n) = n availName (AvailTC n _ _) = n -- | All names made available by the availability information (excluding overloaded selectors) availNames :: AvailInfo -> [Name] availNames (Avail _ n) = [n] availNames (AvailTC _ ns fs) = ns ++ [ flSelector f | f <- fs, not (flIsOverloaded f) ] -- | All names made available by the availability information (including overloaded selectors) availNamesWithSelectors :: AvailInfo -> [Name] availNamesWithSelectors (Avail _ n) = [n] availNamesWithSelectors (AvailTC _ ns fs) = ns ++ map flSelector fs -- | Names for non-fields made available by the availability information availNonFldNames :: AvailInfo -> [Name] availNonFldNames (Avail _ n) = [n] availNonFldNames (AvailTC _ ns _) = ns -- | Fields made available by the availability information availFlds :: AvailInfo -> [FieldLabel] availFlds (AvailTC _ _ fs) = fs availFlds _ = [] -- ----------------------------------------------------------------------------- -- Printing instance Outputable AvailInfo where ppr = pprAvail pprAvail :: AvailInfo -> SDoc pprAvail (Avail _ n) = ppr n pprAvail (AvailTC n ns fs) = ppr n <> braces (hsep (punctuate comma (map ppr ns ++ map (ppr . flLabel) fs))) instance Binary AvailInfo where put_ bh (Avail b aa) = do putByte bh 0 put_ bh aa put_ bh b put_ bh (AvailTC ab ac ad) = do putByte bh 1 put_ bh ab put_ bh ac put_ bh ad get bh = do h <- getByte bh case h of 0 -> do aa <- get bh b <- get bh return (Avail b aa) _ -> do ab <- get bh ac <- get bh ad <- get bh return (AvailTC ab ac ad) instance Binary IsPatSyn where put_ bh IsPatSyn = putByte bh 0 put_ bh NotPatSyn = putByte bh 1 get bh = do h <- getByte bh case h of 0 -> return IsPatSyn _ -> return NotPatSyn
vikraman/ghc
compiler/basicTypes/Avail.hs
bsd-3-clause
7,066
0
15
2,070
1,233
647
586
98
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} -- | -- Module : Data.Array.Nikola.Backend.C.Codegen -- Copyright : (c) Geoffrey Mainland 2012 -- License : BSD-style -- -- Maintainer : Geoffrey Mainland <[email protected]> -- Stability : experimental -- Portability : non-portable module Data.Array.Nikola.Backend.C.Codegen ( compileProgram, compileKernelFun, calcKernelDims ) where import Control.Applicative ((<$>), (<*>)) import Control.Monad (replicateM, when, zipWithM_) import Control.Monad.Trans (MonadIO(..)) import Data.Functor.Identity import Data.List (findIndex) import Data.Monoid (Last(..), Sum(..)) import Language.C.Quote.C import qualified Language.C.Syntax as C import Text.PrettyPrint.Mainland #if !MIN_VERSION_template_haskell(2,7,0) import qualified Data.Loc import qualified Data.Symbol import qualified Language.C.Syntax #endif /* !MIN_VERSION_template_haskell(2,7,0) */ import Data.Array.Nikola.Backend.C.Monad import Data.Array.Nikola.Backend.C.Quoters import Data.Array.Nikola.Backend.Flags import Data.Array.Nikola.Language.Check import Data.Array.Nikola.Language.Generic import Data.Array.Nikola.Language.Syntax -- import Data.Array.Nikola.Pretty -- Compile a program to a C function compileProgram :: Flags -> Exp -> IO [C.Definition] compileProgram flags p = do (_, cenv) <- runC go (defaultCEnv flags) return $ cenvToCUnit cenv where (vtaus, body) = splitLamE p go :: C CExp go = do let dialect = fromLJust fDialect flags addIncludes dialect flags <- getFlags fname <- case fFunction flags of Last Nothing -> gensym "host" Last (Just fname) -> return fname tau_host <- inferExp p tau_ret <- snd <$> checkFunT tau_host compileFun dialect Host Host fname vtaus tau_ret $ do declareHeap dialect (numAllocs p) declareResult dialect addFinalStm (returnResult dialect) addFinalStm [cstm|done: $stm:gc|] ce <- compileExp body mark ce return ce addIncludes :: Dialect -> C () addIncludes CUDA = do addInclude "\"cuda.h\"" addInclude "\"cuda_runtime_api.h\"" addInclude "<stdint.h>" addIncludes OpenMP = do addInclude "<stdlib.h>" addInclude "<stdint.h>" addInclude "<math.h>" addInclude "<omp.h>" addIncludes _ = return () -- Compile a constant to a C expression compileConst :: Const -> C CExp compileConst (BoolC True) = return $ ScalarCE [cexp|1|] compileConst (BoolC False) = return $ ScalarCE [cexp|0|] compileConst (Int8C n) = return $ ScalarCE [cexp|$int:(toInteger n)|] compileConst (Int16C n) = return $ ScalarCE [cexp|$int:(toInteger n)|] compileConst (Int32C n) = return $ ScalarCE [cexp|$int:(toInteger n)|] compileConst (Int64C n) = return $ ScalarCE [cexp|$lint:(toInteger n)|] compileConst (Word8C n) = return $ ScalarCE [cexp|$uint:(toInteger n)|] compileConst (Word16C n) = return $ ScalarCE [cexp|$uint:(toInteger n)|] compileConst (Word32C n) = return $ ScalarCE [cexp|$uint:(toInteger n)|] compileConst (Word64C n) = return $ ScalarCE [cexp|$ulint:(toInteger n)|] compileConst (FloatC n) = return $ ScalarCE [cexp|$float:(toRational n)|] compileConst (DoubleC n) = return $ ScalarCE [cexp|$double:(toRational n)|] -- Compile an expression to a C expression compileExp :: Exp -> C CExp compileExp (VarE v) = lookupVarTrans v compileExp (ConstE c) = compileConst c compileExp UnitE = return VoidCE compileExp (TupleE es) = TupCE <$> mapM compileExp es compileExp (ProjE i _ e) = do ce <- compileExp e tau <- inferExp e case ce of TupCE ces -> return $ ces !! i _ -> faildoc $ ppr e <+> text "::" <+> ppr tau <+> text "-->" <+> ppr ce compileExp (LetE v tau _ e1 e2) = do ce1 <- bindExp (Just (unVar v)) e1 extendVarTypes [(v, tau)] $ do extendVarTrans [(v, ce1)] $ do compileExp e2 compileExp (LamE vtaus e) = do dialect <- fromLJust fDialect <$> getFlags fname <- gensym "f" tau_ret <- snd <$> (inferExp (LamE vtaus e) >>= checkFunT) ctx <- getContext compileFun dialect ctx ctx fname vtaus tau_ret (compileExp e) compileExp (AppE f es) = do dialect <- fromLJust fDialect <$> getFlags ctx <- getContext tau <- inferExp f cf <- compileExp f compileCall dialect ctx ctx tau es $ \maybe_cresult cargs -> case maybe_cresult of Nothing -> addStm [cstm|($cf)($args:cargs);|] Just cresult -> addStm [cstm|$cresult = ($cf)($args:cargs);|] compileExp (CallE f es) = inContext Kernel $ do dialect <- fromLJust fDialect <$> getFlags tau <- inferExp f kname <- gensym "kern" kern <- compileKernelFun dialect kname f compileCall dialect Host Kernel tau es (callKernel dialect kern) where callKernel :: Dialect -> CudaKernel -> Maybe CExp -> [C.Exp] -> C () callKernel CUDA kern _ cargs = inBlock $ do (gdims, tdims) <- liftIO $ calcKernelDims kern es addLocal [cdecl|typename dim3 gdims;|] addLocal [cdecl|typename dim3 tdims;|] setGridDim "gdims" gdims setGridDim "tdims" tdims wbInits kern addStm [cstmCU|$id:(cukernName kern)<<<gdims,tdims>>>($args:cargs);|] callKernel _ kern Nothing cargs = addStm [cstm|$id:(cukernName kern)($args:cargs);|] callKernel _ kern (Just cresult) cargs = addStm [cstm|$cresult = $id:(cukernName kern)($args:cargs);|] setGridDim :: String -> (Int, Int, Int) -> C () setGridDim dim (x, y, z) = do addStm [cstm|$id:dim.x = $int:x;|] addStm [cstm|$id:dim.y = $int:y;|] addStm [cstm|$id:dim.z = $int:z;|] wbInits :: CudaKernel -> C () wbInits kern = mapM_ wbInit (cukernWorkBlocks kern) where wbInit :: CudaWorkBlock -> C () wbInit wb = do hbc <- gensym "hBlockCounter" addLocal [cdecl|$ty:cIdxT $id:hbc = 0;|] addStm [cstm|cudaMemcpyToSymbol($(cuworkBlockCounter wb), &$id:hbc, sizeof($ty:cIdxT), 0, cudaMemcpyHostToDevice);|] compileExp (UnopE op e) = do tau <- inferExp e >>= checkScalarT ScalarCE <$> (go op tau <$> compileExp e) where go :: Unop -> ScalarType -> CExp -> C.Exp go (Cast Int8T) _ ce = [cexp|(typename int8_t) $ce|] go (Cast Int16T) _ ce = [cexp|(typename int16_t) $ce|] go (Cast Int32T) _ ce = [cexp|(typename int32_t) $ce|] go (Cast Int64T) _ ce = [cexp|(typename int64_t) $ce|] go (Cast Word8T) _ ce = [cexp|(typename uint8_t) $ce|] go (Cast Word16T) _ ce = [cexp|(typename uint16_t) $ce|] go (Cast Word32T) _ ce = [cexp|(typename uint32_t) $ce|] go (Cast Word64T) _ ce = [cexp|(typename uint64_t) $ce|] go (Cast FloatT) _ ce = [cexp|(float) $ce|] go (Cast DoubleT) _ ce = [cexp|(double) $ce|] go NotL _ ce = [cexp|!$ce|] go NegN _ ce = [cexp|-$ce|] go AbsN FloatT ce = [cexp|fabsf($ce)|] go AbsN DoubleT ce = [cexp|fabs($ce)|] go AbsN tau ce | isIntT (ScalarT tau) = [cexp|abs($ce)|] go SignumN FloatT ce = [cexp|$ce > 0 ? 1 : ($ce < 0 ? -1 : 0)|] go SignumN DoubleT ce = [cexp|$ce > 0.0 ? 1.0 : ($ce < 0.0 ? -1.0 : 0.0)|] go SignumN tau ce | isIntT (ScalarT tau) = [cexp|$ce > 0.0f ? 1.0f : ($ce < 0.0f ? -1.0f : 0.0f)|] go RecipF FloatT ce = [cexp|1.0f/$ce|] go RecipF DoubleT ce = [cexp|1.0/$ce|] go ExpF FloatT ce = [cexp|expf($ce)|] go ExpF DoubleT ce = [cexp|exp($ce)|] go SqrtF FloatT ce = [cexp|sqrtf($ce)|] go SqrtF DoubleT ce = [cexp|sqrt($ce)|] go LogF FloatT ce = [cexp|logf($ce)|] go LogF DoubleT ce = [cexp|log($ce)|] go SinF FloatT ce = [cexp|sinf($ce)|] go SinF DoubleT ce = [cexp|sinf($ce)|] go TanF FloatT ce = [cexp|tanf($ce)|] go TanF DoubleT ce = [cexp|tan($ce)|] go CosF FloatT ce = [cexp|cosf($ce)|] go CosF DoubleT ce = [cexp|cos($ce)|] go AsinF FloatT ce = [cexp|asinf($ce)|] go AsinF DoubleT ce = [cexp|asin($ce)|] go AtanF FloatT ce = [cexp|atanf($ce)|] go AtanF DoubleT ce = [cexp|atan($ce)|] go AcosF FloatT ce = [cexp|acosf($ce)|] go AcosF DoubleT ce = [cexp|acos($ce)|] go SinhF FloatT ce = [cexp|asinhf($ce)|] go SinhF DoubleT ce = [cexp|asinh($ce)|] go TanhF FloatT ce = [cexp|atanhf($ce)|] go TanhF DoubleT ce = [cexp|atanh($ce)|] go CoshF FloatT ce = [cexp|acoshf($ce)|] go CoshF DoubleT ce = [cexp|acosh($ce)|] go AsinhF FloatT ce = [cexp|asinhf($ce)|] go AsinhF DoubleT ce = [cexp|asinh($ce)|] go AtanhF FloatT ce = [cexp|atanhf($ce)|] go AtanhF DoubleT ce = [cexp|atanh($ce)|] go AcoshF FloatT ce = [cexp|acoshf($ce)|] go AcoshF DoubleT ce = [cexp|acosh($ce)|] go RoundF FloatT ce = [cexp|roundf($ce)|] go RoundF DoubleT ce = [cexp|round($ce)|] go CeilF FloatT ce = [cexp|ceilf($ce)|] go CeilF DoubleT ce = [cexp|ceil($ce)|] go FloorF FloatT ce = [cexp|floorf($ce)|] go FloorF DoubleT ce = [cexp|floor($ce)|] go _ tau _ = errordoc $ text "Cannot compile" <+> ppr (UnopE op e) <+> text "at type" <+> ppr tau compileExp (BinopE op e1 e2) = do tau <- inferExp e1 >>= checkScalarT ScalarCE <$> (go op tau <$> compileExp e1 <*> compileExp e2) where go :: Binop -> ScalarType -> CExp -> CExp -> C.Exp go EqO _ ce1 ce2 = [cexp|$ce1 == $ce2|] go NeO _ ce1 ce2 = [cexp|$ce1 != $ce2|] go GtO _ ce1 ce2 = [cexp|$ce1 > $ce2|] go GeO _ ce1 ce2 = [cexp|$ce1 >= $ce2|] go LtO _ ce1 ce2 = [cexp|$ce1 < $ce2|] go LeO _ ce1 ce2 = [cexp|$ce1 <= $ce2|] go MaxO _ ce1 ce2 = [cexp|$ce1 > $ce2 ? $ce1 : $ce2 |] go MinO _ ce1 ce2 = [cexp|$ce1 > $ce2 ? $ce2 : $ce1 |] go AndL _ ce1 ce2 = [cexp|$ce1 && $ce2|] go OrL _ ce1 ce2 = [cexp|$ce1 || $ce2|] go AddN _ ce1 ce2 = [cexp|$ce1 + $ce2|] go SubN _ ce1 ce2 = [cexp|$ce1 - $ce2|] go MulN _ ce1 ce2 = [cexp|$ce1 * $ce2|] go AndB _ ce1 ce2 = [cexp|$ce1 & $ce2|] go OrB _ ce1 ce2 = [cexp|$ce1 | $ce2|] go QuotI _ ce1 ce2 = [cexp|$ce1 / $ce2|] go RemI _ ce1 ce2 = [cexp|$ce1 % $ce2|] go DivF _ ce1 ce2 = [cexp|$ce1 / $ce2|] go ModF FloatT ce1 ce2 = [cexp|fmodf($ce1,$ce2)|] go ModF DoubleT ce1 ce2 = [cexp|fmod($ce1,$ce2)|] go PowF FloatT ce1 ce2 = [cexp|powf($ce1,$ce2)|] go PowF DoubleT ce1 ce2 = [cexp|pow($ce1,$ce2)|] go LogBaseF FloatT ce1 ce2 = [cexp|logf($ce2)/logf($ce1)|] go LogBaseF DoubleT ce1 ce2 = [cexp|log($ce2)/log($ce1)|] go _ tau _ _ = errordoc $ text "Cannot compile" <+> ppr (BinopE op e1 e2) <+> text "at type" <+> ppr tau compileExp (IfThenElseE test th el) = do tau <- inferExp th ctest <- compileExp test cvresult <- newCVar "ifte_result" tau cthitems <- inNewBlock_ $ do cresult <- compileExp th assignC cvresult cresult celitems <- inNewBlock_ $ do cresult <- compileExp el assignC cvresult cresult case celitems of [] -> addStm [cstm|if ($ctest) { $items:cthitems }|] _ -> addStm [cstm|if ($ctest) { $items:cthitems } else { $items:celitems }|] return cvresult compileExp e@(SwitchE e_scrut cases dflt) = do tau <- inferExp e cscrut <- compileExp e_scrut cvresult <- newCVar "switch_result" tau ccases <- (++) <$> mapM (compileCase cvresult) cases <*> compileDefault cvresult dflt addStm [cstm|switch ($cscrut) { $stms:ccases }|] return cvresult where compileCase :: CExp -> (Int, Exp) -> C C.Stm compileCase cvresult (i, e) = do items <- inNewBlock_ $ do ce <- compileExp e assignC cvresult ce return [cstm|case $int:i: { $items:items }|] compileDefault :: CExp -> Maybe Exp -> C [C.Stm] compileDefault _ Nothing = return [] compileDefault cvresult (Just e) = do items <- inNewBlock_ $ do ce <- compileExp e assignC cvresult ce return [[cstm|default: { $items:items }|]] compileExp (ReturnE UnitE) = return VoidCE compileExp (ReturnE e) = compileExp e compileExp (SeqE m1 m2) = do compileExp m1 compileExp m2 compileExp (ParE m1 m2) = do compileExp m1 compileExp m2 compileExp (BindE v tau m1 m2) = do ce1 <- compileExp m1 extendVarTypes [(v, tau)] $ do extendVarTrans [(v, ce1)] $ do compileExp m2 compileExp (AllocE tau_arr sh) = do dialect <- fromLJust fDialect <$> getFlags (tau, _) <- checkArrayT tau_arr csh <- mapM compileExp sh let csz = toSize csh cptr <- allocPtr dialect csz tau return $ ArrayCE cptr csh where toSize :: [CExp] -> C.Exp toSize [] = [cexp|0|] toSize [ce] = [cexp|$ce|] toSize (ce:ces) = [cexp|$ce*$(toSize ces)|] allocPtr :: Dialect -> C.Exp -> ScalarType -> C PtrCExp allocPtr dialect csz (TupleT taus) = TupPtrCE <$> mapM (allocPtr dialect csz) taus allocPtr dialect csz tau = do ctemp <- gensym "alloc" let cptr = PtrCE [cexp|$id:ctemp|] addLocal [cdecl|$ty:ctau* $id:ctemp = NULL;|] case dialect of CUDA -> addStm [cstm|if(cudaMalloc(&$cptr, $exp:csz*sizeof($ty:ctau)) != cudaSuccess) $stm:(failWithResult dialect cnegone) |] _ -> addStm [cstm|if(($cptr = ($ty:ctau*) malloc($exp:csz*sizeof($ty:ctau))) == NULL) $stm:(failWithResult dialect cnegone) |] addStm [cstm|allocs[nallocs] = (void*) $cptr;|] addStm [cstm|marks[nallocs++] = 0;|] return cptr where cnegone :: C.Exp cnegone = [cexp|-1|] ctau :: C.Type ctau = [cty|$ty:(toCType tau)|] compileExp (DimE i _ e) = do ce <- compileExp e tau <- inferExp e case ce of ArrayCE _ sh -> return (sh !! i) _ -> faildoc $ ppr e <+> text "::" <+> ppr tau <+> text "-->" <+> ppr ce compileExp (ProjArrE i _ e) = do ce <- compileExp e tau <- inferExp e case ce of ArrayCE (TupPtrCE ptr) sh -> return $ ArrayCE (ptr !! i) sh _ -> faildoc $ ppr e <+> text "::" <+> ppr tau <+> text "-->" <+> ppr ce compileExp (IndexE arr idx) = do carr <- compileExp arr cidx <- compileExp idx return $ ScalarCE [cexp|$carr[$cidx]|] compileExp (WriteE arr idx e) = do carr <- compileExp arr cidx <- compileExp idx ce <- compileExp e addStm [cstm|$carr[$cidx] = $ce;|] return VoidCE -- A bit disgusting, but we relay on the fact that f is a lambda. Our -- combinators guarantee that this will be the case compileExp (IterateE n (LamE [(x, tau)] e) x0) = do i <- gensym "i" cn <- compileExp n cx0 <- compileExp x0 cx <- newCVar (unVar x) tau assignC cx cx0 citems <- inNewBlock_ $ do ce <- extendVarTypes [(x, tau)] $ extendVarTrans [(x, cx)] $ compileExp e assignC cx ce addStm [cstm|if ($cn > 0) { for (int $id:i = 0; $id:i < $cn; ++$id:i) { $items:citems } } |] return cx compileExp e@(IterateE {}) = faildoc $ nest 2 $ text "Cannot compile:" </> ppr e compileExp (IterateWhileE n (LamE [(x, tau)] e) x0) = do i <- gensym "i" cn <- compileExp n cx0 <- compileExp x0 ctest <- newCVar (unVar x ++ "test") boolT cx <- newCVar (unVar x) tau assignC cx cx0 assignC ctest (ScalarCE [cexp|1|]) citems <- inNewBlock_ $ do ce <- extendVarTypes [(x, tau)] $ extendVarTrans [(x, cx)] $ compileExp e (ctest', cx') <- case ce of TupCE [ctest', cx'] -> return (ctest', cx') _ -> faildoc $ nest 2 $ text "Bad iteration test:" </> ppr e assignC cx cx' assignC ctest ctest' addStm [cstm|if ($cn > 0) { for (int $id:i = 0; $ctest && $id:i < $cn; ++$id:i) { $items:citems } } |] return cx compileExp e@(IterateWhileE {}) = faildoc $ nest 2 $ text "Cannot compile:" </> ppr e compileExp (ForE forloop loopvs m) = do dialect <- fromLJust fDialect <$> getFlags tau <- extendVarTypes (vs `zip` repeat ixT) $ inferExp m cvresult <- newCVar "for_result" tau let idxs = allIdxs dialect forloop compileLoop dialect forloop $ go dialect forloop (vs `zip` es) idxs cvresult return cvresult where (vs, es) = unzip loopvs compileLoop :: Dialect -> ForLoop -> C () -> C () compileLoop CUDA IrregParFor mloop = do loop <- inNewBlock_ mloop idxs <- getIndices blockCounter <- gensym "blockCounter" addWorkBlock CudaWorkBlock{ cuworkBlockCounter = blockCounter } addGlobal [cedeclCU|__device__ $ty:cIdxT $id:blockCounter;|] inBlock $ do addLocal [cdeclCU|__shared__ $ty:cIdxT $id:gridWidth;|] addLocal [cdeclCU|__shared__ $ty:cIdxT $id:gridHeight;|] addLocal [cdeclCU|__shared__ $ty:cIdxT $id:numBlocks;|] addLocal [cdeclCU|__shared__ $ty:cIdxT $id:blockIdx;|] mapM_ addBlockIdxLocal idxs whileTrue $ do body <- inNewBlock_ $ setupBlockIndex blockCounter idxs addStm [cstm|if ($(isFirstThread idxs)) { $items:body }|] addStm [cstm|__syncthreads();|] addStm [cstm|if ($id:blockIdx >= $id:numBlocks) break;|] addStm [cstm|{ $items:loop }|] where setupBlockIndex :: String -> [(Idx, Exp)] -> C () setupBlockIndex blockCounter [(IrregCudaThreadIdx CudaDimX, width) ,(IrregCudaThreadIdx CudaDimY, height)] = do cwidth <- compileExp width cheight <- compileExp height let threadGridWidth = [cexp|blockDim.x|] let threadGridHeight = [cexp|blockDim.y|] addStm [cstm|$id:gridWidth = ($cwidth + $threadGridWidth - 1) / $threadGridWidth;|] addStm [cstm|$id:gridHeight = ($cheight + $threadGridHeight - 1) / $threadGridHeight;|] addStm [cstm|$id:numBlocks = $id:gridWidth * $id:gridHeight;|] addStm [cstm|$id:blockIdx = atomicAdd(&$id:blockCounter, 1);|] addStm [cstm|$id:(irregCudaDimVar CudaDimX) = $id:blockIdx % $id:gridWidth;|] addStm [cstm|$id:(irregCudaDimVar CudaDimY) = $id:blockIdx / $id:gridWidth;|] setupBlockIndex _ idxs = faildoc $ text "setupBlockIndex cannot compile:" <+> (text . show) idxs isFirstThread :: [(Idx, Exp)] -> C.Exp isFirstThread idxs = foldr1 cband (map go idxs) where go :: (Idx, Exp) -> C.Exp go (IrregCudaThreadIdx dim, _) = [cexp|threadIdx.$id:(cudaDimVar dim) == 0|] go _ = error "isFirstThread: bad index" addBlockIdxLocal :: (Idx, Exp) -> C () addBlockIdxLocal (IrregCudaThreadIdx dim, _) = addLocal [cdeclCU|__shared__ $ty:cIdxT $id:(irregCudaDimVar dim);|] addBlockIdxLocal _ = error "isFirstThread: bad index" cband :: C.Exp -> C.Exp -> C.Exp cband e1 e2 = [cexp|$e1 && $e2|] whileTrue :: C () -> C () whileTrue act = do body <- inNewBlock_ act addStm [cstm|while (1) { $items:body }|] compileLoop _ _ mloop = mloop go :: Dialect -> ForLoop -> [(Var, Exp)] -> [Idx] -> CExp -> C () go _ _ _ [] _ = fail "compileFor: the impossible happened!" go _ _ [] _ cvresult = do cresult <- compileExp m assignC cvresult cresult go CUDA IrregParFor ((v@(Var i),bound):is) (idx:idxs) cresult = do useIndex (idx,bound) let cv = ScalarCE [cexp|$id:i|] cbound <- gensym "bound" cebound <- compileExp bound extendVarTypes [(v, ixT)] $ do extendVarTrans [(v, cv)] $ do addLocal [cdecl|const $ty:cIdxT $id:cbound = $cebound;|] addLocal [cdecl|const $ty:cIdxT $id:i = $(idxInit idx);|] body <- inNewBlock_ $ go CUDA IrregParFor is idxs cresult addStm [cstm|if ($id:i < $id:cbound) { $items:body } |] go dialect forloop ((v@(Var i),bound):is) (idx:idxs) cresult = do useIndex (idx,bound) let cv = ScalarCE [cexp|$id:i|] cbound <- bindExp (Just "bound") bound extendVarTypes [(v, ixT)] $ do extendVarTrans [(v, cv)] $ do body <- inNewBlock_ $ go dialect forloop is idxs cresult when (isParFor forloop && dialect == OpenMP) $ addStm [cstm|$pragma:("omp parallel for")|] addStm [cstm|for ($ty:cIdxT $id:i = $(idxInit idx); $id:i < $cbound; $(idxStride idx i)) { $items:body } |] allIdxs :: Dialect -> ForLoop -> [Idx] allIdxs CUDA ParFor = map CudaThreadIdx [CudaDimX, CudaDimY, CudaDimZ] ++ repeat CIdx allIdxs CUDA IrregParFor = map IrregCudaThreadIdx [CudaDimX, CudaDimY, CudaDimZ] ++ repeat CIdx allIdxs _ _ = repeat CIdx idxInit :: Idx -> C.Exp idxInit CIdx = [cexp|0|] idxInit (CudaThreadIdx dim) = [cexp|blockIdx.$id:x*blockDim.$id:x + threadIdx.$id:x|] where x = cudaDimVar dim idxInit (IrregCudaThreadIdx dim) = [cexp|$id:(irregCudaDimVar dim)*blockDim.$id:x + threadIdx.$id:x|] where x = cudaDimVar dim idxStride :: Idx -> String -> C.Exp idxStride CIdx v = [cexp|++$id:v|] idxStride (CudaThreadIdx dim) v = [cexp|$id:v += blockDim.$id:x*gridDim.$id:x|] where x = cudaDimVar dim idxStride (IrregCudaThreadIdx dim) v = [cexp|$id:v += blockDim.$id:x*gridDim.$id:x|] where x = cudaDimVar dim irregCudaDimVar :: CudaDim -> String irregCudaDimVar CudaDimX = "__blockX" irregCudaDimVar CudaDimY = "__blockY" irregCudaDimVar CudaDimZ = "__blockZ" numBlocks :: String numBlocks = "__numBlocks" blockIdx :: String blockIdx = "__blockIdx" gridWidth :: String gridWidth = "__gridWidth" gridHeight :: String gridHeight = "__gridHeight" compileExp SyncE = do dialect <- fromLJust fDialect <$> getFlags case dialect of CUDA -> addStm [cstm|__syncthreads();|] _ -> return () return VoidCE compileExp e@(DelayedE {}) = faildoc $ text "Cannot compile:" <+> ppr e -- | Compile a kernel function given a dialect. The result is a list of indices -- and their bounds. A bound is represented as a function from the kernel's -- arguments to an expression. compileKernelFun :: Dialect -> String -> Exp -> C CudaKernel compileKernelFun dialect fname f = do (((_, idxs), wbs), cdefs) <- collectDefinitions $ do collectWorkBlocks $ do addIncludes dialect collectIndices $ do inContext Kernel $ do tau_kern <- inferExp f tau_ret <- snd <$> checkFunT tau_kern compileFun dialect Host Kernel fname vtaus tau_ret (compileExp body) return () return CudaKernel { cukernDefs = cdefs , cukernName = fname , cukernIdxs = idxs , cukernWorkBlocks = wbs , cukernRewrite = rewrite } where (vtaus, body) = splitLamE f vs = map fst vtaus -- Rewrite an expression written in terms of the kernel's parameters so that -- it is written in terms of the arguments. We use this to take a loop -- bound, which occurs in the body of a kernel, and rewrite it to the -- equivalent expression in the caller's context. This allows the caller to -- work with the loop bounds and compute things like the proper CUDA grid -- and thread block parameters. rewrite :: Exp -> [Exp] -> Exp rewrite e args = runIdentity (go ExpA e) where go :: Traversal AST Identity go ExpA e@(VarE v) = case findIndex (== v) vs of Nothing -> Identity e Just i -> Identity (args !! i) go w a = traverseFam go w a calcKernelDims :: CudaKernel -> [Exp] -> IO (CudaGridDim, CudaThreadBlockDim) calcKernelDims kern args = do let rewrite = cukernRewrite kern let bs = [(idx, rewrite e args) | (idx, e) <- cukernIdxs kern] let cudaIdxs = [(idx, bs') | dim <- [CudaDimX, CudaDimY, CudaDimZ] , idx <- [CudaThreadIdx dim, IrregCudaThreadIdx dim] , let bs' = idxBounds idx bs , not (null bs')] cudaGridDims cudaIdxs where -- Given a list of CUDA dimensions (x, y, z) and their bounds (each -- dimension may be used in more than one loop, leading to more than one -- bound), return an action in the 'Ex' monad that yields a pair consisting -- of the thread block dimensions and the grid dimensions. cudaGridDims :: [(Idx, [Exp])] -> IO (CudaGridDim, CudaThreadBlockDim) cudaGridDims [] = return ((1, 1, 1), (1, 1, 1)) cudaGridDims [(CudaThreadIdx CudaDimX, _)] = return ((128, 1, 1), (480, 1, 1)) cudaGridDims [(CudaThreadIdx CudaDimX, _), (CudaThreadIdx CudaDimY, _)] = return ((32, 32, 1), (16, 8, 1)) cudaGridDims [(IrregCudaThreadIdx CudaDimX, _), (IrregCudaThreadIdx CudaDimY, _)] = return ((16, 1, 1), (32, 32, 1)) cudaGridDims _ = error "cudaGridDims: failed to compute grid dimensions" -- Given a CUDA dimension (x, y, or z) and a list of indices and their -- bounds, return the list of bounds for the given CUDA dimension. idxBounds :: Idx -> [(Idx, Exp)] -> [Exp] idxBounds idx bs = [e | (idx', e) <- bs, idx' == idx] returnResultsByReference :: Dialect -> Context -> Context -> Type -> Bool returnResultsByReference _ callerCtx calleeCtx tau | isUnitT tau = False | calleeCtx == callerCtx && isBaseT tau = False | otherwise = True compileFun :: Dialect -> Context -> Context -> String -> [(Var, Type)] -> Type -> C CExp -> C CExp compileFun dialect callerCtx calleeCtx fname vtaus tau_ret mbody = do (ps, body) <- inNewFunction $ extendParams vtaus $ do cresult <- mbody if returnResultsByReference dialect callerCtx calleeCtx tau_ret then do cvresult <- toCResultParam (dialect, callerCtx, calleeCtx) tau_ret assignC cvresult cresult else addStm [cstm|return $cresult;|] case (dialect, callerCtx, calleeCtx) of (CUDA, Host, Host) -> addGlobal [cedeclCU|typename cudaError_t $id:fname($params:ps) { $items:body }|] (CUDA, Host, Kernel) -> addGlobal [cedeclCU|extern "C" __global__ void $id:fname($params:ps) { $items:body }|] (CUDA, Kernel, Kernel) -> addGlobal [cedeclCU|__device__ $ty:ctau_ret $id:fname($params:ps) { $items:body }|] (_, Host, Host) -> addGlobal [cedecl|$ty:ctau_ret $id:fname($params:ps) { $items:body }|] (_, Host, Kernel) -> addGlobal [cedecl|void $id:fname($params:ps) { $items:body }|] (_, Kernel, Kernel) -> addGlobal [cedecl|$ty:ctau_ret $id:fname($params:ps) { $items:body } |] (_, Kernel, Host) -> fail "Cannot call host function from device" return $ FunCE [cexp|$id:fname|] where ctau_ret :: C.Type ctau_ret = toCType tau_ret compileCall :: Dialect -- ^ Dialect -> Context -- ^ Caller's context -> Context -- ^ Callee's context -> Type -- ^ The type of the function to call -> [Exp] -- ^ Function arguments -> (Maybe CExp -> [C.Exp] -> C ()) -- ^ Function to generate the -- call given a destination for -- the result of the call and the -- arguments to the call -> C CExp -- ^ Result of calling the function compileCall dialect callerCtx calleeCtx tau args mcf = do tau_ret <- snd <$> checkFunT tau cargs <- concatMap toCArgs <$> mapM compileExp args let callCtx = (dialect, callerCtx, calleeCtx) case tau_ret of ScalarT UnitT -> do mcf Nothing cargs return VoidCE _ | calleeCtx == callerCtx && isBaseT tau_ret -> do cresult <- newCVar "call_result" tau_ret mcf (Just cresult) cargs return cresult | otherwise -> do toCResultArgs callCtx tau_ret $ \cresult cresultargs -> do mcf Nothing (cargs ++ cresultargs) return cresult -- -- Result codes -- declareResult :: Dialect -> C () declareResult CUDA = return () declareResult _ = addLocal [cdecl|int result = 0;|] failWithResult :: Dialect -> C.Exp -> C.Stm failWithResult CUDA _ = [cstm|goto done;|] failWithResult _ ce = [cstm|{ result = $ce; goto done; }|] returnResult :: Dialect -> C.Stm returnResult CUDA = [cstm|return cudaGetLastError();|] returnResult _ = [cstm|return result;|] -- -- Memory allocation -- declareHeap :: Dialect -> Int -> C () declareHeap dialect n = do addLocal [cdecl|void* allocs[$int:n];|] addLocal [cdecl|int marks[$int:n];|] addLocal [cdecl|int nallocs = 0;|] let free = case dialect of CUDA -> [cstm|cudaFree((char*) allocs[i]);|] _ -> [cstm|free(allocs[i]);|] addGlobal [cedecl|void gc(void **allocs, int* marks, int nallocs) { for (int i = 0; i < nallocs; ++i) { if (marks[i] == 0) { $stm:free allocs[i] = NULL; } marks[i] = 0; } } |] addGlobal [cedecl|void mark(void **allocs, int* marks, int nallocs, void* alloc) { for (int i = 0; i < nallocs; ++i) { if (allocs[i] == alloc) { marks[i] = 1; return; } } } |] gc :: C.Stm gc = [cstm|gc(allocs, marks, nallocs);|] mark :: CExp -> C () mark (VoidCE {}) = return () mark (ScalarCE {}) = return () mark (TupCE {}) = return () mark (ArrayCE ptr _) = go ptr where go :: PtrCExp -> C () go (PtrCE ce) = addStm [cstm|mark(allocs, marks, nallocs, $ce);|] go (TupPtrCE ptrs) = mapM_ go ptrs mark (FunCE _) = return () numAllocs :: Exp -> Int numAllocs p = getSum (go ExpA p) where go :: Fold AST (Sum Int) go ExpA (AllocE (ArrayT tau _) _) = Sum (numScalarTs tau) go w a = foldFam go w a numScalarTs :: ScalarType -> Int numScalarTs (TupleT taus) = sum (map numScalarTs taus) numScalarTs _ = 1 -- | Extend the current function's set of parameters extendParams :: [(Var, Type)] -> C a -> C a extendParams vtaus act = do cvs <- mapM toCParam vtaus extendVarTypes vtaus $ do extendVarTrans (vs `zip` cvs) $ do act where vs :: [Var] vs = map fst vtaus -- | Conversion to C type class IsCType a where toCType :: a -> C.Type instance IsCType ScalarType where toCType UnitT = [cty|void|] toCType BoolT = [cty|typename uint8_t|] toCType Int8T = [cty|typename int8_t|] toCType Int16T = [cty|typename int16_t|] toCType Int32T = [cty|typename int32_t|] toCType Int64T = [cty|typename int64_t|] toCType Word8T = [cty|typename uint8_t|] toCType Word16T = [cty|typename uint16_t|] toCType Word32T = [cty|typename uint32_t|] toCType Word64T = [cty|typename uint64_t|] toCType FloatT = [cty|float|] toCType DoubleT = [cty|double|] toCType (TupleT {}) = error "toCType: cannot convert tuple type to C type" instance IsCType PtrType where toCType (PtrT tau) = [cty|$ty:(toCType tau)*|] instance IsCType Type where toCType (ScalarT tau) = toCType tau toCType (ArrayT (TupleT {}) _) = error "toCType: cannot convert array of tuple to C type" toCType (ArrayT tau _) = [cty|$ty:(toCType tau)*|] toCType (FunT taus tau) = [cty|$ty:(toCType tau) (*)($params:params)|] where -- XXX not quite right... params :: [C.Param] params = map (\tau -> [cparam|$ty:(toCType tau)|]) (concatMap flattenT taus) toCType (MT tau) = toCType tau cIdxT :: C.Type cIdxT = toCType ixT -- | C variable allocation class NewCVar a where type CVar a :: * newCVar :: String -> a -> C (CVar a) instance NewCVar ScalarType where type CVar ScalarType = CExp newCVar _ UnitT = return VoidCE newCVar v (TupleT taus) = TupCE <$> mapM (newCVar v) taus newCVar v tau = do ctemp <- gensym v addLocal [cdecl|$ty:(toCType tau) $id:ctemp;|] return $ ScalarCE [cexp|$id:ctemp|] instance NewCVar PtrType where type CVar PtrType = PtrCExp newCVar _ (PtrT UnitT) = return $ PtrCE [cexp|NULL|] newCVar v (PtrT (TupleT taus)) = TupPtrCE <$> mapM (\tau -> newCVar v (PtrT tau)) taus newCVar v tau = do ctemp <- gensym v addLocal [cdecl|$ty:(toCType tau) $id:ctemp;|] return $ PtrCE [cexp|$id:ctemp|] instance NewCVar Type where type CVar Type = CExp newCVar v (ScalarT tau) = newCVar v tau newCVar v (ArrayT tau n) = do cptr <- newCVar v (PtrT tau) cdims <- replicateM n (newCVar vdim ixScalarT) return $ ArrayCE cptr cdims where vdim :: String vdim = v ++ "dim" newCVar v tau@(FunT {}) = do ctemp <- gensym v addLocal [cdecl|$ty:(toCType tau) $id:ctemp;|] return $ FunCE [cexp|$id:ctemp|] newCVar v (MT tau) = newCVar v tau -- | Type associated with a CExp thing type family CExpType a :: * type instance CExpType PtrCExp = PtrType type instance CExpType CExp = Type -- | C assignment class AssignC a where assignC :: a -- ^ Destination -> a -- ^ Source -> C () instance AssignC PtrCExp where assignC ce1@(PtrCE {}) ce2@(PtrCE {}) = addStm [cstm|$ce1 = $ce2;|] assignC (TupPtrCE ces1) (TupPtrCE ces2) | length ces1 == length ces2 = zipWithM_ assignC ces1 ces2 assignC ce1 ce2 = faildoc $ text "assignC: cannot assign" <+> ppr ce2 <+> text "to" <+> ppr ce1 instance AssignC CExp where assignC VoidCE VoidCE = return () assignC ce1@(ScalarCE {}) ce2@(ScalarCE {}) = addStm [cstm|$ce1 = $ce2;|] assignC (TupCE ces1) (TupCE ces2) | length ces1 == length ces2 = zipWithM_ assignC ces1 ces2 assignC (ArrayCE arr1 dims1) (ArrayCE arr2 dims2) | length dims1 == length dims2 = do assignC arr1 arr2 zipWithM_ assignC dims1 dims2 assignC (FunCE ce1) (FunCE ce2) = addStm [cstm|$ce1 = $ce2;|] assignC ce1 ce2 = faildoc $ text "assignC: cannot assign" <+> ppr ce2 <+> text "to" <+> ppr ce1 -- | Convert an 'a' into function parameters class IsCParam a where type CParam a :: * toCParam :: (Var, a) -> C (CParam a) toCResultParam :: (Dialect, Context, Context) -> a -> C (CParam a) instance IsCParam ScalarType where type CParam ScalarType = CExp toCParam (_, UnitT) = return VoidCE toCParam (v, TupleT taus) = TupCE <$> mapM (\tau -> toCParam (v, tau)) taus toCParam (v, tau) = do ctemp <- gensym (unVar v) addParam [cparam|$ty:(toCType tau) $id:ctemp|] return $ ScalarCE [cexp|$id:ctemp|] toCResultParam _ UnitT = return VoidCE toCResultParam ctx (TupleT taus) = TupCE <$> mapM (toCResultParam ctx) taus toCResultParam (CUDA, Host, Kernel) tau = do ctemp <- gensym "cuscalar_resultparam" addParam [cparam|$ty:ctau* $id:ctemp|] return $ ScalarCE [cexp|*$id:ctemp|] where ctau :: C.Type ctau = toCType tau toCResultParam _ tau = do ctemp <- gensym "scalar_resultparam" addParam [cparam|$ty:(toCType tau)* $id:ctemp|] return $ ScalarCE [cexp|*$id:ctemp|] instance IsCParam PtrType where type CParam PtrType = PtrCExp toCParam (_, PtrT UnitT) = return $ PtrCE [cexp|NULL|] toCParam (v, PtrT (TupleT taus)) = TupPtrCE <$> mapM (\tau -> toCParam (v, PtrT tau)) taus toCParam (v, PtrT tau) = do ctemp <- gensym (unVar v) addParam [cparam|$ty:(toCType tau)* $id:ctemp|] return $ PtrCE [cexp|$id:ctemp|] toCResultParam _ (PtrT UnitT) = return $ PtrCE [cexp|NULL|] toCResultParam ctx (PtrT (TupleT taus)) = TupPtrCE <$> mapM (toCResultParam ctx . PtrT) taus toCResultParam (CUDA, Host, Kernel) (PtrT tau) = do ctemp <- gensym "cuptr_resultparam" addParam [cparam|$ty:(toCType tau)** $id:ctemp|] return $ PtrCE [cexp|*$id:ctemp|] toCResultParam _ (PtrT tau) = do ctemp <- gensym "ptr_resultparam" addParam [cparam|$ty:(toCType tau)** $id:ctemp|] return $ PtrCE [cexp|*$id:ctemp|] instance IsCParam Type where type CParam Type = CExp toCParam (v, ScalarT tau) = toCParam (v, tau) toCParam (v, ArrayT tau n) = do cptr <- toCParam (v, PtrT tau) cdims <- replicateM n (toCParam (vdim, ixT)) return $ ArrayCE cptr cdims where vdim :: Var vdim = Var (unVar v ++ "dim") toCParam (v, tau@(FunT {})) = do ctemp <- gensym (unVar v) addParam [cparam|$ty:(toCType tau) $id:ctemp|] return $ FunCE [cexp|$id:ctemp|] toCParam (v, MT tau) = toCParam (v, tau) toCResultParam ctx (ScalarT tau) = toCResultParam ctx tau toCResultParam ctx (ArrayT tau n) = do cptr <- toCResultParam ctx (PtrT tau) cdims <- replicateM n (toCResultParam ctx ixT) return $ ArrayCE cptr cdims toCResultParam (CUDA, Host, Kernel) tau@(FunT {}) = do ctemp <- gensym "funresult_param" addParam [cparam|$ty:(toCType tau)* $id:ctemp|] return $ FunCE [cexp|*$id:ctemp|] toCResultParam _ tau@(FunT {}) = do ctemp <- gensym "funresult_param" addParam [cparam|$ty:(toCType tau)* $id:ctemp|] return $ FunCE [cexp|*$id:ctemp|] toCResultParam ctx (MT tau) = toCResultParam ctx tau -- | Convert an 'a' into a list of C function arguments. class IsCArg a where toCArgs :: a -> [C.Exp] instance IsCArg PtrCExp where toCArgs (PtrCE ce) = [[cexp|$ce|]] toCArgs (TupPtrCE es) = concatMap toCArgs es instance IsCArg CExp where toCArgs VoidCE = [] toCArgs (ScalarCE ce) = [[cexp|$ce|]] toCArgs (TupCE es) = concatMap toCArgs es toCArgs (ArrayCE ce dims) = toCArgs ce ++ concatMap toCArgs dims toCArgs (FunCE ce) = [ce] -- | Convert an 'a' into a list of C function result arguments class IsCResultArg a where type CResultArg a :: * toCResultArgs :: (Dialect, Context, Context) -> a -> (CResultArg a -> [C.Exp] -> C b) -> C b instance IsCResultArg a => IsCResultArg [a] where type CResultArg [a] = [CResultArg a] toCResultArgs ctx xs (kont :: [CResultArg a] -> [C.Exp] -> C b) = go [] [] xs where go :: [CResultArg a] -> [C.Exp] -> [a] -> C b go ces cargs [] = kont ces cargs go ces cargs (x:xs) = toCResultArgs ctx x $ \ces' cargs' -> go (ces ++ [ces']) (cargs ++ cargs') xs instance IsCResultArg ScalarType where type CResultArg ScalarType = CExp toCResultArgs _ UnitT kont = kont VoidCE [] toCResultArgs ctx (TupleT taus) kont = toCResultArgs ctx taus $ \ces cargs -> kont (TupCE ces) cargs toCResultArgs (CUDA, Host, Kernel) tau kont = do ce_h <- gensym "scalar_resultarg" ce_d <- gensym "cuscalar_resultarg" addLocal [cdecl|$ty:ctau $id:ce_h;|] addLocal [cdecl|$ty:ctau* $id:ce_d;|] addStm [cstm|cudaMalloc(&$id:ce_d, sizeof($ty:ctau));|] x <- kont (ScalarCE [cexp|$id:ce_h|]) [[cexp|$id:ce_d|]] addStm [cstm|cudaMemcpy(&$id:ce_h, $id:ce_d, sizeof($ty:ctau), cudaMemcpyDeviceToHost);|] addStm [cstm|cudaFree($id:ce_d);|] return x where ctau :: C.Type ctau = toCType tau toCResultArgs _ tau kont = do ce <- gensym "scalar_resultarg" addLocal [cdecl|$ty:(toCType tau) $id:ce;|] kont (ScalarCE [cexp|$id:ce|]) [[cexp|&$id:ce|]] instance IsCResultArg PtrType where type CResultArg PtrType = PtrCExp toCResultArgs ctx (PtrT (TupleT taus)) kont = toCResultArgs ctx (map PtrT taus) $ \ces cargs -> kont (TupPtrCE ces) cargs toCResultArgs (CUDA, Host, Kernel) (PtrT tau) kont = do ce_h <- gensym "ptr_resultarg" ce_d <- gensym "cuptr_resultarg" addLocal [cdecl|$ty:ctau* $id:ce_h = NULL;|] addLocal [cdecl|$ty:ctau** $id:ce_d = NULL;|] addStm [cstm|cudaMalloc(&$id:ce_d, sizeof($ty:ctau*));|] x <- kont (PtrCE [cexp|$id:ce_h|]) [[cexp|$id:ce_d|]] addStm [cstm|cudaMemcpy(&$id:ce_h, $id:ce_d, sizeof($ty:ctau*), cudaMemcpyDeviceToHost);|] addStm [cstm|cudaFree($id:ce_d);|] return x where ctau :: C.Type ctau = toCType tau toCResultArgs _ (PtrT tau) kont = do ce <- gensym "ptr_resultarg" addLocal [cdecl|$ty:ctau* $id:ce = NULL;|] x <- kont (PtrCE [cexp|$id:ce|]) [[cexp|&$id:ce|]] return x where ctau :: C.Type ctau = toCType tau instance IsCResultArg Type where type CResultArg Type = CExp toCResultArgs ctx (ScalarT tau) kont = toCResultArgs ctx tau kont toCResultArgs ctx (ArrayT tau n) kont = toCResultArgs ctx (PtrT tau) $ \ce_ptr cargs_ptr -> toCResultArgs ctx (replicate n ixT) $ \ces_dim cargs_dim -> kont (ArrayCE ce_ptr ces_dim) (cargs_ptr ++ cargs_dim) toCResultArgs _ tau@(FunT {}) kont = do ce_h <- gensym "fun_resultarg" ce_d <- gensym "cufun_resultarg" addLocal [cdecl|$ty:ctau* $id:ce_h = NULL;|] addLocal [cdecl|$ty:ctau** $id:ce_d = NULL;|] addStm [cstm|cudaMalloc(&$id:ce_d, sizeof($ty:ctau*));|] x <- kont (FunCE [cexp|$id:ce_h|]) [[cexp|$id:ce_h|]] addStm [cstm|cudaMemcpy(&$id:ce_h, $id:ce_d, sizeof($ty:ctau*), cudaMemcpyDeviceToHost);|] addStm [cstm|cudaFree($id:ce_d);|] return x where ctau :: C.Type ctau = toCType tau toCResultArgs ctx (MT tau) kont = toCResultArgs ctx tau kont -- -- Expression binding -- bindExp :: Maybe String -> Exp -> C CExp bindExp maybe_v e = do ce <- compileExp e if isAtomic ce then return ce else do tau <- inferExp e cv <- newCVar (maybe "temp" (++ "_") maybe_v) tau assignC cv ce return cv isAtomic :: CExp -> Bool isAtomic (ScalarCE (C.Var {})) = True isAtomic (ScalarCE (C.Const {})) = True isAtomic (TupCE ces) = all isAtomic ces isAtomic (ArrayCE _ ces) = all isAtomic ces isAtomic (FunCE {}) = True isAtomic _ = False
mainland/nikola
src/Data/Array/Nikola/Backend/C/Codegen.hs
bsd-3-clause
45,486
2
22
14,397
13,182
6,974
6,208
-1
-1
-- | Auxiliary functions for traversing recursive data structures such as -- grammars, and for converting mappings to arrays. module Data.Parser.Grempa.Auxiliary.Auxiliary where import Control.Monad.State import Data.Array import Data.Map(Map) import qualified Data.Map as M import Data.Maybe import Data.Set(Set) import qualified Data.Set as S setFromJust :: Ord a => Set (Maybe a) -> Set a setFromJust = S.map fromJust . S.delete Nothing -- | Traverse a recursive data structure without doing the same thing more -- than once and return a Set of results. Similar to a fold. -- Takes a function returning (result, candidates), then the initial set recTraverseG :: (Ord a, Ord b) => (Set a -> (Set b, Set a)) -- ^ Function returning (result, -- candidates) -> Set a -- ^ Input -> Set b recTraverseG = recTraverseG' S.empty where recTraverseG' done f x = if S.null cand' then res else res `S.union` recTraverseG' done' f cand' where (res, cand) = f x cand' = cand S.\\ done' done' = done `S.union` x -- | Traverse a recursive data structure where results and candidates is the -- same thing. recTraverse :: Ord a => (Set a -> Set a) -> Set a -> Set a recTraverse f = recTraverseG $ split . f where split x = (x, x) dot :: (c -> d) -> (a -> b -> c) -> a -> b -> d dot = (.) . (.) -- | State monad for keeping track of what values have already been computed type Done k v = State (Map k v) type DoneA k v = Done k v v -- | If the value has already been computed, return that, otherwise compute it! ifNotDoneG :: Ord k => k -> (v -> a) -> Done k v a -> Done k v a ifNotDoneG k ifDone action = do done <- getDone k case done of Just x -> return $ ifDone x Nothing -> action -- | See if a value has been computed already. getDone :: Ord k => k -> Done k v (Maybe v) getDone = gets . M.lookup -- | If the value has already been computed, return that, otherwise compute it! ifNotDone :: Ord k => k -> DoneA k v -> DoneA k v ifNotDone = flip ifNotDoneG id -- | Insert a value into the map of computed values. putDone :: Ord k => k -> v -> Done k v () putDone = modify `dot` M.insert -- | Get the result. evalDone :: Done k v a -> a evalDone = flip evalState M.empty -- | Convert a mapping to an array. -- Uses 'minimum' and 'maximum', which means that the Ix and Num instances -- must comply. class IxMinMax a where ixMax :: [a] -> a ixMin :: [a] -> a instance IxMinMax Int where ixMax = maximum ixMin = minimum instance (IxMinMax a, IxMinMax b) => IxMinMax (a, b) where ixMax xs = (ixMax fs, ixMax ss) where (fs, ss) = unzip xs ixMin xs = (ixMin fs, ixMin ss) where (fs, ss) = unzip xs -- | Convert a list of mappings to an array using the IxMinMax instance to -- determine the array bounds. listToArr :: (IxMinMax k, Ix k) => v -> [(k, v)] -> Array k v listToArr def ass = accumArray (flip const) def (ixMin keys, ixMax keys) ass where keys = map fst ass
ollef/Grempa
Data/Parser/Grempa/Auxiliary/Auxiliary.hs
bsd-3-clause
3,150
0
11
869
926
496
430
56
2
{-# LANGUAGE NoImplicitPrelude #-} module Protocol.ROC.PointTypes.PointType42 where import Data.Binary.Get (getByteString, Get) import Data.ByteString (ByteString) import Prelude (($), return, Eq, Float, Read, Show) import Protocol.ROC.Float (getIeeeFloat32) data PointType42 = PointType42 { pointType42PointTag :: !PointType42PointTag ,pointType42FlowToday :: !PointType42FlowToday ,pointType42FlowYesterday :: !PointType42FlowYesterday ,pointType42FlowMonth :: !PointType42FlowMonth ,pointType42FlowPrvsMonth :: !PointType42FlowPrvsMonth ,pointType42FlowAccum :: !PointType42FlowAccum ,pointType42MinutesToday :: !PointType42MinutesToday ,pointType42MinutesYesteray :: !PointType42MinutesYesteray ,pointType42MinutesMonth :: !PointType42MinutesMonth ,pointType42MinutesPrvsMonth :: !PointType42MinutesPrvsMonth ,pointType42MinutesAccum :: !PointType42MinutesAccum ,pointType42EnergyToday :: !PointType42EnergyToday ,pointType42EnergyYesterday :: !PointType42EnergyYesterday ,pointType42EnergyMonth :: !PointType42EnergyMonth ,pointType42EnergyPrvsMonth :: !PointType42EnergyPrvsMonth ,pointType42EnergyAccum :: !PointType42EnergyAccum ,pointType42UncrtdToday :: !PointType42UncrtdToday ,pointType42UncrtdYesterday :: !PointType42UncrtdYesterday ,pointType42UncrtdMonth :: !PointType42UncrtdMonth ,pointType42UncrtdPrvsMonth :: !PointType42UncrtdPrvsMonth ,pointType42UncrtdAccum :: !PointType42UncrtdAccum ,pointType42OrPlateBoreDiam :: !PointType42OrPlateBoreDiam ,pointType42MtrTubeIntDiamatFlowingTemp :: !PointType42MtrTubeIntDiamatFlowingTemp ,pointType42BetaDiamRatio :: !PointType42BetaDiamRatio ,pointType42EvApproachVelocity :: !PointType42EvApproachVelocity ,pointType42CdDischargeCoeff :: !PointType42CdDischargeCoeff ,pointType42ReynoldsNum :: !PointType42ReynoldsNum ,pointType42UpStrAbsoluteStaticPress :: !PointType42UpStrAbsoluteStaticPress ,pointType42MolecularWeight :: !PointType42MolecularWeight } deriving (Read,Eq, Show) type PointType42PointTag = ByteString type PointType42FlowToday = Float type PointType42FlowYesterday = Float type PointType42FlowMonth = Float type PointType42FlowPrvsMonth = Float type PointType42FlowAccum = Float type PointType42MinutesToday = Float type PointType42MinutesYesteray = Float type PointType42MinutesMonth = Float type PointType42MinutesPrvsMonth = Float type PointType42MinutesAccum = Float type PointType42EnergyToday = Float type PointType42EnergyYesterday = Float type PointType42EnergyMonth = Float type PointType42EnergyPrvsMonth = Float type PointType42EnergyAccum = Float type PointType42UncrtdToday = Float type PointType42UncrtdYesterday = Float type PointType42UncrtdMonth = Float type PointType42UncrtdPrvsMonth = Float type PointType42UncrtdAccum = Float type PointType42OrPlateBoreDiam = Float type PointType42MtrTubeIntDiamatFlowingTemp = Float type PointType42BetaDiamRatio = Float type PointType42EvApproachVelocity = Float type PointType42CdDischargeCoeff = Float type PointType42ReynoldsNum = Float type PointType42UpStrAbsoluteStaticPress = Float type PointType42MolecularWeight = Float pointType42Parser :: Get PointType42 pointType42Parser = do pointTag <- getByteString 10 flowToday <- getIeeeFloat32 flowYesterday <- getIeeeFloat32 flowMonth <- getIeeeFloat32 flowPrvsMonth <- getIeeeFloat32 flowAccum <- getIeeeFloat32 minutesToday <- getIeeeFloat32 minutesYesteray <- getIeeeFloat32 minutesMonth <- getIeeeFloat32 minutesPrvsMonth <- getIeeeFloat32 minutesAccum <- getIeeeFloat32 energyToday <- getIeeeFloat32 energyYesterday <- getIeeeFloat32 energyMonth <- getIeeeFloat32 energyPrvsMonth <- getIeeeFloat32 energyAccum <- getIeeeFloat32 uncrtdToday <- getIeeeFloat32 uncrtdYesterday <- getIeeeFloat32 uncrtdMonth <- getIeeeFloat32 uncrtdPrvsMonth <- getIeeeFloat32 uncrtdAccum <- getIeeeFloat32 orPlateBoreDiam <- getIeeeFloat32 mtrTubeIntDiamatFlowingTemp <- getIeeeFloat32 betaDiamRatio <- getIeeeFloat32 evApproachVelocity <- getIeeeFloat32 cdDischargeCoeff <- getIeeeFloat32 reynoldsNum <- getIeeeFloat32 upStrAbsoluteStaticPress <- getIeeeFloat32 molecularWeight <- getIeeeFloat32 return $ PointType42 pointTag flowToday flowYesterday flowMonth flowPrvsMonth flowAccum minutesToday minutesYesteray minutesMonth minutesPrvsMonth minutesAccum energyToday energyYesterday energyMonth energyPrvsMonth energyAccum uncrtdToday uncrtdYesterday uncrtdMonth uncrtdPrvsMonth uncrtdAccum orPlateBoreDiam mtrTubeIntDiamatFlowingTemp betaDiamRatio evApproachVelocity cdDischargeCoeff reynoldsNum upStrAbsoluteStaticPress molecularWeight
plow-technologies/roc-translator
src/Protocol/ROC/PointTypes/PointType42.hs
bsd-3-clause
9,208
0
9
5,055
755
418
337
164
1
{-# LANGUAGE DeriveGeneric #-} module Budget.Core.Data ( module Budget.Core.Data.Amount , module Budget.Core.Data.Category , module Budget.Core.Data.Date , module Budget.Core.Data.Item , module Budget.Core.Data.ItemTemplate , module Budget.Core.Data.Income , module Budget.Core.Data.Expense ) where import GHC.Generics import Control.Monad (mzero) import Data.Aeson import Data.Monoid import Data.Time import Budget.Core.Data.Amount import Budget.Core.Data.Category import Budget.Core.Data.Date import Budget.Core.Data.Item import Budget.Core.Data.ItemTemplate (ItemTemplate, NewItemTemplateR(..), newItemTemplateName, newItemTemplateCategoryId) import Budget.Core.Data.Income (Income) import Budget.Core.Data.Expense (Expense) -- Primitives -- ================================================================== data Saving = Saving { amount :: Item } -- Methods -- ================================================================== -- Tag types -- ================================================================== {-| Category of expense. -} data ExpenseClass = FixedCost | VariableCost deriving (Eq)
utky/budget
src/Budget/Core/Data.hs
bsd-3-clause
1,277
0
8
269
212
146
66
28
0
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE ViewPatterns #-} ------------------------------------------------------------------------------------- -- | -- Copyright : (c) Hans Hoglund 2012-2014 -- -- License : BSD-style -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : non-portable (TF,GNTD) -- ------------------------------------------------------------------------------------- module Music.Score.Export.Lilypond ( -- * Lilypond backend HasLilypondInstrument(..), Lilypond, LyContext(..), HasLilypond, -- ** Converting to Lilypond toLilypond, toLilypondString, -- ** Lilypond I/O showLilypond, openLilypond, writeLilypond, -- ** Customize Lilypond backend LilypondOptions(..), openLilypond', writeLilypond', ) where import Control.Applicative import Control.Comonad (Comonad (..), extract) import Control.Lens hiding (rewrite) import Control.Monad import Data.AffineSpace import Data.Bifunctor import Data.Colour.Names as Color import Data.Either import Data.Foldable (Foldable) import Data.Functor.Adjunction (unzipR) import Data.Functor.Context -- import Data.Functor.Contravariant import Data.Functor.Couple import qualified Data.List import Data.Maybe import Data.Ratio import Data.Semigroup import Data.Traversable (Traversable, sequenceA) import Data.VectorSpace hiding (Sum (..)) import System.Process import qualified Text.Pretty as Pretty import Music.Dynamics.Literal import Music.Pitch.Literal import Music.Score.Articulation import Music.Score.Color import Music.Score.Dynamics import Music.Score.Export.ArticulationNotation import Music.Score.Export.Backend import Music.Score.Export.Backend import Music.Score.Export.DynamicNotation import Music.Score.Harmonics import Music.Score.Internal.Export hiding (MVoice) import Music.Score.Internal.Util (composed, retainUpdates, swap, unRatio, withPrevNext) import Music.Score.Meta import Music.Score.Meta.Time import Music.Score.Meta.Title import Music.Score.Meta.Attribution import Music.Score.Part import Music.Score.Phrases import Music.Score.Slide import Music.Score.Text import Music.Score.Ties import Music.Score.Tremolo import Music.Time import Music.Score.Internal.Quantize import Music.Score.Internal.Data (getData) import qualified Data.Music.Lilypond as Lilypond #define COMPLEX_POLY_STUFF 1 -- | -- Extract instrument info as per "Music.Part" -- This is really crude, needs rethinking! -- class HasLilypondInstrument a where getLilypondClef :: a -> Int {- TODO rewrite so that: - Each bar may include voices/layers (a la Sibelius) - Each part may generate more than one staff (for piano etc) -} -- | A token to represent the Lilypond backend. data Lilypond data ScoreInfo = ScoreInfo deriving (Eq, Show) data StaffInfo = StaffInfo { staffName :: String, staffClef :: Lilypond.Clef } deriving (Eq, Show) data BarInfo = BarInfo { barTimeSignature :: Maybe TimeSignature } deriving (Eq, Show) -- | Hierachical representation of a Lilypond score. -- A score is a parallel composition of staves. data LyScore a = LyScore { getLyScore :: (ScoreInfo, [LyStaff a]) } deriving (Functor, Eq, Show) -- | A staff is a sequential composition of bars. data LyStaff a = LyStaff { getLyStaff :: (StaffInfo, [LyBar a]) } deriving (Functor, Eq, Show) -- | A bar is a sequential composition of chords/notes/rests. data LyBar a = LyBar { getLyBar :: (BarInfo, Rhythm a) } deriving (Functor, Eq, Show) -- | Context passed to the note export. -- Includes duration and note/rest distinction. data LyContext a = LyContext Duration (Maybe a) deriving (Functor, Foldable, Traversable, Eq, Show) {- TODO move instance Monoid LyMusic where mempty = pcatL [] mappend x y = pcatL [x,y] -} type LyMusic = Lilypond.Music instance HasBackend Lilypond where type BackendScore Lilypond = LyScore type BackendContext Lilypond = LyContext type BackendNote Lilypond = LyMusic type BackendMusic Lilypond = LyMusic finalizeExport _ = finalizeScore where finalizeScore :: LyScore LyMusic -> LyMusic finalizeScore (LyScore (info, x)) = pcatL . map finalizeStaff $ x -- TODO finalizeStaffGroup finalizeStaff :: LyStaff LyMusic -> LyMusic finalizeStaff (LyStaff (info, x)) = addStaff . addPartName (staffName info) . addClef (staffClef info) . scatL . map finalizeBar $ x where addStaff = Lilypond.New "Staff" Nothing addClef c x = scatL [Lilypond.Clef c, x] addPartName partName xs = scatL [longName, shortName, xs] where longName = Lilypond.Set "Staff.instrumentName" (Lilypond.toValue partName) shortName = Lilypond.Set "Staff.shortInstrumentName" (Lilypond.toValue partName) finalizeBar :: LyBar LyMusic -> LyMusic finalizeBar (LyBar (BarInfo timeSignature, x)) = (setTimeSignature `ifJust` timeSignature) . renderBarMusic $ x where ifJust = maybe id -- TODO key signatures -- TODO rehearsal marks -- TODO bar number change -- TODO compound time signatures setTimeSignature (getTimeSignature -> (ms, n)) x = scatL [Lilypond.Time (sum ms) n, x] renderBarMusic :: Rhythm LyMusic -> LyMusic renderBarMusic = go where go (Beat d x) = Lilypond.removeSingleChords x go (Dotted n (Beat d x)) = Lilypond.removeSingleChords x go (Group rs) = scatL $ map renderBarMusic rs go (Tuplet m r) = Lilypond.Times (realToFrac m) (renderBarMusic r) where (a,b) = bimap fromIntegral fromIntegral $ unRatio $ realToFrac m #ifdef COMPLEX_POLY_STUFF instance ( HasDynamicNotation a b c, HasArticulationNotation c d e, Part e ~ Part c, HasOrdPart a, Transformable a, Semigroup a, Tiable e, HasOrdPart c, Show (Part c), HasLilypondInstrument (Part c), Satisfied ) => HasBackendScore Lilypond (Score a) where #else instance ( Tiable a, HasOrdPart a, Show (Part a), HasLilypondInstrument (Part a), Satisfied ) => HasBackendScore Lilypond (Score a) where #endif #ifdef COMPLEX_POLY_STUFF type BackendScoreEvent Lilypond (Score a) = SetArticulation ArticulationNotation (SetDynamic DynamicNotation a) #else type BackendScoreEvent Lilypond (Score a) = a #endif exportScore b score = LyScore . (ScoreInfo,) -- Store time signatures etc for later use by finalizeScore . map (uncurry $ exportPart timeSignatureMarks barDurations) . notateAspects . extractPartsWithInfo $ normScore where -- notateAspects :: [(part,score)] notateAspects = id #ifdef COMPLEX_POLY_STUFF -- Notate articulation . map (second $ over articulations notateArticulation) . map (second $ preserveMeta addArtCon) -- Notate dynamics . map (second $ removeCloseDynMarks) . map (second $ over dynamics notateDynamic) . map (second $ preserveMeta addDynCon) -- Merge simultaneous chords . map (second $ preserveMeta simultaneous) #endif (timeSignatureMarks, barDurations) = extractTimeSignatures normScore normScore = normalizeScore score -- | Export a score as a single part. Overlapping notes will cause an error. exportPart :: ( Show (Part a), HasLilypondInstrument (Part a), Tiable a ) => [Maybe TimeSignature] -> [Duration] -> Part a -> Score a -> LyStaff (LyContext a) exportPart timeSignatureMarks barDurations part = exportStaff timeSignatureMarks barDurations (show part) (getLilypondClef part) . view oldSingleMVoice exportStaff :: Tiable a => [Maybe TimeSignature] -> [Duration] -> String -- ^ name -> Int -- ^ clef, as per Music.Parts -> MVoice a -> LyStaff (LyContext a) exportStaff timeSignatures barDurations name clefId = LyStaff . addStaffInfo . zipWith exportBar timeSignatures . splitIntoBars barDurations where clef = case clefId of 0 -> Lilypond.Treble 1 -> Lilypond.Alto 2 -> Lilypond.Bass addStaffInfo = (,) $ StaffInfo { staffName = name, staffClef = clef } splitIntoBars = splitTiesAt exportBar :: Tiable a => Maybe TimeSignature -> MVoice a -> LyBar (LyContext a) exportBar timeSignature = LyBar . addBarInfo . quantizeBar where addBarInfo = (,) $ BarInfo timeSignature quantizeBar :: Tiable a => MVoice a -> Rhythm (LyContext a) -- Note: this is when quantized duration escapes to LyContext! quantizeBar = mapWithDur LyContext . rewrite . handleErrors . quantize . view pairs where -- FIXME propagate quantization errors handleErrors (Left e) = error $ "Quantization failed: " ++ e handleErrors (Right x) = x -------------------------------------------------------------------------------- {- Note: We want all note transformers to be applicative morphisms, i.e. notate (pure x) = pure (notate x) Specifically notate (mempty,x) = id . notate x Note: We use these idioms: exportNote b = exportNote b . fmap extract exportNote b = uncurry notate . fmap (exportNote b) . getTieT . sequenceA The latter looks a lot like cotraverse. Generalization? -} instance HasBackendNote Lilypond a => HasBackendNote Lilypond [a] where exportNote = exportChord instance HasBackendNote Lilypond Integer where -- TODO can we get rid of exportChord alltogether and just use LyContext? exportNote _ (LyContext d Nothing) = (^*realToFrac (4*d)) Lilypond.rest exportNote _ (LyContext d (Just x)) = (^*realToFrac (4*d)) $ Lilypond.note $ spellL x exportChord _ (LyContext d Nothing) = (^*realToFrac (4*d)) Lilypond.rest exportChord _ (LyContext d (Just xs)) = (^*realToFrac (4*d)) $ Lilypond.chord $ fmap spellL xs instance HasBackendNote Lilypond Int where exportNote b = exportNote b . fmap toInteger exportChord b = exportChord b . fmap (fmap toInteger) instance HasBackendNote Lilypond Float where exportNote b = exportNote b . fmap (toInteger . round) exportChord b = exportChord b . fmap (fmap (toInteger . round)) instance HasBackendNote Lilypond Double where exportNote b = exportNote b . fmap (toInteger . round) exportChord b = exportChord b . fmap (fmap (toInteger . round)) instance Integral a => HasBackendNote Lilypond (Ratio a) where exportNote b = exportNote b . fmap (toInteger . round) instance HasBackendNote Lilypond a => HasBackendNote Lilypond (Behavior a) where exportNote b = exportNote b . fmap (! 0) exportChord b = exportChord b . fmap (fmap (! 0)) instance HasBackendNote Lilypond a => HasBackendNote Lilypond (Sum a) where exportNote b = exportNote b . fmap getSum instance HasBackendNote Lilypond a => HasBackendNote Lilypond (Product a) where exportNote b = exportNote b . fmap getProduct instance HasBackendNote Lilypond a => HasBackendNote Lilypond (PartT n a) where -- Part structure is handled by HasMidiBackendScore instances, so this is just an identity exportNote b = exportNote b . fmap extract exportChord b = exportChord b . fmap (fmap extract) #ifdef COMPLEX_POLY_STUFF instance HasBackendNote Lilypond a => HasBackendNote Lilypond (DynamicT DynamicNotation a) where exportNote b = uncurry notate . getDynamicT . fmap (exportNote b) . sequenceA where notate :: DynamicNotation -> LyMusic -> LyMusic notate (DynamicNotation (crescDims, level)) = rcomposed (fmap notateCrescDim crescDims) . notateLevel level notateCrescDim crescDims = case crescDims of NoCrescDim -> id BeginCresc -> Lilypond.beginCresc EndCresc -> Lilypond.endCresc BeginDim -> Lilypond.beginDim EndDim -> Lilypond.endDim -- TODO these literals are not so nice... notateLevel showLevel = case showLevel of Nothing -> id Just lvl -> Lilypond.addDynamics (fromDynamics (DynamicsL (Just (fixLevel . realToFrac $ lvl), Nothing))) fixLevel :: Double -> Double fixLevel x = fromIntegral (round (x - 0.5)) + 0.5 -- Use rcomposed as notateDynamic returns "mark" order, not application order rcomposed = composed . reverse #else instance HasBackendNote Lilypond a => HasBackendNote Lilypond (DynamicT b a) where exportNote b = exportNote b . fmap extract #endif #ifdef COMPLEX_POLY_STUFF instance HasBackendNote Lilypond a => HasBackendNote Lilypond (ArticulationT ArticulationNotation a) where exportNote b = uncurry notate . getArticulationT . fmap (exportNote b) . sequenceA where notate :: ArticulationNotation -> LyMusic -> LyMusic notate (ArticulationNotation (slurs, marks)) = rcomposed (fmap notateMark marks) . rcomposed (fmap notateSlur slurs) notateMark mark = case mark of NoMark -> id Staccato -> Lilypond.addStaccato MoltoStaccato -> Lilypond.addStaccatissimo Marcato -> Lilypond.addMarcato Accent -> Lilypond.addAccent Tenuto -> Lilypond.addTenuto notateSlur slurs = case slurs of NoSlur -> id BeginSlur -> Lilypond.beginSlur EndSlur -> Lilypond.endSlur -- Use rcomposed as notateDynamic returns "mark" order, not application order rcomposed = composed . reverse #else instance HasBackendNote Lilypond a => HasBackendNote Lilypond (ArticulationT {-ArticulationNotation-}b a) where exportNote b = exportNote b . fmap extract #endif instance HasBackendNote Lilypond a => HasBackendNote Lilypond (ColorT a) where exportNote b = uncurry notate . getCouple . getColorT . fmap (exportNote b) . sequenceA where -- TODO This syntax will change in future Lilypond versions -- TODO handle any color notate (Option Nothing) = id notate (Option (Just (Last color))) = \x -> Lilypond.Sequential [ Lilypond.Override "NoteHead#' color" (Lilypond.toLiteralValue $ "#" ++ colorName color), x, Lilypond.Revert "NoteHead#' color" ] colorName c | c == Color.black = "black" | c == Color.red = "red" | c == Color.blue = "blue" | otherwise = error "Lilypond backend: Unkown color" instance HasBackendNote Lilypond a => HasBackendNote Lilypond (TremoloT a) where -- TODO can this instance use the new shorter idiom? exportNote b (LyContext d x) = fst (notateTremolo x d) $ exportNote b $ LyContext (snd $ notateTremolo x d) (fmap extract x) instance HasBackendNote Lilypond a => HasBackendNote Lilypond (TextT a) where exportNote b = uncurry notateText . getCouple . getTextT . fmap (exportNote b) . sequenceA where instance HasBackendNote Lilypond a => HasBackendNote Lilypond (HarmonicT a) where exportNote b = uncurry notateHarmonic . getCouple . getHarmonicT . fmap (exportNote b) . sequenceA instance HasBackendNote Lilypond a => HasBackendNote Lilypond (SlideT a) where exportNote b = uncurry notateGliss . getCouple . getSlideT . fmap (exportNote b) . sequenceA exportChord b = uncurry notateGliss . getCouple . getSlideT . fmap (exportChord b) . sequenceA . fmap sequenceA {- exportNote :: b -> BC a -> BN exportChord :: b -> BC [a] -> BN uncurry notateTie :: ((Any, Any), LyMusic) -> LyMusic BC (TieT a) sequenceA TieT (BC a) fmap (exportNote b) TieT BN notate . getTieT BN BC [TieT a] fmap sequenceA BC (TieT [a]) sequenceA TieT (BC [a]) fmap (exportChord b) TieT BN notate . getTieT BN -} instance HasBackendNote Lilypond a => HasBackendNote Lilypond (TieT a) where exportNote b = uncurry notateTie . getTieT . fmap (exportNote b) . sequenceA exportChord b = uncurry notateTie . getTieT . fmap (exportChord b) . sequenceA . fmap sequenceA notateTremolo :: RealFrac b => Maybe (TremoloT a) -> b -> (LyMusic -> LyMusic, b) notateTremolo Nothing d = (id, d) notateTremolo (Just (runTremoloT -> (0, _))) d = (id, d) notateTremolo (Just (runTremoloT -> (n, _))) d = let scale = 2^n newDur = (d `min` (1/4)) / scale repeats = d / newDur in (Lilypond.Tremolo (round repeats), newDur) notateText :: [String] -> LyMusic -> LyMusic notateText texts = composed (fmap Lilypond.addText texts) notateHarmonic :: (Eq t, Num t) => (Any, Sum t) -> LyMusic -> LyMusic notateHarmonic (Any isNat, Sum n) = case (isNat, n) of (_, 0) -> id (True, n) -> notateNatural n (False, n) -> notateArtificial n where notateNatural n = Lilypond.addFlageolet -- addOpen? notateArtificial n = id -- TODO notateGliss :: ((Any, Any), (Any, Any)) -> LyMusic -> LyMusic notateGliss ((Any eg, Any es),(Any bg, Any bs)) | bg = Lilypond.beginGlissando | bs = Lilypond.beginGlissando | otherwise = id notateTie :: (Any, Any) -> LyMusic -> LyMusic notateTie (Any ta, Any tb) | ta && tb = Lilypond.beginTie | tb = Lilypond.beginTie | ta = id | otherwise = id -- | -- Constraint for types that has a Lilypond representation. -- type HasLilypond a = (HasBackendNote Lilypond (BackendScoreEvent Lilypond a), HasBackendScore Lilypond a) -- | -- Convert a score to a Lilypond representation. -- toLilypond :: HasLilypond a => a -> LyMusic toLilypond = export (undefined::Lilypond) -- | -- Convert a score to a Lilypond string. -- toLilypondString :: HasLilypond a => a -> String toLilypondString = show . Pretty.pretty . toLilypond -- | -- Convert a score to a Lilypond representaiton and print it on the standard output. -- showLilypond :: HasLilypond a => a -> IO () showLilypond = putStrLn . toLilypondString -- | -- Convert a score to a Lilypond representation and write to a file. -- writeLilypond :: HasLilypond a => FilePath -> a -> IO () writeLilypond = writeLilypond' mempty data LilypondOptions = LyInlineFormat | LyScoreFormat | LyLargeScoreFormat instance Monoid LilypondOptions where mempty = LyInlineFormat mappend = const -- | -- Convert a score to a Lilypond representation and write to a file. -- writeLilypond' :: HasLilypond a => LilypondOptions -> FilePath -> a -> IO () writeLilypond' options path sc = writeFile path $ (lyFilePrefix ++) $ toLilypondString sc where -- title = fromMaybe "" $ flip getTitleAt 0 $ metaAtStart sc -- composer = fromMaybe "" $ flip getAttribution "composer" $ metaAtStart sc title = "" composer = "" -- TODO generalize metaAtStart! lyFilePrefix = case options of LyInlineFormat -> lyInlinePrefix LyScoreFormat -> lyScorePrefix LyLargeScoreFormat -> getData "ly_big_score.ily" -- TODO use files for other headers as well lyInlinePrefix = mempty ++ "%%% Generated by music-score %%%\n" ++ "\\include \"lilypond-book-preamble.ly\"\n" ++ "\\paper {\n" ++ " #(define dump-extents #t)\n" ++ "\n" ++ " indent = 0\\mm\n" ++ " line-width = 210\\mm - 2.0 * 0.4\\in\n" ++ " ragged-right = ##t\n" ++ " force-assignment = #\"\"\n" ++ " line-width = #(- line-width (* mm 3.000000))\n" ++ "}\n" ++ "\\header {\n" ++ " title = \"" ++ title ++ "\"\n" ++ " composer = \"" ++ composer ++ "\"\n" ++ "}\n" ++ "\\layout {\n" ++ "}" ++ "\n\n" lyScorePrefix = mempty ++ "\\paper {" ++ " indent = 0\\mm" ++ " line-width = 210\\mm - 2.0 * 0.4\\in" ++ "}" ++ "\\header {\n" ++ " title = \"" ++ title ++ "\"\n" ++ " composer = \"" ++ composer ++ "\"\n" ++ "}\n" ++ "\\layout {" ++ "}" ++ "\n\n" -- | -- Typeset a score using Lilypond and open it. (This is simple wrapper around -- 'writeLilypond' that may not work well on all platforms.) -- openLilypond :: HasLilypond a => a -> IO () openLilypond = openLilypond' mempty -- | -- Typeset a score using Lilypond and open it. (This is simple wrapper around -- 'writeLilypond' that may not work well on all platforms.) -- openLilypond' :: HasLilypond a => LilypondOptions -> a -> IO () openLilypond' options sc = do writeLilypond' options "test.ly" sc runLilypond >> cleanLilypond >> runOpen where runLilypond = void $ runCommand -- "lilypond -f pdf test.ly" >>= waitForProcess "lilypond -f pdf test.ly 2>/dev/null" >>= waitForProcess cleanLilypond = void $ runCommand "rm -f test-*.tex test-*.texi test-*.count test-*.eps test-*.pdf test.eps" runOpen = void $ runCommand $ openCommand ++ " test.pdf" pcatL :: [LyMusic] -> LyMusic pcatL = pcatL' False pcatL' :: Bool -> [LyMusic] -> LyMusic pcatL' p = foldr Lilypond.simultaneous (Lilypond.Simultaneous p []) scatL :: [LyMusic] -> LyMusic scatL = foldr Lilypond.sequential (Lilypond.Sequential []) spellL :: Integer -> Lilypond.Note spellL a = Lilypond.NotePitch (spellL' a) Nothing spellL' :: Integer -> Lilypond.Pitch spellL' p = Lilypond.Pitch ( toEnum $ fromIntegral pc, fromIntegral alt, fromIntegral oct ) where (pc,alt,oct) = spellPitch (p + 72) -- | A constraint that is always satisfied. type Satisfied = (() ~ ()) -- | A constraint that is never satisfied. type Unsatisfied = (() ~ Bool)
FranklinChen/music-score
src/Music/Score/Export/Lilypond.hs
bsd-3-clause
24,372
0
28
7,373
5,236
2,773
2,463
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module System.Sound where import Control.Monad.State import Data.ECS import Control.Lens.Extra import Data.Yaml import GHC.Generics data SoundSystem = SoundSystem { _ssBlah :: Int } deriving Show defineSystemKey ''SoundSystem makeLenses ''SoundSystem data SoundSource = SoundSource { scChannel :: Int , scSourceID :: Int } deriving (Show, Generic, FromJSON, ToJSON) defineComponentKey ''SoundSource initSystemSound :: (MonadState ECS m) => m () initSystemSound = do registerSystem sysSound (SoundSystem 0) registerComponent "SoundSource" mySoundSource (newComponentInterface mySoundSource) tickSystemSound :: (MonadState ECS m, MonadIO m) => m () tickSystemSound = modifySystemState sysSound $ do newValue <- ssBlah <+= 1 liftIO . print $ newValue
lukexi/extensible-ecs
app/System/Sound.hs
bsd-3-clause
915
0
9
147
236
125
111
26
1
module Lib ( baseIntegral , sqrIntegral ) where import Prelude hiding ((.)) import Control.Wire import FRP.Netwire baseIntegral :: (Monad m, HasTime t s, Fractional a) => Wire s () m a a baseIntegral = integral 0 . 1 sqrIntegral :: (Monad m, HasTime t s, Fractional t) => Wire s () m a t sqrIntegral = integral 0 . time
rmcmaho/tasklib
src/Lib.hs
bsd-3-clause
337
0
7
77
139
76
63
10
1
module Enemy where import Types.Hitbox import Types.Drawable import Graphics.Gloss.Data.Vector import Graphics.Gloss.Data.Point class (Drawable a, Hitbox a)=>Enemy a where health :: a -> Int moveV :: a -> Vector xy :: a -> (Point, Point)
Smurf/dodgem
src/Types/Enemy.hs
bsd-3-clause
267
0
8
63
85
50
35
9
0
-- Testcases for assertion optimization and Ivory to ACL2 compilation. {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} module Main (main) where import qualified Language.ACL2 as A import Ivory.Language import Ivory.Compile.ACL2 import Ivory.Opts.Asserts main :: IO () main = do -- Tests of assertion optimization, i.e. verification and removal of assertions. _ <- assertsFold [Progress, Failure] {-, VC, VCOpt, ACL2, ACL2Result] -} $ [ package "assertsFoldTest" $ do incl factorial incl intrinsicTest incl wait incl waitLoop incl loopTest incl structTest incl arrayTest ] -- Tests of Ivory-to-ACL2 compilation. testThm "factorial 4 == 24" factorial $ A.equal 24 $ A.cdr $ A.call "factorial" [A.nil, 4] testThm "arrayTest == 6" arrayTest $ A.equal 6 $ A.cdr $ A.call "arrayTest" [A.nil] testThm "loopTest 8 == 8" loopTest $ A.equal 8 $ A.cdr $ A.call "loopTest" [A.nil, 8] testThm "structTest == 22" structTest $ A.equal 22 $ A.cdr $ A.call "structTest" [A.nil] where testThm name func thm = do pass <- A.check $ compile (package name $ incl func) ++ [A.thm thm] if pass then putStrLn $ "pass: " ++ name else putStrLn $ "FAIL: " ++ name intrinsicTest :: Def ('[IBool, Sint32] :-> ()) intrinsicTest = proc "intrinsicTest" $ \ cond1 num1 -> requires (num1 ==? 22) $ body $ do -- Tests of basic expressions. assert $ true assert $ iNot false assert $ 1 + 2 ==? (3 :: Sint32) assert $ iNot $ 1 + 2 ==? (4 :: Sint32) assert $ 3 - 2 ==? (1 :: Sint32) assert $ iNot $ 2 - 2 ==? (1 :: Sint32) assert $ 1 /=? (2 :: Sint32) assert $ iNot $ 1 /=? (1 :: Sint32) assert $ 1 <? (2 :: Sint32) assert $ 3 >? (2 :: Sint32) assert $ 1 <=? (1 :: Sint32) assert $ 3 >=? (3 :: Sint32) assert $ iNot false assert $ iNot $ iNot true assert $ iNot $ iNot $ iNot false assert $ iNot $ iNot $ iNot $ iNot true assert $ (false .&& false) ==? false assert $ (false .&& true ) ==? false assert $ (true .&& false) ==? false assert $ (true .&& true ) ==? true assert $ (false .|| false) ==? false assert $ (false .|| true ) ==? true assert $ (true .|| false) ==? true assert $ (true .|| true ) ==? true assert $ true ? (true , false) assert $ true ? (true , true ) assert $ false ? (false, true ) assert $ false ? (true , true ) assert $ (3 .% 7) ==? (3 :: Sint32) assert $ negate 3 ==? (-3 :: Sint32) assert $ abs (-3) ==? (3 :: Sint32) assert $ signum 0 ==? (0 :: Sint32) -- Test of preconditions. assert $ num1 ==? 22 -- Test of refs and branches. ref <- local (ival 0) ifte_ cond1 (do { assert cond1; store ref (22 :: Sint32) }) (do { assert $ iNot cond1; store ref (44 :: Sint32) }) assert $ cond1 .|| iNot cond1 n <- deref ref assert $ implies cond1 (n ==? 22) assert $ implies (iNot cond1) (n ==? 44) -- A test of assumptions. --assume false --assert false retVoid implies :: IBool -> IBool -> IBool implies a b = iNot a .|| b wait :: Def ('[Sint32, Sint32] :-> Sint32) wait = proc "wait" $ \ n i -> requires (n >=? 0) $ requires (i >? 0) $ ensures (\ result -> result >? 0) $ ensures (\ result -> result >? 10) $ body $ do iters <- local (ival 0) call_ waitLoop n i iters itersValue <- deref iters ret itersValue waitLoop :: Def ('[Sint32, Sint32, Ref s (Stored Sint32)] :-> ()) waitLoop = proc "waitLoop" $ \ n i iters -> requires (checkStored iters (>=? 0)) $ ensures_ (checkStored iters (>=? 0)) $ -- XXX How are these passing? Is this a problem with recursion? body $ do ifte_ (n >? 0) ( do itersValue <- deref iters store iters $ itersValue + 1 assert $ n >? i assert $ i >? 0 call_ waitLoop (n - i) i iters retVoid ) retVoid -- Factorial of a number. factorial :: Def ('[Sint32] :-> Sint32) factorial = proc "factorial" $ \ n -> requires (n >=? 1) $ ensures (>=? n) $ body $ ifte_ (n >? 1) (do n' <- call factorial (n - 1) ret (n' * n) ) (do ret n) -- A test of loops and arrays. loopTest :: Def ('[Ix 10] :-> Uint32) loopTest = proc "loopTest" $ \ix -> ensures (<=? 10) $ body $ do ref <- local (ival 0) ix `times` \_ -> do n <- deref ref store ref (n+1) ret =<< deref ref --struct Foo { i :: Stored Uint32 } --[ivory| --struct Bar { name :: Array 32 (Stored Uint32) } -- |] [ivory| struct Foo { i :: Stored Uint32 } --struct Bar { name :: Array 32 (Stored Uint32) } |] structTest :: Def ('[] :-> Uint32) structTest = proc "structTest" $ ensures (==? 22) $ body $ do struct <- local $ istruct [ i .= ival 22 ] a <- deref $ struct ~> i ret a arrayTest :: Def ('[] :-> Uint32) arrayTest = proc "arrayTest" $ ensures (==? 6) $ body $ do -- Allocate a 4 element array with zeros: [0, 0, 0, 0] (array :: Ref (Stack cs) (Array 4 (Stored Uint32))) <- local $ iarray $ replicate 4 $ ival 0 -- Iterate over the array making it: [0, 1, 2, 3] arrayMap $ \ i -> store (array ! i) $ safeCast i --XXX Having both this loop and the loop below gives ACL2 troubles. -- Create a reference to sum the elements in the array. sum <- local $ ival (0 :: Uint32) -- Loop across the array summing the elements. arrayMap $ \ i -> do n <- deref sum m <- deref $ array ! i store sum $ n + m -- Return the computed sum. deref sum >>= ret
GaloisInc/ivory-backend-acl2
Testcases.hs
bsd-3-clause
5,648
0
16
1,516
2,134
1,070
1,064
138
2
-- | Holds the default definition string. module Data.Quantities.DefaultUnits (defaultDefString) where -- | View the source code for this declaration to see what units and prefixes -- are defined by default. -- -- This string holds the definitions for units and prefixes. Base units are -- defined by the name of the unit, the name of the base in brackets, and any -- aliases for the unit after that, all separated by equal signs: @meter = -- [length] = m@. Prefixes are defined by placing a dash after all identifiers, -- and providing a value for the prefix: @milli- = 1e-3 = m-@. Other units are -- defined by using /previously defined units/ in an expression: @minute = 60 * -- second = min@. -- -- The reason these definitions aren't placed in a text file is so you don't -- have to operate your whole program in the IO monad. Users can copy this file -- into their source and modify definitions, or simply add a few definitions to -- the end of this string. -- -- These definitions are taken almost verbatim from the Pint unit conversion -- library for the Python programming language. Check them out on -- <https://github.com/hgrecco/pint GitHub>. defaultDefString :: String defaultDefString = unlines [ -- decimal prefixes "yocto- = 1e-24 = y-" ,"zepto- = 1e-21 = z-" ,"atto- = 1e-18 = a-" ,"femto- = 1e-15 = f-" ,"pico- = 1e-12 = p-" ,"nano- = 1e-9 = n-" ,"micro- = 1e-6 = u-" ,"milli- = 1e-3 = m-" ,"centi- = 1e-2 = c-" ,"deci- = 1e-1 = d-" ,"deca- = 1e+1 = da-" ,"hecto- = 1e2 = h-" ,"kilo- = 1e3 = k-" ,"mega- = 1e6 = M-" ,"giga- = 1e9 = G-" ,"tera- = 1e12 = T-" ,"peta- = 1e15 = P-" ,"exa- = 1e18 = E-" ,"zetta- = 1e21 = Z-" ,"yotta- = 1e24 = Y-" -- binary_prefixes ,"kibi- = 2**10 = Ki-" ,"mebi- = 2**20 = Mi-" ,"gibi- = 2**30 = Gi-" ,"tebi- = 2**40 = Ti-" ,"pebi- = 2**50 = Pi-" ,"exbi- = 2**60 = Ei-" ,"zebi- = 2**70 = Zi-" ,"yobi- = 2**80 = Yi-" -- reference ,"meter = [length] = m = metre" ,"second = [time] = s = sec" ,"ampere = [current] = A = amp" ,"candela = [luminosity] = cd = candle" ,"gram = [mass] = g" ,"mole = [substance] = mol" --,"degK = [temperature]; offset: 0 = K = kelvin" ,"radian = [] = rad" ,"bit = []" ,"count = []" ,"pi = 3.14159265359" ,"gstandard_gravity = 9.806650 * meter / second ** 2 = g_0 = g_n = gravity" ,"speed_of_light = 299792458 * meter / second = c" -- acceleration -- [acceleration] = [length] / [time] ** 2 -- Angle ,"turn = 2 * pi * radian = revolution = cycle = circle" ,"degree = pi / 180 * radian = deg = arcdeg = arcdegree = angular_degree" ,"arcminute = arcdeg / 60 = arcmin = arc_minute = angular_minute" ,"arcsecond = arcmin / 60 = arcsec = arc_second = angular_second" ,"steradian = radian ** 2 = sr" -- Time ,"minute = 60 * second = min" ,"hour = 60 * minute = h = hr" ,"day = 24 * hour" ,"week = 7 * day" ,"fortnight = 2 * week" ,"year = 31556925.9747 * second" ,"month = year/12" ,"shake = 1e-8 * second" ,"sidereal_day = day / 1.00273790935079524" ,"sidereal_hour = sidereal_day/24" ,"sidereal_minute = sidereal_hour/60" ,"sidereal_second =sidereal_minute/60" ,"sidereal_year = 366.25636042 * sidereal_day" ,"sidereal_month = 27.321661 * sidereal_day" ,"tropical_month = 27.321661 * day" ,"synodic_month = 29.530589 * day = lunar_month" ,"common_year = 365 * day" ,"leap_year = 366 * day" ,"julian_year = 365.25 * day" ,"gregorian_year = 365.2425 * day" ,"millenium = 1000 * year = millenia = milenia = milenium" ,"eon = 1e9 * year" ,"work_year = 2056 * hour" ,"work_month = work_year/12" -- Length ,"angstrom = 1e-10 * meter" ,"inch = 2.54 * centimeter = international_inch = inches = international_inches = in" ,"foot = 12 * inch = international_foot = ft = feet = international_foot = international_feet" ,"mile = 5280 * foot = mi = international_mile" ,"yard = 3 * feet = yd = international_yard" ,"mil = inch / 1000 = thou" ,"parsec = 3.08568025e16 * meter = pc" ,"light_year = speed_of_light * julian_year = ly = lightyear" ,"astronomical_unit = 149597870691 * meter = au" ,"nautical_mile = 1.852e3 * meter = nmi" ,"printers_point = 127 * millimeter / 360 = point" ,"printers_pica = 12 * printers_point = pica" ,"US_survey_foot = 1200 * meter / 3937" ,"US_survey_yard = 3 * US_survey_foot" ,"US_survey_mile = 5280 * US_survey_foot = US_statute_mile" ,"rod = 16.5 * US_survey_foot = pole = perch" ,"furlong = 660 * US_survey_foot" ,"fathom = 6 * US_survey_foot" ,"chain = 66 * US_survey_foot" ,"barleycorn = inch / 3" ,"arpentlin = 191.835 * feet" ,"kayser = 1 / centimeter = wavenumber" -- Mass ,"ounce = 28.349523125 * gram = oz = avoirdupois_ounce" ,"dram = oz / 16 = dr = avoirdupois_dram" ,"pound = 0.45359237 * kilogram = lb = avoirdupois_pound" ,"stone = 14 * lb = st" ,"carat = 200 * milligram" ,"grain = 64.79891 * milligram = gr" ,"long_hundredweight = 112 * lb" ,"short_hundredweight = 100 * lb" ,"metric_ton = 1000 * kilogram = t = tonne" ,"pennyweight = 24 * gram = dwt" ,"slug = 14.59390 * kilogram" ,"troy_ounce = 480 * gram = toz = apounce = apothecary_ounce" ,"troy_pound = 12 * toz = tlb = appound = apothecary_pound" ,"drachm = 60 * gram = apdram = apothecary_dram" ,"atomic_mass_unit = 1.660538782e-27 * kilogram = u = amu = dalton = Da" ,"scruple = 20 * gram" ,"bag = 94 * lb" ,"ton = 2000 * lb = short_ton" -- Force --[force] = [mass] * [acceleration] ,"newton = kilogram * meter / second ** 2 = N" ,"dyne = gram * centimeter / second ** 2 = dyn" ,"force_kilogram = g_0 * kilogram = kgf = kilogram_force = pond" ,"force_gram = g_0 * gram = gf = gram_force" ,"force_ounce = g_0 * ounce = ozf = ounce_force" ,"force_pound = g_0 * lb = lbf = pound_force" ,"force_ton = 2000 * force_pound = ton_force" ,"poundal = lb * feet / second ** 2 = pdl" ,"kip = 1000*lbf" -- Area -- [area] = [length] ** 2 ,"are = 100 * m**2" ,"barn = 1e-28 * m ** 2 = b" ,"cmil = 5.067075e-10 * m ** 2 = circular_mils" ,"darcy = 9.869233e-13 * m ** 2" ,"acre = 4046.8564224 * m ** 2 = international_acre" ,"US_survey_acre = 160 * rod ** 2" -- Energy ,"joule = newton * meter = J" ,"erg = dyne * centimeter" ,"btu = 1.05505585262e3 * joule = Btu = BTU = british_thermal_unit" ,"eV = 1.60217653e-19 * J = electron_volt" ,"thm = 100000 * BTU = therm = EC_therm" ,"cal = 4.184 * joule = calorie = thermochemical_calorie" ,"international_steam_table_calorie = 4.1868 * joule" ,"ton_TNT = 4.184e9 * joule = tTNT" ,"US_therm = 1.054804e8 * joule" ,"E_h = 4.35974394e-18 * joule = hartree = hartree_energy" -- Power ,"watt = joule / second = W = volt_ampere = VA" ,"horsepower = 33000 * ft * lbf / min = hp = UK_horsepower = British_horsepower" ,"boiler_horsepower = 33475 * btu / hour" ,"metric_horsepower = 75 * force_kilogram * meter / second" ,"electric_horsepower = 746 * watt" ,"hydraulic_horsepower = 550 * feet * lbf / second" ,"refrigeration_ton = 12000 * btu / hour = ton_of_refrigeration" -- More Energy ,"watt_hour = watt * hour = Wh = watthour" -- EM ,"esu = 1 * erg**0.5 * centimeter**0.5 = statcoulombs = statC = franklin = Fr" ,"esu_per_second = 1 * esu / second = statampere" ,"ampere_turn = 1 * A" ,"gilbert = 10 / (4 * pi ) * ampere_turn = G" ,"coulomb = ampere * second = C" ,"volt = joule / coulomb = V" ,"farad = coulomb / volt = F" ,"ohm = volt / ampere" ,"siemens = ampere / volt = S = mho" ,"weber = volt * second = Wb" ,"tesla = weber / meter ** 2 = T" ,"henry = weber / ampere = H" ,"elementary_charge = 1.602176487e-19 * coulomb = e" ,"chemical_faraday = 9.64957e4 * coulomb" ,"physical_faraday = 9.65219e4 * coulomb" ,"faraday = 96485.3399 * coulomb = C12_faraday" ,"gamma = 1e-9 * tesla" ,"gauss = 1e-4 * tesla" ,"maxwell = 1e-8 * weber = mx" ,"oersted = 1000 / (4 * pi) * A / m = Oe" ,"statfarad = 1.112650e-12 * farad = statF = stF" ,"stathenry = 8.987554e11 * henry = statH = stH" ,"statmho = 1.112650e-12 * siemens = statS = stS" ,"statohm = 8.987554e11 * ohm" ,"statvolt = 2.997925e2 * volt = statV = stV" ,"unit_pole = 1.256637e-7 * weber" -- Frequency ,"hertz = 1 / second = Hz = rps" ,"revolutions_per_minute = revolution / minute = rpm" ,"counts_per_second = count / second = cps" -- Information ,"byte = 8 * bit = Bo = octet" ,"baud = bit / second = Bd = bps" -- Textile ,"denier = gram / (9000 * meter)" ,"tex = gram/ (1000 * meter)" ,"dtex = decitex" -- Pressure -- [pressure] = [force] / [area] ,"Hg = gravity * 13.59510 * gram / centimeter ** 3 = mercury = conventional_mercury" ,"mercury_60F = gravity * 13.5568 * gram / centimeter ** 3" ,"H2O = gravity * 1000 * kilogram / meter ** 3 = h2o = water = conventional_water" ,"water_4C = gravity * 999.972 * kilogram / meter ** 3 = water_39F" ,"water_60F = gravity * 999.001 * kilogram / m ** 3" ,"pascal = newton / meter ** 2 = Pa" ,"bar = 100000 * pascal" ,"atmosphere = 101325 * pascal = atm = standard_atmosphere" ,"technical_atmosphere = kilogram * gravity / centimeter ** 2 = at" ,"torr = atm / 760" ,"psi = pound * gravity / inch ** 2 = pound_force_per_square_inch" ,"ksi = kip / inch ** 2 = kip_per_square_inch" ,"barye = 0.1 * newton / meter ** 2 = barie = barad = barrie = baryd = Ba" ,"mmHg = millimeter * Hg = mm_Hg = millimeter_Hg = millimeter_Hg_0C" ,"cmHg = centimeter * Hg = cm_Hg = centimeter_Hg" ,"inHg = inch * Hg = in_Hg = inch_Hg = inch_Hg_32F" ,"inch_Hg_60F = inch * mercury_60F" ,"inch_H2O_39F = inch * water_39F" ,"inch_H2O_60F = inch * water_60F" ,"footH2O = ft * water" ,"cmH2O = centimeter * water" ,"foot_H2O = ft * water = ftH2O" ,"standard_liter_per_minute = 1.68875 * Pa * m ** 3 / s = slpm = slm" -- Radiation ,"Bq = Hz = becquerel" ,"curie = 3.7e10 * Bq = Ci" ,"rutherford = 1e6*Bq = rd = Rd" ,"Gy = joule / kilogram = gray = Sv = sievert" ,"rem = 1e-2 * sievert" ,"rads = 1e-2 * gray" ,"roentgen = 2.58e-4 * coulomb / kilogram = R" -- Velocity -- [speed] = [length] / [time] ,"knot = nautical_mile / hour = kt = knot_international = international_knot = nautical_miles_per_hour" ,"mph = mile / hour = MPH" ,"kph = kilometer / hour = KPH" -- Viscosity -- [viscosity] = [pressure] * [time] ,"poise = 1e-1 * Pa * second = P" ,"stokes = 1e-4 * meter ** 2 / second = St" ,"rhe = 10 / (Pa * s)" -- Volume -- [volume] = [length] ** 3 ,"liter = 1e-3 * m ** 3 = l = L = litre" ,"cc = centimeter ** 3 = cubic_centimeter" ,"stere = meter ** 3" ,"gross_register_ton = 100 * foot ** 3 = register_ton = GRT" ,"acre_foot = acre * foot = acre_feet" ,"board_foot = foot ** 2 * inch = FBM" ,"bushel = 2150.42 * inch ** 3 = bu = US_bushel" ,"dry_gallon = bushel / 8 = US_dry_gallon" ,"dry_quart = dry_gallon / 4 = US_dry_quart" ,"dry_pint = dry_quart / 2 = US_dry_pint" ,"gallon = 231 * inch ** 3 = liquid_gallon = US_liquid_gallon" ,"quart = gallon / 4 = liquid_quart = US_liquid_quart" ,"pint = quart / 2 = pt = liquid_pint = US_liquid_pint" ,"cup = pint / 2 = liquid_cup = US_liquid_cup" ,"gill = cup / 2 = liquid_gill = US_liquid_gill" ,"floz = gill / 4 = fluid_ounce = US_fluid_ounce = US_liquid_ounce" ,"imperial_bushel = 36.36872 * liter = UK_bushel" ,"imperial_gallon = imperial_bushel / 8 = UK_gallon" ,"imperial_quart = imperial_gallon / 4 = UK_quart" ,"imperial_pint = imperial_quart / 2 = UK_pint" ,"imperial_cup = imperial_pint / 2 = UK_cup" ,"imperial_gill = imperial_cup / 2 = UK_gill" ,"imperial_floz = imperial_gill / 5 = UK_fluid_ounce = imperial_fluid_ounce" ,"barrel = 42 * gallon = bbl" ,"tablespoon = floz / 2 = tbsp = Tbsp = Tblsp = tblsp = tbs = Tbl" ,"teaspoon = tablespoon / 3 = tsp" ,"peck = bushel / 4 = pk" ,"fluid_dram = floz / 8 = fldr = fluidram" ,"firkin = barrel / 4" ] -- otherDefinitions :: String -- otherDefinitions = unlines [ -- -- Heat -- "RSI = degK * meter ** 2 / watt" -- ,"clo = 0.155 * RSI = clos" -- ,"R_value = foot ** 2 * degF * hour / btu" -- -- Temperature -- ,"degR = 9 / 5 * degK; offset: 0 = rankine" -- ,"degC = degK; offset: 273.15 = celsius = C" -- ,"degF = 9 / 5 * degK; offset: 255.372222 = fahrenheit = F" -- ]
jdreaver/quantities
library/Data/Quantities/DefaultUnits.hs
bsd-3-clause
12,394
0
6
2,852
809
558
251
244
1
module Problem84Tests ( problem84Tests ) where import Test.HUnit import Problem84 testFindPosition :: Test testFindPosition = TestCase $ do assertEqual "GO position" 0 (findPosition "GO") assertEqual "JAIL position" 10 (findPosition "JAIL") testNextCellFromGroup :: Test testNextCellFromGroup = TestCase $ do assertEqual "U1 from GO" (findPosition "U1") (nextCellFromGroup 'U' (findPosition "GO")) assertEqual "U2 from U1" (findPosition "U2") (nextCellFromGroup 'U' (findPosition "U1")) assertEqual "U1 from U2" (findPosition "U1") (nextCellFromGroup 'U' (findPosition "U2")) problem84Tests = TestList [ testFindPosition, testNextCellFromGroup ]
candidtim/euler
test/Problem84Tests.hs
bsd-3-clause
670
0
12
99
181
91
90
14
1
{-# LANGUAGE OverloadedStrings #-} module Test.Sunlight ( Description , Compiler , GhcPkg , Cabal , TestInputs(..) , runTests ) where import Distribution.Package import Distribution.Text import Test.Sunlight.Shell import System.Directory import Distribution.PackageDescription import Distribution.PackageDescription.Parse import Distribution.Simple.Utils import Distribution.Verbosity import Distribution.Version import Data.Tuple.Select import qualified Data.ByteString.Char8 as BS8 import Data.Monoid import Data.Time import System.Locale (defaultTimeLocale) import Data.List (intersperse) import System.Random import Control.Monad import System.Exit -- | Result from installing the package's dependencies. data InstallResult = InstallResult { drOutput :: CmdResult , drGhcPkg :: CmdResult } deriving Show instance CheckOk InstallResult where isOk r = all isOk . map ($ r) $ [drOutput, drGhcPkg] -- | Install a package's dependencies. -- Preconditions: -- -- * current directory has the unpacked tarball. -- -- Side effects: -- -- * dependencies are fully or partially installed. If partially -- installed, the ExitCode should be non-zero. installDeps :: [PackageIdentifier] -- ^ Optional constraints. Currently constraints may only be tied -- to specific versions (for instance, flag constraints or -- constraints tied to a range of versions are not allowed.) -> FilePath -- ^ Install using this compiler (full path to compiler). -> FilePath -- ^ Full path to ghc-pkg. -> FilePath -- ^ Path to cabal executable -> FilePath -- ^ Path to directory to use for user package DB. -> FilePath -- ^ Directory to use for installation prefix -> IO InstallResult installDeps cs ghc pkg cabal db dir = do let opts = [ "install" , "--verbose=2" , "--with-compiler=" ++ ghc , "--with-hc-pkg=" ++ pkg , "--prefix=" ++ dir , "--disable-library-profiling" , "--disable-executable-profiling" , "--package-db=clear" , "--package-db=global" , "--package-db=" ++ db , "--enable-tests" , "--disable-documentation" , "--only-dependencies" ] ++ map constraint cs out <- tee cabal opts let pkgOpts = [ "list", "--global", "--package-conf=" ++ db ] pkgOut <- tee pkg pkgOpts return $ InstallResult out pkgOut -- | Makes a PackageIdentifier into a version constraint option. constraint :: PackageIdentifier -> String constraint i = "--constraint=" ++ name ++ "==" ++ ver where name = display . pkgName $ i ver = display . pkgVersion $ i data PackageInstResult = PackageInstResult { piSetup :: CmdResult , piConfigure :: CmdResult , piBuild :: CmdResult , piInst :: CmdResult , piGhcPkg :: CmdResult } deriving Show instance CheckOk PackageInstResult where isOk r = all isOk . map ($ r) $ [ piSetup, piConfigure, piBuild, piInst, piGhcPkg ] -- | Install a package. -- -- Preconditions: -- -- * dependencies have already been installed at the given prefix -- and registered in the given db -- -- * current directory has the unpacked tarball. -- -- Side effects: -- -- * package should be installed, or exit code is non-zero installPackage :: FilePath -- ^ Install using this compiler (full path to compiler) -> FilePath -- ^ Full path to ghc-pkg -> FilePath -- ^ User DB -> FilePath -- ^ Installation prefix -> IO PackageInstResult installPackage ghc pkg db pfx = do let opts = [ "configure" , "--verbose=2" , "--with-compiler=" ++ ghc , "--with-hc-pkg=" ++ pkg , "--prefix=" ++ pfx , "--package-db=clear" , "--package-db=global" , "--package-db=" ++ db , "--enable-tests" ] rBuildSetup <- tee "ghc" ["--make", "Setup.hs"] rConf <- tee "./Setup" opts let bOpts = [ "build", "--verbose=2" ] rBuild <- tee "./Setup" bOpts rInst <- tee "./Setup" ["install", "--verbose=2"] rPkg <- tee pkg [ "list" , "--global" , "--package-conf=" ++ db ] return $ PackageInstResult rBuildSetup rConf rBuild rInst rPkg -- | Test a package. -- -- Preconditions: -- -- * Package has already been built. testPackage :: [(String, [String])] -- ^ From the package root directory, these are the commands and -- arguments to run to test the package. -> IO [CmdResult] testPackage = mapM (uncurry tee) data InstallAndTestResult = InstallAndTestResult { itDate :: UTCTime -- ^ Current time , itGhcVersion :: CmdResult -- ^ Result of ghc --version , itPkgVersion :: CmdResult -- ^ Result of ghc-pkg --version , itCabalVersion :: CmdResult -- ^ Result of cabal --version , itCompileSetup :: CmdResult -- ^ Result from compiling Setup.hs , itSdistDeps :: CmdResult -- ^ Result from running sdist to create tree from which to -- install dependencies , itSdistPkg :: CmdResult -- ^ Result from running sdist to create tree from which to -- install package , itInit :: CmdResult -- ^ Result from initializing user package DB , itDeps :: InstallResult , itPackage :: PackageInstResult , itTest :: [CmdResult] } deriving Show instance CheckOk InstallAndTestResult where isOk r = and [ rsltsOk, testsOk, isOk (itDeps r), isOk (itPackage r) ] where rsltsOk = all isOk . map ($ r) $ [ itGhcVersion, itPkgVersion, itCabalVersion, itCompileSetup, itSdistDeps, itSdistPkg, itInit ] testsOk = all isOk . itTest $ r -- | Performs test installation. -- -- Preconditions: -- -- * is run from root package directory. A temporary directory is -- created inside this directory. All work is done within the -- temporary directory. -- -- Postconditions: -- -- * cleans up after itself; no temporary files should remain. installAndTest :: [PackageIdentifier] -- ^ Constraints -> UTCTime -> FilePath -- ^ Path to compiler -> FilePath -- ^ Path to ghc-pkg -> FilePath -- ^ Path to cabal executable -> [(String, [String])] -- ^ How to test the package -> IO InstallAndTestResult installAndTest cs date ghc pkg cabal test = withTempDirectory verbose "." "sunlight" $ \relDir -> do dir <- canonicalizePath relDir let setup = dir ++ "/Setup" distDeps = dir ++ "/distDeps" distPkg = dir ++ "/distPkg" db = dir ++ "/db" pfx = dir ++ "/prefix" ghcVer <- tee ghc ["--version"] pkgVer <- tee pkg ["--version"] cblVer <- tee "cabal" ["--version"] rSetup <- tee ghc ["--make", "-outputdir", dir, "-o", setup, "Setup.hs"] rDistDeps <- tee setup ["sdist", "--output-directory=" ++ distDeps ] rDistPkg <- tee setup ["sdist", "--output-directory=" ++ distPkg ] createDirectory pfx rInit <- tee pkg ["init", db] rDeps <- inDirectory distDeps $ installDeps cs ghc pkg cabal db pfx rInst <- inDirectory distPkg $ installPackage ghc pkg db pfx rTest <- inDirectory distPkg $ testPackage test return $ InstallAndTestResult date ghcVer pkgVer cblVer rSetup rDistDeps rDistPkg rInit rDeps rInst rTest -- | Gets a list of PackageIdentifier with the lowest possible -- versions. Fails if a package has a dependency range with no -- minimum. lowestVersions :: GenericPackageDescription -> Either Dependency [PackageIdentifier] -- ^ Left with the bad dependency if there is one; Right -- otherwise. lowestVersions pd = mapM lowestVersion ls where ls = depsLib ++ depsExe ++ depsTest ++ depsBench depsLib = case condLibrary pd of Nothing -> [] Just deps -> getDependencies deps getDeps = getDepsList pd depsExe = getDeps condExecutables depsTest = getDeps condTestSuites depsBench = getDeps condBenchmarks getDepsList :: GenericPackageDescription -> (GenericPackageDescription -> [(a, CondTree b [Dependency] c)]) -> [Dependency] getDepsList d f = concatMap getDependencies . map snd . f $ d getDependencies :: CondTree v [Dependency] a -> [Dependency] getDependencies t = let this = condTreeConstraints t rest = concatMap getDependencies . map sel2 . condTreeComponents $ t in this ++ rest lowestVersion :: Dependency -> Either Dependency PackageIdentifier lowestVersion d@(Dependency n r) = case asVersionIntervals r of [] -> Left d (LowerBound v b, _):_ | b == ExclusiveBound -> Left d | otherwise -> Right $ PackageIdentifier n v testLowestVersions :: UTCTime -> FilePath -- ^ Path to compiler -> FilePath -- ^ Path to ghc-pkg -> FilePath -- ^ Path to cabal executable -> [(String, [String])] -- ^ How to test the package -> GenericPackageDescription -> Either Dependency (IO InstallAndTestResult) testLowestVersions date ghc pkg cabal test d = case lowestVersions d of Left e -> Left e Right ps -> Right $ installAndTest ps date ghc pkg cabal test testDefaultVersions :: UTCTime -> FilePath -- ^ Path to compiler -> FilePath -- ^ Path to ghc-pkg -> FilePath -- ^ Path to cabal executable -> [(String, [String])] -- ^ How to test the package -> IO InstallAndTestResult testDefaultVersions date ghc pkg cabal test = installAndTest [] date ghc pkg cabal test testMultipleVersions :: UTCTime -> (FilePath, FilePath) -- ^ Compiler and ghc-pkg to use when testing lowest version -> [(FilePath, FilePath)] -- ^ Compilers and ghc-pkg to use to test default versions -> FilePath -- ^ Path to cabal executable -> [(String, [String])] -- ^ How to test package -> GenericPackageDescription -> Either Dependency (IO (InstallAndTestResult, [InstallAndTestResult])) testMultipleVersions date (lowestGhc, lowestPkg) rest cabal test pd = case testLowestVersions date lowestGhc lowestPkg cabal test pd of Left d -> Left d Right g -> Right $ do r1 <- g let testRest (c, p) = testDefaultVersions date c p cabal test rs <- mapM testRest rest return (r1, rs) -- Sample test directory structure: -- minimum-versions.txt -- current-versions.txt -- sunlight -- - 2014 -- - 02 -- - 22 -- - UTCtime -- - [random string] -- - lowest-7.4.2-passed.txt -- - current-7.4.2-passed.txt -- - current-7.6.1-passed.txt versionsReport :: BS8.ByteString -- ^ Description of dependencies -> Compiler -> Description -> UTCTime -> InstallAndTestResult -> BS8.ByteString versionsReport desc c d t r = BS8.concat [ "This package was tested to work with these dependency\n" , "versions and compiler version.\n" , desc , "Tested as of: " <> (BS8.pack . show $ t) <> "\n" , "Path to compiler: " <> BS8.pack c <> "\n" , "Compiler description: " <> BS8.pack d <> "\n" , "\n" ] <> (crStdOut . piGhcPkg . itPackage $ r) minimumVersionsReport :: Compiler -> Description -> UTCTime -> InstallAndTestResult -> BS8.ByteString minimumVersionsReport = versionsReport "These are the minimum versions given in the .cabal file.\n" writeMinimumVersionsReport :: BS8.ByteString -> IO () writeMinimumVersionsReport = BS8.writeFile "minimum-versions.txt" currentVersionsReport :: UTCTime -> [(Description, Compiler, a)] -> [InstallAndTestResult] -> Maybe BS8.ByteString currentVersionsReport t ds ts | null ds || null ts = Nothing | otherwise = Just $ versionsReport dep comp desc t r where dep = "These are the default versions fetched by cabal install.\n" (desc, comp, _) = last ds r = last ts writeCurrentVersionsReport :: BS8.ByteString -> IO () writeCurrentVersionsReport = BS8.writeFile "current-versions.txt" instance ShowBS InstallResult where showBS r = showBS (drOutput r) <> showBS (drGhcPkg r) instance ShowBS PackageInstResult where showBS r = showBS (piSetup r) <> showBS (piConfigure r) <> showBS (piBuild r) <> showBS (piInst r) <> showBS (piGhcPkg r) instance ShowBS InstallAndTestResult where showBS i = "Current time: " <> showBS (itDate i) <> "\n" <> showBS (itGhcVersion i) <> showBS (itPkgVersion i) <> showBS (itCabalVersion i) <> showBS (itCompileSetup i) <> showBS (itSdistDeps i) <> showBS (itSdistPkg i) <> showBS (itInit i) <> showBS (itDeps i) <> showBS (itPackage i) <> (BS8.concat . map showBS . itTest $ i) -- | Gets four-character random string. randomString :: IO String randomString = fmap (map toEnum) $ replicateM 4 (getStdRandom (randomR (fromEnum 'a', fromEnum 'z'))) makeResultFile :: UTCTime -> String -- ^ Random string -> String -- ^ Description string, e.g. "lowest" or "current" -> String -- ^ Compiler version description -> InstallAndTestResult -> IO () makeResultFile utct rand desc comp res = do let dir = resultDirectory utct rand createDirectoryIfMissing True dir let fn = dir ++ "/" ++ desc ++ "-" ++ comp ++ "-" ++ passFail ++ ".txt" passFail | isOk res = "passed" | otherwise = "FAILED" BS8.writeFile fn . showBS $ res resultDirectory :: UTCTime -> String -- ^ Random string -> String resultDirectory t s = concat . intersperse "/" $ ["sunlight", yr, mo, dy, ti, s ] where (y, m, d) = toGregorian . utctDay $ t yr = show y mo = pad . show $ m dy = pad . show $ d pad str | length str > 1 = str | otherwise = '0':str ti = formatTime defaultTimeLocale "%H%M%S" t -- | A description for this compiler version. This will be used in -- the directory name in the tree that is written to disk. I simply -- use a compiler version, such as @7.4@. type Description = String -- | Path to GHC compiler. You can use a full path name or, if you use -- just an executable name, the PATH will be searched. type Compiler = String -- | Path to ghc-pkg. If you use just an executable name, the PATH -- will be searched. type GhcPkg = String -- | Path to cabal executable. Used to install package -- dependencies. If you use just an executable name, the PATH will -- be searched. type Cabal = String data TestInputs = TestInputs { tiDescription :: Maybe GenericPackageDescription -- ^ If Just, use this package description. Handy if you write -- your own package description in Haskell rather than in the -- cabal format. Otherwise, use Nothing and sunlight will look -- for the default cabal file and parse that. , tiCabal :: Cabal -- ^ Which @cabal@ executable to use. , tiLowest :: (Description, Compiler, GhcPkg) -- ^ Test the minimum dependency bounds using this compiler. A -- report is left in the main package directory showing which -- package versions worked with this compiler and with the minimum -- bounds. , tiDefault :: [(Description, Compiler, GhcPkg)] -- ^ Test the default dependencies using these compilers. Since -- cabal-install will eagerly get the most recent dependencies it -- can find, this will test the highest possible versions. The -- compiler specified in 'tiLowest' is not automatically retried -- here, so if you want to use that compiler specify it as well. -- -- The last compiler in this list is assumed to be the most recent -- compiler. A report is left in the main package directory -- showing the dependencies that worked with this compiler -- version. , tiTest :: [(String, [String])] -- ^ How to test the package. Each pair is a command to run, -- and the arguments to that command. The command is run from -- the resulting package root directory after the package is -- unpacked and compiled. So, if your test suite is an -- executable called @myTest@ and it requires the argument -- @--verbose@, you would use something like this: -- -- > [("dist/build/myTest/myTest", ["--verbose"])] -- -- The tests are considered to pass if all these commands exit -- with a zero exit status. -- -- You can also abuse this option to get output in the record of -- the test; for instance, maybe you want to record the current -- git HEAD: -- -- > [("git", ["rev-parse", "HEAD"])] } deriving Show runTests :: TestInputs -> IO () runTests i = do desc <- case tiDescription i of Just pd -> return pd Nothing -> do path <- defaultPackageDesc verbose readPackageDescription verbose path date <- getCurrentTime randStr <- randomString let last2 (_, b, c) = (b, c) eiRes = testMultipleVersions date (last2 . tiLowest $ i) (map last2 . tiDefault $ i) (tiCabal i) (tiTest i) desc (r1, rs) <- case eiRes of Left e -> dependencyError e Right g -> g makeResultFile date randStr "lowest" (sel1 . tiLowest $ i) r1 let makeRest r (d, _, _) = makeResultFile date randStr "current" d r _ <- zipWithM makeRest rs (tiDefault i) when (not $ isOk r1 && all isOk rs) exitFailure writeMinimumVersionsReport $ minimumVersionsReport (sel2 . tiLowest $ i) (sel1 . tiLowest $ i) date r1 maybe (return ()) writeCurrentVersionsReport $ currentVersionsReport date (tiDefault i) rs exitSuccess dependencyError :: Dependency -> IO a dependencyError d = putStrLn s >> exitFailure where s = "dependency invalid: " ++ show d ++ " sunlight requires " ++ "that you specify a fixed lower bound for each dependency."
massysett/sunlight
lib/Test/Sunlight.hs
bsd-3-clause
17,225
0
20
3,918
3,774
2,020
1,754
366
3
{-# LANGUAGE ViewPatterns, OverloadedStrings #-} module Insomnia.Typecheck.Selfify ( selfifySignature , selfifyTypeDefn ) where import Data.Monoid (Monoid(..), (<>)) import qualified Unbound.Generics.LocallyNameless as U import qualified Unbound.Generics.LocallyNameless.Unsafe as UU import Insomnia.Common.ModuleKind import Insomnia.Identifier (Path(..)) import Insomnia.Types (TypeConstructor(..), TypePath(..)) import Insomnia.Expr (QVar(..)) import Insomnia.TypeDefn (TypeDefn(..)) import Insomnia.ValueConstructor (ValConName, InferredValConPath(..), ValueConstructor(..), ConstructorDef(..)) import Insomnia.ModuleType (Signature(..), SigV(..), ModuleTypeNF(..), TypeSigDecl(..)) import Insomnia.Typecheck.Env import Insomnia.Typecheck.SelfSig (SelfSig(..)) import Insomnia.Typecheck.WhnfModuleType (whnfModuleType) import {-# SOURCE #-} Insomnia.Typecheck.ExtendModuleCtx (extendTypeSigDeclCtx, extendModuleCtx) -- | "Selfification" (c.f. TILT) is the process of adding to the current scope -- a type variable of singleton kind (ie, a module variable standing -- for a module expression) such that the module variable is given its principal -- kind (exposes maximal sharing). selfifySignature :: Path -> Signature -> TC SelfSig selfifySignature pmod msig_ = case msig_ of UnitSig -> return UnitSelfSig ValueSig fld ty msig -> do let qvar = QVar pmod fld selfSig <- selfifySignature pmod msig return $ ValueSelfSig qvar ty selfSig TypeSig fld bnd -> U.lunbind bnd $ \((tyId, U.unembed -> tsd), msig) -> do let p = TypePath pmod fld -- replace the local Con (IdP tyId) way of refering to -- this definition in the rest of the signature by -- the full projection from the model path. Also replace the -- type constructors tcon = TCGlobal p substVCons = selfifyTypeSigDecl p tsd substTyCon = [(tyId, tcon)] tsd' = U.substs substTyCon $ U.substs substVCons tsd msig' = U.substs substTyCon $ U.substs substVCons msig selfSig <- extendTypeSigDeclCtx tcon tsd $ selfifySignature pmod msig' return $ TypeSelfSig p tsd' selfSig SubmoduleSig fld bnd -> U.lunbind bnd $ \((modId, U.unembed -> modTy), msig) -> do let p = ProjP pmod fld mtnf <- whnfModuleType modTy <??@ ("while selfifying signature of " <> formatErr pmod) case mtnf of (SigMTNF (SigV subSig ModuleMK)) -> do subSelfSig <- selfifySignature p subSig let msig' = U.subst modId p msig selfSig' <- extendModuleCtx subSelfSig $ selfifySignature pmod msig' return $ SubmoduleSelfSig p subSelfSig selfSig' (SigMTNF (SigV _ ModelMK)) -> do let msig' = U.subst modId p msig selfSig' <- selfifySignature pmod msig' return $ GenerativeSelfSig p mtnf selfSig' (FunMTNF {}) -> do let msig' = U.subst modId p msig selfSig' <- selfifySignature pmod msig' return $ GenerativeSelfSig p mtnf selfSig' selfifyTypeSigDecl :: TypePath -> TypeSigDecl -> [(ValConName, ValueConstructor)] selfifyTypeSigDecl tpath tsd = case tsd of AbstractTypeSigDecl _k -> mempty ManifestTypeSigDecl defn -> selfifyTypeDefn tpath defn AliasTypeSigDecl _alias -> mempty -- | Given the path to a type defintion and the type definition, construct -- a substitution that replaces unqualified references to the components of -- the definition (for example the value constructors of an algebraic datatype) -- by their qualified names with respect to the given path. selfifyTypeDefn :: TypePath -> TypeDefn -> [(ValConName, ValueConstructor)] selfifyTypeDefn _ (EnumDefn _) = [] selfifyTypeDefn dtPath (DataDefn bnd) = let (_, constrDefs) = UU.unsafeUnbind bnd cs = map (\(ConstructorDef c _) -> c) constrDefs in map mkSubst cs where mkSubst :: ValConName -> (ValConName, ValueConstructor) mkSubst short = let fld = U.name2String short in (short, VCGlobal (Right $ InferredValConPath dtPath fld))
lambdageek/insomnia
src/Insomnia/Typecheck/Selfify.hs
bsd-3-clause
4,286
0
21
1,081
1,038
554
484
76
6