code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GADTs #-}
module Control.Monad.Takahashi.Slide
( BlockOption(..)
, fontColor, bgColor, frameColor, frameStyle
, SlideOption(..)
, slideTitle, slideFontSize, titleOption, codeOption
, contentsOption, contentsOption2, annotationOption, blockFontSize
, defaultSlideOption
----
, Taka(..)
, buildTakahashi
, writeSlideWithTemplate
, writeSlide
----
, runTakahashi
, showTakahashi
, makeSlideWithTemplate
, makeSlide
) where
import Control.Lens
import Control.Monad.RWS
import Data.List
import Control.Monad.Skeleton
import Paths_takahashi
import Control.Monad.Takahashi.Monad
import Control.Monad.Takahashi.HtmlBuilder
import Control.Monad.Takahashi.Util
type TakahashiRWS a = RWS () Html SlideOption a
----
buildTakahashi :: Taka a -> TakahashiRWS a
buildTakahashi t = interpret advent t
where
advent :: TakahashiBase a -> TakahashiRWS a
advent GetSlideOption = get
advent (PutSlideOption o) = put o
advent (Slide t) = do
style <- mkStyle
tell $ Div Nothing (Just "pages") (Just style) (runBuildHtml t) Emp
mkStyle :: TakahashiRWS Style
mkStyle = do
option <- get
return . execMakeStyle defaultStyle $ do
font.fontSize .= option^.slideFontSize
----
runTakahashi :: Taka a -> Html
runTakahashi t = snd $ execRWS (buildTakahashi t) () defaultSlideOption
showTakahashi :: Taka a -> String
showTakahashi = showHtml . runTakahashi
makeSlideWithTemplate :: String -> Taka a -> IO String
makeSlideWithTemplate r t = do
instr <- readFile r
return $ sub "##Presentation" (showTakahashi t) instr
makeSlide :: Taka a -> IO String
makeSlide t = getDataFileName "html/Temp.html" >>= flip makeSlideWithTemplate t
writeSlideWithTemplate :: String -> String -> Taka a -> IO ()
writeSlideWithTemplate r w = makeSlideWithTemplate r >=> writeFile w
writeSlide :: String -> Taka a -> IO ()
writeSlide w = makeSlide >=> writeFile w
|
tokiwoousaka/takahashi
|
src/Control/Monad/Takahashi/Slide.hs
|
mit
| 1,995 | 0 | 14 | 368 | 571 | 303 | 268 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
module Tests.Command.Dupes (tests) where
import Dupes
import Control.Applicative
import Data.Machine
import Data.Serialize
import qualified Data.ByteString.Char8 as C
import Test.Framework
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck
instance Arbitrary PathKey where
arbitrary = PathKey <$> liftA C.pack arbitrary
tests :: [Test]
tests = [ (testProperty "Rebuilding combined lists is identity" prop_combineAndRebuildIntList)
, (testProperty "Encode decode PathKey is identity" prop_serializePathKey)
, (testProperty "Rebuilding combined path keys is identity" prop_combineAndRebuildSimplePathKeys)
, (testProperty "Rebuild merged streams in identity" prop_rebuildMergedStreamsInt)]
rebuild :: [MergedOperation a] -> ([a], [a])
rebuild = r
where
r [] = ([], [])
r ((LeftOnly x) : xs) = left x (rebuild xs)
r (RightOnly x : xs) = right x (rebuild xs)
r (Both x : xs) = left x $ right x (rebuild xs)
left x (xs, ys) = (x : xs, ys)
right y (xs, ys) = (xs, y : ys)
prop_combineAndRebuildIntList :: OrderedList Int -> OrderedList Int -> Bool
prop_combineAndRebuildIntList olx oly =
(ident xs ys) == (xs, ys)
where
xs = getOrdered olx
ys = getOrdered oly
ident x y = rebuild $ combine x y
prop_serializePathKey :: PathKey -> Bool
prop_serializePathKey a = case decode (encode a) of
Left _ -> False
Right b -> a == b
prop_combineAndRebuildSimplePathKeys :: [PathKey] -> [PathKey] -> Bool
prop_combineAndRebuildSimplePathKeys = prop_combineAndRebuild
prop_combineAndRebuild :: (Ord a) => [a] -> [a] -> Bool
prop_combineAndRebuild xs ys =
(rebuild $ combine xs ys) == (xs, ys)
prop_rebuildMergedStreamsInt :: [Int] -> [Int] -> Bool
prop_rebuildMergedStreamsInt = prop_rebuildMergedStreams
prop_rebuildMergedStreams :: (Ord a) => [a] -> [a] -> Bool
prop_rebuildMergedStreams xs ys =
(rebuild . run $ mergeOrderedStreams sourceX sourceY) == (xs, ys)
where
sourceX = source xs
sourceY = source ys
|
danstiner/clod
|
test/Tests/Command/Dupes.hs
|
mit
| 2,057 | 0 | 11 | 380 | 672 | 365 | 307 | 47 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Consensus.Configuration
-- Copyright : (c) Phil Hargett 2014
-- License : MIT (see LICENSE file)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (requires STM)
--
-- A 'Configuration' generally describes membership in a cluster. Within a cluster, there
-- may or may not be an active leader at any given time, there should be 1 or more participants
-- actively engaged in consensus algorithms and the work of the cluster, and there may be
-- 0 or more observers: these are passive members who receive updates on shared cluster
-- state, but do not participate in consensus decisions or the work of the cluster.
--
-----------------------------------------------------------------------------
module Control.Consensus.Configuration (
-- * Configuration
Configuration(..),
mkConfiguration,
isJointConfiguration,
clusterLeader,
isClusterParticipant,
isClusterMember,
clusterMembers,
clusterMembersOnly,
clusterParticipants,
addClusterParticipants,
removeClusterParticipants,
setClusterParticipants
) where
-- local imports
-- external imports
import qualified Data.List as L
import Data.Serialize
import qualified Data.Set as S
import Data.Typeable
import GHC.Generics
import Network.Endpoints
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Cofiguration
--------------------------------------------------------------------------------
{- |
A configuration identifies all the members of a cluster and the nature of their participation
in the cluster.
-}
data Configuration =
-- | A simple configuration with an optional leader, some participants, and some observers.
Configuration {
configurationLeader :: Maybe Name,
configurationParticipants :: S.Set Name,
configurationObservers :: S.Set Name
}
-- | A combined configuration temporarily used for transitioning between two simplie configurations.
| JointConfiguration {
jointOldConfiguration :: Configuration,
jointNewConfiguration :: Configuration
} deriving (Generic,Show,Typeable,Eq)
instance Serialize Configuration
{-|
Create a new configuration with no leader and no observers; the supplie names
will be recorded as participants.
-}
mkConfiguration :: [Name] -> Configuration
mkConfiguration participants = Configuration {
configurationLeader = Nothing,
configurationParticipants = S.fromList participants,
configurationObservers = S.empty
}
{-|
Returns 'True' if the configuration is a joint one.
-}
isJointConfiguration :: Configuration -> Bool
isJointConfiguration (Configuration _ _ _) = False
isJointConfiguration (JointConfiguration _ _) = True
{-|
Returns the leader of the configuration, if any.
-}
clusterLeader :: Configuration -> Maybe Name
clusterLeader Configuration {configurationLeader = leaderId} = leaderId
clusterLeader (JointConfiguration _ configuration) = clusterLeader configuration
{-|
Returns 'True' if the supplied name is a participant in the configuration.
-}
isClusterParticipant :: Name -> Configuration -> Bool
isClusterParticipant name (Configuration _ participants _) = S.member name participants
isClusterParticipant name (JointConfiguration jointOld jointNew) =
(isClusterParticipant name jointOld) || (isClusterParticipant name jointNew)
{-|
Return all members of the cluster (e.g., participants and observers) as a list.
-}
clusterMembers :: Configuration -> [Name]
clusterMembers (Configuration _ participants observers) = S.toList $ S.union participants observers
clusterMembers (JointConfiguration jointOld jointNew) =
S.toList $ S.union (S.fromList $ clusterMembers jointOld) (S.fromList $ clusterMembers jointNew)
{-|
Return true if the supplied name is a participant or observer in the cluster.
-}
isClusterMember :: Name -> Configuration -> Bool
isClusterMember name (Configuration _ participants observers) = S.member name participants || S.member name observers
isClusterMember name (JointConfiguration jointOld jointNew) =
(isClusterMember name jointOld) || (isClusterMember name jointNew)
{-|
Return just the participants in the cluster as a list.
-}
clusterParticipants :: Configuration -> [Name]
clusterParticipants (Configuration _ participants _) = (S.toList participants)
clusterParticipants (JointConfiguration jointOld jointNew) =
S.toList $ S.fromList $ clusterParticipants jointOld ++ (clusterParticipants jointNew)
{-|
Return members of the cluster, excluding any leader
-}
clusterMembersOnly :: Configuration -> [Name]
clusterMembersOnly cfg = case clusterLeader cfg of
Just ldr -> L.delete ldr (clusterMembers cfg)
Nothing -> clusterMembers cfg
{-|
Return a new configuration with the supplied participants added to the cluster.
-}
addClusterParticipants :: Configuration -> [Name] -> Configuration
addClusterParticipants cfg@(Configuration _ _ _) participants = cfg {
configurationParticipants = S.union (configurationParticipants cfg) $ S.fromList participants
}
addClusterParticipants (JointConfiguration jointOld jointNew) participants = JointConfiguration {
jointOldConfiguration = jointOld,
jointNewConfiguration = addClusterParticipants jointNew participants
}
{-|
Return a new configuration with the participants removed from the cluster.
-}
removeClusterParticipants :: Configuration -> [Name] -> Configuration
removeClusterParticipants cfg@(Configuration _ _ _) participants = cfg {
configurationParticipants = S.difference (configurationParticipants cfg) $ S.fromList participants
}
removeClusterParticipants (JointConfiguration jointOld jointNew) participants = JointConfiguration {
jointOldConfiguration = jointOld,
jointNewConfiguration = removeClusterParticipants jointNew participants
}
{-|
Return a new configuration with the provided list of participants replacing any prior participants
in the cluster.
-}
setClusterParticipants :: Configuration -> [Name] -> Configuration
setClusterParticipants cfg@(Configuration _ _ _) participants = cfg {
configurationParticipants = S.fromList participants
}
setClusterParticipants (JointConfiguration _ jointNew) participants = setClusterParticipants jointNew participants
|
hargettp/raft
|
src/Control/Consensus/Configuration.hs
|
mit
| 6,626 | 0 | 10 | 990 | 1,030 | 565 | 465 | 78 | 2 |
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE ParallelListComp #-}
{-# LANGUAGE TupleSections #-}
module Examples.AES where
import Circuit
import Circuit.Builder
import Circuit.Utils
import qualified Circuit.Format.Acirc as Acirc
import qualified Circuit.Format.Acirc2 as Acirc2
import Control.Monad
import Control.Monad.Trans (lift)
import qualified Data.Vector as V
exportAcirc :: [(String, [IO (String, Acirc)])]
exportAcirc = [ ("aes", [ ("aes1r" ,) <$> buildAesRound 128
, ("aes1r_128_1",) <$> aes1Bit 128
, ("aes1r_64_1" ,) <$> aes1Bit 64
, ("aes1r_32_1" ,) <$> aes1Bit 32
, ("aes1r_16_1" ,) <$> aes1Bit 16
, ("aes1r_8_1" ,) <$> aes1Bit 8
, ("aes1r_4_1" ,) <$> aes1Bit 4
, ("aes1r_2_1" ,) <$> aes1Bit 2
, ("sbox",) <$> return subByteCirc
] )
, ("aes1r", [ ("aes1r",) <$> buildAesRound 128 ] )
, ("aes10r", [ ("aes",) <$> buildAes 10 128 ] )
]
exportAcirc2 :: [(String, [IO (String, Acirc2)])]
exportAcirc2 = [ ("aes1r", [ ("aes1r",) <$> buildAesRoundA2 128 ])]
sbox :: V.Vector (V.Vector Bool)-- {{{
sbox =
[ [False, True, True, False, False, False, True, True]
, [False, True, True, True, True, True, False, False]
, [False, True, True, True, False, True, True, True]
, [False, True, True, True, True, False, True, True]
, [True, True, True, True, False, False, True, False]
, [False, True, True, False, True, False, True, True]
, [False, True, True, False, True, True, True, True]
, [True, True, False, False, False, True, False, True]
, [False, False, True, True, False, False, False, False]
, [False, False, False, False, False, False, False, True]
, [False, True, True, False, False, True, True, True]
, [False, False, True, False, True, False, True, True]
, [True, True, True, True, True, True, True, False]
, [True, True, False, True, False, True, True, True]
, [True, False, True, False, True, False, True, True]
, [False, True, True, True, False, True, True, False]
, [True, True, False, False, True, False, True, False]
, [True, False, False, False, False, False, True, False]
, [True, True, False, False, True, False, False, True]
, [False, True, True, True, True, True, False, True]
, [True, True, True, True, True, False, True, False]
, [False, True, False, True, True, False, False, True]
, [False, True, False, False, False, True, True, True]
, [True, True, True, True, False, False, False, False]
, [True, False, True, False, True, True, False, True]
, [True, True, False, True, False, True, False, False]
, [True, False, True, False, False, False, True, False]
, [True, False, True, False, True, True, True, True]
, [True, False, False, True, True, True, False, False]
, [True, False, True, False, False, True, False, False]
, [False, True, True, True, False, False, True, False]
, [True, True, False, False, False, False, False, False]
, [True, False, True, True, False, True, True, True]
, [True, True, True, True, True, True, False, True]
, [True, False, False, True, False, False, True, True]
, [False, False, True, False, False, True, True, False]
, [False, False, True, True, False, True, True, False]
, [False, False, True, True, True, True, True, True]
, [True, True, True, True, False, True, True, True]
, [True, True, False, False, True, True, False, False]
, [False, False, True, True, False, True, False, False]
, [True, False, True, False, False, True, False, True]
, [True, True, True, False, False, True, False, True]
, [True, True, True, True, False, False, False, True]
, [False, True, True, True, False, False, False, True]
, [True, True, False, True, True, False, False, False]
, [False, False, True, True, False, False, False, True]
, [False, False, False, True, False, True, False, True]
, [False, False, False, False, False, True, False, False]
, [True, True, False, False, False, True, True, True]
, [False, False, True, False, False, False, True, True]
, [True, True, False, False, False, False, True, True]
, [False, False, False, True, True, False, False, False]
, [True, False, False, True, False, True, True, False]
, [False, False, False, False, False, True, False, True]
, [True, False, False, True, True, False, True, False]
, [False, False, False, False, False, True, True, True]
, [False, False, False, True, False, False, True, False]
, [True, False, False, False, False, False, False, False]
, [True, True, True, False, False, False, True, False]
, [True, True, True, False, True, False, True, True]
, [False, False, True, False, False, True, True, True]
, [True, False, True, True, False, False, True, False]
, [False, True, True, True, False, True, False, True]
, [False, False, False, False, True, False, False, True]
, [True, False, False, False, False, False, True, True]
, [False, False, True, False, True, True, False, False]
, [False, False, False, True, True, False, True, False]
, [False, False, False, True, True, False, True, True]
, [False, True, True, False, True, True, True, False]
, [False, True, False, True, True, False, True, False]
, [True, False, True, False, False, False, False, False]
, [False, True, False, True, False, False, True, False]
, [False, False, True, True, True, False, True, True]
, [True, True, False, True, False, True, True, False]
, [True, False, True, True, False, False, True, True]
, [False, False, True, False, True, False, False, True]
, [True, True, True, False, False, False, True, True]
, [False, False, True, False, True, True, True, True]
, [True, False, False, False, False, True, False, False]
, [False, True, False, True, False, False, True, True]
, [True, True, False, True, False, False, False, True]
, [False, False, False, False, False, False, False, False]
, [True, True, True, False, True, True, False, True]
, [False, False, True, False, False, False, False, False]
, [True, True, True, True, True, True, False, False]
, [True, False, True, True, False, False, False, True]
, [False, True, False, True, True, False, True, True]
, [False, True, True, False, True, False, True, False]
, [True, True, False, False, True, False, True, True]
, [True, False, True, True, True, True, True, False]
, [False, False, True, True, True, False, False, True]
, [False, True, False, False, True, False, True, False]
, [False, True, False, False, True, True, False, False]
, [False, True, False, True, True, False, False, False]
, [True, True, False, False, True, True, True, True]
, [True, True, False, True, False, False, False, False]
, [True, True, True, False, True, True, True, True]
, [True, False, True, False, True, False, True, False]
, [True, True, True, True, True, False, True, True]
, [False, True, False, False, False, False, True, True]
, [False, True, False, False, True, True, False, True]
, [False, False, True, True, False, False, True, True]
, [True, False, False, False, False, True, False, True]
, [False, True, False, False, False, True, False, True]
, [True, True, True, True, True, False, False, True]
, [False, False, False, False, False, False, True, False]
, [False, True, True, True, True, True, True, True]
, [False, True, False, True, False, False, False, False]
, [False, False, True, True, True, True, False, False]
, [True, False, False, True, True, True, True, True]
, [True, False, True, False, True, False, False, False]
, [False, True, False, True, False, False, False, True]
, [True, False, True, False, False, False, True, True]
, [False, True, False, False, False, False, False, False]
, [True, False, False, False, True, True, True, True]
, [True, False, False, True, False, False, True, False]
, [True, False, False, True, True, True, False, True]
, [False, False, True, True, True, False, False, False]
, [True, True, True, True, False, True, False, True]
, [True, False, True, True, True, True, False, False]
, [True, False, True, True, False, True, True, False]
, [True, True, False, True, True, False, True, False]
, [False, False, True, False, False, False, False, True]
, [False, False, False, True, False, False, False, False]
, [True, True, True, True, True, True, True, True]
, [True, True, True, True, False, False, True, True]
, [True, True, False, True, False, False, True, False]
, [True, True, False, False, True, True, False, True]
, [False, False, False, False, True, True, False, False]
, [False, False, False, True, False, False, True, True]
, [True, True, True, False, True, True, False, False]
, [False, True, False, True, True, True, True, True]
, [True, False, False, True, False, True, True, True]
, [False, True, False, False, False, True, False, False]
, [False, False, False, True, False, True, True, True]
, [True, True, False, False, False, True, False, False]
, [True, False, True, False, False, True, True, True]
, [False, True, True, True, True, True, True, False]
, [False, False, True, True, True, True, False, True]
, [False, True, True, False, False, True, False, False]
, [False, True, False, True, True, True, False, True]
, [False, False, False, True, True, False, False, True]
, [False, True, True, True, False, False, True, True]
, [False, True, True, False, False, False, False, False]
, [True, False, False, False, False, False, False, True]
, [False, True, False, False, True, True, True, True]
, [True, True, False, True, True, True, False, False]
, [False, False, True, False, False, False, True, False]
, [False, False, True, False, True, False, True, False]
, [True, False, False, True, False, False, False, False]
, [True, False, False, False, True, False, False, False]
, [False, True, False, False, False, True, True, False]
, [True, True, True, False, True, True, True, False]
, [True, False, True, True, True, False, False, False]
, [False, False, False, True, False, True, False, False]
, [True, True, False, True, True, True, True, False]
, [False, True, False, True, True, True, True, False]
, [False, False, False, False, True, False, True, True]
, [True, True, False, True, True, False, True, True]
, [True, True, True, False, False, False, False, False]
, [False, False, True, True, False, False, True, False]
, [False, False, True, True, True, False, True, False]
, [False, False, False, False, True, False, True, False]
, [False, True, False, False, True, False, False, True]
, [False, False, False, False, False, True, True, False]
, [False, False, True, False, False, True, False, False]
, [False, True, False, True, True, True, False, False]
, [True, True, False, False, False, False, True, False]
, [True, True, False, True, False, False, True, True]
, [True, False, True, False, True, True, False, False]
, [False, True, True, False, False, False, True, False]
, [True, False, False, True, False, False, False, True]
, [True, False, False, True, False, True, False, True]
, [True, True, True, False, False, True, False, False]
, [False, True, True, True, True, False, False, True]
, [True, True, True, False, False, True, True, True]
, [True, True, False, False, True, False, False, False]
, [False, False, True, True, False, True, True, True]
, [False, True, True, False, True, True, False, True]
, [True, False, False, False, True, True, False, True]
, [True, True, False, True, False, True, False, True]
, [False, True, False, False, True, True, True, False]
, [True, False, True, False, True, False, False, True]
, [False, True, True, False, True, True, False, False]
, [False, True, False, True, False, True, True, False]
, [True, True, True, True, False, True, False, False]
, [True, True, True, False, True, False, True, False]
, [False, True, True, False, False, True, False, True]
, [False, True, True, True, True, False, True, False]
, [True, False, True, False, True, True, True, False]
, [False, False, False, False, True, False, False, False]
, [True, False, True, True, True, False, True, False]
, [False, True, True, True, True, False, False, False]
, [False, False, True, False, False, True, False, True]
, [False, False, True, False, True, True, True, False]
, [False, False, False, True, True, True, False, False]
, [True, False, True, False, False, True, True, False]
, [True, False, True, True, False, True, False, False]
, [True, True, False, False, False, True, True, False]
, [True, True, True, False, True, False, False, False]
, [True, True, False, True, True, True, False, True]
, [False, True, True, True, False, True, False, False]
, [False, False, False, True, True, True, True, True]
, [False, True, False, False, True, False, True, True]
, [True, False, True, True, True, True, False, True]
, [True, False, False, False, True, False, True, True]
, [True, False, False, False, True, False, True, False]
, [False, True, True, True, False, False, False, False]
, [False, False, True, True, True, True, True, False]
, [True, False, True, True, False, True, False, True]
, [False, True, True, False, False, True, True, False]
, [False, True, False, False, True, False, False, False]
, [False, False, False, False, False, False, True, True]
, [True, True, True, True, False, True, True, False]
, [False, False, False, False, True, True, True, False]
, [False, True, True, False, False, False, False, True]
, [False, False, True, True, False, True, False, True]
, [False, True, False, True, False, True, True, True]
, [True, False, True, True, True, False, False, True]
, [True, False, False, False, False, True, True, False]
, [True, True, False, False, False, False, False, True]
, [False, False, False, True, True, True, False, True]
, [True, False, False, True, True, True, True, False]
, [True, True, True, False, False, False, False, True]
, [True, True, True, True, True, False, False, False]
, [True, False, False, True, True, False, False, False]
, [False, False, False, True, False, False, False, True]
, [False, True, True, False, True, False, False, True]
, [True, True, False, True, True, False, False, True]
, [True, False, False, False, True, True, True, False]
, [True, False, False, True, False, True, False, False]
, [True, False, False, True, True, False, True, True]
, [False, False, False, True, True, True, True, False]
, [True, False, False, False, False, True, True, True]
, [True, True, True, False, True, False, False, True]
, [True, True, False, False, True, True, True, False]
, [False, True, False, True, False, True, False, True]
, [False, False, True, False, True, False, False, False]
, [True, True, False, True, True, True, True, True]
, [True, False, False, False, True, True, False, False]
, [True, False, True, False, False, False, False, True]
, [True, False, False, False, True, False, False, True]
, [False, False, False, False, True, True, False, True]
, [True, False, True, True, True, True, True, True]
, [True, True, True, False, False, True, True, False]
, [False, True, False, False, False, False, True, False]
, [False, True, True, False, True, False, False, False]
, [False, True, False, False, False, False, False, True]
, [True, False, False, True, True, False, False, True]
, [False, False, True, False, True, True, False, True]
, [False, False, False, False, True, True, True, True]
, [True, False, True, True, False, False, False, False]
, [False, True, False, True, False, True, False, False]
, [True, False, True, True, True, False, True, True]
, [False, False, False, True, False, True, True, False]
]
-- }}}
subByteFromSelection :: (Gate g, Monad m) => [Ref] -> BuilderT g m [Ref]
subByteFromSelection xs = do
when (length xs /= 256) $
error "[subByteFromSelection] need a sigma vector of length 256!"
forM [0..7] $ \j -> do
let vars = map snd $ filter (\(i,_) -> sbox V.! i V.! j) (zip [0..] xs)
circSum vars
subByte :: (Gate g, Monad m) => [Ref] -> BuilderT g m [Ref]
subByte xs = do
when (length xs /= 8) $
error "[subByte] expected a length 8 binary input!"
subByteFromSelection =<< selectionVector xs
subByteCirc :: Circuit ArithGate
subByteCirc = buildCircuit $ outputs =<< subByte =<< inputs 8
buildAesRound :: Int -> IO Acirc
buildAesRound n = buildCircuitT $ do
linearParts <- lift buildLinearParts
inp <- inputs n
one <- constant 1
zero <- constant 0
key <- secrets (replicate 128 0)
let fixed = replicate (128 - n) zero
let state = safeChunksOf 8 (inp ++ fixed)
xs <- concat <$> mapM subByte state
xs' <- subcircuit linearParts xs
xs'' <- zipWithM circXor xs' key -- addRoundKey
outputs xs''
buildAesRoundA2 :: Int -> IO Acirc2
buildAesRoundA2 n = buildCircuitT $ do
linearParts <- lift buildLinearPartsA2
inp <- inputs n
one <- constant 1
zero <- constant 0
key <- secrets (replicate 128 0)
let fixed = replicate (128 - n) zero
let state = safeChunksOf 8 (inp ++ fixed)
xs <- concat <$> mapM subByte state
xs' <- subcircuit linearParts xs
xs'' <- zipWithM circXor xs' key -- addRoundKey
outputs xs''
buildAes :: Int -> Int -> IO (Circuit ArithGate)
buildAes nrounds ninputs = buildCircuitT $ do
aesRound <- lift $ Acirc.read "optimized_circuits/aes1r.o2.acirc"
inp <- inputs ninputs
fixed <- replicateM (128 - ninputs) (constant 0)
k0 <- replicateM 128 (secret 0)
-- round 1
xs <- zipWithM circXor (inp ++ fixed) k0
if nrounds > 1 then do
-- round 2+
zs <- foldM (\x _ -> subcircuit aesRound x) xs ([2..nrounds] :: [Int])
outputs zs
else do
outputs xs
aes1Bit :: Int -> IO (Circuit ArithGate)
aes1Bit n = buildCircuitT $ do
aes <- lift $ buildAesRound n
inp <- inputs n
zs <- subcircuit aes inp
output (head zs)
sbox0 :: Circuit ArithGate
sbox0 = buildCircuit $ do
xs <- inputs 8
ys <- subByte xs
output (head ys)
sboxsum :: IO (Circuit ArithGate)
sboxsum = buildCircuitT $ do
ks <- lift $ randKeyIO 8
xs <- inputs 8
ys <- subByte xs
zs <- zipWithM circXor ys =<< secrets ks
output =<< circXors zs
xor :: Circuit ArithGate
xor = buildCircuit $ do
x <- input
y <- input
z <- circXor x y
output z
toState :: [Ref] -> [[[Ref]]]
toState = transpose . safeChunksOf 4 . safeChunksOf 8
fromState :: [[[Ref]]] -> [Ref]
fromState = concat . concat . transpose
-- assume inputs come in chunks of 8
gf28DotProduct :: (Gate g, Monad m) => Circuit g -> Circuit g -> [Int] -> [[Ref]] -> BuilderT g m [Ref]
gf28DotProduct double triple xs ys = do
when (length xs /= length ys) $ error "[gf28DotProduct] unequal length vectors"
let mult (1,x) = return x
mult (2,x) = subcircuit double x
mult (3,x) = subcircuit triple x
mult (_,_) = error "whoops"
ws <- mapM mult (zip xs ys)
mapM circXors (transpose ws)
gf28VectorMult :: (Gate g, Monad m) => Circuit g -> Circuit g -> [Int] -> [[[Ref]]] -> BuilderT g m [[Ref]]
gf28VectorMult double triple v ms = mapM (gf28DotProduct double triple v) ms
gf28MatrixMult :: (Gate g, Monad m) => Circuit g -> Circuit g -> [[Int]] -> [[[Ref]]] -> BuilderT g m [[[Ref]]]
gf28MatrixMult double triple xs ys = mapM (\x -> gf28VectorMult double triple x (transpose ys)) xs
rotate :: Int -> [a] -> [a]
rotate n xs = drop n xs ++ take n xs
buildLinearParts :: IO Acirc
buildLinearParts = buildCircuitT $ do
double <- lift $ Acirc.read "optimized_circuits/gf28Double.c2v.acirc"
triple <- lift $ Acirc.read "optimized_circuits/gf28Triple.c2v.acirc"
xs <- shiftRows <$> toState <$> inputs 128
ys <- gf28MatrixMult double triple m xs
outputs (fromState ys)
where
m = [[2, 3, 1, 1],
[1, 2, 3, 1],
[1, 1, 2, 3],
[3, 1, 1, 2]]
buildLinearPartsA2 :: IO Acirc2
buildLinearPartsA2 = buildCircuitT $ do
double <- lift $ Acirc2.read "optimized_circuits/gf28Double.c2v.acirc2"
triple <- lift $ Acirc2.read "optimized_circuits/gf28Triple.c2v.acirc2"
xs <- shiftRows <$> toState <$> inputs 128
ys <- gf28MatrixMult double triple m xs
outputs (fromState ys)
where
m = [[2, 3, 1, 1],
[1, 2, 3, 1],
[1, 1, 2, 3],
[3, 1, 1, 2]]
shiftRows :: [[[Ref]]] -> [[[Ref]]]
shiftRows xs = [ rotate n row | row <- xs | n <- [0..3] ]
|
spaceships/circuit-synthesis
|
src/Examples/AES.hs
|
mit
| 22,206 | 1 | 19 | 6,014 | 9,261 | 5,811 | 3,450 | 403 | 4 |
-- | Functions to facilitate automated and manual testing.
module Text.Docvim.Util ( compileUnits
, p
, parseUnit
, pm
, pp
, ppm
, ppv
, pv
) where
import Text.Docvim.AST
import Text.Docvim.Compile
import Text.Docvim.Parse
import Text.Docvim.Printer.Markdown
import Text.Docvim.Printer.Vim
import Text.Parsec
import Text.Show.Pretty
-- | Parse a string containing a translation unit.
parseUnit :: String -> Either ParseError Node
parseUnit = runParser unit () "(eval)"
-- | Parse and compile a list of strings containing a translation units.
compileUnits :: [String] -> Either ParseError Node
compileUnits inputs = do
parsed <- mapM parseUnit inputs
return $ compile parsed
-- | Convenience function: Parse and compile a list of strings containing
-- translation units, but always returns a string even in the case of an error.
p :: [String] -> String
p inputs = case compileUnits inputs of
Left err -> show err
Right ast -> ppShow ast
-- | Pretty-prints the result of parsing and compiling an input string.
--
-- To facilitate quick testing in the REPL; example:
--
-- pp "unlet g:var"
pp :: String -> IO ()
pp input = putStrLn $ p [input]
-- | Parse and compile a list of input strings into Vim help format.
pv :: [String] -> String
pv inputs = case compileUnits inputs of
Left err -> show err
Right ast -> vimHelp ast
-- | Pretty-prints the result of parsing and compiling an input string and
-- transforming into Vim help format.
--
-- For logging in the REPL.
ppv :: String -> IO ()
ppv input = putStr $ pv [input]
-- | Parse and compile a list of input strings into Markdown help format.
pm :: [String] -> String
pm inputs = case compileUnits inputs of
Left err -> show err
Right ast -> markdown ast
-- | Pretty-prints the result of parsing and compiling an input string and
-- transforming into Markdown format.
--
-- For logging in the REPL.
ppm :: String -> IO ()
ppm input = putStr $ pm [input]
|
wincent/docvim
|
lib/Text/Docvim/Util.hs
|
mit
| 2,139 | 0 | 8 | 569 | 420 | 227 | 193 | 39 | 2 |
module Phone (number) where
import Data.Char (isDigit)
number :: String -> Maybe String
number = validate . filter isDigit
where
validate :: String -> Maybe String
validate s | n == 10 && h /= '1' && c `elem` ['2' .. '9'] = Just s
| n == 11 && h == '1' = validate $ tail s
| otherwise = Nothing
where
n = length s
h = head s
c = s !! 3
|
genos/online_problems
|
exercism/haskell/phone-number/src/Phone.hs
|
mit
| 394 | 0 | 14 | 134 | 166 | 85 | 81 | 11 | 1 |
import Text.Printf
main = do
line <- getLine
putStrLn $ printf "%.2f" $ abs (read line :: Double)
|
Voleking/ICPC
|
references/aoapc-book/BeginningAlgorithmContests/haskell/ch1/ex1-8.hs
|
mit
| 104 | 0 | 10 | 24 | 44 | 21 | 23 | 4 | 1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.WebGPUFunction
(getName, WebGPUFunction(..), gTypeWebGPUFunction) where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <https://developer.mozilla.org/en-US/docs/Web/API/WebGPUFunction.name Mozilla WebGPUFunction.name documentation>
getName ::
(MonadDOM m, FromJSString result) => WebGPUFunction -> m result
getName self = liftDOM ((self ^. js "name") >>= fromJSValUnchecked)
|
ghcjs/jsaddle-dom
|
src/JSDOM/Generated/WebGPUFunction.hs
|
mit
| 1,287 | 0 | 10 | 146 | 351 | 227 | 124 | 21 | 1 |
module Unison.Util.List where
import Unison.Prelude
import qualified Data.List as List
import qualified Data.Set as Set
import qualified Data.Map as Map
multimap :: Foldable f => Ord k => f (k, v) -> Map k [v]
multimap kvs =
-- preserve the order of the values from the original list
reverse <$> foldl' step Map.empty kvs
where
step m (k,v) = Map.insertWith (++) k [v] m
groupBy :: (Foldable f, Ord k) => (v -> k) -> f v -> Map k [v]
groupBy f vs = reverse <$> foldl' step Map.empty vs
where step m v = Map.insertWith (++) (f v) [v] m
-- returns the subset of `f a` which maps to unique `b`s.
-- prefers earlier copies, if many `a` map to some `b`.
uniqueBy, nubOrdOn :: (Foldable f, Ord b) => (a -> b) -> f a -> [a]
uniqueBy f as = wrangle' (toList as) Set.empty where
wrangle' [] _ = []
wrangle' (a:as) seen =
if Set.member b seen
then wrangle' as seen
else a : wrangle' as (Set.insert b seen)
where b = f a
nubOrdOn = uniqueBy
-- prefers later copies
uniqueBy' :: (Foldable f, Ord b) => (a -> b) -> f a -> [a]
uniqueBy' f = reverse . uniqueBy f . reverse . toList
safeHead :: Foldable f => f a -> Maybe a
safeHead = headMay . toList
validate :: (Semigroup e, Foldable f) => (a -> Either e b) -> f a -> Either e [b]
validate f as = case partitionEithers (f <$> toList as) of
([], bs) -> Right bs
(e:es, _) -> Left (foldl' (<>) e es)
-- Intercalate a list with separators determined by inspecting each
-- adjacent pair.
intercalateMapWith :: (a -> a -> b) -> (a -> b) -> [a] -> [b]
intercalateMapWith sep f xs = result where
xs' = map f xs
pairs = filter (\p -> length p == 2) $ map (take 2) $ List.tails xs
seps = (flip map) pairs $ \case
x1 : x2 : _ -> sep x1 x2
_ -> error "bad list length"
paired = zipWith (\sep x -> [sep, x]) seps (drop 1 xs')
result = (take 1 xs') ++ mconcat paired
-- Take runs of consecutive occurrences of r within a list,
-- and in each run, overwrite all but the first occurrence of r with w.
quenchRuns :: Eq a => a -> a -> [a] -> [a]
quenchRuns r w = reverse . (go False r w []) where
go inRun r w acc = \case
[] -> acc
h : tl ->
if h == r
then go True r w ((if inRun then w else r) : acc) tl
else go False r w (h : acc) tl
|
unisonweb/platform
|
unison-core/src/Unison/Util/List.hs
|
mit
| 2,260 | 0 | 15 | 565 | 983 | 518 | 465 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-condition.html
module Stratosphere.ResourceProperties.GlueTriggerCondition where
import Stratosphere.ResourceImports
-- | Full data type definition for GlueTriggerCondition. See
-- 'glueTriggerCondition' for a more convenient constructor.
data GlueTriggerCondition =
GlueTriggerCondition
{ _glueTriggerConditionJobName :: Maybe (Val Text)
, _glueTriggerConditionLogicalOperator :: Maybe (Val Text)
, _glueTriggerConditionState :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON GlueTriggerCondition where
toJSON GlueTriggerCondition{..} =
object $
catMaybes
[ fmap (("JobName",) . toJSON) _glueTriggerConditionJobName
, fmap (("LogicalOperator",) . toJSON) _glueTriggerConditionLogicalOperator
, fmap (("State",) . toJSON) _glueTriggerConditionState
]
-- | Constructor for 'GlueTriggerCondition' containing required fields as
-- arguments.
glueTriggerCondition
:: GlueTriggerCondition
glueTriggerCondition =
GlueTriggerCondition
{ _glueTriggerConditionJobName = Nothing
, _glueTriggerConditionLogicalOperator = Nothing
, _glueTriggerConditionState = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-condition.html#cfn-glue-trigger-condition-jobname
gtcJobName :: Lens' GlueTriggerCondition (Maybe (Val Text))
gtcJobName = lens _glueTriggerConditionJobName (\s a -> s { _glueTriggerConditionJobName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-condition.html#cfn-glue-trigger-condition-logicaloperator
gtcLogicalOperator :: Lens' GlueTriggerCondition (Maybe (Val Text))
gtcLogicalOperator = lens _glueTriggerConditionLogicalOperator (\s a -> s { _glueTriggerConditionLogicalOperator = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-glue-trigger-condition.html#cfn-glue-trigger-condition-state
gtcState :: Lens' GlueTriggerCondition (Maybe (Val Text))
gtcState = lens _glueTriggerConditionState (\s a -> s { _glueTriggerConditionState = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/GlueTriggerCondition.hs
|
mit
| 2,281 | 0 | 12 | 253 | 355 | 202 | 153 | 32 | 1 |
-- | Parsers for first-order logic and other important structures (e.g. Markov
-- logic networks).
module Faun.Parser.Term (
parseFunForm,
parseTerm
) where
import Data.Char (isLower)
import qualified Data.Text as T
import Text.Parsec
import Text.Parsec.String (Parser)
import Faun.Parser.Core
import Faun.Term
-- | Parse function-like objects of the form Name(args0, args1, args2, ...).
parseFunForm :: Parser (T.Text, [Term])
parseFunForm = do
n <- identifier
reservedOp "("
ts <- commaSep parseTerm
reservedOp ")"
return (T.pack n, ts)
-- | Parse basic terms.
parseTerm, parseVarCon, parseFunction :: Parser Term
parseTerm = try parseFunction <|> parseVarCon
parseFunction = do
args <- parseFunForm
return $ uncurry Function args
parseVarCon = do
n <- identifier
return $ (if isLower $ head n then Variable else Constant) (T.pack n)
|
PhDP/Sphinx-AI
|
Faun/Parser/Term.hs
|
mit
| 863 | 0 | 12 | 148 | 230 | 125 | 105 | 24 | 2 |
{- |
Module : Main
Description : Implementation of Problem 12 from 99 Questions.
Copyright : (c) Jeff Smits
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : portable
Decode a run-length encoded list.
Given a run-length code list generated as specified in problem 11. Construct
its uncompressed version.
P12> decodeModified [Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']
"aaaabccaadeeee"
Derived both implementations from my implementations of pack from P11.
-}
data RLEnc a = Multiple Int a | Single a deriving(Show, Read)
decodeModified :: Eq a => [RLEnc a] -> [a]
decodeModified [] = []
decodeModified ((Single e):t) = e : decodeModified t
decodeModified ((Multiple 2 e):t) = e : decodeModified ((Single e):t)
decodeModified ((Multiple n e):t) = e : decodeModified ((Multiple (n-1) e):t)
decodeModified' :: Eq a => [RLEnc a] -> [a]
decodeModified' [] = []
decodeModified' ((Single e):t) = e : decodeModified' t
decodeModified' ((Multiple n e):t) = (replicate n e) ++ decodeModified' t
|
Apanatshka/99-questions
|
P12.hs
|
mit
| 1,131 | 0 | 12 | 231 | 293 | 151 | 142 | 10 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Mezzo.Model.Harmony.Chords
-- Description : Models of chords
-- Copyright : (c) Dima Szamozvancev
-- License : MIT
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- Types and type functions modelling harmonic chords.
--
-----------------------------------------------------------------------------
module Mezzo.Model.Harmony.Chords
(
-- * Chords
DyadType (..)
, TriadType (..)
, TetradType (..)
, Inversion (..)
, DyaType (..)
, TriType (..)
, TetType (..)
, Inv (..)
, InvertChord
, ChordType (..)
, Cho (..)
, FromChord
) where
import GHC.TypeLits
import Data.Kind (Type)
import Mezzo.Model.Types
import Mezzo.Model.Prim
import Mezzo.Model.Reify
-------------------------------------------------------------------------------
-- Chords
-------------------------------------------------------------------------------
-- | The type of a dyad.
data DyadType = MinThird | MajThird | PerfFourth | PerfFifth | PerfOct
-- | The type of a triad.
data TriadType = MajTriad | MinTriad | AugTriad | DimTriad | DoubledD DyadType
-- | The type of a tetrad.
data TetradType = MajSeventh | MajMinSeventh | MinSeventh | HalfDimSeventh | DimSeventh | DoubledT TriadType
-- | The inversion of a chord.
data Inversion = Inv0 | Inv1 | Inv2 | Inv3
-- | A chord type, indexed by the number of notes.
data ChordType :: Nat -> Type where
-- | A dyad, consisting of two pitches.
Dyad :: RootType -> DyadType -> Inversion -> ChordType 2
-- | A triad, consisting of three pitches.
Triad :: RootType -> TriadType -> Inversion -> ChordType 3
-- | A tetrad, consisting of four pitches.
Tetrad :: RootType -> TetradType -> Inversion -> ChordType 4
-- | The singleton type for 'DyadType'
data DyaType (t :: DyadType) = DyaType
-- | The singleton type for 'TriadType'.
data TriType (t :: TriadType) = TriType
-- | The singleton type for 'TetradType'.
data TetType (t :: TetradType) = TetType
-- | The singleton type for 'Inversion'.
data Inv (t :: Inversion) = Inv
-- | The singleton type for 'ChordType'.
data Cho (c :: ChordType n) = Cho
-- | Convert a dyad type to a list of intervals between the individual pitches.
type family DyadTypeToIntervals (t :: DyadType) :: Vector IntervalType 2 where
DyadTypeToIntervals MinThird =
Interval Perf Unison :-- Interval Min Third :-- None
DyadTypeToIntervals MajThird =
Interval Perf Unison :-- Interval Maj Third :-- None
DyadTypeToIntervals PerfFourth =
Interval Perf Unison :-- Interval Perf Fourth :-- None
DyadTypeToIntervals PerfFifth =
Interval Perf Unison :-- Interval Perf Fifth :-- None
DyadTypeToIntervals PerfOct =
Interval Perf Unison :-- Interval Perf Octave :-- None
-- | Convert a triad type to a list of intervals between the individual pitches.
type family TriadTypeToIntervals (t :: TriadType) :: Vector IntervalType 3 where
TriadTypeToIntervals MajTriad = DyadTypeToIntervals MajThird :-| Interval Perf Fifth
TriadTypeToIntervals MinTriad = DyadTypeToIntervals MinThird :-| Interval Perf Fifth
TriadTypeToIntervals AugTriad = DyadTypeToIntervals MajThird :-| Interval Aug Fifth
TriadTypeToIntervals DimTriad = DyadTypeToIntervals MinThird :-| Interval Dim Fifth
TriadTypeToIntervals (DoubledD dt) = DyadTypeToIntervals dt :-| Interval Perf Octave
-- | Convert a seventh chord type to a list of intervals between the individual pitches.
type family TetradTypeToIntervals (s :: TetradType) :: Vector IntervalType 4 where
TetradTypeToIntervals MajSeventh = TriadTypeToIntervals MajTriad :-| Interval Maj Seventh
TetradTypeToIntervals MajMinSeventh = TriadTypeToIntervals MajTriad :-| Interval Min Seventh
TetradTypeToIntervals MinSeventh = TriadTypeToIntervals MinTriad :-| Interval Min Seventh
TetradTypeToIntervals HalfDimSeventh = TriadTypeToIntervals DimTriad :-| Interval Min Seventh
TetradTypeToIntervals DimSeventh = TriadTypeToIntervals DimTriad :-| Interval Dim Seventh
TetradTypeToIntervals (DoubledT tt) = TriadTypeToIntervals tt :-| Interval Perf Octave
-- | Apply an inversion to a list of pitches.
type family Invert (i :: Inversion) (n :: Nat) (ps :: Vector PitchType n) :: Vector PitchType n where
Invert Inv0 n ps = ps
-- Need awkward workarounds because of #12564.
Invert Inv1 n (p :-- ps) = ps :-| RaiseByOct p
Invert Inv2 n (p :-- ps) = Invert Inv1 (n - 1) (p :-- Tail' ps) :-| RaiseByOct (Head' ps)
Invert Inv3 n (p :-- ps) = Invert Inv2 (n - 1) (p :-- (Head' ps) :-- (Tail' (Tail' (ps)))) :-| RaiseByOct (Head' (Tail' ps))
-- | Invert a doubled triad chord.
type family InvertDoubledD (i :: Inversion) (ps :: Vector PitchType 3) :: Vector PitchType 3 where
InvertDoubledD Inv0 ps = ps
InvertDoubledD Inv1 ps = Invert Inv1 2 (Init' ps) :-| (RaiseByOct (Head' (Tail' ps)))
InvertDoubledD Inv2 ps = RaiseAllBy' ps (Interval Perf Octave)
-- | Invert a doubled triad chord.
type family InvertDoubledT (i :: Inversion) (ps :: Vector PitchType 4) :: Vector PitchType 4 where
InvertDoubledT Inv0 ps = ps
InvertDoubledT Inv1 ps = Invert Inv1 3 (Init' ps) :-| (RaiseByOct (Head' (Tail' ps)))
InvertDoubledT Inv2 ps = Invert Inv2 3 (Init' ps) :-| (RaiseByOct (Head' (Tail' (Tail' ps))))
InvertDoubledT Inv3 ps = RaiseAllBy' ps (Interval Perf Octave)
-- | Enumerate inversions.
type family InvSucc (i :: Inversion) :: Inversion where
InvSucc Inv0 = Inv1
InvSucc Inv1 = Inv2
InvSucc Inv2 = Inv3
InvSucc Inv3 = Inv0
-- | Invert a chord once.
type family InvertChord (c :: ChordType n) :: ChordType n where
InvertChord (Dyad r t Inv0) = Dyad r t Inv1
InvertChord (Dyad r t Inv1) = Dyad r t Inv0
InvertChord (Triad r t Inv2) = Triad r t Inv0
InvertChord (Triad r t i) = Triad r t (InvSucc i)
InvertChord (Tetrad r t i) = Tetrad r t (InvSucc i)
-- | Build a list of pitches with the given intervals starting from a root.
type family BuildOnRoot (r :: RootType) (is :: Vector IntervalType n) :: Vector PitchType n where
BuildOnRoot (PitchRoot Silence) _ = TypeError (Text "Can't build a chord on a rest.")
BuildOnRoot r None = None
BuildOnRoot r (i :-- is) = RaiseBy (RootToPitch r) i :-- BuildOnRoot r is
-- | Convert a chord to a list of constituent pitches.
type family ChordToPitchList (c :: ChordType n) :: Vector PitchType n where
ChordToPitchList (Dyad r t i)
= Invert i 2 (BuildOnRoot r (DyadTypeToIntervals t))
ChordToPitchList (Triad r (DoubledD dt) i)
= InvertDoubledD i (BuildOnRoot r (TriadTypeToIntervals (DoubledD dt)))
ChordToPitchList (Triad r t i)
= Invert i 3 (BuildOnRoot r (TriadTypeToIntervals t))
ChordToPitchList (Tetrad r (DoubledT tt) i)
= InvertDoubledT i (BuildOnRoot r (TetradTypeToIntervals (DoubledT tt)))
ChordToPitchList (Tetrad r t i)
= Invert i 4 (BuildOnRoot r (TetradTypeToIntervals t))
-- | Convert a chord to a partiture with the given length (one voice for each pitch).
type family FromChord (c :: ChordType n) (l :: Nat) :: Partiture n l where
FromChord (c :: ChordType n) l = VectorToColMatrix n (ChordToPitchList c) l
-------------------------------------------------------------------------------
-- Primitive instances
-------------------------------------------------------------------------------
-- Chord types
instance Primitive MajThird where
type Rep MajThird = Int -> [Int]
prim t = \r -> [r, r + 4]
pretty t = "M3"
instance Primitive MinThird where
type Rep MinThird = Int -> [Int]
prim t = \r -> [r, r + 3]
pretty t = "m3"
instance Primitive PerfFourth where
type Rep PerfFourth = Int -> [Int]
prim t = \r -> [r, r + 5]
pretty t = "P4"
instance Primitive PerfFifth where
type Rep PerfFifth = Int -> [Int]
prim t = \r -> [r, r + 7]
pretty t = "P5"
instance Primitive PerfOct where
type Rep PerfOct = Int -> [Int]
prim t = \r -> [r, r + 12]
pretty t = "P8"
instance Primitive MajTriad where
type Rep MajTriad = Int -> [Int]
prim t = \r -> [r, r + 4, r + 7]
pretty t = "Maj"
instance Primitive MinTriad where
type Rep MinTriad = Int -> [Int]
prim t = \r -> [r, r + 3, r + 7]
pretty t = "min"
instance Primitive AugTriad where
type Rep AugTriad = Int -> [Int]
prim t = \r -> [r, r + 4, r + 8]
pretty t = "aug"
instance Primitive DimTriad where
type Rep DimTriad = Int -> [Int]
prim t = \r -> [r, r + 3, r + 6]
pretty t = "dim"
instance FunRep Int [Int] c => Primitive (DoubledD c) where
type Rep (DoubledD c) = Int -> [Int]
prim t = \r -> prim (DyaType @c) r ++ [r + 12]
pretty t = pretty (DyaType @c) ++ "D"
instance Primitive MajSeventh where
type Rep MajSeventh = Int -> [Int]
prim t = \r -> [r, r + 4, r + 7, r + 11]
pretty t = "Maj7"
instance Primitive MajMinSeventh where
type Rep MajMinSeventh = Int -> [Int]
prim t = \r -> [r, r + 4, r + 7, r + 10]
pretty t = "7"
instance Primitive MinSeventh where
type Rep MinSeventh = Int -> [Int]
prim t = \r -> [r, r + 3, r + 7, r + 10]
pretty t = "min7"
instance Primitive HalfDimSeventh where
type Rep HalfDimSeventh = Int -> [Int]
prim t = \r -> [r, r + 3, r + 6, r + 10]
pretty t = "hdim7"
instance Primitive DimSeventh where
type Rep DimSeventh = Int -> [Int]
prim t = \r -> [r, r + 3, r + 6, r + 9]
pretty t = "dim7"
instance FunRep Int [Int] c => Primitive (DoubledT c) where
type Rep (DoubledT c) = Int -> [Int]
prim t = \r -> prim (TriType @c) r ++ [r + 12]
pretty t = pretty (TriType @c) ++ "D"
-- Inversions
-- Places the first element of the list on its end.
invChord :: [Int] -> [Int]
invChord [] = []
invChord (x : xs) = xs ++ [x + 12]
instance Primitive Inv0 where
type Rep Inv0 = [Int] -> [Int]
prim i = id
pretty i = "I0"
instance Primitive Inv1 where
type Rep Inv1 = [Int] -> [Int]
prim i = invChord
pretty i = "I1"
instance Primitive Inv2 where
type Rep Inv2 = [Int] -> [Int]
prim i = invChord . invChord
pretty i = "I2"
instance Primitive Inv3 where
type Rep Inv3 = [Int] -> [Int]
prim i = invChord . invChord . invChord
pretty i = "I3"
instance (IntRep r, FunRep Int [Int] t, FunRep [Int] [Int] i)
=> Primitive (Dyad r t i) where
type Rep (Dyad r t i) = [Int]
prim c = prim (Inv @i) . prim (DyaType @t) $ prim (Root @r)
pretty c = pc ++ " " ++ pretty (DyaType @t) ++ " " ++ pretty (Inv @i)
where pc = takeWhile (\c -> c /= ' ' && c /= '\'' && c /= '_') $ pretty (Root @r)
instance (IntRep r, FunRep Int [Int] dt, FunRep [Int] [Int] i)
=> Primitive (Triad r (DoubledD dt) i) where
type Rep (Triad r (DoubledD dt) i) = [Int]
prim c = inverted ++ [head inverted + 12]
where rootPos = prim (DyaType @dt) $ prim (Root @r)
inverted = prim (Inv @i) rootPos
pretty c = pc ++ " " ++ pretty (DyaType @dt) ++ "D " ++ pretty (Inv @i)
where pc = takeWhile (\c -> c /= ' ' && c /= '\'' && c /= '_') $ pretty (Root @r)
instance {-# OVERLAPPABLE #-} (IntRep r, FunRep Int [Int] t, FunRep [Int] [Int] i)
=> Primitive (Triad r t i) where
type Rep (Triad r t i) = [Int]
prim c = prim (Inv @i) . prim (TriType @t) $ prim (Root @r)
pretty c = pc ++ " " ++ pretty (TriType @t) ++ " " ++ pretty (Inv @i)
where pc = takeWhile (\c -> c /= ' ' && c /= '\'' && c /= '_') $ pretty (Root @r)
instance (IntRep r, FunRep Int [Int] tt, FunRep [Int] [Int] i)
=> Primitive (Tetrad r (DoubledT tt) i) where
type Rep (Tetrad r (DoubledT tt) i) = [Int]
prim c = inverted ++ [head inverted + 12]
where rootPos = prim (TriType @tt) $ prim (Root @r)
inverted = prim (Inv @i) rootPos
pretty c = pc ++ " " ++ pretty (TriType @tt) ++ "D " ++ pretty (Inv @i)
where pc = takeWhile (\c -> c /= ' ' && c /= '\'' && c /= '_') $ pretty (Root @r)
instance {-# OVERLAPPABLE #-} (IntRep r, FunRep Int [Int] t, FunRep [Int] [Int] i)
=> Primitive (Tetrad r t i) where
type Rep (Tetrad r t i) = [Int]
prim c = prim (Inv @i) . prim (TetType @t) $ prim (Root @r)
pretty c = pc ++ " " ++ pretty (TetType @t) ++ " " ++ pretty (Inv @i)
where pc = takeWhile (\c -> c /= ' ' && c /= '\'' && c /= '_') $ pretty (Root @r)
|
DimaSamoz/mezzo
|
src/Mezzo/Model/Harmony/Chords.hs
|
mit
| 12,720 | 0 | 16 | 3,154 | 4,451 | 2,364 | 2,087 | -1 | -1 |
type Name = String
type Age = Int
type Breed = String
type Color = String
data Doggy = Dog Name Breed Age Color
deriving Show
data Who = Person Name Age
deriving Show
data Soumya = Who | Doggy
deriving Show
data A = B Int | C String
deriving Show
data D = E Int | F String | D
deriving Show
data HouseholdMember = Human Name Age | Canine Name Breed Age
deriving (Show, Eq)
data Cart = Cartesian Double Double
deriving (Eq, Show)
data Polar = Polar Double Double
deriving (Eq, Show)
data Roygbiv = Red
| Orange
| Yellow
| Green
| Blue
| Indigo
| Violet
deriving (Eq, Show)
myNot True = False
myNot False = True
sumList (x:xs) = x + sumList xs
sumList [] = 0
hname (Human name age) = name
hage (Human name age) = age
cname (Canine name _ _ ) = name
cage (Canine _ _ age) = age
cbreed (Canine _ breed _) = breed
data Expert = Expert {
name :: String,
fields::[String],
degrees::[String]
} deriving (Show, Eq)
data List a = Cons a (List a) | Nil
deriving (Show, Eq)
data Tree a = Node a (Tree a) (Tree a) | Empty
deriving (Show, Eq)
fromList (x:xs) = Cons x (fromList xs)
fromList []=Nil
toList Nil = []
toList (Cons x y) = x: (toList y)
what::[a]->a
what xs = if null (tail xs)
then error "Too short!"
else head (tail xs)
safe::[a] -> Maybe a
safe [] = Nothing
safe xs = if null (tail xs)
then Nothing
else Just (head (tail xs))
tidy::[a]-> Maybe a
tidy (_:x:_) = Just x
tidy _ = Nothing
lend amount balance = let
reserve = 100
newBalance = balance - amount
in
if balance < reserve
then Nothing
else Just newBalance
foo =
let
a = 1
in
let b = 2
in
a+b
bar = let
x=1
in
((let x = "foo" in x),x)
quux a =
let
a="foo"
in
a++"eek!"
lending amount balance =
if amount < reserve*0.5
then Just newBalance
else Nothing
where
reserve=100
newBalance=balance-amount
pluralise :: String -> [Int] -> [String]
pluralise word counts = map plural counts
where
plural 0 = "no "++word++"s"
plural 1 = "one "++word
plural n = show n ++ " " ++ word ++ "s"
hee =
let
b=2
c=True
in
let a=b
in (a,c)
haa = x
where
x=y
where
y=2
unwrap trash thing =
case thing of
Nothing -> trash
Just bleh -> bleh
data Fruit = Apple | Banana
deriving (Show, Eq)
whichFruit::String -> Fruit
whichFruit f =
case f of
"apple" -> Apple
"banana" -> Banana
same (Node a _ _ ) (Node b _ _)
| a==b = Just a
same _ _ = Nothing
lender amount balance
| amount<=0 = Nothing
| amount > reserve*0.5 = Nothing
| otherwise = Just newBalance
where
reserve = 100
newBalance = balance - amount
myDrop n xs =
if n<=0 || null xs
then xs
else myDrop (n-1) (tail xs)
dropper n xs
| n<=0 || (null xs) = xs
| otherwise = dropper (n-1) (tail xs)
longer :: [a] -> Int
longer xs
| (null xs) = 0
| otherwise = 1 + (longer (tail xs))
palindrome:: (Eq a) => [a] -> [a]
palindrome string
| (head string == last string) =
let
bit = reverse ( tail (reverse string))
point = [last string]
in
bit ++ point ++ (reverse bit)
| otherwise = string ++ (reverse string)
ifpal :: (Eq a)=> [a] -> Bool
ifpal string
| string == (reverse string) = True
| otherwise = False
splitLines [] = []
splitLines cs =
let (pre,suf) = break isLineTerminator cs
in pre : case suf of
('\r':'\n':rest) -> splitLines rest
('\r':rest) -> splitLines rest
('\n':rest) -> splitLines rest
_ -> []
isLineTerminator c = (c == '\r' || c == '\n')
a `plus` b = a+b
data a `Pair` b = a `Pair` b
deriving (Show)
-- Here we're trying to write standard list functions from scratch
long::[a] -> Int
long [] = 0
long (x:xs) = 1+long(xs)
empty :: [a] -> Bool
empty [] = True
empty _ = False
top :: [a] -> a
top list
| (empty list) = error "Empty list, silly!"
| otherwise = x
where
(x:rest) = list
remainder :: [a] -> [a]
remainder list
| (empty list) = error "Empty list, silly!"
| otherwise = rest
where
(x:rest) = list
listadder :: [a] -> [a] -> [a]
listadder lista listb
| empty lista = listb
| otherwise = x: (listadder rest listb)
where
(x:rest) = lista
cat :: [[a]] -> [a]
cat list
| empty list = []
| otherwise = listadder x (cat rest)
where
(x:rest) = list
rev:: [a] -> [a]
rev [] = []
rev (x:xs) = listadder (rev xs) [x]
final :: [a] -> a
final list = top (rev list)
finaller :: [a] -> a
finaller list
| empty list = error "Empty list, silly!"
| (not (empty xs)) = finaller xs
| (empty xs) = x
| otherwise = error "Invalid arguments!"
where
(x:xs) = list
ender :: [a] -> [a]
ender list
| empty list = error "Empty list, silly!"
| otherwise = rest
where
(x:rest) = list
conjunct :: [Bool] -> Bool
conjunct list
| empty list = error "Empty list!"
| rest==[] = x
| otherwise = (x && (conjunct rest))
where
(x:rest)=list
disjunct :: [Bool] -> Bool
disjunct list
| empty list = error "Empty list, silly!"
| rest == [] = x
| otherwise = (x || (disjunct rest))
where
(x:rest) = list
|
soumyadsanyal/99
|
ch03/soumya.hs
|
gpl-2.0
| 4,980 | 0 | 14 | 1,253 | 2,491 | 1,279 | 1,212 | 210 | 4 |
module Html.GenHtml where
import Test.QuickCheck
import Control.Applicative
import Data.List
import Html.ShowHtml
import Html.HtmlNode
instance Arbitrary HtmlNode where
arbitrary = sized $ arbNode flowNodes []
arbNode :: [NodeName] -> [NodeName] -> Int -> Gen HtmlNode
arbNode _ _ 0 = Text <$> arbText
arbNode allowed forbidden n =
oneof [ node 0 n allowed forbidden,
node 1 n allowed forbidden,
node 2 n allowed forbidden ]
node :: Int -> Int -> [NodeName] -> [NodeName] -> Gen HtmlNode
node size n allowed forbidden = do
name <- elements (allowed \\ forbidden)
if size == 0
then frequency [ (1, Node <$> arbAttrs name <*> pure []),
(3, nodeWithText name) ]
else do
let n' = (n-1) `div` size
subs <- children name size n' allowed forbidden
attrs <- arbAttrs name
return $ Node attrs subs
where
children :: NodeName -> Int -> Int -> [NodeName] -> [NodeName] -> Gen [HtmlNode]
children name size n allowed forbidden = vectorOf size $ do
let a' = allowed `intersect` (subNodes name)
let f' = forbidden `union` (forbiddenSubNodes name)
if null a'
then Text <$> arbText
else arbNode a' f' n
arbAttrs :: String -> Gen NodeAttrs
arbAttrs name = NodeAttrs name <$> pure Nothing <*> arbClasses
arbClasses = oneof [ return [], vectorOf 1 arbClassName, vectorOf 2 arbClassName ]
arbClassName = elements [ "big", "small", "title", "lhs" ]
nodeWithText name = do
attrs <- arbAttrs name
text <- Text <$> arbText
return $ Node attrs [text]
type NodeName = String
subNodes :: NodeName -> [NodeName]
subNodes "body" = flowNodes
subNodes "a" = flowNodes `union` phrasingNodes
subNodes "form" = flowNodes
subNodes _ = phrasingNodes
forbiddenSubNodes :: NodeName -> [NodeName]
forbiddenSubNodes "form" = ["form"]
forbiddenSubNodes _ = []
-- flowNodes = [ "a", "p", "h1", "h2", "h3", "form", "div", "span" ]
flowNodes = [ "p", "h1", "h2", "h3", "form", "div" ]
flowNodesNoForm = [ "a", "p", "h1", "h2", "h3", "form", "div", "span" ]
phrasingNodes = [ "span" ]
-- flowNodes = [ "a", "abbr", "address", "article", "aside", "audio", "b","bdo", "bdi", "blockquote", "br", "button", "canvas", "cite", "code", "command", "data", "datalist", "del", "details", "dfn", "div", "dl", "em", "embed", "fieldset", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hgroup", "hr", "i", "iframe", "img", "input", "ins", "kbd", "keygen", "label", "main", "map", "mark", "math", "menu", "meter", "nav", "noscript", "object", "ol", "output", "p", "pre", "progress", "q", "ruby", "s", "samp", "script", "section", "select", "small", "span", "strong", "sub", "sup", "svg", "table", "template", "textarea", "time", "ul", "var", "video", "wbr" ]
-- sectionNodes = [ "article", "aside", "nav", "section" ]
-- headingNodes = [ "h1", "h2", "h3", "h4", "h5", "h6", "hgroup" ]
-- phrasingNodes = [ "abbr", "audio", "b", "bdo", "br", "button", "canvas", "cite", "code", "command", "datalist", "dfn", "em", "embed", "i", "iframe", "img", "input", "kbd", "keygen", "label", "mark", "math", "meter", "noscript", "object", "output", "progress", "q", "ruby", "samp", "script", "select", "small", "span", "strong", "sub", "sup", "svg", "textarea", "time", "var", "video", "wbr" ]
-- formNodes = [ "button", "fieldset", "input", "keygen", "label", "meter", "object", "output", "progress", "select", "textarea" ]
arbNodeName :: Gen String
arbNodeName = elements [ "h1", "h2", "div", "span", "form", "p", "a" ]
arbNodeNameNoContent :: Gen String
arbNodeNameNoContent = elements [ "input" ]
arbText = return "a"
-- arbText = elements [ "Lorem Ipsum",
-- "Dolor sit amet",
-- "consectetur adipiscing elit",
-- "Vestibulum vel ante",
-- "ut turpis dapibus blandit" ]
s = sample' (arbitrary :: Gen HtmlNode) >>= putStrLn . unlines . map show
ss = sample' (arbitrary :: Gen HtmlNode) >>= (return . map pphtml) >>= putStrLn . unlines
|
pbevin/toycss
|
src/html/GenHtml.hs
|
gpl-2.0
| 4,044 | 0 | 15 | 828 | 880 | 468 | 412 | 59 | 3 |
{-
Copyright 2012, 2013, 2014 Colin Woodbury <[email protected]>
This file is part of Aura.
Aura 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.
Aura 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 Aura. If not, see <http://www.gnu.org/licenses/>.
-}
module Aura.Conflicts where
import Text.Regex.PCRE ((=~))
import Aura.Core
import Aura.Languages
import Aura.Monad.Aura
import Aura.Settings.Base
import Aura.Utils.Numbers (version)
---
-- Questions to be answered in conflict checks:
-- 1. Is the package ignored in `pacman.conf`?
-- 2. Is the version requested different from the one provided by
-- the most recent version?
checkConflicts :: Package -> Dep -> Aura ()
checkConflicts pkg dep = ask >>= \ss ->
case realPkgConflicts ss pkg dep of
Nothing -> return ()
Just msg -> failure msg
-- | Must be called with a (f)unction that yields the version number
-- of the most up-to-date form of the package.
realPkgConflicts :: Settings -> Package -> Dep -> Maybe Error
realPkgConflicts ss pkg dep
| isIgnored name toIgnore = Just failMsg1
| isVersionConflict reqVer curVer = Just failMsg2
| otherwise = Nothing
where name = pkgNameOf pkg
curVer = pkgVersionOf pkg
reqVer = depVerDemandOf dep
lang = langOf ss
toIgnore = ignoredPkgsOf ss
failMsg1 = getRealPkgConflicts_2 name lang
failMsg2 = getRealPkgConflicts_1 name curVer (show reqVer) lang
-- Compares a (r)equested version number with a (c)urrent up-to-date one.
-- The `MustBe` case uses regexes. A dependency demanding version 7.4
-- SHOULD match as `okay` against version 7.4, 7.4.0.1, or even 7.4.0.1-2.
isVersionConflict :: VersionDemand -> String -> Bool
isVersionConflict Anything _ = False
isVersionConflict (LessThan r) c = version c >= version r
isVersionConflict (MoreThan r) c = version c <= version r
isVersionConflict (MustBe r) c = not $ c =~ ('^' : r)
isVersionConflict (AtLeast r) c | version c > version r = False
| isVersionConflict (MustBe r) c = True
| otherwise = False
|
vigoos/Farrago-OS
|
aura-master/aura-master/src/Aura/Conflicts.hs
|
gpl-2.0
| 2,584 | 0 | 11 | 591 | 445 | 226 | 219 | 32 | 2 |
-- PolRepTDA.hs
-- Implementación de los polinomios mediante tipos de datos algebraicos.
-- José A. Alonso Jiménez https://jaalonso.github.com
-- =====================================================================
{-# OPTIONS_GHC -fno-warn-unused-top-binds #-}
module Tema_21.PolRepTDA
( Polinomio,
polCero, -- Polinomio a
esPolCero, -- Polinomio a -> Bool
consPol, -- (Num a, Eq a)) => Int -> a -> Polinomio a -> Polinomio a
grado, -- Polinomio a -> Int
coefLider, -- Num t => Polinomio t -> t
restoPol -- Polinomio t -> Polinomio t
) where
-- ---------------------------------------------------------------------
-- TAD de los polinomios mediante un tipo de dato algebraico --
-- ---------------------------------------------------------------------
-- Representamos un polinomio mediante los constructores ConsPol y
-- PolCero. Por ejemplo, el polinomio
-- 6x^4 -5x^2 + 4x -7
-- se representa por
-- ConsPol 4 6 (ConsPol 2 (-5) (ConsPol 1 4 (ConsPol 0 (-7) PolCero)))
data Polinomio a = PolCero
| ConsPol Int a (Polinomio a)
deriving Eq
-- ---------------------------------------------------------------------
-- Escritura de los polinomios --
-- ---------------------------------------------------------------------
-- (escribePol p) es la cadena correspondiente al polinomio p. Por
-- ejemplo,
-- λ> escribePol (consPol 4 3 (consPol 2 (-5) (consPol 0 3 polCero)))
-- "3*x^4 + -5*x^2 + 3"
escribePol :: (Num a, Show a, Eq a) => Polinomio a -> String
escribePol PolCero = "0"
escribePol (ConsPol 0 b PolCero) = show b
escribePol (ConsPol 0 b p) = concat [show b, " + ", escribePol p]
escribePol (ConsPol 1 b PolCero) = show b ++ "*x"
escribePol (ConsPol 1 b p) = concat [show b, "*x + ", escribePol p]
escribePol (ConsPol n 1 PolCero) = "x^" ++ show n
escribePol (ConsPol n b PolCero) = concat [show b, "*x^", show n]
escribePol (ConsPol n 1 p) = concat ["x^", show n, " + ", escribePol p]
escribePol (ConsPol n b p) = concat [show b, "*x^", show n, " + ", escribePol p]
-- Procedimiento de escritura de polinomios.
instance (Num a, Show a, Eq a) => Show (Polinomio a) where
show = escribePol
-- ---------------------------------------------------------------------
-- Ejemplos de polinomios --
-- ---------------------------------------------------------------------
-- Ejemplos de polinomios con coeficientes enteros:
ejPol1, ejPol2, ejPol3 :: Polinomio Int
ejPol1 = consPol 4 3 (consPol 2 (-5) (consPol 0 3 polCero))
ejPol2 = consPol 5 1 (consPol 2 5 (consPol 1 4 polCero))
ejPol3 = consPol 4 6 (consPol 1 2 polCero)
-- Comprobación de escritura:
-- > ejPol1
-- 3*x^4 + -5*x^2 + 3
-- > ejPol2
-- x^5 + 5*x^2 + 4*x
-- > ejPol3
-- 6*x^4 + 2*x
-- ---------------------------------------------------------------------
-- Implementación de la especificación --
-- ---------------------------------------------------------------------
-- polCero es el polinomio cero. Por ejemplo,
-- > polCero
-- 0
polCero :: Polinomio a
polCero = PolCero
-- (esPolCero p) se verifica si p es el polinomio cero. Por ejemplo,
-- esPolCero polCero == True
-- esPolCero ejPol1 == False
esPolCero :: Polinomio a -> Bool
esPolCero PolCero = True
esPolCero _ = False
-- (consPol n b p) es el polinomio bx^n+p. Por ejemplo,
-- ejPol2 == x^5 + 5*x^2 + 4*x
-- consPol 3 0 ejPol2 == x^5 + 5*x^2 + 4*x
-- consPol 3 2 polCero == 2*x^3
-- consPol 6 7 ejPol2 == 7*x^6 + x^5 + 5*x^2 + 4*x
-- consPol 4 7 ejPol2 == x^5 + 7*x^4 + 5*x^2 + 4*x
-- consPol 5 7 ejPol2 == 8*x^5 + 5*x^2 + 4*x
consPol :: (Num a, Eq a) => Int -> a -> Polinomio a -> Polinomio a
consPol _ 0 p = p
consPol n b PolCero = ConsPol n b PolCero
consPol n b (ConsPol m c p)
| n > m = ConsPol n b (ConsPol m c p)
| n < m = ConsPol m c (consPol n b p)
| b+c == 0 = p
| otherwise = ConsPol n (b+c) p
-- (grado p) es el grado del polinomio p. Por ejemplo,
-- ejPol3 == 6*x^4 + 2*x
-- grado ejPol3 == 4
grado :: Polinomio a -> Int
grado PolCero = 0
grado (ConsPol n _ _) = n
-- (coefLider p) es el coeficiente líder del polinomio p. Por ejemplo,
-- ejPol3 == 6*x^4 + 2*x
-- coefLider ejPol3 == 6
coefLider :: Num t => Polinomio t -> t
coefLider PolCero = 0
coefLider (ConsPol _ b _) = b
-- (restoPol p) es el resto del polinomio p. Por ejemplo,
-- ejPol3 == 6*x^4 + 2*x
-- restoPol ejPol3 == 2*x
-- ejPol2 == x^5 + 5*x^2 + 4*x
-- restoPol ejPol2 == 5*x^2 + 4*x
restoPol :: Polinomio t -> Polinomio t
restoPol PolCero = PolCero
restoPol (ConsPol _ _ p) = p
|
jaalonso/I1M-Cod-Temas
|
src/Tema_21/PolRepTDA.hs
|
gpl-2.0
| 4,853 | 0 | 9 | 1,220 | 920 | 498 | 422 | 50 | 1 |
-- | Module for the 'Monster' type and related functions. 'Monster'
-- represents a Sil monster, containing all the information we need
-- to simulate attacks by or against the monster.
module Monster where
import qualified Data.Map as Map
import Rdice
import Types
import Text.Regex.Posix ((=~))
import Control.Applicative
import Data.Maybe(fromJust)
import Data.List(find)
--import Data.List(filter,null)
-- | A monster's critical resistance: most monsters have none, but some
-- are resistance (halve crit dice) or completely immune.
data MonsterCritRes = NoCritRes | CritResistant | CritImmune
deriving (Show,Eq)
-- | A monster's alertness; the default is 'Alert', but it can be set
-- to 'Unwary' or 'Sleeping' to simulate attacks against an unwary or
-- sleeping monster.
data Alertness = Alert | Unwary | Sleeping
deriving (Show,Eq)
--seenByPlayer defaults to true (Fsil doesn't do perception checks for
--Sulrauko etc); use this to make the monster invisible
unseen :: Monster -> Monster
unseen m = m {seenByPlayer = False}
-- | 'Monster' represents a Sil monster, containing all the information
-- we need to simulate attacks by or against the monster. Many of the
-- fields are identical in name and function to their 'Player'
-- counterparts.
data Monster = Monster { name :: String,
depth :: Int,
-- ^ the depth at which a monster is usually found;
-- doesn't affect any combat calculations, but can
-- be interesting for
attacks :: [Attack],
evasion :: Int,
lightRadius :: Int,
alertness :: Alertness,
protDice :: Dice,
speed :: Int,
-- ^ The monster's speed, between 1 and 4. Currently
-- not used by fsil.
will :: Int,
health :: Dice,
-- ^ The dice rolled to determine the monster's max
-- hitpoints.
hatesLight :: Bool,
-- ^Some monsters are vulnerable to strong light.
glows :: Bool,
-- ^Balrogs glow, meaning that they're always
-- visible.
seenByPlayer :: Bool,
-- Fsil doesn't currently do perception checks for
-- whether the player can see an invisible monster
-- or not; if SeenByPlayer is True, the player can
-- always see the monster (if it's not too dark),
-- and if SeenByPlayer is False, the monster will
-- be invisible regardless of light. Defaults to
-- True for all monsters.
resistances :: Map.Map Element Int,
criticalRes :: MonsterCritRes,
slainBy :: Maybe Slay,
-- ^ SlayOrcs if the monster is an orc, etc;
-- Nothing if there is no slay for this monster
-- in the game.
onLitSquare :: Bool
} deriving Show
dungeonLight m = if onLitSquare m then 1 else 0
-- | Check whether a monster's name matches a regular expression (given as
-- a string)
matchMonster :: String -> Monster -> Bool
matchMonster regex mons = (name mons) =~ regex
baseCritThreshold = 7.0
-- | The base critical threshold of a monster is determined by it's damage
-- dice.
monsterCritThreshold :: Dice -> Double
monsterCritThreshold dice = baseCritThreshold + 2 * fromIntegral (nDice dice)
modifyEvasionWith :: (Int -> Int) -> Monster -> Monster
modifyEvasionWith func monster = monster {evasion = func $ evasion monster}
modifyAccuracyWith :: (Int -> Int) -> Monster -> Monster
modifyAccuracyWith func monster =
let newAttacks = Prelude.map (adjustAccuracy func) (attacks monster)
adjustAccuracy func attack = attack { accuracy = func $ accuracy attack}
in monster {attacks = newAttacks}
modifyCritThreshold :: (Double -> Double) -> Monster -> Monster
modifyCritThreshold func monster =
let newAttacks = Prelude.map (adjustCritThres func) (attacks monster)
adjustCritThres f a = a { critThreshold = f $ critThreshold a }
in monster {attacks = newAttacks}
--Finds the first monster in monsList whose name matches nameRegex.
--Gives preference to monsters whose name starts with regex, so
--getMonster "Morgoth" will return the monster "Morgoth, Lord of Darkness"
--rather than "Gorthaur, servant of Morgoth".
--If no monster's name matches nameRegex, returns the first monster of
--monsList.
getMonster :: String -> [Monster] -> Monster
getMonster nameRegex monsList =
let startsWithName = '^' : nameRegex
completeName = startsWithName ++ "$"
completeMatch = find (matchMonster completeName) monsList
matchesBeginning = find (matchMonster startsWithName) monsList
matchesSomewhere = find (matchMonster nameRegex) monsList
defaultValue = head monsList
in fromJust $ completeMatch <|> matchesBeginning <|>
matchesSomewhere <|> Just defaultValue
|
kryft/fsil
|
Monster.hs
|
gpl-2.0
| 5,381 | 0 | 12 | 1,714 | 748 | 435 | 313 | 60 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import SequenceFormats.FreqSum (FreqSumEntry(..), readFreqSumStdIn, printFreqSumStdOut,
FreqSumHeader(..))
import SequenceFormats.Utils (liftParsingErrors, Chrom(..))
import Control.Applicative (optional)
import Control.Monad.Trans.Class (lift)
import Data.Char (isSpace)
import Data.Text (unpack, Text)
import qualified Data.Attoparsec.Text as A
-- import Debug.Trace (trace)
import Data.Version (showVersion)
import Pipes (Producer, runEffect, yield, (>->), next, cat)
import Pipes.Attoparsec (parsed)
import qualified Pipes.Prelude as P
import Pipes.Safe (runSafeT)
import qualified Pipes.Text.IO as PT
import Prelude hiding (FilePath)
import qualified Text.PrettyPrint.ANSI.Leijen as PT
import Turtle hiding (stdin, cat)
import Paths_rarecoal_tools (version)
type BedEntry = (Chrom, Int, Int)
data IntervalStatus = BedBehind | FSwithin | BedAhead
argParser :: Parser (Maybe FilePath, Maybe Double, Maybe Text)
argParser = (,,) <$>
optional (optPath "bed" 'b' "a bed file that contains the regions to be included") <*>
optional (optDouble "missingness" 'm' "the maximum missingness allowed (0-1). Default=1") <*>
optional (optText "sampleMissingness" 's' "an optional sample name to condition on having \
\no missingness")
desc :: Description
desc = Description $ PT.text ("filterFreqSum version " ++ showVersion version ++
": a program to filter freqSum files.")
main :: IO ()
main = runSafeT $ do
(maybeBedFile, maybeMissingness, maybeSampleMissingness) <-
options desc argParser
(fsHeader, fsBody) <- readFreqSumStdIn
let fsProd = case maybeBedFile of
Nothing -> fsBody
Just bedFile ->
let textProd = PT.readFile . unpack . format fp $ bedFile
bedProd = parsed bedFileParser textProd >>= liftParsingErrors
in filterThroughBed bedProd fsBody
let missingnessFilterPipe = case maybeMissingness of
Nothing -> cat
Just m -> P.filter (missingnessFilter m (fshCounts fsHeader))
let sampleMissingnessFilterPipe = case maybeSampleMissingness of
Nothing -> cat
Just s' ->
let samplePos = fst . head . filter ((==s') . snd) . zip [0..] . fshNames $ fsHeader
in P.filter (sampleMissingnessFilter samplePos)
runEffect $ fsProd >-> missingnessFilterPipe >-> sampleMissingnessFilterPipe >->
printFreqSumStdOut fsHeader
filterThroughBed :: (Monad m) => Producer BedEntry m () -> Producer FreqSumEntry m () ->
Producer FreqSumEntry m ()
filterThroughBed bedProd fsProd = do
b <- lift $ next bedProd
let (bedCurrent, bedRest) = case b of
Left _ -> error "Bed file empty or not readable"
Right r -> r
f' <- lift $ next fsProd
let (fsCurrent, fsRest) = case f' of
Left _ -> error "FreqSum stream empty or not readable"
Right r -> r
go bedCurrent fsCurrent bedRest fsRest
where
go bedCurrent fsCurrent bedRest fsRest = do
let recurseNextBed = do
b <- lift $ next bedRest
case b of
Left () -> return ()
Right (nextBed, bedRest') -> go nextBed fsCurrent bedRest' fsRest
recurseNextFS = do
f' <- lift $ next fsRest
case f' of
Left () -> return ()
Right (nextFS, fsRest') -> go bedCurrent nextFS bedRest fsRest'
case bedCurrent `checkIntervalStatus` fsCurrent of
BedBehind -> recurseNextBed
BedAhead -> recurseNextFS
FSwithin -> do
yield fsCurrent
recurseNextFS
missingnessFilter :: Double -> [Int] -> FreqSumEntry -> Bool
missingnessFilter m hapNums fs =
let num = sum [n | (n, freq) <- zip hapNums (fsCounts fs), freq == Nothing]
denom = sum hapNums
in (fromIntegral num / fromIntegral denom) <= m
sampleMissingnessFilter :: Int -> FreqSumEntry -> Bool
sampleMissingnessFilter filterPos fs = (fsCounts fs) !! filterPos /= Nothing
checkIntervalStatus :: BedEntry -> FreqSumEntry -> IntervalStatus
checkIntervalStatus (bedChrom, bedStart, bedEnd) (FreqSumEntry fsChrom' fsPos' _ _ _) =
case bedChrom `compare` fsChrom' of
LT -> BedBehind
GT -> BedAhead
EQ -> if bedStart + 1 > fsPos' then
BedAhead
else
if bedEnd < fsPos' then BedBehind else FSwithin
bedFileParser :: A.Parser BedEntry
bedFileParser = (,,) <$> chrom <* A.skipSpace <*> A.decimal <* A.skipSpace <*> A.decimal <*
A.endOfLine
where
chrom = Chrom <$> A.takeTill isSpace
|
stschiff/rarecoal-tools
|
src-filterFreqSum/filterFreqSum.hs
|
gpl-3.0
| 4,717 | 0 | 25 | 1,247 | 1,334 | 697 | 637 | 98 | 7 |
{-# LANGUAGE NamedFieldPuns #-}
{-
This module provides the main function perform.
See license info at end of file.
-}
module Git.Pile.PileLib
(perform
,Action(MakePileable,RunGitCommand)
,Recursiveness(Recursive,NonRecursive)) where
import Git.Pile.Types
import Git.Pile.PathConstants
import Git.Pile.ReposToWorkOn(reposToWorkOn)
import Git.Pile.DoWork(doWork)
perform :: Action -> IO ()
perform action
= reposToWorkOn action
>>= doWork action
{-GPLv3.0 Timothy Hobbs [email protected]
Copyright 2013.
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/>.-}
|
timthelion/git-toggle
|
Git/Pile/PileLib.hs
|
gpl-3.0
| 1,136 | 0 | 7 | 171 | 99 | 62 | 37 | 18 | 1 |
{-# OPTIONS_GHC -XTypeFamilies -XTypeSynonymInstances -XOverloadedStrings -XRecursiveDo -pgmF marxup3 -F #-}
module Paper where
import MarXup
import MarXup.Latex
import MarXup.Tex
import Data.Monoid
import Framework
import Data.List
import PaperData
acmCategories,keywords,abstract,header :: TeX
acmCategories = do
cmdn_ "category" ["F.4.1","Mathematical Logic","Lambda calculus and related system"]
cmdn_ "category" ["D.3.3","Language Constructs and Features","Concurrent programming structures"]
keywords = do
cmd0 "keywords"
mconcat $ intersperse ", " ["deforestation","fusion", "..."]
abstract = env "abstract" «»
header = do
maketitle
abstract
keywords
outputTexMp :: Bool -> MPOutFormat -> String -> IO ()
outputTexMp includeAppendix fmt name = renderToDisk' fmt name $ latexDocument preamble «
@header
arstras arstarstarst arst arsta rst
tdiqlwfjhpd;wpdh
@(emph «rstarst»)
@intro
@intro<-section«Introduction»
@section«Conclusion»
»
|
jyp/ControlledFusion
|
paper/Paper.hs
|
gpl-3.0
| 1,018 | 17 | 10 | 175 | 250 | 134 | 116 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.YouTube.PlayListItems.Update
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates an existing resource.
--
-- /See:/ <https://developers.google.com/youtube/ YouTube Data API v3 Reference> for @youtube.playlistItems.update@.
module Network.Google.Resource.YouTube.PlayListItems.Update
(
-- * REST Resource
PlayListItemsUpdateResource
-- * Creating a Request
, playListItemsUpdate
, PlayListItemsUpdate
-- * Request Lenses
, pliuXgafv
, pliuPart
, pliuUploadProtocol
, pliuAccessToken
, pliuUploadType
, pliuPayload
, pliuOnBehalfOfContentOwner
, pliuCallback
) where
import Network.Google.Prelude
import Network.Google.YouTube.Types
-- | A resource alias for @youtube.playlistItems.update@ method which the
-- 'PlayListItemsUpdate' request conforms to.
type PlayListItemsUpdateResource =
"youtube" :>
"v3" :>
"playlistItems" :>
QueryParams "part" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PlayListItem :>
Put '[JSON] PlayListItem
-- | Updates an existing resource.
--
-- /See:/ 'playListItemsUpdate' smart constructor.
data PlayListItemsUpdate =
PlayListItemsUpdate'
{ _pliuXgafv :: !(Maybe Xgafv)
, _pliuPart :: ![Text]
, _pliuUploadProtocol :: !(Maybe Text)
, _pliuAccessToken :: !(Maybe Text)
, _pliuUploadType :: !(Maybe Text)
, _pliuPayload :: !PlayListItem
, _pliuOnBehalfOfContentOwner :: !(Maybe Text)
, _pliuCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PlayListItemsUpdate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pliuXgafv'
--
-- * 'pliuPart'
--
-- * 'pliuUploadProtocol'
--
-- * 'pliuAccessToken'
--
-- * 'pliuUploadType'
--
-- * 'pliuPayload'
--
-- * 'pliuOnBehalfOfContentOwner'
--
-- * 'pliuCallback'
playListItemsUpdate
:: [Text] -- ^ 'pliuPart'
-> PlayListItem -- ^ 'pliuPayload'
-> PlayListItemsUpdate
playListItemsUpdate pPliuPart_ pPliuPayload_ =
PlayListItemsUpdate'
{ _pliuXgafv = Nothing
, _pliuPart = _Coerce # pPliuPart_
, _pliuUploadProtocol = Nothing
, _pliuAccessToken = Nothing
, _pliuUploadType = Nothing
, _pliuPayload = pPliuPayload_
, _pliuOnBehalfOfContentOwner = Nothing
, _pliuCallback = Nothing
}
-- | V1 error format.
pliuXgafv :: Lens' PlayListItemsUpdate (Maybe Xgafv)
pliuXgafv
= lens _pliuXgafv (\ s a -> s{_pliuXgafv = a})
-- | The *part* parameter serves two purposes in this operation. It
-- identifies the properties that the write operation will set as well as
-- the properties that the API response will include. Note that this method
-- will override the existing values for all of the mutable properties that
-- are contained in any parts that the parameter value specifies. For
-- example, a playlist item can specify a start time and end time, which
-- identify the times portion of the video that should play when users
-- watch the video in the playlist. If your request is updating a playlist
-- item that sets these values, and the request\'s part parameter value
-- includes the contentDetails part, the playlist item\'s start and end
-- times will be updated to whatever value the request body specifies. If
-- the request body does not specify values, the existing start and end
-- times will be removed and replaced with the default settings.
pliuPart :: Lens' PlayListItemsUpdate [Text]
pliuPart
= lens _pliuPart (\ s a -> s{_pliuPart = a}) .
_Coerce
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pliuUploadProtocol :: Lens' PlayListItemsUpdate (Maybe Text)
pliuUploadProtocol
= lens _pliuUploadProtocol
(\ s a -> s{_pliuUploadProtocol = a})
-- | OAuth access token.
pliuAccessToken :: Lens' PlayListItemsUpdate (Maybe Text)
pliuAccessToken
= lens _pliuAccessToken
(\ s a -> s{_pliuAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pliuUploadType :: Lens' PlayListItemsUpdate (Maybe Text)
pliuUploadType
= lens _pliuUploadType
(\ s a -> s{_pliuUploadType = a})
-- | Multipart request metadata.
pliuPayload :: Lens' PlayListItemsUpdate PlayListItem
pliuPayload
= lens _pliuPayload (\ s a -> s{_pliuPayload = a})
-- | *Note:* This parameter is intended exclusively for YouTube content
-- partners. The *onBehalfOfContentOwner* parameter indicates that the
-- request\'s authorization credentials identify a YouTube CMS user who is
-- acting on behalf of the content owner specified in the parameter value.
-- This parameter is intended for YouTube content partners that own and
-- manage many different YouTube channels. It allows content owners to
-- authenticate once and get access to all their video and channel data,
-- without having to provide authentication credentials for each individual
-- channel. The CMS account that the user authenticates with must be linked
-- to the specified YouTube content owner.
pliuOnBehalfOfContentOwner :: Lens' PlayListItemsUpdate (Maybe Text)
pliuOnBehalfOfContentOwner
= lens _pliuOnBehalfOfContentOwner
(\ s a -> s{_pliuOnBehalfOfContentOwner = a})
-- | JSONP
pliuCallback :: Lens' PlayListItemsUpdate (Maybe Text)
pliuCallback
= lens _pliuCallback (\ s a -> s{_pliuCallback = a})
instance GoogleRequest PlayListItemsUpdate where
type Rs PlayListItemsUpdate = PlayListItem
type Scopes PlayListItemsUpdate =
'["https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl",
"https://www.googleapis.com/auth/youtubepartner"]
requestClient PlayListItemsUpdate'{..}
= go _pliuPart _pliuXgafv _pliuUploadProtocol
_pliuAccessToken
_pliuUploadType
_pliuOnBehalfOfContentOwner
_pliuCallback
(Just AltJSON)
_pliuPayload
youTubeService
where go
= buildClient
(Proxy :: Proxy PlayListItemsUpdateResource)
mempty
|
brendanhay/gogol
|
gogol-youtube/gen/Network/Google/Resource/YouTube/PlayListItems/Update.hs
|
mpl-2.0
| 7,245 | 0 | 19 | 1,612 | 906 | 535 | 371 | 130 | 1 |
-- This module deals with how we represent the imformation that is
-- stored in an `.ogz` file.
{-# LANGUAGE TemplateHaskell #-}
module Types where
import HomoTuple
import Control.Applicative
import Control.DeepSeq
import Control.Monad
import Data.Binary
import Data.Bits
import Data.ByteString (ByteString)
import Data.ByteString.Short (ShortByteString)
import Data.DeriveTH
import Data.Maybe
import GHC.Generics
import Orphans ()
import Prelude.Unicode
import Test.QuickCheck (Arbitrary, Gen, arbitrary, choose)
import qualified Test.SmallCheck.Series as SC
-- High-Level Structure --------------------------------------------------------
newtype GameType = GameType { unGameType ∷ ShortByteString }
deriving (Show,Ord,Eq,Generic)
-- TODO What does this mean? I think this is the maximum geometry
-- depth, but I need to double check that.
newtype WorldSize = WorldSize { unWorldSize ∷ Int }
deriving (Show,Ord,Eq,Generic)
mkWorldSize ∷ Int → Maybe WorldSize
mkWorldSize n | n<1 ∨ n>31 = Nothing
mkWorldSize n = Just $ WorldSize n
-- TODO What is the point of these? In all of the built-in maps,
-- these are both set to zero.
data Extras = Extras {
extraEntInfoSize ∷ !Word16
, extrasLength ∷ !Word16
} deriving (Show,Ord,Eq,Generic)
data OGZ = OGZ {
ogzWorldSize ∷ WorldSize
, ogzVars ∷ [OGZVar]
, ogzGameType ∷ GameType
, ogzExtras ∷ Extras
, ogzTextureMRU ∷ TextureMRU
, ogzEntities ∷ [Entity]
, ogzGeometry ∷ LzTup8 Octree
} deriving (Show,Ord,Eq,Generic)
-- Variables -------------------------------------------------------------------
data OGZVar = OGZVar !ByteString !OGZVal
deriving (Show,Ord,Eq,Generic)
data OGZVal = OInt !Word32 | OFloat !Float | OStr !ByteString
deriving (Show,Ord,Eq,Generic)
-- Texture Stuff ---------------------------------------------------------------
newtype TextureMRU = TextureMRU [Word16]
deriving (Show,Ord,Eq,Generic)
newtype Textures = Textures (Tup6 Word16)
deriving (Show,Ord,Eq,Generic)
-- Entities --------------------------------------------------------------------
-- TODO Decide if this is useful and then use it or toss it.
--
-- This just documents the data contained in various entities. Using
-- this type would be a lot more code and provide questionable
-- value. Also, it's not clear what to do with the unused parameters.
--
-- If we just enforce that they're always zero, this probably wont agree with
-- the actual bits-on-disk from the map files.
--
-- TODO Can we do an experiement to see if this is true?
--
-- Also, if it's NOT true, then maybe that doesn't matter. Instead
-- of requiring that mapfiles can be reproduce in a bit-perfect
-- way. We could store the expected parse along with all of the example
-- bytestrings. For example, the current types of an on-disk test-suite is [1]:
--
-- ∀(ty∷Mapfile a⇒Proxy a, file∷[ByteString]),
-- ∀bs←file,
-- bs ≡ dump (load bs `asProxyType` ty)
--
-- This might be too restrictive, the following[2] gives weaker
-- guarentees, but should be sufficient for preventing regressions:
--
-- ∀ (Mapfile a,Binary a) ⇒ file∷Map ByteString a,
-- ∀ (bs,v)←file,
-- load bs ≡ v
--
-- TODO Implement property #2, and make property #1 opt-in.
data EntData = AEmpty
| ALight { entLightSrc,entRadius,entIntensity ∷ !Word16 }
| AMapModel { entAngle,entIdx ∷ !Word16 }
| APlayerStart { entAngle,entTeam ∷ !Word16 }
| AEnvMap { entRadius ∷ !Word16 }
| AParticles
| ASound
| ASpotLight
| AShells
| ABullets
| ARockets
| ARounds
| AGrenades
| ACartridges
| AHealth
| ABoost
| AGreenArmour
| AYellowArmour
| AQuad
| ATeleport { entIdx,entModel,entTag ∷ !Word16 }
| ATeledest { entAngle,entIdx ∷ !Word16 }
| AMonster { entAngle,entMonsterTy ∷ !Word16 }
| ACarrot { entTag,entCarrotTy ∷ !Word16 }
| AJumpPad { entPushX,entPushY,entPushZ ∷ !Word16 }
| ABase
| ARespawnPoint
| ABox
| ABarrel { entAngle,entIdx,entWight,entHealth ∷ !Word16 }
| APlatform { entAngle,endIdx,entTag,entSpeed ∷ !Word16 }
| AElevator { entAngle,endIdx,entTag,entSpeed ∷ !Word16 }
| AFlag
deriving (Show,Ord,Eq,Generic)
data EntTy = Empty | Light | MapModel | PlayerStart
| EnvMap | Particles | Sound | SpotLight
| Shells | Bullets | Rockets | Rounds
| Grenades | Cartridges | Health | Boost
| GreenArmour | YellowArmour | Quad | Teleport
| Teledest | Monster | Carrot | JumpPad
| Base | RespawnPoint | Box | Barrel
| Platform | Elevator | Flag
deriving (Show,Ord,Enum,Bounded,Eq,Generic)
newtype Vec3 = Vec3 (Tup3 Float)
deriving (Show,Ord,Eq,Generic)
newtype BVec3 = BVec3 (Tup3 Word8)
deriving (Show,Ord,Eq,Generic)
bVec3ToVec3 ∷ BVec3 → Vec3
bVec3ToVec3 (BVec3(Tup3 x y z)) = Vec3 $ Tup3 (cvt x) (cvt y) (cvt z)
where cvt c = (fromIntegral c * (2/255)) - 1
vec3ToBVec3 ∷ Vec3 → BVec3
vec3ToBVec3 (Vec3(Tup3 x y z)) = BVec3 $ Tup3 (cvt x) (cvt y) (cvt z)
where cvt c = floor $ (c+1)*(255/2)
-- TODO Why does the `unusedByte` take on different values?
-- TODO If the `unusedByte` is just the result of uninitialized data, then
-- try to change the test framework to be robust to this shit.
-- TODO Instead of having a tag and then 80 bits of info, why not
-- use an ADT? Need to understand what the attr data means per
-- entity first, though.
data Entity = Entity {
entityPosition ∷ !Vec3
, entityAttrs ∷ !(Tup5 Word16)
, entityType ∷ !EntTy
, unusedByte ∷ !Word8
} deriving (Show,Ord,Eq,Generic)
-- Faces -----------------------------------------------------------------------
-- This contains the surface normal at each corner of a (square)
-- surface. This information is used by the engine in lighting calculations.
--
-- This can be derived from the rest of the geometry.
-- For now, we are storing it so that we can rebuild map files
-- bit-for-bit, but it might make sense to drop it eventually.
data LightMapTy =
Ambient | Ambient1 | Bright | Bright1 | Dark | Dark1 | Reserved
deriving (Eq,Ord,Enum,Show,Generic)
-- The type is stored in the lowest three bits, and the remaining
-- 5 are used to store an id.
newtype LightMap = LightMap { unLightMap ∷ Word8 }
deriving (Eq,Ord,Show,Generic)
-- TODO What is this?
data Layer = Top | Bottom
deriving (Eq,Ord,Show,Enum,Generic)
-- Per-surface lighting information.
data FaceInfo = FaceInfo {
sfTexCoords ∷ !(Tup8 Word8)
, sfDims ∷ !(Tup2 Word8)
, sfPos ∷ !(Tup2 Word16)
, sfLightMap ∷ !LightMap
, sfLayer ∷ !Layer
} deriving (Eq,Ord,Show,Generic)
data Face = Face !FaceInfo
| MergedFace !FaceInfo !FaceInfo
deriving (Show,Ord,Eq,Generic)
newtype Normals = Normals (Tup4 BVec3)
deriving (Show,Ord,Eq,Generic)
data FaceWithNormals = FaceWithNormals !Face !Normals
deriving (Show,Ord,Eq,Generic)
data Faces = Faces !(Tup6 (Maybe Face))
| FacesNormals !(Tup6 (Maybe FaceWithNormals))
deriving (Show,Ord,Eq,Generic)
lightMapTy ∷ LightMap → LightMapTy
lightMapTy = toEnum . fromIntegral . (.&. 0x07) . unLightMap
lightMapId ∷ LightMap → Word8
lightMapId = (`shiftR` 3) . unLightMap
mkLightMap ∷ LightMapTy → Word8 → Maybe LightMap
mkLightMap ty lmid = do
let low3∷Word8 = fromIntegral(fromEnum ty)
let high5∷Word8 = lmid
guard $ high5 < 32
return $ LightMap $ (high5 `shiftL` 3) .|. low3
-- Geometry --------------------------------------------------------------------
newtype MergeInfo = MergeInfo (Tup4 Word16)
deriving (Eq,Ord,Show,Generic)
newtype Material = Material Word8
deriving (Show,Ord,Eq,Generic)
-- TODO This is invalid: MergeData w Nothing where (w `testBit` 7)
-- TODO This is invalid: MergeData w (Just _) where (not (w `testBit` 7))
data MergeData = MergeData !Word8 !(Maybe (Tup8 (Maybe MergeInfo)))
deriving (Eq,Ord,Show,Generic)
data Octree = NBroken (LzTup8 Octree)
| NEmpty !Textures !Properties !(Maybe MergeData)
| NSolid !Textures !Properties !(Maybe MergeData)
| NDeformed !Offsets !Textures !Properties !(Maybe MergeData)
| NLodCube !Textures !Properties (LzTup8 Octree) !(Maybe MergeData)
deriving (Show,Ord,Eq,Generic)
data Properties = Properties !(Maybe Material) !Faces
deriving (Show,Ord,Eq,Generic)
newtype Offsets = Offsets (Tup3 Word32)
deriving (Show,Ord,Eq,Generic)
-- Serial Instances -------------------------------------------------------
instance NFData GameType
instance NFData WorldSize
instance NFData Extras
instance NFData OGZ
instance NFData OGZVar
instance NFData OGZVal
instance NFData TextureMRU
instance NFData Textures
instance NFData EntData
instance NFData EntTy
instance NFData Vec3
instance NFData BVec3
instance NFData Entity
instance NFData LightMapTy
instance NFData LightMap
instance NFData Layer
instance NFData FaceInfo
instance NFData Face
instance NFData Normals
instance NFData FaceWithNormals
instance NFData Faces
instance NFData MergeInfo
instance NFData Material
instance NFData MergeData
instance NFData Octree
instance NFData Properties
instance NFData Offsets
instance Binary GameType
instance Binary WorldSize
instance Binary Extras
instance Binary OGZ
instance Binary OGZVar
instance Binary OGZVal
instance Binary TextureMRU
instance Binary Textures
instance Binary EntData
instance Binary EntTy
instance Binary Vec3
instance Binary BVec3
instance Binary Entity
instance Binary LightMapTy
instance Binary LightMap
instance Binary Layer
instance Binary FaceInfo
instance Binary Face
instance Binary Normals
instance Binary FaceWithNormals
instance Binary Faces
instance Binary MergeInfo
instance Binary Material
instance Binary MergeData
instance Binary Octree
instance Binary Properties
instance Binary Offsets
instance Monad m ⇒ SC.Serial m BVec3 where series = BVec3 <$> SC.series
instance Monad m ⇒ SC.Serial m GameType where series = GameType <$> SC.series
instance Monad m ⇒ SC.Serial m LightMap where series = LightMap <$> SC.series
instance Monad m ⇒ SC.Serial m Material where series = Material <$> SC.series
instance Monad m ⇒ SC.Serial m MergeInfo where series = MergeInfo <$> SC.series
instance Monad m ⇒ SC.Serial m Normals where series = Normals <$> SC.series
instance Monad m ⇒ SC.Serial m Offsets where series = Offsets <$> SC.series
instance Monad m ⇒ SC.Serial m TextureMRU where series = TextureMRU <$> SC.series
instance Monad m ⇒ SC.Serial m Textures where series = Textures <$> SC.series
instance Monad m ⇒ SC.Serial m Vec3 where series = Vec3 <$> SC.series
instance Monad m ⇒ SC.Serial m EntTy
instance Monad m ⇒ SC.Serial m Octree
instance Monad m ⇒ SC.Serial m Entity
instance Monad m ⇒ SC.Serial m Extras
instance Monad m ⇒ SC.Serial m Face
instance Monad m ⇒ SC.Serial m FaceInfo
instance Monad m ⇒ SC.Serial m FaceWithNormals
instance Monad m ⇒ SC.Serial m Faces
instance Monad m ⇒ SC.Serial m Layer
instance Monad m ⇒ SC.Serial m OGZ
instance Monad m ⇒ SC.Serial m OGZVal
instance Monad m ⇒ SC.Serial m OGZVar
instance Monad m ⇒ SC.Serial m Properties
instance Monad m ⇒ SC.Serial m WorldSize where
series = SC.generate $ \d → catMaybes $ mkWorldSize <$> [0..d]
-- Arbitrary Instances -------------------------------------------------------
derive makeArbitrary ''BVec3
derive makeArbitrary ''EntTy
derive makeArbitrary ''Entity
derive makeArbitrary ''Extras
derive makeArbitrary ''Face
derive makeArbitrary ''FaceInfo
derive makeArbitrary ''FaceWithNormals
derive makeArbitrary ''Faces
derive makeArbitrary ''GameType
derive makeArbitrary ''Layer
derive makeArbitrary ''LightMap
derive makeArbitrary ''Material
derive makeArbitrary ''MergeInfo
derive makeArbitrary ''Normals
derive makeArbitrary ''OGZ
derive makeArbitrary ''OGZVal
derive makeArbitrary ''OGZVar
derive makeArbitrary ''Offsets
derive makeArbitrary ''Properties
derive makeArbitrary ''TextureMRU
derive makeArbitrary ''Textures
derive makeArbitrary ''Vec3
arb ∷ Arbitrary a ⇒ Gen a
arb = arbitrary
genOctreeWDepth ∷ Int → Gen Octree
genOctreeWDepth d = do
depthBelow ← (`mod` (d∷Int)) <$> arb
let modTagBy = if depthBelow <= 0 then 3 else 4 ∷ Int
ty ← (`mod` modTagBy) <$> arb
let times8 x = LzTup8 <$> x <*> x <*> x <*> x <*> x <*> x <*> x <*> x
children = times8 $ genOctreeWDepth depthBelow
case ty of
0 → NEmpty <$> arb <*> arb <*> arb
1 → NSolid <$> arb <*> arb <*> arb
2 → NDeformed <$> arb <*> arb <*> arb <*> arb
-- Nodes with children. These aren't generated if d≤1.
3 → NBroken <$> children
4 → NLodCube <$> arb <*> arb <*> children <*> arb
_ → error "The impossible happened in genOctreeWDepth."
instance Arbitrary Octree where
arbitrary = genOctreeWDepth 3
instance Arbitrary WorldSize where
arbitrary = do
arbInt ← arbitrary
let arbSize = 1 + (arbInt `mod` 31)
Just ws ← return $ mkWorldSize arbSize
return ws
instance Arbitrary MergeData where
arbitrary = do
tag ∷ Word8 ← (`clearBit` 7) <$> arbitrary
MergeData tag <$> arbitrary
instance Monad m ⇒ SC.Serial m MergeData
|
bsummer4/ogz
|
src/Types.hs
|
agpl-3.0
| 13,903 | 0 | 17 | 3,076 | 3,641 | 1,909 | 1,732 | -1 | -1 |
{- |
Module : $Header$
Description : Solution to problem 2
License : PublicDomain
Each new term in the Fibonacci sequence is generated by adding the
previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not
exceed four million, find the sum of the even-valued terms.
-}
module Solutions.Problem002 where
import Sequences(fibs)
solution n = sum $ takeWhile (<=n) [x | x <- fibs, even x]
|
jhnesk/project-euler
|
src/Solutions/Problem002.hs
|
unlicense
| 526 | 0 | 9 | 108 | 54 | 30 | 24 | 3 | 1 |
module Lux.Core where
data Status =
Ok
| Warning
| Critical
deriving (Enum, Show)
type Description = String
type MetricKey = String
type MetricValue = Float
data Metric = Metric MetricKey MetricValue deriving (Eq, Show)
data Response = Response Status Description [Metric] deriving (Show)
|
doismellburning/lux
|
src/Lux/Core.hs
|
apache-2.0
| 296 | 4 | 7 | 51 | 97 | 57 | 40 | 11 | 0 |
module TestMain where
import FRP.Yampa
import Game.Games
import Game.GameState
import Input
testMain :: IO()
testMain = do
-- timeRef <- initializeTimeRef
reactimate initAction
inputAction
actuate
wholeGame
initAction :: IO Input
initAction = return NoInput
inputAction :: Bool -> IO (DTime, Maybe Input)
inputAction _ = return (1, Just NoInput)
actuate :: Bool -> GameState -> IO Bool
actuate _ gState = do
let state = show gState
putStrLn state
putStr "\n\n"
return False
|
no-moree-ria10/utsuEater
|
app/TestMain.hs
|
apache-2.0
| 536 | 0 | 10 | 135 | 163 | 81 | 82 | 21 | 1 |
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TypeFamilies #-}
module Language.K3.Interpreter.Evaluation where
import Control.Arrow hiding ( (+++) )
import Control.Concurrent.MVar
import Control.Monad.Reader
import Control.Monad.State
import Data.Fixed
import Data.List
import Data.Maybe
import Data.Word (Word8)
import Language.K3.Core.Annotation
import Language.K3.Core.Annotation.Analysis
import Language.K3.Core.Common
import Language.K3.Core.Declaration
import Language.K3.Core.Expression
import Language.K3.Core.Literal
import Language.K3.Core.Type
import Language.K3.Core.Utils
import Language.K3.Analysis.Core
import Language.K3.Interpreter.Data.Types
import Language.K3.Interpreter.Data.Accessors
import Language.K3.Interpreter.Values
import Language.K3.Interpreter.Collection
import Language.K3.Interpreter.Utils
import Language.K3.Interpreter.Builtins
import Language.K3.Runtime.Engine
import Language.K3.Utils.Logger
import Language.K3.Utils.Pretty
$(loggingFunctions)
-- | Monadic message passing primitive for the interpreter.
sendE :: Address -> Identifier -> Value -> Interpretation ()
sendE addr n val = liftEngine $ send addr n val
{- Interpretation -}
-- | Default values for specific types
defaultValue :: K3 Type -> Interpretation Value
defaultValue (tag -> TBool) = return $ VBool False
defaultValue (tag -> TByte) = return $ VByte 0
defaultValue (tag -> TInt) = return $ VInt 0
defaultValue (tag -> TReal) = return $ VReal 0.0
defaultValue (tag -> TString) = return $ VString ""
defaultValue t@(tag -> TOption) = return $ VOption (Nothing, vQualOfType t)
defaultValue (tag -> TAddress) = return $ VAddress defaultAddress
defaultValue (tag &&& children -> (TIndirection, [x])) =
defaultValue x >>= (\y -> (\i tg -> (i, onQualifiedType x MemImmut MemMut, tg))
<$> liftIO (newMVar y) <*> memEntTag y) >>= return . VIndirection
defaultValue (tag &&& children -> (TTuple, ch)) =
mapM (\ct -> defaultValue ct >>= return . (, vQualOfType ct)) ch >>= return . VTuple
defaultValue (tag &&& children -> (TRecord ids, ch)) =
mapM (\ct -> defaultValue ct >>= return . (, vQualOfType ct)) ch >>= return . VRecord . membersFromList . zip ids
defaultValue (tag &&& annotations -> (TCollection, anns)) =
(getComposedAnnotationT anns) >>= maybe (emptyCollection annIds) emptyAnnotatedCollection
where annIds = namedTAnnotations anns
{- TODO:
TSource
TSink
TTrigger
TBuiltIn TypeBuiltIn
TForall [TypeVarDecl]
TDeclaredVar Identifier
-}
defaultValue t = throwE . RunTimeTypeError $ "Cannot create default value for " ++ show t
-- | Interpretation of Constants.
constant :: Constant -> [Annotation Expression] -> Interpretation Value
constant (CBool b) _ = return $ VBool b
constant (CByte w) _ = return $ VByte w
constant (CInt i) _ = return $ VInt i
constant (CReal r) _ = return $ VReal r
constant (CString s) _ = return $ VString s
constant (CNone _) anns = return $ VOption (Nothing, vQualOfAnnsE anns)
constant (CEmpty _) anns =
(getComposedAnnotationE anns) >>= maybe (emptyCollection annIds) emptyAnnotatedCollection
where annIds = namedEAnnotations anns
numericOp :: (Word8 -> Word8 -> Word8)
-> (Int -> Int -> Int)
-> (Double -> Double -> Double)
-> Interpretation Value -> Value -> Value -> Interpretation Value
numericOp byteOpF intOpF realOpF err a b =
case (a, b) of
(VByte x, VByte y) -> return . VByte $ byteOpF x y
(VByte x, VInt y) -> return . VInt $ intOpF (fromIntegral x) y
(VByte x, VReal y) -> return . VReal $ realOpF (fromIntegral x) y
(VInt x, VByte y) -> return . VInt $ intOpF x (fromIntegral y)
(VInt x, VInt y) -> return . VInt $ intOpF x y
(VInt x, VReal y) -> return . VReal $ realOpF (fromIntegral x) y
(VReal x, VByte y) -> return . VReal $ realOpF x (fromIntegral y)
(VReal x, VInt y) -> return . VReal $ realOpF x (fromIntegral y)
(VReal x, VReal y) -> return . VReal $ realOpF x y
_ -> err
-- | Common Numeric-Operation handling, with casing for int/real promotion.
numeric :: (forall a. Num a => a -> a -> a)
-> K3 Expression -> K3 Expression -> Interpretation Value
numeric op a b = do
a' <- expression a
b' <- expression b
numericOp op op op err a' b'
where err = throwE $ RunTimeTypeError "Arithmetic Type Mis-Match"
-- | Similar to numeric above, except disallow a zero value for the second argument.
numericExceptZero :: (Word8 -> Word8 -> Word8)
-> (Int -> Int -> Int)
-> (Double -> Double -> Double)
-> K3 Expression -> K3 Expression -> Interpretation Value
numericExceptZero byteOpF intOpF realOpF a b = do
a' <- expression a
b' <- expression b
void $ case b' of
VByte 0 -> throwE $ RunTimeInterpretationError "Zero denominator"
VInt 0 -> throwE $ RunTimeInterpretationError "Zero denominator"
VReal 0 -> throwE $ RunTimeInterpretationError "Zero denominator"
_ -> return ()
numericOp byteOpF intOpF realOpF err a' b'
where err = throwE $ RunTimeTypeError "Arithmetic Type Mis-Match"
-- | Common boolean operation handling.
logic :: (Bool -> Bool -> Bool) -> K3 Expression -> K3 Expression -> Interpretation Value
logic op a b = do
a' <- expression a
b' <- expression b
case (a', b') of
(VBool x, VBool y) -> return $ VBool $ op x y
_ -> throwE $ RunTimeTypeError "Invalid Boolean Operation"
-- | Common comparison operation handling.
comparison :: (Value -> Value -> Interpretation Value)
-> K3 Expression -> K3 Expression -> Interpretation Value
comparison op a b = do
a' <- expression a
b' <- expression b
op a' b'
-- | Common string operation handling.
textual :: (String -> String -> String)
-> K3 Expression -> K3 Expression -> Interpretation Value
textual op a b = do
a' <- expression a
b' <- expression b
case (a', b') of
(VString s1, VString s2) -> return . VString $ op s1 s2
_ -> throwE $ RunTimeTypeError "Invalid String Operation"
-- | Interpretation of unary operators.
unary :: Operator -> K3 Expression -> Interpretation Value
-- | Interpretation of unary negation of numbers.
unary ONeg a = expression a >>= \case
VInt i -> return $ VInt (negate i)
VReal r -> return $ VReal (negate r)
_ -> throwE $ RunTimeTypeError "Invalid Negation"
-- | Interpretation of unary negation of booleans.
unary ONot a = expression a >>= \case
VBool b -> return $ VBool (not b)
_ -> throwE $ RunTimeTypeError "Invalid Complement"
unary _ _ = throwE $ RunTimeTypeError "Invalid Unary Operator"
-- | Interpretation of binary operators.
binary :: Operator -> K3 Expression -> K3 Expression -> Interpretation Value
-- | Standard numeric operators.
binary OAdd = numeric (+)
binary OSub = numeric (-)
binary OMul = numeric (*)
-- | Division and modulo handled similarly, but accounting zero-division errors.
binary ODiv = numericExceptZero div div (/)
binary OMod = numericExceptZero mod mod mod'
-- | Logical operators
binary OAnd = logic (&&)
binary OOr = logic (||)
-- | Comparison operators
binary OEqu = comparison valueEq
binary ONeq = comparison valueNeq
binary OLth = comparison valueLt
binary OLeq = comparison valueLte
binary OGth = comparison valueGt
binary OGeq = comparison valueGte
-- | String operators
binary OConcat = textual (++)
-- | Function Application
binary OApp = \f x -> do
f' <- expression f
x' <- expression x >>= freshenValue
case f' of
VFunction (b, cl, _) -> withClosure cl $ b x'
_ -> throwE $ RunTimeTypeError $ "Invalid Function Application on:\n" ++ pretty f
where withClosure cl doApp = mergeE cl >> doApp >>= \r -> pruneE cl >> freshenValue r
-- | Message Passing
binary OSnd = \target x -> do
target' <- expression target
x' <- expression x
case target' of
VTuple [(VTrigger (n, _, _), _), (VAddress addr, _)] -> sendE addr n x' >> return vunit
_ -> throwE $ RunTimeTypeError "Invalid Trigger Target"
-- | Sequential expressions
binary OSeq = \e1 e2 -> expression e1 >> expression e2
binary _ = \_ _ -> throwE $ RunTimeInterpretationError "Invalid binary operation"
-- | Interpretation of Expressions
expression :: K3 Expression -> Interpretation Value
expression e_ = traceExpression $ do
result <- expr e_
void $ buildProxyPath e_
return result
where
traceExpression :: Interpretation a -> Interpretation a
traceExpression m = do
let suOpt = spanUid (annotations e_)
pushed <- maybe (return False) (\su -> pushTraceUID su >> return True) suOpt
result <- m
void $ if pushed then popTraceUID else return ()
case suOpt of
Nothing -> return ()
Just (_, uid) -> do
(watched, wvars) <- (,) <$> isWatchedExpression uid <*> getWatchedVariables uid
void $ if watched then logIStateMI else return ()
void $ mapM_ (prettyWatchedVar $ maximum $ map length wvars) wvars
return result
prettyWatchedVar :: Int -> Identifier -> Interpretation ()
prettyWatchedVar w i =
lookupE i >>= liftEngine . prettyIEnvEntry defaultPrintConfig
>>= liftIO . putStrLn . ((i ++ replicate (max (w - length i) 0) ' ' ++ " => ") ++)
-- TODO: dataspace bind aliases
buildProxyPath :: K3 Expression -> Interpretation ()
buildProxyPath e =
case e @~ isBindAliasAnnotation of
Just (EAnalysis (BindAlias i)) -> appendAlias (Named i)
Just (EAnalysis (BindFreshAlias i)) -> appendAlias (Temporary i)
Just (EAnalysis (BindAliasExtension i)) -> appendAliasExtension i
Nothing -> return ()
Just _ -> throwE $ RunTimeInterpretationError "Invalid bind alias annotation matching"
isBindAliasAnnotation :: Annotation Expression -> Bool
isBindAliasAnnotation (EAnalysis (BindAlias _)) = True
isBindAliasAnnotation (EAnalysis (BindFreshAlias _)) = True
isBindAliasAnnotation (EAnalysis (BindAliasExtension _)) = True
isBindAliasAnnotation _ = False
refreshEntry :: Identifier -> IEnvEntry Value -> Value -> Interpretation ()
refreshEntry n (IVal _) v = replaceE n (IVal v)
refreshEntry _ (MVal mv) v = liftIO (modifyMVar_ mv $ const $ return v)
lookupVQ :: Identifier -> Interpretation (Value, VQualifier)
lookupVQ i = lookupE i >>= valueQOfEntry
-- | Performs a write-back for a bind expression.
-- This retrieves the current binding values from the environment
-- and reconstructs a path value to replace the bind target.
refreshBindings :: Binder -> ProxyPath -> Value -> Interpretation ()
refreshBindings (BIndirection i) proxyPath bindV =
lookupVQ i >>= \case
(iV, MemMut) ->
replaceProxyPath proxyPath bindV iV (\oldV newPathV ->
case oldV of
VIndirection (mv, MemMut, _) ->
liftIO (modifyMVar_ mv $ const $ return newPathV) >> return oldV
_ -> throwE $ RunTimeTypeError "Invalid bind indirection target")
(_, _) -> return () -- Skip writeback to an immutable value.
refreshBindings (BTuple ts) proxyPath bindV =
mapM lookupVQ ts >>= \vqs ->
if any (/= MemImmut) $ map snd vqs
then replaceProxyPath proxyPath bindV (VTuple vqs) (\_ newPathV -> return newPathV)
else return () -- Skip writeback if all fields are immutable.
refreshBindings (BRecord ids) proxyPath bindV =
mapM lookupVQ (map snd ids) >>= \vqs ->
if any (/= MemImmut) $ map snd vqs
then replaceProxyPath proxyPath bindV
(VRecord $ membersFromList $ zip (map fst ids) vqs)
(\oldV newPathV -> mergeRecords oldV newPathV)
else return () -- Skip writebsack if all fields are immutable.
replaceProxyPath :: ProxyPath -> Value -> Value
-> (Value -> Value -> Interpretation Value)
-> Interpretation ()
replaceProxyPath proxyPath origV newComponentV refreshF =
case proxyPath of
(Named n):t -> do
entry <- lookupE n
oldV <- valueOfEntry entry
pathV <- reconstructPathValue t newComponentV oldV
refreshF oldV pathV >>= refreshEntry n entry
(Temporary _):t -> reconstructPathValue t newComponentV origV >>= refreshF origV >> return ()
_ -> throwE $ RunTimeInterpretationError "Invalid path in bind writeback"
reconstructPathValue :: ProxyPath -> Value -> Value -> Interpretation Value
reconstructPathValue [] newR@(VRecord _) oldR@(VRecord _) = mergeRecords oldR newR
reconstructPathValue [] v _ = return v
reconstructPathValue (Dereference:t) v (VIndirection (iv, q, tg)) =
liftIO (readMVar iv)
>>= reconstructPathValue t v
>>= \nv -> liftIO (modifyMVar_ iv $ const $ return nv) >> return (VIndirection (iv, q, tg))
reconstructPathValue (MatchOption:t) v (VOption (Just ov, q)) =
reconstructPathValue t v ov >>= \nv -> return $ VOption (Just nv, q)
reconstructPathValue ((TupleField i):t) v (VTuple vs) =
let (x,y) = splitAt i vs in
reconstructPathValue t v (fst $ last x) >>= \nv -> return $ VTuple ((init x) ++ [(nv, snd $ last x)] ++ y)
reconstructPathValue ((RecordField n):t) v (VRecord ivs) = do
fields <- flip mapMembers ivs (\fn (fv, fq) ->
if fn == n then reconstructPathValue t v fv >>= return . (, fq)
else return (fv, fq))
return $ VRecord fields
reconstructPathValue _ _ _ =
throwE $ RunTimeInterpretationError "Invalid path in bind writeback reconstruction"
-- | Merge two records, restricting to the domain of the first record, and
-- preferring values from the second argument for duplicates.
mergeRecords :: Value -> Value -> Interpretation Value
mergeRecords (VRecord r1) (VRecord r2) =
mapBindings (\n v -> maybe (return v) return $ lookupBinding n r2) r1 >>= return . VRecord
mergeRecords _ _ =
throwE $ RunTimeTypeError "Invalid bind record target"
expr :: K3 Expression -> Interpretation Value
-- | Interpretation of constant expressions.
expr (details -> (EConstant c, _, as)) = constant c as
-- | Interpretation of variable lookups.
expr (details -> (EVariable i, _, _)) =
lookupE i >>= \e -> valueOfEntry e >>= syncCollectionE i e
-- | Interpretation of option type construction expressions.
expr (tag &&& children -> (ESome, [x])) =
expression x >>= freshenValue >>= return . VOption . (, vQualOfExpr x) . Just
expr (details -> (ESome, _, _)) =
throwE $ RunTimeTypeError "Invalid Construction of Option"
-- | Interpretation of indirection type construction expressions.
expr (tag &&& children -> (EIndirect, [x])) = do
new_val <- expression x >>= freshenValue
(\a b -> VIndirection (a, vQualOfExpr x, b)) <$> liftIO (newMVar new_val) <*> memEntTag new_val
expr (details -> (EIndirect, _, _)) =
throwE $ RunTimeTypeError "Invalid Construction of Indirection"
-- | Interpretation of tuple construction expressions.
expr (tag &&& children -> (ETuple, cs)) =
mapM (\e -> expression e >>= freshenValue >>= return . (, vQualOfExpr e)) cs >>= return . VTuple
-- | Interpretation of record construction expressions.
expr (tag &&& children -> (ERecord is, cs)) =
mapM (\e -> expression e >>= freshenValue >>= return . (, vQualOfExpr e)) cs >>= return . VRecord . membersFromList . zip is
-- | Interpretation of function construction.
expr (details -> (ELambda i, [b], _)) =
mkFunction $ \v -> insertE i (IVal v) >> expression b >>= removeE i
where
mkFunction f = (\cl tg -> VFunction (f, cl, tg)) <$> closure <*> memEntTag f
-- TODO: currently, this definition of a closure captures
-- annotation member variables during annotation member initialization.
-- This invalidates the use of annotation member function contextualization
-- since the context is overridden by the closure whenever applying the
-- member function.
closure :: Interpretation (Closure Value)
closure = do
globals <- get >>= return . getGlobals
vars <- return $ filter (\n -> n /= i && n `notElem` globals) $ freeVariables b
vals <- mapM lookupE vars
envFromList $ zip vars vals
-- | Interpretation of unary/binary operators.
expr (details -> (EOperate otag, cs, _))
| otag `elem` [ONeg, ONot], [a] <- cs = unary otag a
| otherwise, [a, b] <- cs = binary otag a b
| otherwise = undefined
-- | Interpretation of Record Projection.
expr (details -> (EProject i, [r], _)) = expression r >>= syncCollection >>= \case
VRecord vm -> maybe (unknownField i) (return . fst) $ lookupMember i vm
VCollection (_, c) -> do
if null (realizationId c) then unannotatedCollection
else maybe (unknownCollectionMember i c) (return . fst)
$ lookupMember i $ collectionNS $ namespace c
v -> throwE . RunTimeTypeError $ "Invalid projection on value: " ++ show v
where unknownField i' = throwE . RunTimeTypeError $ "Unknown record field " ++ i'
unannotatedCollection = throwE . RunTimeTypeError $ "Invalid projection on an unannotated collection"
unknownCollectionMember i' c = throwE . RunTimeTypeError $ "Unknown collection member " ++ i' ++ " in collection " ++ show c
expr (details -> (EProject _, _, _)) = throwE $ RunTimeTypeError "Invalid Record Projection"
-- | Interpretation of Let-In Constructions.
expr (tag &&& children -> (ELetIn i, [e, b])) = do
entry <- expression e >>= freshenValue >>= entryOfValueE (e @~ isEQualified)
insertE i entry >> expression b >>= removeE i
expr (details -> (ELetIn _, _, _)) = throwE $ RunTimeTypeError "Invalid LetIn Construction"
-- | Interpretation of Assignment.
expr (details -> (EAssign i, [e], _)) = do
entry <- lookupE i
case entry of
MVal mv -> expression e >>= freshenValue >>= \v -> liftIO (modifyMVar_ mv $ const $ return v) >> return v
IVal _ -> throwE $ RunTimeInterpretationError
$ "Invalid assignment to an immutable variable: " ++ i
expr (details -> (EAssign _, _, _)) = throwE $ RunTimeTypeError "Invalid Assignment"
-- | Interpretation of If-Then-Else constructs.
expr (details -> (EIfThenElse, [p, t, e], _)) = expression p >>= \case
VBool True -> expression t
VBool False -> expression e
_ -> throwE $ RunTimeTypeError "Invalid Conditional Predicate"
expr (details -> (EAddress, [h, p], _)) = do
hv <- expression h
pv <- expression p
case (hv, pv) of
(VString host, VInt port) -> return $ VAddress $ Address (host, port)
_ -> throwE $ RunTimeTypeError "Invalid address"
expr (details -> (ESelf, _, _)) = lookupE annotationSelfId >>= valueOfEntry
-- | Interpretation of Case-Matches.
-- Case expressions behave like bind-as, i.e., w/ isolated bindings and writeback
expr (details -> (ECaseOf i, [e, s, n], _)) = do
void $ pushProxyFrame
targetV <- expression e
case targetV of
VOption (Just v, q) -> do
pp <- getProxyPath >>= \case
Just ((Named pn):t) -> return $ (Named pn):t
Just ((Temporary pn):t) -> return $ (Temporary pn):t
_ -> throwE $ RunTimeTypeError "Invalid proxy path in case-of expression"
void $ popProxyFrame
entry <- entryOfValueQ v q
insertE i entry
sV <- expression s
void $ lookupVQ i >>= \case
(iV, MemMut) -> replaceProxyPath pp targetV (VOption (Just iV, MemMut)) (\_ newPathV -> return newPathV)
_ -> return () -- Skip writeback for immutable values.
removeE i sV
VOption (Nothing, _) -> popProxyFrame >> expression n
_ -> throwE $ RunTimeTypeError "Invalid Argument to Case-Match"
expr (details -> (ECaseOf _, _, _)) = throwE $ RunTimeTypeError "Invalid Case-Match"
-- | Interpretation of Binding.
-- TODO: For now, all bindings are added in mutable fashion. This should be extracted from
-- the type inferred for the bind target expression.
expr (details -> (EBindAs b, [e, f], _)) = do
void $ pushProxyFrame
pc <- getPrintConfig <$> get
bv <- expression e
bp <- getProxyPath >>= \case
Just ((Named n):t) -> return $ (Named n):t
Just ((Temporary n):t) -> return $ (Temporary n):t
_ -> throwE $ RunTimeTypeError "Invalid bind path in bind-as expression"
void $ popProxyFrame
case (b, bv) of
(BIndirection i, VIndirection (r,q,_)) -> do
entry <- liftIO (readMVar r) >>= flip entryOfValueQ q
void $ insertE i entry
fV <- expression f
void $ refreshBindings b bp bv
removeE i fV
(BTuple ts, VTuple vs) -> do
let tupMems = membersFromList $ zip ts vs
bindAndRefresh bp bv tupMems
(BRecord ids, VRecord ivs) -> do
let (idls, ivls) = (map fst ids, boundNames ivs)
-- Testing the intersection with the bindings ensures every bound name
-- has a value, while also allowing us to bind a subset of the values.
if idls `intersect` ivls == idls
then do
let recordMems = membersFromList $ joinByKeys (,) idls ids ivs
bindAndRefresh bp bv recordMems
else throwE $ RunTimeTypeError "Invalid Bind-Pattern"
(binder, binderV) ->
throwE $ RunTimeTypeError $
"Bind Mis-Match: value is " ++ showPC (pc {convertToTuples=False}) binderV
++ " but bind is " ++ show binder
where
bindAndRefresh bp bv mems = do
bindings <- bindMembers mems
fV <- expression f
void $ refreshBindings b bp bv
unbindMembers bindings >> return fV
joinByKeys joinF keys l r =
catMaybes $ map (\k -> lookup k l >>= (\matchL -> lookupMember k r >>= return . joinF matchL)) keys
expr (details -> (EBindAs _,_,_)) = throwE $ RunTimeTypeError "Invalid Bind Construction"
expr _ = throwE $ RunTimeInterpretationError "Invalid Expression"
{- Literal interpretation -}
literal :: K3 Literal -> Interpretation Value
literal (tag -> LBool b) = return $ VBool b
literal (tag -> LByte b) = return $ VByte b
literal (tag -> LInt i) = return $ VInt i
literal (tag -> LReal r) = return $ VReal r
literal (tag -> LString s) = return $ VString s
literal l@(tag -> LNone _) = return $ VOption (Nothing, vQualOfLit l)
literal (tag &&& children -> (LSome, [x])) = literal x >>= return . VOption . (, vQualOfLit x) . Just
literal (details -> (LSome, _, _)) = throwE $ RunTimeTypeError "Invalid option literal"
literal (tag &&& children -> (LIndirect, [x])) = literal x >>= (\y -> (\i tg -> (i, vQualOfLit x, tg)) <$> liftIO (newMVar y) <*> memEntTag y) >>= return . VIndirection
literal (details -> (LIndirect, _, _)) = throwE $ RunTimeTypeError "Invalid indirection literal"
literal (tag &&& children -> (LTuple, ch)) = mapM (\l -> literal l >>= return . (, vQualOfLit l)) ch >>= return . VTuple
literal (details -> (LTuple, _, _)) = throwE $ RunTimeTypeError "Invalid tuple literal"
literal (tag &&& children -> (LRecord ids, ch)) = mapM (\l -> literal l >>= return . (, vQualOfLit l)) ch >>= return . VRecord . membersFromList . zip ids
literal (details -> (LRecord _, _, _)) = throwE $ RunTimeTypeError "Invalid record literal"
literal (details -> (LEmpty _, [], anns)) =
getComposedAnnotationL anns >>= maybe (emptyCollection annIds) emptyAnnotatedCollection
where annIds = namedLAnnotations anns
literal (details -> (LEmpty _, _, _)) = throwE $ RunTimeTypeError "Invalid empty literal"
literal (details -> (LCollection _, elems, anns)) = do
cElems <- mapM literal elems
realizationOpt <- getComposedAnnotationL anns
case realizationOpt of
Nothing -> initialCollection (namedLAnnotations anns) cElems
Just comboId -> initialAnnotatedCollection comboId cElems
literal (details -> (LAddress, [h,p], _)) = mapM literal [h,p] >>= \case
[VString a, VInt b] -> return . VAddress $ Address (a,b)
_ -> throwE $ RunTimeTypeError "Invalid address literal"
literal (details -> (LAddress, _, _)) = throwE $ RunTimeTypeError "Invalid address literal"
literal _ = throwE $ RunTimeTypeError "Invalid literal"
{- Declaration interpretation -}
replaceTrigger :: (HasSpan a, HasUID a) => Identifier -> [a] -> Value -> Interpretation ()
replaceTrigger n _ (VFunction (f,_,tg)) = replaceE n (IVal $ VTrigger (n, Just f, tg))
replaceTrigger n _ _ = throwE $ RunTimeTypeError ("Invalid body for trigger " ++ n)
global :: Identifier -> K3 Type -> Maybe (K3 Expression) -> Interpretation ()
global n (details -> (TSink, _, anns)) (Just e) = expression e >>= replaceTrigger n anns
global _ (details -> (TSink, _, _)) Nothing = throwE $ RunTimeInterpretationError "Invalid sink trigger"
-- ^ Interpret and add sink triggers to the program environment.
-- | Sources have already been translated into K3 code
global _ (tag -> TSource) _ = return ()
-- | Functions have already been initialized as part of the program environment.
global _ (isTFunction -> True) _ = return ()
-- | Add collection declaration, generating the collection type given by the annotation
-- combination on demand.
-- n is the name of the variable
global n t@(details -> (TCollection, _, _)) eOpt = elemE n >>= \case
True -> void . getComposedAnnotationT $ annotations t
False -> (getComposedAnnotationT $ annotations t) >>= initializeCollection . maybe "" id
where
initializeCollection comboId = case eOpt of
Nothing | not (null comboId) -> emptyAnnotatedCollection comboId >>= entryOfValueT (t @~ isTQualified) >>= insertE n
Just e | not (null comboId) -> expression e >>= verifyInitialCollection comboId
-- TODO: error on these cases. All collections must have at least the builtin Collection annotation.
Nothing -> emptyCollection (namedTAnnotations $ annotations t) >>= entryOfValueT (t @~ isTQualified) >>= insertE n
Just e -> expression e >>= entryOfValueT (t @~ isTQualified) >>= insertE n
verifyInitialCollection comboId = \case
v@(VCollection (_, Collection _ _ cId)) ->
if comboId == cId then entryOfValueT (t @~ isTQualified) v >>= insertE n
else collInitError comboId cId
_ -> collValError
collInitError c c' = throwE . RunTimeTypeError $ "Invalid annotations on collection initializer for " ++ n ++ ": " ++ c ++ " and " ++ c'
collValError = throwE . RunTimeTypeError $ "Invalid collection value " ++ n
-- | Instantiate all other globals in the interpretation environment.
global n t eOpt = elemE n >>= \case
True -> return ()
False -> maybe (defaultValue t) expression eOpt >>= entryOfValueT (t @~ isTQualified) >>= insertE n
-- TODO: qualify names?
role :: Identifier -> [K3 Declaration] -> Interpretation ()
role _ subDecls = mapM_ declaration subDecls
declaration :: K3 Declaration -> Interpretation ()
declaration (tag &&& children -> (DGlobal n t eO, ch)) =
debugDecl n t $ global n t eO >> mapM_ declaration ch
declaration (details -> (DTrigger n t e, cs, anns)) =
debugDecl n t $ (expression e >>= replaceTrigger n anns) >> mapM_ declaration cs
declaration (tag &&& children -> (DRole r, ch)) = role r ch
declaration (tag -> DDataAnnotation n vdecls members) = annotation n vdecls members
declaration _ = undefined
{- Annotations -}
annotation :: Identifier -> [TypeVarDecl] -> [AnnMemDecl] -> Interpretation ()
annotation n _ memberDecls = tryLookupADef n >>= \case
Nothing -> addAnnotationDef
Just _ -> return ()
where
addAnnotationDef = do
(annMems, bindings) <- foldM initializeMembers
(emptyMembers, emptyBindings)
[liftedAttrFuns, liftedAttrs, attrFuns, attrs]
_ <- unbindMembers bindings
void $ modifyADefs $ (:) (n, annMems)
-- | Initialize members, while adding each member declaration to the environment to
-- support linear immediate initializer access.
initializeMembers mbAcc spec = foldM (memberWithBindings spec) mbAcc memberDecls
memberWithBindings (isLifted, matchF) mbAcc mem = do
ivOpt <- annotationMember n isLifted matchF mem
maybe (return mbAcc) (bindAndAppendMem mbAcc) ivOpt
bindAndAppendMem (memAcc, bindAcc) (memN,(v,q)) = do
entry <- case q of
MemImmut -> return $ IVal v
MemMut -> liftIO (newMVar v) >>= return . MVal
void $ insertE memN entry
return (insertMember memN (v,q) memAcc, insertBinding memN entry bindAcc)
(liftedAttrFuns, liftedAttrs) = ((True, isTFunction), (True, not . isTFunction))
(attrFuns, attrs) = ((False, isTFunction), (False, not . isTFunction))
annotationMember :: Identifier -> Bool -> (K3 Type -> Bool) -> AnnMemDecl
-> Interpretation (Maybe (Identifier, (Value, VQualifier)))
annotationMember annId matchLifted matchF annMem = case (matchLifted, annMem) of
(True, Lifted Provides n t (Just e) _) | matchF t -> initializeMember n t e
(False, Attribute Provides n t (Just e) _) | matchF t -> initializeMember n t e
(True, Lifted Provides n t Nothing _) | matchF t -> builtinLiftedAttribute annId n t >>= return . builtinQual t
(False, Attribute Provides n t Nothing _) | matchF t -> builtinAttribute annId n t >>= return . builtinQual t
_ -> return Nothing
where initializeMember n t e = expression e >>= \v -> return . Just $ (n, (v, memberQual t))
builtinQual t (Just (n,v)) = Just (n, (v, memberQual t))
builtinQual _ Nothing = Nothing
memberQual t = case t @~ isTQualified of
Just TMutable -> MemMut
_ -> MemImmut
|
DaMSL/K3
|
src/Language/K3/Interpreter/Evaluation.hs
|
apache-2.0
| 30,705 | 0 | 23 | 7,655 | 9,890 | 4,999 | 4,891 | 488 | 69 |
{-
Copyright 2010-2012 Cognimeta Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is
distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
or implied. See the License for the specific language governing permissions and limitations under the License.
-}
{-# LANGUAGE TupleSections, FlexibleInstances, MultiParamTypeClasses, Rank2Types, ScopedTypeVariables, TypeFamilies #-}
module Cgm.Control.Monad.State(
StateT(..),
State,
mState,
runState,
viewState,
partialState,
partialStateE,
eitherState,
maybeState,
toStandardState,
mapStateT,
pairStateT,
module Control.Monad.State.Class,
module Control.Monad.Trans.Class,
module Control.Monad.IO.Class
) where
import Control.Applicative
import Control.Monad
import Control.Arrow
import Data.Functor.Identity
import Data.Maybe
import Control.Monad.State.Class
import Control.Monad.Trans.Class
import Control.Monad.IO.Class
import Control.Concurrent.MVar
import qualified Control.Monad.State.Strict as Std
import Control.Lens hiding (focus)
import Control.Lens.Zoom
import Control.Lens.Internal.Zoom
import Control.Comonad.Trans.Store
import Data.Profunctor.Unsafe
-- | runStateT and runState do not have the usual types: for now we do not make it too easy to discard the precious 'Nothing'
newtype StateT s m a = StateT {runStateT :: s -> m (a, Maybe s)}
type State s = StateT s Identity
mState :: (s -> (a, Maybe s)) -> State s a
mState = StateT . fmap Identity
runState :: State s a -> s -> (a, Maybe s)
runState = fmap runIdentity . runStateT
instance Functor m => Functor (StateT s m) where
fmap f = StateT . fmap (fmap $ first f) . runStateT
instance (Functor m, Monad m) => Applicative (StateT s m) where
pure = return
(<*>) = ap
instance Monad m => Monad (StateT s m) where
return = lift . return
(StateT c) >>= fd = StateT $ \s ->
c s >>= \(a, ms) -> -- We are strict in the state. We do as in Control.Monad.Trans.State.Strict (not .Lazy)
let d = runStateT (fd a)
in maybe (d s) (\s' -> liftM (second $ Just . fromMaybe s') $ d s') ms
instance MonadTrans (StateT s) where
lift = StateT . const . liftM (, Nothing)
instance MonadIO m => MonadIO (StateT s m) where
liftIO = lift . liftIO
instance Monad m => MonadState s (StateT s m) where
get = StateT $ return . (, Nothing)
put = StateT . const . return . ((), ) . Just
type instance Zoomed (StateT s z) = StateTOut z
instance Monad m => Zoom (StateT s m) (StateT t m) s t where
zoom l (StateT tmat) = StateT $ stateTOut . l (\t -> StateTOut (tmat t)) where
newtype StateTOut m a s = StateTOut {stateTOut :: m (a, Maybe s)}
instance Monad m => Functor (StateTOut m a) where
fmap f (StateTOut msa) = StateTOut $ liftM (second $ fmap f) msa
-- | functions st and ts should form a bijection since a StateT t with no changes will become a StateT s with no changes, no matter what st and ts are
viewState :: Monad m => (s -> t, t -> s) -> StateT t m a -> StateT s m a
viewState (st, ts) (StateT tf) = StateT $ liftM (second $ fmap ts) . tf . st
-- Work on a part of the state, that may not exist for some inputs
partialState :: Monad m => m a -> (s -> Maybe t, t -> s) -> StateT t m a -> StateT s m a
--partialState d (smt, ts) (StateT tf) = get >>= \s -> maybe (lift d) ((>>= \(a, mt) -> maybe (return ()) (put . ts) mt >> return a) . lift . tf) $ smt s
partialState d (smt, ts) t = viewState (\s -> maybe (Left s) Right $ smt s, either id ts) $ eitherState (lift d) t -- note that we use a view 's -> Either s t'
-- Like partialState, but remembers which path was taken
partialStateE :: Monad m => m a -> (s -> Maybe t, t -> s) -> StateT t m b -> StateT s m (Either a b)
partialStateE d fs t = partialState (liftM Left d) fs (liftM Right t)
eitherState :: Monad m => StateT s m a -> StateT t m a -> StateT (Either s t) m a
eitherState (StateT sf) (StateT tf) = StateT $ either (liftM (second $ fmap Left) . sf) (liftM (second $ fmap Right) . tf)
maybeState :: Monad m => m a -> StateT s m a -> StateT (Maybe s) m a
maybeState n s = viewState (maybe (Left ()) Right, either (const Nothing) Just) $ eitherState (lift n) s
toStandardState :: Monad m => StateT s m a -> Std.StateT s m a
toStandardState (StateT f) = Std.StateT $ \s -> liftM (second $ fromMaybe s) $ f s
mapStateT :: (m (a, Maybe s) -> n (b, Maybe s)) -> StateT s m a -> StateT s n b
mapStateT f m = StateT $ f . runStateT m
pairStateT :: Functor m => StateT s (StateT t m) a -> StateT (s, t) m a
pairStateT (StateT sf) = StateT $ \(s, t) -> fmap (\((a, ms), mt) -> (a, combineMaybes s t ms mt)) $ runStateT (sf s) t where
combineMaybes s t ms = maybe (fmap (, t) ms) (Just . (fromMaybe s ms,))
|
Cognimeta/cognimeta-utils
|
src/Cgm/Control/Monad/State.hs
|
apache-2.0
| 5,094 | 0 | 19 | 1,130 | 1,742 | 920 | 822 | 79 | 1 |
{-# Language DataKinds #-}
{-# Language StandaloneDeriving #-}
module Stackist.Parser
(parseExpr, Expr(..), parseJoy)
where
import Text.ParserCombinators.Parsec hiding (spaces)
symbol :: Parser Char
symbol = oneOf "!$%&|*+-/:<=>?@^_~#"
spaces :: Parser ()
spaces = skipMany1 space
data Expr = Numeric Integer
| Literal String
| JString String
| Quote [Expr]
| Boolean Bool
deriving (Read, Eq, Show)
-- instance Show Literal where
-- show (Literal x) = show x
parseString :: Parser Expr
parseString = do
_ <- char '"'
x <- many (noneOf "\"")
_ <- char '"'
return $ JString x
parseAtom :: Parser Expr
parseAtom = do first <- letter <|> symbol
rest <- many (letter <|> digit <|> symbol)
let atom = [first] ++ rest
return $ case atom of
"#t" -> Boolean True
"#f" -> Boolean False
_ -> Literal atom
parseNumber :: Parser Expr
parseNumber = fmap (Numeric . read) $ many1 digit
parseList :: Parser Expr
parseList = fmap Quote $ sepBy parseExpr spaces
parseQuoted :: Parser Expr
parseQuoted = do
_ <- char '\''
x <- parseExpr
return $ Quote [Literal "quote", x]
parseExpr :: Parser Expr
parseExpr = parseAtom
<|> parseString
<|> parseNumber
<|> parseQuoted
<|> do _ <- char '['
x <- (try parseList)
_ <- char ']'
return x
-- | parseJoy "[1 2 +]"
--
-- >> parseJoy "[1 2 +]"
-- [Quote [Numeric 1, Numeric 2, Literal "+"]]
parseJoy :: String -> Either ParseError Expr
parseJoy input = parse parseExpr "(unknown)" input
|
stevej/stackist
|
src/Stackist/Parser.hs
|
apache-2.0
| 1,700 | 0 | 11 | 534 | 481 | 242 | 239 | 49 | 3 |
{-|
Copyright : (C) 2012-2016, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <[email protected]>
Module that connects all the parts of the CLaSH compiler library
-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
module CLaSH.Driver where
import qualified Control.Concurrent.Supply as Supply
import Control.DeepSeq
import Control.Monad (when)
import Control.Monad.State (evalState, get)
import qualified Data.HashMap.Lazy as HML
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HashSet
import Data.IntMap (IntMap)
import Data.Maybe (fromMaybe)
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as Text
import qualified Data.Time.Clock as Clock
import qualified System.Directory as Directory
import System.FilePath ((</>), (<.>))
import qualified System.FilePath as FilePath
import qualified System.IO as IO
import Text.PrettyPrint.Leijen.Text (Doc, hPutDoc)
import Unbound.Generics.LocallyNameless (name2String)
import CLaSH.Annotations.TopEntity (TopEntity (..))
import CLaSH.Backend
import CLaSH.Core.Term (Term, TmName)
import CLaSH.Core.Type (Type)
import CLaSH.Core.TyCon (TyCon, TyConName)
import CLaSH.Driver.TestbenchGen
import CLaSH.Driver.TopWrapper
import CLaSH.Driver.Types
import CLaSH.Netlist (genComponentName, genNetlist)
import CLaSH.Netlist.BlackBox.Parser (runParse)
import CLaSH.Netlist.BlackBox.Types (BlackBoxTemplate)
import CLaSH.Netlist.Types (Component (..), HWType)
import CLaSH.Normalize (checkNonRecursive, cleanupGraph,
normalize, runNormalization)
import CLaSH.Normalize.Util (callGraph, mkRecursiveComponents)
import CLaSH.Primitives.Types
import CLaSH.Util (first)
-- | Create a set of target HDL files for a set of functions
generateHDL :: forall backend . Backend backend
=> BindingMap -- ^ Set of functions
-> Maybe backend
-> PrimMap (Text.Text) -- ^ Primitive / BlackBox Definitions
-> HashMap TyConName TyCon -- ^ TyCon cache
-> IntMap TyConName -- ^ Tuple TyCon cache
-> (HashMap TyConName TyCon -> Type -> Maybe (Either String HWType)) -- ^ Hardcoded 'Type' -> 'HWType' translator
-> (HashMap TyConName TyCon -> Bool -> Term -> Term) -- ^ Hardcoded evaluator (delta-reduction)
-> (TmName,Maybe TopEntity) -- ^ topEntity bndr + (maybe) TopEntity annotation
-> Maybe TmName -- ^ testInput bndr
-> Maybe TmName -- ^ expectedOutput bndr
-> CLaSHOpts -- ^ Debug information level for the normalization process
-> (Clock.UTCTime,Clock.UTCTime)
-> IO ()
generateHDL bindingsMap hdlState primMap tcm tupTcm typeTrans eval (topEntity,annM) testInpM expOutM opts (startTime,prepTime) = do
let primMap' = (HM.map parsePrimitive :: PrimMap Text.Text -> PrimMap BlackBoxTemplate) primMap
(supplyN,supplyTB) <- Supply.splitSupply
. snd
. Supply.freshId
<$> Supply.newSupply
let doNorm = do norm <- normalize [topEntity]
let normChecked = checkNonRecursive topEntity norm
cleanupGraph topEntity normChecked
cg = callGraph [] bindingsMap topEntity
rcs = concat $ mkRecursiveComponents cg
rcsMap = HML.fromList
$ map (\(t,_) -> (t,t `elem` rcs)) cg
transformedBindings = runNormalization opts supplyN bindingsMap typeTrans tcm tupTcm eval primMap' rcsMap doNorm
normTime <- transformedBindings `deepseq` Clock.getCurrentTime
let prepNormDiff = Clock.diffUTCTime normTime prepTime
putStrLn $ "Normalisation took " ++ show prepNormDiff
let modName = takeWhile (/= '.') (name2String topEntity)
iw = opt_intWidth opts
hdlsyn = opt_hdlSyn opts
hdlState' = setModName modName
$ fromMaybe (initBackend iw hdlsyn :: backend) hdlState
mkId = evalState mkBasicId hdlState'
topNm = maybe (mkId (Text.pack $ modName ++ "_topEntity"))
(Text.pack . t_name)
annM
(netlist,dfiles,seen) <- genNetlist transformedBindings primMap' tcm
typeTrans Nothing modName [] iw mkId [topNm] topEntity
netlistTime <- netlist `deepseq` Clock.getCurrentTime
let normNetDiff = Clock.diffUTCTime netlistTime normTime
putStrLn $ "Netlist generation took " ++ show normNetDiff
let topComponent = head
$ filter (\(Component cName _ _ _ _) ->
Text.isSuffixOf (genComponentName [topNm] mkId modName topEntity)
cName)
netlist
(testBench,dfiles') <- genTestBench opts supplyTB primMap'
typeTrans tcm tupTcm eval mkId seen bindingsMap
testInpM
expOutM
modName
dfiles
topComponent
testBenchTime <- testBench `seq` Clock.getCurrentTime
let netTBDiff = Clock.diffUTCTime testBenchTime netlistTime
putStrLn $ "Testbench generation took " ++ show netTBDiff
let topWrapper = mkTopWrapper primMap' mkId annM modName iw topComponent
hdlDocs = createHDL hdlState' modName (topWrapper : netlist ++ testBench)
dir = fromMaybe "." (opt_hdlDir opts) </>
CLaSH.Backend.name hdlState' </>
takeWhile (/= '.') (name2String topEntity)
prepareDir (opt_cleanhdl opts) (extension hdlState') dir
mapM_ (writeHDL hdlState' dir) hdlDocs
copyDataFiles dir dfiles'
endTime <- hdlDocs `seq` Clock.getCurrentTime
let startEndDiff = Clock.diffUTCTime endTime startTime
putStrLn $ "Total compilation took " ++ show startEndDiff
parsePrimitive :: Primitive Text -> Primitive BlackBoxTemplate
parsePrimitive (BlackBox pNm templT) =
let (templ,err) = either (first Left . runParse) (first Right . runParse) templT
in case err of
[] -> BlackBox pNm templ
_ -> error $ "Errors in template for: " ++ show pNm ++ ":\n" ++ show err
parsePrimitive (Primitive pNm typ) = Primitive pNm typ
-- | Pretty print Components to HDL Documents
createHDL :: Backend backend
=> backend -- ^ Backend
-> String
-> [Component] -- ^ List of components
-> [(String,Doc)]
createHDL backend modName components = flip evalState backend $ do
-- (hdlNms,hdlDocs) <- unzip <$> mapM genHDL components
-- let hdlNmDocs = zip hdlNms hdlDocs
hdlNmDocs <- mapM (genHDL modName) components
hwtys <- HashSet.toList <$> extractTypes <$> get
typesPkg <- mkTyPackage modName hwtys
return (typesPkg ++ hdlNmDocs)
-- | Prepares the directory for writing HDL files. This means creating the
-- dir if it does not exist and removing all existing .hdl files from it.
prepareDir :: Bool -- ^ Remove existing HDL files
-> String -- ^ File extension of the HDL files.
-> String
-> IO ()
prepareDir cleanhdl ext dir = do
-- Create the dir if needed
Directory.createDirectoryIfMissing True dir
-- Clean the directory when needed
when cleanhdl $ do
-- Find all HDL files in the directory
files <- Directory.getDirectoryContents dir
let to_remove = filter ((==ext) . FilePath.takeExtension) files
-- Prepend the dirname to the filenames
let abs_to_remove = map (FilePath.combine dir) to_remove
-- Remove the files
mapM_ Directory.removeFile abs_to_remove
-- | Writes a HDL file to the given directory
writeHDL :: Backend backend => backend -> FilePath -> (String, Doc) -> IO ()
writeHDL backend dir (cname, hdl) = do
handle <- IO.openFile (dir </> cname <.> CLaSH.Backend.extension backend) IO.WriteMode
hPutDoc handle hdl
IO.hPutStr handle "\n"
IO.hClose handle
copyDataFiles :: FilePath -> [(String,FilePath)] -> IO ()
copyDataFiles dir = mapM_ copyFile'
where
copyFile' (nm,old) = Directory.copyFile old (dir FilePath.</> nm)
|
ggreif/clash-compiler
|
clash-lib/src/CLaSH/Driver.hs
|
bsd-2-clause
| 8,862 | 0 | 20 | 2,729 | 1,964 | 1,045 | 919 | 147 | 2 |
module Day2(paperAmount, bowAmount) where
import Data.List (sort)
import Data.Maybe (fromJust)
import Data.Text (pack, splitOn, unpack)
paperAmount :: String -> Integer
paperAmount xs = sum $ map getPaper (lines xs)
getPaper :: String -> Integer
getPaper = (+) . minimum . fromJust . sides . components <*> fromJust . surfaceArea . components
components :: String -> [Integer]
components xs = map (read . unpack) (splitOn (pack "x") (pack xs))
surfaceArea :: [Integer] -> Maybe Integer
surfaceArea (x:y:z:_) = Just $ 2 * (x*y + x*z + y*z)
surfaceArea _ = Nothing
sides :: [Integer] -> Maybe [Integer]
sides (x:y:z:_) = Just [x*y, x*z, y*z]
sides _ = Nothing
bowAmount :: String -> Integer
bowAmount xs = sum $ map getRibbon (lines xs)
getRibbon :: String -> Integer
getRibbon = (+) . fromJust . toWrap . components <*> fromJust . toBow . components
toWrap :: [Integer] -> Maybe Integer
toWrap xs@(a:b:c:_) = Just $ sum (map (*2) (take 2 (sort xs)))
toWrap _ = Nothing
toBow :: [Integer] -> Maybe Integer
toBow (x:y:z:_) = Just $ x * y * z
toBow _ = Nothing
|
samfoy/adventOfCode
|
src/Day2.hs
|
bsd-3-clause
| 1,099 | 0 | 12 | 225 | 538 | 287 | 251 | 26 | 1 |
module ImplicitRefs.Data where
import Control.Monad.Except
import Data.IORef
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import qualified Text.Megaparsec as Mega
type Environment = M.Map String DenotedValue
empty :: Environment
empty = M.empty
initEnvironment :: [(String, DenotedValue)] -> Environment
initEnvironment = M.fromList
extend :: String -> DenotedValue -> Environment -> Environment
extend = M.insert
extendRec :: Store -> String -> [String] -> Expression -> Environment
-> IOTry Environment
extendRec store name params body = extendRecMany store [(name, params, body)]
extendRecMany :: Store -> [(String, [String], Expression)] -> Environment
-> IOTry Environment
extendRecMany store lst env = do
refs <- allocMany (length lst)
let denoVals = fmap DenoRef refs
let names = fmap (\(n, _, _) -> n) lst
let newEnv = extendMany (zip names denoVals) env
extendRecMany' lst refs newEnv
where
extendRecMany' [] [] env = return env
extendRecMany' ((name, params, body):triples) (ref:refs) env = do
setRef store ref (ExprProc $ Procedure params body env)
extendRecMany' triples refs env
allocMany 0 = return []
allocMany x = do
ref <- newRef store (ExprBool False) -- dummy value false for allocating space
(ref:) <$> allocMany (x - 1)
apply :: Environment -> String -> Maybe DenotedValue
apply = flip M.lookup
extendMany :: [(String, DenotedValue)] -> Environment -> Environment
extendMany = flip (foldl func)
where
func env (var, val) = extend var val env
applyForce :: Environment -> String -> DenotedValue
applyForce env var = fromMaybe
(error $ "Var " `mappend` var `mappend` " is not in environment!")
(apply env var)
newtype Ref = Ref { addr::Integer } deriving (Show, Eq)
type Store = IORef [ExpressedValue]
type Try = Either LangError
type IOTry = ExceptT LangError IO
liftTry :: Try a -> IOTry a
liftTry (Left err) = throwError err
liftTry (Right val) = return val
initStore :: IO Store
initStore = newIORef []
newRef :: Store -> ExpressedValue -> IOTry Ref
newRef store val = do
vals <- liftIO $ readIORef store
liftIO $ atomicWriteIORef store (val:vals)
return . Ref . toInteger . length $ vals
deRef :: Store -> Ref -> IOTry ExpressedValue
deRef store (Ref r) = do
vals <- liftIO $ readIORef store
findVal r (reverse vals)
where
findVal :: Integer -> [ExpressedValue] -> IOTry ExpressedValue
findVal 0 (x:_) = return x
findVal 0 [] = throwError $ IndexOutOfBound "deref"
findVal i (_:xs) = findVal (i - 1) xs
setRef :: Store -> Ref -> ExpressedValue -> IOTry ()
setRef store ref val = do
vals <- liftIO $ readIORef store
newVals <- reverse <$> setRefVal (addr ref) (reverse vals) val
liftIO $ writeIORef store newVals
where
setRefVal :: Integer -> [ExpressedValue] -> ExpressedValue
-> IOTry [ExpressedValue]
setRefVal 0 (_:xs) val = return (val:xs)
setRefVal _ [] _ = throwError $ IndexOutOfBound "setref"
setRefVal i (x:xs) val = (x:) <$> setRefVal (i - 1) xs val
data Program = Prog Expression
deriving (Show, Eq)
data Expression =
ConstExpr ExpressedValue
| VarExpr String
| LetExpr [(String, Expression)] Expression
| BinOpExpr BinOp Expression Expression
| UnaryOpExpr UnaryOp Expression
| CondExpr [(Expression, Expression)]
| ProcExpr [String] Expression
| CallExpr Expression [Expression]
| LetRecExpr [(String, [String], Expression)] Expression
| BeginExpr [Expression]
| AssignExpr String Expression
| SetDynamicExpr String Expression Expression
| RefExpr String
| DeRefExpr String
| SetRefExpr String Expression
deriving (Show, Eq)
data BinOp =
Add | Sub | Mul | Div | Gt | Le | Eq
deriving (Show, Eq)
data UnaryOp = Minus | IsZero
deriving (Show, Eq)
data Procedure = Procedure [String] Expression Environment
instance Show Procedure where
show _ = "<procedure>"
data ExpressedValue = ExprNum Integer
| ExprBool Bool
| ExprProc Procedure
| ExprRef Ref
instance Show ExpressedValue where
show (ExprNum i) = show i
show (ExprBool b) = show b
show (ExprProc p) = show p
show (ExprRef ref) = show ref
instance Eq ExpressedValue where
(ExprNum i1) == (ExprNum i2) = i1 == i2
(ExprBool b1) == (ExprBool b2) = b1 == b2
(ExprRef ref1) == (ExprRef ref2) = ref1 == ref2
_ == _ = False
data DenotedValue = DenoRef Ref
instance Show DenotedValue where
show (DenoRef v) = show v
instance Eq DenotedValue where
DenoRef v1 == DenoRef v2 = v1 == v2
data LangError =
ParseError (Mega.ParseError (Mega.Token String) Mega.Dec)
| TypeMismatch String ExpressedValue
| IndexOutOfBound String
| ArgNumMismatch Integer [ExpressedValue]
| UnknownOperator String
| UnboundVar String
| RuntimeError String
| DefaultError String
deriving (Show, Eq)
|
li-zhirui/EoplLangs
|
src/ImplicitRefs/Data.hs
|
bsd-3-clause
| 4,969 | 0 | 13 | 1,124 | 1,779 | 932 | 847 | 129 | 3 |
{-# LANGUAGE BangPatterns #-}
module SECDH.Types where
import Data.Monoid
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import System.IO
import Language.Slambda.Types
data Instr = TermI { instrTerm :: Term }
| ApI Bool -- indicates that argument is at top of stack, function is just below it,
-- *and* that the function is strict in its argument
| UpdateI Addr -- indicates that the atom at the top of the
-- stack should be written to the given
-- address
| IOBindI -- perform whatever io action is on the top of the stack and apply the function underneath it to the result
deriving (Show, Read)
type Addr = Int
data IOAction = ReturnIO !Atom
| BindIO !IOAction !Atom
| WriteIO !Char
| ReadIO
deriving (Show, Read)
data Atom = ErrorA String
| ConstA !Const
| PrimA !Prim [Atom]
| IOActionA !IOAction
| ClosureA Env !Strictness Var Term
deriving (Show, Read)
data Value = AtomV !Atom
| PointerV !Addr
deriving (Show, Read)
data Object = AtomOb !Atom
| SuspOb Env Term
| IndirOb !Addr -- Indirection to another object
| UpdatingOb -- Object is being updated
deriving (Show, Read)
type Stack = [Value]
type Env = Map Var Addr
type Control = [Instr]
type Dump = [(Stack, Env, Control)]
type Heap = Seq Object
data SECDH = SECDH
{ secdhStack :: !Stack
, secdhEnv :: !Env
, secdhControl :: !Control
, secdhDump :: !Dump
, secdhHeap :: Seq Object
} deriving (Show, Read)
newtype Rule = Rule { ruleNum :: Int }
deriving (Eq, Ord, Show, Read)
class Monad m => MonadSECDHIO m where
secdhRead :: m (Maybe Char)
secdhWrite :: Char -> m ()
secdhWriteErr :: Char -> m ()
instance MonadSECDHIO IO where
secdhRead = do
eof <- isEOF
if not eof
then fmap Just getChar
else return Nothing
secdhWrite = putChar
secdhWriteErr = hPutChar stderr
data SECDHStats = SECDHStats
{ secdhStatsIters :: !Int
, secdhStatsMaxStack :: !Int
, secdhStatsMaxEnv :: !Int
, secdhStatsMaxControl :: !Int
, secdhStatsMaxDump :: !Int
, secdhStatsMaxHeap :: !Int
, secdhStatsMaxRetained :: !Int
, secdhStatsGCs :: !Int
, secdhStatsRuleExecs :: !(Map Rule Int)
}
instance Monoid SECDHStats where
mempty =
SECDHStats
{ secdhStatsIters = 0
, secdhStatsMaxStack = 0
, secdhStatsMaxEnv = 0
, secdhStatsMaxControl = 0
, secdhStatsMaxDump = 0
, secdhStatsMaxHeap = 0
, secdhStatsMaxRetained = 0
, secdhStatsGCs = 0
, secdhStatsRuleExecs = Map.empty
}
mappend s1 s2 =
SECDHStats
{ secdhStatsIters = secdhStatsIters s1 + secdhStatsIters s2
, secdhStatsMaxStack = max (secdhStatsMaxStack s1) (secdhStatsMaxStack s2)
, secdhStatsMaxEnv = max (secdhStatsMaxEnv s1) (secdhStatsMaxEnv s2)
, secdhStatsMaxControl = max (secdhStatsMaxControl s1) (secdhStatsMaxControl s2)
, secdhStatsMaxDump = max (secdhStatsMaxDump s1) (secdhStatsMaxDump s2)
, secdhStatsMaxHeap = max (secdhStatsMaxHeap s1) (secdhStatsMaxHeap s2)
, secdhStatsMaxRetained = max (secdhStatsMaxRetained s1) (secdhStatsMaxRetained s2)
, secdhStatsGCs = secdhStatsGCs s1 + secdhStatsGCs s2
, secdhStatsRuleExecs =
let f a (r, n) =
case Map.lookup r a of
Just n' -> let !n'' = n + n'
in Map.insert r n'' a
Nothing -> Map.insert r n a
in foldl f (secdhStatsRuleExecs s1) (Map.assocs (secdhStatsRuleExecs s2))
}
|
pgavin/secdh
|
lib/SECDH/Types.hs
|
bsd-3-clause
| 4,127 | 0 | 19 | 1,452 | 977 | 537 | 440 | 149 | 0 |
module Internal.Random (
module Data.Monoid
, ($>), (|+|)
) where
import Data.Monoid
infix 4 $>
($>) :: (Functor f) => f a -> (a -> b) -> f b
($>) = flip fmap
infixl 0 |>
(|>) = flip ($)
infixl 7 |+|
(|+|) :: Monoid a => a -> a -> a
(|+|) = mappend
|
pqwy/redex
|
src/Internal/Random.hs
|
bsd-3-clause
| 258 | 0 | 9 | 65 | 132 | 80 | 52 | 12 | 1 |
module Codex.Meetup.M1.NumericalAbstraction.Nat (
fact,
fib
) where
import Codex.Lib.Church.Nat
fact :: Nat -> Nat
fact O = (S O)
fact s@(S n') = (*) s $ fact n'
fib :: Nat -> Nat
fib O = O
fib (S O) = (S O)
fib s = fib ((-) s (succ O)) + fib ((-) s (succ (S O)))
|
adarqui/Codex
|
src/Codex/Meetup/M1/NumericalAbstraction/Nat.hs
|
bsd-3-clause
| 271 | 0 | 12 | 65 | 169 | 92 | 77 | 11 | 1 |
import Distribution.Simple
import System.IO
import System.Directory
import Data.List
import System.Environment
main = do
--your
(x:_) <- getArgs
if x == "configure" then do
dir <- getAppUserDataDirectory "GiveYouAHead"
isE <- doesDirectoryExist dir
if isE == True then putStrLn "" else createDirectory dir
isE <- doesDirectoryExist (dir++"/data")
if isE == True then putStrLn "" else createDirectory (dir++"/data")
isE <- doesDirectoryExist (dir++"/data/shell")
if isE == True then putStrLn "" else createDirectory (dir++"/data/shell")
hD <- openFile (dir++"/data/delList.dat") ReadMode
stSrc <- hGetLine hD
hClose hD
writeFile (dir ++ "/data/delList.dat") (show$dropRepeated$sort((read stSrc ::[String])++dL))
writeFile (dir ++ "/data/shell/cmd.cmap") (show shell)
defaultMain
--your end
else
defaultMain
where
shell = [
("*Del","del"),
("*DelForce"," /F"),
("*DelQuite","/Q"),
("*ShellFileBack",".bat"),
("*SysShellRun"," "),
("*MakefileBegin","@echo off\n"),
("*MakefileEnd","del .makefile.bat\n"),
("*ExecutableFE","exe")
]
dL = ["*.exe"]
dropRepeated :: (Eq a)=> [a] -> [a]
dropRepeated [] = []
dropRepeated (x:[]) = [x]
dropRepeated (x:y:xs)
| x == y = dropRepeated (x:xs)
| otherwise = x:dropRepeated (y:xs)
|
Qinka/cmd
|
Setup.hs
|
bsd-3-clause
| 1,500 | 0 | 16 | 432 | 503 | 264 | 239 | 38 | 5 |
module Config
(
ConfigData(..),
ConfigPicker(..),
pickerData,
getData,
getDataFromFile
) where
import System.IO.Extra
data ConfigPicker = Picker String Integer
data ConfigData = Data Integer String
pickerData :: [ConfigPicker]
pickerData = [
Picker "hackage-url" 1,
Picker "XHSK-Home" 2
]
getLineFromPicker :: [ConfigPicker] -> String -> Maybe Integer
getLineFromPicker [] _ = Nothing
getLineFromPicker (Picker str li:xs) findedstr
| str == findedstr = Just li
| otherwise = getLineFromPicker xs findedstr
getValFromData :: [ConfigData] -> Integer -> Maybe String
getValFromData _ (-1) =Nothing
getValFromData [] _ = Nothing
getValFromData (Data li str:xs) num
| li == num = Just str
| otherwise = getValFromData xs num
getData :: [ConfigData] -> [ConfigPicker] -> String -> Maybe String
getData cd cp = getValFromData cd.item.getLineFromPicker cp
where
item Nothing = -1
item (Just x) = x
getDataFromFile :: FilePath -> IO [ConfigData] --readFileUTF8
getDataFromFile path = do
text <- readFileUTF8 path --"./.xhsk.home.config"
return $ getDataFromFileStep (lines text) 1
getDataFromFileStep :: [String] -> Integer -> [ConfigData]
getDataFromFileStep [] _ = []
getDataFromFileStep (x:xs) i
| note x = Data i x:getDataFromFileStep xs (1+i)
| otherwise = getDataFromFileStep xs $ 1+i
where
note (xx:yy:_)
| xx==yy && yy=='-' =False
| otherwise = True
note _ = True
|
Xidian-Haskell-Server-Keeper/XHSK-Home
|
src/Config.hs
|
bsd-3-clause
| 1,683 | 0 | 12 | 519 | 541 | 274 | 267 | 42 | 2 |
---------
-- NIM --
---------
module Nim (Nim, nim) where
import Game
import Graphics.UI.WX hiding (prev)
-- import Graphics.UI.WXCore
import Tools
data Nim = Nim Int deriving (Show, Eq)
nim :: Nim
nim = undefined
instance Game Nim where
name _ = "nim"
standard _ = Properties { players = 2, boardsize = 21, human = [True, False, False] }
possible _ = PropertyRange { playersrange = [2, 3], boardsizerange = [1 .. 100] }
new pr = Nim $ boardsize pr
moves pr _ (Nim n) = map (move pr) $ filter (<= n) [1 .. 3]
showmove _ _ _ i = numberword (i + 1)
value pr p (Nim n)
| n == 0 = (prev p |> 1) $ replicate (players pr) (negate 1)
| otherwise = replicate (players pr) 0
where
prev :: Player -> Player
prev p' = (p' - 1) `mod` players pr
board p _pr vart _ move' = do
st <- staticText p [ text := "There are currently quite a number of rods.\n" ]
b1 <- button p []
b2 <- button p []
b3 <- button p []
let
onpaint _dc _r = do
t <- varGet vart
let Nim n = state t
set st [ text := "There are currently " ++ numberword n ++ " rods.\n"
++ "How many will you take away?" ]
set b1 [ text := "one rod" , on command := move' 0 ]
set b2 [ text := "two rods" , on command := move' 1 ]
set b3 [ text := "three rods", on command := move' 2 ]
set p [ layout := floatCentre $ column 4 [ centre $ widget st
, row 4 [widget b1, widget b2, widget b3]
]
, on paint := onpaint
]
return ()
{-
dist :: Int -> Int -> Int
dist x y = let i = x * x + y * y
f = fromInteger $ toInteger i
s = sqrt f
in floor s
drawButton :: Int -> DC () -> Rect -> IO ()
drawButton n dc (Rect x y w h) =
do circle dc (pt (x + w `div` 2) (y + h `div` 2)) (min w h `div` 2) [brushKind := BrushTransparent]
let t = w `div` (n + 1)
for 1 n (\i -> line dc (pt (x + i * t) (y + h `div` 5)) (pt (x + i * t) (y + h - h `div` 5)) [])
-}
move :: Properties -> Int -> (Player, Nim) -> (Player, Nim)
move pr n (p, Nim m) = ((p + 1) `mod` players pr, Nim (m - n))
|
HJvT/GeBoP
|
Nim.hs
|
bsd-3-clause
| 2,252 | 0 | 18 | 795 | 742 | 380 | 362 | 39 | 1 |
{-# OPTIONS_GHC -Wall #-}
module Messages.Strings where
import Messages.Types (Message(..))
showFiles :: [FilePath] -> String
showFiles = unlines . map ((++) " ")
renderMessage :: Message -> String
renderMessage ErrorsHeading = "ERRORS"
renderMessage ErrorFileLocation = "<location>"
renderMessage (FilesWillBeOverwritten filePaths) =
unlines
[ "This will overwrite the following files to use Elm's preferred style:"
, ""
, showFiles filePaths
, "This cannot be undone! Make sure to back up these files before proceeding."
, ""
, "Are you sure you want to overwrite these files with formatted versions? (y/n)"
]
renderMessage (NoElmFilesFound filePaths) =
unlines
[ "Could not find any .elm files on the specified paths:"
, ""
, showFiles filePaths
, "Please check the given paths."
]
renderMessage CantWriteToOutputBecauseInputIsDirectory =
unlines
[ "Can't write to the OUTPUT path, because multiple .elm files have been specified."
, ""
, "Please remove the --output argument. The .elm files in INPUT will be formatted in place."
]
renderMessage (ProcessingFile file) =
"Processing file " ++ file
renderMessage TooManyInputSources =
"Too many input sources! Please only provide one of either INPUT or --stdin"
|
fredcy/elm-format
|
src/Messages/Strings.hs
|
bsd-3-clause
| 1,305 | 0 | 8 | 271 | 194 | 107 | 87 | 31 | 1 |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE StandaloneDeriving #-}
module GRIN.GrinLiteral where
import Data.Text
import Data.Data
data GrinLiteral =
LitInteger Integer
| LitFloat Float
| LitDouble Double
| LitChar Char
| LitBool Bool
| LitNull
| LitString String
| LitLLVM
deriving (Eq, Ord, Data, Typeable, Show)
|
spacekitteh/libgrin
|
src/GRIN/GrinLiteral.hs
|
bsd-3-clause
| 399 | 0 | 6 | 77 | 83 | 50 | 33 | 17 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Network.Raptr.ServerSpec where
import Control.Concurrent.MVar
import Control.Concurrent.Queue
import Control.Exception
import Control.Monad
import Data.Binary
import Network.Raptr.Raptr
import Network.Raptr.TestUtils
import Network.URI
import Network.Wai (Application)
import System.Directory (removePathForcibly)
import System.IO
import System.Posix.Temp
import Test.Hspec
import Test.Hspec.Wai
import Test.Hspec.Wai.Matcher
app :: FilePath -> IO Application
app logFile = do
nodeLog <- openLog logFile
node <- newNode Nothing defaultRaftConfig (Client emptyNodes) nodeLog
return $ server node
startStopServer = bracket startServer stopServer
where
startServer = do
(logfile, hdl) <- mkstemp "test-log"
hClose hdl
theApp <- app logfile
s <- start defaultConfig theApp
pure (logfile, s)
stopServer (logFile, s) = do
stop s
removePathForcibly logFile
clientSpec :: Spec
clientSpec = around startStopServer $ do
it "can send message from client to server" $ \ (_, srv) -> do
let p = raptrPort srv
Just uri = parseURI $ "http://localhost:" ++ show p ++"/raptr/bar"
msg :: Message Value = MRequestVote $ RequestVote term0 "foo" index0 term0
sendClient msg uri -- expect no exception
serverSpec :: Spec
serverSpec = with (app "/dev/null") $ do
let msg :: Message Value = MRequestVote $ RequestVote term0 "foo" index0 term0
it "on POST /raptr/foo it enqueues event and returns it" $ do
let ev = EMessage "foo" msg
post "/raptr/foo" (encode msg) `shouldRespondWith` ResponseMatcher { matchStatus = 200
, matchHeaders = ["Content-Type" <:> "application/octet-stream"]
, matchBody = bodyEquals (encode ev) }
it "on POST /raptr/foo it returns 503 if queue is full" $ do
replicateM 10 $ post "/raptr/foo" (encode msg)
post "/raptr/foo" (encode msg) `shouldRespondWith` 503
|
capital-match/raptr
|
test/Network/Raptr/ServerSpec.hs
|
bsd-3-clause
| 2,273 | 0 | 17 | 685 | 556 | 281 | 275 | 51 | 1 |
module FP.Monads where
import FP.Core
---------------------
-- Monadic Effects --
---------------------
-- ID {{{
newtype ID a = ID { runID :: a }
deriving
( Eq, Ord
, PartialOrder
, HasBot
, Monoid
, JoinLattice
)
instance Unit ID where
unit = ID
instance CUnit Universal ID where
cunit = unit
instance Functor ID where
map f = ID . f . runID
instance FunctorM ID where
mapM f = map ID . f . runID
instance CFunctor Universal ID where
cmap = map
instance CFunctorM Universal ID where
cmapM = mapM
instance Product ID where
aM <*> bM = ID $ (runID aM, runID bM)
instance Applicative ID where
fM <@> aM = ID $ runID fM $ runID aM
instance Bind ID where
aM >>= k = k $ runID aM
instance Monad ID where
instance Functorial HasBot ID where
functorial = W
instance Functorial JoinLattice ID where
functorial = W
instance Functorial Monoid ID where
functorial = W
newtype IDT m a = IDT { runIDT :: m a }
-- }}}
-- MaybeT {{{
maybeCommute :: (Functor m) => MaybeT (MaybeT m) ~> MaybeT (MaybeT m)
maybeCommute aMM = MaybeT $ MaybeT $ ff ^$ runMaybeT $ runMaybeT aMM
where
ff Nothing = Just Nothing
ff (Just Nothing) = Nothing
ff (Just (Just a)) = Just (Just a)
instance (Unit m) => Unit (MaybeT m) where
unit = MaybeT . unit . Just
instance (Functor m) => Functor (MaybeT m) where
map f = MaybeT . f ^^. runMaybeT
instance (Functor m, Product m) => Product (MaybeT m) where
aM1 <*> aM2 = MaybeT $ uncurry ff ^$ runMaybeT aM1 <*> runMaybeT aM2
where
ff Nothing _ = Nothing
ff _ Nothing = Nothing
ff (Just a1) (Just a2) = Just (a1, a2)
instance (Functor m, Applicative m) => Applicative (MaybeT m) where
fM <@> aM = MaybeT $ ff ^@ runMaybeT fM <$> runMaybeT aM
where
ff Nothing _ = Nothing
ff _ Nothing = Nothing
ff (Just f) (Just a) = Just $ f a
instance (Monad m) => Bind (MaybeT m) where
aM >>= k = MaybeT $ do
aM' <- runMaybeT aM
case aM' of
Nothing -> return Nothing
Just a -> runMaybeT $ k a
instance (Monad m) => Monad (MaybeT m) where
instance FunctorUnit MaybeT where
ftUnit = MaybeT .^ Just
instance FunctorJoin MaybeT where
ftJoin = MaybeT . ff ^. runMaybeT . runMaybeT
where
ff Nothing = Nothing
ff (Just aM) = aM
instance MonadFunctor MaybeT where
mtMap :: (Monad m, Monad n) => (m ~> n) -> MaybeT m ~> MaybeT n
mtMap f = MaybeT . f . runMaybeT
instance (Monad m) => MonadMaybeI (MaybeT m) where
maybeI :: MaybeT m ~> MaybeT (MaybeT m)
maybeI = maybeCommute . ftUnit
instance (Monad m) => MonadMaybeE (MaybeT m) where
maybeE :: MaybeT (MaybeT m) ~> MaybeT m
maybeE = ftJoin . maybeCommute
-- }}}
-- ErrorT {{{
mapError :: (Functor m) => (e1 -> e2) -> ErrorT e1 m a -> ErrorT e2 m a
mapError f = ErrorT . mapLeft f ^. runErrorT
errorCommute :: (Functor m) => ErrorT e (ErrorT e m) ~> ErrorT e (ErrorT e m)
errorCommute = ErrorT . ErrorT . ff ^. runErrorT . runErrorT
where
ff (Inl e) = Inr (Inl e)
ff (Inr (Inl e)) = Inl e
ff (Inr (Inr a)) = Inr $ Inr a
instance (Unit m) => Unit (ErrorT e m) where
unit a = ErrorT $ unit $ Inr a
instance (Functor m) => Functor (ErrorT e m) where
map f aM = ErrorT $ mapRight f ^$ runErrorT aM
instance (Functor m, Product m) => Product (ErrorT e m) where
aM1 <*> aM2 = ErrorT $ ff ^$ runErrorT aM1 <*> runErrorT aM2
where
ff (Inl e, _) = Inl e
ff (_, Inl e) = Inl e
ff (Inr a, Inr b) = Inr (a, b)
instance (Functor m, Applicative m) => Applicative (ErrorT e m) where
fM <@> aM = ErrorT $ ff ^@ runErrorT fM <$> runErrorT aM
where
ff (Inl e) _ = Inl e
ff _ (Inl e) = Inl e
ff (Inr f) (Inr a) = Inr $ f a
instance (Unit m, Bind m) => Bind (ErrorT e m) where
aM >>= k = ErrorT $ do
aeM <- runErrorT aM
case aeM of
Inl e -> unit $ Inl e
Inr a -> runErrorT $ k a
instance (Monad m) => Monad (ErrorT e m) where
instance MonadUnit (ErrorT e) where
mtUnit :: (Monad m) => m ~> ErrorT e m
mtUnit aM = ErrorT $ Inr ^$ aM
instance MonadJoin (ErrorT e) where
mtJoin :: (Monad m) => ErrorT e (ErrorT e m) ~> ErrorT e m
mtJoin = ErrorT . ff ^. runErrorT . runErrorT
where
ff (Inl e) = Inl e
ff (Inr ea) = ea
instance MonadFunctor (ErrorT e) where
mtMap :: (Monad m, Monad n) => m ~> n -> ErrorT e m ~> ErrorT e n
mtMap f = ErrorT . f . runErrorT
instance (Monad m) => MonadErrorI e (ErrorT e m) where
errorI :: ErrorT e m ~> ErrorT e (ErrorT e m)
errorI = errorCommute . mtUnit
instance (Monad m) => MonadErrorE e (ErrorT e m) where
errorE :: ErrorT e (ErrorT e m) ~> ErrorT e m
errorE = mtJoin . errorCommute
instance (Monad m) => MonadError e (ErrorT e m) where
-- }}}
-- ReaderT {{{
type Reader r = ReaderT r ID
runReader :: r -> Reader r a -> a
runReader r = runID . runReaderT r
readerCommute :: ReaderT r1 (ReaderT r2 m) ~> ReaderT r2 (ReaderT r1 m)
readerCommute aMM = ReaderT $ \ r2 -> ReaderT $ \ r1 -> runReaderT r2 $ runReaderT r1 aMM
instance (Unit m) => Unit (ReaderT r m) where
unit = ReaderT . const . unit
instance (Functor m) => Functor (ReaderT r m) where
map f = ReaderT . f ^^. unReaderT
instance (Product m) => Product (ReaderT r m) where
aM1 <*> aM2 = ReaderT $ \ r ->
runReaderT r aM1 <*> runReaderT r aM2
instance (Applicative m) => Applicative (ReaderT r m) where
fM <@> aM = ReaderT $ \ r ->
runReaderT r fM <@> runReaderT r aM
instance (Bind m) => Bind (ReaderT r m) where
aM >>= k = ReaderT $ \ r -> runReaderT r . k *$ runReaderT r aM
instance (Monad m) => Monad (ReaderT r m) where
instance MonadUnit (ReaderT r) where
mtUnit = ReaderT . const
instance MonadJoin (ReaderT r) where
mtJoin aMM = ReaderT $ \ r -> runReaderT r $ runReaderT r aMM
instance MonadFunctor (ReaderT r) where
mtMap :: (Monad m, Monad n) => (m ~> n) -> (ReaderT r m ~> ReaderT r n)
mtMap f aM = ReaderT $ \ r -> f $ runReaderT r aM
instance (Monad m) => MonadReaderI r (ReaderT r m) where
readerI :: ReaderT r m ~> ReaderT r (ReaderT r m)
readerI = readerCommute . mtUnit
instance (Monad m) => MonadReaderE r (ReaderT r m) where
readerE :: ReaderT r (ReaderT r m) ~> ReaderT r m
readerE = mtJoin . readerCommute
instance (Monad m) => MonadReader r (ReaderT r m) where
instance (MonadZero m) => MonadZero (ReaderT r m) where
mzero = ReaderT $ const mzero
-- }}}
-- WriterT {{{
execWriterT :: (Functor m) => WriterT o m a -> m o
execWriterT = snd ^. runWriterT
mapOutput :: (Functor m) => (o1 -> o2) -> WriterT o1 m a -> WriterT o2 m a
mapOutput f = WriterT . mapSnd f ^. runWriterT
writerCommute :: (Functor m) => WriterT o1 (WriterT o2 m) ~> WriterT o2 (WriterT o1 m)
writerCommute aMM = WriterT $ WriterT $ ff ^$ runWriterT $ runWriterT aMM
where
ff ((a, o1), o2) = ((a, o2), o1)
instance (Unit m, Monoid o) => Unit (WriterT o m) where
unit = WriterT . unit . (,null)
instance (Functor m) => Functor (WriterT o m) where
map f = WriterT . mapFst f ^. runWriterT
instance (Functor m, Product m, Monoid o) => Product (WriterT o m) where
aM1 <*> aM2 = WriterT $ ff ^$ runWriterT aM1 <*> runWriterT aM2
where
ff ((a1, o1), (a2, o2)) = ((a1, a2), o1 ++ o2)
instance (Functor m, Applicative m, Monoid o) => Applicative (WriterT o m) where
fM <@> aM = WriterT $ ff2 ^$ ff1 ^@ runWriterT fM <$> runWriterT aM
where
ff1 (f, o) = mapFst ((,o) . f)
ff2 ((a, o1), o2) = (a, o1 ++ o2)
instance (Monad m, Monoid o) => Bind (WriterT o m) where
aM >>= k = WriterT $ do
(a, o1) <- runWriterT aM
(b, o2) <- runWriterT $ k a
return (b, o1 ++ o2)
instance (Monad m, Monoid o) => Monad (WriterT o m) where
instance (Monoid w) => MonadUnit (WriterT w) where
mtUnit = WriterT .^ (,null)
instance MonadJoin (WriterT w) where
mtJoin = fst ^. runWriterT
instance MonadFunctor (WriterT w) where
mtMap :: (Monad m, Monad n) => (m ~> n) -> (WriterT w m ~> WriterT w n)
mtMap f aM = WriterT $ f $ runWriterT aM
instance (Monad m, Monoid o) => MonadWriterI o (WriterT o m) where
writerI :: WriterT o m ~> WriterT o (WriterT o m)
writerI = writerCommute . mtUnit
instance (Monad m, Monoid o) => MonadWriterE o (WriterT o m) where
writerE :: WriterT o (WriterT o m) ~> WriterT o m
writerE = mtJoin . writerCommute
instance (Monad m, Monoid o) => MonadWriter o (WriterT o m) where
instance (MonadZero m, Monoid o) => MonadZero (WriterT o m) where
mzero = WriterT $ mzero
-- }}}
-- StateT {{{ --
runStateT :: s -> StateT s m a -> m (a, s)
runStateT = flip unStateT
evalStateT :: (Functor m) => s -> StateT s m a -> m a
evalStateT = fst ^.: runStateT
execStateT :: (Functor m) => s -> StateT s m a -> m s
execStateT = snd ^.: runStateT
type State s = StateT s ID
runState :: s -> State s a -> (a, s)
runState = runID .: runStateT
evalState :: s -> State s a -> a
evalState = fst .: runState
execState :: s -> State s a -> s
execState = snd .: runState
stateCommute :: (Functor m) => StateT s1 (StateT s2 m) ~> StateT s2 (StateT s1 m)
stateCommute aMM = StateT $ \ s2 -> StateT $ \ s1 -> ff ^$ runStateT s2 $ runStateT s1 aMM
where
ff ((a, s1), s2) = ((a, s2), s1)
stateLens :: (Monad m) => Lens s1 s2 -> StateT s2 m ~> StateT s1 m
stateLens l aM = StateT $ \ s1 -> do
let s2 = access l s1
(a, s2') <- unStateT aM s2
return (a, set l s2' s1)
instance (Unit m) => Unit (StateT s m) where
unit x = StateT $ \ s -> unit (x, s)
instance (Functor m) => Functor (StateT s m) where
map f aM = StateT $ \ s -> mapFst f ^$ unStateT aM s
instance (Monad m) => Product (StateT s m) where
(<*>) = mpair
instance (Monad m) => Applicative (StateT s m) where
(<@>) = mapply
instance (Bind m) => Bind (StateT s m) where
aM >>= k = StateT $ \ s -> do
(a, s') <- unStateT aM s
unStateT (k a) s'
instance (Monad m) => Monad (StateT s m) where
instance MonadUnit (StateT s) where
mtUnit aM = StateT $ \ s -> (,s) ^$ aM
instance MonadJoin (StateT s) where
mtJoin aMM = StateT $ \ s -> runStateT s $ fst ^$ runStateT s aMM
instance MonadFunctor (StateT s) where
mtMap :: (Monad m, Monad n) => (m ~> n) -> StateT s m ~> StateT s n
mtMap f aM = StateT $ f . unStateT aM
instance (MonadZero m) => MonadZero (StateT s m) where
mzero = StateT $ const mzero
instance (MonadPlus m) => MonadPlus (StateT s m) where
aM1 <+> aM2 = StateT $ \ s -> unStateT aM1 s <+> unStateT aM2 s
instance (MonadMonoid m) => MonadMonoid (StateT s m) where
aM1 <++> aM2 = StateT $ \ s -> unStateT aM1 s <++> unStateT aM2 s
instance (Functorial HasBot m, HasBot s, HasBot a) => HasBot (StateT s m a) where
bot :: StateT s m a
bot =
with (functorial :: W (HasBot (m (a, s)))) $
StateT $ \ _ -> bot
instance (Functorial Monoid m, Monoid s, Monoid a) => Monoid (StateT s m a) where
null =
with (functorial :: W (Monoid (m (a, s)))) $
StateT $ \ _ -> null
aM1 ++ aM2 =
with (functorial :: W (Monoid (m (a, s)))) $
StateT $ \ s -> unStateT aM1 s ++ unStateT aM2 s
instance (Functorial Monoid m, Monoid s) => Functorial Monoid (StateT s m) where
functorial = W
instance (Functorial HasBot m, Functorial JoinLattice m, JoinLattice s, JoinLattice a) => JoinLattice (StateT s m a) where
aM1 \/ aM2 =
with (functorial :: W (JoinLattice (m (a, s)))) $
StateT $ \ s -> unStateT aM1 s \/ unStateT aM2 s
instance (Functorial HasBot m, Functorial JoinLattice m, JoinLattice s) => Functorial JoinLattice (StateT s m) where
functorial = W
instance (Monad m) => MonadStateI s (StateT s m) where
stateI :: StateT s m ~> StateT s (StateT s m)
stateI = stateCommute . mtUnit
instance (Monad m) => MonadStateE s (StateT s m) where
stateE :: StateT s (StateT s m) ~> StateT s m
stateE = mtJoin . stateCommute
instance (Monad m) => MonadState s (StateT s m) where
-- }}} --
-- RWST {{{
runRWST :: (Functor m) => r -> s -> RWST r o s m a -> m (a, o, s)
runRWST r0 s0 = ff ^. runStateT s0 . runWriterT . runReaderT r0 . unRWST
where
ff ((a, o), s) = (a, o, s)
rwsCommute :: (Monad m, Monoid o1, Monoid o2) => RWST r1 o1 s1 (RWST r2 o2 s2 m) ~> RWST r2 o2 s2 (RWST r1 o1 s1 m)
rwsCommute =
RWST
. mtMap (mtMap rwsStateCommute . rwsWriterCommute)
. rwsReaderCommute
. mtMap unRWST
deriving instance (Unit m, Monoid o) => Unit (RWST r o s m)
deriving instance (Functor m) => Functor (RWST r o s m)
deriving instance (Monad m, Monoid o) => Product (RWST r o s m)
deriving instance (Monad m, Monoid o) => Applicative (RWST r o s m)
deriving instance (Monad m, Monoid o) => Bind (RWST r o s m)
deriving instance (Monad m, Monoid o) => Monad (RWST r o s m)
instance (Monoid o) => MonadUnit (RWST r o s) where
mtUnit = RWST . mtUnit . mtUnit . mtUnit
instance (Monoid o) => MonadJoin (RWST r o s) where
mtJoin =
RWST
. mtJoin
. mtMap (mtMap mtJoin . writerReaderCommute)
. mtMap (mtMap (mtMap (mtMap mtJoin . stateWriterCommute) . stateReaderCommute))
. unRWST . mtMap unRWST
instance (Monoid o) => MonadFunctor (RWST r o s) where
mtMap f = RWST . mtMap (mtMap (mtMap f)) . unRWST
deriving instance (Monad m, Monoid o) => MonadReaderI r (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadReaderE r (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadReader r (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadWriterI o (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadWriterE o (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadWriter o (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadStateI s (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadStateE s (RWST r o s m)
deriving instance (Monad m, Monoid o) => MonadState s (RWST r o s m)
instance (Monad m, Monoid o) => MonadRWSI r o s (RWST r o s m) where
rwsI :: RWST r o s m ~> RWST r o s (RWST r o s m)
rwsI = rwsCommute . mtUnit
instance (Monad m, Monoid o) => MonadRWSE r o s (RWST r o s m) where
rwsE :: RWST r o s (RWST r o s m) ~> RWST r o s m
rwsE = mtJoin . rwsCommute
instance (Monad m, Monoid o) => MonadRWS r o s (RWST r o s m) where
deriving instance (MonadZero m, Monoid o) => MonadZero (RWST r o s m)
deriving instance (MonadMaybeI m, Monoid o) => MonadMaybeI (RWST r o s m)
deriving instance (MonadMaybeE m, Monoid o) => MonadMaybeE (RWST r o s m)
deriving instance (MonadMaybe m, Monoid o) => MonadMaybe (RWST r o s m)
-- }}}
-- ListT {{{
listCommute :: (Functor m) => ListT (ListT m) ~> ListT (ListT m)
listCommute = ListT . ListT . transpose ^. runListT . runListT
instance (Unit m) => Unit (ListT m) where
unit = ListT . unit . singleton
instance (Functor m) => Functor (ListT m) where
map f = ListT . f ^^. runListT
instance (Monad m, Functorial Monoid m) => Product (ListT m) where
(<*>) = mpair
instance (Monad m, Functorial Monoid m) => Applicative (ListT m) where
(<@>) = mapply
instance (Bind m, Functorial Monoid m) => Bind (ListT m) where
(>>=) :: forall a b. ListT m a -> (a -> ListT m b) -> ListT m b
aM >>= k = ListT $ do
xs <- runListT aM
runListT $ concat $ k ^$ xs
instance (Monad m, Functorial Monoid m) => Monad (ListT m) where
instance FunctorUnit ListT where
ftUnit = ListT .^ unit
instance FunctorJoin ListT where
ftJoin = ListT . concat ^. runListT . runListT
instance FunctorFunctor ListT where
ftMap f = ListT . f . runListT
instance (Functorial Monoid m) => Monoid (ListT m a) where
null =
with (functorial :: W (Monoid (m [a]))) $
ListT null
xs ++ ys =
with (functorial :: W (Monoid (m [a]))) $
ListT $ runListT xs ++ runListT ys
instance (Functorial Monoid m) => Functorial Monoid (ListT m) where functorial = W
instance (Functorial Monoid m) => MonadZero (ListT m) where
mzero = null
instance (Functorial Monoid m) => MonadMonoid (ListT m) where
(<++>) = (++)
instance (Monad m, Functorial Monoid m) => MonadListI (ListT m) where
listI :: ListT m ~> ListT (ListT m)
listI = listCommute . ftUnit
instance (Monad m, Functorial Monoid m) => MonadListE (ListT m) where
listE :: ListT (ListT m) ~> ListT m
listE = ftJoin . listCommute
instance (Monad m, Functorial Monoid m) => MonadList (ListT m) where
maybeToList :: (Functor m) => MaybeT m a -> ListT m a
maybeToList aM = ListT $ ff ^$ runMaybeT aM
where
ff Nothing = []
ff (Just a) = [a]
instance (Monad m, Functorial Monoid m) => MonadMaybeE (ListT m) where
maybeE :: MaybeT (ListT m) ~> ListT m
maybeE = listE . maybeToList
-- }}}
-- ErrorListT {{{
errorListCommute :: (Functor m) => ErrorListT e (ErrorListT e m) ~> ErrorListT e (ErrorListT e m)
errorListCommute aMM = ErrorListT $ ErrorListT $ errorListTranspose ^$ runErrorListT $ runErrorListT aMM
instance (Unit m) => Unit (ErrorListT e m) where
unit = ErrorListT . unit . unit
instance (Functor m) => Functor (ErrorListT e m) where
map f = ErrorListT . f ^^. runErrorListT
instance (Monad m, Functorial Monoid m) => Product (ErrorListT e m) where
(<*>) = mpair
instance (Monad m, Functorial Monoid m) => Applicative (ErrorListT e m) where
(<@>) = mapply
instance (Bind m, Functorial Monoid m) => Bind (ErrorListT e m) where
(>>=) :: forall a b. ErrorListT e m a -> (a -> ErrorListT e m b) -> ErrorListT e m b
aM >>= k = ErrorListT $ do
xs <- runErrorListT aM
runErrorListT $ concat $ k ^$ xs
instance (Monad m, Functorial Monoid m) => Monad (ErrorListT e m) where
instance FunctorUnit (ErrorListT e) where
ftUnit = ErrorListT .^ unit
instance FunctorJoin (ErrorListT e) where
ftJoin = ErrorListT . errorListConcat ^. runErrorListT . runErrorListT
instance FunctorFunctor (ErrorListT e) where
ftMap f = ErrorListT . f . runErrorListT
instance (Functorial Monoid m) => Monoid (ErrorListT e m a) where
null =
with (functorial :: W (Monoid (m (ErrorList e a)))) $
ErrorListT null
xs ++ ys =
with (functorial :: W (Monoid (m (ErrorList e a)))) $
ErrorListT $ runErrorListT xs ++ runErrorListT ys
instance (Functorial Monoid m) => Functorial Monoid (ErrorListT e m) where functorial = W
instance (Functorial Monoid m) => MonadZero (ErrorListT e m) where
mzero = null
instance (Functorial Monoid m) => MonadMonoid (ErrorListT e m) where
(<++>) = (++)
instance (Monad m, Functorial Monoid m) => MonadErrorListI e (ErrorListT e m) where
errorListI :: ErrorListT e m ~> ErrorListT e (ErrorListT e m)
errorListI = errorListCommute . ftUnit
instance (Monad m, Functorial Monoid m) => MonadErrorListE e (ErrorListT e m) where
errorListE :: ErrorListT e (ErrorListT e m) ~> ErrorListT e m
errorListE = ftJoin . errorListCommute
instance (Monad m, Functorial Monoid m) => MonadErrorList e (ErrorListT e m) where
errorToErrorList :: (Functor m) => ErrorT e m ~> ErrorListT e m
errorToErrorList aM = ErrorListT $ ff ^$ runErrorT aM
where
ff (Inl e) = ErrorListFailure [e]
ff (Inr a) = ErrorListSuccess a []
-- this might not be right
errorListToError :: (Monad m, Functorial Monoid m) => ErrorListT e (ErrorListT e m) a -> ErrorT e (ErrorListT e m) a
errorListToError aM = ErrorT $ mconcat . ff *$ runErrorListT aM
where
ff (ErrorListFailure e) = map (return . Inl) e
ff (ErrorListSuccess x xs) = map (return . Inr) $ x:xs
instance (Monad m, Functorial Monoid m) => MonadErrorE e (ErrorListT e m) where
errorE :: ErrorT e (ErrorListT e m) ~> ErrorListT e m
errorE = errorListE . errorToErrorList
-- instance (Monad m, Functorial Monoid m) => MonadErrorI e (ErrorListT e m) where
-- errorI :: ErrorListT e m ~> ErrorT e (ErrorListT e m)
-- errorI = errorListToError . errorListI
-- instance (Monad m, Functorial Monoid m) => MonadError e (ErrorListT e m) where
-- }}}
-- ListSetT {{{
listSetCommute :: (Functor m) => ListSetT (ListSetT m) ~> ListSetT (ListSetT m)
listSetCommute = ListSetT . ListSetT . (ListSet . ListSet ^. transpose . runListSet ^. runListSet) ^. runListSetT . runListSetT
instance (Unit m) => Unit (ListSetT m) where
unit = ListSetT . unit . ListSet . singleton
instance (CUnit c m) => CUnit (c ::.:: ListSet) (ListSetT m) where
cunit = ListSetT . cunit . ListSet . singleton
instance (Functor m) => Functor (ListSetT m) where
map f = ListSetT . f ^^. runListSetT
instance (Monad m, Functorial JoinLattice m) => Product (ListSetT m) where
(<*>) = mpair
instance (Monad m, Functorial JoinLattice m) => Applicative (ListSetT m) where
(<@>) = mapply
instance (Bind m, Functorial JoinLattice m) => Bind (ListSetT m) where
(>>=) :: forall a b. ListSetT m a -> (a -> ListSetT m b) -> ListSetT m b
aM >>= k = ListSetT $ do
xs <- runListSetT aM
runListSetT $ msum $ k ^$ xs
-- PROOF of: monad laws for (ListSetT m) {{{
--
-- ASSUMPTION 1: returnₘ a <+> returnₘ b = returnₘ (a \/ b)
-- [this comes from m being a lattice functor. (1 x + 1 y) = 1 (x + y)]
--
-- * PROOF of: left unit := return x >>= k = k x {{{
--
-- return x >>= k
-- = [[definition of >>=]]
-- ListSetT $ do { xs <- runListSetT $ return x ; runListSetT $ msums $ map k xs }
-- = [[definition of return]]
-- ListSetT $ do { xs <- runListSetT $ ListSetT $ return [x] ; runListSetT $ msums $ map k xs }
-- = [[ListSetT beta]]
-- ListSetT $ do { xs <- return [x] ; runListSetT $ msums $ map k xs }
-- = [[monad left unit]]
-- ListSetT $ runListSetT $ msums $ map k [x]
-- = [[definition of map]]
-- ListSetT $ runListSetT $ msums $ [k x]
-- = [[definition of msums and <+> unit]]
-- ListSetT $ runListSetT $ k x
-- = [[ListSetT eta]]
-- k x
-- QED }}}
--
-- * PROOF of: right unit := aM >>= return = aM {{{
--
-- aM >>= return
-- = [[definition of >>=]]
-- ListSetT $ { xs <- runListSetT aM ; runListSetT $ msums $ map return xs }
-- = [[induction/expansion on xs]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; runListSetT $ msums $ map return [x1,..,xn] }
-- = [[definition of return and map]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; runListSetT $ msums $ [ListSetT $ return [x1],..,ListSetT $ return [xn]] }
-- = [[definition of msums]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; runListSetT $ ListSetT $ return [x1] <+> .. <+> return [xn] }
-- = [[assumption 1]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; runListSetT $ ListSetT $ return [x1,..,xn] }
-- = [[ListSetT beta]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; return [x1,..,xn] }
-- = [[monad right unit]]
-- ListSetT $ runListSetT aM
-- = [[ListSetT eta]]
-- aM
-- QED }}}
--
-- * PROOF of: associativity := (aM >>= k1) >>= k2 = { x <- aM ; k1 x >>= k2 } {{{
--
-- (aM >>= k1) >>= k2
-- = [[definition of >>=]]
-- ListSetT $ { xs <- runListSetT $ ListSetT $ { xs' <- runListSetT aM ; runListSetT $ msums $ map k1 xs' } ; runListSetT $ msums $ map k xs }
-- = [[ListSetT beta]]
-- ListSetT $ { xs <- { xs' <- runListSetT aM ; runListSetT $ msums $ map k1 xs' } ; runListSetT $ msums $ map k xs }
-- = [[monad associativity]]
-- ListSetT $ { xs' <- runListSetT aM ; xs <- runListSetT $ msums $ map k1 xs' ; runListSetT $ msums $ map k xs }
-- =
-- LHS
--
-- { x <- aM ; k1 x >>= k2 }
-- = [[definition of >>=]]
-- ListSetT $ { xs' <- runListSetT aM ; runListSetT $ msums $ map (\ x -> ListSetT $ { xs <- runListSetT (k1 x) ; runListSetT $ msums $ map k2 xs }) xs' }
-- = [[induction/expansion on xs']]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; runListSetT $ msums $ map (\ x -> ListSetT $ { xs <- runListSetT (k1 x) ; runListSetT $ msums $ map k2 xs }) [x1,..,xn] }
-- = [[definition of map]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; runListSetT $ msums $ [ListSetT $ { xs <- runListSetT (k1 x1) ; runListSetT $ msums $ map k2 xs },..,ListSetT $ { xs <- runListSetT (k1 xn) ; runList $ msums $ map k2 xs}] }
-- = [[definition of msum]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; runListSetT $ ListSetT { xs <- runListSetT (k1 x1) ; runListSetT $ msums $ map k2 xs } <+> .. <+> ListSetT { xs <- runListSetT (k1 xn) ; runListSetT $ msums $ map k2 xs } }
-- = [[ListSetT beta and definition of <+> for ListSetT]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; { xs <- runListSetT (k1 x1) ; runListSetT $ msums $ map k2 xs } <+> .. <+> { xs <- runListSetT (k1 xn) ; runListSetT $ msums $ map k2 xs } }
-- = [[<+> distribute with >>=]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; xs <- (runListSetT (k1 x1) <+> .. <+> runListSetT (k1 xn)) ; runListSetT $ msums $ map k2 xs }
-- = [[definition of msums and map]]
-- ListSetT $ { [x1,..,xn] <- runListSetT aM ; xs <- runListSetT $ msums $ map k1 [x1,..,xn] ; runListSetT $ msums $ map k2 xs }
-- = [[collapsing [x1,..,xn]]]
-- ListSetT $ { xs' <- runListSetT aM ; xs <- runListSetT $ msums $ map k1 xs' ; runListSetT $ msums $ map k xs }
-- =
-- RHS
--
-- LHS = RHS
-- QED }}}
--
-- }}}
instance (Monad m, Functorial JoinLattice m) => Monad (ListSetT m) where
instance MonadUnit ListSetT where
mtUnit = ListSetT .^ unit
instance MonadJoin ListSetT where
mtJoin = ListSetT . concat ^. runListSetT . runListSetT
instance MonadFunctor ListSetT where
mtMap f = ListSetT . f . runListSetT
instance (Functorial JoinLattice m) => MonadZero (ListSetT m) where
mzero :: forall a. ListSetT m a
mzero =
with (functorial :: W (JoinLattice (m (ListSet a)))) $
ListSetT bot
instance (Functorial JoinLattice m) => MonadPlus (ListSetT m) where
(<+>) :: forall a. ListSetT m a -> ListSetT m a -> ListSetT m a
aM1 <+> aM2 =
with (functorial :: W (JoinLattice (m (ListSet a)))) $
ListSetT $ runListSetT aM1 \/ runListSetT aM2
instance (Monad m, Functorial JoinLattice m) => MonadListSetI (ListSetT m) where
listSetI :: ListSetT m ~> ListSetT (ListSetT m)
listSetI = listSetCommute . mtUnit
instance (Monad m, Functorial JoinLattice m) => MonadListSetE (ListSetT m) where
listSetE :: ListSetT (ListSetT m) ~> ListSetT m
listSetE = mtJoin . listSetCommute
instance (Monad m, Functorial JoinLattice m) => MonadListSet (ListSetT m) where
-- }}}
-- SetT {{{
setCommute :: (Functor m) => SetT (SetT m) ~> SetT (SetT m)
setCommute = SetT . SetT . setTranspose ^. runSetT . runSetT
instance (CUnit c m) => CUnit (Ord ::*:: (c ::.:: Set)) (SetT m) where
cunit = SetT . cunit . ssingleton
instance (Functor m, Product m) => Product (SetT m) where
(<*>) :: forall a b. SetT m a -> SetT m b -> SetT m (a, b)
aM1 <*> aM2 = SetT $ uncurry ff ^$ runSetT aM1 <*> runSetT aM2
where
ff :: Set a -> Set b -> Set (a, b)
ff s1 s2 =
learnSetOn s1 null $
learnSetOn s2 null $
fromList $ toList s1 <*> toList s2
instance (CFunctor c m) => CFunctor (Ord ::*:: (c ::.:: Set)) (SetT m) where
cmap = mapSetT . cmap . cmap
instance (Functorial JoinLattice m, Bind m) => Bind (SetT m) where
aM >>= k = SetT $ do
aC <- runSetT aM
runSetT $ msum $ k ^$ toList aC
instance (Functorial JoinLattice m) => MonadZero (SetT m) where
mzero :: forall a. SetT m a
mzero =
with (functorial :: W (JoinLattice (m (Set a)))) $
SetT bot
instance (Functorial JoinLattice m) => MonadPlus (SetT m) where
(<+>) :: forall a. SetT m a -> SetT m a -> SetT m a
aM1 <+> aM2 =
with (functorial :: W (JoinLattice (m (Set a)))) $
SetT $ runSetT aM1 \/ runSetT aM2
-- }}}
-- KonT {{{
evalKonT :: (Unit m) => KonT r m r -> m r
evalKonT aM = runKonT aM unit
type Kon r = KonT r ID
runKon :: Kon r a -> (a -> r) -> r
runKon aM f = runID $ runKonT aM (ID . f)
evalKon :: Kon r r -> r
evalKon aM = runKon aM id
instance (Unit m) => Unit (KonT r m) where
unit a = KonT $ \ k -> k a
instance (Unit m) => Applicative (KonT r m) where
(<@>) = mapply
instance (Unit m) => Product (KonT r m) where
(<*>) = mpair
instance (Unit m) => Functor (KonT r m) where
map = mmap
instance (Unit m) => Bind (KonT r m) where
(>>=) :: KonT r m a -> (a -> KonT r m b) -> KonT r m b
aM >>= kM = KonT $ \ (k :: b -> m r) -> runKonT aM $ \ a -> runKonT (kM a) k
instance (Unit m) => Monad (KonT r m) where
instance MonadIsoFunctor (KonT r) where
mtIsoMap :: (Monad m, Monad n) => m ~> n -> n ~> m -> KonT r m ~> KonT r n
mtIsoMap to from aM = KonT $ \ (k :: a -> n r) -> to $ runKonT aM $ \ a -> from $ k a
instance (Monad m) => MonadKonI r (KonT r m) where
konI :: KonT r m ~> KonT r (KonT r m)
konI aM = KonT $ \ (k1 :: a -> KonT r m r) -> KonT $ \ (k2 :: r -> m r) ->
k2 *$ runKonT aM $ \ a -> runKonT (k1 a) return
instance (Monad m) => MonadKonE r (KonT r m) where
konE :: KonT r (KonT r m) ~> KonT r m
konE aMM = KonT $ \ (k :: a -> m r) ->
let aM :: KonT r m r
aM = runKonT aMM $ \ a -> KonT $ \ (k' :: r -> m r) -> k' *$ k a
in runKonT aM return
instance (Monad m) => MonadKon r (KonT r m) where
-- }}}
-- OpaqueKonT {{{
runOpaqueKonTWith :: k r m a -> OpaqueKonT k r m a -> m r
runOpaqueKonTWith = flip runOpaqueKonT
makeMetaKonT :: (FFMorphism (k r) (KFun r)) => ((a -> m r) -> m r) -> OpaqueKonT k r m a
makeMetaKonT nk = OpaqueKonT $ \ (k :: k r m a) -> nk $ runKFun $ ffmorph k
runMetaKonT :: (FFMorphism (KFun r) (k r)) => OpaqueKonT k r m a -> (a -> m r) -> m r
runMetaKonT aM k = runOpaqueKonT aM $ ffmorph $ KFun k
runMetaKonTWith :: (FFMorphism (KFun r) (k r)) => (a -> m r) -> OpaqueKonT k r m a -> m r
runMetaKonTWith = flip runMetaKonT
evalOpaqueKonT :: (Unit m, FFMorphism (KFun r) (k r)) => OpaqueKonT k r m r -> m r
evalOpaqueKonT aM = runMetaKonT aM unit
type OpaqueKon k r = OpaqueKonT k r ID
makeOpaqueKon :: (k r ID a -> r) -> OpaqueKon k r a
makeOpaqueKon nk = OpaqueKonT $ ID . nk
makeMetaKon :: (FFMorphism (k r) (KFun r)) => ((a -> r) -> r) -> OpaqueKon k r a
makeMetaKon nk = makeOpaqueKon $ \ (k :: k r ID a) -> nk $ (.) runID . runKFun $ ffmorph k
runOpaqueKon :: OpaqueKon k r a -> k r ID a -> r
runOpaqueKon = runID .: runOpaqueKonT
runMetaKon :: (FFMorphism (KFun r) (k r)) => OpaqueKon k r a -> (a -> r) -> r
runMetaKon aM k = runOpaqueKon aM $ ffmorph $ KFun $ ID . k
evalOpaqueKon :: (FFMorphism (KFun r) (k r)) => OpaqueKon k r r -> r
evalOpaqueKon aM = runMetaKon aM id
metaKonT :: (FFMorphism (KFun r) (k r)) => OpaqueKonT k r m ~> KonT r m
metaKonT aM = KonT $ \ (k :: a -> m r) -> runMetaKonT aM k
opaqueKonT :: (FFMorphism (k r) (KFun r)) => KonT r m ~> OpaqueKonT k r m
opaqueKonT aM = makeMetaKonT $ \ (k :: a -> m r) -> runKonT aM k
instance (Monad m, FFMorphism (k r) (KFun r)) => Unit (OpaqueKonT k r m) where
unit :: a -> OpaqueKonT k r m a
unit = opaqueKonT . unit
instance (Monad m, FFIsomorphism (KFun r) (k r)) => Functor (OpaqueKonT k r m) where
map = mmap
instance (Monad m, FFIsomorphism (KFun r) (k r)) => Applicative (OpaqueKonT k r m) where
(<@>) = mapply
instance (Monad m, FFIsomorphism (KFun r) (k r)) => Product (OpaqueKonT k r m) where
(<*>) = mpair
instance (Monad m, FFIsomorphism (KFun r) (k r)) => Bind (OpaqueKonT k r m) where
(>>=) :: OpaqueKonT k r m a -> (a -> OpaqueKonT k r m b) -> OpaqueKonT k r m b
aM >>= kM = OpaqueKonT $ \ (k :: k r m a) -> runMetaKonT aM $ \ a -> runOpaqueKonT (kM a) k
instance (Monad m, FFIsomorphism (KFun r) (k r)) => Monad (OpaqueKonT k r m) where
instance (FFIsomorphism (k r) (KFun r)) => MonadIsoFunctor (OpaqueKonT k r) where
mtIsoMap :: (Monad m, Monad n) => m ~> n -> n ~> m -> OpaqueKonT k r m ~> OpaqueKonT k r n
mtIsoMap to from = opaqueKonT . mtIsoMap to from . metaKonT
class Balloon k r | k -> r where
inflate :: (Monad m) => k r m ~> k r (OpaqueKonT k r m)
deflate :: (Monad m) => k r (OpaqueKonT k r m) ~> k r m
instance (Monad m, FFIsomorphism (KFun r) (k r), Balloon k r) => MonadOpaqueKonI k r (OpaqueKonT k r m) where
withOpaqueC :: k r (OpaqueKonT k r m) a -> OpaqueKonT k r m a -> OpaqueKonT k r m r
withOpaqueC k1 aM = makeMetaKonT $ \ (k2 :: r -> m r) -> k2 *$ runOpaqueKonT aM $ deflate k1
instance (Monad m, FFIsomorphism (KFun r) (k r), Balloon k r) => MonadOpaqueKonE k r (OpaqueKonT k r m) where
callOpaqueCC :: (k r (OpaqueKonT k r m) a -> OpaqueKonT k r m r) -> OpaqueKonT k r m a
callOpaqueCC kk = OpaqueKonT $ \ (k :: k r m a ) -> runMetaKonTWith return $ kk $ inflate k
instance (Monad m, FFIsomorphism (KFun r) (k r), Balloon k r) => MonadOpaqueKon k r (OpaqueKonT k r m) where
instance (Monad m, FFIsomorphism (KFun r) (k r)) => MonadKonI r (OpaqueKonT k r m) where
konI :: OpaqueKonT k r m ~> KonT r (OpaqueKonT k r m)
konI aM = KonT $ \ (k1 :: a -> OpaqueKonT k r m r) -> makeMetaKonT $ \ (k2 :: r -> m r) ->
k2 *$ runMetaKonT aM $ \ a -> runMetaKonT (k1 a) return
instance (Monad m, FFIsomorphism (KFun r) (k r)) => MonadKonE r (OpaqueKonT k r m) where
konE :: KonT r (OpaqueKonT k r m) ~> OpaqueKonT k r m
konE aMM = makeMetaKonT $ \ (k :: a -> m r) ->
runMetaKonTWith return $ runKonT aMM $ \ a -> makeMetaKonT $ \ (k' :: r -> m r) -> k' *$ k a
instance (Monad m, FFIsomorphism (KFun r) (k r)) => MonadKon r (OpaqueKonT k r m) where
-- }}}
----------------------
-- Monads Commuting --
----------------------
-- Maybe // * --
-- Maybe // Reader // FULL COMMUTE {{{
maybeReaderCommute :: (Monad m) => MaybeT (ReaderT r m) ~> ReaderT r (MaybeT m)
maybeReaderCommute aMRM = ReaderT $ \ r -> MaybeT $ runReaderT r $ runMaybeT aMRM
readerMaybeCommute :: (Monad m) => ReaderT r (MaybeT m) ~> MaybeT (ReaderT r m)
readerMaybeCommute aRMM = MaybeT $ ReaderT $ \ r -> runMaybeT $ runReaderT r aRMM
instance (MonadReaderI r m) => MonadReaderI r (MaybeT m) where
readerI :: MaybeT m ~> ReaderT r (MaybeT m)
readerI = maybeReaderCommute . mtMap readerI
instance (MonadReaderE r m) => MonadReaderE r (MaybeT m) where
readerE :: ReaderT r (MaybeT m) ~> MaybeT m
readerE = mtMap readerE . readerMaybeCommute
instance (MonadReader r m) => MonadReader r (MaybeT m) where
instance (MonadMaybeI m) => MonadMaybeI (ReaderT r m) where
maybeI :: ReaderT r m ~> MaybeT (ReaderT r m)
maybeI = readerMaybeCommute . mtMap maybeI
instance (MonadMaybeE m) => MonadMaybeE (ReaderT r m) where
maybeE :: MaybeT (ReaderT r m) ~> ReaderT r m
maybeE = mtMap maybeE . maybeReaderCommute
instance (MonadMaybe m) => MonadMaybe (ReaderT r m) where
-- }}}
-- Maybe // Writer {{{
writerMaybeCommute :: (Monoid w, Monad m) => WriterT w (MaybeT m) ~> MaybeT (WriterT w m)
writerMaybeCommute aRMM = MaybeT $ WriterT $ do
awM <- runMaybeT $ runWriterT aRMM
return $ case awM of
Nothing -> (Nothing, null)
Just (a, w) -> (Just a, w)
maybeWriterCommute :: (Monad m) => MaybeT (WriterT w m) ~> WriterT w (MaybeT m)
maybeWriterCommute aMRM = WriterT $ MaybeT $ do
(aM, w) <- runWriterT $ runMaybeT aMRM
return $ case aM of
Nothing -> Nothing
Just a -> Just (a, w)
instance (Monoid w, MonadWriter w m) => MonadWriterI w (MaybeT m) where
writerI :: MaybeT m ~> WriterT w (MaybeT m)
writerI = maybeWriterCommute . mtMap writerI
instance (Monoid w, MonadWriter w m) => MonadWriterE w (MaybeT m) where
writerE :: WriterT w (MaybeT m) ~> MaybeT m
writerE = mtMap writerE . writerMaybeCommute
instance (Monoid w, MonadWriter w m) => MonadWriter w (MaybeT m) where
instance (Monoid w, MonadMaybeI m) => MonadMaybeI (WriterT w m) where
maybeI :: WriterT w m ~> MaybeT (WriterT w m)
maybeI = writerMaybeCommute . mtMap maybeI
instance (Monoid w, MonadMaybeE m) => MonadMaybeE (WriterT w m) where
maybeE :: MaybeT (WriterT w m) ~> WriterT w m
maybeE = mtMap maybeE . maybeWriterCommute
instance (Monoid w, MonadMaybe m) => MonadMaybe (WriterT w m) where
-- }}}
-- Maybe // State {{{
maybeStateCommute :: (Monad m) => MaybeT (StateT s m) ~> StateT s (MaybeT m)
maybeStateCommute aMSM = StateT $ \ s1 -> MaybeT $ do
(aM, s2) <- runStateT s1 $ runMaybeT aMSM
return $ case aM of
Nothing -> Nothing
Just a -> Just (a, s2)
stateMaybeCommute :: (Monad m) => StateT s (MaybeT m) ~> MaybeT (StateT s m)
stateMaybeCommute aSMM = MaybeT $ StateT $ \ s1 -> do
asM <- runMaybeT $ runStateT s1 aSMM
return $ case asM of
Nothing -> (Nothing, s1)
Just (a, s2) -> (Just a, s2)
instance (MonadStateI s m) => MonadStateI s (MaybeT m) where
stateI :: MaybeT m ~> StateT s (MaybeT m)
stateI = maybeStateCommute . mtMap stateI
instance (MonadStateE s m) => MonadStateE s (MaybeT m) where
stateE :: StateT s (MaybeT m) ~> MaybeT m
stateE = mtMap stateE . stateMaybeCommute
instance (MonadState s m) => MonadState s (MaybeT m) where
instance (MonadMaybeI m) => MonadMaybeI (StateT s m) where
maybeI :: StateT s m ~> MaybeT (StateT s m)
maybeI = stateMaybeCommute . mtMap maybeI
instance (MonadMaybeE m) => MonadMaybeE (StateT s m) where
maybeE :: MaybeT (StateT s m) ~> StateT s m
maybeE = mtMap maybeE . maybeStateCommute
instance (MonadMaybe m) => MonadMaybe (StateT s m) where
-- }}}
-- Error // * --
-- Error // Reader {{{
errorReaderCommute :: (Monad m) => ErrorT e (ReaderT r m) ~> ReaderT r (ErrorT e m)
errorReaderCommute aMRM = ReaderT $ \ r -> ErrorT $ runReaderT r $ runErrorT aMRM
readerErrorCommute :: (Monad m) => ReaderT r (ErrorT e m) ~> ErrorT e (ReaderT r m)
readerErrorCommute aRMM = ErrorT $ ReaderT $ \ r -> runErrorT $ runReaderT r aRMM
instance (MonadReaderI r m) => MonadReaderI r (ErrorT e m) where
readerI :: ErrorT e m ~> ReaderT r (ErrorT e m)
readerI = errorReaderCommute . mtMap readerI
instance (MonadReaderE r m) => MonadReaderE r (ErrorT e m) where
readerE :: ReaderT r (ErrorT e m) ~> ErrorT e m
readerE = mtMap readerE . readerErrorCommute
instance (MonadReader r m) => MonadReader r (ErrorT e m) where
instance (MonadErrorI e m) => MonadErrorI e (ReaderT r m) where
errorI :: ReaderT r m ~> ErrorT e (ReaderT r m)
errorI = readerErrorCommute . mtMap errorI
instance (MonadErrorE e m) => MonadErrorE e (ReaderT r m) where
errorE :: ErrorT e (ReaderT r m) ~> ReaderT r m
errorE = mtMap errorE . errorReaderCommute
instance (MonadError e m) => MonadError e (ReaderT r m) where
-- }}}
-- Error // State {{{
errorStateCommute :: (Monad m) => ErrorT e (StateT s m) ~> StateT s (ErrorT e m)
errorStateCommute aMRM = StateT $ \ s -> ErrorT $ ff ^$ runStateT s $ runErrorT aMRM
where
ff :: (e :+: a, s) -> e :+: (a, s)
ff (Inl e, _) = Inl e
ff (Inr a, s) = Inr $ (a, s)
stateErrorCommute :: (Monad m) => StateT s (ErrorT e m) ~> ErrorT e (StateT s m)
stateErrorCommute aRMM = ErrorT $ StateT $ \ s -> ff s ^$ runErrorT $ runStateT s aRMM
where
ff :: s -> e :+: (a, s) -> (e :+: a, s)
ff s (Inl e) = (Inl e, s)
ff _ (Inr (a, s)) = (Inr a, s)
instance (MonadStateI s m) => MonadStateI s (ErrorT e m) where
stateI :: ErrorT e m ~> StateT s (ErrorT e m)
stateI = errorStateCommute . mtMap stateI
instance (MonadStateE s m) => MonadStateE s (ErrorT e m) where
stateE :: StateT s (ErrorT e m) ~> ErrorT e m
stateE = mtMap stateE . stateErrorCommute
instance (MonadState s m) => MonadState s (ErrorT e m) where
instance (MonadErrorI e m) => MonadErrorI e (StateT s m) where
errorI :: StateT s m ~> ErrorT e (StateT s m)
errorI = stateErrorCommute . mtMap errorI
instance (MonadErrorE e m) => MonadErrorE e (StateT s m) where
errorE :: ErrorT e (StateT s m) ~> StateT s m
errorE = mtMap errorE . errorStateCommute
instance (MonadError e m) => MonadError e (StateT s m) where
-- }}}
-- Reader // * --
-- Reader // Writer // FULL COMMUTE {{{
readerWriterCommute :: ReaderT r (WriterT w m) ~> WriterT w (ReaderT r m)
readerWriterCommute aRWM = WriterT $ ReaderT $ \ r -> runWriterT $ runReaderT r aRWM
writerReaderCommute :: WriterT w (ReaderT r m) ~> ReaderT r (WriterT w m)
writerReaderCommute aWRM = ReaderT $ \ r -> WriterT $ runReaderT r $ runWriterT aWRM
instance (Monoid w, MonadWriterI w m) => MonadWriterI w (ReaderT r m) where
writerI :: ReaderT r m ~> WriterT w (ReaderT r m)
writerI = readerWriterCommute . mtMap writerI
instance (Monoid w, MonadWriterE w m) => MonadWriterE w (ReaderT r m) where
writerE :: WriterT w (ReaderT r m) ~> ReaderT r m
writerE = mtMap writerE . writerReaderCommute
instance (Monoid w, MonadWriter w m) => MonadWriter w (ReaderT r m) where
instance (Monoid w, MonadReaderI r m) => MonadReaderI r (WriterT w m) where
readerI :: WriterT w m ~> ReaderT r (WriterT w m)
readerI = writerReaderCommute . mtMap readerI
instance (Monoid w, MonadReaderE r m) => MonadReaderE r (WriterT w m) where
readerE :: ReaderT r (WriterT w m) ~> WriterT w m
readerE = mtMap readerE . readerWriterCommute
instance (Monoid w, MonadReader r m) => MonadReader r (WriterT w m) where
-- }}}
-- Reader // State // FULL COMMUTE {{{
readerStateCommute :: (Functor m) => ReaderT r (StateT s m) ~> StateT s (ReaderT r m)
readerStateCommute aRSM = StateT $ \ s -> ReaderT $ \ r ->
runStateT s $ runReaderT r aRSM
stateReaderCommute :: (Functor m) => StateT s (ReaderT r m) ~> ReaderT r (StateT s m)
stateReaderCommute aSRM = ReaderT $ \ r -> StateT $ \ s ->
runReaderT r $ runStateT s aSRM
instance (MonadStateI s m) => MonadStateI s (ReaderT r m) where
stateI :: ReaderT r m ~> StateT s (ReaderT r m)
stateI = readerStateCommute . mtMap stateI
instance (MonadStateE s m) => MonadStateE s (ReaderT r m) where
stateE :: StateT s (ReaderT r m) ~> ReaderT r m
stateE = mtMap stateE . stateReaderCommute
instance (MonadState s m) => MonadState s (ReaderT r m) where
instance (MonadReaderI r m) => MonadReaderI r (StateT s m) where
readerI :: StateT s m ~> ReaderT r (StateT s m)
readerI = stateReaderCommute . mtMap readerI
instance (MonadReaderE r m) => MonadReaderE r (StateT s m) where
readerE :: ReaderT r (StateT s m) ~> StateT s m
readerE = mtMap readerE . readerStateCommute
instance (MonadReader r m) => MonadReader r (StateT s m) where
-- }}}
-- Reader // RWS {{{
readerRWSCommute :: (Monad m, Monoid o) => ReaderT r1 (RWST r2 o s m) ~> RWST r2 o s (ReaderT r1 m)
readerRWSCommute =
RWST
. mtMap
( mtMap readerStateCommute
. readerWriterCommute
)
. readerCommute
. mtMap unRWST
rwsReaderCommute :: (Monad m, Monoid o) => RWST r1 o s (ReaderT r2 m) ~> ReaderT r2 (RWST r1 o s m)
rwsReaderCommute =
mtMap RWST
. readerCommute
. mtMap
( writerReaderCommute
. mtMap stateReaderCommute
)
. unRWST
-- }}}
-- Writer // * --
-- Writer // State // FULL COMMUTE {{{
writerStateCommute :: (Functor m) => WriterT w (StateT s m) ~> StateT s (WriterT w m)
writerStateCommute aRMM = StateT $ \ s1 -> WriterT $ ff ^$ runStateT s1 $ runWriterT aRMM
where
ff ((a, w), s) = ((a, s), w)
stateWriterCommute :: (Functor m) => StateT s (WriterT w m) ~> WriterT w (StateT s m)
stateWriterCommute aMRM = WriterT $ StateT $ ff ^. runWriterT . unStateT aMRM
where
ff ((a, s), w) = ((a, w), s)
instance (Monoid w, MonadStateI s m) => MonadStateI s (WriterT w m) where
stateI :: WriterT w m ~> StateT s (WriterT w m)
stateI = writerStateCommute . mtMap stateI
instance (Monoid w, MonadStateE s m) => MonadStateE s (WriterT w m) where
stateE :: StateT s (WriterT w m) ~> WriterT w m
stateE = mtMap stateE . stateWriterCommute
instance (Monoid w, MonadState s m) => MonadState s (WriterT w m) where
instance (Monoid w, MonadWriter w m) => MonadWriterI w (StateT s m) where
writerI :: StateT s m ~> WriterT w (StateT s m)
writerI = stateWriterCommute . mtMap writerI
instance (Monoid w, MonadWriter w m) => MonadWriterE w (StateT s m) where
writerE :: WriterT w (StateT s m) ~> StateT s m
writerE = mtMap writerE . writerStateCommute
instance (Monoid w, MonadWriter w m) => MonadWriter w (StateT s m) where
-- }}}
-- Writer // RWS {{{
writerRWSCommute :: (Monad m, Monoid o1, Monoid o2) => WriterT o1 (RWST r o2 s m) ~> RWST r o2 s (WriterT o1 m)
writerRWSCommute =
RWST
. mtMap
( mtMap writerStateCommute
. writerCommute
)
. writerReaderCommute
. mtMap unRWST
rwsWriterCommute :: (Monad m, Monoid o1, Monoid o2) => RWST r o1 s (WriterT o2 m) ~> WriterT o2 (RWST r o1 s m)
rwsWriterCommute =
mtMap RWST
. readerWriterCommute
. mtMap
( writerCommute
. mtMap stateWriterCommute
)
. unRWST
-- }}}
-- State // * --
-- State // RWS {{{
stateRWSCommute :: (Monad m, Monoid o) => StateT s1 (RWST r o s2 m) ~> RWST r o s2 (StateT s1 m)
stateRWSCommute =
RWST
. mtMap
( mtMap stateCommute
. stateWriterCommute
)
. stateReaderCommute
. mtMap unRWST
rwsStateCommute :: (Monad m, Monoid o) => RWST r o s1 (StateT s2 m) ~> StateT s2 (RWST r o s1 m)
rwsStateCommute =
mtMap RWST
. readerStateCommute
. mtMap
( writerStateCommute
. mtMap stateCommute
)
. unRWST
-- }}}
-- State // List {{{
-- (s -> m [a, s]) -> (s -> m ([a], s))
stateListCommute :: (Functor m, Monoid s) => StateT s (ListT m) ~> ListT (StateT s m)
stateListCommute aMM = ListT $ StateT $ \ s -> ff ^$ runListT $ runStateT s aMM
where
ff asL = (fst ^$ asL, concat $ snd ^$ asL)
listStateCommute :: (Functor m) => ListT (StateT s m) ~> StateT s (ListT m)
listStateCommute aMM = StateT $ \ s -> ListT $ ff ^$ runStateT s $ runListT aMM
where
ff (xs, s) = (,s) ^$ xs
instance (MonadListI m, Functorial Monoid m, Monoid s) => MonadListI (StateT s m) where
listI :: StateT s m ~> ListT (StateT s m)
listI = stateListCommute . mtMap listI
instance (MonadListE m, Functorial Monoid m) => MonadListE (StateT s m) where
listE :: ListT (StateT s m) ~> StateT s m
listE = mtMap listE . listStateCommute
instance (MonadList m, Functorial Monoid m, Monoid s) => MonadList (StateT s m) where
instance (MonadStateI s m, Functorial Monoid m) => MonadStateI s (ListT m) where
stateI :: ListT m ~> StateT s (ListT m)
stateI = listStateCommute . ftMap stateI
instance (MonadStateE s m, Functorial Monoid m, Monoid s) => MonadStateE s (ListT m) where
stateE :: StateT s (ListT m) ~> ListT m
stateE = ftMap stateE . stateListCommute
instance (MonadState s m, Functorial Monoid m, Monoid s) => MonadState s (ListT m) where
-- }}}
-- State // ListSet {{{
stateListSetCommute :: (Functor m, JoinLattice s) => StateT s (ListSetT m) ~> ListSetT (StateT s m)
stateListSetCommute aMM = ListSetT $ StateT $ \ s -> ff ^$ runListSetT $ runStateT s aMM
where
ff asL = (fst ^$ asL, joins $ snd ^$ asL)
listSetStateCommute :: (Functor m) => ListSetT (StateT s m) ~> StateT s (ListSetT m)
listSetStateCommute aMM = StateT $ \ s -> ListSetT $ ff ^$ runStateT s $ runListSetT aMM
where
ff (xs, s) = (,s) ^$ xs
instance (MonadListSetI m, Functorial JoinLattice m, JoinLattice s) => MonadListSetI (StateT s m) where
listSetI :: StateT s m ~> ListSetT (StateT s m)
listSetI = stateListSetCommute . mtMap listSetI
instance (MonadListSetE m, Functorial JoinLattice m) => MonadListSetE (StateT s m) where
listSetE :: ListSetT (StateT s m) ~> StateT s m
listSetE = mtMap listSetE . listSetStateCommute
instance (MonadListSet m, Functorial JoinLattice m, JoinLattice s) => MonadListSet (StateT s m) where
instance (MonadStateI s m, Functorial JoinLattice m) => MonadStateI s (ListSetT m) where
stateI :: ListSetT m ~> StateT s (ListSetT m)
stateI = listSetStateCommute . mtMap stateI
instance (MonadStateE s m, Functorial JoinLattice m, JoinLattice s) => MonadStateE s (ListSetT m) where
stateE :: StateT s (ListSetT m) ~> ListSetT m
stateE = mtMap stateE . stateListSetCommute
instance (MonadState s m, Functorial JoinLattice m, JoinLattice s) => MonadState s (ListSetT m) where
-- }}}
-- State // ErrorList {{{
stateErrorListCommute :: (Functor m, Monoid s) => StateT s (ErrorListT e m) ~> ErrorListT e (StateT s m)
stateErrorListCommute aMM = ErrorListT $ StateT $ \ s -> ff ^$ runErrorListT $ runStateT s aMM
where
ff asL = (fst ^$ asL, concat $ snd ^$ asL)
errorListStateCommute :: (Functor m) => ErrorListT e (StateT s m) ~> StateT s (ErrorListT e m)
errorListStateCommute aMM = StateT $ \ s -> ErrorListT $ ff ^$ runStateT s $ runErrorListT aMM
where
ff (xs, s) = (,s) ^$ xs
instance (MonadErrorListI e m, Functorial Monoid m, Monoid s) => MonadErrorListI e (StateT s m) where
errorListI :: StateT s m ~> ErrorListT e (StateT s m)
errorListI = stateErrorListCommute . mtMap errorListI
instance (MonadErrorListE e m, Functorial Monoid m) => MonadErrorListE e (StateT s m) where
errorListE :: ErrorListT e (StateT s m) ~> StateT s m
errorListE = mtMap errorListE . errorListStateCommute
instance (MonadErrorList e m, Functorial Monoid m, Monoid s) => MonadErrorList e (StateT s m) where
instance (MonadStateI s m, Functorial Monoid m) => MonadStateI s (ErrorListT e m) where
stateI :: ErrorListT e m ~> StateT s (ErrorListT e m)
stateI = errorListStateCommute . ftMap stateI
instance (MonadStateE s m, Functorial Monoid m, Monoid s) => MonadStateE s (ErrorListT e m) where
stateE :: StateT s (ErrorListT e m) ~> ErrorListT e m
stateE = ftMap stateE . stateErrorListCommute
instance (MonadState s m, Functorial Monoid m, Monoid s) => MonadState s (ErrorListT e m) where
-- }}}
-- State // Kon {{{
stateKonCommute :: StateT s (KonT (r, s) m) ~> KonT r (StateT s m)
stateKonCommute aSK = KonT $ \ (k :: a -> StateT s m r) -> StateT $ \ s ->
runKonT (runStateT s aSK) $ \ (a, s') -> runStateT s' $ k a
konStateCommute :: KonT r (StateT s m) ~> StateT s (KonT (r, s) m)
konStateCommute aKS = StateT $ \ s -> KonT $ \ (k :: (a, s) -> m (r, s)) ->
runStateT s $ runKonT aKS $ \ a -> StateT $ \ s' -> k (a, s')
instance (MonadState s m) => MonadStateI s (KonT r m) where
stateI :: KonT r m ~> StateT s (KonT r m)
stateI =
mtMap (mtIsoMap stateE stateI)
. mtMap stateKonCommute
. stateI
. konStateCommute
. mtIsoMap stateI (stateE :: StateT s m ~> m)
instance (MonadState s m) => MonadStateE s (KonT r m) where
stateE :: StateT s (KonT r m) ~> KonT r m
stateE =
mtIsoMap stateE stateI
. stateKonCommute
. stateE
. mtMap konStateCommute
. mtMap (mtIsoMap stateI (stateE :: StateT s m ~> m))
-- }}}
-- State // OpaqueKon {{{
instance (MonadState s m, FFIsomorphism (KFun r) (k r)) => MonadStateI s (OpaqueKonT k r m) where
stateI :: OpaqueKonT k r m ~> StateT s (OpaqueKonT k r m)
stateI =
mtMap opaqueKonT
. stateI
. metaKonT
instance (MonadState s m, FFIsomorphism (KFun r) (k r)) => MonadStateE s (OpaqueKonT k r m) where
stateE :: StateT s (OpaqueKonT k r m) ~> OpaqueKonT k r m
stateE =
opaqueKonT
. stateE
. mtMap metaKonT
instance (MonadState s m, FFIsomorphism (KFun r) (k r)) => MonadState s (OpaqueKonT k r m) where
-- }}}
|
davdar/quals
|
src/FP/Monads.hs
|
bsd-3-clause
| 50,076 | 235 | 19 | 11,300 | 21,077 | 10,734 | 10,343 | -1 | -1 |
module GameState where
import Player hiding (tell,put,get,putS,getS,putC,getC,putCS,getCS)
import Data
import NameGenerator
import Control.Concurrent.STM
import Control.Concurrent.Async
import Control.Monad.Reader
import Control.Monad.State hiding (get, put)
import Control.Exception (catch, Exception, throw, throwIO)
import Prelude hiding (catch)
data GameState = GameState { you, left, partner, right :: Player
, inPlay :: TVar [Play]
, yourScore, oppScore :: TVar Int
, yourName, oppName :: String
, phase :: TVar Phase
, firstOut :: TVar (Maybe Player)
, wish :: TVar (Maybe FaceValue)
}
instance Show GameState where
show GameState {yourName = yn, oppName = on,
you = y, left = l, partner = p, right = r}
= "Team " ++ yn ++ " (" ++ show y ++ ", " ++ show p ++ ")\n\n VS.\n\n" ++
"Team " ++ on ++ " (" ++ show l ++ ", " ++ show r ++ ")\n"
initialiseGame :: Player -> Player -> Player -> Player -> IO GameState
initialiseGame y l p r = do
n <- getName
m <- getName
atomically $ do
a <- newTVar []
[b,c] <- sequence [newTVar 0, newTVar 0]
d <- newTVar PreRound
e <- newTVar Nothing
f <- newTVar Nothing
return $ GameState y l p r a b c n m d e f
type Game a = StateT GameState IO a
data Phase = PreRound | Passing | Playing | PostGame
deriving (Show, Read, Eq)
data Direction = You | L | Partner | R
deriving (Show, Read, Eq)
onRotate You = L
onRotate L = Partner
onRotate Partner = R
onRotate R = You
seat :: Direction -> GameState -> Player
seat You = you
seat L = left
seat Partner = partner
seat R = right
rotate :: GameState -> GameState
rotate (GameState y l p r a b c m n d e f) = GameState r y l p a c b n m d e f
nextPlayer :: (Monad m) => StateT GameState m ()
nextPlayer = modify rotate
nextInPlayer :: Int -> StateT GameState STM Int
nextInPlayer 4 = return 4
nextInPlayer n = do
nextPlayer
out <- checkIfOut
if out then nextInPlayer (n+1) else return (n+1)
--helpful StateT functions
getS :: (r -> TVar a) -> StateT r STM a
getS f = gets f >>= \a -> lift $ readTVar a
putS :: (r -> TVar a) -> a -> StateT r STM ()
putS f x = gets f >>= \a -> lift $ writeTVar a x
getCS :: (r -> TChan a) -> StateT r STM a
getCS f = gets f >>= \a -> lift $ readTChan a
putCS :: (r -> TChan a) -> a -> StateT r STM ()
putCS f x = gets f >>= \a -> lift $ writeTChan a x
get :: (r -> TVar a) -> StateT r IO a
get f = gets f >>= \a -> liftIO $ atomically $ readTVar a
put :: (r -> TVar a) -> a -> StateT r IO ()
put f x = gets f >>= \a -> liftIO $ atomically $ writeTVar a x
getC :: (r -> TChan a) -> StateT r IO a
getC f = gets f >>= \a -> liftIO $ atomically $ readTChan a
putC :: (r -> TChan a) -> a -> StateT r IO ()
putC f x = gets f >>= \a -> liftIO $ atomically $ writeTChan a x
trickRace :: Game a -> Game a -> Game a
trickRace a b = do
r <- gets id
ei <- liftIO $ race (runStateT a r) (runStateT b r)
case ei of
Left (a,s) -> modify (const s) >> return a
Right (a,s) -> modify (const s) >> return a
tRaceList :: [Game a] -> Game a
tRaceList = foldr trickRace endless
endless :: Game a
endless = liftIO $ atomically retry
sCatch :: (Exception e) => Game a -> (e -> Game a) -> Game a
sCatch act handler = do
s <- gets id
(a,s') <- liftIO $ catch (runStateT act s) (\e -> runStateT (handler e) s)
modify $ const s'
return a
sAtom :: StateT GameState STM a -> Game a
sAtom = mapStateT atomically
withYou :: (Monad m) => ReaderT Player m a -> StateT GameState m a
withYou rdr = do
pl <- gets you
lift $ runReaderT rdr pl
withYouAtom :: ReaderT Player STM a -> Game a
withYouAtom rdr = sAtom $ withYou rdr
checkIfOut :: StateT GameState STM Bool
checkIfOut = do
pl <- gets you
cds <- lift $ runReaderT totalCards pl
noPlay <- lift $ isEmptyTChan (playChan pl)
return $ cds == 0 && noPlay
broadcast :: String -> Game ()
broadcast s = mapStateT atomically $ eachPlayer_ $ tellS You s
broadcastS s = eachPlayer_ $ tellS You s
tell :: Direction -> String -> Game ()
tell d s = putC (toChan . (seat d)) s
tellS d s = putCS (toChan . (seat d)) s
eachPlayer_ :: (Monad m) => StateT GameState m () -> StateT GameState m ()
eachPlayer_ act = sequence_ $ replicate 4 $ act >> nextPlayer
eachPlayer :: (Monad m) => StateT GameState m a -> StateT GameState m [a]
eachPlayer act = sequence $ replicate 4 $ nextPlayer >> act
|
thomasathorne/h-chu
|
src/GameState.hs
|
bsd-3-clause
| 4,509 | 0 | 18 | 1,178 | 2,047 | 1,035 | 1,012 | 114 | 2 |
module Geometry.Sphere (volume, area) where
volume :: Float -> Float
volume radius = (4.0 / 3.0) * pi * (radius ^ 3)
area :: Float -> Float
area radius = 4 * pi * (radius ^ 2)
|
zxl20zxl/learnyouahaskell
|
Geometry/Sphere.hs
|
mit
| 178 | 0 | 8 | 39 | 85 | 47 | 38 | 5 | 1 |
{-# LANGUAGE TemplateHaskell, Rank2Types, FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances, FunctionalDependencies #-}
module World where
import qualified Data.IntMap as IM
import Control.Applicative ((<$>))
import Control.Lens
import Control.Monad.State
import Data.Foldable (foldMap, for_)
import Building
import Item
import Terrain
import Tile
import Utils
import Creature
import AIState
type Creature = CreatureP World
type Building = BuildingP World
type Item = ItemP World Creature
type ItemId = ItemIdP World Creature
type BuildingId = BuildingIdP World
type CreatureId = CreatureIdP World
type AI = AIState World Creature
data World = World {
_worldTerrain :: Terrain
, _worldCreatures :: IM.IntMap Creature
, _worldItems :: IM.IntMap Item
, _worldMaxId :: Int
, _worldJobs :: [Job]
, _worldBuildings :: IM.IntMap Building
}
data Job =
JobDig Area
| JobBuild BuildingId
| JobBrew
makeLenses ''World
class WorldObject world obj | obj -> world where
objLens :: ObjId obj -> Lens' world (Maybe obj)
objId :: obj -> ObjId obj
objPos :: Traversal' obj Point
tileContains :: Point -> ObjId obj -> Lens' world Bool
instance WorldObject World (CreatureP World) where
objLens i = worldCreatures . at (getObjId i)
objId = view creatureId
objPos = creaturePos
tileContains p oid = worldTerrain . terrainTile p . tileCreatures . contains (getObjId oid)
instance WorldObject World (BuildingP World) where
objLens i = worldBuildings . at (getObjId i)
objId = view buildingId
objPos = buildingPos
tileContains p oid = worldTerrain . terrainTile p . tileBuildings . contains (getObjId oid)
instance WorldObject World (ItemP World Creature) where
objLens i = worldItems . at (getObjId i)
objId = view itemId
objPos = itemState . _ItemPos
tileContains p oid = worldTerrain . terrainTile p . tileItems . contains (getObjId oid)
instance Show Job where
show (JobDig area) = "Dig area " ++ show area
show (JobBuild bid) = "Building " ++ show bid
show JobBrew = "Brew"
instance Show World where
show w = show (w ^. worldTerrain)
++ showObjs (w ^.. worldCreatures.traverse)
++ showObjs (w ^.. worldItems.traverse)
++ showObjs (w ^.. worldBuildings.traverse)
++ showObjs (w ^.. worldJobs.traverse)
where
showObjs :: Show a => [a] -> String
showObjs = foldMap ((++"\n").show)
worldPhysics :: State World ()
worldPhysics = do
world <- get
let phys obj = do
let mpos = obj ^? objPos
case mpos of
Just pos -> do
let newpos = pos & _3 +~ 1
let getTileType position = world ^. worldTerrain . terrainTile position . tileType
if TileEmpty == getTileType pos && not (tileIsWall (getTileType newpos))
then moveObj obj newpos
else return obj
Nothing ->
return obj
newCreatures <- traverse phys (world ^. worldCreatures)
worldCreatures .= newCreatures
newItems <- traverse phys (world ^. worldItems)
worldItems .= newItems
jobFinished :: Job -> State World Bool
jobFinished (JobDig area) = do
terrain <- use worldTerrain
return . and $ map (\pos -> not . tileIsWall $ terrain ^. terrainTile pos . tileType) (areaPoints area)
jobFinished (JobBuild bid) = do
bState <- use . pre $ objLens bid . traverse . buildingState
return $ isn't (_Just . _BuildingBuilding) bState
jobFinished JobBrew = return False
checkJobs :: State World ()
checkJobs = do
jobs <- use worldJobs
newJobs <- filterM (\job -> not <$> jobFinished job) jobs
worldJobs .= newJobs
stepWorld :: State World ()
stepWorld = do
creatures <- use worldCreatures
for_ creatures $ \creature ->
(creature ^. creatureAct) creature
buildings <- use worldBuildings
for_ buildings $ \building ->
(building ^. buildingAct) building
checkJobs
worldPhysics
startBuilding :: BuildingType -> Point -> World -> World
startBuilding bt pos world =
world & worldMaxId +~ 1
& objLens newId ?~ b
& worldJobs %~ (JobBuild newId :)
& tileContains pos newId .~ True
where
newId :: BuildingId
newId = ObjId $ world ^. worldMaxId + 1
b = makeBuilding bt
& buildingPos .~ pos
& buildingId .~ newId
addCreature :: Creature -> World -> World
addCreature creature world =
world & worldMaxId +~ 1
& objLens newId ?~ newCreature
& tileContains (creature ^. creaturePos) newId .~ True
where
newId :: CreatureId
newId = ObjId $ world ^. worldMaxId + 1
newCreature = creature & creatureId .~ newId
addItem :: Item -> World -> World
addItem item world =
world & worldMaxId +~ 1
& objLens newId ?~ newItem
& case item ^. itemState of
ItemPos pos -> tileContains pos newId .~ True
ItemHeldBy cid -> objLens cid . traverse . creatureItems %~ (newItem :)
where
newId :: ItemId
newId = ObjId $ world ^. worldMaxId + 1
newItem = item
& itemId .~ newId
getObjPosId :: (MonadState world m, WorldObject world object) => ObjId object -> m (Maybe Point)
getObjPosId oid = preuse $ objLens oid . traverse . objPos
pickUpItemId :: MonadState World m => ItemId -> Creature -> m Creature
pickUpItemId itemid creature = do
mitem <- use (objLens itemid)
case mitem of
Just item -> do
forMOf_ objPos item $ \pos -> tileContains pos itemid .= False
let newItem = item & itemState .~ ItemHeldBy (creature ^. creatureId)
objLens itemid ?= newItem
return $ creature & creatureItems %~ (newItem :)
Nothing -> return creature
moveObjDir :: (MonadState World m, WorldObject World obj) => obj -> Dir -> m (obj, Bool)
moveObjDir obj dir = do
terrain <- use worldTerrain
case (\x -> (canMoveDir terrain x dir, x)) <$> obj ^? objPos of
Just (True, oldPos) -> do
let pos = addDir dir oldPos
newObj <- moveObj obj pos
return (newObj, True)
_ -> return (obj, False)
moveObj :: (MonadState world m, WorldObject world obj) => obj -> Point -> m obj
moveObj obj pos = do
let oid = objId obj
forMOf_ objPos obj $ \opos -> tileContains opos oid .= False
tileContains pos oid .= True
return $ obj & objPos .~ pos
makeBuilding :: BuildingType -> Building
makeBuilding BuildingField =
defBuilding & buildingType .~ BuildingField
& buildingAct .~ fieldAct
& buildingInternal .~ Just (FieldTimer 10)
makeBuilding BuildingBrewery =
defBuilding & buildingType .~ BuildingBrewery
fieldAct :: Building -> State World ()
fieldAct field =
when (hasn't (buildingState . _BuildingBuilding) field) $
if anyOf (buildingInternal . _Just . _FieldTimer) (<= 0) field
then do
modify $ addItem Item {
_itemId = ObjId (-1)
, _itemType = Wheat
, _itemMaterial = None
, _itemState = ItemPos (field ^. buildingPos)
}
fieldTimer .= 10
else fieldTimer -= 1
where
fieldTimer = objLens (objId field) . _Just . buildingInternal . _Just . _FieldTimer
|
skeskinen/neflEFortress
|
World.hs
|
mit
| 7,479 | 0 | 23 | 2,139 | 2,376 | 1,190 | 1,186 | -1 | -1 |
-- A fractal consisting of circles and lines which looks a bit like
-- the workings of a clock.
import Graphics.Gloss
main
= animate (InWindow "Clock" (600, 600) (20, 20))
black frame
-- Build the fractal, scale it so it fits in the window
-- and rotate the whole thing as time moves on.
frame :: Float -> Picture
frame time
= Color white
$ Scale 120 120
$ Rotate (time * 2*pi)
$ clockFractal 5 time
-- The basic fractal consists of three circles offset from the origin
-- as follows.
--
-- 1
-- |
-- .
-- / \
-- 2 3
--
-- The direction of rotation switches as n increases.
-- Components at higher iterations also spin faster.
--
clockFractal :: Int -> Float -> Picture
clockFractal 0 s = Blank
clockFractal n s = Pictures [circ1, circ2, circ3, lines]
where
-- y offset from origin to center of circle 1.
a = 1 / sin (2 * pi / 6)
-- x offset from origin to center of circles 2 and 3.
b = a * cos (2 * pi / 6)
nf = fromIntegral n
rot = if n `mod` 2 == 0
then 50 * s * (log (1 + nf))
else (-50 * s * (log (1 + nf)))
-- each element contains a copy of the (n-1) iteration contained
-- within a larger circle, and some text showing the time since
-- the animation started.
--
circNm1
= Pictures
[ circle 1
, Scale (a/2.5) (a/2.5) $ clockFractal (n-1) s
, if n > 2
then Color cyan
$ Translate (-0.15) 1
$ Scale 0.001 0.001
$ Text (show s)
else Blank
]
circ1 = Translate 0 a $ Rotate rot circNm1
circ2 = Translate 1 (-b) $ Rotate (-rot) circNm1
circ3 = Translate (-1) (-b) $ Rotate rot circNm1
-- join each iteration to the origin with some lines.
lines
= Pictures
[ Line [(0, 0), ( 0, a)]
, Line [(0, 0), ( 1, -b)]
, Line [(0, 0), (-1, -b)] ]
|
kylegodbey/haskellProject
|
src/test.hs
|
mit
| 1,777 | 55 | 14 | 482 | 614 | 339 | 275 | 37 | 3 |
module Data.Wright.CIE.Illuminant.D55 (d55) where
import Data.Wright.Types (Model)
import Data.Wright.CIE.Illuminant.Environment (environment)
d55 :: Model
d55 = environment (0.33242, 0.34743)
|
fmap/wright
|
src/Data/Wright/CIE/Illuminant/D55.hs
|
mit
| 194 | 0 | 6 | 19 | 57 | 37 | 20 | 5 | 1 |
module Foundation where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Network.HTTP.Client.Conduit (Manager, HasHttpManager (getHttpManager))
import qualified Settings
import Settings.Development (development)
import qualified Database.Persist
import Database.Persist.Sql (SqlPersistT)
import Settings.StaticFiles
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Text.Hamlet (hamletFile)
import Yesod.Core.Types (Logger)
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data App = App
{ settings :: AppConfig DefaultEnv Extra
, getStatic :: Static -- ^ Settings for static file serving.
, connPool :: Database.Persist.PersistConfigPool Settings.PersistConf -- ^ Database connection pool.
, httpManager :: Manager
, persistConfig :: Settings.PersistConf
, appLogger :: Logger
}
instance HasHttpManager App where
getHttpManager = httpManager
-- Set up i18n messages. See the message folder.
mkMessage "App" "messages" "en"
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://www.yesodweb.com/book/routing-and-handlers
--
-- Note that this is really half the story; in Application.hs, mkYesodDispatch
-- generates the rest of the code. Please see the linked documentation for an
-- explanation for this split.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget)
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod App where
approot = ApprootMaster $ appRoot . settings
-- Store session data on the client in encrypted cookies,
-- default session idle timeout is 120 minutes
makeSessionBackend _ = fmap Just $ defaultClientSessionBackend
120 -- timeout in minutes
"config/client_session_key.aes"
defaultLayout widget = do
master <- getYesod
mmsg <- getMessage
-- We break up the default layout into two components:
-- default-layout is the contents of the body tag, and
-- default-layout-wrapper is the entire page. Since the final
-- value passed to hamletToRepHtml cannot be a widget, this allows
-- you to use normal widget features in default-layout.
pc <- widgetToPageContent $ do
$(combineStylesheets 'StaticR
[ css_normalize_css
, css_bootstrap_css
])
$(widgetFile "default-layout")
giveUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")
-- This is done to provide an optimization for serving static files from
-- a separate domain. Please see the staticRoot setting in Settings.hs
urlRenderOverride y (StaticR s) =
Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s
urlRenderOverride _ _ = Nothing
-- The page to be redirected to when authentication is required.
authRoute _ = Just $ AuthR LoginR
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent =
addStaticContentExternal minifym genFileName Settings.staticDir (StaticR . flip StaticRoute [])
where
-- Generate a unique filename based on the content itself
genFileName lbs
| development = "autogen-" ++ base64md5 lbs
| otherwise = base64md5 lbs
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- What messages should be logged. The following includes all messages when
-- in development, and warnings and errors in production.
shouldLog _ _source level =
development || level == LevelWarn || level == LevelError
makeLogger = return . appLogger
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlPersistT
runDB = defaultRunDB persistConfig connPool
instance YesodPersistRunner App where
getDBRunner = defaultGetDBRunner connPool
instance YesodAuth App where
type AuthId App = UserId
-- Where to send a user after successful login
loginDest _ = HomeR
-- Where to send a user after logout
logoutDest _ = HomeR
getAuthId creds = runDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Just uid
Nothing -> do
fmap Just $ insert User
{ userIdent = credsIdent creds
, userPassword = Nothing
}
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [authBrowserId def]
authHttpManager = httpManager
-- This instance is required to use forms. You can modify renderMessage to
-- achieve customized and internationalized form validation messages.
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
-- | Get the 'Extra' value, used to hold data from the settings.yml file.
getExtra :: Handler Extra
getExtra = fmap (appExtra . settings) getYesod
-- Note: previous versions of the scaffolding included a deliver function to
-- send emails. Unfortunately, there are too many different options for us to
-- give a reasonable default. Instead, the information is available on the
-- wiki:
--
-- https://github.com/yesodweb/yesod/wiki/Sending-email
|
athanclark/Chupacabra
|
Foundation.hs
|
mit
| 6,024 | 0 | 18 | 1,352 | 864 | 475 | 389 | -1 | -1 |
--------------------------------------------------------------------------
-- Copyright (c) 2015, ETH Zurich.
-- All rights reserved.
--
-- This file is distributed under the terms in the attached LICENSE file.
-- If you do not find this file, copies can be found by writing to:
-- ETH Zurich D-INFK, CAB F.78, Universitaetstrasse 6, CH-8092 Zurich.
-- Attn: Systems Group.
--
-- Architectural definitions for Barrelfish on ARMv8.
--
--------------------------------------------------------------------------
module ARMv8 where
import HakeTypes
import qualified Config
import qualified ArchDefaults
import Data.Char
-------------------------------------------------------------------------
--
-- Architecture specific definitions for ARM
--
-------------------------------------------------------------------------
arch = "armv8"
archFamily = "aarch64"
compiler = Config.aarch64_cc
objcopy = Config.aarch64_objcopy
objdump = Config.aarch64_objdump
ar = Config.aarch64_ar
ranlib = Config.aarch64_ranlib
cxxcompiler = Config.aarch64_cxx
ourCommonFlags = [ Str "-fno-unwind-tables",
Str "-Wno-packed-bitfield-compat",
Str "-fno-stack-protector",
Str "-mcpu=cortex-a57",
Str "-march=armv8-a",
Str "-mabi=lp64",
Str "-mstrict-align",
Str "-fPIE",
-- The dispatcher needs a scratch register on ARMv8.
-- We use r18, which is reserved as the 'platform register'
-- by the ARM-64 ABI.
Str "-ffixed-x18",
Str "-D__ARM_CORTEX__",
Str "-D__ARM_ARCH_8A__",
-- Str "-DPREFER_SIZE_OVER_SPEED",
Str "-Wno-unused-but-set-variable",
Str "-Wno-format"
]
cFlags = ArchDefaults.commonCFlags
++ ArchDefaults.commonFlags
++ ourCommonFlags
cxxFlags = ArchDefaults.commonCxxFlags
++ ArchDefaults.commonFlags
++ ourCommonFlags
++ [Str "-std=gnu++11"]
cDefines = ArchDefaults.cDefines options
ourLdFlags = [ Str "-Wl,--build-id=none", Str "-static" ]
ldFlags = ArchDefaults.ldFlags arch ++ ourLdFlags
ldCxxFlags = ArchDefaults.ldCxxFlags arch ++ ourLdFlags
stdLibs = ArchDefaults.stdLibs arch
options = (ArchDefaults.options arch archFamily) {
optFlags = cFlags,
optCxxFlags = cxxFlags,
optDefines = cDefines,
optDependencies =
[ PreDep InstallTree arch "/include/trace_definitions/trace_defs.h",
PreDep InstallTree arch "/include/errors/errno.h",
PreDep InstallTree arch "/include/barrelfish_kpi/capbits.h",
PreDep InstallTree arch "/include/asmoffsets.h"
],
optLdFlags = ldFlags,
optLdCxxFlags = ldCxxFlags,
optLibs = stdLibs,
optInterconnectDrivers = ["lmp", "ump", "multihop", "local"],
optFlounderBackends = ["lmp", "ump", "multihop", "local"]
}
--
-- Compilers
--
cCompiler = ArchDefaults.cCompiler arch compiler Config.cOptFlags
cxxCompiler = ArchDefaults.cxxCompiler arch cxxcompiler Config.cOptFlags
makeDepend = ArchDefaults.makeDepend arch compiler
makeCxxDepend = ArchDefaults.makeCxxDepend arch cxxcompiler
cToAssembler = ArchDefaults.cToAssembler arch compiler Config.cOptFlags
assembler = ArchDefaults.assembler arch compiler Config.cOptFlags
archive = ArchDefaults.archive arch
linker = ArchDefaults.linker arch compiler
ldtLinker = ArchDefaults.ldtLinker arch compiler
strip = ArchDefaults.strip arch objcopy
debug = ArchDefaults.debug arch objcopy
cxxlinker = ArchDefaults.cxxlinker arch cxxcompiler
ldtCxxlinker = ArchDefaults.ldtCxxlinker arch cxxcompiler
--
-- The kernel needs different flags
--
kernelCFlags = [ Str s | s <- [ "-fno-builtin",
"-fno-unwind-tables",
"-nostdinc",
"-std=c99",
"-mcpu=cortex-a57",
"-march=armv8-a+nofp",
"-mgeneral-regs-only",
"-mabi=lp64",
"-mstrict-align",
"-U__linux__",
"-Wall",
"-Wshadow",
"-Wstrict-prototypes",
"-Wold-style-definition",
"-Wmissing-prototypes",
"-Wmissing-declarations",
"-Wmissing-field-initializers",
"-Wredundant-decls",
"-Werror",
"-imacros deputy/nodeputy.h",
"-fno-stack-check",
"-ffreestanding",
"-fomit-frame-pointer",
"-Wmissing-noreturn",
"-D__ARM_CORTEX__",
"-D__ARM_ARCH_8A__",
"-DPREFER_SIZE_OVER_SPEED",
"-Wno-unused-but-set-variable",
"-Wno-format"
]]
kernelLdFlags = [ Str "-Wl,-N",
Str "-pie",
Str "-fno-builtin",
Str "-nostdlib",
Str "-Wl,--fatal-warnings",
Str "-Wl,--build-id=none"
]
--
-- Link the kernel (CPU Driver)
--
linkKernel :: Options -> [String] -> [String] -> String -> String -> HRule
linkKernel opts objs libs name driverType=
let linkscript = "/kernel/" ++ name ++ ".lds"
kernelmap = "/kernel/" ++ name ++ ".map"
kasmdump = "/kernel/" ++ name ++ ".asm"
kbinary = "/sbin/" ++ name
kdebug = kbinary ++ ".debug"
kfull = kbinary ++ ".full"
in
Rules ([ Rule ([ Str compiler ] ++
map Str Config.cOptFlags ++
[ NStr "-T", In BuildTree arch linkscript,
Str "-o",
Out arch kfull,
NStr "-Wl,-Map,", Out arch kernelmap
]
++ (optLdFlags opts)
++
[ In BuildTree arch o | o <- objs ]
++
[ In BuildTree arch l | l <- libs ]
++
(ArchDefaults.kernelLibs arch)
++
[ NL, NStr "bash -c \"echo -e '\\0002'\" | dd of=",
Out arch kfull,
Str "bs=1 seek=16 count=1 conv=notrunc status=noxfer"
]
),
Rule $ strip opts kfull kdebug kbinary,
Rule $ debug opts kfull kdebug,
-- Generate kernel assembly dump
Rule [ Str objdump,
Str "-d",
Str "-M reg-names-raw",
In BuildTree arch kbinary,
Str ">",
Out arch kasmdump ],
Rule [ Str "cpp",
NStr "-I", NoDep SrcTree "src" "/kernel/include/arch/armv8",
NStr "-I", NoDep SrcTree "src" "/kernel/include",
Str "-D__ASSEMBLER__",
Str "-P", In SrcTree "src"
("/kernel/arch/armv8/"++driverType++".lds.in"),
Out arch linkscript
]
] ++ [ Phony ((map toUpper arch) ++ "_All") False
[ Dep BuildTree arch kbinary]])
|
kishoredbn/barrelfish
|
hake/ARMv8.hs
|
mit
| 7,856 | 0 | 21 | 3,086 | 1,241 | 680 | 561 | 142 | 1 |
{-# LANGUAGE CPP #-}
module Main where
#define READLINE
#if __GLASGOW_HASKELL__ > 602
import Test.HUnit
import Test.QuickCheck hiding (test)
#else
import HUnit
import Debug.QuickCheck hiding (test)
#endif
import Plugin.Pl.Common
import Plugin.Pl.Transform
import Plugin.Pl.Parser
import Plugin.Pl.PrettyPrinter
import Data.List ((\\))
import Data.Char (isSpace)
import Control.Monad.Error
import System.IO (hSetBuffering, stdout, BufferMode(NoBuffering))
import System.Environment (getArgs)
#ifdef READLINE
import System.Console.Readline (readline, addHistory, initialize)
#endif
import Debug.Trace
instance Arbitrary Expr where
arbitrary = sized $ \size -> frequency $ zipWith (,) [1,size,size]
[arbVar,
liftM2 Lambda arbPat arbitrary,
let se = resize (size `div` 2) arbitrary in liftM2 App se se ]
coarbitrary = error "Expr.coarbitrary"
arbVar :: Gen Expr
arbVar = oneof [(Var Pref . return) `fmap` choose ('a','z'),
(Var Inf . return) `fmap` elements (opchars\\"=")]
arbPat :: Gen Pattern
arbPat = sized $ \size ->
let
spat = resize (size `div` 5) arbPat
in
frequency $ zipWith (,) [1,size,size] [
(PVar . return) `fmap` choose ('a','z'),
liftM2 PTuple spat spat,
liftM2 PCons spat spat]
propRoundTrip :: Expr -> Bool
propRoundTrip e = Right (TLE e) == parsePF (show e)
-- hacking qc2 functionality (?) in here
propRoundTrip' :: Expr -> Property
propRoundTrip' e = not (propRoundTrip e) ==> trace (show $ findMin e) False
where
findMin e' = case filter (not . propRoundTrip) $ subExpr e' of
[] -> e'
(x:_) -> findMin x
propMonotonic1 :: Expr -> Expr -> Expr -> Bool
propMonotonic1 e e1 e2 = App e e1 `compare` App e e2 == e1 `compare` e2
propMonotonic2 :: Expr -> Expr -> Expr -> Bool
propMonotonic2 e e1 e2 = App e1 e `compare` App e2 e == e1 `compare` e2
subExpr :: Expr -> [Expr]
subExpr (Var _ _) = []
subExpr (Lambda v e) = [e] ++ Lambda v `map` subExpr e
subExpr (App e1 e2) = [e1, e2]
++ App e1 `map` subExpr e2 ++ (`App` e2) `map` subExpr e1
subExpr (Let {}) = bt
sizeTest :: IO ()
sizeTest = quickCheck $ \e -> collect (sizeExpr e) (propRoundTrip e)
quick :: Config
quick = Config
{ configMaxTest = 100
, configMaxFail = 1000
, configSize = const 40
, configEvery = \n _ -> let sh = show n in sh ++ [ '\b' | _ <- sh ]
}
myTest :: IO ()
myTest = check quick propRoundTrip'
qcTests :: IO ()
qcTests = do
quickCheck propRoundTrip
quickCheck propMonotonic1
quickCheck propMonotonic2
pf :: String -> IO ()
pf inp = case parsePF inp of
Right d -> do
putStrLn "Your expression:"
print d
putStrLn "Transformed to pointfree style:"
let d' = mapTopLevel transform d
print $ d'
putStrLn "Optimized expression:"
mapM_ print $ mapTopLevel' optimize d'
Left err -> putStrLn $ err
mapTopLevel' :: Functor f => (Expr -> f Expr) -> TopLevel -> f TopLevel
mapTopLevel' f tl = case getExpr tl of (e, c) -> fmap c $ f e
pf' :: String -> IO ()
pf' = putStrLn . (id ||| show) . parsePF
-- NB: this is a special case of (import Control.Monad.Reader)
-- ap :: m (a -> b) -> m a -> m b
s :: (t -> a -> b) -> (t -> a) -> t -> b
s f g x = f x $ g x
unitTest :: String -> [String] -> Test
unitTest inp out = TestCase $ do
d <- case parsePF inp of
Right x -> return x
Left err -> fail $ "Parse error on input " ++ inp ++ ": " ++ err
let d' = mapTopLevel (last . optimize . transform) d
foldr1 mplus [assertEqual (inp++" failed.") o (show d') | o <- out]
unitTests :: Test
unitTests = TestList [
unitTest "foldr (++) []" ["join"],
unitTest "flip flip [] . ((:) .)" ["(return .)"],
unitTest "\\x -> x - 2" ["subtract 2"],
unitTest "\\(x,_) (y,_) -> x == y" ["(. fst) . (==) . fst"],
unitTest "\\x y z -> return x >>= \\x' -> return y >>= \\y' -> return z >>= \\z' -> f x' y' z'" ["f"],
unitTest "let (x,y) = (1,2) in y" ["2"],
unitTest "fix . const" ["id"],
unitTest "all f . map g" ["all (f . g)"],
unitTest "any f . map g" ["any (f . g)"],
unitTest "liftM2 ($)" ["ap"],
unitTest "\\f -> f x" ["($ x)"],
unitTest "flip (-)" ["subtract"],
unitTest "\\xs -> [f x | x <- xs, p x]" ["map f . filter p"],
unitTest "all id" ["and"],
unitTest "any id" ["or"],
unitTest "and . map f" ["all f"],
unitTest "or . map f" ["any f"],
unitTest "return ()" ["return ()"],
unitTest "f (fix f)" ["fix f"],
unitTest "concat ([concat (map h (k a))])" ["h =<< k a"],
unitTest "uncurry (const f)" ["f . snd"],
unitTest "uncurry const" ["fst"],
unitTest "uncurry (const . f)" ["f . fst"],
unitTest "\\a b -> a >>= \\x -> b >>= \\y -> return (x,y)" ["liftM2 (,)"],
unitTest "\\b a -> a >>= \\x -> b >>= \\y -> return (x,y)" ["flip liftM2 (,)"],
unitTest "curry snd" ["const id"],
unitTest "\\x -> return x y" ["const y"],
unitTest "\\x -> f x x" ["join f"],
unitTest "join (+) 1" ["2"],
unitTest "fmap f g x" ["f (g x)"],
unitTest "liftM2 (+) f g 0" ["f 0 + g 0", "g 0 + f 0"],
unitTest "return 1 x" ["x"],
unitTest "f =<< return x" ["f x"],
unitTest "(=<<) id" ["join"],
unitTest "zipWith (,)" ["zip"],
unitTest "map fst . zip [1..]" ["zipWith const [1..]"],
unitTest "curry . uncurry" ["id"],
unitTest "uncurry . curry" ["id"],
unitTest "curry fst" ["const"],
unitTest "return x >> y" ["y"],
-- What were they smoking when they decided >> should be infixl
unitTest "a >>= \\_ -> b >>= \\_ -> return $ const (1 + 2) $ a + b" ["a >> (b >> return 3)"],
unitTest "foo = m >>= \\x -> return 1" ["foo = m >> return 1"],
unitTest "foo m = m >>= \\x -> return 1" ["foo = (>> return 1)"],
unitTest "return (+) `ap` return 1 `ap` return 2" ["return 3"],
unitTest "liftM2 (+) (return 1) (return 2)" ["return 3"],
unitTest "(. ((return .) . (+))) . (>>=)" ["flip (fmap . (+))"],
unitTest "\\a b -> a >>= \\x -> b >>= \\y -> return $ x + y" ["liftM2 (+)"],
unitTest "ap (flip const . f)" ["id"],
unitTest "uncurry (flip (const . flip (,) (snd t))) . ap (,) id" ["flip (,) (snd t)"],
unitTest "foo = (1, fst foo)" ["foo = (1, 1)"],
unitTest "foo = (snd foo, 1)" ["foo = (1, 1)"],
unitTest "map (+1) [1,2,3]" ["[2, 3, 4]"],
unitTest "snd . (,) (\\x -> x*x)" ["id"],
unitTest "return x >>= f" ["f x"],
unitTest "m >>= return" ["m"],
unitTest "m >>= \\x -> f x >>= g" ["m >>= f >>= g", "g =<< f =<< m"],
unitTest "\\x -> 1:2:3:4:x" ["([1, 2, 3, 4] ++)"],
unitTest "\\(x:xs) -> x" ["head"],
unitTest "\\(x:xs) -> xs" ["tail"],
unitTest "\\(x,y) -> x" ["fst"],
unitTest "\\(x,y) -> y" ["snd"],
unitTest "\\x -> x" ["id"],
unitTest "\\x y -> x" ["const"],
unitTest "\\f x y -> f y x" ["flip"],
unitTest "t f g x = f x (g x)" ["t = ap"],
unitTest "(+2).(+3).(+4)" ["(9 +)"],
unitTest "head $ fix (x:)" ["x"],
unitTest "head $ tail $ let xs = x:ys; ys = y:ys in xs" ["y"],
unitTest "head $ tail $ let ys = y:ys in let xs = x:ys in xs" ["y"],
unitTest "2+3*4-3*3" ["5"],
unitTest "foldr (+) x [1,2,3,4]" ["10 + x", "x + 10"],
unitTest "foldl (+) x [1,2,3,4]" ["10 + x", "x + 10"],
unitTest "head $ fst (x:xs, y:ys)" ["x"],
unitTest "snd $ (,) 2 3" ["3"],
unitTest "\\id x -> id" ["const"],
unitTest "\\y -> let f x = foo x; g = f in g y" ["foo"],
unitTest "neq x y = not $ x == y" ["neq = (/=)"],
unitTest "not (x /= y)" ["x == y"],
unitTest "\\x x -> x" ["const id"],
unitTest "\\(x, x) -> x" ["snd"],
unitTest "not $ not 4" ["4"],
unitTest "\\xs -> foldl (+) 0 (1:2:xs)" ["foldl (+) 3"],
unitTest "\\x -> foldr (+) x [0,1,2,3]" ["(6 +)"],
unitTest "foldr (+) 0 [x,y,z]" ["x + y + z"],
unitTest "foldl (*) 0 [x,y,z]" ["0"],
unitTest "length \"abcdefg\"" ["7"],
unitTest "ap (f x . fst) snd" ["uncurry (f x)"],
unitTest "sum [1,2,3,x]" ["6 + x", "x + 6"],
unitTest "p x = product [1,2,3,x]" ["p = (6 *)"],
unitTest "(concat .) . map" ["(=<<)"],
unitTest "let f ((a,b),(c,d)) = a + b + c + d in f ((1,2),(3,4))" ["10"],
unitTest "let x = const 3 y; y = const 4 x in x + y" ["7"] -- yay!
]
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
args <- getArgs
case args of
("tests":_) -> doTests
xs -> do
mapM_ pf xs
#ifdef READLINE
initialize
#endif
pfloop
pfloop :: IO ()
pfloop = do
#ifdef READLINE
line' <- readline "pointless> "
#else
line' <- Just `fmap` getLine
#endif
case line' of
Just line
| all isSpace line -> pfloop
| otherwise -> do
#ifdef READLINE
addHistory line
#endif
pf line
pfloop
Nothing -> putStrLn "Bye."
doTests :: IO ()
doTests = do
runTestTT unitTests
-- qcTests
return ()
|
jwiegley/lambdabot-1
|
Plugin/Pl/Test.hs
|
mit
| 8,625 | 0 | 17 | 2,030 | 2,631 | 1,393 | 1,238 | 207 | 2 |
{-
Copyright 2015 Markus Ongyerth, Stephan Guenther
This file is part of Monky.
Monky is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Monky is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Monky. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Monky.Version
Description : The current version of the package, this updates from monky.hs
Maintainer : ongy
Stability : testing
Portability : Linux
-}
module Monky.Version
where
import Monky.VersionTH
-- |The current version as 4tupel
getVersion :: (Int, Int, Int, Int)
getVersion = $versionTH
|
Ongy/monky
|
Monky/Version.hs
|
lgpl-3.0
| 1,097 | 0 | 5 | 228 | 38 | 25 | 13 | 5 | 1 |
module Main where
import Parser
import Tokenizer
import Data.String.Utils
import Text.Parsec
main :: IO ()
main = do
c <- getContents
case parse mainparser "(stdin)" c of
Left e -> do putStrLn "Error parsing input:"
print e
Right r -> putStrLn $ rstrip $ interpreter r 0
|
andsild/TextToNumber
|
src/Main.hs
|
unlicense
| 325 | 0 | 12 | 101 | 100 | 49 | 51 | 12 | 2 |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fr-FR">
<title>TLS Debug | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
veggiespam/zap-extensions
|
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_fr_FR/helpset_fr_FR.hs
|
apache-2.0
| 971 | 80 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
-- | Renderer that supports rendering to xmlhtml forests. This is a port of
-- the Hexpat renderer.
--
-- Warning: because this renderer doesn't directly create the output, but
-- rather an XML tree representation, it is impossible to render pre-escaped
-- text.
--
module Text.Blaze.Renderer.XmlHtml (renderHtml, renderHtmlNodes) where
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Text.Blaze.Html
import Text.Blaze.Internal
import Text.XmlHtml
-- | Render a 'ChoiceString' to Text. This is only meant to be used for
-- shorter strings, since it is inefficient for large strings.
--
fromChoiceStringText :: ChoiceString -> Text
fromChoiceStringText (Static s) = getText s
fromChoiceStringText (String s) = T.pack s
fromChoiceStringText (Text s) = s
fromChoiceStringText (ByteString s) = T.decodeUtf8 s
fromChoiceStringText (PreEscaped s) = fromChoiceStringText s
fromChoiceStringText (External s) = fromChoiceStringText s
fromChoiceStringText (AppendChoiceString x y) =
fromChoiceStringText x `T.append` fromChoiceStringText y
fromChoiceStringText EmptyChoiceString = T.empty
{-# INLINE fromChoiceStringText #-}
-- | Render a 'ChoiceString' to an appending list of nodes
--
fromChoiceString :: ChoiceString -> [Node] -> [Node]
fromChoiceString s@(Static _) = (TextNode (fromChoiceStringText s) :)
fromChoiceString s@(String _) = (TextNode (fromChoiceStringText s) :)
fromChoiceString s@(Text _) = (TextNode (fromChoiceStringText s) :)
fromChoiceString s@(ByteString _) = (TextNode (fromChoiceStringText s) :)
fromChoiceString (PreEscaped s) = fromChoiceString s
fromChoiceString (External s) = fromChoiceString s
fromChoiceString (AppendChoiceString x y) =
fromChoiceString x . fromChoiceString y
fromChoiceString EmptyChoiceString = id
{-# INLINE fromChoiceString #-}
-- | Render some 'Html' to an appending list of nodes
--
renderNodes :: Html -> [Node] -> [Node]
renderNodes = go []
where
go :: [(Text, Text)] -> MarkupM a -> [Node] -> [Node]
go attrs (Parent tag _ _ content) =
(Element (getText tag) attrs (go [] content []) :)
go attrs (CustomParent tag content) =
(Element (fromChoiceStringText tag) attrs (go [] content []) :)
go attrs (Leaf tag _ _) =
(Element (getText tag) attrs [] :)
go attrs (CustomLeaf tag _) =
(Element (fromChoiceStringText tag) attrs [] :)
go attrs (AddAttribute key _ value content) =
go ((getText key, fromChoiceStringText value) : attrs) content
go attrs (AddCustomAttribute key value content) =
go ((fromChoiceStringText key, fromChoiceStringText value) : attrs)
content
go _ (Content content) = fromChoiceString content
go attrs (Append h1 h2) = go attrs h1 . go attrs h2
go _ Empty = id
{-# NOINLINE go #-}
{-# INLINE renderNodes #-}
-- | Render HTML to an xmlhtml 'Document'
--
renderHtml :: Html -> Document
renderHtml html = HtmlDocument UTF8 Nothing (renderNodes html [])
{-# INLINE renderHtml #-}
-- | Render HTML to a list of xmlhtml nodes
--
renderHtmlNodes :: Html -> [Node]
renderHtmlNodes = flip renderNodes []
|
23Skidoo/xmlhtml
|
src/Text/Blaze/Renderer/XmlHtml.hs
|
bsd-3-clause
| 3,286 | 0 | 11 | 704 | 895 | 477 | 418 | 55 | 9 |
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "Control/Concurrent/STM/TVar.hs" #-}
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-}
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.STM.TVar
-- Copyright : (c) The University of Glasgow 2004
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (requires STM)
--
-- TVar: Transactional variables
--
-----------------------------------------------------------------------------
module Control.Concurrent.STM.TVar (
-- * TVars
TVar,
newTVar,
newTVarIO,
readTVar,
readTVarIO,
writeTVar,
modifyTVar,
modifyTVar',
swapTVar,
registerDelay,
mkWeakTVar
) where
import GHC.Base
import GHC.Conc
import GHC.Weak
-- Like 'modifyIORef' but for 'TVar'.
-- | Mutate the contents of a 'TVar'. /N.B./, this version is
-- non-strict.
modifyTVar :: TVar a -> (a -> a) -> STM ()
modifyTVar var f = do
x <- readTVar var
writeTVar var (f x)
{-# INLINE modifyTVar #-}
-- | Strict version of 'modifyTVar'.
modifyTVar' :: TVar a -> (a -> a) -> STM ()
modifyTVar' var f = do
x <- readTVar var
writeTVar var $! f x
{-# INLINE modifyTVar' #-}
-- Like 'swapTMVar' but for 'TVar'.
-- | Swap the contents of a 'TVar' for a new value.
swapTVar :: TVar a -> a -> STM a
swapTVar var new = do
old <- readTVar var
writeTVar var new
return old
{-# INLINE swapTVar #-}
-- | Make a 'Weak' pointer to a 'TVar', using the second argument as
-- a finalizer to run when 'TVar' is garbage-collected
--
-- @since 2.4.3
mkWeakTVar :: TVar a -> IO () -> IO (Weak (TVar a))
mkWeakTVar t@(TVar t#) (IO finalizer) = IO $ \s ->
case mkWeak# t# t finalizer s of (# s1, w #) -> (# s1, Weak w #)
|
phischu/fragnix
|
tests/packages/scotty/Control.Concurrent.STM.TVar.hs
|
bsd-3-clause
| 1,993 | 0 | 11 | 494 | 367 | 200 | 167 | 38 | 1 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, FlexibleInstances #-}
-- | If you are interested in the IHaskell library for the purpose of augmenting the IHaskell
-- notebook or writing your own display mechanisms and widgets, this module contains all functions
-- you need.
--
-- In order to create a display mechanism for a particular data type, write a module named (for
-- example) @IHaskell.Display.YourThing@ in a package named @ihaskell-yourThing@. (Note the
-- capitalization - it's important!) Then, in that module, add an instance of @IHaskellDisplay@ for
-- your data type. Similarly, to create a widget, add an instance of @IHaskellWidget@.
--
-- An example of creating a display is provided in the
-- <http://gibiansky.github.io/IHaskell/demo.html demo notebook>.
--
module IHaskell.Display (
-- * Rich display and interactive display typeclasses and types
IHaskellDisplay(..),
Display(..),
DisplayData(..),
IHaskellWidget(..),
-- ** Interactive use functions
printDisplay,
-- * Constructors for displays
plain,
html,
png,
jpg,
svg,
latex,
javascript,
many,
-- ** Image and data encoding functions
Width,
Height,
Base64(..),
encode64,
base64,
-- ** Utilities
switchToTmpDir,
-- * Internal only use
displayFromChanEncoded,
serializeDisplay,
Widget(..),
) where
import IHaskellPrelude
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as CBS
import Data.Serialize as Serialize
import qualified Data.ByteString.Base64 as Base64
import Data.Aeson (Value)
import System.Directory (getTemporaryDirectory, setCurrentDirectory)
import Control.Concurrent.STM (atomically)
import Control.Exception (try)
import Control.Concurrent.STM.TChan
import System.IO.Unsafe (unsafePerformIO)
import qualified Data.Text.Encoding as E
import IHaskell.Types
import IHaskell.Eval.Util (unfoldM)
import StringUtils (rstrip)
type Base64 = Text
-- | these instances cause the image, html etc. which look like:
--
-- > Display
-- > [Display]
-- > IO [Display]
-- > IO (IO Display)
--
-- be run the IO and get rendered (if the frontend allows it) in the pretty form.
instance IHaskellDisplay a => IHaskellDisplay (IO a) where
display = (display =<<)
instance IHaskellDisplay Display where
display = return
instance IHaskellDisplay DisplayData where
display disp = return $ Display [disp]
instance IHaskellDisplay a => IHaskellDisplay [a] where
display disps = do
displays <- mapM display disps
return $ ManyDisplay displays
-- | Encode many displays into a single one. All will be output.
many :: [Display] -> Display
many = ManyDisplay
-- | Generate a plain text display.
plain :: String -> DisplayData
plain = DisplayData PlainText . T.pack . rstrip
-- | Generate an HTML display.
html :: String -> DisplayData
html = DisplayData MimeHtml . T.pack
-- | Generate an SVG display.
svg :: String -> DisplayData
svg = DisplayData MimeSvg . T.pack
-- | Generate a LaTeX display.
latex :: String -> DisplayData
latex = DisplayData MimeLatex . T.pack
-- | Generate a Javascript display.
javascript :: String -> DisplayData
javascript = DisplayData MimeJavascript . T.pack
-- | Generate a PNG display of the given width and height. Data must be provided in a Base64 encoded
-- manner, suitable for embedding into HTML. The @base64@ function may be used to encode data into
-- this format.
png :: Width -> Height -> Base64 -> DisplayData
png width height = DisplayData (MimePng width height)
-- | Generate a JPG display of the given width and height. Data must be provided in a Base64 encoded
-- manner, suitable for embedding into HTML. The @base64@ function may be used to encode data into
-- this format.
jpg :: Width -> Height -> Base64 -> DisplayData
jpg width height = DisplayData (MimeJpg width height)
-- | Convert from a string into base 64 encoded data.
encode64 :: String -> Base64
encode64 str = base64 $ CBS.pack str
-- | Convert from a ByteString into base 64 encoded data.
base64 :: ByteString -> Base64
base64 = E.decodeUtf8 . Base64.encode
-- | For internal use within IHaskell. Serialize displays to a ByteString.
serializeDisplay :: Display -> ByteString
serializeDisplay = Serialize.encode
-- | Items written to this chan will be included in the output sent to the frontend (ultimately the
-- browser), the next time IHaskell has an item to display.
{-# NOINLINE displayChan #-}
displayChan :: TChan Display
displayChan = unsafePerformIO newTChanIO
-- | Take everything that was put into the 'displayChan' at that point out, and make a 'Display' out
-- of it.
displayFromChanEncoded :: IO ByteString
displayFromChanEncoded =
Serialize.encode <$> Just . many <$> unfoldM (atomically $ tryReadTChan displayChan)
-- | Write to the display channel. The contents will be displayed in the notebook once the current
-- execution call ends.
printDisplay :: IHaskellDisplay a => a -> IO ()
printDisplay disp = display disp >>= atomically . writeTChan displayChan
-- | Convenience function for client libraries. Switch to a temporary directory so that any files we
-- create aren't visible. On Unix, this is usually /tmp.
switchToTmpDir = void (try switchDir :: IO (Either SomeException ()))
where
switchDir =
getTemporaryDirectory >>=
setCurrentDirectory
|
thomasjm/IHaskell
|
src/IHaskell/Display.hs
|
mit
| 5,582 | 0 | 10 | 1,090 | 846 | 502 | 344 | 87 | 1 |
-- ----------------------------------------------------------------------------
-- | Base LLVM Code Generation module
--
-- Contains functions useful through out the code generator.
--
module LlvmCodeGen.Base (
LlvmCmmDecl, LlvmBasicBlock,
LiveGlobalRegs,
LlvmUnresData, LlvmData, UnresLabel, UnresStatic,
LlvmVersion, defaultLlvmVersion, minSupportLlvmVersion,
maxSupportLlvmVersion,
LlvmM,
runLlvm, liftStream, withClearVars, varLookup, varInsert,
markStackReg, checkStackReg,
funLookup, funInsert, getLlvmVer, getDynFlags, getDynFlag, getLlvmPlatform,
dumpIfSetLlvm, renderLlvm, runUs, markUsedVar, getUsedVars,
ghcInternalFunctions,
getMetaUniqueId,
setUniqMeta, getUniqMeta,
freshSectionId,
cmmToLlvmType, widthToLlvmFloat, widthToLlvmInt, llvmFunTy,
llvmFunSig, llvmStdFunAttrs, llvmFunAlign, llvmInfAlign,
llvmPtrBits, mkLlvmFunc, tysToParams,
strCLabel_llvm, strDisplayName_llvm, strProcedureName_llvm,
getGlobalPtr, generateAliases,
) where
#include "HsVersions.h"
import Llvm
import LlvmCodeGen.Regs
import CLabel
import CodeGen.Platform ( activeStgRegs )
import DynFlags
import FastString
import Cmm
import qualified Outputable as Outp
import qualified Pretty as Prt
import Platform
import UniqFM
import Unique
import BufWrite ( BufHandle )
import UniqSet
import UniqSupply
import ErrUtils
import qualified Stream
import Control.Monad (ap)
import Control.Applicative (Applicative(..))
-- ----------------------------------------------------------------------------
-- * Some Data Types
--
type LlvmCmmDecl = GenCmmDecl [LlvmData] (Maybe CmmStatics) (ListGraph LlvmStatement)
type LlvmBasicBlock = GenBasicBlock LlvmStatement
-- | Global registers live on proc entry
type LiveGlobalRegs = [GlobalReg]
-- | Unresolved code.
-- Of the form: (data label, data type, unresolved data)
type LlvmUnresData = (CLabel, Section, LlvmType, [UnresStatic])
-- | Top level LLVM Data (globals and type aliases)
type LlvmData = ([LMGlobal], [LlvmType])
-- | An unresolved Label.
--
-- Labels are unresolved when we haven't yet determined if they are defined in
-- the module we are currently compiling, or an external one.
type UnresLabel = CmmLit
type UnresStatic = Either UnresLabel LlvmStatic
-- ----------------------------------------------------------------------------
-- * Type translations
--
-- | Translate a basic CmmType to an LlvmType.
cmmToLlvmType :: CmmType -> LlvmType
cmmToLlvmType ty | isVecType ty = LMVector (vecLength ty) (cmmToLlvmType (vecElemType ty))
| isFloatType ty = widthToLlvmFloat $ typeWidth ty
| otherwise = widthToLlvmInt $ typeWidth ty
-- | Translate a Cmm Float Width to a LlvmType.
widthToLlvmFloat :: Width -> LlvmType
widthToLlvmFloat W32 = LMFloat
widthToLlvmFloat W64 = LMDouble
widthToLlvmFloat W80 = LMFloat80
widthToLlvmFloat W128 = LMFloat128
widthToLlvmFloat w = panic $ "widthToLlvmFloat: Bad float size: " ++ show w
-- | Translate a Cmm Bit Width to a LlvmType.
widthToLlvmInt :: Width -> LlvmType
widthToLlvmInt w = LMInt $ widthInBits w
-- | GHC Call Convention for LLVM
llvmGhcCC :: DynFlags -> LlvmCallConvention
llvmGhcCC dflags
| platformUnregisterised (targetPlatform dflags) = CC_Ccc
| otherwise = CC_Ncc 10
-- | Llvm Function type for Cmm function
llvmFunTy :: LiveGlobalRegs -> LlvmM LlvmType
llvmFunTy live = return . LMFunction =<< llvmFunSig' live (fsLit "a") ExternallyVisible
-- | Llvm Function signature
llvmFunSig :: LiveGlobalRegs -> CLabel -> LlvmLinkageType -> LlvmM LlvmFunctionDecl
llvmFunSig live lbl link = do
lbl' <- strCLabel_llvm lbl
llvmFunSig' live lbl' link
llvmFunSig' :: LiveGlobalRegs -> LMString -> LlvmLinkageType -> LlvmM LlvmFunctionDecl
llvmFunSig' live lbl link
= do let toParams x | isPointer x = (x, [NoAlias, NoCapture])
| otherwise = (x, [])
dflags <- getDynFlags
return $ LlvmFunctionDecl lbl link (llvmGhcCC dflags) LMVoid FixedArgs
(map (toParams . getVarType) (llvmFunArgs dflags live))
(llvmFunAlign dflags)
-- | Create a Haskell function in LLVM.
mkLlvmFunc :: LiveGlobalRegs -> CLabel -> LlvmLinkageType -> LMSection -> LlvmBlocks
-> LlvmM LlvmFunction
mkLlvmFunc live lbl link sec blks
= do funDec <- llvmFunSig live lbl link
dflags <- getDynFlags
let funArgs = map (fsLit . Outp.showSDoc dflags . ppPlainName) (llvmFunArgs dflags live)
return $ LlvmFunction funDec funArgs llvmStdFunAttrs sec blks
-- | Alignment to use for functions
llvmFunAlign :: DynFlags -> LMAlign
llvmFunAlign dflags = Just (wORD_SIZE dflags)
-- | Alignment to use for into tables
llvmInfAlign :: DynFlags -> LMAlign
llvmInfAlign dflags = Just (wORD_SIZE dflags)
-- | A Function's arguments
llvmFunArgs :: DynFlags -> LiveGlobalRegs -> [LlvmVar]
llvmFunArgs dflags live =
map (lmGlobalRegArg dflags) (filter isPassed (activeStgRegs platform))
where platform = targetPlatform dflags
isLive r = not (isSSE r) || r `elem` alwaysLive || r `elem` live
isPassed r = not (isSSE r) || isLive r
isSSE (FloatReg _) = True
isSSE (DoubleReg _) = True
isSSE (XmmReg _) = True
isSSE (YmmReg _) = True
isSSE (ZmmReg _) = True
isSSE _ = False
-- | Llvm standard fun attributes
llvmStdFunAttrs :: [LlvmFuncAttr]
llvmStdFunAttrs = [NoUnwind]
-- | Convert a list of types to a list of function parameters
-- (each with no parameter attributes)
tysToParams :: [LlvmType] -> [LlvmParameter]
tysToParams = map (\ty -> (ty, []))
-- | Pointer width
llvmPtrBits :: DynFlags -> Int
llvmPtrBits dflags = widthInBits $ typeWidth $ gcWord dflags
-- ----------------------------------------------------------------------------
-- * Llvm Version
--
-- | LLVM Version Number
type LlvmVersion = Int
-- | The LLVM Version we assume if we don't know
defaultLlvmVersion :: LlvmVersion
defaultLlvmVersion = 30
minSupportLlvmVersion :: LlvmVersion
minSupportLlvmVersion = 28
maxSupportLlvmVersion :: LlvmVersion
maxSupportLlvmVersion = 34
-- ----------------------------------------------------------------------------
-- * Environment Handling
--
data LlvmEnv = LlvmEnv
{ envVersion :: LlvmVersion -- ^ LLVM version
, envDynFlags :: DynFlags -- ^ Dynamic flags
, envOutput :: BufHandle -- ^ Output buffer
, envUniq :: UniqSupply -- ^ Supply of unique values
, envNextSection :: Int -- ^ Supply of fresh section IDs
, envFreshMeta :: Int -- ^ Supply of fresh metadata IDs
, envUniqMeta :: UniqFM Int -- ^ Global metadata nodes
, envFunMap :: LlvmEnvMap -- ^ Global functions so far, with type
, envAliases :: UniqSet LMString -- ^ Globals that we had to alias, see [Llvm Forward References]
, envUsedVars :: [LlvmVar] -- ^ Pointers to be added to llvm.used (see @cmmUsedLlvmGens@)
-- the following get cleared for every function (see @withClearVars@)
, envVarMap :: LlvmEnvMap -- ^ Local variables so far, with type
, envStackRegs :: [GlobalReg] -- ^ Non-constant registers (alloca'd in the function prelude)
}
type LlvmEnvMap = UniqFM LlvmType
-- | The Llvm monad. Wraps @LlvmEnv@ state as well as the @IO@ monad
newtype LlvmM a = LlvmM { runLlvmM :: LlvmEnv -> IO (a, LlvmEnv) }
instance Functor LlvmM where
fmap f m = LlvmM $ \env -> do (x, env') <- runLlvmM m env
return (f x, env')
instance Applicative LlvmM where
pure = return
(<*>) = ap
instance Monad LlvmM where
return x = LlvmM $ \env -> return (x, env)
m >>= f = LlvmM $ \env -> do (x, env') <- runLlvmM m env
runLlvmM (f x) env'
instance HasDynFlags LlvmM where
getDynFlags = LlvmM $ \env -> return (envDynFlags env, env)
-- | Lifting of IO actions. Not exported, as we want to encapsulate IO.
liftIO :: IO a -> LlvmM a
liftIO m = LlvmM $ \env -> do x <- m
return (x, env)
-- | Get initial Llvm environment.
runLlvm :: DynFlags -> LlvmVersion -> BufHandle -> UniqSupply -> LlvmM () -> IO ()
runLlvm dflags ver out us m = do
_ <- runLlvmM m env
return ()
where env = LlvmEnv { envFunMap = emptyUFM
, envVarMap = emptyUFM
, envStackRegs = []
, envUsedVars = []
, envAliases = emptyUniqSet
, envVersion = ver
, envDynFlags = dflags
, envOutput = out
, envUniq = us
, envFreshMeta = 0
, envUniqMeta = emptyUFM
, envNextSection = 1
}
-- | Get environment (internal)
getEnv :: (LlvmEnv -> a) -> LlvmM a
getEnv f = LlvmM (\env -> return (f env, env))
-- | Modify environment (internal)
modifyEnv :: (LlvmEnv -> LlvmEnv) -> LlvmM ()
modifyEnv f = LlvmM (\env -> return ((), f env))
-- | Lift a stream into the LlvmM monad
liftStream :: Stream.Stream IO a x -> Stream.Stream LlvmM a x
liftStream s = Stream.Stream $ do
r <- liftIO $ Stream.runStream s
case r of
Left b -> return (Left b)
Right (a, r2) -> return (Right (a, liftStream r2))
-- | Clear variables from the environment for a subcomputation
withClearVars :: LlvmM a -> LlvmM a
withClearVars m = LlvmM $ \env -> do
(x, env') <- runLlvmM m env { envVarMap = emptyUFM, envStackRegs = [] }
return (x, env' { envVarMap = emptyUFM, envStackRegs = [] })
-- | Insert variables or functions into the environment.
varInsert, funInsert :: Uniquable key => key -> LlvmType -> LlvmM ()
varInsert s t = modifyEnv $ \env -> env { envVarMap = addToUFM (envVarMap env) s t }
funInsert s t = modifyEnv $ \env -> env { envFunMap = addToUFM (envFunMap env) s t }
-- | Lookup variables or functions in the environment.
varLookup, funLookup :: Uniquable key => key -> LlvmM (Maybe LlvmType)
varLookup s = getEnv (flip lookupUFM s . envVarMap)
funLookup s = getEnv (flip lookupUFM s . envFunMap)
-- | Set a register as allocated on the stack
markStackReg :: GlobalReg -> LlvmM ()
markStackReg r = modifyEnv $ \env -> env { envStackRegs = r : envStackRegs env }
-- | Check whether a register is allocated on the stack
checkStackReg :: GlobalReg -> LlvmM Bool
checkStackReg r = getEnv ((elem r) . envStackRegs)
-- | Allocate a new global unnamed metadata identifier
getMetaUniqueId :: LlvmM Int
getMetaUniqueId = LlvmM $ \env -> return (envFreshMeta env, env { envFreshMeta = envFreshMeta env + 1})
-- | Get the LLVM version we are generating code for
getLlvmVer :: LlvmM LlvmVersion
getLlvmVer = getEnv envVersion
-- | Get the platform we are generating code for
getDynFlag :: (DynFlags -> a) -> LlvmM a
getDynFlag f = getEnv (f . envDynFlags)
-- | Get the platform we are generating code for
getLlvmPlatform :: LlvmM Platform
getLlvmPlatform = getDynFlag targetPlatform
-- | Dumps the document if the corresponding flag has been set by the user
dumpIfSetLlvm :: DumpFlag -> String -> Outp.SDoc -> LlvmM ()
dumpIfSetLlvm flag hdr doc = do
dflags <- getDynFlags
liftIO $ dumpIfSet_dyn dflags flag hdr doc
-- | Prints the given contents to the output handle
renderLlvm :: Outp.SDoc -> LlvmM ()
renderLlvm sdoc = do
-- Write to output
dflags <- getDynFlags
out <- getEnv envOutput
let doc = Outp.withPprStyleDoc dflags (Outp.mkCodeStyle Outp.CStyle) sdoc
liftIO $ Prt.bufLeftRender out doc
-- Dump, if requested
dumpIfSetLlvm Opt_D_dump_llvm "LLVM Code" sdoc
return ()
-- | Run a @UniqSM@ action with our unique supply
runUs :: UniqSM a -> LlvmM a
runUs m = LlvmM $ \env -> do
let (x, us') = initUs (envUniq env) m
return (x, env { envUniq = us' })
-- | Marks a variable as "used"
markUsedVar :: LlvmVar -> LlvmM ()
markUsedVar v = modifyEnv $ \env -> env { envUsedVars = v : envUsedVars env }
-- | Return all variables marked as "used" so far
getUsedVars :: LlvmM [LlvmVar]
getUsedVars = getEnv envUsedVars
-- | Saves that at some point we didn't know the type of the label and
-- generated a reference to a type variable instead
saveAlias :: LMString -> LlvmM ()
saveAlias lbl = modifyEnv $ \env -> env { envAliases = addOneToUniqSet (envAliases env) lbl }
-- | Sets metadata node for a given unique
setUniqMeta :: Unique -> Int -> LlvmM ()
setUniqMeta f m = modifyEnv $ \env -> env { envUniqMeta = addToUFM (envUniqMeta env) f m }
-- | Gets metadata node for given unique
getUniqMeta :: Unique -> LlvmM (Maybe Int)
getUniqMeta s = getEnv (flip lookupUFM s . envUniqMeta)
-- | Returns a fresh section ID
freshSectionId :: LlvmM Int
freshSectionId = LlvmM $ \env -> return (envNextSection env, env { envNextSection = envNextSection env + 1})
-- ----------------------------------------------------------------------------
-- * Internal functions
--
-- | Here we pre-initialise some functions that are used internally by GHC
-- so as to make sure they have the most general type in the case that
-- user code also uses these functions but with a different type than GHC
-- internally. (Main offender is treating return type as 'void' instead of
-- 'void *'). Fixes trac #5486.
ghcInternalFunctions :: LlvmM ()
ghcInternalFunctions = do
dflags <- getDynFlags
mk "memcpy" i8Ptr [i8Ptr, i8Ptr, llvmWord dflags]
mk "memmove" i8Ptr [i8Ptr, i8Ptr, llvmWord dflags]
mk "memset" i8Ptr [i8Ptr, llvmWord dflags, llvmWord dflags]
mk "newSpark" (llvmWord dflags) [i8Ptr, i8Ptr]
where
mk n ret args = do
let n' = fsLit n
decl = LlvmFunctionDecl n' ExternallyVisible CC_Ccc ret
FixedArgs (tysToParams args) Nothing
renderLlvm $ ppLlvmFunctionDecl decl
funInsert n' (LMFunction decl)
-- ----------------------------------------------------------------------------
-- * Label handling
--
-- | Pretty print a 'CLabel'.
strCLabel_llvm :: CLabel -> LlvmM LMString
strCLabel_llvm lbl = do
platform <- getLlvmPlatform
dflags <- getDynFlags
let sdoc = pprCLabel platform lbl
str = Outp.renderWithStyle dflags sdoc (Outp.mkCodeStyle Outp.CStyle)
return (fsLit str)
strDisplayName_llvm :: CLabel -> LlvmM LMString
strDisplayName_llvm lbl = do
platform <- getLlvmPlatform
dflags <- getDynFlags
let sdoc = pprCLabel platform lbl
depth = Outp.PartWay 1
style = Outp.mkUserStyle (\ _ _ -> Outp.NameNotInScope2, Outp.alwaysQualifyModules) depth
str = Outp.renderWithStyle dflags sdoc style
return (fsLit (dropInfoSuffix str))
dropInfoSuffix :: String -> String
dropInfoSuffix = go
where go "_info" = []
go "_static_info" = []
go "_con_info" = []
go (x:xs) = x:go xs
go [] = []
strProcedureName_llvm :: CLabel -> LlvmM LMString
strProcedureName_llvm lbl = do
platform <- getLlvmPlatform
dflags <- getDynFlags
let sdoc = pprCLabel platform lbl
depth = Outp.PartWay 1
style = Outp.mkUserStyle Outp.neverQualify depth
str = Outp.renderWithStyle dflags sdoc style
return (fsLit str)
-- ----------------------------------------------------------------------------
-- * Global variables / forward references
--
-- | Create/get a pointer to a global value. Might return an alias if
-- the value in question hasn't been defined yet. We especially make
-- no guarantees on the type of the returned pointer.
getGlobalPtr :: LMString -> LlvmM LlvmVar
getGlobalPtr llvmLbl = do
m_ty <- funLookup llvmLbl
let mkGlbVar lbl ty = LMGlobalVar lbl (LMPointer ty) Private Nothing Nothing
case m_ty of
-- Directly reference if we have seen it already
Just ty -> return $ mkGlbVar llvmLbl ty Global
-- Otherwise use a forward alias of it
Nothing -> do
saveAlias llvmLbl
return $ mkGlbVar (llvmLbl `appendFS` fsLit "$alias") i8 Alias
-- | Generate definitions for aliases forward-referenced by @getGlobalPtr@.
--
-- Must be called at a point where we are sure that no new global definitions
-- will be generated anymore!
generateAliases :: LlvmM ([LMGlobal], [LlvmType])
generateAliases = do
delayed <- fmap uniqSetToList $ getEnv envAliases
defss <- flip mapM delayed $ \lbl -> do
let var ty = LMGlobalVar lbl (LMPointer ty) External Nothing Nothing Global
aliasLbl = lbl `appendFS` fsLit "$alias"
aliasVar = LMGlobalVar aliasLbl i8Ptr Private Nothing Nothing Alias
-- If we have a definition, set the alias value using a
-- cost. Otherwise, declare it as an undefined external symbol.
m_ty <- funLookup lbl
case m_ty of
Just ty -> return [LMGlobal aliasVar $ Just $ LMBitc (LMStaticPointer (var ty)) i8Ptr]
Nothing -> return [LMGlobal (var i8) Nothing,
LMGlobal aliasVar $ Just $ LMStaticPointer (var i8) ]
-- Reset forward list
modifyEnv $ \env -> env { envAliases = emptyUniqSet }
return (concat defss, [])
-- Note [Llvm Forward References]
--
-- The issue here is that LLVM insists on being strongly typed at
-- every corner, so the first time we mention something, we have to
-- settle what type we assign to it. That makes things awkward, as Cmm
-- will often reference things before their definition, and we have no
-- idea what (LLVM) type it is going to be before that point.
--
-- Our work-around is to define "aliases" of a standard type (i8 *) in
-- these kind of situations, which we later tell LLVM to be either
-- references to their actual local definitions (involving a cast) or
-- an external reference. This obviously only works for pointers.
-- ----------------------------------------------------------------------------
-- * Misc
--
-- | Error function
panic :: String -> a
panic s = Outp.panic $ "LlvmCodeGen.Base." ++ s
|
jwiegley/ghc-release
|
compiler/llvmGen/LlvmCodeGen/Base.hs
|
gpl-3.0
| 18,056 | 0 | 22 | 4,132 | 4,151 | 2,207 | 1,944 | 288 | 6 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Client.Init
-- Copyright : (c) Brent Yorgey 2009
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Implementation of the 'cabal init' command, which creates an initial .cabal
-- file for a project.
--
-----------------------------------------------------------------------------
module Distribution.Client.Init (
-- * Commands
initCabal
, pvpize
, incVersion
) where
import System.IO
( hSetBuffering, stdout, BufferMode(..) )
import System.Directory
( getCurrentDirectory, doesDirectoryExist, doesFileExist, copyFile
, getDirectoryContents, createDirectoryIfMissing )
import System.FilePath
( (</>), (<.>), takeBaseName )
import Data.Time
( getCurrentTime, utcToLocalTime, toGregorian, localDay, getCurrentTimeZone )
import Data.Char
( toUpper )
import Data.List
( intercalate, nub, groupBy, (\\) )
import Data.Maybe
( fromMaybe, isJust, catMaybes, listToMaybe )
import Data.Function
( on )
import qualified Data.Map as M
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
( (<$>) )
import Data.Traversable
( traverse )
#endif
import Control.Monad
( when, unless, (>=>), join, forM_ )
import Control.Arrow
( (&&&), (***) )
import Text.PrettyPrint hiding (mode, cat)
import Data.Version
( Version(..) )
import Distribution.Version
( orLaterVersion, earlierVersion, intersectVersionRanges, VersionRange )
import Distribution.Verbosity
( Verbosity )
import Distribution.ModuleName
( ModuleName, fromString ) -- And for the Text instance
import Distribution.InstalledPackageInfo
( InstalledPackageInfo, sourcePackageId, exposed )
import qualified Distribution.Package as P
import Language.Haskell.Extension ( Language(..) )
import Distribution.Client.Init.Types
( InitFlags(..), PackageType(..), Category(..) )
import Distribution.Client.Init.Licenses
( bsd2, bsd3, gplv2, gplv3, lgpl21, lgpl3, agplv3, apache20, mit, mpl20, isc )
import Distribution.Client.Init.Heuristics
( guessPackageName, guessAuthorNameMail, guessMainFileCandidates,
SourceFileEntry(..),
scanForModules, neededBuildPrograms )
import Distribution.License
( License(..), knownLicenses )
import Distribution.ReadE
( runReadE, readP_to_E )
import Distribution.Simple.Setup
( Flag(..), flagToMaybe )
import Distribution.Simple.Configure
( getInstalledPackages )
import Distribution.Simple.Compiler
( PackageDBStack, Compiler )
import Distribution.Simple.Program
( ProgramConfiguration )
import Distribution.Simple.PackageIndex
( InstalledPackageIndex, moduleNameIndex )
import Distribution.Text
( display, Text(..) )
import Distribution.Client.PackageIndex
( elemByPackageName )
import Distribution.Client.IndexUtils
( getSourcePackages )
import Distribution.Client.Types
( SourcePackageDb(..) )
import Distribution.Client.Setup
( RepoContext(..) )
initCabal :: Verbosity
-> PackageDBStack
-> RepoContext
-> Compiler
-> ProgramConfiguration
-> InitFlags
-> IO ()
initCabal verbosity packageDBs repoCtxt comp conf initFlags = do
installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf
sourcePkgDb <- getSourcePackages verbosity repoCtxt
hSetBuffering stdout NoBuffering
initFlags' <- extendFlags installedPkgIndex sourcePkgDb initFlags
case license initFlags' of
Flag PublicDomain -> return ()
_ -> writeLicense initFlags'
writeSetupFile initFlags'
writeChangeLog initFlags'
createSourceDirectories initFlags'
createMainHs initFlags'
success <- writeCabalFile initFlags'
when success $ generateWarnings initFlags'
---------------------------------------------------------------------------
-- Flag acquisition -----------------------------------------------------
---------------------------------------------------------------------------
-- | Fill in more details by guessing, discovering, or prompting the
-- user.
extendFlags :: InstalledPackageIndex -> SourcePackageDb -> InitFlags -> IO InitFlags
extendFlags pkgIx sourcePkgDb =
getPackageName sourcePkgDb
>=> getVersion
>=> getLicense
>=> getAuthorInfo
>=> getHomepage
>=> getSynopsis
>=> getCategory
>=> getExtraSourceFiles
>=> getLibOrExec
>=> getSrcDir
>=> getLanguage
>=> getGenComments
>=> getModulesBuildToolsAndDeps pkgIx
-- | Combine two actions which may return a value, preferring the first. That
-- is, run the second action only if the first doesn't return a value.
infixr 1 ?>>
(?>>) :: IO (Maybe a) -> IO (Maybe a) -> IO (Maybe a)
f ?>> g = do
ma <- f
if isJust ma
then return ma
else g
-- | Witness the isomorphism between Maybe and Flag.
maybeToFlag :: Maybe a -> Flag a
maybeToFlag = maybe NoFlag Flag
-- | Get the package name: use the package directory (supplied, or the current
-- directory by default) as a guess. It looks at the SourcePackageDb to avoid
-- using an existing package name.
getPackageName :: SourcePackageDb -> InitFlags -> IO InitFlags
getPackageName sourcePkgDb flags = do
guess <- traverse guessPackageName (flagToMaybe $ packageDir flags)
?>> Just `fmap` (getCurrentDirectory >>= guessPackageName)
let guess' | isPkgRegistered guess = Nothing
| otherwise = guess
pkgName' <- return (flagToMaybe $ packageName flags)
?>> maybePrompt flags (prompt "Package name" guess')
?>> return guess'
chooseAgain <- if isPkgRegistered pkgName'
then promptYesNo promptOtherNameMsg (Just True)
else return False
if chooseAgain
then getPackageName sourcePkgDb flags
else return $ flags { packageName = maybeToFlag pkgName' }
where
isPkgRegistered (Just pkg) = elemByPackageName (packageIndex sourcePkgDb) pkg
isPkgRegistered Nothing = False
promptOtherNameMsg = "This package name is already used by another " ++
"package on hackage. Do you want to choose a " ++
"different name"
-- | Package version: use 0.1.0.0 as a last resort, but try prompting the user
-- if possible.
getVersion :: InitFlags -> IO InitFlags
getVersion flags = do
let v = Just $ Version [0,1,0,0] []
v' <- return (flagToMaybe $ version flags)
?>> maybePrompt flags (prompt "Package version" v)
?>> return v
return $ flags { version = maybeToFlag v' }
-- | Choose a license.
getLicense :: InitFlags -> IO InitFlags
getLicense flags = do
lic <- return (flagToMaybe $ license flags)
?>> fmap (fmap (either UnknownLicense id))
(maybePrompt flags
(promptList "Please choose a license" listedLicenses (Just BSD3) display True))
return $ flags { license = maybeToFlag lic }
where
listedLicenses =
knownLicenses \\ [GPL Nothing, LGPL Nothing, AGPL Nothing
, Apache Nothing, OtherLicense]
-- | The author's name and email. Prompt, or try to guess from an existing
-- darcs repo.
getAuthorInfo :: InitFlags -> IO InitFlags
getAuthorInfo flags = do
(authorName, authorEmail) <-
(flagToMaybe *** flagToMaybe) `fmap` guessAuthorNameMail
authorName' <- return (flagToMaybe $ author flags)
?>> maybePrompt flags (promptStr "Author name" authorName)
?>> return authorName
authorEmail' <- return (flagToMaybe $ email flags)
?>> maybePrompt flags (promptStr "Maintainer email" authorEmail)
?>> return authorEmail
return $ flags { author = maybeToFlag authorName'
, email = maybeToFlag authorEmail'
}
-- | Prompt for a homepage URL.
getHomepage :: InitFlags -> IO InitFlags
getHomepage flags = do
hp <- queryHomepage
hp' <- return (flagToMaybe $ homepage flags)
?>> maybePrompt flags (promptStr "Project homepage URL" hp)
?>> return hp
return $ flags { homepage = maybeToFlag hp' }
-- | Right now this does nothing, but it could be changed to do some
-- intelligent guessing.
queryHomepage :: IO (Maybe String)
queryHomepage = return Nothing -- get default remote darcs repo?
-- | Prompt for a project synopsis.
getSynopsis :: InitFlags -> IO InitFlags
getSynopsis flags = do
syn <- return (flagToMaybe $ synopsis flags)
?>> maybePrompt flags (promptStr "Project synopsis" Nothing)
return $ flags { synopsis = maybeToFlag syn }
-- | Prompt for a package category.
-- Note that it should be possible to do some smarter guessing here too, i.e.
-- look at the name of the top level source directory.
getCategory :: InitFlags -> IO InitFlags
getCategory flags = do
cat <- return (flagToMaybe $ category flags)
?>> fmap join (maybePrompt flags
(promptListOptional "Project category" [Codec ..]))
return $ flags { category = maybeToFlag cat }
-- | Try to guess extra source files (don't prompt the user).
getExtraSourceFiles :: InitFlags -> IO InitFlags
getExtraSourceFiles flags = do
extraSrcFiles <- return (extraSrc flags)
?>> Just `fmap` guessExtraSourceFiles flags
return $ flags { extraSrc = extraSrcFiles }
defaultChangeLog :: FilePath
defaultChangeLog = "ChangeLog.md"
-- | Try to guess things to include in the extra-source-files field.
-- For now, we just look for things in the root directory named
-- 'readme', 'changes', or 'changelog', with any sort of
-- capitalization and any extension.
guessExtraSourceFiles :: InitFlags -> IO [FilePath]
guessExtraSourceFiles flags = do
dir <-
maybe getCurrentDirectory return . flagToMaybe $ packageDir flags
files <- getDirectoryContents dir
let extraFiles = filter isExtra files
if any isLikeChangeLog extraFiles
then return extraFiles
else return (defaultChangeLog : extraFiles)
where
isExtra = likeFileNameBase ("README" : changeLogLikeBases)
isLikeChangeLog = likeFileNameBase changeLogLikeBases
likeFileNameBase candidates = (`elem` candidates) . map toUpper . takeBaseName
changeLogLikeBases = ["CHANGES", "CHANGELOG"]
-- | Ask whether the project builds a library or executable.
getLibOrExec :: InitFlags -> IO InitFlags
getLibOrExec flags = do
isLib <- return (flagToMaybe $ packageType flags)
?>> maybePrompt flags (either (const Library) id `fmap`
promptList "What does the package build"
[Library, Executable]
Nothing display False)
?>> return (Just Library)
mainFile <- if isLib /= Just Executable then return Nothing else
getMainFile flags
return $ flags { packageType = maybeToFlag isLib
, mainIs = maybeToFlag mainFile
}
-- | Try to guess the main file of the executable, and prompt the user to choose
-- one of them. Top-level modules including the word 'Main' in the file name
-- will be candidates, and shorter filenames will be preferred.
getMainFile :: InitFlags -> IO (Maybe FilePath)
getMainFile flags =
return (flagToMaybe $ mainIs flags)
?>> do
candidates <- guessMainFileCandidates flags
let showCandidate = either (++" (does not yet exist, but will be created)") id
defaultFile = listToMaybe candidates
maybePrompt flags (either id (either id id) `fmap`
promptList "What is the main module of the executable"
candidates
defaultFile showCandidate True)
?>> return (fmap (either id id) defaultFile)
-- | Ask for the base language of the package.
getLanguage :: InitFlags -> IO InitFlags
getLanguage flags = do
lang <- return (flagToMaybe $ language flags)
?>> maybePrompt flags
(either UnknownLanguage id `fmap`
promptList "What base language is the package written in"
[Haskell2010, Haskell98]
(Just Haskell2010) display True)
?>> return (Just Haskell2010)
return $ flags { language = maybeToFlag lang }
-- | Ask whether to generate explanatory comments.
getGenComments :: InitFlags -> IO InitFlags
getGenComments flags = do
genComments <- return (not <$> flagToMaybe (noComments flags))
?>> maybePrompt flags (promptYesNo promptMsg (Just False))
?>> return (Just False)
return $ flags { noComments = maybeToFlag (fmap not genComments) }
where
promptMsg = "Add informative comments to each field in the cabal file (y/n)"
-- | Ask for the source root directory.
getSrcDir :: InitFlags -> IO InitFlags
getSrcDir flags = do
srcDirs <- return (sourceDirs flags)
?>> fmap (:[]) `fmap` guessSourceDir flags
?>> fmap (>>= fmap ((:[]) . either id id)) (maybePrompt
flags
(promptListOptional' "Source directory" ["src"] id))
return $ flags { sourceDirs = srcDirs }
-- | Try to guess source directory. Could try harder; for the
-- moment just looks to see whether there is a directory called 'src'.
guessSourceDir :: InitFlags -> IO (Maybe String)
guessSourceDir flags = do
dir <-
maybe getCurrentDirectory return . flagToMaybe $ packageDir flags
srcIsDir <- doesDirectoryExist (dir </> "src")
return $ if srcIsDir
then Just "src"
else Nothing
-- | Get the list of exposed modules and extra tools needed to build them.
getModulesBuildToolsAndDeps :: InstalledPackageIndex -> InitFlags -> IO InitFlags
getModulesBuildToolsAndDeps pkgIx flags = do
dir <- maybe getCurrentDirectory return . flagToMaybe $ packageDir flags
-- TODO: really should use guessed source roots.
sourceFiles <- scanForModules dir
Just mods <- return (exposedModules flags)
?>> (return . Just . map moduleName $ sourceFiles)
tools <- return (buildTools flags)
?>> (return . Just . neededBuildPrograms $ sourceFiles)
deps <- return (dependencies flags)
?>> Just <$> importsToDeps flags
(fromString "Prelude" : -- to ensure we get base as a dep
( nub -- only need to consider each imported package once
. filter (`notElem` mods) -- don't consider modules from
-- this package itself
. concatMap imports
$ sourceFiles
)
)
pkgIx
exts <- return (otherExts flags)
?>> (return . Just . nub . concatMap extensions $ sourceFiles)
return $ flags { exposedModules = Just mods
, buildTools = tools
, dependencies = deps
, otherExts = exts
}
importsToDeps :: InitFlags -> [ModuleName] -> InstalledPackageIndex -> IO [P.Dependency]
importsToDeps flags mods pkgIx = do
let modMap :: M.Map ModuleName [InstalledPackageInfo]
modMap = M.map (filter exposed) $ moduleNameIndex pkgIx
modDeps :: [(ModuleName, Maybe [InstalledPackageInfo])]
modDeps = map (id &&& flip M.lookup modMap) mods
message flags "\nGuessing dependencies..."
nub . catMaybes <$> mapM (chooseDep flags) modDeps
-- Given a module and a list of installed packages providing it,
-- choose a dependency (i.e. package + version range) to use for that
-- module.
chooseDep :: InitFlags -> (ModuleName, Maybe [InstalledPackageInfo])
-> IO (Maybe P.Dependency)
chooseDep flags (m, Nothing)
= message flags ("\nWarning: no package found providing " ++ display m ++ ".")
>> return Nothing
chooseDep flags (m, Just [])
= message flags ("\nWarning: no package found providing " ++ display m ++ ".")
>> return Nothing
-- We found some packages: group them by name.
chooseDep flags (m, Just ps)
= case pkgGroups of
-- if there's only one group, i.e. multiple versions of a single package,
-- we make it into a dependency, choosing the latest-ish version (see toDep).
[grp] -> Just <$> toDep grp
-- otherwise, we refuse to choose between different packages and make the user
-- do it.
grps -> do message flags ("\nWarning: multiple packages found providing "
++ display m
++ ": " ++ intercalate ", " (map (display . P.pkgName . head) grps))
message flags "You will need to pick one and manually add it to the Build-depends: field."
return Nothing
where
pkgGroups = groupBy ((==) `on` P.pkgName) (map sourcePackageId ps)
-- Given a list of available versions of the same package, pick a dependency.
toDep :: [P.PackageIdentifier] -> IO P.Dependency
-- If only one version, easy. We change e.g. 0.4.2 into 0.4.*
toDep [pid] = return $ P.Dependency (P.pkgName pid) (pvpize . P.pkgVersion $ pid)
-- Otherwise, choose the latest version and issue a warning.
toDep pids = do
message flags ("\nWarning: multiple versions of " ++ display (P.pkgName . head $ pids) ++ " provide " ++ display m ++ ", choosing the latest.")
return $ P.Dependency (P.pkgName . head $ pids)
(pvpize . maximum . map P.pkgVersion $ pids)
-- | Given a version, return an API-compatible (according to PVP) version range.
--
-- Example: @0.4.1@ produces the version range @>= 0.4 && < 0.5@ (which is the
-- same as @0.4.*@).
pvpize :: Version -> VersionRange
pvpize v = orLaterVersion v'
`intersectVersionRanges`
earlierVersion (incVersion 1 v')
where v' = (v { versionBranch = take 2 (versionBranch v) })
-- | Increment the nth version component (counting from 0).
incVersion :: Int -> Version -> Version
incVersion n (Version vlist tags) = Version (incVersion' n vlist) tags
where
incVersion' 0 [] = [1]
incVersion' 0 (v:_) = [v+1]
incVersion' m [] = replicate m 0 ++ [1]
incVersion' m (v:vs) = v : incVersion' (m-1) vs
---------------------------------------------------------------------------
-- Prompting/user interaction -------------------------------------------
---------------------------------------------------------------------------
-- | Run a prompt or not based on the nonInteractive flag of the
-- InitFlags structure.
maybePrompt :: InitFlags -> IO t -> IO (Maybe t)
maybePrompt flags p =
case nonInteractive flags of
Flag True -> return Nothing
_ -> Just `fmap` p
-- | Create a prompt with optional default value that returns a
-- String.
promptStr :: String -> Maybe String -> IO String
promptStr = promptDefault' Just id
-- | Create a yes/no prompt with optional default value.
--
promptYesNo :: String -> Maybe Bool -> IO Bool
promptYesNo =
promptDefault' recogniseYesNo showYesNo
where
recogniseYesNo s | s == "y" || s == "Y" = Just True
| s == "n" || s == "N" = Just False
| otherwise = Nothing
showYesNo True = "y"
showYesNo False = "n"
-- | Create a prompt with optional default value that returns a value
-- of some Text instance.
prompt :: Text t => String -> Maybe t -> IO t
prompt = promptDefault'
(either (const Nothing) Just . runReadE (readP_to_E id parse))
display
-- | Create a prompt with an optional default value.
promptDefault' :: (String -> Maybe t) -- ^ parser
-> (t -> String) -- ^ pretty-printer
-> String -- ^ prompt message
-> Maybe t -- ^ optional default value
-> IO t
promptDefault' parser pretty pr def = do
putStr $ mkDefPrompt pr (pretty `fmap` def)
inp <- getLine
case (inp, def) of
("", Just d) -> return d
_ -> case parser inp of
Just t -> return t
Nothing -> do putStrLn $ "Couldn't parse " ++ inp ++ ", please try again!"
promptDefault' parser pretty pr def
-- | Create a prompt from a prompt string and a String representation
-- of an optional default value.
mkDefPrompt :: String -> Maybe String -> String
mkDefPrompt pr def = pr ++ "?" ++ defStr def
where defStr Nothing = " "
defStr (Just s) = " [default: " ++ s ++ "] "
promptListOptional :: (Text t, Eq t)
=> String -- ^ prompt
-> [t] -- ^ choices
-> IO (Maybe (Either String t))
promptListOptional pr choices = promptListOptional' pr choices display
promptListOptional' :: Eq t
=> String -- ^ prompt
-> [t] -- ^ choices
-> (t -> String) -- ^ show an item
-> IO (Maybe (Either String t))
promptListOptional' pr choices displayItem =
fmap rearrange
$ promptList pr (Nothing : map Just choices) (Just Nothing)
(maybe "(none)" displayItem) True
where
rearrange = either (Just . Left) (fmap Right)
-- | Create a prompt from a list of items.
promptList :: Eq t
=> String -- ^ prompt
-> [t] -- ^ choices
-> Maybe t -- ^ optional default value
-> (t -> String) -- ^ show an item
-> Bool -- ^ whether to allow an 'other' option
-> IO (Either String t)
promptList pr choices def displayItem other = do
putStrLn $ pr ++ ":"
let options1 = map (\c -> (Just c == def, displayItem c)) choices
options2 = zip ([1..]::[Int])
(options1 ++ [(False, "Other (specify)") | other])
mapM_ (putStrLn . \(n,(i,s)) -> showOption n i ++ s) options2
promptList' displayItem (length options2) choices def other
where showOption n i | n < 10 = " " ++ star i ++ " " ++ rest
| otherwise = " " ++ star i ++ rest
where rest = show n ++ ") "
star True = "*"
star False = " "
promptList' :: (t -> String) -> Int -> [t] -> Maybe t -> Bool -> IO (Either String t)
promptList' displayItem numChoices choices def other = do
putStr $ mkDefPrompt "Your choice" (displayItem `fmap` def)
inp <- getLine
case (inp, def) of
("", Just d) -> return $ Right d
_ -> case readMaybe inp of
Nothing -> invalidChoice inp
Just n -> getChoice n
where invalidChoice inp = do putStrLn $ inp ++ " is not a valid choice."
promptList' displayItem numChoices choices def other
getChoice n | n < 1 || n > numChoices = invalidChoice (show n)
| n < numChoices ||
(n == numChoices && not other)
= return . Right $ choices !! (n-1)
| otherwise = Left `fmap` promptStr "Please specify" Nothing
readMaybe :: (Read a) => String -> Maybe a
readMaybe s = case reads s of
[(a,"")] -> Just a
_ -> Nothing
---------------------------------------------------------------------------
-- File generation ------------------------------------------------------
---------------------------------------------------------------------------
writeLicense :: InitFlags -> IO ()
writeLicense flags = do
message flags "\nGenerating LICENSE..."
year <- show <$> getYear
let authors = fromMaybe "???" . flagToMaybe . author $ flags
let licenseFile =
case license flags of
Flag BSD2
-> Just $ bsd2 authors year
Flag BSD3
-> Just $ bsd3 authors year
Flag (GPL (Just (Version {versionBranch = [2]})))
-> Just gplv2
Flag (GPL (Just (Version {versionBranch = [3]})))
-> Just gplv3
Flag (LGPL (Just (Version {versionBranch = [2, 1]})))
-> Just lgpl21
Flag (LGPL (Just (Version {versionBranch = [3]})))
-> Just lgpl3
Flag (AGPL (Just (Version {versionBranch = [3]})))
-> Just agplv3
Flag (Apache (Just (Version {versionBranch = [2, 0]})))
-> Just apache20
Flag MIT
-> Just $ mit authors year
Flag (MPL (Version {versionBranch = [2, 0]}))
-> Just mpl20
Flag ISC
-> Just $ isc authors year
_ -> Nothing
case licenseFile of
Just licenseText -> writeFileSafe flags "LICENSE" licenseText
Nothing -> message flags "Warning: unknown license type, you must put a copy in LICENSE yourself."
getYear :: IO Integer
getYear = do
u <- getCurrentTime
z <- getCurrentTimeZone
let l = utcToLocalTime z u
(y, _, _) = toGregorian $ localDay l
return y
writeSetupFile :: InitFlags -> IO ()
writeSetupFile flags = do
message flags "Generating Setup.hs..."
writeFileSafe flags "Setup.hs" setupFile
where
setupFile = unlines
[ "import Distribution.Simple"
, "main = defaultMain"
]
writeChangeLog :: InitFlags -> IO ()
writeChangeLog flags = when (any (== defaultChangeLog) $ maybe [] id (extraSrc flags)) $ do
message flags ("Generating "++ defaultChangeLog ++"...")
writeFileSafe flags defaultChangeLog changeLog
where
changeLog = unlines
[ "# Revision history for " ++ pname
, ""
, "## " ++ pver ++ " -- YYYY-mm-dd"
, ""
, "* First version. Released on an unsuspecting world."
]
pname = maybe "" display $ flagToMaybe $ packageName flags
pver = maybe "" display $ flagToMaybe $ version flags
writeCabalFile :: InitFlags -> IO Bool
writeCabalFile flags@(InitFlags{packageName = NoFlag}) = do
message flags "Error: no package name provided."
return False
writeCabalFile flags@(InitFlags{packageName = Flag p}) = do
let cabalFileName = display p ++ ".cabal"
message flags $ "Generating " ++ cabalFileName ++ "..."
writeFileSafe flags cabalFileName (generateCabalFile cabalFileName flags)
return True
-- | Write a file \"safely\", backing up any existing version (unless
-- the overwrite flag is set).
writeFileSafe :: InitFlags -> FilePath -> String -> IO ()
writeFileSafe flags fileName content = do
moveExistingFile flags fileName
writeFile fileName content
-- | Create source directories, if they were given.
createSourceDirectories :: InitFlags -> IO ()
createSourceDirectories flags = case sourceDirs flags of
Just dirs -> forM_ dirs (createDirectoryIfMissing True)
Nothing -> return ()
-- | Create Main.hs, but only if we are init'ing an executable and
-- the mainIs flag has been provided.
createMainHs :: InitFlags -> IO ()
createMainHs flags@InitFlags{ sourceDirs = Just (srcPath:_)
, packageType = Flag Executable
, mainIs = Flag mainFile } =
writeMainHs flags (srcPath </> mainFile)
createMainHs flags@InitFlags{ sourceDirs = _
, packageType = Flag Executable
, mainIs = Flag mainFile } =
writeMainHs flags mainFile
createMainHs _ = return ()
-- | Write a main file if it doesn't already exist.
writeMainHs :: InitFlags -> FilePath -> IO ()
writeMainHs flags mainPath = do
dir <- maybe getCurrentDirectory return (flagToMaybe $ packageDir flags)
let mainFullPath = dir </> mainPath
exists <- doesFileExist mainFullPath
unless exists $ do
message flags $ "Generating " ++ mainPath ++ "..."
writeFileSafe flags mainFullPath mainHs
-- | Default Main.hs file. Used when no Main.hs exists.
mainHs :: String
mainHs = unlines
[ "module Main where"
, ""
, "main :: IO ()"
, "main = putStrLn \"Hello, Haskell!\""
]
-- | Move an existing file, if there is one, and the overwrite flag is
-- not set.
moveExistingFile :: InitFlags -> FilePath -> IO ()
moveExistingFile flags fileName =
unless (overwrite flags == Flag True) $ do
e <- doesFileExist fileName
when e $ do
newName <- findNewName fileName
message flags $ "Warning: " ++ fileName ++ " already exists, backing up old version in " ++ newName
copyFile fileName newName
findNewName :: FilePath -> IO FilePath
findNewName oldName = findNewName' 0
where
findNewName' :: Integer -> IO FilePath
findNewName' n = do
let newName = oldName <.> ("save" ++ show n)
e <- doesFileExist newName
if e then findNewName' (n+1) else return newName
-- | Generate a .cabal file from an InitFlags structure. NOTE: this
-- is rather ad-hoc! What we would REALLY like is to have a
-- standard low-level AST type representing .cabal files, which
-- preserves things like comments, and to write an *inverse*
-- parser/pretty-printer pair between .cabal files and this AST.
-- Then instead of this ad-hoc code we could just map an InitFlags
-- structure onto a low-level AST structure and use the existing
-- pretty-printing code to generate the file.
generateCabalFile :: String -> InitFlags -> String
generateCabalFile fileName c =
(++ "\n") .
renderStyle style { lineLength = 79, ribbonsPerLine = 1.1 } $
(if minimal c /= Flag True
then showComment (Just $ "Initial " ++ fileName ++ " generated by cabal "
++ "init. For further documentation, see "
++ "http://haskell.org/cabal/users-guide/")
$$ text ""
else empty)
$$
vcat [ field "name" (packageName c)
(Just "The name of the package.")
True
, field "version" (version c)
(Just $ "The package version. See the Haskell package versioning policy (PVP) for standards guiding when and how versions should be incremented.\nhttps://wiki.haskell.org/Package_versioning_policy\n"
++ "PVP summary: +-+------- breaking API changes\n"
++ " | | +----- non-breaking API additions\n"
++ " | | | +--- code changes with no API change")
True
, fieldS "synopsis" (synopsis c)
(Just "A short (one-line) description of the package.")
True
, fieldS "description" NoFlag
(Just "A longer description of the package.")
True
, fieldS "homepage" (homepage c)
(Just "URL for the project homepage or repository.")
False
, fieldS "bug-reports" NoFlag
(Just "A URL where users can report bugs.")
False
, field "license" (license c)
(Just "The license under which the package is released.")
True
, case (license c) of
Flag PublicDomain -> empty
_ -> fieldS "license-file" (Flag "LICENSE")
(Just "The file containing the license text.")
True
, fieldS "author" (author c)
(Just "The package author(s).")
True
, fieldS "maintainer" (email c)
(Just "An email address to which users can send suggestions, bug reports, and patches.")
True
, case (license c) of
Flag PublicDomain -> empty
_ -> fieldS "copyright" NoFlag
(Just "A copyright notice.")
True
, fieldS "category" (either id display `fmap` category c)
Nothing
True
, fieldS "build-type" (Flag "Simple")
Nothing
True
, fieldS "extra-source-files" (listFieldS (extraSrc c))
(Just "Extra files to be distributed with the package, such as examples or a README.")
True
, field "cabal-version" (Flag $ orLaterVersion (Version [1,10] []))
(Just "Constraint on the version of Cabal needed to build this package.")
False
, case packageType c of
Flag Executable ->
text "\nexecutable" <+>
text (maybe "" display . flagToMaybe $ packageName c) $$
nest 2 (vcat
[ fieldS "main-is" (mainIs c) (Just ".hs or .lhs file containing the Main module.") True
, generateBuildInfo Executable c
])
Flag Library -> text "\nlibrary" $$ nest 2 (vcat
[ fieldS "exposed-modules" (listField (exposedModules c))
(Just "Modules exported by the library.")
True
, generateBuildInfo Library c
])
_ -> empty
]
where
generateBuildInfo :: PackageType -> InitFlags -> Doc
generateBuildInfo pkgtype c' = vcat
[ fieldS "other-modules" (listField (otherModules c'))
(Just $ case pkgtype of
Library -> "Modules included in this library but not exported."
Executable -> "Modules included in this executable, other than Main.")
True
, fieldS "other-extensions" (listField (otherExts c'))
(Just "LANGUAGE extensions used by modules in this package.")
True
, fieldS "build-depends" (listField (dependencies c'))
(Just "Other library packages from which modules are imported.")
True
, fieldS "hs-source-dirs" (listFieldS (sourceDirs c'))
(Just "Directories containing source files.")
True
, fieldS "build-tools" (listFieldS (buildTools c'))
(Just "Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.")
False
, field "default-language" (language c')
(Just "Base language which the package is written in.")
True
]
listField :: Text s => Maybe [s] -> Flag String
listField = listFieldS . fmap (map display)
listFieldS :: Maybe [String] -> Flag String
listFieldS = Flag . maybe "" (intercalate ", ")
field :: Text t => String -> Flag t -> Maybe String -> Bool -> Doc
field s f = fieldS s (fmap display f)
fieldS :: String -- ^ Name of the field
-> Flag String -- ^ Field contents
-> Maybe String -- ^ Comment to explain the field
-> Bool -- ^ Should the field be included (commented out) even if blank?
-> Doc
fieldS _ NoFlag _ inc | not inc || (minimal c == Flag True) = empty
fieldS _ (Flag "") _ inc | not inc || (minimal c == Flag True) = empty
fieldS s f com _ = case (isJust com, noComments c, minimal c) of
(_, _, Flag True) -> id
(_, Flag True, _) -> id
(True, _, _) -> (showComment com $$) . ($$ text "")
(False, _, _) -> ($$ text "")
$
comment f <> text s <> colon
<> text (replicate (20 - length s) ' ')
<> text (fromMaybe "" . flagToMaybe $ f)
comment NoFlag = text "-- "
comment (Flag "") = text "-- "
comment _ = text ""
showComment :: Maybe String -> Doc
showComment (Just t) = vcat
. map (text . ("-- "++)) . lines
. renderStyle style {
lineLength = 76,
ribbonsPerLine = 1.05
}
. vcat
. map (fcat . map text . breakLine)
. lines
$ t
showComment Nothing = text ""
breakLine [] = []
breakLine cs = case break (==' ') cs of (w,cs') -> w : breakLine' cs'
breakLine' [] = []
breakLine' cs = case span (==' ') cs of (w,cs') -> w : breakLine cs'
-- | Generate warnings for missing fields etc.
generateWarnings :: InitFlags -> IO ()
generateWarnings flags = do
message flags ""
when (synopsis flags `elem` [NoFlag, Flag ""])
(message flags "Warning: no synopsis given. You should edit the .cabal file and add one.")
message flags "You may want to edit the .cabal file and add a Description field."
-- | Possibly generate a message to stdout, taking into account the
-- --quiet flag.
message :: InitFlags -> String -> IO ()
message (InitFlags{quiet = Flag True}) _ = return ()
message _ s = putStrLn s
|
tolysz/prepare-ghcjs
|
spec-lts8/cabal/cabal-install/Distribution/Client/Init.hs
|
bsd-3-clause
| 36,774 | 0 | 22 | 10,729 | 8,743 | 4,469 | 4,274 | 684 | 17 |
{- |
Module : $Id$
Description : hybrid logic extension of CASL
Stability : experimental
This folder contains the files for HybridCASL basic specs
* "Hybrid.AS_Hybrid" abstract syntax
* "Hybrid.Parse_AS" parser
* "Hybrid.HybridSign" signatures
* "Hybrid.ATC_Hybrid"
* "Hybrid.Logic_Hybrid" the HybridCASL instance of type class 'Logic.Logic.Logic'
* "Hybrid.StatAna.hs"
-}
module Hybrid where
|
keithodulaigh/Hets
|
Hybrid.hs
|
gpl-2.0
| 453 | 0 | 2 | 111 | 5 | 4 | 1 | 1 | 0 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>Directory List v2.3</title>
<maps>
<homeID>directorylistv2_3</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/directorylistv2_3/src/main/javahelp/help_sq_AL/helpset_sq_AL.hs
|
apache-2.0
| 978 | 78 | 66 | 157 | 412 | 209 | 203 | -1 | -1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sq-AL">
<title>Sequence Scanner | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
kingthorin/zap-extensions
|
addOns/sequence/src/main/javahelp/org/zaproxy/zap/extension/sequence/resources/help_sq_AL/helpset_sq_AL.hs
|
apache-2.0
| 977 | 78 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
{-| Implementation of DataCollectors CLI functions.
This module holds the common command-line related functions for the
collector binaries.
-}
{-
Copyright (C) 2009, 2010, 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.DataCollectors.CLI
( Options(..)
, OptType
, defaultOptions
-- * The options
, oShowHelp
, oShowVer
, oShowComp
, oDrbdPairing
, oDrbdStatus
, oNode
, oConfdAddr
, oConfdPort
, oInputFile
, oInstances
, genericOptions
) where
import System.Console.GetOpt
import Ganeti.BasicTypes
import Ganeti.Common as Common
import Ganeti.Utils
-- * Data types
-- | Command line options structure.
data Options = Options
{ optShowHelp :: Bool -- ^ Just show the help
, optShowComp :: Bool -- ^ Just show the completion info
, optShowVer :: Bool -- ^ Just show the program version
, optDrbdStatus :: Maybe FilePath -- ^ Path to the file containing DRBD
-- status information
, optDrbdPairing :: Maybe FilePath -- ^ Path to the file containing pairings
-- between instances and DRBD minors
, optNode :: Maybe String -- ^ Info are requested for this node
, optConfdAddr :: Maybe String -- ^ IP address of the Confd server
, optConfdPort :: Maybe Int -- ^ The port of the Confd server to
-- connect to
, optInputFile :: Maybe FilePath -- ^ Path to the file containing the
-- information to be parsed
, optInstances :: Maybe FilePath -- ^ Path to the file contained a
-- serialized list of instances as in:
-- ([Primary], [Secondary])
} deriving Show
-- | Default values for the command line options.
defaultOptions :: Options
defaultOptions = Options
{ optShowHelp = False
, optShowComp = False
, optShowVer = False
, optDrbdStatus = Nothing
, optDrbdPairing = Nothing
, optNode = Nothing
, optConfdAddr = Nothing
, optConfdPort = Nothing
, optInputFile = Nothing
, optInstances = Nothing
}
-- | Abbreviation for the option type.
type OptType = GenericOptType Options
instance StandardOptions Options where
helpRequested = optShowHelp
verRequested = optShowVer
compRequested = optShowComp
requestHelp o = o { optShowHelp = True }
requestVer o = o { optShowVer = True }
requestComp o = o { optShowComp = True }
-- * Command line options
oDrbdPairing :: OptType
oDrbdPairing =
( Option "p" ["drbd-pairing"]
(ReqArg (\ f o -> Ok o { optDrbdPairing = Just f}) "FILE")
"the FILE containing pairings between instances and DRBD minors",
OptComplFile)
oDrbdStatus :: OptType
oDrbdStatus =
( Option "s" ["drbd-status"]
(ReqArg (\ f o -> Ok o { optDrbdStatus = Just f }) "FILE")
"the DRBD status FILE",
OptComplFile)
oNode :: OptType
oNode =
( Option "n" ["node"]
(ReqArg (\ n o -> Ok o { optNode = Just n }) "NODE")
"the FQDN of the NODE about which information is requested",
OptComplFile)
oConfdAddr :: OptType
oConfdAddr =
( Option "a" ["address"]
(ReqArg (\ a o -> Ok o { optConfdAddr = Just a }) "IP_ADDR")
"the IP address of the Confd server to connect to",
OptComplFile)
oConfdPort :: OptType
oConfdPort =
(Option "p" ["port"]
(reqWithConversion (tryRead "reading port")
(\port opts -> Ok opts { optConfdPort = Just port }) "PORT")
"Network port of the Confd server to connect to",
OptComplInteger)
oInputFile :: OptType
oInputFile =
( Option "f" ["file"]
(ReqArg (\ f o -> Ok o { optInputFile = Just f }) "FILE")
"the input FILE",
OptComplFile)
oInstances :: OptType
oInstances =
( Option "i" ["instances"]
(ReqArg (\ f o -> Ok o { optInstances = Just f}) "FILE")
"the FILE containing serialized instances",
OptComplFile)
-- | Generic options.
genericOptions :: [GenericOptType Options]
genericOptions = [ oShowVer
, oShowHelp
, oShowComp
]
|
apyrgio/snf-ganeti
|
src/Ganeti/DataCollectors/CLI.hs
|
bsd-2-clause
| 5,402 | 0 | 14 | 1,392 | 801 | 473 | 328 | 98 | 1 |
module TH_abstractFamily where
import Language.Haskell.TH
-- Empty closed type families are okay...
ds1 :: Q [Dec]
ds1 = [d| type family F a where |]
-- ...but abstract ones should result in a type error
ds2 :: Q [Dec]
ds2 = [d| type family G a where .. |]
|
urbanslug/ghc
|
testsuite/tests/quotes/TH_abstractFamily.hs
|
bsd-3-clause
| 260 | 0 | 6 | 52 | 52 | 35 | 17 | -1 | -1 |
module Main where
import System.Environment
import System.Exit
import qualified Data.Map as Map
import Crosscells.Tokens
import Crosscells.Puzzle
import Crosscells.Solver
main :: IO ()
main =
do name <- getArg
file <- readFile name
xs <- solvePuzzle (compile (parseTokens file))
mapM_ print (Map.toList xs)
getArg :: IO String
getArg =
do args <- getArgs
case args of
[x] -> do return x
_ -> do putStrLn "Usage: Crosscells PUZZLE_FILENAME"
exitFailure
|
glguy/5puzzle
|
Crosscells.hs
|
isc
| 513 | 0 | 12 | 129 | 164 | 82 | 82 | 20 | 2 |
module Platform.JWT where
import ClassyPrelude
import Data.Has
import Jose.Jwk
import Crypto.Random.Types (MonadRandom)
import System.Environment
import qualified Data.Aeson as Aeson
data Env = Env
{ envExpirationSecs :: Integer
, envJwks :: [Jwk]
}
type JWT r m = (MonadReader r m, Has Env r, MonadRandom m, MonadIO m)
-- * Resource acquisitions
init :: IO Env
init = Env <$> acquireJWTExpirationSecs <*> acquireJwks
acquireJwks :: IO [Jwk]
acquireJwks = do
envUrl <- lookupEnv "JWK_PATH"
let jwkPath = fromMaybe "secrets/jwk.sig" envUrl
fileContent <- readFile jwkPath
let parsed = Aeson.eitherDecodeStrict fileContent
return $ either (\e -> error $ "invalid JWK file: " <> e) pure parsed
acquireJWTExpirationSecs :: IO Integer
acquireJWTExpirationSecs = do
param <- lookupEnv "JWT_EXPIRATION_SECS"
let expirationSecs = fromMaybe (2 * 60 * 60) $ param >>= readMay
return expirationSecs
|
eckyputrady/haskell-scotty-realworld-example-app
|
src/Platform/JWT.hs
|
mit
| 919 | 0 | 15 | 160 | 279 | 147 | 132 | 25 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
module Render.RichText
( Block(..),
Inlines (..),
-- LinkTarget (..),
space,
text,
text',
parens,
-- link,
linkRange,
linkHole,
icon,
-- combinators
(<+>),
punctuate,
braces,
braces',
dbraces,
mparens,
hcat,
hsep,
sep,
fsep,
vcat,
fcat,
-- symbols
arrow,
lambda,
forallQ,
showIndex,
leftIdiomBrkt,
rightIdiomBrkt,
emptyIdiomBrkt,
)
where
-- import qualified Agda.Interaction.Options as Agda
-- import qualified Agda.Syntax.Concrete.Glyph as Agda
import qualified Agda.Syntax.Position as Agda
import qualified Agda.Utils.FileName as Agda
import qualified Agda.Utils.Null as Agda
import Agda.Utils.Suffix (toSubscriptDigit)
import Data.Aeson (ToJSON (toJSON), Value (Null))
import Data.Foldable (toList)
import Data.Sequence (Seq (..))
import qualified Data.Sequence as Seq
import Data.String (IsString (..))
import qualified Data.Strict.Maybe as Strict
import GHC.Generics (Generic)
--------------------------------------------------------------------------------
-- | Block elements
data Block
-- for blocks like "Goal" & "Have"
= Labeled Inlines (Maybe String) (Maybe Agda.Range) String String
-- for ordinary goals & context
| Unlabeled Inlines (Maybe String) (Maybe Agda.Range)
-- headers
| Header String
deriving (Generic)
instance ToJSON Block
--------------------------------------------------------------------------------
newtype Inlines = Inlines {unInlines :: Seq Inline}
-- Represent Inlines with String literals
instance IsString Inlines where
fromString s = Inlines (Seq.singleton (Text s mempty))
instance Semigroup Inlines where
Inlines as <> Inlines bs = Inlines (merge as bs)
where
merge :: Seq Inline -> Seq Inline -> Seq Inline
merge Empty ys = ys
merge (xs :|> x) ys = merge xs (cons x ys)
cons :: Inline -> Seq Inline -> Seq Inline
cons (Text s c) (Text t d :<| xs)
-- merge 2 adjacent Text if they have the same classnames
| c == d = Text (s <> t) c :<| xs
| otherwise = Text s c :<| Text t d :<| xs
cons (Text s c) (Horz [] :<| xs) = cons (Text s c) xs
cons (Text s c) (Horz (Inlines t:ts) :<| xs)
-- merge Text with Horz when possible
= Horz (Inlines (cons (Text s c) t) :ts) :<| xs
cons x xs = x :<| xs
instance Monoid Inlines where
mempty = Inlines mempty
instance ToJSON Inlines where
toJSON (Inlines xs) = toJSON xs
instance Show Inlines where
show (Inlines xs) = unwords $ map show $ toList xs
-- | see if the rendered text is "empty"
isEmpty :: Inlines -> Bool
isEmpty (Inlines elems) = all elemIsEmpty (Seq.viewl elems)
where
elemIsEmpty :: Inline -> Bool
elemIsEmpty (Icon _ _) = False
elemIsEmpty (Text "" _) = True
elemIsEmpty (Text _ _) = False
elemIsEmpty (Link _ xs _) = all elemIsEmpty $ unInlines xs
elemIsEmpty (Hole _) = False
elemIsEmpty (Horz xs) = all isEmpty xs
elemIsEmpty (Vert xs) = all isEmpty xs
elemIsEmpty (Parn _) = False
elemIsEmpty (PrHz _) = False
infixr 6 <+>
(<+>) :: Inlines -> Inlines -> Inlines
x <+> y
| isEmpty x = y
| isEmpty y = x
| otherwise = x <> " " <> y
-- | Whitespace
space :: Inlines
space = " "
text :: String -> Inlines
text s = Inlines $ Seq.singleton $ Text s mempty
text' :: ClassNames -> String -> Inlines
text' cs s = Inlines $ Seq.singleton $ Text s cs
-- When there's only 1 Horz inside a Parn, convert it to PrHz
parens :: Inlines -> Inlines
parens (Inlines (Horz xs :<| Empty)) = Inlines $ Seq.singleton $ PrHz xs
parens others = Inlines $ Seq.singleton $ Parn others
icon :: String -> Inlines
icon s = Inlines $ Seq.singleton $ Icon s []
linkRange :: Agda.Range -> Inlines -> Inlines
linkRange range xs = Inlines $ Seq.singleton $ Link range xs mempty
linkHole :: Int -> Inlines
linkHole i = Inlines $ Seq.singleton $ Hole i
--------------------------------------------------------------------------------
type ClassNames = [String]
--------------------------------------------------------------------------------
-- | Internal type, to be converted to JSON values
data Inline
= Icon String ClassNames
| Text String ClassNames
| Link Agda.Range Inlines ClassNames
| Hole Int
| -- | Horizontal grouping, wrap when there's no space
Horz [Inlines]
| -- | Vertical grouping, each children would end with a newline
Vert [Inlines]
| -- | Parenthese
Parn Inlines
| -- | Parenthese around a Horizontal, special case
PrHz [Inlines]
deriving (Generic)
instance ToJSON Inline
instance Show Inline where
show (Icon s _) = s
show (Text s _) = s
show (Link _ xs _) = mconcat (map show $ toList $ unInlines xs)
show (Hole i) = "?" ++ show i
show (Horz xs) = unwords (map show $ toList xs)
show (Vert xs) = unlines (map show $ toList xs)
show (Parn x) = "(" <> show x <> ")"
show (PrHz xs) = "(" <> unwords (map show $ toList xs) <> ")"
--------------------------------------------------------------------------------
-- | ToJSON instances for A.types
instance {-# OVERLAPS #-} ToJSON Agda.Range
instance ToJSON (Agda.Interval' ()) where
toJSON (Agda.Interval start end) = toJSON (start, end)
instance ToJSON (Agda.Position' ()) where
toJSON (Agda.Pn () pos line col) = toJSON [line, col, pos]
instance {-# OVERLAPS #-} ToJSON Agda.SrcFile where
toJSON Strict.Nothing = Null
toJSON (Strict.Just path) = toJSON path
instance ToJSON Agda.AbsolutePath where
toJSON (Agda.AbsolutePath path) = toJSON path
--------------------------------------------------------------------------------
-- | Utilities / Combinators
-- -- TODO: implement this
-- indent :: Inlines -> Inlines
-- indent x = " " <> x
punctuate :: Inlines -> [Inlines] -> [Inlines]
punctuate _ [] = []
punctuate delim xs = zipWith (<>) xs (replicate (length xs - 1) delim ++ [mempty])
--------------------------------------------------------------------------------
-- | Just pure concatenation, no grouping or whatsoever
hcat :: [Inlines] -> Inlines
hcat = mconcat
hsep :: [Inlines] -> Inlines
hsep [] = mempty
hsep [x] = x
hsep (x : xs) = x <+> hsep xs
--------------------------------------------------------------------------------
-- | Vertical listing
vcat :: [Inlines] -> Inlines
vcat = Inlines . pure . Vert
-- | Horizontal listing
sep :: [Inlines] -> Inlines
sep = Inlines . pure . Horz
fsep :: [Inlines] -> Inlines
fsep = sep
fcat :: [Inlines] -> Inlines
fcat = sep
--------------------------------------------------------------------------------
-- | Single braces
braces :: Inlines -> Inlines
braces x = "{" <> x <> "}"
-- | Double braces
dbraces :: Inlines -> Inlines
dbraces = _dbraces specialCharacters
arrow :: Inlines
arrow = _arrow specialCharacters
lambda :: Inlines
lambda = _lambda specialCharacters
forallQ :: Inlines
forallQ = _forallQ specialCharacters
-- left, right, and empty idiom bracket
leftIdiomBrkt, rightIdiomBrkt, emptyIdiomBrkt :: Inlines
leftIdiomBrkt = _leftIdiomBrkt specialCharacters
rightIdiomBrkt = _rightIdiomBrkt specialCharacters
emptyIdiomBrkt = _emptyIdiomBrkt specialCharacters
-- | Apply 'parens' to 'Doc' if boolean is true.
mparens :: Bool -> Inlines -> Inlines
mparens True = parens
mparens False = id
-- | From braces'
braces' :: Inlines -> Inlines
braces' d =
let s = show d
in if Agda.null s
then braces d
else braces (spaceIfDash (head s) <> d <> spaceIfDash (last s))
where
-- Add space to avoid starting a comment (Ulf, 2010-09-13, #269)
-- Andreas, 2018-07-21, #3161: Also avoid ending a comment
spaceIfDash '-' = " "
spaceIfDash _ = mempty
-- | Shows a non-negative integer using the characters ₀-₉ instead of
-- 0-9 unless the user explicitly asked us to not use any unicode characters.
showIndex :: (Show i, Integral i) => i -> String
showIndex = map toSubscriptDigit . show
--------------------------------------------------------------------------------
--
-- | Picking the appropriate set of special characters depending on
-- whether we are allowed to use unicode or have to limit ourselves
-- to ascii.
data SpecialCharacters = SpecialCharacters
{ _dbraces :: Inlines -> Inlines,
_lambda :: Inlines,
_arrow :: Inlines,
_forallQ :: Inlines,
_leftIdiomBrkt :: Inlines,
_rightIdiomBrkt :: Inlines,
_emptyIdiomBrkt :: Inlines
}
{-# NOINLINE specialCharacters #-}
specialCharacters :: SpecialCharacters
specialCharacters =
SpecialCharacters
{ _dbraces = ("\x2983 " <>) . (<> " \x2984"),
_lambda = "\x03bb",
_arrow = "\x2192",
_forallQ = "\x2200",
_leftIdiomBrkt = "\x2987",
_rightIdiomBrkt = "\x2988",
_emptyIdiomBrkt = "\x2987\x2988"
}
|
banacorn/agda-language-server
|
src/Render/RichText.hs
|
mit
| 8,930 | 0 | 16 | 1,922 | 2,454 | 1,325 | 1,129 | 197 | 9 |
nwd :: Integer -> Integer -> Integer
nwd 0 y = y
nwd x 0 = x
nwd x y
| x >= y = if x`mod`y>y then nwd (x`mod`y) y else nwd y (x`mod`y)
| x < y = nwd y x
|
RAFIRAF/HASKELL
|
nwdEuMod2.hs
|
mit
| 157 | 0 | 9 | 47 | 118 | 61 | 57 | 6 | 2 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module LLVM.Codegen.Array (
Order(..),
Array(..),
arrayType,
asArray,
arrayPtrC,
arrayPtrF,
arrayArg,
arraySet,
arrayGet
) where
import Control.Monad
import LLVM.Codegen.Builder
import LLVM.Codegen.Logic
import LLVM.Codegen.Types
import LLVM.Codegen.Constant
import LLVM.Codegen.Instructions
import LLVM.General.AST (Type, Operand)
data Order
= RowMajor
| ColMajor
deriving (Eq, Ord, Show)
-- | Array representation. The equivelant C type would be:
--
-- @
-- typedef struct Array {
-- char *data;
-- intp *shape;
-- intp *strides;
-- } Array;
-- @
arrayType :: Type
arrayType = struct
[ pointer char -- char *data
, pointer intp -- intp *shape
, pointer intp -- intp *strides
]
data Array = Array
{ arrOrder :: Order -- ^ Array order
, arrShape :: [Operand] -- ^ Array shape
, arrStrides :: [Operand] -- ^ Array strides
, arrDim :: Int -- ^ Array dimensions
, arrType :: Type -- ^ Array data type
, arrValue :: Operand -- ^ Underlying array struct
} deriving (Eq, Ord, Show)
-- | Interpret a typed LLVM pointer as an Array
asArray :: Operand -> Type -> [Operand] -> Codegen Array
asArray arr ty shape =
return $ Array RowMajor shape strides (length shape) ty arr
where
strides = []
-- | Generate instructions to calculate the pointer for the multidimensional C contiguous array with given
-- shape with for a given index.
--
-- @
-- Dim : d
-- Shape : D = D_1 × D_2 ... × D_d
-- Index : I = (I_1, I_2, ... I_d)
--
-- offset(D, I) = \sum_{k=1}^d \left( \prod_{l=k+1}^d D_l \right) I_k
-- @
-- | Generate the instructions to calculate the linear offset from the shape of the array.
-- @
--
-- S = (8, 8)
-- P = [p0, p1]
--
-- %0 = mul i32 p0, 1
-- %1 = add i32 0, %0
-- %2 = mul i32 p1, 8
-- %3 = add i32 %1, %2
-- @
offset :: Operand -> (Operand, Operand) -> Codegen Operand
offset p (x,y) = mul x y >>= add p
arrayPtrC :: Array -> [Operand] -> Codegen Operand
arrayPtrC arr ix = do
steps <- scanlM mul el sh
pos <- foldM offset zero (zip ix steps)
dat <- load (arrValue arr)
gep dat [pos]
where
el = constant i32 1
zero = cons $ cnull i32
sh = arrShape arr
-- | Generate instructions to calculate the pointer for the multidimensional Fotran contiguous array with
-- given shape with for a given index.
--
-- @
-- Dim : d
-- Shape : D = D_0 × D_2 ... × D_d
-- Index : I = (I_1, I_2, ... I_d)
--
-- offset(D, I) = \sum_{k=1}^d \left( \prod_{\l=1}^{k-1} D_l \right) I_k
-- @
arrayPtrF :: Array -> [Operand] -> Codegen Operand
arrayPtrF arr ix = do
steps <- scanrM mul el sh
pos <- foldM offset zero (zip ix steps)
dat <- load (arrValue arr)
gep dat [pos]
where
el = constant i32 1
zero = cons $ cnull i32
sh = arrShape arr
-- C contiguous by default
arrayPtr :: Array -> [Operand] -> Codegen Operand
arrayPtr = arrayPtrC
-- | Set an index of an array to a value
arraySet :: Array -> [Operand] -> Operand -> Codegen ()
arraySet arr ix val = do
ptr <- arrayPtr arr ix
store ptr val
-- | Index into an array retrieving a value.
arrayGet :: Array -> [Operand] -> Codegen Operand
arrayGet arr ix = do
ptr <- arrayPtr arr ix
load ptr
-- | Interpret an array ptr from a function as a local array.
arrayArg :: String -> Type -> [Operand] -> Codegen Array
arrayArg s ty size = do
ptr <- getvar s
asArray ptr ty size
-------------------------------------------------------------------------------
-- Offsets Utilities
-------------------------------------------------------------------------------
-- | Calculate the element offset for a given shape.
-- rowMajorStrides [1,2,3,4]
-- [24,12,4,1]
--
-- rowMajorStrides [1,2,3,4]
-- [1,1,2,6]
rowMajorStrides :: [Int] -> [Int]
rowMajorStrides = scanr (*) 1 . tail
colMajorStrides :: [Int] -> [Int]
colMajorStrides = init . scanl (*) 1
scanlM :: (Monad m) => (a -> b -> m a) -> a -> [b] -> m [a]
scanlM _ q0 [] = return [q0]
scanlM f q0 (x:xs) =
do q2 <- f q0 x
qs <- scanlM f q2 xs
return (q0:qs)
scanrM :: (Monad m) => (a -> b -> m b) -> b -> [a] -> m [b]
scanrM _ q0 [] = return [q0]
scanrM f q0 (x:xs) =
do q2 <- f x q0
qs <- scanrM f q2 xs
return (q0:qs)
|
sdiehl/llvm-codegen
|
src/LLVM/Codegen/Array.hs
|
mit
| 4,284 | 0 | 10 | 1,003 | 1,143 | 625 | 518 | 89 | 1 |
{-
- By Yue Wang 14.12.2014
- proj06 insertion sort.
--}
insertionSort :: (Ord a) => [a] -> [a]
insertionSort [] = []
insertionSort xs = fst (insert ([],xs))
where insert(low, high) = if hs==[] then (ls, hs) else insert (ls, hs)
where ls = [x|x<-low, x <= head high] ++ [head high] ++ [x|x<-low, x > head high]
hs = tail high
|
Mooophy/DMA
|
ch02/proj06.hs
|
mit
| 366 | 7 | 9 | 103 | 142 | 85 | 57 | -1 | -1 |
-- |
-- Module: Network.Transportation.Germany.DVB.Monitor
-- Copyright: (C) 2016 Braden Walters
-- License: MIT (see LICENSE file)
-- Maintainer: Braden Walters <[email protected]>
-- Stability: experimental
-- Portability: ghc
module Network.Transportation.Germany.DVB.Monitor
( MonitorRequest(..)
, MonitorResult(..)
, TransitConnection(..)
, Error(..)
, monitor
) where
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as BS8
import Network.HTTP
import Network.Stream
import Network.Transportation.Germany.DVB
import qualified Network.Transportation.Germany.DVB.Monitor.JSON as JSON
-- |All data sent to DVB to monitor a stop.
data MonitorRequest = MonitorRequest
{ monitorReqCity :: City
, monitorReqStop :: Location
, monitorReqOffset :: Integer
, monitorReqLimit :: Integer
} deriving (Show)
-- |Either monitor data or an error.
type MonitorResult = Either Error [TransitConnection]
-- |An arriving vehicle at the stop.
data TransitConnection = TransitConnection
{ transConnNumber :: String
, transConnDesc :: String
, transConnArrivalMinutes :: Integer
} deriving (Show)
-- |All possible errors which could occur while fetching data, including HTTP
-- errors and JSON parsing errors.
data Error = HttpResetError | HttpClosedError | HttpParseError String |
HttpMiscError String | JsonParseError String deriving (Show)
-- |Given information about a stop, query and return data from DVB about
-- vehicles stopping there.
monitor :: MonitorRequest -> IO MonitorResult
monitor req = do
let (City city) = monitorReqCity req
(Location stop) = monitorReqStop req
params = [("ort", city),
("hst", stop),
("vz", show $ monitorReqOffset req),
("lim", show $ monitorReqLimit req)]
result <- simpleHTTP (getRequest (monitorUrl ++ "?" ++ urlEncodeVars params))
case result of
Left connError -> return $ Left $ connErrToResultErr connError
Right response' ->
let body = BS8.pack $ rspBody response'
in case eitherDecode body of
Left err ->
return $ Left $ JsonParseError err
Right transConns ->
return $ Right (map fromJsonTransitConnection transConns)
-- |The HTTP URL to query for DVB monitor data.
monitorUrl :: String
monitorUrl = "http://widgets.vvo-online.de/abfahrtsmonitor/Abfahrten.do"
-- |Take an HTTP connection error and convert it into an error which can be
-- returned in a RouteResult.
connErrToResultErr :: ConnError -> Error
connErrToResultErr ErrorReset = HttpResetError
connErrToResultErr ErrorClosed = HttpClosedError
connErrToResultErr (ErrorParse msg) = HttpParseError msg
connErrToResultErr (ErrorMisc msg) = HttpMiscError msg
fromJsonTransitConnection :: JSON.TransitConnection -> TransitConnection
fromJsonTransitConnection transConn =
TransitConnection {
transConnNumber = JSON.transConnNumber transConn,
transConnDesc = JSON.transConnDesc transConn,
-- TODO: Use a total function instead of read.
transConnArrivalMinutes = read $ JSON.transConnArrivalMinutes transConn
}
|
meoblast001/dresdner-verkehrsbetriebe
|
src/Network/Transportation/Germany/DVB/Monitor.hs
|
mit
| 3,102 | 0 | 18 | 564 | 597 | 339 | 258 | 57 | 3 |
{-# LANGUAGE GADTs, OverloadedStrings, InstanceSigs, TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
-- | Provides actions for Channel API interactions
module Network.Discord.Rest.Channel
(
ChannelRequest(..)
) where
import Data.Aeson
import Data.ByteString.Lazy
import Data.Hashable
import Data.Monoid (mempty, (<>))
import Data.Text as T
import Network.HTTP.Client (RequestBody (..))
import Network.HTTP.Client.MultipartFormData (partFileRequestBody)
import Network.HTTP.Req (reqBodyMultipart)
import Network.Discord.Rest.Prelude
import Network.Discord.Types
import Network.Discord.Rest.HTTP
-- | Data constructor for Channel requests. See <https://discordapp.com/developers/docs/resources/Channel Channel API>
data ChannelRequest a where
-- | Gets a channel by its id.
GetChannel :: Snowflake -> ChannelRequest Channel
-- | Edits channels options.
ModifyChannel :: ToJSON a => Snowflake -> a -> ChannelRequest Channel
-- | Deletes a channel if its id doesn't equal to the id of guild.
DeleteChannel :: Snowflake -> ChannelRequest Channel
-- | Gets a messages from a channel with limit of 100 per request.
GetChannelMessages :: Snowflake -> Range -> ChannelRequest [Message]
-- | Gets a message in a channel by its id.
GetChannelMessage :: Snowflake -> Snowflake -> ChannelRequest Message
-- | Sends a message to a channel.
CreateMessage :: Snowflake -> Text -> Maybe Embed -> ChannelRequest Message
-- | Sends a message with a file to a channel.
UploadFile :: Snowflake -> FilePath -> ByteString -> ChannelRequest Message
-- | Edits a message content.
EditMessage :: Message -> Text -> Maybe Embed -> ChannelRequest Message
-- | Deletes a message.
DeleteMessage :: Message -> ChannelRequest ()
-- | Deletes a group of messages.
BulkDeleteMessage :: Snowflake -> [Message] -> ChannelRequest ()
-- | Edits a permission overrides for a channel.
EditChannelPermissions :: ToJSON a => Snowflake -> Snowflake -> a -> ChannelRequest ()
-- | Gets all instant invites to a channel.
GetChannelInvites :: Snowflake -> ChannelRequest Object
-- | Creates an instant invite to a channel.
CreateChannelInvite :: ToJSON a => Snowflake -> a -> ChannelRequest Object
-- | Deletes a permission override from a channel.
DeleteChannelPermission :: Snowflake -> Snowflake -> ChannelRequest ()
-- | Sends a typing indicator a channel which lasts 10 seconds.
TriggerTypingIndicator :: Snowflake -> ChannelRequest ()
-- | Gets all pinned messages of a channel.
GetPinnedMessages :: Snowflake -> ChannelRequest [Message]
-- | Pins a message.
AddPinnedMessage :: Snowflake -> Snowflake -> ChannelRequest ()
-- | Unpins a message.
DeletePinnedMessage :: Snowflake -> Snowflake -> ChannelRequest ()
instance Hashable (ChannelRequest a) where
hashWithSalt s (GetChannel chan) = hashWithSalt s ("get_chan"::Text, chan)
hashWithSalt s (ModifyChannel chan _) = hashWithSalt s ("mod_chan"::Text, chan)
hashWithSalt s (DeleteChannel chan) = hashWithSalt s ("mod_chan"::Text, chan)
hashWithSalt s (GetChannelMessages chan _) = hashWithSalt s ("msg"::Text, chan)
hashWithSalt s (GetChannelMessage chan _) = hashWithSalt s ("get_msg"::Text, chan)
hashWithSalt s (CreateMessage chan _ _) = hashWithSalt s ("msg"::Text, chan)
hashWithSalt s (UploadFile chan _ _) = hashWithSalt s ("msg"::Text, chan)
hashWithSalt s (EditMessage (Message _ chan _ _ _ _ _ _ _ _ _ _ _ _) _ _) =
hashWithSalt s ("get_msg"::Text, chan)
hashWithSalt s (DeleteMessage (Message _ chan _ _ _ _ _ _ _ _ _ _ _ _)) =
hashWithSalt s ("get_msg"::Text, chan)
hashWithSalt s (BulkDeleteMessage chan _) = hashWithSalt s ("del_msgs"::Text, chan)
hashWithSalt s (EditChannelPermissions chan _ _) = hashWithSalt s ("perms"::Text, chan)
hashWithSalt s (GetChannelInvites chan) = hashWithSalt s ("invites"::Text, chan)
hashWithSalt s (CreateChannelInvite chan _) = hashWithSalt s ("invites"::Text, chan)
hashWithSalt s (DeleteChannelPermission chan _) = hashWithSalt s ("perms"::Text, chan)
hashWithSalt s (TriggerTypingIndicator chan) = hashWithSalt s ("tti"::Text, chan)
hashWithSalt s (GetPinnedMessages chan) = hashWithSalt s ("pins"::Text, chan)
hashWithSalt s (AddPinnedMessage chan _) = hashWithSalt s ("pin"::Text, chan)
hashWithSalt s (DeletePinnedMessage chan _) = hashWithSalt s ("pin"::Text, chan)
instance RateLimit (ChannelRequest a)
instance (FromJSON a) => DoFetch (ChannelRequest a) where
doFetch req = SyncFetched <$> go req
where
maybeEmbed :: Maybe Embed -> [(Text, Value)]
maybeEmbed = maybe [] $ \embed -> ["embed" .= embed]
url = baseUrl /: "channels"
go :: ChannelRequest a -> DiscordM a
go r@(GetChannel chan) = makeRequest r
$ Get (url // chan) mempty
go r@(ModifyChannel chan patch) = makeRequest r
$ Patch (url // chan)
(ReqBodyJson patch) mempty
go r@(DeleteChannel chan) = makeRequest r
$ Delete (url // chan) mempty
go r@(GetChannelMessages chan range) = makeRequest r
$ Get (url // chan /: "messages") (toQueryString range)
go r@(GetChannelMessage chan msg) = makeRequest r
$ Get (url // chan /: "messages" // msg) mempty
go r@(CreateMessage chan msg embed) = makeRequest r
$ Post (url // chan /: "messages")
(ReqBodyJson . object $ ["content" .= msg] <> maybeEmbed embed)
mempty
go r@(UploadFile chan fileName file) = do
body <- reqBodyMultipart [partFileRequestBody "file" fileName $ RequestBodyLBS file]
makeRequest r $ Post (url // chan /: "messages")
body mempty
go r@(EditMessage (Message msg chan _ _ _ _ _ _ _ _ _ _ _ _) new embed) = makeRequest r
$ Patch (url // chan /: "messages" // msg)
(ReqBodyJson . object $ ["content" .= new] <> maybeEmbed embed)
mempty
go r@(DeleteMessage (Message msg chan _ _ _ _ _ _ _ _ _ _ _ _)) = makeRequest r
$ Delete (url // chan /: "messages" // msg) mempty
go r@(BulkDeleteMessage chan msgs) = makeRequest r
$ Post (url // chan /: "messages" /: "bulk-delete")
(ReqBodyJson $ object ["messages" .= Prelude.map messageId msgs])
mempty
go r@(EditChannelPermissions chan perm patch) = makeRequest r
$ Put (url // chan /: "permissions" // perm)
(ReqBodyJson patch) mempty
go r@(GetChannelInvites chan) = makeRequest r
$ Get (url // chan /: "invites") mempty
go r@(CreateChannelInvite chan patch) = makeRequest r
$ Post (url // chan /: "invites")
(ReqBodyJson patch) mempty
go r@(DeleteChannelPermission chan perm) = makeRequest r
$ Delete (url // chan /: "permissions" // perm) mempty
go r@(TriggerTypingIndicator chan) = makeRequest r
$ Post (url // chan /: "typing")
NoReqBody mempty
go r@(GetPinnedMessages chan) = makeRequest r
$ Get (url // chan /: "pins") mempty
go r@(AddPinnedMessage chan msg) = makeRequest r
$ Put (url // chan /: "pins" // msg)
NoReqBody mempty
go r@(DeletePinnedMessage chan msg) = makeRequest r
$ Delete (url // chan /: "pins" // msg) mempty
|
jano017/Discord.hs
|
src/Network/Discord/Rest/Channel.hs
|
mit
| 7,883 | 0 | 16 | 2,174 | 2,224 | 1,162 | 1,062 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
module JobServer (initializeJobServer, getJobServer, clearJobServer, runJobs, JobServerHandle,
waitOnJob, runJob, tryWaitOnJob, returnToken, getToken, Token(..)) where
import Control.Exception.Base (assert)
import Control.Exception (catch, SomeException(..))
import Foreign.C.Types (CInt)
import System.Environment (getEnv, setEnv)
import System.Exit (ExitCode(..))
import System.Posix.IO (fdWrite, fdRead, closeFd, openFd, OpenMode(..), defaultFileFlags, OpenFileFlags(..))
import System.Posix.Types (Fd(..), ByteCount, ProcessID)
import System.Posix.Process (forkProcess, getProcessStatus, ProcessStatus(..))
import System.Posix.Files (createNamedPipe, ownerReadMode, ownerWriteMode, namedPipeMode, unionFileModes)
import Data.Bool (bool)
import Control.Monad (void)
import Database
newtype JobServerHandle = JobServerHandle { unJobServerHandle :: (Fd, Fd, Fd) }
newtype Token = Token { unToken :: Char } deriving (Eq, Show)
-- Define the character to store in the pipe as a token.
-- All tokens can be the same.
jobServerToken :: Token
jobServerToken = Token 't'
-- Function to initialize a new job server. The job server will
-- allow up to 'n' jobs at a time.
initializeJobServer :: Int -> IO JobServerHandle
initializeJobServer n = do
-- Create a named pipe:
pipeName <- getJobServerPipe
createNamedPipe pipeName (unionFileModes (unionFileModes ownerReadMode ownerWriteMode) namedPipeMode)
-- Open read and write ends of named pipe:
-- Note: the order in which this is done is important, otherwise this function will
-- block forever.
-- See: http://stackoverflow.com/questions/5782279/why-does-a-read-only-open-of-a-named-pipe-block
readNonBlocking <- openFd pipeName ReadOnly Nothing readNonBlockFlags
write <- openFd pipeName WriteOnly Nothing defaultFileFlags
readBlocking <- openFd pipeName ReadOnly Nothing defaultFileFlags
-- Make sure something silly didn't happen:
assert_ $ readBlocking >= 0
assert_ $ readNonBlocking >= 0
assert_ $ write >= 0
assert_ $ readBlocking /= readNonBlocking
assert_ $ readNonBlocking /= write
assert_ $ write /= readBlocking
-- Write the tokens to the pipe:
byteCount <- fdWrite write tokens
assert_ $ countToInt byteCount == tokensToWrite
-- Set an environment variable to store the handle for
-- other programs that might use this server:
setEnv "REDO_JOB_SERVER_PIPE" $ show readBlocking ++ ", " ++
show readNonBlocking ++ ", " ++
show write
-- Return the read and write ends of the pipe:
return $ JobServerHandle (readBlocking, readNonBlocking, write)
where tokens = replicate tokensToWrite (unToken jobServerToken)
tokensToWrite = n-1
readNonBlockFlags =
OpenFileFlags { nonBlock = True, append = False,
exclusive = False, noctty = False,
trunc = False }
-- Get a job server that has already been created:
getJobServer :: IO JobServerHandle
getJobServer = do flags <- getEnv "REDO_JOB_SERVER_PIPE"
let handle = handle' flags
return $ JobServerHandle (Fd $ head handle, Fd $ handle !! 1, Fd $ handle !! 2)
where handle' flags = map convert (splitBy ',' flags)
convert a = read a :: CInt
-- Clear the job server by closing all the open file descriptors associated
-- with it.
clearJobServer :: JobServerHandle -> IO ()
clearJobServer handle = safeCloseFd w >> safeCloseFd r >> safeCloseFd r'
where safeCloseFd fd = catch (closeFd fd) (\(_ :: SomeException) -> return ())
(r', r, w) = unJobServerHandle handle
-- Given a list of IO () jobs, run them when a space on the job server is
-- available.
runJobs :: JobServerHandle -> [IO ExitCode] -> IO [ExitCode]
runJobs _ [] = return []
runJobs _ [j] = do ret <- j
return [ret]
runJobs handle (j:jobs) = bool runJob' forkJob =<< tryGetToken handle
where
-- We got a token, so fork a new process for the job, and then
-- recurse to run the remaining jobs:
forkJob = do
-- Fork new thread to run job:
processId <- forkProcess $ runForkedJob handle j
-- Run the rest of the jobs:
rets <- runJobs handle jobs
maybe (return $ ExitFailure 1 : rets) (returnExitCode rets)
=<< getProcessStatus True False processId
-- Run a job on the current process without forking:
runJob' = do ret1 <- j
rets <- runJobs handle jobs
return $ ret1:rets
-- Return a list of exit codes:
returnExitCode rets processStatus = return $ code:rets
where code = getExitCode processStatus
-- Run a single job. Fork it if a token is avalable, otherwise run it on
-- the current thread.
runJob :: JobServerHandle -> IO ExitCode -> IO (Either ProcessID ExitCode)
runJob handle j = bool runJob' forkJob =<< tryGetToken handle
where
-- We got a token, so fork a new process for the job and run it:
forkJob = do
processStatus <- forkProcess $ runForkedJob handle j
return $ Left processStatus
-- Run a job on the current process without forking:
runJob' = Right <$> j
-- Run a job and then return the token associated with it.
runForkedJob :: JobServerHandle -> IO ExitCode -> IO ()
runForkedJob handle job = do
_ <- job
returnToken handle
-- Wait on job to finish, and return the exit code when it does:
waitOnJob :: ProcessID -> IO ExitCode
waitOnJob pid = maybe (ExitFailure 1) getExitCode <$> getProcessStatus True False pid
-- Return a job's exit code if it's finished, otherwise return Nothing.
tryWaitOnJob :: ProcessID -> IO (Maybe ExitCode)
tryWaitOnJob pid = (getExitCode <$>) <$> getProcessStatus False False pid
-- Get the exit code from a process status:
getExitCode :: ProcessStatus -> ExitCode
getExitCode (Exited code) = code
getExitCode (Terminated _ _) = ExitFailure 1
getExitCode (Stopped _) = ExitFailure 1
-- Get a token if one is available, otherwise return Nothing:
tryGetToken :: JobServerHandle -> IO Bool
tryGetToken handle = catch (readToken r >> return True) (\(_ :: SomeException) -> return False)
where (_, r, _) = unJobServerHandle handle
-- Wait for a token to become available and then return it:
getToken :: JobServerHandle -> IO ()
getToken handle = void $ readToken r
where (r, _, _) = unJobServerHandle handle
-- Blocking read the next token from the pipe:
readToken :: Fd -> IO Token
readToken fd = do (token, byteCount) <- fdRead fd 1
assert_ $ countToInt byteCount == 1
return $ Token $ head token
-- Return a token to the pipe:
returnToken :: JobServerHandle -> IO ()
returnToken handle = do byteCount <- fdWrite w $ unToken jobServerToken:""
assert_ $ countToInt byteCount == 1
where (_, _, w) = unJobServerHandle handle
-- Convenient assert function:
assert_ :: Monad m => Bool -> m ()
assert_ c = assert c (return ())
-- Conversion helper for ByteCount type:
countToInt :: ByteCount -> Int
countToInt = fromIntegral
-- Split a string into a list of strings given a delimiter:
splitBy :: Char -> String -> [String]
splitBy delimiter = foldr f [[]]
where f c l@(x:xs) | c == delimiter = []:l
| otherwise = (c:x):xs
f _ [] = []
|
dinkelk/redo
|
src/JobServer.hs
|
mit
| 7,334 | 0 | 14 | 1,634 | 1,799 | 944 | 855 | 110 | 2 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverlappingInstances #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
module Apply
(App(..)
,Wrap(..)
,TagC(..)
,TagD(..)
,TDef
,WrapDef(..)
,makeApplyInst
,wApply
,applyW
,wApplyW
,wApply2
,partial
,(@@)
,(#@)
,(#@#)
,(@#)
,(&)
) where
import ApplyInternal
--If there is no instance for a tag and wrapper, use the default wrapper
--This is declared here since ApplyInternal does not have OverlappingInstances
instance (Wrap w, TagC t a b) => App t w a b where
apply f _ = apply f ADef
|
rgleichman/smock
|
Apply.hs
|
mit
| 706 | 0 | 6 | 215 | 144 | 95 | 49 | 25 | 0 |
{-# LANGUAGE LambdaCase, RecordWildCards, ScopedTypeVariables, ViewPatterns #-}
module Test where
import Rubik.Cube
import Rubik.Cube.Facelet.Internal
import Rubik.Cube.Cubie.Internal
import Rubik.Cube.Moves.Internal
import Rubik.Tables.Moves
import Rubik.Misc
import Rubik.Symmetry
import Control.Applicative
import Control.Monad
import Data.List
import Data.List.Split (chunksOf)
import Data.Maybe
import Data.Monoid
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Primitive.Pinned as P
import Distribution.TestSuite
import Distribution.TestSuite.QuickCheck
import Test.HUnitPlus
import Test.QuickCheck
import qualified Test.QuickCheck as Gen
import System.Environment
-- If the test suite receives some command line arguments, only tests whose
-- fully qualified name has a prefix among them are run.
tests :: IO [Test]
tests = (filterTests . rename)
[ testGroup "Cube"
[ testGroup "Facelets"
[ testProperty "permutation-to-facelet" $
forAll (shuffle [0 .. 53]) (isJust . facelets')
, testGroupInstance genFacelets
, testProperty "facelet-colors" $
forAll genCenteredFacelets (\(colorFaceletsOf -> c) ->
(colorFacelets' . fromColorFacelets') c === Just c)
]
, testGroup "Cubie"
[ testGroup "CornerPermu"
[ testGenerator genCornerPermu (cornerPermu . fromCornerPermu)
, testGroupInstance genCornerPermu
, testCubeAction genCornerPermu genCubeFull
]
, testGroup "CornerOrien"
[ testGenerator genCornerOrienFull (cornerOrien . fromCornerOrien)
, testCubeAction genCornerOrienFull genCubeFull
]
, testGroup "Corner"
[ testGroupInstance genCornerFull
, testCubeAction genCornerFull genCubeFull
]
, testGroup "EdgePermu"
[ testGenerator genEdgePermu (edgePermu . fromEdgePermu)
, testGroupInstance genEdgePermu
, testCubeAction genEdgePermu genCube
]
, testGroup "EdgeOrien"
[ testGenerator genEdgeOrien (edgeOrien . fromEdgeOrien)
]
, testGroup "Edge"
[ testGroupInstance genEdge
, testCubeAction genEdge genCube
]
, testGroup "Cube"
[ testGroupInstance genCubeFull
]
, testGroup "UDSlicePermu"
[ testGenerator genUDSlicePermu (uDSlicePermu . fromUDSlicePermu)
, testCubeAction genUDSlicePermu genCube
]
, testGroup "UDSlice"
[ testGenerator genUDSlice (uDSlice . fromUDSlice)
, testCubeAction genUDSlice genCube
]
, testGroup "UDSlicePermu2"
[ testGenerator genUDSlicePermu2 (uDSlicePermu2 . fromUDSlicePermu2)
, testCubeAction genUDSlicePermu2 genCubeUDFixFull
]
, testGroup "UDEdgePermu2"
[ testGenerator genUDEdgePermu2 (uDEdgePermu2 . fromUDEdgePermu2)
, testCubeAction genUDEdgePermu2 genCubeUDFixFull
]
, testGroup "EdgePermu2"
[ testGenerator genEdgePermu2 (edgePermu . fromEdgePermu)
]
, testGroup "FlipUDSlicePermu"
[ testConjugate genCubeUDFixSym genCubeFull conjugateFlipUDSlicePermu
]
, testGroup "ToFacelet"
[ testGroupMorphism genCubeFull toFacelet
]
]
, testGroup "Coord"
[ testCoord "CornerPermu"
genCornerPermu (cornerPermu . fromCornerPermu)
, testCoord "CornerOrien"
genCornerOrien (cornerOrien . fromCornerOrien)
, testCoord "EdgePermu"
genEdgePermu (edgePermu . fromEdgePermu)
, testCoord "EdgeOrien"
genEdgeOrien (edgeOrien . fromEdgeOrien)
, testCoord "UDSlicePermu"
genUDSlicePermu (uDSlicePermu . fromUDSlicePermu)
, testCoord "UDSlice"
genUDSlice (uDSlice . fromUDSlice)
, testCoord "UDSlicePermu2"
genUDSlicePermu2 (uDSlicePermu2 . fromUDSlicePermu2)
, testCoord "UDEdgePermu2"
genUDEdgePermu2 (uDEdgePermu2 . fromUDEdgePermu2)
, testCoord "FlipUDSlicePermu"
genFlipUDSlicePermu Just
]
, testGroup "Moves"
[ testMoves ""
"UUUUUUUUU LLLLLLLLL FFFFFFFFF RRRRRRRRR BBBBBBBBB DDDDDDDDD"
, testMoves "uuuu"
"UUUUUUUUU LLLLLLLLL FFFFFFFFF RRRRRRRRR BBBBBBBBB DDDDDDDDD"
, testMoves "u"
"UUUUUUUUU FFFLLLLLL RRRFFFFFF BBBRRRRRR LLLBBBBBB DDDDDDDDD"
, testMoves "l"
"BUUBUUBUU LLLLLLLLL UFFUFFUFF RRRRRRRRR BBDBBDBBD FDDFDDFDD"
, testMoves "f"
"UUUUUULLL LLDLLDLLD FFFFFFFFF URRURRURR BBBBBBBBB RRRDDDDDD"
, testMoves "r"
"UUFUUFUUF LLLLLLLLL FFDFFDFFD RRRRRRRRR UBBUBBUBB DDBDDBDDB"
, testMoves "b"
"RRRUUUUUU ULLULLULL FFFFFFFFF RRDRRDRRD BBBBBBBBB DDDDDDLLL"
, testMoves "d"
"UUUUUUUUU LLLLLLBBB FFFFFFLLL RRRRRRFFF BBBBBBRRR DDDDDDDDD"
, testMoves "ulfrbd"
"LBBBURFFR ULRULDDDD UUBFFDBLD UULRRDFFD UUFBBLRRF LFRLDRLBB"
, testCube "sURF" surf3
"FFFFUFFFF DDDDLDDDD RRRRFRRRR UUUURUUUU LLLLBLLLL BBBBDBBBB"
, testCube "sF" sf2
"DDDDUDDDD RRRRLRRRR FFFFFFFFF LLLLRLLLL BBBBBBBBB UUUUDUUUU"
, testCube "sU" su4
"UUUUUUUUU FFFFLFFFF RRRRFRRRR BBBBRBBBB LLLLBLLLL DDDDDDDDD"
, testCube "sLR" slr2
"UUUUUUUUU RRRRLRRRR FFFFFFFFF LLLLRLLLL BBBBBBBBB DDDDDDDDD"
]
]
, testGroup "Tables"
[ testGroup "Moves"
[ testMoveTables "move18CornerPermu"
move18 move18CornerPermu
, testMoveTables "move18CornerOrien"
move18 move18CornerOrien
, testMoveTables "move18EdgeOrien"
move18 move18EdgeOrien
, testMoveTables "move18UDSlicePermu"
move18 move18UDSlicePermu
, testMoveTables "move18UDSlice"
move18 move18UDSlice
, testMoveTables "move10UDSlicePermu2"
move10 move10UDSlicePermu2
, testMoveTables "move10UDEdgePermu2"
move10 move10UDEdgePermu2
]
, testUDSlicePermu
, testFlipUDSlicePermu
, testRawToSymFlipUDSlicePermu
, testSymReprTable "srFUDSP"
reprFlipUDSlicePermu conjugateFlipUDSlicePermu
, testMoveSymTables "msFUDSP" move18 move18SymFlipUDSlicePermu
]
]
-- * Facelets
genFacelets = unsafeFacelets' <$> shuffle [0 .. 53]
-- | Centers remain fixed
genCenteredFacelets = unsafeFacelets' <$> do
let chunks = chunksOf 9 [4 .. 53]
shuffled <- (shuffle . ([0 .. 3] ++) . concat . fmap tail) chunks
let (x, y) = splitAt 4 shuffled
facelets = (x ++) . concat . zipWith (:) (fmap head chunks) . chunksOf 8
return (facelets y)
-- * Cubies
genCornerPermu = unsafeCornerPermu' <$> shuffle [0 .. 7]
genCornerOrien = unsafeCornerOrien'
. (\x -> (3 - sum x) `mod` 3 : x) <$> replicateM 7 (Gen.choose (0, 2))
genCornerOrienFull = unsafeCornerOrien' <$> replicateM 8 (Gen.choose (0,5))
genCorner = liftA2 Corner genCornerPermu genCornerOrien
genCornerFull = liftA2 Corner genCornerPermu genCornerOrienFull
genEdgePermu = unsafeEdgePermu' <$> shuffle [0 .. 11]
genEdgeOrien = unsafeEdgeOrien'
. (\x -> sum x `mod` 2 : x) <$> replicateM 11 (Gen.choose (0, 1))
genEdge = liftA2 Edge genEdgePermu genEdgeOrien
genCube = liftA2 Cube genCorner genEdge
genCubeFull = liftA2 Cube genCornerFull genEdge
genCubeSolvable = genCube `suchThat` solvable
genUDSlicePermu = unsafeUDSlicePermu' . take 4 <$> shuffle [0 .. 11]
genUDSlice = unpermuUDSlice <$> genUDSlicePermu
genUDSlicePermu2 = unsafeUDSlicePermu2' <$> shuffle [0 .. 3]
genUDEdgePermu2 = unsafeUDEdgePermu2' <$> shuffle [0 .. 7]
genEdgePermu2 = liftA2 edgePermu2 genUDSlicePermu2 genUDEdgePermu2
genEdge2 = liftA2 Edge genEdgePermu2 genEdgeOrien
genFlipUDSlicePermu = liftA2 (,) genUDSlicePermu genEdgeOrien
genCubeUDFixFull = liftA2 Cube genCornerFull genEdge2
genCubeUDFixSym = elements sym16'
testConjugate :: (FromCube a, Eq a, Show a)
=> Gen Cube -> Gen Cube -> (Cube -> a -> a) -> Test
testConjugate genSym genCube conj
= testProperty "conjugate" $
forAll genSym $ \s -> forAll genCube $ \c ->
fromCube (inverse s <> c <> s) === conj s (fromCube c)
-- * Coord
testCoord :: forall a. (RawEncodable a, Show a, Eq a)
=> String -> Gen a -> (a -> Maybe a) -> Test
testCoord name gen check = testGroup name $
[ testProperty "coord-bijection-1" $
forAll genCoord $ join ((===) . encode . decode)
, testProperty "coord-bijection-2" $
forAll gen $ join ((===) . decode . encode)
, testProperty "coord-range" $
forAll gen $ liftA2 (&&) (range gen >) (>= 0) . unRawCoord . encode
, testProperty "coord-correct" $
forAll genCoord $ isJust . check . decode
]
where
genCoord = RawCoord <$> Gen.choose (0, range gen-1) :: Gen (RawCoord a)
testMoveTables :: (CubeAction a, RawEncodable a)
=> String -> MoveTag m [Cube] -> MoveTag m [RawMove a]
-> Test
testMoveTables name (MoveTag cubes) (MoveTag moves)
= testProperty name $
conjoin $ zipWith propMoveTable1 cubes moves
propMoveTable1 :: forall a. (CubeAction a, RawEncodable a)
=> Cube -> RawMove a -> Property
propMoveTable1 c m'@(RawMove m)
= forAll genCoord $ \x ->
RawCoord (m P.! unRawCoord x)
=== (encode . (`cubeAction` c) . decode) x
where
genCoord = RawCoord <$> Gen.choose (0, range m'-1) :: Gen (RawCoord a)
-- * Moves
testMoves :: String -> String -> Test
testMoves moves result = '.' : moves ~:
(stringOfCubeColors . moveToCube <$> stringToMove moves) ~?= Right result
testCube :: String -> Cube -> String -> Test
testCube name c result = name ~: stringOfCubeColors c ~?= result
-- * Move tables
-- ** FlipUDSlice implementation
testUDSlicePermu
= testProperty "UDSlicePermu" $
forAll (Gen.choose (0, 15)) $ \c -> forAll genUDSlicePermu $ \udsp ->
conjugateUDSlicePermu (sym16' !! c) udsp
=== conjugateUDSlicePermu' (SymCode c) udsp
testFlipUDSlicePermu
= testProperty "FlipUDSlicePermu" $
forAll (Gen.choose (0, 15)) $ \c -> forAll genFlipUDSlicePermu $ \fudsp ->
counterexample ((show $ sym16' !! c) ++ "XXQS") $
conjugateFlipUDSlicePermu (sym16' !! c) fudsp
=== conjugateFlipUDSlicePermu' (SymCode c) fudsp
testRawToSymFlipUDSlicePermu
= testProperty "raw-to-sym-fudsp" $
forAll genCoordFUDSP $ \z ->
let (SymClass c, sc) = rawToSymFlipUDSlicePermu z
in encode
( conjugateFlipUDSlicePermu' sc
. decode . RawCoord
$ unSymClassTable classFlipUDSlicePermu P.! c)
=== z
where
genCoordFUDSP = RawCoord <$> Gen.choose (0, range ([] :: [FlipUDSlicePermu]) -1)
testMoveSymTables :: ()
=> String -> MoveTag m [Cube] -> MoveTag m [SymMove UDFix FlipUDSlicePermu]
-> Test
testMoveSymTables name (MoveTag cubes) (MoveTag moves)
= testProperty name $
conjoin $ zipWith propMoveSymTable1 cubes moves
propMoveSymTable1 c (SymMove m)
-- = forAll (Gen.choose (0, P.length m-1)) $ \x ->
= case G.find (\x -> x >= 16 * P.length m) m of
Nothing -> property True
Just x -> counterexample (show (x, P.length m)) False
testSymReprTable name (SymReprTable repr) conj
= testProperty name $
forAll (Gen.choose (0, P.length repr-1)) $ \x ->
let y = repr P.! x
(r, i) = y `divMod` 16
in (encode . conj (sym16' !! i) . decode . RawCoord) r
=== RawCoord x
-- * Typeclass laws
testMonoid0 :: (Monoid a, Eq a, Show a) => proxy a -> Test
testMonoid0 proxy =
"mempty-mappend-mempty" ~:
mempty <> mempty ~?= mempty `asProxyTypeOf` proxy
testMonoid :: (Monoid a, Eq a, Show a) => Gen a -> Test
testMonoid gen = testGroup "Monoid"
[ testProperty "left-identity" $
forAll gen (\x -> mempty <> x === x)
, testProperty "right-identity" $
forAll gen (\x -> x <> mempty === x)
, testProperty "associativity" $
forAll gen $ \x -> forAll gen $ \y -> forAll gen $ \z ->
(x <> y) <> z === x <> (y <> z)
, testMonoid0 gen
]
testGroup0 :: (Group a, Eq a, Show a) => proxy a -> Test
testGroup0 proxy =
"inverse-mempty" ~:
inverse mempty ~?= mempty `asProxyTypeOf` proxy
testGroupInstance :: (Group a, Eq a, Show a) => Gen a -> Test
testGroupInstance gen = testGroup "Group"
[ testProperty "inverse-left" $
forAll gen (\x -> inverse x <> x === mempty)
, testProperty "inverse-right" $
forAll gen (\x -> x <> inverse x === mempty)
, testGroup0 gen
, testMonoid gen
]
testMonoidMorphism :: (Monoid a, Monoid b, Eq a, Eq b, Show a, Show b)
=> Gen a -> (a -> b) -> Test
testMonoidMorphism gen f = testGroup "MonoidM"
[ "morphism-iden" ~: f mempty ~?= mempty
, testProperty "morphism-compose" $
forAll gen $ \x -> forAll gen $ \y ->
f (x <> y) === f x <> f y
]
testGroupMorphism :: (Group a, Group b, Eq a, Eq b, Show a, Show b)
=> Gen a -> (a -> b) -> Test
testGroupMorphism gen f = testGroup "GroupM"
[ testMonoidMorphism gen f
, testProperty "morphism-inverse" $
forAll gen $ \x -> (inverse . f) x === (f . inverse) x
]
testCubeAction
:: (CubeAction a, FromCube a, Eq a, Show a)
=> Gen a -> Gen Cube -> Test
testCubeAction gen genCube = testGroup "CubeAction"
[ testProperty "id-cube-action" $
forAll gen $ \x -> cubeAction x iden === x
, testProperty "from-cube-action" $
forAll genCube $ \x -> forAll genCube $ \c ->
cubeAction (fromCube x) c === fromCube (x <> c) `asProxyTypeOf` gen
]
testGenerator :: (Eq a, Show a) => Gen a -> (a -> Maybe b) -> Test
testGenerator gen p = testProperty "generator" $ forAll gen (isJust . p)
-- * Utilities
-- Qualify test names
rename :: [Test] -> [Test]
rename = fmap (rename' "")
rename' :: String -> Test -> Test
rename' pfx (Test t) = Test t{ name = pfx ++ name t }
rename' pfx (Group name conc tests)
= Group name conc (fmap (rename' (pfx ++ name ++ "/")) tests)
rename' pfx (ExtraOptions opts test) = ExtraOptions opts (rename' pfx test)
filterTests :: [Test] -> IO [Test]
filterTests tests = do
getArgs <&> \case
[] -> tests
pfxs -> filterTests' pfxs tests
filterTests' pfxs = (>>= filterTest pfxs)
filterTest pfxs test@(Test t) = [test | any (`isPrefixOf` name t) pfxs]
filterTest pfxs (Group name conc tests)
= let tests' = filterTests' pfxs tests
in [Group name conc tests' | (not . null) tests']
filterTest pfxs (ExtraOptions opts test) = ExtraOptions opts <$> filterTest pfxs test
|
Lysxia/twentyseven
|
test/Test.hs
|
mit
| 14,319 | 0 | 18 | 3,353 | 4,187 | 2,164 | 2,023 | 312 | 2 |
----------------------------------------
-- |
-- Module : Data.InfiniteSet
-- License : MIT
--
-- Maintainer : Joomy Korkut <[email protected]>
-- Stability : experimental
-- Portability : portable
--
-- An experimental infinite set implementation.
-- Important: This structure can contain repeated elements in a set.
-- This contradicts the essence of sets, but since herbrand-prolog
-- doesn't use delete, we can ignore this issue, because
-- checking for repeated elements is too costly.
-- Especially in infinite sets, things go crazy pretty quickly.
----------------------------------------
module Data.InfiniteSet
(
-- data type itself
Set
-- Query
, null , size , member
-- Construction
, notMember , empty , singleton , insert , delete
-- Combine
, union , unions
-- Map
, map
-- Conversion
, toList , fromList) where
import Prelude hiding (map, null)
import qualified Data.List as L
data Set a = Set [a]
| Union [Set a]
deriving (Show, Eq)
-- Query
-- | O(1). Is this the empty set?
null :: Set a -> Bool
null (Set []) = True
null (Union []) = True
null _ = False
-- | The number of elements in the set.
-- Will not terminate if the set is infinite, use at your own risk.
size :: Set a -> Int
size (Set xs) = length xs
size (Union xs) = sum $ L.map size xs
-- | Is the element in the set?
-- If the set is infinite and the element is not found,
-- it will never terminate, use at your own risk.
member :: Eq a => a -> Set a -> Bool
member x (Set xs) = x `elem` xs
-- TODO: This should be implemented in the way described in the blog post
member x (Union xs) = any (member x) xs
-- | Is the element not in the set?
-- If the set is infinite and the element is not found,
-- it will never terminate, use at your own risk.
notMember :: Eq a => a -> Set a -> Bool
notMember x s = not $ member x s
-- Construction
-- | O(1). The empty set.
empty :: Set a
empty = Set []
-- | O(1). Create a singleton set.
singleton :: a -> Set a
singleton x = Set [x]
-- | Insert an element in a set.
-- If the set already contains an element equal to the given value,
-- it is replaced with the new value.
insert :: a -> Set a -> Set a
insert x (Set xs) = Set (x:xs)
insert x (Union []) = singleton x
insert x (Union (y:ys)) = Union $ insert x y : ys
-- | Delete an element from a set.
-- If the set already contains an element equal to the given value,
-- it is replaced with the new value.
delete :: Eq a => a -> Set a -> Set a
delete x (Set xs) = Set $ filter (== x) xs
delete x (Union xs) = Union $ L.map (delete x) xs
-- Combine
-- | The union of two sets.
union :: Set a -> Set a -> Set a
union x@(Set xs) y@(Set ys) = Union [x, y]
union x@(Set xs) y@(Union ys) = Union (x:ys)
union x@(Union xs) y@(Set ys) = y `union` x
union x@(Union xs) y@(Union ys) = Union [x, y] -- this might change
-- | The union of a list of sets.
unions :: [Set a] -> Set a
unions = foldl union empty
-- Map
-- map f s is the set obtained by applying f to each element of s.
map :: (a -> b) -> Set a -> Set b
map f (Set xs) = Set $ L.map f xs
map f (Union xs) = Union $ L.map (map f) xs
-- Conversion
-- | Convert the set to a list of elements.
toList :: Set a -> [a]
toList (Set xs) = xs
toList (Union xs) = concatMap toList xs
-- | Create a set from a list of elements.
fromList :: Eq a => [a] -> Set a
fromList = Set
|
joom/herbrand-prolog
|
src/Data/InfiniteSet.hs
|
mit
| 3,423 | 0 | 9 | 818 | 967 | 524 | 443 | 51 | 1 |
module Solidran.Fib.DetailSpec (spec) where
import Test.Hspec
import Solidran.Fib.Detail
spec :: Spec
spec = do
describe "Solidran.Fib.Detail" $ do
describe "nextPair" $ do
it "should correctly calculate the next sequence" $ do
nextPair 1 (0, 1) `shouldBe` (1, 1)
nextPair 1 (1, 1) `shouldBe` (1, 2)
nextPair 1 (1, 2) `shouldBe` (2, 3)
nextPair 1 (2, 3) `shouldBe` (3, 5)
nextPair 1 (3, 5) `shouldBe` (5, 8)
describe "rabbitsCount" $ do
it "should correctly calculate the rabbits count" $ do
rabbitsCount 5 2 `shouldBe` 11
rabbitsCount 5 3 `shouldBe` 19
|
Jefffrey/Solidran
|
test/Solidran/Fib/DetailSpec.hs
|
mit
| 713 | 0 | 18 | 247 | 241 | 130 | 111 | 17 | 1 |
module Main where
import Network
import Control.Monad
import Control.Concurrent
import System.IO
import Text.Printf
import Control.Exception
import Control.Concurrent.Async
import Control.Concurrent.STM
import ConcurrentUtils (forkFinally)
main :: IO ()
main = withSocketsDo $ do
sock <- listenOn (PortNumber (fromIntegral port))
printf "Listening on port %d\n" port
factor <- atomically $ newTVar 2
forever $ do
(handle, host, port) <- accept sock
printf "Accepted connection from %s:%s\n" host (show port)
forkFinally (talk handle factor) (\_ -> hClose handle)
port :: Int
port = 44444
talk :: Handle -> TVar Integer -> IO ()
talk h factor = do
hSetBuffering h LineBuffering
c <- atomically newTChan
race (server h factor c) (receive h c)
return ()
receive :: Handle -> TChan String -> IO ()
receive h c = forever $ do
line <- hGetLine h
atomically $ writeTChan c line
server :: Handle -> TVar Integer -> TChan String -> IO ()
server h factor c = do
f <- atomically $ readTVar factor
hPrintf h "Current factor: %d\n" f
loop f
where
loop f = join $ atomically $ do
f' <- readTVar factor
if f /= f'
then return (newfactor f')
else do
l <- readTChan c
return (command f l)
newfactor f = do
hPrintf h "new factor: %d\n" f
loop f
command f s =
case s of
"end" -> hPutStrLn h ("Thank you for using the " ++
"Haskell doubling service")
'*': s -> do
atomically $ writeTVar factor (read s :: Integer)
loop f
line -> do
hPrint h (f * (read line :: Integer))
loop f
|
Forec/learn
|
2017.3/Parallel Haskell/ch12/server2.hs
|
mit
| 1,645 | 0 | 16 | 447 | 609 | 290 | 319 | 56 | 4 |
module Sing where
fstString :: [Char] -> [Char]
fstString x = x ++ " in the rain"
sndString :: [Char] -> [Char]
sndString x = x ++ " over the rainbow"
sing = if (x > y) then fstString x
else sndString y
where x = "Singin"
y = "Somewhere"
|
Numberartificial/workflow
|
haskell-first-principles/haskell-from-first-principles-master/05/05.08.07-fix-it-1.hs
|
mit
| 257 | 0 | 7 | 69 | 96 | 54 | 42 | 9 | 2 |
{-# LANGUAGE NoImplicitPrelude #-}
module Lib.List (filterA, unprefixed, unsuffixed, partitionA) where
import Data.List (isPrefixOf, isSuffixOf)
import Prelude.Compat
filterA :: Applicative f => (a -> f Bool) -> [a] -> f [a]
filterA p = go
where
go [] = pure []
go (x:xs) = combine <$> p x <*> go xs
where
combine True rest = x : rest
combine False rest = rest
partitionA :: Applicative f => (a -> f Bool) -> [a] -> f ([a], [a])
partitionA p =
fmap mconcat . traverse onEach
where
onEach x = partitionOne x <$> p x
partitionOne x True = ([x], [])
partitionOne x False = ([], [x])
unprefixed :: Eq a => [a] -> [a] -> Maybe [a]
unprefixed prefix full
| prefix `isPrefixOf` full = Just $ drop (length prefix) full
| otherwise = Nothing
unsuffixed :: Eq a => [a] -> [a] -> Maybe [a]
unsuffixed suffix full
| suffix `isSuffixOf` full = Just $ take (length full - length suffix) full
| otherwise = Nothing
|
sinelaw/buildsome
|
src/Lib/List.hs
|
gpl-2.0
| 964 | 0 | 10 | 233 | 449 | 232 | 217 | 24 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
module Glance.Web.Image
where
import Common (fromObject, underscoreOptions)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Aeson ( object, (.=), FromJSON(..), Value(..), ToJSON(..))
import Data.Aeson.TH (mkParseJSON)
import Data.HashMap.Strict (insert)
import Data.Maybe (fromMaybe)
import Data.String (IsString(fromString))
import Glance.Config (GlanceConfig(database))
--import Glance.Model.Image (createImage)
import Glance.Web.Image.Types (ImageCreateRequest(..))
import Network.HTTP.Types.Status (status200, status204, status404)
import Web.Common (ActionM, parseRequest, parseId, parseMaybeString)
import qualified Error as E
import qualified Data.ByteString.Lazy as LB
import qualified Database.MongoDB as M
import qualified Glance.Model.Image as MI
import qualified Model.Mongo.Common as CD
import qualified Web.Scotty.Trans as S
listImagesH :: (Functor m, MonadIO m) => GlanceConfig -> ActionM m ()
listImagesH config = do
imageName <- parseMaybeString "name"
images <- liftIO $ CD.withDB (database config) $ MI.listImages imageName
S.status status200
S.json $ object [ "images" .= (map (fromObject . toJSON) images)
, "schema" .= ("/v2/schemas/images" :: String)
, "first" .= ("/v2/images" :: String)]
createImageH :: (Functor m, MonadIO m) => GlanceConfig -> ActionM m ()
createImageH config = do
(d :: ImageCreateRequest) <- parseRequest
image <- liftIO $ newRequestToImage d
liftIO $ putStrLn $ show image
liftIO $ CD.withDB (database config) $ MI.createImage image
S.status status200
S.json $ produceImageJson image
imageDetailsH :: (Functor m, MonadIO m) => GlanceConfig -> ActionM m ()
imageDetailsH config = do
(iid :: M.ObjectId) <- parseId "iid"
mImage <- liftIO $ CD.withDB (database config) $ MI.findImageById iid
case mImage of
Nothing -> do
S.status status404
S.json $ E.notFound "Image not found"
Just image -> do
S.status status200
S.json $ produceImageJson image
uploadImageH :: (Functor m, MonadIO m) => GlanceConfig -> ActionM m ()
uploadImageH config = do
(iid :: M.ObjectId) <- parseId "iid"
s <- S.body
liftIO $ LB.writeFile (show iid) s
S.status status204
downloadImageH :: (Functor m, MonadIO m) => GlanceConfig -> ActionM m ()
downloadImageH config = do
(iid :: M.ObjectId) <- parseId "iid"
S.setHeader "Content-Type" "application/octet-stream"
S.status status200
S.file $ show iid
newRequestToImage :: ImageCreateRequest -> IO MI.Image
newRequestToImage ImageCreateRequest{..} = do
imageId <- M.genObjectId
return $ MI.Image
imageId
name
(fromMaybe MI.Private visibility)
MI.Queued
(fromMaybe [] tags)
containerFormat
diskFormat
(fromMaybe 0 minDisk)
(fromMaybe 0 minRam)
(fromMaybe False protected)
instance FromJSON ImageCreateRequest where
parseJSON v = parseIcr v
parseIcr = $(mkParseJSON underscoreOptions ''ImageCreateRequest)
produceImageJson :: MI.Image -> Value
produceImageJson ([email protected]{..})
= Object
$ insert "self" (String $ fromString $ "/v2/images/" ++ (show _id))
$ insert "schema" (String $ "/v2/schemas/image")
$ fromObject $ toJSON image
|
VictorDenisov/keystone
|
src/Glance/Web/Image.hs
|
gpl-2.0
| 3,466 | 0 | 14 | 720 | 1,088 | 572 | 516 | 84 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module EightTracks.Config
( Config(..)
, withConfig
, apiKey
) where
import Data.ByteString
import Data.Configurator
import Data.Text
data Config = Config { getLogin :: Text
, getPassword :: Text
}
withConfig :: (Config -> IO ()) -> IO ()
withConfig f = do
config <- load [ Required "$(HOME)/.8tracksrc" ]
l <- require config "login" :: IO Text
p <- require config "password" :: IO Text
let c = Config l p
f c
apiKey :: ByteString
apiKey = "6d61f31b0ff438fecf0cdd2bde3c9822eedeb4bb"
|
vikraman/8tracks
|
src/EightTracks/Config.hs
|
gpl-3.0
| 606 | 0 | 10 | 171 | 174 | 91 | 83 | 19 | 1 |
{-# LANGUAGE OverloadedStrings, ViewPatterns, DeriveGeneric #-}
module Data.TPG where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Char (isSpace)
import Data.String (fromString)
import Data.List (stripPrefix, isSuffixOf, elemIndex)
import Text.Printf (printf)
import Data.Maybe (fromJust)
import Control.Lens
import Control.Arrow
import Network.Wreq
import Network.Wreq.Types
import qualified Network.Wreq.Session as S
import Text.XML.HXT.Core
import Text.XML.HXT.Arrow.XmlArrow (getAttrValue)
import qualified Text.XML.HXT.DOM.XmlNode as XN
import Data.Tree.NTree.TypeDefs (NTree(..))
import Text.HandsomeSoup
import Data.Binary
import GHC.Generics (Generic)
baseUrl = "https://cyberstore.tpg.com.au/your_account/"
indexUrl = baseUrl ++ "index.php"
-- Type describing a month of billing.
data BillingPeriod = BillingPeriod String Int deriving (Show, Generic)
-- Type describing a single charge/cost.
-- Charge (time of charge) (plan cost in cents) (excess cost in cents) (info)
data Charge = Charge {
time :: String,
otherNetworkCost :: Int,
sameNetworkCost :: Int,
excessCost :: Int,
chargeInfo :: ChargeInfo
} deriving (Show, Generic)
-- Type describing the reason for a charge.
data ChargeInfo =
--- Sms (number)
Sms String |
-- Call (type) (number) (duration in seconds)
Call CallType String Int |
-- Data (usage in kB)
Data Int |
-- Voicemail (number) (duration in seconds)
Voicemail String Int |
-- Other charges.
Other String |
-- Parsing errors.
Error String deriving (Show, Generic)
data CallType = Mobile | Landline | Tpg | OneThree deriving (Show, Generic)
-- Serialisation instances.
instance Binary BillingPeriod
instance Binary Charge
instance Binary ChargeInfo
instance Binary CallType
isSms (chargeInfo -> Sms _) = True
isSms _ = False
isCall (chargeInfo -> Call _ _ _) = True
isCall _ = False
isMobileCall (chargeInfo -> Call Mobile _ _) = True
isMobileCall _ = False
isLandlineCall (chargeInfo -> Call Landline _ _) = True
isLandlineCall _ = False
isTpgCall (chargeInfo -> Call Tpg _ _) = True
isTpgCall _ = False
isData (chargeInfo -> Data _) = True
isData _ = False
isVoicemail (chargeInfo -> Voicemail _ _) = True
isVoicemail _ = False
isOther (chargeInfo -> Other _) = True
isOther _ = False
isParseError (chargeInfo -> Error _) = True
isParseError _ = False
planCost :: Charge -> Int
planCost c = otherNetworkCost c + sameNetworkCost c
-- Login to the TPG user panel.
login :: String -> String -> IO (S.Session)
login username password = S.withSession $ \sesh -> do
-- Login.
let loginData = ["check_username" := username,
"password" := password,
"password1" := ("Password" :: B.ByteString),
"x" := (0 :: Int),
"y" := (0 :: Int) ]
S.post sesh indexUrl loginData
return sesh
-- Fetch the list of billing periods for a given plan ID.
getBillingPeriods :: S.Session -> Int -> IO [BillingPeriod]
getBillingPeriods sesh planId = do
index <- downloadIndex sesh planId
parseIndex index planId
-- Download the page that lists billing periods.
downloadIndex :: S.Session -> Int -> IO (Response LB.ByteString)
downloadIndex sesh planId = do
-- Query params.
let opts = defaults & param "function" .~ ["view_all_mobile"]
-- POST data.
let planSelection = B.append "viewdetails-" (fromString (show planId))
S.postWith opts sesh indexUrl (planSelection := ("Mobile+Usage" :: B.ByteString))
-- Parse the index page to form a list of billing periods.
parseIndex :: Response LB.ByteString -> Int -> IO [BillingPeriod]
parseIndex response planId = do
nodes <- runX $ doc >>> css selector >>> (arr getInnerText &&& getAttrValue "href")
return (map createBillingPeriod nodes)
where
doc = responseToDoc response
linkPrefix = getLinkPrefix planId
selector = printf "a[href|=\"%s\"]" linkPrefix
createBillingPeriod (title, chargeId) = BillingPeriod title (createChargeId chargeId)
createChargeId = read . fromJust . (stripPrefix linkPrefix)
-- Get the string that appears at the beginning of all links for a given plan ID.
getLinkPrefix :: Int -> String
getLinkPrefix planId = printf "index.php?function=view_all_mobile&plan_id=%s&chg_id=" (show planId)
-- Get the charge data for a single billing period.
getDataForPeriod :: S.Session -> Int -> BillingPeriod -> IO [Charge]
getDataForPeriod sesh planId (BillingPeriod desc chargeId) = do
page <- S.get sesh pageUrl
let doc = responseToDoc page
rows <- runX $ doc >>> css "table[rules=all] tr" >>> arr createRow
return (map rowToCharge rows)
where
pageUrl = baseUrl ++ getLinkPrefix planId ++ show chargeId
-- Extract the string contents of an XML <tr> node's children.
createRow (NTree _ children) = map (trim . getInnerText) children
-- Fetch the text from within an XML node.
getInnerText :: NTree XNode -> String
getInnerText (NTree _ (inner:_)) = fromJust (XN.getText inner)
-- Convert a response to an XML document.
responseToDoc :: Response LB.ByteString -> IOSArrow b (NTree XNode)
responseToDoc res = (parseHtml . LB.unpack) (res ^. responseBody)
-- Parse a cost like $0.00 to a value in cents.
parseCost :: String -> Int
parseCost ('$':x) = round ((read x :: Float) * 100)
-- Parse a data value like 1.50MB to an integer value in decimal kilobytes.
parseDataUse :: String -> Int
parseDataUse s = round (mb * 1000)
where mb = (read . fromJust . stripSuffix "MB") s
-- Parse a duration in minutes like 10:15 to a duration in seconds.
parseDuration :: String -> Int
parseDuration s = (read minutes) * 60 + read seconds
where
colonIdx = fromJust (elemIndex ':' s)
(minutes, ':':seconds) = splitAt colonIdx s
-- Parse a call type string.
parseCallType :: String -> Maybe CallType
parseCallType "Call to landline" = Just Landline
parseCallType "Info Service" = Just Landline
parseCallType "Mobile Call" = Just Mobile
parseCallType "Call to non-Optus GSM" = Just Mobile
parseCallType "TPG Mobile to TPG Mobile" = Just Tpg
parseCallType "TPG Mobile to TPG Home Phone" = Just Tpg
parseCallType "13 Numbers" = Just OneThree
parseCallType _ = Nothing
-- Convert a row of a charge table into a charge.
rowToCharge :: [String] -> Charge
-- Pay as you go format (6 columns).
rowToCharge [time, ty, value, number, inc, excess] =
Charge time (parseCost inc) 0 (parseCost excess) (createChargeInfo ty value number)
-- Monthly plan format (8 columns).
rowToCharge [time, ty, value, number, _, other, tpg, excess] =
Charge time (parseCost other) (parseCost tpg) (parseCost excess) ci
where ci = createChargeInfo ty value number
rowToCharge _ = Charge "" 0 0 0 $ Error "irregular row not understood"
createChargeInfo :: String -> String -> String -> ChargeInfo
createChargeInfo "SMS National" _ number = Sms number
createChargeInfo v duration number
| v `elem` ["Voicemail Deposit", "Voicemail Retrieval"] =
Voicemail number (parseDuration duration)
createChargeInfo d mb _
| d `elem` ["Data", "Data (Volume based)"] = Data $ parseDataUse mb
createChargeInfo (parseCallType -> Just ty) duration number =
Call ty number (parseDuration duration)
createChargeInfo desc _ _ = Other desc
-- Download the charges for a single (numbered) billing period.
downloadSingle :: String -> String -> Int -> Int -> IO (BillingPeriod, [Charge])
downloadSingle username password planId i = do
sesh <- login username password
bps <- getBillingPeriods sesh planId
let bp = bps !! i
charges <- getDataForPeriod sesh planId bp
return (bp, charges)
-- Download all the charges for a given plan ID.
downloadAll :: String -> String -> Int -> IO [(BillingPeriod, [Charge])]
downloadAll username password planId = do
sesh <- login username password
bps <- getBillingPeriods sesh planId
charges <- mapM (getDataForPeriod sesh planId) bps
return (zip bps charges)
totalBy :: (Charge -> Int) -> (Charge -> Bool) -> [[Charge]] -> [Int]
totalBy cost p charges = map (sum . map cost . filter p) charges
avg :: [Int] -> Double
avg l = fromIntegral (sum l) / fromIntegral (length l)
-- Inefficient trim function.
trim :: String -> String
trim = f . f
where f = reverse . dropWhile isSpace
-- Remove a suffix from a list.
stripSuffix :: Eq a => [a] -> [a] -> Maybe [a]
stripSuffix s l = if s `isSuffixOf` l then Just $ take (length l - length s) l else Nothing
|
michaelsproul/tpg-analyser
|
src/Data/TPG.hs
|
gpl-3.0
| 8,545 | 0 | 15 | 1,684 | 2,446 | 1,283 | 1,163 | 161 | 2 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
module Data.Dist.Internal
( SDist
, expected
, extractSingleton
, nonZeroPieces
, normalize
, sample
, singleton
, withProbability
) where
import Control.Arrow (first)
import Control.Monad.Random (Randomizable, getUniform)
import Data.List (find)
import Data.List.NonEmpty (NonEmpty((:|)))
import qualified Data.List.NonEmpty as NonEmpty
import Data.Maybe (fromJust)
import Data.Vector.Class (Vector)
import qualified Data.Vector.Class as Vector
newtype SDist a = SDist { pieces :: NonEmpty (Float, a) }
deriving (Functor, Show)
singleton :: a -> SDist a
singleton x = SDist $ (1, x) :| []
extractSingleton :: SDist a -> Maybe a
extractSingleton (SDist ((_, x) :| [])) = Just x
extractSingleton _ = Nothing
normalize :: NonEmpty (Float, a) -> SDist a
normalize xs
| total <= 0 = SDist $ NonEmpty.map (first (const uniProb)) posified
| otherwise = SDist $ NonEmpty.map (\(d, x) -> (d / total, x)) posified
where
posified = NonEmpty.map (first (max 0)) xs
total = sum $ NonEmpty.map fst posified
uniProb :: Float
uniProb = 1 / fromIntegral (length xs)
expected :: (Vector a) => SDist a -> a
expected (SDist xs) = Vector.vsum [Vector.scale d x | (d, x) <- NonEmpty.toList xs, d /= 0]
accumsOf :: SDist a -> NonEmpty (Float, a)
accumsOf (SDist xs) = NonEmpty.scanl1 (\(cur, _) (d, y) -> (cur + d, y)) xs
sample :: Randomizable m Float => SDist a -> m a
sample ds = do
let accumed = accumsOf ds
d <- getUniform
return $ snd $ fromJust $ find ((>= d) . fst) accumed
withProbability :: SDist a -> SDist (Float, a)
withProbability (SDist xs) = SDist $ NonEmpty.map (\(d, x) -> (d, (d, x))) xs
nonZeroPieces :: SDist a -> NonEmpty (Float, a)
nonZeroPieces = NonEmpty.fromList . filter ((/= 0) . fst) . NonEmpty.toList . pieces
|
davidspies/regret-solver
|
game/src/Data/Dist/Internal.hs
|
gpl-3.0
| 1,883 | 0 | 11 | 395 | 782 | 428 | 354 | 47 | 1 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 [email protected]
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Grid.Output.Fancy.ShadePath
(
shadePathBegin,
shadePathEnd,
shadePathAlpha,
shadePathColor,
shadePathRadius,
shadePathDraw,
shadePathDrawBegin,
shadePathDrawBeginEnd,
shadePathDrawPath0,
shadePathDrawPath0Begin,
shadePathDrawPath0BeginEnd,
shadePathDrawPath1,
shadePathDrawSegment,
shadePathDrawLine,
) where
import MyPrelude
import Game
import Game.Grid
import Game.Data.Color
import OpenGL
import OpenGL.Helpers
-- fixme: begin relative to pathArrayBegin/End!!
--------------------------------------------------------------------------------
-- begin/end shadePath
shadePathBegin :: ShadePath -> Float -> Mat4 -> IO ()
shadePathBegin sh alpha projmodv = do
glUseProgram $ shadePathPrg sh
glDepthMask gl_FALSE
glBlendFuncSeparate gl_ONE gl_ONE
gl_ZERO gl_ONE
-- vao
glBindVertexArrayOES $ shadePathVAO sh
-- projmodv matrix
uniformMat4 (shadePathUniProjModvMatrix sh) projmodv
-- alpha
glUniform1f (shadePathUniAlpha sh) $ rTF alpha
-- bind the canonical texture
glActiveTexture gl_TEXTURE0
glBindTexture gl_TEXTURE_2D $ shadePathTex sh
shadePathEnd :: ShadePath -> IO ()
shadePathEnd sh = do
-- end blending
glBlendFuncSeparate gl_ONE gl_ONE_MINUS_SRC_ALPHA
gl_ONE gl_ONE_MINUS_SRC_ALPHA
glDepthMask gl_TRUE
--------------------------------------------------------------------------------
-- parameters
shadePathAlpha :: ShadePath -> Float -> IO ()
shadePathAlpha sh alpha = do
glUniform1f (shadePathUniAlpha sh) $ rTF alpha
shadePathColor :: ShadePath -> Color -> IO ()
shadePathColor sh color =
uniformColor (shadePathUniColor sh) color
shadePathRadius :: ShadePath -> Float -> IO ()
shadePathRadius sh r =
glUniform1f (shadePathUniRadius sh) $ rTF r
--------------------------------------------------------------------------------
-- draw Path
shadePathDraw :: ShadePath -> Path -> IO ()
shadePathDraw sh path =
shadePathDrawBegin sh (pathArrayBegin path) path
-- | draw Path beginning from array ix
shadePathDrawBegin :: ShadePath -> UInt -> Path -> IO ()
shadePathDrawBegin sh begin path = do
--assertIx "shadePathDrawBegin" path begin -- tmp
shadePathDrawPath0Begin sh begin path
shadePathDrawPath1 sh path
-- | drawing path in range [ix, ix'), alpha interpolates against ix'
shadePathDrawBeginEnd :: ShadePath -> UInt -> UInt -> Float -> Path -> IO ()
shadePathDrawBeginEnd sh begin end alpha path = do
--assertIx "shadePathDrawBeginEnd begin" path begin
--assertIx "shadePathDrawBeginEnd end" path end
-- path0
shadePathDrawPath0BeginEnd sh begin end path
-- path1
let current = if end == pathArrayEnd path
then pathCurrent path
else segmentarrayRead (pathArray path) end -- fixme: valid ix?
shadePathDrawSegment sh current alpha
--------------------------------------------------------------------------------
-- draw Path0
shadePathDrawPath0 :: ShadePath -> Path -> IO ()
shadePathDrawPath0 sh path =
shadePathDrawPath0Begin sh (pathArrayBegin path) path
shadePathDrawPath0Begin :: ShadePath -> UInt -> Path -> IO ()
shadePathDrawPath0Begin sh begin path = do
--assertIx "shadePathDrawPath0Begin" path begin
shadePathDrawPath0BeginEnd sh begin (pathArrayEnd path) path
shadePathDrawPath0BeginEnd :: ShadePath -> UInt -> UInt -> Path -> IO ()
shadePathDrawPath0BeginEnd sh begin end path = do
--assertIx "shadePathDrawPath0BeginEnd begin" path begin
--assertIx "shadePathDrawPath0BeginEnd end" path end
glBindBuffer gl_ARRAY_BUFFER $ pathoutputGLVBO $ pathPathOutput path
glVertexAttribPointer attPos 3 gl_SHORT gl_FALSE 16 $ mkPtrGLvoid 0
glVertexAttribPointer attAntiPos 3 gl_SHORT gl_FALSE 16 $ mkPtrGLvoid 8
--
{-
let size = pathArraySize path
abegin = pathArrayBegin path
begin' = (abegin + begin) `mod` size
end' = (abegin + end) `mod` size
end'' = begin' + ((end' + (size - begin')) `mod` size)
a0 = begin'
a1 = min end'' size
b0 = 0
b1 = (max end'' size) `mod` size
-}
let size = pathArraySize path
out = begin + (end + (size - begin)) `mod` size
a0 = begin
a1 = min size out
b0 = 0
b1 = (max size out) `mod` size
-- tmp
assertBE "a0 a1" begin end path a0 a1
assertBE "b0 b1" begin end path b0 b1
-- [a0, a1)
glDrawElements gl_TRIANGLE_STRIP (fI $ (8 + 2) * (a1 - a0)) gl_UNSIGNED_SHORT
(mkPtrGLvoid (fI $ 2 * (8 + 2) * a0))
-- [b0, b1)
glDrawElements gl_TRIANGLE_STRIP (fI $ (8 + 2) * (b1 - b0)) gl_UNSIGNED_SHORT
(mkPtrGLvoid (fI $ 2 * (8 + 2) * b0))
--debugGLError "shadePath"
where
assertBE tag begin end path b e = do
let size = pathArraySize path
when (size <= b) $ assertErr (tag ++ " (size <= b)")
when (size < e) $ assertErr (tag ++ " (size < e)")
where
assertErr tag = do
let size = pathArraySize path
abegin = pathArrayBegin path
begin' = (abegin + begin) `mod` size
end' = (abegin + end) `mod` size
end'' = begin' + ((end' + (size - begin')) `mod` size)
a0 = begin'
a1 = min end'' size
b0 = 0
b1 = (max end'' size) `mod` size
pathBegin = pathArrayBegin path
pathEnd = pathArrayEnd path
bufVBO <- getBufferSize gl_ARRAY_BUFFER $ pathoutputGLVBO
$ pathPathOutput path
putStrLn $ "VBO size: " ++ show bufVBO ++ " (/ 128 == "
++ show (div bufVBO 128) ++ ")"
putStrLn $ "pathArraySize: " ++ show size
putStrLn $ "pathArrayBegin: " ++ show pathBegin
putStrLn $ "pathArrayEnd: " ++ show pathEnd
putStrLn $ "begin: " ++ show begin
putStrLn $ "end: " ++ show end
putStrLn $ "end': " ++ show end'
putStrLn $ "a0: " ++ show a0
putStrLn $ "a1: " ++ show a1
putStrLn $ "b0: " ++ show b0
putStrLn $ "b1: " ++ show b1
putStrLn ""
getBufferSize tgt buf =
alloca $ \ptr -> do
glGetBufferParameteriv tgt gl_BUFFER_SIZE ptr
peek ptr
--------------------------------------------------------------------------------
-- draw Path1
shadePathDrawPath1 :: ShadePath -> Path -> IO ()
shadePathDrawPath1 sh path = do
shadePathDrawSegment sh (pathCurrent path) (pathAlpha path)
shadePathDrawSegment :: ShadePath -> Segment -> Float -> IO ()
shadePathDrawSegment sh segment alpha = do
case segment of
Segment (Node x y z) (Turn a0 a1 a2
_ _ _
_ _ _) ->
let xf = fI x
yf = fI y
zf = fI z
xf' = smooth xf (xf + fI a0) alpha
yf' = smooth yf (yf + fI a1) alpha
zf' = smooth zf (zf + fI a2) alpha
in shadePathDrawLine sh xf yf zf xf' yf' zf'
-- | draw a line
shadePathDrawLine :: ShadePath -> Float -> Float -> Float ->
Float -> Float -> Float -> IO ()
shadePathDrawLine sh x0 y0 z0 x1 y1 z1 = do
glBindBuffer gl_ARRAY_BUFFER $ shadePathPath1VBO sh
glBufferData gl_ARRAY_BUFFER (1 * 8 * 24) nullPtr gl_STREAM_DRAW
writeBuf gl_ARRAY_BUFFER $ \ptr -> do
-- pos
pokeByteOff ptr 0 (rTF x0 :: GLfloat)
pokeByteOff ptr 4 (rTF y0 :: GLfloat)
pokeByteOff ptr 8 (rTF z0 :: GLfloat)
pokeByteOff ptr 12 (rTF x1 :: GLfloat)
pokeByteOff ptr 16 (rTF y1 :: GLfloat)
pokeByteOff ptr 20 (rTF z1 :: GLfloat)
pokeByteOff ptr 24 (rTF x0 :: GLfloat)
pokeByteOff ptr 28 (rTF y0 :: GLfloat)
pokeByteOff ptr 32 (rTF z0 :: GLfloat)
pokeByteOff ptr 36 (rTF x1 :: GLfloat)
pokeByteOff ptr 40 (rTF y1 :: GLfloat)
pokeByteOff ptr 44 (rTF z1 :: GLfloat)
pokeByteOff ptr 48 (rTF x0 :: GLfloat)
pokeByteOff ptr 52 (rTF y0 :: GLfloat)
pokeByteOff ptr 56 (rTF z0 :: GLfloat)
pokeByteOff ptr 60 (rTF x1 :: GLfloat)
pokeByteOff ptr 64 (rTF y1 :: GLfloat)
pokeByteOff ptr 68 (rTF z1 :: GLfloat)
pokeByteOff ptr 72 (rTF x0 :: GLfloat)
pokeByteOff ptr 76 (rTF y0 :: GLfloat)
pokeByteOff ptr 80 (rTF z0 :: GLfloat)
pokeByteOff ptr 84 (rTF x1 :: GLfloat)
pokeByteOff ptr 88 (rTF y1 :: GLfloat)
pokeByteOff ptr 92 (rTF z1 :: GLfloat)
-- pos'
pokeByteOff ptr 96 (rTF x1 :: GLfloat)
pokeByteOff ptr 100 (rTF y1 :: GLfloat)
pokeByteOff ptr 104 (rTF z1 :: GLfloat)
pokeByteOff ptr 108 (rTF x0 :: GLfloat)
pokeByteOff ptr 112 (rTF y0 :: GLfloat)
pokeByteOff ptr 116 (rTF z0 :: GLfloat)
pokeByteOff ptr 120 (rTF x1 :: GLfloat)
pokeByteOff ptr 124 (rTF y1 :: GLfloat)
pokeByteOff ptr 128 (rTF z1 :: GLfloat)
pokeByteOff ptr 132 (rTF x0 :: GLfloat)
pokeByteOff ptr 136 (rTF y0 :: GLfloat)
pokeByteOff ptr 140 (rTF z0 :: GLfloat)
pokeByteOff ptr 144 (rTF x1 :: GLfloat)
pokeByteOff ptr 148 (rTF y1 :: GLfloat)
pokeByteOff ptr 152 (rTF z1 :: GLfloat)
pokeByteOff ptr 156 (rTF x0 :: GLfloat)
pokeByteOff ptr 160 (rTF y0 :: GLfloat)
pokeByteOff ptr 164 (rTF z0 :: GLfloat)
pokeByteOff ptr 168 (rTF x1 :: GLfloat)
pokeByteOff ptr 172 (rTF y1 :: GLfloat)
pokeByteOff ptr 176 (rTF z1 :: GLfloat)
pokeByteOff ptr 180 (rTF x0 :: GLfloat)
pokeByteOff ptr 184 (rTF y0 :: GLfloat)
pokeByteOff ptr 188 (rTF z0 :: GLfloat)
glVertexAttribPointer attPos 3 gl_FLOAT gl_FALSE 24 $ mkPtrGLvoid 0
glVertexAttribPointer attAntiPos 3 gl_FLOAT gl_FALSE 24 $ mkPtrGLvoid 12
-- draw!
glDrawElements gl_TRIANGLE_STRIP 8 gl_UNSIGNED_SHORT nullPtr
--------------------------------------------------------------------------------
--
{-
-- tmp
assertIx :: String -> Path -> UInt -> IO ()
assertIx tag path ix =
when (pathArraySize path <= ix) $ do
putStrLn $ tag ++ "assertIx with pathArraySize: " ++ show (pathArraySize path) ++
", ix: " ++ show ix
-}
|
karamellpelle/grid
|
source/Game/Grid/Output/Fancy/ShadePath.hs
|
gpl-3.0
| 11,540 | 0 | 20 | 3,510 | 2,862 | 1,410 | 1,452 | 192 | 2 |
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString as S
|
ljwolf/learnyouahaskell-assignments
|
sysrand.hs
|
gpl-3.0
| 81 | 0 | 4 | 10 | 18 | 13 | 5 | 2 | 0 |
module Main where
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy as BL
import Lib
main :: IO ()
main = do
let fileRemote = "fasljlajljalfjlajfasdjkg;fdk;kqpitpk;k;asdk;kg;adskg"
fileLocal = "ljljalsjdgljadslfjlasjdfqporiuqplsadljfaljdf"
blockSize = 5
-- generate signatures at block boundaries for the local file and send it to remote.
fileLocalSigs = fileSignatures (BL.fromStrict (BS.pack fileLocal)) blockSize
-- at remote, take the signatures from the other size and generate instructions.
insns = genInstructions fileLocalSigs blockSize (BL.fromStrict (BS.pack fileRemote))
-- at the local side, take those instructions and apply to fileLocal
fileLocalNew = recreate (BL.fromStrict (BS.pack fileLocal)) blockSize insns
putStrLn $ "remote: " ++ fileRemote
putStrLn $ "local: " ++ fileLocal
BS.putStrLn $ (BS.pack "recreated: ") `BS.append` (BL.toStrict fileLocalNew)
|
vu3rdd/hs-rsync
|
app/Main.hs
|
gpl-3.0
| 987 | 0 | 15 | 195 | 199 | 108 | 91 | 15 | 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.ReplicaPool.Pools.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a replica pool.
--
-- /See:/ <https://developers.google.com/compute/docs/replica-pool/ Replica Pool API Reference> for @replicapool.pools.delete@.
module Network.Google.Resource.ReplicaPool.Pools.Delete
(
-- * REST Resource
PoolsDeleteResource
-- * Creating a Request
, poolsDelete
, PoolsDelete
-- * Request Lenses
, pdPoolName
, pdZone
, pdPayload
, pdProjectName
) where
import Network.Google.Prelude
import Network.Google.ReplicaPool.Types
-- | A resource alias for @replicapool.pools.delete@ method which the
-- 'PoolsDelete' request conforms to.
type PoolsDeleteResource =
"replicapool" :>
"v1beta1" :>
"projects" :>
Capture "projectName" Text :>
"zones" :>
Capture "zone" Text :>
"pools" :>
Capture "poolName" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] PoolsDeleteRequest :> Post '[JSON] ()
-- | Deletes a replica pool.
--
-- /See:/ 'poolsDelete' smart constructor.
data PoolsDelete =
PoolsDelete'
{ _pdPoolName :: !Text
, _pdZone :: !Text
, _pdPayload :: !PoolsDeleteRequest
, _pdProjectName :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PoolsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pdPoolName'
--
-- * 'pdZone'
--
-- * 'pdPayload'
--
-- * 'pdProjectName'
poolsDelete
:: Text -- ^ 'pdPoolName'
-> Text -- ^ 'pdZone'
-> PoolsDeleteRequest -- ^ 'pdPayload'
-> Text -- ^ 'pdProjectName'
-> PoolsDelete
poolsDelete pPdPoolName_ pPdZone_ pPdPayload_ pPdProjectName_ =
PoolsDelete'
{ _pdPoolName = pPdPoolName_
, _pdZone = pPdZone_
, _pdPayload = pPdPayload_
, _pdProjectName = pPdProjectName_
}
-- | The name of the replica pool for this request.
pdPoolName :: Lens' PoolsDelete Text
pdPoolName
= lens _pdPoolName (\ s a -> s{_pdPoolName = a})
-- | The zone for this replica pool.
pdZone :: Lens' PoolsDelete Text
pdZone = lens _pdZone (\ s a -> s{_pdZone = a})
-- | Multipart request metadata.
pdPayload :: Lens' PoolsDelete PoolsDeleteRequest
pdPayload
= lens _pdPayload (\ s a -> s{_pdPayload = a})
-- | The project ID for this replica pool.
pdProjectName :: Lens' PoolsDelete Text
pdProjectName
= lens _pdProjectName
(\ s a -> s{_pdProjectName = a})
instance GoogleRequest PoolsDelete where
type Rs PoolsDelete = ()
type Scopes PoolsDelete =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/ndev.cloudman",
"https://www.googleapis.com/auth/replicapool"]
requestClient PoolsDelete'{..}
= go _pdProjectName _pdZone _pdPoolName
(Just AltJSON)
_pdPayload
replicaPoolService
where go
= buildClient (Proxy :: Proxy PoolsDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-replicapool/gen/Network/Google/Resource/ReplicaPool/Pools/Delete.hs
|
mpl-2.0
| 3,857 | 0 | 17 | 957 | 550 | 326 | 224 | 87 | 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.Gmail.Users.Threads.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 the specified thread.
--
-- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.threads.get@.
module Network.Google.Resource.Gmail.Users.Threads.Get
(
-- * REST Resource
UsersThreadsGetResource
-- * Creating a Request
, usersThreadsGet
, UsersThreadsGet
-- * Request Lenses
, utgFormat
, utgUserId
, utgId
, utgMetadataHeaders
) where
import Network.Google.Gmail.Types
import Network.Google.Prelude
-- | A resource alias for @gmail.users.threads.get@ method which the
-- 'UsersThreadsGet' request conforms to.
type UsersThreadsGetResource =
"gmail" :>
"v1" :>
"users" :>
Capture "userId" Text :>
"threads" :>
Capture "id" Text :>
QueryParam "format" UsersThreadsGetFormat :>
QueryParams "metadataHeaders" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Thread
-- | Gets the specified thread.
--
-- /See:/ 'usersThreadsGet' smart constructor.
data UsersThreadsGet = UsersThreadsGet'
{ _utgFormat :: !UsersThreadsGetFormat
, _utgUserId :: !Text
, _utgId :: !Text
, _utgMetadataHeaders :: !(Maybe [Text])
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'UsersThreadsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'utgFormat'
--
-- * 'utgUserId'
--
-- * 'utgId'
--
-- * 'utgMetadataHeaders'
usersThreadsGet
:: Text -- ^ 'utgId'
-> UsersThreadsGet
usersThreadsGet pUtgId_ =
UsersThreadsGet'
{ _utgFormat = UTGFFull
, _utgUserId = "me"
, _utgId = pUtgId_
, _utgMetadataHeaders = Nothing
}
-- | The format to return the messages in.
utgFormat :: Lens' UsersThreadsGet UsersThreadsGetFormat
utgFormat
= lens _utgFormat (\ s a -> s{_utgFormat = a})
-- | The user\'s email address. The special value me can be used to indicate
-- the authenticated user.
utgUserId :: Lens' UsersThreadsGet Text
utgUserId
= lens _utgUserId (\ s a -> s{_utgUserId = a})
-- | The ID of the thread to retrieve.
utgId :: Lens' UsersThreadsGet Text
utgId = lens _utgId (\ s a -> s{_utgId = a})
-- | When given and format is METADATA, only include headers specified.
utgMetadataHeaders :: Lens' UsersThreadsGet [Text]
utgMetadataHeaders
= lens _utgMetadataHeaders
(\ s a -> s{_utgMetadataHeaders = a})
. _Default
. _Coerce
instance GoogleRequest UsersThreadsGet where
type Rs UsersThreadsGet = Thread
type Scopes UsersThreadsGet =
'["https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.metadata",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.readonly"]
requestClient UsersThreadsGet'{..}
= go _utgUserId _utgId (Just _utgFormat)
(_utgMetadataHeaders ^. _Default)
(Just AltJSON)
gmailService
where go
= buildClient
(Proxy :: Proxy UsersThreadsGetResource)
mempty
|
rueshyna/gogol
|
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Threads/Get.hs
|
mpl-2.0
| 4,017 | 0 | 16 | 1,018 | 554 | 329 | 225 | 86 | 1 |
{-
Copyright (C) 2013–2014 Albert Krewinkel <[email protected]>
This file is part of ZeitLinse.
ZeitLinse is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.
ZeitLinse 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 Affero General Public
License for more details.
You should have received a copy of the GNU Affero General Public License
along with ZeitLinse. If not, see <http://www.gnu.org/licenses/>.
-}
-- | ZeitLinse -- time dependent rating of information sources.
module ZeitLinse where
import ZeitLinse.Core.Types
import ZeitLinse.Core.WeightedMerging
import ZeitLinse.FocalItem
main = print "Sorry, this doesn't work yet."
|
tarleb/zeitlinse
|
src/ZeitLinse.hs
|
agpl-3.0
| 959 | 0 | 5 | 149 | 31 | 20 | 11 | 5 | 1 |
{-# LANGUAGE CPP, MagicHash, BangPatterns #-}
-- |
-- Module : Data.Text.Internal.Encoding.Utf8
-- Copyright : (c) 2008, 2009 Tom Harper,
-- (c) 2009, 2010 Bryan O'Sullivan,
-- (c) 2009 Duncan Coutts
--
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : GHC
--
-- /Warning/: this is an internal module, and does not have a stable
-- API or name. Functions in this module may not check or enforce
-- preconditions expected by public modules. Use at your own risk!
--
-- Basic UTF-8 validation and character manipulation.
module Data.Text.Internal.Encoding.Utf8
(
-- Decomposition
ord2
, ord3
, ord4
-- Construction
, chr2
, chr3
, chr4
-- * Validation
, continuationByte
, validate1
, validate2
, validate3
, validate4
, decodeChar
, decodeCharIndex
, reverseDecodeCharIndex
, encodeChar
, charTailBytes
) where
#if defined(TEST_SUITE)
# undef ASSERTS
#endif
#if defined(ASSERTS)
import Control.Exception (assert)
#endif
import Data.Bits ((.&.))
import Data.Text.Internal.Unsafe.Char (ord, unsafeChr8)
import Data.Text.Internal.Unsafe.Shift (shiftR)
import GHC.Exts
import GHC.Word (Word8(..))
default(Int)
between :: Word8 -- ^ byte to check
-> Word8 -- ^ lower bound
-> Word8 -- ^ upper bound
-> Bool
between x y z = x >= y && x <= z
{-# INLINE between #-}
ord2 :: Char -> (Word8,Word8)
ord2 c =
#if defined(ASSERTS)
assert (n >= 0x80 && n <= 0x07ff)
#endif
(x1,x2)
where
n = ord c
x1 = fromIntegral $ (n `shiftR` 6) + 0xC0
x2 = fromIntegral $ (n .&. 0x3F) + 0x80
ord3 :: Char -> (Word8,Word8,Word8)
ord3 c =
#if defined(ASSERTS)
assert (n >= 0x0800 && n <= 0xffff)
#endif
(x1,x2,x3)
where
n = ord c
x1 = fromIntegral $ (n `shiftR` 12) + 0xE0
x2 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80
x3 = fromIntegral $ (n .&. 0x3F) + 0x80
ord4 :: Char -> (Word8,Word8,Word8,Word8)
ord4 c =
#if defined(ASSERTS)
assert (n >= 0x10000)
#endif
(x1,x2,x3,x4)
where
n = ord c
x1 = fromIntegral $ (n `shiftR` 18) + 0xF0
x2 = fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80
x3 = fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80
x4 = fromIntegral $ (n .&. 0x3F) + 0x80
chr2 :: Word8 -> Word8 -> Char
chr2 (W8# x1#) (W8# x2#) = C# (chr# (z1# +# z2#))
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!z1# = uncheckedIShiftL# (y1# -# 0xC0#) 6#
!z2# = y2# -# 0x80#
{-# INLINE chr2 #-}
chr3 :: Word8 -> Word8 -> Word8 -> Char
chr3 (W8# x1#) (W8# x2#) (W8# x3#) = C# (chr# (z1# +# z2# +# z3#))
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!y3# = word2Int# x3#
!z1# = uncheckedIShiftL# (y1# -# 0xE0#) 12#
!z2# = uncheckedIShiftL# (y2# -# 0x80#) 6#
!z3# = y3# -# 0x80#
{-# INLINE chr3 #-}
chr4 :: Word8 -> Word8 -> Word8 -> Word8 -> Char
chr4 (W8# x1#) (W8# x2#) (W8# x3#) (W8# x4#) =
C# (chr# (z1# +# z2# +# z3# +# z4#))
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!y3# = word2Int# x3#
!y4# = word2Int# x4#
!z1# = uncheckedIShiftL# (y1# -# 0xF0#) 18#
!z2# = uncheckedIShiftL# (y2# -# 0x80#) 12#
!z3# = uncheckedIShiftL# (y3# -# 0x80#) 6#
!z4# = y4# -# 0x80#
{-# INLINE chr4 #-}
validate1 :: Word8 -> Bool
validate1 x1 = x1 <= 0x7F
{-# INLINE validate1 #-}
validate2 :: Word8 -> Word8 -> Bool
validate2 x1 x2 = between x1 0xC2 0xDF && between x2 0x80 0xBF
{-# INLINE validate2 #-}
validate3 :: Word8 -> Word8 -> Word8 -> Bool
{-# INLINE validate3 #-}
validate3 x1 x2 x3 = validate3_1 || validate3_2 || validate3_3 || validate3_4
where
validate3_1 = (x1 == 0xE0) &&
between x2 0xA0 0xBF &&
between x3 0x80 0xBF
validate3_2 = between x1 0xE1 0xEC &&
between x2 0x80 0xBF &&
between x3 0x80 0xBF
validate3_3 = x1 == 0xED &&
between x2 0x80 0x9F &&
between x3 0x80 0xBF
validate3_4 = between x1 0xEE 0xEF &&
between x2 0x80 0xBF &&
between x3 0x80 0xBF
validate4 :: Word8 -> Word8 -> Word8 -> Word8 -> Bool
{-# INLINE validate4 #-}
validate4 x1 x2 x3 x4 = validate4_1 || validate4_2 || validate4_3
where
validate4_1 = x1 == 0xF0 &&
between x2 0x90 0xBF &&
between x3 0x80 0xBF &&
between x4 0x80 0xBF
validate4_2 = between x1 0xF1 0xF3 &&
between x2 0x80 0xBF &&
between x3 0x80 0xBF &&
between x4 0x80 0xBF
validate4_3 = x1 == 0xF4 &&
between x2 0x80 0x8F &&
between x3 0x80 0xBF &&
between x4 0x80 0xBF
-- | Utility function: check if a word is an UTF-8 continuation byte
continuationByte :: Word8 -> Bool
continuationByte x = x .&. 0xC0 == 0x80
{-# INLINE [0] continuationByte #-}
-- | Inverse of 'continuationByte'
notContinuationByte :: Word8 -> Bool
notContinuationByte x = x .&. 0xC0 /= 0x80
{-# INLINE [0] notContinuationByte #-}
-- | Hybrid combination of 'unsafeChr8', 'chr2', 'chr3' and 'chr4'. This
-- function will not touch the bytes it doesn't need.
decodeChar :: (Char -> Int -> a) -> Word8 -> Word8 -> Word8 -> Word8 -> a
decodeChar f !n1 n2 n3 n4
| n1 < 0xC0 = f (unsafeChr8 n1) 1
| n1 < 0xE0 = f (chr2 n1 n2) 2
| n1 < 0xF0 = f (chr3 n1 n2 n3) 3
| otherwise = f (chr4 n1 n2 n3 n4) 4
{-# INLINE [0] decodeChar #-}
-- | Version of 'decodeChar' which works with an indexing function.
decodeCharIndex :: (Char -> Int -> a) -> (Int -> Word8) -> Int -> a
decodeCharIndex f idx n =
decodeChar f (idx n) (idx (n + 1)) (idx (n + 2)) (idx (n + 3))
{-# INLINE [0] decodeCharIndex #-}
-- | Version of 'decodeCharIndex' that takes the rightmost index and tracks
-- back to the left. Note that this function requires that the input is
-- valid unicode.
reverseDecodeCharIndex :: (Char -> Int -> a) -> (Int -> Word8) -> Int -> a
reverseDecodeCharIndex f idx !r =
let !x1 = idx r in
if notContinuationByte x1 then f (unsafeChr8 x1) 1
else let !x2 = idx (r - 1) in
if notContinuationByte x2 then f (chr2 x2 x1) 2
else let !x3 = idx (r - 2) in
if notContinuationByte x3 then f (chr3 x3 x2 x1) 3
else let !x4 = idx (r - 3) in
f (chr4 x4 x3 x2 x1) 4
{-# INLINE [0] reverseDecodeCharIndex #-}
-- | This function provides fast UTF-8 encoding of characters because the user
-- can supply custom functions for the different code paths, which should be
-- inlined properly.
encodeChar :: (Word8 -> a)
-> (Word8 -> Word8 -> a)
-> (Word8 -> Word8 -> Word8 -> a)
-> (Word8 -> Word8 -> Word8 -> Word8 -> a)
-> Char
-> a
encodeChar f1 f2 f3 f4 c
-- One-byte character
| n < 0x80 = f1 (fromIntegral n)
-- Two-byte character
| n < 0x0800 = f2 (fromIntegral $ (n `shiftR` 6) + 0xC0)
(fromIntegral $ (n .&. 0x3F) + 0x80)
-- Three-byte character
| n < 0x10000 = f3 (fromIntegral $ (n `shiftR` 12) + 0xE0)
(fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80)
(fromIntegral $ (n .&. 0x3F) + 0x80)
-- Four-byte character
| otherwise = f4 (fromIntegral $ (n `shiftR` 18) + 0xF0)
(fromIntegral $ ((n `shiftR` 12) .&. 0x3F) + 0x80)
(fromIntegral $ ((n `shiftR` 6) .&. 0x3F) + 0x80)
(fromIntegral $ (n .&. 0x3F) + 0x80)
where
n = ord c
{-# INLINE [0] encodeChar #-}
-- | Count the number of UTF-8 tail bytes needed to encode a character
charTailBytes :: Char -> Int
charTailBytes x
| n < 0x00080 = 0
| n < 0x00800 = 1
| n < 0x10000 = 2
| otherwise = 3
where
n = ord x
{-# INLINE [0] charTailBytes #-}
|
text-utf8/text
|
Data/Text/Internal/Encoding/Utf8.hs
|
bsd-2-clause
| 8,093 | 0 | 20 | 2,491 | 2,471 | 1,307 | 1,164 | 171 | 4 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- | Defines a type-safe 'Data.Binary.Binary' instance to ensure data is
-- encoded with the type it was serialized from.
--
-- * The "Data.Binary.Typed.Tutorial" provides some more examples of usage.
-- * The "Data.Binary.Typed.Debug" is useful to ensure calculated type
-- representations are shared properly.
module Data.Binary.Typed (
-- * Core functions
Typed
, typed
, TypeFormat(..)
, erase
-- * Useful general helpers
, mapTyped
, reValue
, reType
, preserialize
-- * Typed serialization
-- ** Encoding
, encodeTyped
-- ** Decoding
, decodeTyped
, decodeTypedOrFail
, unsafeDecodeTyped
) where
import qualified Data.ByteString.Lazy as BSL
import Data.Typeable (Typeable, typeRep, Proxy(..))
import Data.Binary
import Data.Binary.Get (ByteOffset)
import Data.Binary.Typed.Internal
-- | Modify the value contained in a 'Typed', keeping the same sort of type
-- representation. In other words, calling 'mapTyped' on something that is
-- typed using 'Hashed' will yield a 'Hashed' value again.
--
-- Note: this destroys 'preserialize'd information, so that values have to be
-- 'preserialize'd again if desired. As a consequence, @'mapTyped' 'id'@
-- can be used to un-'preserialize' values.
mapTyped :: Typeable b => (a -> b) -> Typed a -> Typed b
mapTyped f (Typed ty x) = typed (getFormat ty) (f x)
-- | Change the value contained in a 'Typed', leaving the type representation
-- unchanged. This can be useful to avoid recomputation of the included type
-- information, and can improve performance significantly if many individual
-- messages are serialized.
--
-- Can be seen as a more efficient 'mapTyped' in case @f@ is an endomorphism
-- (i.e. has type @a -> a@).
reValue :: (a -> a) -> Typed a -> Typed a
reValue f (Typed ty x) = Typed ty (f x)
-- | Change the way a type is represented inside a 'Typed' value.
--
-- @
-- 'reType' format x = 'typed' format ('erase' x)
-- @
reType :: Typeable a => TypeFormat -> Typed a -> Typed a
reType format (Typed _ty x) = typed format x
-- | Encode a 'Typeable' value to 'BSL.ByteString' that includes type
-- information. This function is useful to create specialized typed encoding
-- functions, because the type information is cached and does not need to be
-- recalculated on every serialization.
--
-- Observationally, @'encodeTyped' format value@ is equivalent to
-- @'encode' ('typed' format value)@. However, 'encodeTyped' does the type
-- information related calculations in advance and shares the results between
-- future invocations of it, making it much more efficient to serialize many
-- values of the same type.
encodeTyped :: forall a.
(Typeable a, Binary a)
=> TypeFormat
-> a
-> BSL.ByteString
encodeTyped format = \x -> encode (Typed typeInfo x)
where typeInfo = preserialize (makeTypeInformation format typerep)
typerep = typeRep (Proxy :: Proxy a)
{-# INLINE encodeTyped #-}
-- | Decode a typed value, throwing a descriptive 'error' at runtime on failure.
-- Typed cousin of 'Data.Binary.decode'. Based on 'decodeTypedOrFail'.
--
-- @
-- encoded = 'encodeTyped' 'Full' ("hello", 1 :: 'Int', 2.34 :: 'Double')
--
-- -- \<value\>
-- 'unsafeDecodeTyped' encoded :: ('String', 'Int', 'Double')
--
-- -- (Descriptive) runtime 'error'
-- 'unsafeDecodeTyped' encoded :: ('Char', 'Int', 'Double')
-- @
unsafeDecodeTyped :: (Typeable a, Binary a)
=> BSL.ByteString
-> a
unsafeDecodeTyped = \x -> case decodeTypedOrFail x of
Left (_,_,err) -> error ("unsafeDecodeTyped' failure: " ++ err)
Right (_,_,value) -> value
{-# INLINE unsafeDecodeTyped #-} -- Inlining is crucial for caching to work!
-- | Safely decode data, yielding 'Either' an error 'String' or the value.
-- Equivalent to 'decodeTypedOrFail' stripped of the non-essential data.
-- Based on 'decodeTypedOrFail'.
--
-- @
-- encoded = 'encodeTyped' 'Full' ("hello", 1 :: 'Int', 2.34 :: 'Double')
--
-- -- Right \<value\>:
-- 'decodeTyped' encoded :: 'Either' 'String' ('String', 'Int', 'Double')
--
-- -- Left "Type error: expected (Char, Int, Double), got (String, Int, Double)"
-- 'decodeTyped' encoded :: 'Either' 'String' ('Char', 'Int', 'Double')
-- @
decodeTyped :: (Typeable a, Binary a)
=> BSL.ByteString
-> Either String a
decodeTyped = \x -> case decodeTypedOrFail x of
Left (_,_,err) -> Left err
Right (_,_,value) -> Right value
{-# INLINE decodeTyped #-} -- Inlining is crucial for caching to work!
-- | Safely decode data, yielding 'Either' an error 'String' or the value,
-- along with meta-information of the consumed binary data.
--
-- * Typed cousin of 'Data.Binary.decodeOrFail'.
--
-- * Like 'decodeTyped', but with additional data.
--
-- * Automatically caches 'Hashed5', 'Hashed32' and 'Hashed64' representations,
-- so that typechecking does not need to recalculate them on every decoding.
decodeTypedOrFail :: forall a.
(Typeable a, Binary a)
=> BSL.ByteString
-> Either (BSL.ByteString, ByteOffset, String)
(BSL.ByteString, ByteOffset, a)
decodeTypedOrFail = \input -> do
(rest, offset, typed'@(Typed' ty value)) <- decodeOrFail input
let addMeta x = (rest, offset, x)
if isCached ty
then Right (addMeta value) -- cache hit, don't typecheck
else case typecheck' typed' of -- cache miss, typecheck manually
Left err -> Left (addMeta err)
Right _ -> Right (addMeta value)
where
exTypeRep = typeRep (Proxy :: Proxy a)
cache = map (\format -> makeTypeInformation format exTypeRep)
[Hashed5, Hashed32, Hashed64] -- List of formats to be cached
isCached = (`elem` cache)
{-# INLINE decodeTypedOrFail #-} -- Inlining is crucial for caching to work!
|
quchen/binary-typed
|
src/Data/Binary/Typed.hs
|
bsd-2-clause
| 6,134 | 0 | 14 | 1,443 | 879 | 513 | 366 | 67 | 3 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QButtonGroup.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:20
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QButtonGroup (
QqButtonGroup(..)
,checkedButton
,checkedId
,exclusive
,setId
,qButtonGroup_delete
,qButtonGroup_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QButtonGroup ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QButtonGroup_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QButtonGroup_userMethod" qtc_QButtonGroup_userMethod :: Ptr (TQButtonGroup a) -> CInt -> IO ()
instance QuserMethod (QButtonGroupSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QButtonGroup_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QButtonGroup ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QButtonGroup_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QButtonGroup_userMethodVariant" qtc_QButtonGroup_userMethodVariant :: Ptr (TQButtonGroup a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QButtonGroupSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QButtonGroup_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqButtonGroup x1 where
qButtonGroup :: x1 -> IO (QButtonGroup ())
instance QqButtonGroup (()) where
qButtonGroup ()
= withQButtonGroupResult $
qtc_QButtonGroup
foreign import ccall "qtc_QButtonGroup" qtc_QButtonGroup :: IO (Ptr (TQButtonGroup ()))
instance QqButtonGroup ((QObject t1)) where
qButtonGroup (x1)
= withQButtonGroupResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup1 cobj_x1
foreign import ccall "qtc_QButtonGroup1" qtc_QButtonGroup1 :: Ptr (TQObject t1) -> IO (Ptr (TQButtonGroup ()))
instance QaddButton (QButtonGroup a) ((QAbstractButton t1)) (IO ()) where
addButton x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_addButton cobj_x0 cobj_x1
foreign import ccall "qtc_QButtonGroup_addButton" qtc_QButtonGroup_addButton :: Ptr (TQButtonGroup a) -> Ptr (TQAbstractButton t1) -> IO ()
instance QaddButton (QButtonGroup a) ((QAbstractButton t1, Int)) (IO ()) where
addButton x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_addButton1 cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QButtonGroup_addButton1" qtc_QButtonGroup_addButton1 :: Ptr (TQButtonGroup a) -> Ptr (TQAbstractButton t1) -> CInt -> IO ()
instance Qbutton (QButtonGroup a) ((Int)) (IO (QAbstractButton ())) where
button x0 (x1)
= withQAbstractButtonResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_button cobj_x0 (toCInt x1)
foreign import ccall "qtc_QButtonGroup_button" qtc_QButtonGroup_button :: Ptr (TQButtonGroup a) -> CInt -> IO (Ptr (TQAbstractButton ()))
instance Qbuttons (QButtonGroup a) (()) (IO ([QAbstractButton ()])) where
buttons x0 ()
= withQListQAbstractButtonResult $ \arr ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_buttons cobj_x0 arr
foreign import ccall "qtc_QButtonGroup_buttons" qtc_QButtonGroup_buttons :: Ptr (TQButtonGroup a) -> Ptr (Ptr (TQAbstractButton ())) -> IO CInt
checkedButton :: QButtonGroup a -> (()) -> IO (QAbstractButton ())
checkedButton x0 ()
= withQAbstractButtonResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_checkedButton cobj_x0
foreign import ccall "qtc_QButtonGroup_checkedButton" qtc_QButtonGroup_checkedButton :: Ptr (TQButtonGroup a) -> IO (Ptr (TQAbstractButton ()))
checkedId :: QButtonGroup a -> (()) -> IO (Int)
checkedId x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_checkedId cobj_x0
foreign import ccall "qtc_QButtonGroup_checkedId" qtc_QButtonGroup_checkedId :: Ptr (TQButtonGroup a) -> IO CInt
exclusive :: QButtonGroup a -> (()) -> IO (Bool)
exclusive x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_exclusive cobj_x0
foreign import ccall "qtc_QButtonGroup_exclusive" qtc_QButtonGroup_exclusive :: Ptr (TQButtonGroup a) -> IO CBool
instance Qqid (QButtonGroup a) ((QAbstractButton t1)) where
qid x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_id cobj_x0 cobj_x1
foreign import ccall "qtc_QButtonGroup_id" qtc_QButtonGroup_id :: Ptr (TQButtonGroup a) -> Ptr (TQAbstractButton t1) -> IO CInt
instance QremoveButton (QButtonGroup a) ((QAbstractButton t1)) where
removeButton x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_removeButton cobj_x0 cobj_x1
foreign import ccall "qtc_QButtonGroup_removeButton" qtc_QButtonGroup_removeButton :: Ptr (TQButtonGroup a) -> Ptr (TQAbstractButton t1) -> IO ()
instance QsetExclusive (QButtonGroup a) ((Bool)) where
setExclusive x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_setExclusive cobj_x0 (toCBool x1)
foreign import ccall "qtc_QButtonGroup_setExclusive" qtc_QButtonGroup_setExclusive :: Ptr (TQButtonGroup a) -> CBool -> IO ()
setId :: QButtonGroup a -> ((QAbstractButton t1, Int)) -> IO ()
setId x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_setId cobj_x0 cobj_x1 (toCInt x2)
foreign import ccall "qtc_QButtonGroup_setId" qtc_QButtonGroup_setId :: Ptr (TQButtonGroup a) -> Ptr (TQAbstractButton t1) -> CInt -> IO ()
qButtonGroup_delete :: QButtonGroup a -> IO ()
qButtonGroup_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_delete cobj_x0
foreign import ccall "qtc_QButtonGroup_delete" qtc_QButtonGroup_delete :: Ptr (TQButtonGroup a) -> IO ()
qButtonGroup_deleteLater :: QButtonGroup a -> IO ()
qButtonGroup_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_deleteLater cobj_x0
foreign import ccall "qtc_QButtonGroup_deleteLater" qtc_QButtonGroup_deleteLater :: Ptr (TQButtonGroup a) -> IO ()
instance QchildEvent (QButtonGroup ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QButtonGroup_childEvent" qtc_QButtonGroup_childEvent :: Ptr (TQButtonGroup a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QButtonGroupSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QButtonGroup ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QButtonGroup_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QButtonGroup_connectNotify" qtc_QButtonGroup_connectNotify :: Ptr (TQButtonGroup a) -> CWString -> IO ()
instance QconnectNotify (QButtonGroupSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QButtonGroup_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QButtonGroup ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QButtonGroup_customEvent" qtc_QButtonGroup_customEvent :: Ptr (TQButtonGroup a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QButtonGroupSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QButtonGroup ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QButtonGroup_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QButtonGroup_disconnectNotify" qtc_QButtonGroup_disconnectNotify :: Ptr (TQButtonGroup a) -> CWString -> IO ()
instance QdisconnectNotify (QButtonGroupSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QButtonGroup_disconnectNotify cobj_x0 cstr_x1
instance Qevent (QButtonGroup ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QButtonGroup_event_h" qtc_QButtonGroup_event_h :: Ptr (TQButtonGroup a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QButtonGroupSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_event_h cobj_x0 cobj_x1
instance QeventFilter (QButtonGroup ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QButtonGroup_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QButtonGroup_eventFilter_h" qtc_QButtonGroup_eventFilter_h :: Ptr (TQButtonGroup a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QButtonGroupSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QButtonGroup_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QButtonGroup ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QButtonGroup_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QButtonGroup_receivers" qtc_QButtonGroup_receivers :: Ptr (TQButtonGroup a) -> CWString -> IO CInt
instance Qreceivers (QButtonGroupSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QButtonGroup_receivers cobj_x0 cstr_x1
instance Qsender (QButtonGroup ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_sender cobj_x0
foreign import ccall "qtc_QButtonGroup_sender" qtc_QButtonGroup_sender :: Ptr (TQButtonGroup a) -> IO (Ptr (TQObject ()))
instance Qsender (QButtonGroupSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QButtonGroup_sender cobj_x0
instance QtimerEvent (QButtonGroup ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QButtonGroup_timerEvent" qtc_QButtonGroup_timerEvent :: Ptr (TQButtonGroup a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QButtonGroupSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QButtonGroup_timerEvent cobj_x0 cobj_x1
|
keera-studios/hsQt
|
Qtc/Gui/QButtonGroup.hs
|
bsd-2-clause
| 11,769 | 0 | 14 | 1,903 | 3,678 | 1,867 | 1,811 | -1 | -1 |
module Web.Cloud where
import Data.List
import Data.IORef
import Data.ByteString.Lazy.Char8 (pack, unpack)
import System.Environment
import Options.Applicative
import Options.Applicative.Types
import Options.Applicative.Help.Chunk
import Network.CGI
import Network.CGI.Monad
import Network.CGI.Protocol
import System.Exit
execParserWebCloud :: ParserInfo a -> IO a
execParserWebCloud pinfo = do
ref <- newIORef Nothing
title <- (\x -> "<title>" ++ x ++ "</title>") `fmap` getProgName
runCGI . handleErrors $ do
setHeader "Content-Type" "text/html; charset=utf-8"
clouds <- cgiGet (execParserPure (prefs idm) pinfo . getCloud . cgiInputs)
val <- mkWebCloud clouds
case val of
Left e -> do
output $ title
++ "<code><pre>"
++ e
++ "</code></pre>"
++ "<form action=\"\" method=\"get\">" ++ form (infoParser pinfo) ++ "<input type=submit></form>"
Right v -> do
liftIO $ writeIORef ref (Just v)
output $ title ++ "<code><pre>"
r <- readIORef ref
case r of
Just v -> return v
Nothing -> exitWith ExitSuccess -- it's ok to error! :)
getCloud :: [(String, Input)] -> [String]
getCloud =
flip (>>=) $ \(k, v) ->
if unpack (inputValue v) == ""
then []
else if unpack (inputValue v) == "on"
then ["--" ++ k]
else ["--" ++ k, show (inputValue v)]
mkWebCloud :: Monad m => ParserResult a -> m (Either String a)
mkWebCloud (Success a) = return (Right a)
mkWebCloud (Failure failure) = return (Left (fst (renderFailure failure "cloud")))
mkWebCloud (CompletionInvoked _) = return (Left "not web")
form :: Parser a -> String
form (NilP _) = ""
form (OptP opt) = formatOpt (optProps opt) (optMain opt)
form (MultP pf pa) = form pf ++ form pa
form (AltP pa pb) = form pa ++ form pb
form (BindP px _pf) = form px -- TODO: bind... ++ form pf
formatOpt :: OptProperties -> OptReader a -> String
formatOpt (OptProperties _vis halp fmetavar _def _brief) (OptReader names _ _) =
fmt fmetavar halp names (getName names == "help")
formatOpt (OptProperties _vis halp fmetavar _def _brief) (FlagReader names _) =
fmt fmetavar halp names True
formatOpt (OptProperties _vis _halp _metavar _def _brief) (ArgReader _) =
"TODO"
formatOpt (OptProperties _vis _halp _metavar _def _brief) (CmdReader _cmd _ _) =
"TODO"
fmt :: Show a => String -> Chunk a -> [OptName] -> Bool -> String
fmt fmetavar halp names isFlag =
"<p>"
++ "<strong>--"
++ getName names
++ "</strong><br/>"
++ maybe "" show (unChunk halp)
++ "<br/><input type=\"" ++ (if isFlag then "checkbox" else "text") ++ "\" name=\"" ++ getName names ++ "\" placeholder=\"" ++ fmetavar ++ "\"></input><br/></p>"
getName :: [OptName] -> [Char]
getName = head . sortBy (\x y -> length y `compare` length x) . map n
where
n (OptShort c) = return c
n (OptLong s) = s
|
mxswd/webcloud
|
src/Web/Cloud.hs
|
bsd-2-clause
| 2,902 | 0 | 21 | 647 | 1,075 | 541 | 534 | 73 | 3 |
{-# OPTIONS_HADDOCK hide #-}
-- |
--
-- Copyright:
-- This file is part of the package byline. It is subject to the
-- license terms in the LICENSE file found in the top-level
-- directory of this distribution and at:
--
-- https://github.com/pjones/byline
--
-- No part of this package, including this file, may be copied,
-- modified, propagated, or distributed except according to the
-- terms contained in the LICENSE file.
--
-- License: BSD-2-Clause
module Byline.Internal.Eval
( MonadByline (..),
BylineT,
runBylineT,
Settings (..),
defaultBylineSettings,
runBylineT',
defaultRenderMode,
)
where
import Byline.Internal.Completion
import Byline.Internal.Prim (PrimF (..))
import Byline.Internal.Stylized
import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
import Control.Monad.Cont (ContT, MonadCont)
import Control.Monad.Except (MonadError)
import qualified Control.Monad.State.Lazy as LState
import qualified Control.Monad.Trans.Free.Church as Free
import qualified System.Console.ANSI as ANSI
import qualified System.Console.Haskeline as Haskeline
import qualified System.Environment as System
import qualified System.Terminfo as Terminfo
import qualified System.Terminfo.Caps as Terminfo
-- | A class of types that can lift Byline operations into a base
-- monad.
--
-- @since 1.0.0.0
class Monad m => MonadByline (m :: * -> *) where
liftByline :: Free.F PrimF a -> m a
default liftByline :: (MonadTrans t, MonadByline m1, m ~ t m1) => Free.F PrimF a -> m a
liftByline = lift . liftByline
instance MonadByline m => MonadByline (ExceptT e m)
instance MonadByline m => MonadByline (StateT s m)
instance MonadByline m => MonadByline (LState.StateT s m)
instance MonadByline m => MonadByline (ReaderT r m)
instance MonadByline m => MonadByline (IdentityT m)
instance MonadByline m => MonadByline (ContT r m)
-- | A monad transformer that implements 'MonadByline'.
--
-- @since 1.0.0.0
newtype BylineT m a = BylineT
{unBylineT :: Free.FT PrimF m a}
deriving newtype
( Functor,
Applicative,
Monad,
MonadIO,
MonadState s,
MonadReader r,
MonadError e,
MonadCont,
MonadThrow,
MonadCatch
)
instance MonadTrans BylineT where
lift = BylineT . lift
instance MonadByline (BylineT m) where
liftByline = BylineT . Free.fromF
-- | Mutable list of completion functions.
--
-- @since 1.0.0.0
type CompRef m = IORef [CompletionFunc m]
-- | Discharge the 'MonadByline' effect by running all operations and
-- returning the result in the base monad.
--
-- The result is wrapped in a 'Maybe' where a 'Nothing' value
-- indicates that an end-of-file (EOF) signal was received while
-- reading user input.
--
-- @since 1.0.0.0
runBylineT ::
(MonadIO m, MonadMask m) =>
BylineT m a ->
m (Maybe a)
runBylineT = runBylineT' defaultBylineSettings
-- | Settings that control Byline at run time.
--
-- @since 1.0.0.0
data Settings = Settings
{ -- | The output handle to write to. If 'Nothing' use standard
-- output.
--
-- NOTE: This only affects Byline (i.e. functions that use
-- @say@). Functions like @ask@ that invoke Haskeline will always
-- use standard output since that's the hard-coded default.
bylineOutput :: Maybe Handle,
-- | The input handle to read from. If 'Nothing' use standard
-- input.
bylineInput :: Maybe Handle,
-- | Override the detected render mode.
--
-- If 'Nothing' use the render mode that is calculated based on
-- the type of handle Byline writes to.
bylineMode :: Maybe RenderMode
}
-- | The default Byline settings.
--
-- @since 1.0.0.0
defaultBylineSettings :: Settings
defaultBylineSettings = Settings Nothing Nothing Nothing
-- | Like 'runBylineT' except you can override the settings.
--
-- @since 1.0.0.0
runBylineT' ::
forall m a.
(MonadIO m, MonadMask m) =>
Settings ->
BylineT m a ->
m (Maybe a)
runBylineT' Settings {..} m = do
compRef <- newIORef []
let settings =
Haskeline.setComplete
(compFunc compRef)
Haskeline.defaultSettings
let behavior =
maybe
Haskeline.defaultBehavior
Haskeline.useFileHandle
bylineInput
let hOut = fromMaybe stdout bylineOutput
Haskeline.runInputTBehavior behavior settings (go compRef hOut)
where
compFunc :: CompRef IO -> Haskeline.CompletionFunc m
compFunc compRef input = liftIO $
readIORef compRef >>= \case
[] -> Haskeline.completeFilename input
fs -> runCompletionFunctions fs input
go ::
CompRef IO ->
Handle ->
Haskeline.InputT m (Maybe a)
go compRef hOut = do
mode <- maybe (liftIO (defaultRenderMode hOut)) pure bylineMode
unBylineT m
& evalPrimF mode hOut compRef
& unEvalT
& runMaybeT
-- | Internal transformer for evaluating primitive operations in the
-- 'Haskeline.InputT' transformer with EOF handling.
--
-- @since 1.0.0.0
newtype EvalT m a = EvalT
{unEvalT :: MaybeT (Haskeline.InputT m) a}
deriving newtype (Functor, Applicative, Monad, MonadIO)
instance MonadTrans EvalT where
lift = EvalT . lift . lift
-- | Evaluate 'PrimF' values.
--
-- @since 1.0.0.0
evalPrimF ::
forall m a.
(MonadIO m, MonadMask m) =>
RenderMode ->
Handle ->
CompRef IO ->
Free.FT PrimF m a ->
EvalT m a
evalPrimF renderMode outputHandle compRef = Free.iterTM go
where
go ::
PrimF (EvalT m a) ->
EvalT m a
go = \case
Say s k ->
liftIO (render renderMode outputHandle s) >> k
AskLn s d k -> do
let prompt =
renderText renderMode $
maybe s (\d' -> s <> text "[" <> text d' <> text "] ") d
liftHaskeline (Haskeline.getInputLine (toString prompt)) >>= \case
Nothing -> EvalT empty
Just answer
| null answer -> k (fromMaybe mempty d)
| otherwise -> k (toText answer)
AskChar s k -> do
let prompt = toString (renderText renderMode s)
liftHaskeline (Haskeline.getInputChar prompt) >>= \case
Nothing -> EvalT empty
Just c -> k c
AskPassword s m k -> do
let prompt = toString (renderText renderMode s)
liftHaskeline (Haskeline.getPassword m prompt) >>= \case
Nothing -> EvalT empty
Just str -> k (toText str)
PushCompFunc f k ->
modifyIORef' compRef (f :) >> k
PopCompFunc k ->
modifyIORef'
compRef
( \case
[] -> []
(_ : fs) -> fs
)
>> k
liftHaskeline :: Haskeline.InputT m b -> EvalT m b
liftHaskeline = Haskeline.withInterrupt >>> lift >>> EvalT
-- | Calculate the default rendering mode based on the terminal type.
defaultRenderMode :: Handle -> IO RenderMode
defaultRenderMode hOut = do
isTerm <- ANSI.hSupportsANSI hOut
if isTerm
then runMaybeT getMaxColors >>= \case
Nothing -> pure Simple
Just n
| n < 256 -> pure Simple
| n > 256 -> pure TermRGB
| otherwise -> pure Term256
else pure Plain
where
getMaxColors :: MaybeT IO Int
getMaxColors = do
term <- MaybeT (System.lookupEnv "TERM")
lift (Terminfo.acquireDatabase term) >>= \case
Left _ -> empty
Right db ->
hoistMaybe $
Terminfo.queryNumTermCap db Terminfo.MaxColors
|
pjones/byline
|
src/Byline/Internal/Eval.hs
|
bsd-2-clause
| 7,413 | 0 | 22 | 1,866 | 1,824 | 950 | 874 | -1 | -1 |
module Network.YAML
(
module Network.YAML.API,
module Network.YAML.Caller,
module Network.YAML.TH.Server,
module Network.YAML.TH.Client,
module Network.YAML.TH.Dispatcher
) where
import Network.YAML.API
import Network.YAML.Caller
import Network.YAML.TH.Server
import Network.YAML.TH.Client
import Network.YAML.TH.Dispatcher
|
portnov/yaml-rpc
|
Network/YAML.hs
|
bsd-3-clause
| 347 | 0 | 5 | 48 | 79 | 56 | 23 | 12 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
module AstrodynamicsSpec where
import Test.Hspec
import Test.QuickCheck (property, (==>))
import Data.AEq
import TestInstances
import Numeric.Units.Dimensional.Prelude
import qualified Prelude
import Astrodynamics
main = hspec spec
spec = do
spec_driftRateToPeriod
spec_driftRateToSMA
spec_meanAngularMotion
spec_driftRateToPeriod = describe "driftRateToPeriod" $ do
it "is the inverse of periodToDriftRate"
(property $ \(d::AngularVelocity Double) ->
d ~== periodToDriftRate (driftRateToPeriod d))
spec_driftRateToSMA = describe "smaToDriftRate" $ do
it "is the inverse of driftRateToSMA"
(property $ \(NonNegativeD (a::Length Double)) ->
a ~== driftRateToSMA (smaToDriftRate a))
spec_meanAngularMotion = describe "meanAngularMotion" $ do
it "is the inverse of semiMajorAxis"
(property $ \(NonNegativeD (a::Length Double)) ->
a ~== semiMajorAxis (meanAngularMotion a))
|
bjornbm/astro
|
test/AstrodynamicsSpec.hs
|
bsd-3-clause
| 995 | 0 | 16 | 161 | 247 | 130 | 117 | 27 | 1 |
{-# LANGUAGE DeriveGeneric #-}
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Program.Types
-- Copyright : Isaac Jones 2006, Duncan Coutts 2007-2009
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This provides an abstraction which deals with configuring and running
-- programs. A 'Program' is a static notion of a known program. A
-- 'ConfiguredProgram' is a 'Program' that has been found on the current
-- machine and is ready to be run (possibly with some user-supplied default
-- args). Configuring a program involves finding its location and if necessary
-- finding its version. There's reasonable default behavior for trying to find
-- \"foo\" in PATH, being able to override its location, etc.
--
module Distribution.Simple.Program.Types (
-- * Program and functions for constructing them
Program(..),
ProgramSearchPath,
ProgramSearchPathEntry(..),
simpleProgram,
-- * Configured program and related functions
ConfiguredProgram(..),
programPath,
suppressOverrideArgs,
ProgArg,
ProgramLocation(..),
simpleConfiguredProgram,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Simple.Program.Find
import Distribution.Version
import Distribution.Verbosity
import qualified Data.Map as Map
-- | Represents a program which can be configured.
--
-- Note: rather than constructing this directly, start with 'simpleProgram' and
-- override any extra fields.
--
data Program = Program {
-- | The simple name of the program, eg. ghc
programName :: String,
-- | A function to search for the program if its location was not
-- specified by the user. Usually this will just be a call to
-- 'findProgramOnSearchPath'.
--
-- It is supplied with the prevailing search path which will typically
-- just be used as-is, but can be extended or ignored as needed.
--
-- For the purpose of change monitoring, in addition to the location
-- where the program was found, it returns all the other places that
-- were tried.
--
programFindLocation :: Verbosity -> ProgramSearchPath
-> IO (Maybe (FilePath, [FilePath])),
-- | Try to find the version of the program. For many programs this is
-- not possible or is not necessary so it's OK to return Nothing.
programFindVersion :: Verbosity -> FilePath -> IO (Maybe Version),
-- | A function to do any additional configuration after we have
-- located the program (and perhaps identified its version). For example
-- it could add args, or environment vars.
programPostConf :: Verbosity -> ConfiguredProgram -> IO ConfiguredProgram
}
type ProgArg = String
-- | Represents a program which has been configured and is thus ready to be run.
--
-- These are usually made by configuring a 'Program', but if you have to
-- construct one directly then start with 'simpleConfiguredProgram' and
-- override any extra fields.
--
data ConfiguredProgram = ConfiguredProgram {
-- | Just the name again
programId :: String,
-- | The version of this program, if it is known.
programVersion :: Maybe Version,
-- | Default command-line args for this program.
-- These flags will appear first on the command line, so they can be
-- overridden by subsequent flags.
programDefaultArgs :: [String],
-- | Override command-line args for this program.
-- These flags will appear last on the command line, so they override
-- all earlier flags.
programOverrideArgs :: [String],
-- | Override environment variables for this program.
-- These env vars will extend\/override the prevailing environment of
-- the current to form the environment for the new process.
programOverrideEnv :: [(String, Maybe String)],
-- | A key-value map listing various properties of the program, useful
-- for feature detection. Populated during the configuration step, key
-- names depend on the specific program.
programProperties :: Map.Map String String,
-- | Location of the program. eg. @\/usr\/bin\/ghc-6.4@
programLocation :: ProgramLocation,
-- | In addition to the 'programLocation' where the program was found,
-- these are additional locations that were looked at. The combination
-- of ths found location and these not-found locations can be used to
-- monitor to detect when the re-configuring the program might give a
-- different result (e.g. found in a different location).
--
programMonitorFiles :: [FilePath]
}
deriving (Eq, Generic, Read, Show)
instance Binary ConfiguredProgram
-- | Where a program was found. Also tells us whether it's specified by user or
-- not. This includes not just the path, but the program as well.
data ProgramLocation
= UserSpecified { locationPath :: FilePath }
-- ^The user gave the path to this program,
-- eg. --ghc-path=\/usr\/bin\/ghc-6.6
| FoundOnSystem { locationPath :: FilePath }
-- ^The program was found automatically.
deriving (Eq, Generic, Read, Show)
instance Binary ProgramLocation
-- | The full path of a configured program.
programPath :: ConfiguredProgram -> FilePath
programPath = locationPath . programLocation
-- | Suppress any extra arguments added by the user.
suppressOverrideArgs :: ConfiguredProgram -> ConfiguredProgram
suppressOverrideArgs prog = prog { programOverrideArgs = [] }
-- | Make a simple named program.
--
-- By default we'll just search for it in the path and not try to find the
-- version name. You can override these behaviours if necessary, eg:
--
-- > (simpleProgram "foo") { programFindLocation = ... , programFindVersion ... }
--
simpleProgram :: String -> Program
simpleProgram name = Program {
programName = name,
programFindLocation = \v p -> findProgramOnSearchPath v p name,
programFindVersion = \_ _ -> return Nothing,
programPostConf = \_ p -> return p
}
-- | Make a simple 'ConfiguredProgram'.
--
-- > simpleConfiguredProgram "foo" (FoundOnSystem path)
--
simpleConfiguredProgram :: String -> ProgramLocation -> ConfiguredProgram
simpleConfiguredProgram name loc = ConfiguredProgram {
programId = name,
programVersion = Nothing,
programDefaultArgs = [],
programOverrideArgs = [],
programOverrideEnv = [],
programProperties = Map.empty,
programLocation = loc,
programMonitorFiles = [] -- did not look in any other locations
}
|
sopvop/cabal
|
Cabal/Distribution/Simple/Program/Types.hs
|
bsd-3-clause
| 6,743 | 0 | 15 | 1,533 | 645 | 418 | 227 | 61 | 1 |
-- | Display mode is for drawing a static picture.
module Graphics.Gloss.Interface.Pure.Animate
( module Graphics.Gloss.Data.Display
, module Graphics.Gloss.Data.Picture
, module Graphics.Gloss.Data.Color
, animate)
where
import Graphics.Gloss.Data.Display
import Graphics.Gloss.Data.Picture
import Graphics.Gloss.Data.Color
import Graphics.Gloss.Internals.Interface.Animate
import Graphics.Gloss.Internals.Interface.Backend
-- | Open a new window and display the given animation.
--
-- Once the window is open you can use the same commands as with `display`.
--
animate :: Display -- ^ Display mode.
-> Color -- ^ Background color.
-> (Float -> Picture) -- ^ Function to produce the next frame of animation.
-- It is passed the time in seconds since the program started.
-> IO ()
animate display backColor frameFun
= animateWithBackendIO
defaultBackendState
True -- pannable
display backColor
(return . frameFun)
|
ardumont/snake
|
deps/gloss/Graphics/Gloss/Interface/Pure/Animate.hs
|
bsd-3-clause
| 1,129 | 0 | 9 | 333 | 144 | 95 | 49 | 20 | 1 |
-- | An interface to blaze-html without the need for operators.
module Senza
(module Senza.Elements
,module Senza.Types
,module Text.Blaze.Html5.Attributes
,Attribute
,Attributable
,AttributeValue
,toValue
,renderSenza)
where
import Senza.Elements
import Senza.Types
import Data.Text.Lazy (Text)
import Text.Blaze.Html (Attribute,AttributeValue,toValue)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Text.Blaze.Html5.Attributes hiding (span)
import Text.Blaze.Internal (Attributable)
-- | Will protect other codebases from when Text.Blaze.Html eventually
-- gets renamed to Text.Blaze.Markup or something.
renderSenza :: Senza -> Text
renderSenza = renderHtml
|
chrisdone/senza
|
src/Senza.hs
|
bsd-3-clause
| 693 | 0 | 5 | 92 | 133 | 88 | 45 | 18 | 1 |
module Crossword.Regex where
import Data.Set (Set)
import qualified Data.Set as Set
import Crossword.Token
data Regex =
Literal Token
| Any
| OneOf (Set Token)
| NoneOf (Set Token)
| Many Regex
| Many1 Regex
| Seq Regex Regex
| Group Regex
| BackRef Int
| Choice Regex Regex
| Option Regex
deriving Show
lit :: Char -> Regex
lit = Literal . Token
ppr :: Regex -> String
ppr (Literal (Token c)) = [c]
ppr Any = "."
ppr (OneOf toks) = "[" ++ map unToken (Set.toList toks) ++ "]"
ppr (NoneOf toks) = "[^" ++ map unToken (Set.toList toks) ++ "]"
ppr (Many r) = ppr r ++ "*"
ppr (Many1 r) = ppr r ++ "+"
ppr (Seq r1 r2) = ppr r1 ++ ppr r2
ppr (Group r) = "(" ++ ppr r ++ ")"
ppr (BackRef i) = '\\' : show i
ppr (Choice r1 r2) = ppr r1 ++ "|" ++ ppr r2
ppr (Option r) = ppr r ++ "?"
seq, choices :: [Regex] -> Regex
seq = foldr1 Seq
choices = foldr1 Choice
|
hesselink/regex-crossword
|
src/Crossword/Regex.hs
|
bsd-3-clause
| 885 | 0 | 10 | 214 | 428 | 223 | 205 | 34 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.