code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
module Network.IRC.Handlers.Greet (greetMsgHandlerMaker, welcomeMsgHandlerMaker) where
import ClassyPrelude
import Network.IRC
import Network.IRC.Util
greetMsgHandlerMaker :: MsgHandlerMaker
greetMsgHandlerMaker =
MsgHandlerMaker "greeter" $ \_ _ -> return $ newMsgHandler { onMessage = greeter }
welcomeMsgHandlerMaker :: MsgHandlerMaker
welcomeMsgHandlerMaker =
MsgHandlerMaker "welcomer" $ \_ _ -> return $ newMsgHandler { onMessage = welcomer }
greeter :: MonadMsgHandler m => Message -> m [Message]
greeter Message { .. } = case fromMessage message of
Just (ChannelMsg user msg) ->
let reply = maybeToList . map (ChannelMsgReply . (++ nickToText (userNick user)) . (++ " "))
. find (== clean msg) $ greetings
in mapM newMessage reply
_ -> return []
where
greetings = [ "hi", "hello", "hey", "sup", "bye"
, "good morning", "good evening", "good night" ]
welcomer :: MonadMsgHandler m => Message -> m [Message]
welcomer Message { .. } = case fromMessage message of
Just (JoinMsg user) -> do
BotConfig { .. } <- ask
if userNick user /= botNick
then map singleton . newMessage . ChannelMsgReply $ "welcome back " ++ nickToText (userNick user)
else return []
_ -> return []
| abhin4v/hask-irc | hask-irc-handlers/Network/IRC/Handlers/Greet.hs | apache-2.0 | 1,304 | 0 | 22 | 308 | 406 | 212 | 194 | -1 | -1 |
module Calculus.Opra1 where
-- standard modules
import qualified Data.Char as Char
import qualified Data.Map as Map
import qualified Data.Set as Set
-- local modules
import Basics
import Calculus.Opra
data Opra1 = Opra1_0_0 | Opra1_0_1 | Opra1_0_2 | Opra1_0_3
| Opra1_1_0 | Opra1_1_1 | Opra1_1_2 | Opra1_1_3
| Opra1_2_0 | Opra1_2_1 | Opra1_2_2 | Opra1_2_3
| Opra1_3_0 | Opra1_3_1 | Opra1_3_2 | Opra1_3_3
| Opra1_s_0 | Opra1_s_1 | Opra1_s_2 | Opra1_s_3
deriving (Eq, Ord, Read, Show, Enum, Bounded)
instance Opram Opra1 where
m _ = 1
instance Calculus Opra1 where
rank _ = 2
cName _ ="opra-1"
cNameGqr _ ="opra1"
cReadRel = readOpram
cShowRel = showOpram
cSparqifyRel = sparqifyOpram
cGqrifyRel = sparqifyOpram
cBaserelationsArealList = areal cBaserelationsList
cBaserelationsNonArealList = nonAreal cBaserelationsList
identity = Opra1_s_0
bcConvert = opraConvert 1
-- bcComposition = Map.fromList
-- [ ( ( Opra1_0_0 , Opra1_0_0 )
-- , Set.fromList [ Opra1_2_0, Opra1_0_2, Opra1_s_0 ] )
-- , ( ( Opra1_0_0 , Opra1_0_1 )
-- , Set.fromList [ Opra1_s_3, Opra1_2_1, Opra1_0_3 ] )
-- , ( ( Opra1_0_0 , Opra1_0_2 )
-- , Set.fromList [ Opra1_2_2, Opra1_s_2, Opra1_0_0 ] )
-- , ( ( Opra1_0_0 , Opra1_0_3 )
-- , Set.fromList [ Opra1_2_3, Opra1_s_1, Opra1_0_1 ] )
-- , ( ( Opra1_0_0 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_0_0 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_0_0 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_0_0 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_0_0 , Opra1_2_0 )
-- , Set.fromList [ Opra1_0_0 ] )
-- , ( ( Opra1_0_0 , Opra1_2_1 )
-- , Set.fromList [ Opra1_0_1 ] )
-- , ( ( Opra1_0_0 , Opra1_2_2 )
-- , Set.fromList [ Opra1_0_2 ] )
-- , ( ( Opra1_0_0 , Opra1_2_3 )
-- , Set.fromList [ Opra1_0_3 ] )
-- , ( ( Opra1_0_0 , Opra1_3_0 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_0_0 , Opra1_3_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_0_0 , Opra1_3_2 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_0_0 , Opra1_3_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_0_0 , Opra1_s_0 )
-- , Set.fromList [ Opra1_0_0 ] )
-- , ( ( Opra1_0_0 , Opra1_s_1 )
-- , Set.fromList [ Opra1_0_3 ] )
-- , ( ( Opra1_0_0 , Opra1_s_2 )
-- , Set.fromList [ Opra1_0_2 ] )
-- , ( ( Opra1_0_0 , Opra1_s_3 )
-- , Set.fromList [ Opra1_0_1 ] )
-- , ( ( Opra1_0_1 , Opra1_0_0 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_0_1 , Opra1_0_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_0_1 , Opra1_0_2 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_0_1 , Opra1_0_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_0_1 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_0, Opra1_1_3, Opra1_0_2
-- , Opra1_s_0 ] )
-- , ( ( Opra1_0_1 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_s_3
-- , Opra1_2_1, Opra1_1_3, Opra1_1_1, Opra1_1_0
-- , Opra1_0_3 ] )
-- , ( ( Opra1_0_1 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_2, Opra1_s_2, Opra1_1_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_0_1 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_s_1
-- , Opra1_0_1 ] )
-- , ( ( Opra1_0_1 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_0_1 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_0_1 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_0_1 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_0_1 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_3, Opra1_0_0 ] )
-- , ( ( Opra1_0_1 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_1 ] )
-- , ( ( Opra1_0_1 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_1, Opra1_0_2 ] )
-- , ( ( Opra1_0_1 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3 ] )
-- , ( ( Opra1_0_1 , Opra1_s_0 )
-- , Set.fromList [ Opra1_0_1 ] )
-- , ( ( Opra1_0_1 , Opra1_s_1 )
-- , Set.fromList [ Opra1_0_3, Opra1_0_1, Opra1_0_0 ] )
-- , ( ( Opra1_0_1 , Opra1_s_2 )
-- , Set.fromList [ Opra1_0_3 ] )
-- , ( ( Opra1_0_1 , Opra1_s_3 )
-- , Set.fromList [ Opra1_0_3, Opra1_0_2, Opra1_0_1 ] )
-- , ( ( Opra1_0_2 , Opra1_0_0 )
-- , Set.fromList [ Opra1_0_0 ] )
-- , ( ( Opra1_0_2 , Opra1_0_1 )
-- , Set.fromList [ Opra1_0_1 ] )
-- , ( ( Opra1_0_2 , Opra1_0_2 )
-- , Set.fromList [ Opra1_0_2 ] )
-- , ( ( Opra1_0_2 , Opra1_0_3 )
-- , Set.fromList [ Opra1_0_3 ] )
-- , ( ( Opra1_0_2 , Opra1_1_0 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_0_2 , Opra1_1_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_0_2 , Opra1_1_2 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_0_2 , Opra1_1_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_0_2 , Opra1_2_0 )
-- , Set.fromList [ Opra1_2_0, Opra1_0_2, Opra1_s_0 ] )
-- , ( ( Opra1_0_2 , Opra1_2_1 )
-- , Set.fromList [ Opra1_s_3, Opra1_2_1, Opra1_0_3 ] )
-- , ( ( Opra1_0_2 , Opra1_2_2 )
-- , Set.fromList [ Opra1_2_2, Opra1_s_2, Opra1_0_0 ] )
-- , ( ( Opra1_0_2 , Opra1_2_3 )
-- , Set.fromList [ Opra1_2_3, Opra1_s_1, Opra1_0_1 ] )
-- , ( ( Opra1_0_2 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_0_2 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_0_2 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_0_2 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_0_2 , Opra1_s_0 )
-- , Set.fromList [ Opra1_0_2 ] )
-- , ( ( Opra1_0_2 , Opra1_s_1 )
-- , Set.fromList [ Opra1_0_1 ] )
-- , ( ( Opra1_0_2 , Opra1_s_2 )
-- , Set.fromList [ Opra1_0_0 ] )
-- , ( ( Opra1_0_2 , Opra1_s_3 )
-- , Set.fromList [ Opra1_0_3 ] )
-- , ( ( Opra1_0_3 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_0_3 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_0_3 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_0_3 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_0_3 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_3, Opra1_0_0 ] )
-- , ( ( Opra1_0_3 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_1 ] )
-- , ( ( Opra1_0_3 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_1, Opra1_0_2 ] )
-- , ( ( Opra1_0_3 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3 ] )
-- , ( ( Opra1_0_3 , Opra1_2_0 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_0_3 , Opra1_2_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_0_3 , Opra1_2_2 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_0_3 , Opra1_2_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_0_3 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_0, Opra1_1_3, Opra1_0_2
-- , Opra1_s_0 ] )
-- , ( ( Opra1_0_3 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_s_3
-- , Opra1_2_1, Opra1_1_3, Opra1_1_1, Opra1_1_0
-- , Opra1_0_3 ] )
-- , ( ( Opra1_0_3 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_2, Opra1_s_2, Opra1_1_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_0_3 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_s_1
-- , Opra1_0_1 ] )
-- , ( ( Opra1_0_3 , Opra1_s_0 )
-- , Set.fromList [ Opra1_0_3 ] )
-- , ( ( Opra1_0_3 , Opra1_s_1 )
-- , Set.fromList [ Opra1_0_3, Opra1_0_2, Opra1_0_1 ] )
-- , ( ( Opra1_0_3 , Opra1_s_2 )
-- , Set.fromList [ Opra1_0_1 ] )
-- , ( ( Opra1_0_3 , Opra1_s_3 )
-- , Set.fromList [ Opra1_0_3, Opra1_0_1, Opra1_0_0 ] )
-- , ( ( Opra1_1_0 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_0, Opra1_1_2, Opra1_s_1 ] )
-- , ( ( Opra1_1_0 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_1, Opra1_s_3, Opra1_1_3, Opra1_s_1
-- , Opra1_s_0 ] )
-- , ( ( Opra1_1_0 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_2, Opra1_s_3, Opra1_1_0 ] )
-- , ( ( Opra1_1_0 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_s_3, Opra1_s_2, Opra1_1_1
-- , Opra1_s_1 ] )
-- , ( ( Opra1_1_0 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_1_0 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3, Opra1_0_2
-- , Opra1_0_1 ] )
-- , ( ( Opra1_1_0 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_1_0 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_1_0 , Opra1_2_0 )
-- , Set.fromList [ Opra1_1_0 ] )
-- , ( ( Opra1_1_0 , Opra1_2_1 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_1_0 , Opra1_2_2 )
-- , Set.fromList [ Opra1_1_2 ] )
-- , ( ( Opra1_1_0 , Opra1_2_3 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_1_0 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_1_0 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_2_1, Opra1_2_0, Opra1_1_3, Opra1_1_1
-- , Opra1_1_0 ] )
-- , ( ( Opra1_1_0 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_1_0 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_2_2, Opra1_2_1, Opra1_1_3, Opra1_1_2
-- , Opra1_1_1 ] )
-- , ( ( Opra1_1_0 , Opra1_s_0 )
-- , Set.fromList [ Opra1_1_0 ] )
-- , ( ( Opra1_1_0 , Opra1_s_1 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_1_0 , Opra1_s_2 )
-- , Set.fromList [ Opra1_1_2 ] )
-- , ( ( Opra1_1_0 , Opra1_s_3 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_1_1 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_1_1 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_2_1, Opra1_2_0, Opra1_1_3, Opra1_1_1
-- , Opra1_1_0 ] )
-- , ( ( Opra1_1_1 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_1_1 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_2_2, Opra1_2_1, Opra1_1_3, Opra1_1_2
-- , Opra1_1_1 ] )
-- , ( ( Opra1_1_1 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_s_1
-- , Opra1_0_1 ] )
-- , ( ( Opra1_1_1 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_s_3, Opra1_2_3, Opra1_2_1, Opra1_2_0
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_1_0
-- , Opra1_s_1, Opra1_0_3, Opra1_0_2, Opra1_0_1
-- , Opra1_s_0 ] )
-- , ( ( Opra1_1_1 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_s_3
-- , Opra1_2_1, Opra1_1_3, Opra1_1_1, Opra1_1_0
-- , Opra1_0_3 ] )
-- , ( ( Opra1_1_1 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_s_3, Opra1_2_3, Opra1_2_2, Opra1_2_1
-- , Opra1_s_2, Opra1_1_3, Opra1_1_2, Opra1_1_1
-- , Opra1_1_0, Opra1_s_1, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_1_1 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_1_1 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3, Opra1_0_2
-- , Opra1_0_1 ] )
-- , ( ( Opra1_1_1 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_1_1 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_1_1 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_2_3, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_1 ] )
-- , ( ( Opra1_1_1 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_2_3, Opra1_2_1, Opra1_2_0, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_1_0, Opra1_0_3
-- , Opra1_0_2, Opra1_0_1 ] )
-- , ( ( Opra1_1_1 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_2_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3 ] )
-- , ( ( Opra1_1_1 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_2_3, Opra1_2_2, Opra1_2_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_1_0, Opra1_0_3
-- , Opra1_0_1, Opra1_0_0 ] )
-- , ( ( Opra1_1_1 , Opra1_s_0 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_1_1 , Opra1_s_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_1_1 , Opra1_s_2 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_1_1 , Opra1_s_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_1_2 , Opra1_0_0 )
-- , Set.fromList [ Opra1_1_0 ] )
-- , ( ( Opra1_1_2 , Opra1_0_1 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_1_2 , Opra1_0_2 )
-- , Set.fromList [ Opra1_1_2 ] )
-- , ( ( Opra1_1_2 , Opra1_0_3 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_1_2 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_1_2 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_2_1, Opra1_2_0, Opra1_1_3, Opra1_1_1
-- , Opra1_1_0 ] )
-- , ( ( Opra1_1_2 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_1_2 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_2_2, Opra1_2_1, Opra1_1_3, Opra1_1_2
-- , Opra1_1_1 ] )
-- , ( ( Opra1_1_2 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_0, Opra1_1_2, Opra1_s_1 ] )
-- , ( ( Opra1_1_2 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_1, Opra1_s_3, Opra1_1_3, Opra1_s_1
-- , Opra1_s_0 ] )
-- , ( ( Opra1_1_2 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_2, Opra1_s_3, Opra1_1_0 ] )
-- , ( ( Opra1_1_2 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_s_3, Opra1_s_2, Opra1_1_1
-- , Opra1_s_1 ] )
-- , ( ( Opra1_1_2 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_1_2 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3, Opra1_0_2
-- , Opra1_0_1 ] )
-- , ( ( Opra1_1_2 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_1_2 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_1_2 , Opra1_s_0 )
-- , Set.fromList [ Opra1_1_2 ] )
-- , ( ( Opra1_1_2 , Opra1_s_1 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_1_2 , Opra1_s_2 )
-- , Set.fromList [ Opra1_1_0 ] )
-- , ( ( Opra1_1_2 , Opra1_s_3 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_1_3 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_1_3 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3, Opra1_0_2
-- , Opra1_0_1 ] )
-- , ( ( Opra1_1_3 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_1_3 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_1_3 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_2_3, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_1 ] )
-- , ( ( Opra1_1_3 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_2_3, Opra1_2_1, Opra1_2_0, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_1_0, Opra1_0_3
-- , Opra1_0_2, Opra1_0_1 ] )
-- , ( ( Opra1_1_3 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_2_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3 ] )
-- , ( ( Opra1_1_3 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_2_3, Opra1_2_2, Opra1_2_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_1_0, Opra1_0_3
-- , Opra1_0_1, Opra1_0_0 ] )
-- , ( ( Opra1_1_3 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_1_3 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_2_1, Opra1_2_0, Opra1_1_3, Opra1_1_1
-- , Opra1_1_0 ] )
-- , ( ( Opra1_1_3 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_1_3 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_2_2, Opra1_2_1, Opra1_1_3, Opra1_1_2
-- , Opra1_1_1 ] )
-- , ( ( Opra1_1_3 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_s_1
-- , Opra1_0_1 ] )
-- , ( ( Opra1_1_3 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_s_3, Opra1_2_3, Opra1_2_1, Opra1_2_0
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_1_0
-- , Opra1_s_1, Opra1_0_3, Opra1_0_2, Opra1_0_1
-- , Opra1_s_0 ] )
-- , ( ( Opra1_1_3 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_s_3
-- , Opra1_2_1, Opra1_1_3, Opra1_1_1, Opra1_1_0
-- , Opra1_0_3 ] )
-- , ( ( Opra1_1_3 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_s_3, Opra1_2_3, Opra1_2_2, Opra1_2_1
-- , Opra1_s_2, Opra1_1_3, Opra1_1_2, Opra1_1_1
-- , Opra1_1_0, Opra1_s_1, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_1_3 , Opra1_s_0 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_1_3 , Opra1_s_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_1_3 , Opra1_s_2 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_1_3 , Opra1_s_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_2_0 , Opra1_0_0 )
-- , Set.fromList [ Opra1_2_2, Opra1_s_2, Opra1_0_0 ] )
-- , ( ( Opra1_2_0 , Opra1_0_1 )
-- , Set.fromList [ Opra1_2_3, Opra1_s_1, Opra1_0_1 ] )
-- , ( ( Opra1_2_0 , Opra1_0_2 )
-- , Set.fromList [ Opra1_2_0, Opra1_0_2, Opra1_s_0 ] )
-- , ( ( Opra1_2_0 , Opra1_0_3 )
-- , Set.fromList [ Opra1_s_3, Opra1_2_1, Opra1_0_3 ] )
-- , ( ( Opra1_2_0 , Opra1_1_0 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_2_0 , Opra1_1_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_2_0 , Opra1_1_2 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_2_0 , Opra1_1_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_2_0 , Opra1_2_0 )
-- , Set.fromList [ Opra1_2_0 ] )
-- , ( ( Opra1_2_0 , Opra1_2_1 )
-- , Set.fromList [ Opra1_2_1 ] )
-- , ( ( Opra1_2_0 , Opra1_2_2 )
-- , Set.fromList [ Opra1_2_2 ] )
-- , ( ( Opra1_2_0 , Opra1_2_3 )
-- , Set.fromList [ Opra1_2_3 ] )
-- , ( ( Opra1_2_0 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_2_0 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_2_0 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_2_0 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_2_0 , Opra1_s_0 )
-- , Set.fromList [ Opra1_2_0 ] )
-- , ( ( Opra1_2_0 , Opra1_s_1 )
-- , Set.fromList [ Opra1_2_3 ] )
-- , ( ( Opra1_2_0 , Opra1_s_2 )
-- , Set.fromList [ Opra1_2_2 ] )
-- , ( ( Opra1_2_0 , Opra1_s_3 )
-- , Set.fromList [ Opra1_2_1 ] )
-- , ( ( Opra1_2_1 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_2_1 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_2_1 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_2_1 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_2_1 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_2, Opra1_s_2, Opra1_1_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_2_1 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_s_1
-- , Opra1_0_1 ] )
-- , ( ( Opra1_2_1 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_0, Opra1_1_3, Opra1_0_2
-- , Opra1_s_0 ] )
-- , ( ( Opra1_2_1 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_s_3
-- , Opra1_2_1, Opra1_1_3, Opra1_1_1, Opra1_1_0
-- , Opra1_0_3 ] )
-- , ( ( Opra1_2_1 , Opra1_2_0 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_2_1 , Opra1_2_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_2_1 , Opra1_2_2 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_2_1 , Opra1_2_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_2_1 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_0, Opra1_1_1 ] )
-- , ( ( Opra1_2_1 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_1
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_2_1 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_2, Opra1_1_3 ] )
-- , ( ( Opra1_2_1 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_2_1 , Opra1_s_0 )
-- , Set.fromList [ Opra1_2_1 ] )
-- , ( ( Opra1_2_1 , Opra1_s_1 )
-- , Set.fromList [ Opra1_2_3, Opra1_2_1, Opra1_2_0 ] )
-- , ( ( Opra1_2_1 , Opra1_s_2 )
-- , Set.fromList [ Opra1_2_3 ] )
-- , ( ( Opra1_2_1 , Opra1_s_3 )
-- , Set.fromList [ Opra1_2_3, Opra1_2_2, Opra1_2_1 ] )
-- , ( ( Opra1_2_2 , Opra1_0_0 )
-- , Set.fromList [ Opra1_2_0 ] )
-- , ( ( Opra1_2_2 , Opra1_0_1 )
-- , Set.fromList [ Opra1_2_1 ] )
-- , ( ( Opra1_2_2 , Opra1_0_2 )
-- , Set.fromList [ Opra1_2_2 ] )
-- , ( ( Opra1_2_2 , Opra1_0_3 )
-- , Set.fromList [ Opra1_2_3 ] )
-- , ( ( Opra1_2_2 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_2_2 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_2_2 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_2_2 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_2_2 , Opra1_2_0 )
-- , Set.fromList [ Opra1_2_2, Opra1_s_2, Opra1_0_0 ] )
-- , ( ( Opra1_2_2 , Opra1_2_1 )
-- , Set.fromList [ Opra1_2_3, Opra1_s_1, Opra1_0_1 ] )
-- , ( ( Opra1_2_2 , Opra1_2_2 )
-- , Set.fromList [ Opra1_2_0, Opra1_0_2, Opra1_s_0 ] )
-- , ( ( Opra1_2_2 , Opra1_2_3 )
-- , Set.fromList [ Opra1_s_3, Opra1_2_1, Opra1_0_3 ] )
-- , ( ( Opra1_2_2 , Opra1_3_0 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_2_2 , Opra1_3_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_2_2 , Opra1_3_2 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_2_2 , Opra1_3_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_2_2 , Opra1_s_0 )
-- , Set.fromList [ Opra1_2_2 ] )
-- , ( ( Opra1_2_2 , Opra1_s_1 )
-- , Set.fromList [ Opra1_2_1 ] )
-- , ( ( Opra1_2_2 , Opra1_s_2 )
-- , Set.fromList [ Opra1_2_0 ] )
-- , ( ( Opra1_2_2 , Opra1_s_3 )
-- , Set.fromList [ Opra1_2_3 ] )
-- , ( ( Opra1_2_3 , Opra1_0_0 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_2_3 , Opra1_0_1 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_2_3 , Opra1_0_2 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_2_3 , Opra1_0_3 )
-- , Set.fromList [ Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_2_3 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_0, Opra1_1_1 ] )
-- , ( ( Opra1_2_3 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_1
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1 ] )
-- , ( ( Opra1_2_3 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_2, Opra1_1_3 ] )
-- , ( ( Opra1_2_3 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_1_3, Opra1_1_1, Opra1_1_0 ] )
-- , ( ( Opra1_2_3 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_2_3 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_2_3 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_2_3 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_2_3 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_2, Opra1_s_2, Opra1_1_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_2_3 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_s_1
-- , Opra1_0_1 ] )
-- , ( ( Opra1_2_3 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_0, Opra1_1_3, Opra1_0_2
-- , Opra1_s_0 ] )
-- , ( ( Opra1_2_3 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_s_3
-- , Opra1_2_1, Opra1_1_3, Opra1_1_1, Opra1_1_0
-- , Opra1_0_3 ] )
-- , ( ( Opra1_2_3 , Opra1_s_0 )
-- , Set.fromList [ Opra1_2_3 ] )
-- , ( ( Opra1_2_3 , Opra1_s_1 )
-- , Set.fromList [ Opra1_2_3, Opra1_2_2, Opra1_2_1 ] )
-- , ( ( Opra1_2_3 , Opra1_s_2 )
-- , Set.fromList [ Opra1_2_1 ] )
-- , ( ( Opra1_2_3 , Opra1_s_3 )
-- , Set.fromList [ Opra1_2_3, Opra1_2_1, Opra1_2_0 ] )
-- , ( ( Opra1_3_0 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_2, Opra1_s_3, Opra1_1_0 ] )
-- , ( ( Opra1_3_0 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_s_3, Opra1_s_2, Opra1_1_1
-- , Opra1_s_1 ] )
-- , ( ( Opra1_3_0 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_0, Opra1_1_2, Opra1_s_1 ] )
-- , ( ( Opra1_3_0 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_1, Opra1_s_3, Opra1_1_3, Opra1_s_1
-- , Opra1_s_0 ] )
-- , ( ( Opra1_3_0 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_3_0 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_2_2, Opra1_2_1, Opra1_1_3, Opra1_1_2
-- , Opra1_1_1 ] )
-- , ( ( Opra1_3_0 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_3_0 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_2_1, Opra1_2_0, Opra1_1_3, Opra1_1_1
-- , Opra1_1_0 ] )
-- , ( ( Opra1_3_0 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_0 ] )
-- , ( ( Opra1_3_0 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_3_0 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_2 ] )
-- , ( ( Opra1_3_0 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_3_0 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_3_0 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_3_0 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_3_0 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3, Opra1_0_2
-- , Opra1_0_1 ] )
-- , ( ( Opra1_3_0 , Opra1_s_0 )
-- , Set.fromList [ Opra1_3_0 ] )
-- , ( ( Opra1_3_0 , Opra1_s_1 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_3_0 , Opra1_s_2 )
-- , Set.fromList [ Opra1_3_2 ] )
-- , ( ( Opra1_3_0 , Opra1_s_3 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_3_1 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_3_1 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_3_1 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_3_1 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3, Opra1_0_2
-- , Opra1_0_1 ] )
-- , ( ( Opra1_3_1 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_s_3
-- , Opra1_2_1, Opra1_1_3, Opra1_1_1, Opra1_1_0
-- , Opra1_0_3 ] )
-- , ( ( Opra1_3_1 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_s_3, Opra1_2_3, Opra1_2_2, Opra1_2_1
-- , Opra1_s_2, Opra1_1_3, Opra1_1_2, Opra1_1_1
-- , Opra1_1_0, Opra1_s_1, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_3_1 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_s_1
-- , Opra1_0_1 ] )
-- , ( ( Opra1_3_1 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_s_3, Opra1_2_3, Opra1_2_1, Opra1_2_0
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_1_0
-- , Opra1_s_1, Opra1_0_3, Opra1_0_2, Opra1_0_1
-- , Opra1_s_0 ] )
-- , ( ( Opra1_3_1 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_3_1 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_2_2, Opra1_2_1, Opra1_1_3, Opra1_1_2
-- , Opra1_1_1 ] )
-- , ( ( Opra1_3_1 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_3_1 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_2_1, Opra1_2_0, Opra1_1_3, Opra1_1_1
-- , Opra1_1_0 ] )
-- , ( ( Opra1_3_1 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_1
-- , Opra1_1_3, Opra1_1_1, Opra1_0_3 ] )
-- , ( ( Opra1_3_1 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_2_3, Opra1_2_2, Opra1_2_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_1_0, Opra1_0_3
-- , Opra1_0_1, Opra1_0_0 ] )
-- , ( ( Opra1_3_1 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_1_3, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_3_1 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_2_3, Opra1_2_1, Opra1_2_0, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_1_0, Opra1_0_3
-- , Opra1_0_2, Opra1_0_1 ] )
-- , ( ( Opra1_3_1 , Opra1_s_0 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_3_1 , Opra1_s_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_3_1 , Opra1_s_2 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_3_1 , Opra1_s_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_3_2 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_0 ] )
-- , ( ( Opra1_3_2 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_3_2 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_2 ] )
-- , ( ( Opra1_3_2 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_3_2 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_3_2 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_3_2 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_3_2 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3, Opra1_0_2
-- , Opra1_0_1 ] )
-- , ( ( Opra1_3_2 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_2, Opra1_s_3, Opra1_1_0 ] )
-- , ( ( Opra1_3_2 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_s_3, Opra1_s_2, Opra1_1_1
-- , Opra1_s_1 ] )
-- , ( ( Opra1_3_2 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_0, Opra1_1_2, Opra1_s_1 ] )
-- , ( ( Opra1_3_2 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_1, Opra1_s_3, Opra1_1_3, Opra1_s_1
-- , Opra1_s_0 ] )
-- , ( ( Opra1_3_2 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_3_2 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_2_2, Opra1_2_1, Opra1_1_3, Opra1_1_2
-- , Opra1_1_1 ] )
-- , ( ( Opra1_3_2 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_3_2 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_2_1, Opra1_2_0, Opra1_1_3, Opra1_1_1
-- , Opra1_1_0 ] )
-- , ( ( Opra1_3_2 , Opra1_s_0 )
-- , Set.fromList [ Opra1_3_2 ] )
-- , ( ( Opra1_3_2 , Opra1_s_1 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_3_2 , Opra1_s_2 )
-- , Set.fromList [ Opra1_3_0 ] )
-- , ( ( Opra1_3_2 , Opra1_s_3 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_3_3 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_3_3 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_2_2, Opra1_2_1, Opra1_1_3, Opra1_1_2
-- , Opra1_1_1 ] )
-- , ( ( Opra1_3_3 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_3_3 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_2_1, Opra1_2_0, Opra1_1_3, Opra1_1_1
-- , Opra1_1_0 ] )
-- , ( ( Opra1_3_3 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_1
-- , Opra1_1_3, Opra1_1_1, Opra1_0_3 ] )
-- , ( ( Opra1_3_3 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_2_3, Opra1_2_2, Opra1_2_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_1_0, Opra1_0_3
-- , Opra1_0_1, Opra1_0_0 ] )
-- , ( ( Opra1_3_3 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_2_3
-- , Opra1_1_3, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_3_3 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_2_3, Opra1_2_1, Opra1_2_0, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_1_0, Opra1_0_3
-- , Opra1_0_2, Opra1_0_1 ] )
-- , ( ( Opra1_3_3 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_3_3 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_1_3
-- , Opra1_1_1, Opra1_1_0, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_3_3 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_3_3 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_1_3
-- , Opra1_1_2, Opra1_1_1, Opra1_0_3, Opra1_0_2
-- , Opra1_0_1 ] )
-- , ( ( Opra1_3_3 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_s_3
-- , Opra1_2_1, Opra1_1_3, Opra1_1_1, Opra1_1_0
-- , Opra1_0_3 ] )
-- , ( ( Opra1_3_3 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_s_3, Opra1_2_3, Opra1_2_2, Opra1_2_1
-- , Opra1_s_2, Opra1_1_3, Opra1_1_2, Opra1_1_1
-- , Opra1_1_0, Opra1_s_1, Opra1_0_3, Opra1_0_1
-- , Opra1_0_0 ] )
-- , ( ( Opra1_3_3 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0, Opra1_2_3
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_s_1
-- , Opra1_0_1 ] )
-- , ( ( Opra1_3_3 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1, Opra1_3_0
-- , Opra1_s_3, Opra1_2_3, Opra1_2_1, Opra1_2_0
-- , Opra1_1_3, Opra1_1_2, Opra1_1_1, Opra1_1_0
-- , Opra1_s_1, Opra1_0_3, Opra1_0_2, Opra1_0_1
-- , Opra1_s_0 ] )
-- , ( ( Opra1_3_3 , Opra1_s_0 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_3_3 , Opra1_s_1 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_2, Opra1_3_1 ] )
-- , ( ( Opra1_3_3 , Opra1_s_2 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_3_3 , Opra1_s_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_3_1, Opra1_3_0 ] )
-- , ( ( Opra1_s_0 , Opra1_0_0 )
-- , Set.fromList [ Opra1_0_0 ] )
-- , ( ( Opra1_s_0 , Opra1_0_1 )
-- , Set.fromList [ Opra1_0_1 ] )
-- , ( ( Opra1_s_0 , Opra1_0_2 )
-- , Set.fromList [ Opra1_0_2 ] )
-- , ( ( Opra1_s_0 , Opra1_0_3 )
-- , Set.fromList [ Opra1_0_3 ] )
-- , ( ( Opra1_s_0 , Opra1_1_0 )
-- , Set.fromList [ Opra1_1_0 ] )
-- , ( ( Opra1_s_0 , Opra1_1_1 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_s_0 , Opra1_1_2 )
-- , Set.fromList [ Opra1_1_2 ] )
-- , ( ( Opra1_s_0 , Opra1_1_3 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_s_0 , Opra1_2_0 )
-- , Set.fromList [ Opra1_2_0 ] )
-- , ( ( Opra1_s_0 , Opra1_2_1 )
-- , Set.fromList [ Opra1_2_1 ] )
-- , ( ( Opra1_s_0 , Opra1_2_2 )
-- , Set.fromList [ Opra1_2_2 ] )
-- , ( ( Opra1_s_0 , Opra1_2_3 )
-- , Set.fromList [ Opra1_2_3 ] )
-- , ( ( Opra1_s_0 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_0 ] )
-- , ( ( Opra1_s_0 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_s_0 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_2 ] )
-- , ( ( Opra1_s_0 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_s_0 , Opra1_s_0 )
-- , Set.fromList [ Opra1_s_0 ] )
-- , ( ( Opra1_s_0 , Opra1_s_1 )
-- , Set.fromList [ Opra1_s_1 ] )
-- , ( ( Opra1_s_0 , Opra1_s_2 )
-- , Set.fromList [ Opra1_s_2 ] )
-- , ( ( Opra1_s_0 , Opra1_s_3 )
-- , Set.fromList [ Opra1_s_3 ] )
-- , ( ( Opra1_s_1 , Opra1_0_0 )
-- , Set.fromList [ Opra1_1_0 ] )
-- , ( ( Opra1_s_1 , Opra1_0_1 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_s_1 , Opra1_0_2 )
-- , Set.fromList [ Opra1_1_2 ] )
-- , ( ( Opra1_s_1 , Opra1_0_3 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_s_1 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_0, Opra1_2_0, Opra1_1_0 ] )
-- , ( ( Opra1_s_1 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_s_1 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_2, Opra1_2_2, Opra1_1_2 ] )
-- , ( ( Opra1_s_1 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_s_1 , Opra1_2_0 )
-- , Set.fromList [ Opra1_3_0 ] )
-- , ( ( Opra1_s_1 , Opra1_2_1 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_s_1 , Opra1_2_2 )
-- , Set.fromList [ Opra1_3_2 ] )
-- , ( ( Opra1_s_1 , Opra1_2_3 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_s_1 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_0, Opra1_1_0, Opra1_0_0 ] )
-- , ( ( Opra1_s_1 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_s_1 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_2, Opra1_1_2, Opra1_0_2 ] )
-- , ( ( Opra1_s_1 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_s_1 , Opra1_s_0 )
-- , Set.fromList [ Opra1_s_1 ] )
-- , ( ( Opra1_s_1 , Opra1_s_1 )
-- , Set.fromList [ Opra1_s_3, Opra1_s_2, Opra1_s_1 ] )
-- , ( ( Opra1_s_1 , Opra1_s_2 )
-- , Set.fromList [ Opra1_s_3 ] )
-- , ( ( Opra1_s_1 , Opra1_s_3 )
-- , Set.fromList [ Opra1_s_3, Opra1_s_1, Opra1_s_0 ] )
-- , ( ( Opra1_s_2 , Opra1_0_0 )
-- , Set.fromList [ Opra1_2_0 ] )
-- , ( ( Opra1_s_2 , Opra1_0_1 )
-- , Set.fromList [ Opra1_2_1 ] )
-- , ( ( Opra1_s_2 , Opra1_0_2 )
-- , Set.fromList [ Opra1_2_2 ] )
-- , ( ( Opra1_s_2 , Opra1_0_3 )
-- , Set.fromList [ Opra1_2_3 ] )
-- , ( ( Opra1_s_2 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_0 ] )
-- , ( ( Opra1_s_2 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_s_2 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_2 ] )
-- , ( ( Opra1_s_2 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_s_2 , Opra1_2_0 )
-- , Set.fromList [ Opra1_0_0 ] )
-- , ( ( Opra1_s_2 , Opra1_2_1 )
-- , Set.fromList [ Opra1_0_1 ] )
-- , ( ( Opra1_s_2 , Opra1_2_2 )
-- , Set.fromList [ Opra1_0_2 ] )
-- , ( ( Opra1_s_2 , Opra1_2_3 )
-- , Set.fromList [ Opra1_0_3 ] )
-- , ( ( Opra1_s_2 , Opra1_3_0 )
-- , Set.fromList [ Opra1_1_0 ] )
-- , ( ( Opra1_s_2 , Opra1_3_1 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_s_2 , Opra1_3_2 )
-- , Set.fromList [ Opra1_1_2 ] )
-- , ( ( Opra1_s_2 , Opra1_3_3 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_s_2 , Opra1_s_0 )
-- , Set.fromList [ Opra1_s_2 ] )
-- , ( ( Opra1_s_2 , Opra1_s_1 )
-- , Set.fromList [ Opra1_s_3 ] )
-- , ( ( Opra1_s_2 , Opra1_s_2 )
-- , Set.fromList [ Opra1_s_0 ] )
-- , ( ( Opra1_s_2 , Opra1_s_3 )
-- , Set.fromList [ Opra1_s_1 ] )
-- , ( ( Opra1_s_3 , Opra1_0_0 )
-- , Set.fromList [ Opra1_3_0 ] )
-- , ( ( Opra1_s_3 , Opra1_0_1 )
-- , Set.fromList [ Opra1_3_1 ] )
-- , ( ( Opra1_s_3 , Opra1_0_2 )
-- , Set.fromList [ Opra1_3_2 ] )
-- , ( ( Opra1_s_3 , Opra1_0_3 )
-- , Set.fromList [ Opra1_3_3 ] )
-- , ( ( Opra1_s_3 , Opra1_1_0 )
-- , Set.fromList [ Opra1_3_0, Opra1_1_0, Opra1_0_0 ] )
-- , ( ( Opra1_s_3 , Opra1_1_1 )
-- , Set.fromList [ Opra1_3_1, Opra1_1_1, Opra1_0_1 ] )
-- , ( ( Opra1_s_3 , Opra1_1_2 )
-- , Set.fromList [ Opra1_3_2, Opra1_1_2, Opra1_0_2 ] )
-- , ( ( Opra1_s_3 , Opra1_1_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_1_3, Opra1_0_3 ] )
-- , ( ( Opra1_s_3 , Opra1_2_0 )
-- , Set.fromList [ Opra1_1_0 ] )
-- , ( ( Opra1_s_3 , Opra1_2_1 )
-- , Set.fromList [ Opra1_1_1 ] )
-- , ( ( Opra1_s_3 , Opra1_2_2 )
-- , Set.fromList [ Opra1_1_2 ] )
-- , ( ( Opra1_s_3 , Opra1_2_3 )
-- , Set.fromList [ Opra1_1_3 ] )
-- , ( ( Opra1_s_3 , Opra1_3_0 )
-- , Set.fromList [ Opra1_3_0, Opra1_2_0, Opra1_1_0 ] )
-- , ( ( Opra1_s_3 , Opra1_3_1 )
-- , Set.fromList [ Opra1_3_1, Opra1_2_1, Opra1_1_1 ] )
-- , ( ( Opra1_s_3 , Opra1_3_2 )
-- , Set.fromList [ Opra1_3_2, Opra1_2_2, Opra1_1_2 ] )
-- , ( ( Opra1_s_3 , Opra1_3_3 )
-- , Set.fromList [ Opra1_3_3, Opra1_2_3, Opra1_1_3 ] )
-- , ( ( Opra1_s_3 , Opra1_s_0 )
-- , Set.fromList [ Opra1_s_3 ] )
-- , ( ( Opra1_s_3 , Opra1_s_1 )
-- , Set.fromList [ Opra1_s_3, Opra1_s_1, Opra1_s_0 ] )
-- , ( ( Opra1_s_3 , Opra1_s_2 )
-- , Set.fromList [ Opra1_s_1 ] )
-- , ( ( Opra1_s_3 , Opra1_s_3 )
-- , Set.fromList [ Opra1_s_3, Opra1_s_2, Opra1_s_1 ] )
-- ]
| spatial-reasoning/zeno | src/Calculus/Opra1.hs | bsd-2-clause | 50,817 | 0 | 6 | 18,479 | 1,214 | 1,122 | 92 | 26 | 0 |
module Handler.Root where
import Import
import Data.Int
data MemoForm = MemoForm {
text :: Textarea
}
selectAllMemos = do
selectList [] []
memoForm :: Html -> MForm Jabaraster Jabaraster (FormResult MemoForm, Widget)
memoForm = renderDivs $ MemoForm
<$> areq textareaField "あたらしいメモ" Nothing
getRootR :: Handler RepHtml
getRootR = do
((_, widget), enctype) <- runFormPost memoForm
memos <- runDB $ selectAllMemos
defaultLayout $ do
setTitle "first-heroku homepage"
$(widgetFile "homepage")
postRootR :: Handler RepHtml
postRootR = do
((result, _), _) <- runFormPost memoForm
case result of
FormSuccess form -> do
_ <- runDB $ insert Memo {
memoText = unTextarea $ text form
}
redirect RedirectSeeOther RootR
_ -> do
redirect RedirectSeeOther RootR
fromKey :: Key backend entity -> Integer
fromKey key = case (fromPersistValue $ unKey key) :: Either String Int64 of
Left s -> read s
Right i -> read $ show i
| jabaraster/first-heroku | Handler/Root.hs | bsd-2-clause | 1,079 | 0 | 18 | 302 | 334 | 165 | 169 | 31 | 2 |
-- Copyright 2020 Google LLC
--
-- Use of this source code is governed by a BSD-style
-- license that can be found in the LICENSE file or at
-- https://developers.google.com/open-source/licenses/bsd
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE UndecidableInstances #-}
module Export (
exportFunctions, prepareFunctionForExport, exportedSignatureDesc,
ExportedSignature (..), ExportType (..), ExportArg (..), ExportResult (..),
) where
import Data.List (intercalate)
import Control.Monad
import Name
import MTL1
import Err
import Syntax
import Type
import Builder
import Simplify
import Imp
import Util (scanM)
exportFunctions :: FilePath -> [(String, Atom n)] -> Env n -> IO ()
exportFunctions = error "Not implemented"
prepareFunctionForExport :: (EnvReader m, Fallible1 m) => Atom n -> m n (ImpFunction n, ExportedSignature VoidS)
prepareFunctionForExport f = do
naryPi <- getType f >>= asFirstOrderFunction >>= \case
Nothing -> throw TypeErr "Only first-order functions can be exported"
Just npi -> return npi
closedNaryPi <- case hoistToTop naryPi of
HoistFailure _ -> throw TypeErr "Types of exported functions have to be closed terms"
HoistSuccess npi -> return npi
sig <- case runFallibleM $ runEnvReaderT emptyOutMap $ naryPiToExportSig closedNaryPi of
Success sig -> return sig
Failure err -> throwErrs err
argRecon <- case sig of
ExportedSignature argSig _ _ -> do
case sinkFromTop $ EmptyAbs argSig of
Abs argSig' UnitE -> liftEnvReaderM $ exportArgRecon argSig'
fSimp <- simplifyTopFunction naryPi f
fImp <- toImpExportedFunction fSimp argRecon
return (fImp, sig)
where
naryPiToExportSig :: (EnvReader m, EnvExtender m, Fallible1 m)
=> NaryPiType n -> m n (ExportedSignature n)
naryPiToExportSig (NaryPiType (NonEmptyNest tb tbs) effs resultTy) = do
case effs of
Pure -> return ()
_ -> throw TypeErr "Only pure functions can be exported"
goArgs Empty [] (Nest tb tbs) resultTy
where
goArgs :: (EnvReader m, EnvExtender m, Fallible1 m)
=> Nest ExportArg n l' -> [AtomName l'] -> Nest PiBinder l' l -> Type l -> m l' (ExportedSignature n)
goArgs argSig argVs piBs piRes = case piBs of
Empty -> goResult piRes \resSig ->
return $ ExportedSignature argSig resSig $
(fromListE $ sink $ ListE argVs) ++ nestToList (sink . binderName) resSig
Nest b bs -> do
refreshAbs (Abs b (Abs bs piRes)) \(PiBinder v ty arrow) (Abs bs' piRes') -> do
let invalidArrow = throw TypeErr
"Exported functions can only have regular and implicit arrow types"
vis <- case arrow of
PlainArrow -> return ExplicitArg
ImplicitArrow -> return ImplicitArg
ClassArrow -> invalidArrow
TabArrow -> invalidArrow
LinArrow -> invalidArrow
ety <- toExportType ty
goArgs (argSig `joinNest` Nest (ExportArg vis (v:>ety)) Empty)
((fromListE $ sink $ ListE argVs) ++ [binderName v]) bs' piRes'
goResult :: (EnvReader m, EnvExtender m, Fallible1 m)
=> Type l
-> (forall q. DExt l q => Nest ExportResult l q -> m q a)
-> m l a
goResult ty cont = case ty of
ProdTy [lty, rty] ->
goResult lty \lres ->
goResult (sink rty) \rres ->
cont $ joinNest lres rres
_ -> withFreshBinder NoHint ty \b -> do
ety <- toExportType ty
cont $ Nest (ExportResult (b:>ety)) Empty
exportArgRecon :: (EnvReader m, EnvExtender m) => Nest ExportArg n l -> m n (Abs (Nest IBinder) (ListE Block) n)
exportArgRecon topArgs = go [] topArgs
where
go :: (EnvReader m, EnvExtender m)
=> [Block n] -> Nest ExportArg n l -> m n (Abs (Nest IBinder) (ListE Block) n)
go argRecons = \case
Empty -> return $ Abs Empty $ ListE argRecons
Nest (ExportArg _ b) bs ->
refreshAbs (Abs b (EmptyAbs bs)) \(v':>ety) (Abs bs' UnitE) -> do
(ity, block) <- typeRecon (sink ety) $ Var $ binderName v'
Abs ibs' allRecons' <- go (sinkList argRecons ++ [sink block]) bs'
return $ Abs (Nest (IBinder v' ity) ibs') allRecons'
typeRecon :: EnvExtender m => ExportType n -> Atom n -> m n (IType, Block n)
typeRecon ety v = case ety of
ScalarType sbt ->
return (Scalar sbt, Block (BlockAnn $ BaseTy $ Scalar sbt) Empty $ Atom v)
RectContArrayPtr sbt shape -> do
block <- liftBuilder $ buildBlock $ tableAtom (sink v) (sink $ shapeToE shape) [] []
return (PtrType (Heap CPU, Scalar sbt), block)
where
tableAtom :: Emits n => Atom n -> ListE (EitherE AtomName (LiftE Int)) n -> [Atom n] -> [Atom n] -> BuilderM n (Atom n)
tableAtom basePtr (ListE shapeTail) is sizes = case shapeTail of
(h:t) -> buildTabLam NoHint (Fin $ dimSize h) \i ->
tableAtom (sink basePtr) (sink $ ListE t)
(sinkList is ++ [Var i]) (sinkList $ sizes ++ [dimSize h])
[] -> do
strides <- reverse . fst <$> scanM (\si st -> dup <$> imul st si)
(IdxRepVal 1:reverse (tail sizes)) (IdxRepVal 1)
ords <- flip evalStateT1 mempty $ forM is \i -> do
ity <- getType i
appSimplifiedIxMethod ity simpleToOrdinal i
offset <- foldM iadd (IdxRepVal 0) =<< mapM (uncurry imul) (zip strides ords)
unsafePtrLoad =<< ptrOffset basePtr offset
dup x = (x, x)
dimSize = \case LeftE n -> Var n; RightE (LiftE n) -> IdxRepVal (fromIntegral n)
toExportType :: Fallible m => Type n -> m (ExportType n)
toExportType ty = case ty of
BaseTy (Scalar sbt) -> return $ ScalarType sbt
TabTy _ _ -> case parseTabTy ty of
Nothing -> unsupported
Just ety -> return ety
_ -> unsupported
where unsupported = throw TypeErr $ "Unsupported type of argument in exported function: " ++ pprint ty
parseTabTy :: Type n -> Maybe (ExportType n)
parseTabTy = go []
where
go shape = \case
BaseTy (Scalar sbt) -> Just $ RectContArrayPtr sbt shape
TabTy (PiBinder b (Fin n) _) a -> do
dim <- case n of
Var v -> Just (Left v)
IdxRepVal s -> Just (Right $ fromIntegral s)
_ -> Nothing
case hoist b a of
HoistSuccess a' -> go (shape ++ [dim]) a'
HoistFailure _ -> Nothing
_ -> Nothing
-- === Exported function signature ===
data ArgVisibility = ImplicitArg | ExplicitArg
data ExportType n = RectContArrayPtr ScalarBaseType [Either (AtomName n) Int]
| ScalarType ScalarBaseType
data ExportArg n l = ExportArg ArgVisibility (BinderP AtomNameC ExportType n l)
newtype ExportResult n l = ExportResult (BinderP AtomNameC ExportType n l)
data ExportedSignature n = forall l l'.
ExportedSignature { exportedArgSig :: Nest ExportArg n l
, exportedResSig :: Nest ExportResult l l'
, exportedCCallSig :: [AtomName l']
}
instance GenericE ExportType where
type RepE ExportType = EitherE (LiftE ScalarBaseType)
(LiftE ScalarBaseType `PairE` ListE (EitherE AtomName (LiftE Int)))
fromE = \case
ScalarType sbt -> LeftE $ LiftE sbt
RectContArrayPtr sbt shape -> RightE $ LiftE sbt `PairE` shapeToE shape
toE = \case
LeftE (LiftE sbt) -> ScalarType sbt
RightE (LiftE sbt `PairE` shape) -> RectContArrayPtr sbt (shapeFromE shape)
instance SubstE Name ExportType
instance SinkableE ExportType
shapeToE :: [Either (AtomName n) Int] -> ListE (EitherE AtomName (LiftE Int)) n
shapeToE shape = ListE (dimToE <$> shape)
where dimToE = \case Left n -> LeftE n; Right n -> RightE (LiftE n)
shapeFromE :: ListE (EitherE AtomName (LiftE Int)) n -> [Either (AtomName n) Int]
shapeFromE (ListE shape) = (dimFromE <$> shape)
where dimFromE = \case LeftE n -> Left n; RightE (LiftE n) -> Right n
instance ToBinding ExportType AtomNameC where
toBinding = \case
ScalarType sbt -> toBinding $ BaseTy $ Scalar sbt
RectContArrayPtr sbt _ -> toBinding $ BaseTy $ PtrType (Heap CPU, Scalar sbt)
deriving via (BinderP AtomNameC ExportType) instance GenericB ExportResult
deriving via (BinderP AtomNameC ExportType) instance ProvesExt ExportResult
deriving via (BinderP AtomNameC ExportType) instance BindsNames ExportResult
instance BindsAtMostOneName ExportResult AtomNameC where
(ExportResult b) @> v = b @> v
instance BindsOneName ExportResult AtomNameC where
binderName (ExportResult b) = binderName b
instance GenericB ExportArg where
type RepB ExportArg = PairB (LiftB (LiftE ArgVisibility)) (BinderP AtomNameC ExportType)
fromB (ExportArg vis b) = PairB (LiftB (LiftE vis)) b
toB (PairB (LiftB (LiftE vis)) b) = ExportArg vis b
instance ProvesExt ExportArg
instance BindsNames ExportArg
instance SinkableB ExportArg
instance SubstB Name ExportArg
instance BindsAtMostOneName ExportArg AtomNameC where
(ExportArg _ b) @> v = b @> v
instance BindsOneName ExportArg AtomNameC where
binderName (ExportArg _ b) = binderName b
-- Serialization
exportedSignatureDesc :: ExportedSignature n -> (String, String, String)
exportedSignatureDesc ExportedSignature{..} =
( intercalate "," $ nestToList show exportedArgSig
, intercalate "," $ nestToList show exportedResSig
, intercalate "," $ fmap pprint exportedCCallSig
)
showExportSBT :: ScalarBaseType -> String
showExportSBT sbt = case sbt of
Int64Type -> "i64"
Int32Type -> "i32"
Word8Type -> "u8"
Word32Type -> "u32"
Word64Type -> "u64"
Float64Type -> "f64"
Float32Type -> "f32"
instance Show (ExportType n) where
show arr = case arr of
RectContArrayPtr sbt shape -> showExportSBT sbt <> showShape shape
ScalarType sbt -> showExportSBT sbt
where
showShape shape = "[" <> (intercalate "," $ fmap showDim shape) <> "]"
showDim size = case size of
Left name -> pprint name
Right lit -> show lit
instance Show (ExportArg n l) where
show (ExportArg vis (name:>ty)) = showVis vis <> pprint name <> ":" <> show ty
where
showVis ImplicitArg = "?"
showVis ExplicitArg = ""
instance Show (ExportResult n l) where
show (ExportResult (name:>ty)) = pprint name <> ":" <> show ty
| google-research/dex-lang | src/lib/Export.hs | bsd-3-clause | 11,018 | 0 | 26 | 3,186 | 3,669 | 1,800 | 1,869 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Apidoc.DSL.Lenses where
import Apidoc.DSL.Types
import Control.Lens.TH
import Prelude hiding (Enum)
makePrisms ''TypeRef
makePrisms ''BuiltIn
makeLenses ''TypeName
makePrisms ''TypeName
makeLenses ''Uri
makePrisms ''Uri
makeLenses ''Namespace
makePrisms ''Namespace
makeLenses ''ServiceName
makePrisms ''ServiceName
makeLenses ''Spec
makePrisms ''Spec
makeLenses ''Apidoc
makePrisms ''Apidoc
makeLenses ''Attribute
makePrisms ''Attribute
makeLenses ''Enum
makePrisms ''Enum
makeLenses ''EnumValue
makePrisms ''EnumValue
makeLenses ''Header
makePrisms ''Header
makeLenses ''Import
makePrisms ''Import
makeLenses ''Info
makePrisms ''Info
makeLenses ''Model
makePrisms ''Model
makeLenses ''Resource
makePrisms ''Resource
makeLenses ''Union
makePrisms ''Union
makeLenses ''UnionType
makePrisms ''UnionType
makeLenses ''Body
makePrisms ''Body
makeLenses ''Contact
makePrisms ''Contact
makeLenses ''Deprecation
makePrisms ''Deprecation
makeLenses ''Field
makePrisms ''Field
makeLenses ''License
makePrisms ''License
makeLenses ''Operation
makePrisms ''Operation
makePrisms ''HttpMethod
makePrisms ''ResponseCode
makeLenses ''Response
makePrisms ''Response
makeLenses ''Parameter
makePrisms ''Parameter
makePrisms ''ParameterLocation
| chrisbarrett/apidoc-checker | src/Apidoc/DSL/Lenses.hs | bsd-3-clause | 1,336 | 0 | 6 | 190 | 453 | 179 | 274 | 58 | 0 |
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Twilio where
import Control.Monad.Catch as Ex
import qualified Control.Monad.Logger as Logger
import Control.Monad.Trans
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Lazy as BSL
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Network.HTTP.Conduit as HTTP
import Network.HTTP.Types
import Logging
import Types
apiVersion :: BS.ByteString
apiVersion = "2010-04-01"
sendMessage ::
(Logger.MonadLogger m, MonadCatch m, MonadIO m)
=> TwilioConfig
-> Phone
-> Text
-> m ()
sendMessage TwilioConfig{ twilioConfigAccount = account'
, twilioConfigAuthToken = authToken'
, twilioConfigSourceNumber = from
} (Phone to) msg = do
let accountSid = Text.encodeUtf8 account'
username = accountSid
password' = Text.encodeUtf8 authToken'
manager <- liftIO $ newManager tlsManagerSettings
request' <- liftIO $ parseRequest "https://api.twilio.com/"
let urlPath = BS.intercalate "/" [ ""
, apiVersion
, "Accounts"
, accountSid
, "Messages"
]
body = [ ("From", Text.encodeUtf8 from)
, ("To", Text.encodeUtf8 to)
, ("Body", Text.encodeUtf8 msg)
]
req = urlEncodedBody body $
request'{ HTTP.path = urlPath
, HTTP.requestHeaders = [mkAuth username password'
]
}
mbResponse <- Ex.try $ httpLbs req manager
case mbResponse of
Left (e :: HttpException) -> do
logError $ "Error while connection to Twilio: " <> showText e
return ()
Right response -> if statusIsSuccessful $ responseStatus response
then return ()
else do
logError $ "Twilio returned error response "
<> showText (responseStatus response)
<> "; " <> (Text.decodeUtf8 . BSL.toStrict $
responseBody response )
return ()
where
showText :: Show a => a -> Text
showText = Text.pack . show
mkAuth username password' =
("Authorization", "Basic " <> B64.encode (username <> ":" <> password'))
| nejla/auth-service | service/src/Twilio.hs | bsd-3-clause | 2,866 | 0 | 18 | 1,126 | 584 | 321 | 263 | 63 | 3 |
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-- | Discrete Vector Field on a \(sSet\). Also called an 'acyclic
-- matching':
-- <http://nlab-pages.s3.us-east-2.amazonaws.com/nlab/show/discrete+Morse+theory>
module Math.Topology.SSet.DVF where
import Data.Coerce
import qualified Math.Algebra.ChainComplex.DVF as CC
import Math.Topology.SSet.NChains
import Math.Topology.SSet
class SSet a => DVF a where
-- TODO: Name??
vf :: a -> GeomSimplex a -> CC.Status (GeomSimplex a)
instance DVF a => CC.DVF (NChains a) where
vf (NChains a) (BasisSimplex b) = coerce $ vf a b
| mvr/at | src/Math/Topology/SSet/DVF.hs | bsd-3-clause | 602 | 0 | 11 | 87 | 139 | 78 | 61 | 11 | 0 |
module Statistics.Iteratee.Tests
where
import Data.Iteratee as I
import Statistics.Iteratee as Si
import Statistics.Sample as St
import Test.Framework
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Control.Monad.Identity
import qualified Data.Vector.Unboxed as V
tests =
[ testGroup "Sample" $ map mkUnProp uns
]
-- Don't want to drag in more dependencies for just this.
class ApproxEq a where
approxEq :: Double -> a -> a -> Bool
instance ApproxEq Double where
approxEq tol d1 d2 = m == 0.0 || d/m < tol where
m = max (abs d1) (abs d2)
d = abs (d1 - d2)
instance (ApproxEq a, ApproxEq b) => ApproxEq (a,b) where
approxEq tol (l1,r1) (l2,r2) = approxEq tol l1 l2 && approxEq tol r1 r2
infix 4 ===
(===) :: (ApproxEq a) => a -> a -> Bool
(===) = approxEq {-pretty equal-}1.0e-10
unsProp :: (ApproxEq a)
=> (V.Vector Double -> a)
-> (Iteratee [Double] Identity a)
-> [Double]
-> Bool
unsProp vec iter xs = if null xs then True
else vec (V.fromList xs) === (runIdentity $ run =<< enumPure1Chunk xs iter)
-- we're using Eq for doubles, which is always a bad idea...
-- also not checking empty vectors, because in some cases (range,
-- harmonicMean) we get NaN's or other funky values.
mkUnProp (lbl, st, si) = testProperty lbl $ unsProp st si
-- unary properties
uns =
[ ("mean", St.mean, Si.mean)
, ("range", St.range, Si.range)
, ("harmonic_mean", St.harmonicMean, Si.harmonicMean)
, ("variance", St.fastVariance, Si.variance)
, ("std_dev", St.fastStdDev, Si.stdDev)
]
| JohnLato/iter-stats | tests/Statistics/Iteratee/Tests.hs | bsd-3-clause | 1,588 | 0 | 10 | 343 | 519 | 294 | 225 | 35 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PolyKinds #-}
{-# OPTIONS_GHC -Wno-inline-rule-shadowing #-}
-- The RULES for the methods of class Category may never fire
-- e.g. identity/left, identity/right, association; see #10528
-----------------------------------------------------------------------------
-- |
-- Module : Control.Category
-- Copyright : (c) Ashley Yakeley 2007
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : ashley@semantic.org
-- Stability : experimental
-- Portability : portable
-- https://gitlab.haskell.org/ghc/ghc/issues/1773
module Control.Category where
import qualified GHC.Base (id,(.))
import Data.Type.Coercion
import Data.Type.Equality
import Data.Coerce (coerce)
infixr 9 .
infixr 1 >>>, <<<
-- | A class for categories. Instances should satisfy the laws
--
-- [Right identity] @f '.' 'id' = f@
-- [Left identity] @'id' '.' f = f@
-- [Associativity] @f '.' (g '.' h) = (f '.' g) '.' h@
--
class Category cat where
-- | the identity morphism
id :: cat a a
-- | morphism composition
(.) :: cat b c -> cat a b -> cat a c
{-# RULES
"identity/left" forall p .
id . p = p
"identity/right" forall p .
p . id = p
"association" forall p q r .
(p . q) . r = p . (q . r)
#-}
-- | @since 3.0
instance Category (->) where
id = GHC.Base.id
(.) = (GHC.Base..)
-- | @since 4.7.0.0
instance Category (:~:) where
id = Refl
Refl . Refl = Refl
-- | @since 4.10.0.0
instance Category (:~~:) where
id = HRefl
HRefl . HRefl = HRefl
-- | @since 4.7.0.0
instance Category Coercion where
id = Coercion
(.) Coercion = coerce
-- | Right-to-left composition
(<<<) :: Category cat => cat b c -> cat a b -> cat a c
(<<<) = (.)
-- | Left-to-right composition
(>>>) :: Category cat => cat a b -> cat b c -> cat a c
f >>> g = g . f
| sdiehl/ghc | libraries/base/Control/Category.hs | bsd-3-clause | 1,991 | 0 | 9 | 487 | 342 | 204 | 138 | 38 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Distribution.Nixpkgs.Haskell.FromCabal.PostProcess ( postProcess ) where
import Control.Lens
import Control.Lens.Create
import Data.List.Split
import Data.Set ( Set )
import qualified Data.Set as Set
import Data.Set.Lens
import Distribution.Nixpkgs.Haskell
import Distribution.Nixpkgs.Meta
import Distribution.Package
import Distribution.System
import Distribution.Text
import Distribution.Version
import Language.Nix
postProcess :: Derivation -> Derivation
postProcess deriv = foldr ($) (fixGtkBuilds deriv) [ f | (Dependency n vr, f) <- hooks, packageName deriv == n, packageVersion deriv `withinRange` vr ]
fixGtkBuilds :: Derivation -> Derivation
fixGtkBuilds drv = drv & dependencies . pkgconfig %~ Set.filter (not . collidesWithHaskellName)
& dependencies . system %~ Set.filter (not . collidesWithHaskellName)
& dependencies . tool %~ Set.filter (not . collidesWithHaskellName)
where
collidesWithHaskellName :: Binding -> Bool
collidesWithHaskellName b = view localName b `Set.member` buildDeps
myName :: Identifier
myName = create ident n where PackageName n = packageName drv
buildDeps :: Set Identifier
buildDeps = Set.delete myName (setOf (dependencies . haskell . folded . localName) drv)
hooks :: [(Dependency, Derivation -> Derivation)]
hooks =
[ ("Agda", set (executableDepends . tool . contains (pkg "emacs")) True . set phaseOverrides agdaPostInstall)
, ("dns", set testTarget "spec") -- don't execute tests that try to access the network
, ("bindings-GLFW", over (libraryDepends . system) (Set.union (Set.fromList [bind "pkgs.xlibs.libXext", bind "pkgs.xlibs.libXfixes"])))
, ("cabal-install", set phaseOverrides cabalInstallPostInstall)
, ("darcs", set phaseOverrides darcsInstallPostInstall)
, ("eventstore", over (metaSection . platforms) (Set.filter (\(Platform arch _) -> arch == X86_64)))
, ("git-annex", gitAnnexHook)
, ("haddock", set phaseOverrides "preCheck = \"unset GHC_PACKAGE_PATH\";")
, ("HFuse", set phaseOverrides hfusePreConfigure)
, ("gf", set phaseOverrides gfPhaseOverrides . set doCheck False)
, ("github-backup", set (executableDepends . tool . contains (pkg "git")) True)
, ("GlomeVec", set (libraryDepends . pkgconfig . contains (bind "self.llvmPackages.llvm")) True)
, ("gtk3", gtk3Hook)
, ("imagemagick", set (libraryDepends . pkgconfig . contains (pkg "imagemagick")) True) -- https://github.com/NixOS/cabal2nix/issues/136
, ("jsaddle", set (dependencies . haskell . contains (bind "self.ghcjs-base")) False)
, ("liquid-fixpoint", over configureFlags (Set.union (Set.fromList ["-fbuild-external"]))
. set (executableDepends . system . contains (pkg "ocaml")) True
. set (testDepends . system . contains (pkg "z3")) True)
, ("liquidhaskell", set (testDepends . system . contains (pkg "z3")) True)
, ("mysql", set (libraryDepends . system . contains (pkg "mysql")) True)
, ("readline", over (libraryDepends . system) (Set.union (pkgs ["readline", "ncurses"])))
, ("rocksdb-haskell", set (metaSection . platforms) (Set.singleton (Platform X86_64 Linux)))
, ("target", set (testDepends . system . contains (pkg "z3")) True)
, ("terminfo", set (libraryDepends . system . contains (pkg "ncurses")) True)
, ("thyme", set (libraryDepends . tool . contains (bind "self.cpphs")) True) -- required on Darwin
, ("xmonad", set phaseOverrides xmonadPostInstall)
, ("wxc", wxcHook)
, ("wxcore", set (libraryDepends . pkgconfig . contains (pkg "wxGTK")) True)
, ("X11", over (libraryDepends . system) (Set.union (Set.fromList $ map bind ["pkgs.xlibs.libXinerama","pkgs.xlibs.libXext","pkgs.xlibs.libXrender"])))
]
pkg :: Identifier -> Binding
pkg i = create binding (i, create path ["pkgs",i])
pkgs :: [Identifier] -> Set Binding
pkgs = Set.fromList . map pkg
bind :: String -> Binding
bind s = create binding (i, create path is)
where
is = map (create ident) (splitOn "." s)
i = last is
-- TODO: I need to figure out how to conveniently replace a binding in a set.
gtk3Hook :: Derivation -> Derivation -- https://github.com/NixOS/cabal2nix/issues/145
gtk3Hook = set (libraryDepends . pkgconfig . contains (pkg "gtk3")) True
. over (libraryDepends . pkgconfig) (Set.filter (\b -> view localName b /= "gtk3"))
gitAnnexHook :: Derivation -> Derivation
gitAnnexHook = set phaseOverrides gitAnnexOverrides . over (executableDepends . system) (Set.union buildInputs)
where
gitAnnexOverrides = unlines
[ "preConfigure = \"export HOME=$TEMPDIR; patchShebangs .\";"
, "postBuild = \"ln -sf dist/build/git-annex/git-annex git-annex\";"
, "installPhase = \"make PREFIX=$out CABAL=./Setup install\";"
, "checkPhase = \"./git-annex test\";"
]
buildInputs = pkgs ["git","rsync","gnupg","curl","wget","lsof","openssh","which","bup","perl"]
hfusePreConfigure :: String
hfusePreConfigure = unlines
[ "preConfigure = ''"
, " sed -i -e \"s@ Extra-Lib-Dirs: /usr/local/lib@ Extra-Lib-Dirs: ${fuse}/lib@\" HFuse.cabal"
, "'';"
]
gfPhaseOverrides :: String
gfPhaseOverrides = unlines
[ "postPatch = ''"
, " sed -i \"s|\\\"-s\\\"|\\\"\\\"|\" ./Setup.hs"
-- Disable silent compilation. Compiling takes long, it is best to see some
-- output, otherwise it looks like the build step has stalled.
, " sed -i \"s|numJobs (bf bi)++||\" ./Setup.hs"
-- Parallel compilation fails. Disable it.
, "'';"
, "preBuild = ''export LD_LIBRARY_PATH=`pwd`/dist/build:$LD_LIBRARY_PATH'';"
-- The build step itself, after having built the library, needs to be able
-- to find the library it just built in order to compile grammar files.
]
wxcHook :: Derivation -> Derivation
wxcHook drv = drv & libraryDepends . system %~ Set.union (Set.fromList [pkg "mesa", bind "pkgs.xlibs.libX11"])
& libraryDepends . pkgconfig . contains (pkg "wxGTK") .~ True
& phaseOverrides .~ wxcPostInstall (packageVersion drv)
& runHaddock .~ False
where
wxcPostInstall :: Version -> String
wxcPostInstall version = unlines
[ "postInstall = \"cp -v dist/build/libwxc.so." ++ display version ++ " $out/lib/libwxc.so\";"
, "postPatch = \"sed -i -e '/ldconfig inst_lib_dir/d' Setup.hs\";"
]
cabalInstallPostInstall :: String
cabalInstallPostInstall = unlines
[ "postInstall = ''"
, " mkdir $out/etc"
, " mv bash-completion $out/etc/bash_completion.d"
, "'';"
]
darcsInstallPostInstall :: String
darcsInstallPostInstall = unlines
[ "postInstall = ''"
, " mkdir -p $out/etc/bash_completion.d"
, " mv contrib/darcs_completion $out/etc/bash_completion.d/darcs"
, "'';"
]
xmonadPostInstall :: String
xmonadPostInstall = unlines
[ "postInstall = ''"
, " shopt -s globstar"
, " mkdir -p $out/share/man/man1"
, " mv \"$out/\"**\"/man/\"*.1 $out/share/man/man1/"
, "'';"
]
agdaPostInstall :: String
agdaPostInstall = unlines
[ "postInstall = ''"
, " $out/bin/agda -c --no-main $(find $out/share -name Primitive.agda)"
, " $out/bin/agda-mode compile"
, "'';"
]
{-
postProcess' :: Derivation -> Derivation
postProcess' deriv@(MkDerivation {..})
| pname == "alex" && version < Version [3,1] []
= deriv { buildTools = Set.insert "perl" buildTools }
| pname == "alex" && version >= Version [3,1] []
= deriv { buildTools = Set.insert "perl" (Set.insert "happy" buildTools) }
| pname == "apache-md5" = deriv { testDepends = Set.delete "crypto" testDepends }
| pname == "bits-extras" = deriv { configureFlags = Set.insert "--ghc-option=-lgcc_s" configureFlags
, extraLibs = Set.filter (/= "gcc_s") extraLibs
}
| pname == "Cabal" = deriv { phaseOverrides = "preCheck = \"unset GHC_PACKAGE_PATH; export HOME=$NIX_BUILD_TOP\";" }
| pname == "cabal-bounds" = deriv { buildTools = Set.insert "cabal-install" buildTools }
| pname == "editline" = deriv { extraLibs = Set.insert "libedit" extraLibs }
| pname == "ghc-heap-view" = deriv { phaseOverrides = ghciPostInstall }
| pname == "ghc-mod" = deriv { phaseOverrides = ghcModPostInstall pname version, buildTools = Set.insert "emacs" buildTools }
| pname == "ghc-parser" = deriv { buildTools = Set.insert "cpphs" (Set.insert "happy" buildTools)
, phaseOverrides = ghcParserPatchPhase }
| pname == "ghc-vis" = deriv { phaseOverrides = ghciPostInstall }
| pname == "github-backup" = deriv { buildTools = Set.insert "git" buildTools }
| pname == "gloss-raster" = deriv { extraLibs = Set.insert "llvm" extraLibs }
| pname == "GLUT" = deriv { extraLibs = Set.fromList ["glut","libSM","libICE","libXmu","libXi","mesa"] `Set.union` extraLibs }
| pname == "gtkglext" = deriv { pkgConfDeps = Set.insert "pangox_compat" pkgConfDeps }
| pname == "gtk2hs-buildtools"= deriv { buildDepends = Set.insert "hashtables" buildDepends }
| pname == "haddock" && version < Version [2,14] []
= deriv { buildTools = Set.insert "alex" (Set.insert "happy" buildTools) }
| pname == "happy" = deriv { buildTools = Set.insert "perl" buildTools }
| pname == "haskeline" = deriv { buildDepends = Set.insert "utf8-string" buildDepends }
| pname == "haskell-src" = deriv { buildTools = Set.insert "happy" buildTools }
| pname == "haskell-src-meta" = deriv { buildDepends = Set.insert "uniplate" buildDepends }
| pname == "hlibgit2" = deriv { buildTools = Set.insert "git" buildTools }
| pname == "HList" = deriv { buildTools = Set.insert "diffutils" buildTools }
| pname == "hmatrix" = deriv { extraLibs = Set.insert "liblapack" (Set.insert "blas" (Set.filter (/= "lapack") extraLibs)) }
| pname == "hmatrix-special" = deriv { extraLibs = Set.insert "gsl" extraLibs }
| pname == "idris" = deriv { buildTools = Set.insert "happy" buildTools, extraLibs = Set.insert "gmp" (Set.insert "boehmgc" extraLibs) }
| pname == "inline-c-cpp" = deriv { testDepends = Set.delete "stdc++" testDepends }
| pname == "language-c-quote" = deriv { buildTools = Set.insert "alex" (Set.insert "happy" buildTools) }
| pname == "language-java" = deriv { buildDepends = Set.insert "syb" buildDepends }
| pname == "lhs2tex" = deriv { extraLibs = Set.insert "texLive" extraLibs, phaseOverrides = lhs2texPostInstall }
| pname == "libffi" = deriv { extraLibs = Set.delete "ffi" extraLibs }
| pname == "liquid-fixpoint" = deriv { buildTools = Set.insert "z3" (Set.insert "ocaml" buildTools), configureFlags = Set.insert "-fbuild-external" configureFlags }
| pname == "liquidhaskell" = deriv { buildTools = Set.insert "z3" buildTools }
| pname == "MFlow" = deriv { buildTools = Set.insert "cpphs" buildTools }
| pname == "multiarg" = deriv { buildDepends = Set.insert "utf8-string" buildDepends }
| pname == "ncurses" = deriv { phaseOverrides = ncursesPatchPhase }
| pname == "Omega" = deriv { testDepends = Set.delete "stdc++" testDepends }
| pname == "OpenAL" = deriv { extraLibs = Set.insert "openal" extraLibs }
| pname == "OpenGL" = deriv { extraLibs = Set.insert "mesa" (Set.insert "libX11" extraLibs) }
| pname == "pandoc" = deriv { buildDepends = Set.insert "alex" (Set.insert "happy" buildDepends) }
| pname == "persistent" = deriv { extraLibs = Set.insert "sqlite3" extraLibs }
| pname == "purescript" = deriv { buildTools = Set.insert "nodejs" buildTools }
| pname == "repa-algorithms" = deriv { extraLibs = Set.insert "llvm" extraLibs }
| pname == "repa-examples" = deriv { extraLibs = Set.insert "llvm" extraLibs }
| pname == "SDL-image" = deriv { extraLibs = Set.insert "SDL_image" extraLibs }
| pname == "SDL-mixer" = deriv { extraLibs = Set.insert "SDL_mixer" extraLibs }
| pname == "SDL-ttf" = deriv { extraLibs = Set.insert "SDL_ttf" extraLibs }
| pname == "sloane" = deriv { phaseOverrides = sloanePostInstall }
| pname == "structured-haskell-mode" = deriv { buildTools = Set.insert "emacs" buildTools
, phaseOverrides = structuredHaskellModePostInstall
}
| pname == "target" = deriv { buildTools = Set.insert "z3" buildTools }
| pname == "threadscope" = deriv { configureFlags = Set.insert "--ghc-options=-rtsopts" configureFlags }
| pname == "vacuum" = deriv { extraLibs = Set.insert "ghc-paths" extraLibs }
| pname == "wxcore" = deriv { extraLibs = Set.fromList ["wxGTK","mesa","libX11"] `Set.union` extraLibs }
| pname == "X11-xft" = deriv { extraLibs = Set.fromList ["pkgconfig","freetype","fontconfig"] `Set.union` extraLibs
, configureFlags = Set.insert "--extra-include-dirs=${freetype}/include/freetype2" configureFlags
}
-- Unbreak packages during hackage2nix generation:
| pname == "hnetcdf" = deriv { testDepends = Set.delete "netcdf" testDepends }
| pname == "SDL2-ttf" = deriv { buildDepends = Set.delete "SDL2" buildDepends }
| pname == "hzk" = deriv { testDepends = Set.delete "zookeeper_mt" testDepends, buildTools = Set.insert "zookeeper_mt" buildTools }
| pname == "z3" = deriv { phaseOverrides = "preBuild = stdenv.lib.optionalString stdenv.isDarwin \"export DYLD_LIBRARY_PATH=${z3}/lib\";" }
| pname == "zip-archive" = deriv { testDepends = Set.delete "zip" testDepends, buildTools = Set.insert "zip" buildTools }
| otherwise = deriv
ghcModPostInstall :: String -> Version -> String
ghcModPostInstall pname version = unlines
[ "configureFlags = \"--datasubdir=" ++ pname ++ "-" ++ display version ++ "\";"
, "postInstall = ''"
, " cd $out/share/" ++ pname ++ "-" ++ display version
, " make"
, " rm Makefile"
, " cd .."
, " ensureDir \"$out/share/emacs\""
, " mv " ++ pname ++ "-" ++ display version ++ " emacs/site-lisp"
, "'';"
]
ghciPostInstall :: String
ghciPostInstall = unlines
[ "postInstall = ''"
, " ensureDir \"$out/share/ghci\""
, " ln -s \"$out/share/$pname-$version/ghci\" \"$out/share/ghci/$pname\""
, "'';"
]
lhs2texPostInstall :: String
lhs2texPostInstall = unlines
[ "postInstall = ''"
, " mkdir -p \"$out/share/doc/$name\""
, " cp doc/Guide2.pdf $out/share/doc/$name"
, " mkdir -p \"$out/nix-support\""
, "'';"
]
ncursesPatchPhase :: String
ncursesPatchPhase = "patchPhase = \"find . -type f -exec sed -i -e 's|ncursesw/||' {} \\\\;\";"
structuredHaskellModePostInstall :: String
structuredHaskellModePostInstall = unlines
[ "postInstall = ''"
, " emacs -L elisp --batch -f batch-byte-compile \"elisp/\"*.el"
, " install -d $out/share/emacs/site-lisp"
, " install \"elisp/\"*.el \"elisp/\"*.elc $out/share/emacs/site-lisp"
, "'';"
]
sloanePostInstall :: String
sloanePostInstall = unlines
[ "postInstall = ''"
, " mkdir -p $out/share/man/man1"
, " cp sloane.1 $out/share/man/man1/"
, "'';"
]
haddockPreCheck :: String
haddockPreCheck = "preCheck = \"unset GHC_PACKAGE_PATH\";"
ghcParserPatchPhase :: String
ghcParserPatchPhase = unlines
[ "patchPhase = ''"
, " substituteInPlace build-parser.sh --replace \"/bin/bash\" \"$SHELL\""
, "'';"
]
-}
| gridaphobe/cabal2nix | distribution-nixpkgs/src/Distribution/Nixpkgs/Haskell/FromCabal/PostProcess.hs | bsd-3-clause | 15,746 | 0 | 18 | 3,452 | 1,848 | 1,009 | 839 | -1 | -1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE FlexibleContexts #-}
{-# Language TemplateHaskell #-}
module Data.Excel.FormPopulate.Lens where
import Control.Lens
import Control.Lens.Lens
import Control.Lens.Prism
import Control.Lens.TH
import qualified Data.Foldable as F
import Data.Text
| smurphy8/excel-form-maker | src/Data/Excel/FormPopulate/Lens.hs | bsd-3-clause | 395 | 0 | 4 | 45 | 50 | 36 | 14 | 13 | 0 |
{-# LANGUAGE NoImplicitPrelude
, PackageImports
, TypeFamilies
, TypeSynonymInstances
, UnicodeSyntax
#-}
module Text.Numeral.Exp
( Unknown(unknown, isUnknown)
, Lit(lit)
, Neg(neg)
, Add(add)
, Mul(mul)
, Sub(sub)
, Frac(frac)
, Scale(scale)
, Dual(dual)
, Plural(plural)
, Inflection(..)
) where
-------------------------------------------------------------------------------
-- Imports
-------------------------------------------------------------------------------
import "base" Data.Bool ( Bool(False) )
import "base" Data.Function ( const )
import "base" Prelude ( (+), (*), (^), subtract, negate, fromInteger, error )
import "base-unicode-symbols" Prelude.Unicode ( ℤ, (⋅) )
-------------------------------------------------------------------------------
-- Expressions
-------------------------------------------------------------------------------
-- | An unknown value. This is used to signal that a value can not be
-- represented in the expression language.
--
-- Law: isUnknown unknown == True
class Unknown α where
unknown ∷ α
isUnknown ∷ α → Bool
-- | A literal value.
--
-- Example in English:
--
-- > "three" = lit 3
class Lit α where lit ∷ ℤ → α
-- | Negation of a value.
--
-- Example in English:
--
-- > "minus two" = neg (lit 2)
class Neg α where neg ∷ α → α
-- | Addition of two values.
--
-- Example in English:
--
-- > "fifteen" = lit 5 `add` lit 10
class Add α where add ∷ α → α → α
-- | Multiplication of two values.
--
-- Example in English:
--
-- > "thirty" = lit 3 `mul` lit 10
class Mul α where mul ∷ α → α → α
-- | One value subtracted from another value.
--
-- Example in Latin:
--
-- > "duodēvīgintī" = lit 2 `sub` (lit 2 `mul` lit 10)
class Sub α where sub ∷ α → α → α
-- | A fraction.
--
-- Example in English:
--
-- > "two thirds" = `frac` (lit 2) (lit 3)
class Frac α where frac ∷ α → α → α
-- | A step in a scale of large values.
--
-- Should be interpreted as @10 ^ (rank * base + offset)@.
--
-- Example in English:
--
-- > "quadrillion" = scale 3 3 4
class Scale α where
scale ∷ ℤ -- ^ Base.
→ ℤ -- ^ Offset.
→ α -- ^ Rank.
→ α
-- | A dual of a value.
--
-- This is used in some languages that express some values as the dual
-- of a smaller value. For instance, in Hebrew the number 20 is
-- expressed as the dual of 10.
class Dual α where dual ∷ α → α
-- | A plural of a value.
--
-- This is used in some languages that express some values as the
-- plural of a smaller value. For instance, in Hebrew the numbers
-- [30,40..90] are expressed as the plurals of [3..9].
class Plural α where plural ∷ α → α
-- | A change of inflection.
--
-- This is used in a language like Spanish where the inflection of a
-- number word is not always constant. Specifically, in Spanish, large
-- number names always have the masculine gender. So 'millón',
-- 'billón' and the like are all masculine. This can result in the
-- following number word: 10000001 = "un (masculine) millón una
-- (feminine)"
class Inflection α where
type Inf α
inflection ∷ (Inf α → Inf α) → α → α
infixl 6 `add`
infixl 6 `sub`
infixl 7 `mul`
-------------------------------------------------------------------------------
-- Integer instances
-------------------------------------------------------------------------------
instance Unknown ℤ where
unknown = error "unknown"
isUnknown = const False
instance Lit ℤ where lit = fromInteger
instance Neg ℤ where neg = negate
instance Add ℤ where add = (+)
instance Mul ℤ where mul = (*)
instance Sub ℤ where sub = subtract
instance Scale ℤ where scale b o r = 10 ^ (r⋅b + o)
-- TODO: instances for ℚ?
| roelvandijk/numerals-base | src/Text/Numeral/Exp.hs | bsd-3-clause | 3,861 | 2 | 10 | 807 | 633 | 397 | 236 | 73 | 0 |
{-# LANGUAGE ScopedTypeVariables #-}
module Rho.BitfieldSpec where
import Control.Exception (ErrorCall, catch)
import Control.Monad
import Data.Bits
import qualified Data.ByteString as B
import qualified Data.Set as S
import Test.Hspec
import Test.Hspec.Contrib.HUnit
import Test.Hspec.QuickCheck
import Test.HUnit
import Test.QuickCheck hiding (Result)
import Test.QuickCheck.Instances ()
import qualified Rho.Bitfield as BF
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "bitfield properties" $ do
modifyMaxSuccess (const 1000) $ prop "random generation from bytestring and bit checking" $ \bs ->
ioProperty $ do
bf <- BF.fromBS (B.pack bs) (length bs * 8)
rets <- zipWithM (\byteIdx byte ->
forM [0..7] $ \bitIdx -> do
bfRet <- BF.test bf (byteIdx * 8 + bitIdx)
return $ bfRet == testBit byte (7 - bitIdx)) [0..] bs
return $ and (concat rets)
modifyMaxSuccess (const 1000) $ prop "random generation from indexes and bit checking" $
\(Idxs idxs) -> ioProperty $ do
let idxs' = S.toList idxs
bf <- BF.fromBitIdxs idxs' (maximum idxs' + 1)
avails <- BF.availableBits bf
missings <- BF.missingBits bf
return $ (avails == idxs) .&&. (avails `S.intersection` missings == S.empty)
modifyMaxSuccess (const 1000) $ prop "set and test" $ \(Idxs idxs) -> ioProperty $ do
let idxs' = S.toList idxs
bf <- BF.empty (maximum idxs' + 1)
forM_ idxs' (BF.set bf)
tests <- forM idxs' (BF.test bf)
negTests <- forM [0..maximum idxs'] $ \idx -> if S.member idx idxs
then return True
else not <$> BF.test bf idx
return $ and tests .&&. and negTests
modifyMaxSuccess (const 1000) $ prop "bytestring conversions" $ \ws ->
ioProperty $ do
let bs = B.pack ws
bf <- BF.fromBS bs (B.length bs * 8)
bs' <- BF.toBS bf
return $ bs' == bs
fromHUnitTest $ TestLabel "ByteString conversion -- extra bits should be 0" $ TestCase $ do
bf <- BF.fromBitIdxs [0..8] 9
bs <- BF.toBS bf
assertEqual "generated ByteString is wrong" (B.pack [0xFF, 0x80]) bs
fromHUnitTest $ TestLabel "setting invalid bit should fail with error" $ TestCase $ do
bf <- BF.empty 0
ret <- catch (BF.set bf 0 >> return False) (\(_ :: ErrorCall) -> return True)
assertBool "set didn't fail" ret
fromHUnitTest $ TestLabel "getting invalid bit should fail with error" $ TestCase $ do
bf <- BF.empty 0
ret <- catch (BF.test bf 0 >> return False) (\(_ :: ErrorCall) -> return True)
assertBool "test didn't fail" ret
describe "bitfield edge cases (extra trailing zero bits)" $ do
fromHUnitTest $ TestLabel "extra bits should be ignored" $ TestCase $ do
bf <- BF.fromBS (B.pack [0xFF, 0xFF]) 10
missings <- BF.missingBits bf
avails <- BF.availableBits bf
assertBool "missings are not empty" (S.null missings)
assertEqual "available bits are wrong" (S.fromList [0..9]) avails
fromHUnitTest $ TestLabel "all bits up to extra bits should count" $ TestCase $ do
bf <- BF.fromBS (B.pack [0xFF, 0x00]) 10
missings <- BF.missingBits bf
avails <- BF.availableBits bf
assertEqual "missing bits are wrong" (S.fromList [8, 9]) missings
assertEqual "available bits are wrong" (S.fromList [0..7]) avails
describe "checkRange" $ do
fromHUnitTest $ TestLabel "checkRange from bitIdxs (out-of-range bits)" $ TestCase $ do
bf <- BF.fromBitIdxs [4..20] 10
ret1 <- BF.checkRange bf 4 30
assertBool "range check is wrong" ret1
newtype Idxs = Idxs (S.Set Int) deriving (Show)
instance Arbitrary Idxs where
arbitrary = (Idxs . S.fromList) <$> listOf1 (choose (0, 1000))
| osa1/rho-torrent | test/Rho/BitfieldSpec.hs | bsd-3-clause | 4,126 | 0 | 27 | 1,271 | 1,334 | 645 | 689 | 82 | 2 |
{-# LANGUAGE MultiWayIf #-}
module Task2
( goldMin
) where
getU :: Floating a => a -> a -> Int -> a
getU a b i = case i of
1 -> a + phy1 * (b - a)
2 -> a + phy2 * (b - a)
where
phy1 = (3 - sqrt(5)) / 2
phy2 = (sqrt(5) - 1) / 2
getPoints :: (Floating a, Ord b) => (a -> b) -> (a, a) -> (a, a) -> (a, a)
getPoints f (a, b) (u1, u2)
| f1 < f2 = (u1', u1 )
| f1 > f2 = (u2 , u2')
| f1 == f2 = (u2', u1')
where
f1 = f u1
f2 = f u2
u1' = getU a u2 1
u2' = getU u1 b 2
getNext :: (Floating a, Ord b) => (a -> b) -> (a, a) -> (a, a) -> (a, a)
getNext f (a, b) (u1, u2)
| f1 < f2 = (a, u2)
| f1 > f2 = (u1, b )
| f1 == f2 = (u1, u2)
where
u = getU a b
f1 = f $ u 1
f2 = f $ u 2
goldHelp :: (Floating a, Ord a, Ord b) => (a -> b) -> (a, a) -> (a, a) -> a
goldHelp f (a, b) (u1, u2)
| b - a < eps = (a + b) / 2
| otherwise = goldHelp f next points
where
next = getNext f (a, b) (u1, u2)
points = getPoints f (a, b) (u1, u2)
eps = 0.001
goldMin :: (Floating a, Ord a, Ord b) => (a -> b) -> (a, a) -> a
goldMin f (a, b) = goldHelp f (a, b) points
where
u1 = getU a b 1
u2 = getU a b 2
points = (u1, u2)
| vsulabs/OptimizationMethodsHs | src/Task2.hs | bsd-3-clause | 1,464 | 0 | 11 | 680 | 776 | 422 | 354 | 38 | 2 |
{-# OPTIONS_GHC -Wall #-}
-- | A Haskell binding to the bitcoind server.
module Network.Bitcoin
(
-- * Common Types
Client
, getClient
, BitcoinException(..)
, HexString
, TransactionID
, Satoshi(..)
, BTC
, Account
, Address
, ScriptSig
-- * Block Chain Operations
, getBlockCount
, getDifficulty
, setTransactionFee
, getRawMemoryPool
, BlockHash
, getBlockHash
, Block(..)
, getBlock
, OutputSetInfo(..)
, getOutputSetInfo
, OutputInfo(..)
, getOutputInfo
-- * Private Key Operations
, importPrivateKey
, dumpPrivateKey
-- * Mining Operations
, getGenerate
, setGenerate
, getHashesPerSec
, MiningInfo(..)
, getMiningInfo
, HashData(..)
, getWork
, solveBlock
, Transaction(..)
, CoinBaseAux(..)
, BlockTemplate(..)
, getBlockTemplate
, submitBlock
-- * Network Operations
, getConnectionCount
, PeerInfo(..)
, getPeerInfo
-- * Raw Transaction Operations
, RawTransaction
, getRawTransaction
, TxIn(..)
, TxnOutputType(..)
, ScriptPubKey(..)
, TxOut(..)
, BlockInfo(..)
, RawTransactionInfo(..)
, getRawTransactionInfo
, UnspentTransaction(..)
, listUnspent
, createRawTransaction
, DecodedRawTransaction(..)
, decodeRawTransaction
, WhoCanPay(..)
, RawSignedTransaction(..)
, signRawTransaction
, sendRawTransaction
-- * Wallet Operations
, BitcoindInfo(..)
, getBitcoindInfo
, getNewAddress
, getAccountAddress
, getAccount
, setAccount
, getAddressesByAccount
, sendToAddress
, AddressInfo(..)
, listAddressGroupings
, Signature
, signMessage
, verifyMessage
, getReceivedByAddress
, getReceivedByAddress'
, getReceivedByAccount
, getReceivedByAccount'
, getBalance
, getBalance'
, getBalance''
, moveBitcoins
, sendFromAccount
, sendMany
-- , createMultiSig
, ReceivedByAddress(..)
, listReceivedByAddress
, listReceivedByAddress'
, ReceivedByAccount(..)
, listReceivedByAccount
, listReceivedByAccount'
, listTransactions
, listTransactions'
, listAccounts
, importAddress
, SinceBlock(..)
, SimpleTransaction(..)
, TransactionCategory(..)
, listSinceBlock
, listSinceBlock'
, DetailedTransaction(..)
, DetailedTransactionDetails(..)
, getTransaction
, backupWallet
, keyPoolRefill
, unlockWallet
, lockWallet
, changePassword
, encryptWallet
, isAddressValid
) where
import Network.Bitcoin.BlockChain
import Network.Bitcoin.Dump
import Network.Bitcoin.Mining
import Network.Bitcoin.Net
import Network.Bitcoin.RawTransaction
import Network.Bitcoin.Types
import Network.Bitcoin.Wallet
| WraithM/network-bitcoin | src/Network/Bitcoin.hs | bsd-3-clause | 2,929 | 0 | 5 | 814 | 498 | 345 | 153 | 116 | 0 |
import System.Environment (getArgs)
import Control.Distributed.Process
import Control.Distributed.Process.Node (initRemoteTable)
import Control.Distributed.Process.Backend.SimpleLocalnet
import qualified WorkStealing
rtable :: RemoteTable
rtable = WorkStealing.__remoteTable initRemoteTable
main :: IO ()
main = do
args <- getArgs
case args of
["master", host, port, n] -> do
backend <- initializeBackend host port rtable
startMaster backend $ \slaves -> do
result <- WorkStealing.master (read n) slaves
liftIO $ print result
["slave", host, port] -> do
backend <- initializeBackend host port rtable
startSlave backend
| haskell-distributed/distributed-process-demos | src/WorkStealing/SimpleLocalnet.hs | bsd-3-clause | 674 | 0 | 19 | 129 | 197 | 103 | 94 | 19 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Main where
-- import Codec.Encryption.Padding (pkcs5, unPkcs5)
-- import Codec.Utils (listFromOctets, listToOctets)
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.Exception
import Control.Monad
import qualified Data.ByteString as B
import Data.Either
import Data.Monoid ((<>))
import qualified Data.Vector as V
import Foreign.C.Error
import HECS.Internal
import Prelude hiding (catch)
-- import System.Console.Haskeline hiding (handle)
import System.Directory (getDirectoryContents)
import System.Fuse
import System.IO
import System.Posix
data HECS = HECS (V.Vector Fd) (V.Vector Fd) (MVar ())
type HT = HECS
main :: IO ()
main = do
cfg <- readConf "conf.json"
fuseMain (hecsFSOps cfg) hecsExceptionHandler
hecsExceptionHandler :: SomeException -> IO Errno
hecsExceptionHandler _ = getErrno >>= (\(Errno errno) -> return . Errno . negate $ errno)
hecsFSOps :: Config -> FuseOperations HT
hecsFSOps cfg =
defaultFuseOps {
fuseGetFileStat = hecsGetFileStat cfg
, fuseCreateDirectory = hecsCreateDirectory cfg
, fuseOpenDirectory = hecsOpenDirectory cfg
, fuseReadDirectory = hecsReadDirectory cfg
, fuseRemoveDirectory = hecsRemoveDirectory cfg
, fuseRename = hecsRename cfg
, fuseSetFileMode = hecsSetFileMode cfg
, fuseSetFileTimes = hecsSetFileTimes cfg
, fuseSetFileSize = hecsSetFileSize cfg
, fuseCreateDevice = hecsCreateDevice cfg
, fuseOpen = hecsOpen cfg
, fuseRead = hecsRead cfg
, fuseWrite = hecsWrite cfg
, fuseFlush = hecsFlush cfg
, fuseRelease = hecsRelease cfg
, fuseSynchronizeFile = hecsSynchronizeFile cfg
, fuseSetOwnerAndGroup = hecsSetOwnerAndGroup cfg
, fuseCreateLink = hecsCreateLink cfg
, fuseRemoveLink = hecsRemoveLink cfg
-- , fuseCreateSymbolicLink = hecsCreateSymbolicLink cfg
-- , fuseReadSymbolicLink = hecsReadSymbolicLink cfg
-- , fuseGetFileSystemStats = hecsGetFileSystemStats
}
hecsGetFileStat :: Config -> FilePath -> IO (Either Errno FileStat)
hecsGetFileStat cfg path =
do let k = length . primaryNodes $ cfg
status <- mapM getSymbolicLinkStatus $ entireFiles path cfg
size <- calcFileSize . take k $ status
return $ Right $ fileStatusToFileStat (head status) size
hecsCreateDirectory :: Config -> FilePath -> FileMode -> IO Errno
hecsCreateDirectory cfg path mode =
do mapM_ (`createDirectory` mode) $ entireFiles path cfg
return eOK
hecsOpenDirectory :: Config -> FilePath -> IO Errno
hecsOpenDirectory cfg path =
do openDirStream (head $ primeFiles path cfg) >>= closeDirStream
return eOK
hecsReadDirectory :: Config -> FilePath -> IO (Either Errno [(FilePath, FileStat)])
hecsReadDirectory cfg path0 =
let pairType :: FilePath -> IO (FilePath, FileStat)
pairType name = hecsGetFileStat cfg (path0 ++ "/" ++ name)
>>= either
(\errno -> throwIO $ errnoToIOError "hecsReadDirectory" errno Nothing (Just name))
(\stat -> return (name, stat))
in
-- handle (\(_ :: SomeException) -> fmap Left getErrno) $
fmap Right $ getDirectoryContents (head $ primeFiles path0 cfg) >>= mapM pairType
hecsRemoveDirectory :: Config -> FilePath -> IO Errno
hecsRemoveDirectory cfg path =
do mapM_ removeDirectory $ entireFiles path cfg
return eOK
hecsRename :: Config -> FilePath -> FilePath -> IO Errno
hecsRename cfg src dest =
do zipWithM_ rename (entireFiles src cfg) (entireFiles dest cfg)
return eOK
hecsSetFileMode :: Config -> FilePath -> FileMode -> IO Errno
hecsSetFileMode cfg path mode =
do mapM_ (`setFileMode` mode) $ entireFiles path cfg
return eOK
hecsSetFileTimes :: Config -> FilePath -> EpochTime -> EpochTime -> IO Errno
hecsSetFileTimes cfg path at mt =
do mapM_ (\p -> setFileTimes p at mt) $ entireFiles path cfg
return eOK
hecsCreateDevice :: Config -> FilePath -> EntryType -> FileMode -> DeviceID -> IO Errno
hecsCreateDevice cfg path entryType mode dev
= case entryType of
Directory -> makeDevices >> return eOK
RegularFile -> makeDevices >> initMetadata >> return eOK
_ -> return eNOSYS
where
combinedMode = entryTypeToFileMode entryType `unionFileModes` mode
paths = entireFiles path cfg
makeDevices = mapM_ (\p -> createDevice p combinedMode dev) paths
initMetadata =
zipWithM_ (\f i -> withFile f WriteMode $ handleToFd >=> writeMetadata (0, i)) paths [0..]
hecsOpen :: Config -> FilePath -> OpenMode -> OpenFileFlags -> IO (Either Errno HT)
hecsOpen cfg path ReadOnly flags =
do primes <- mapM (\p -> openFd p ReadOnly Nothing flags) (primeFiles path cfg)
lock <- newMVar ()
return . Right $ HECS (V.fromList primes) V.empty lock
hecsOpen cfg path mode flags =
do primes <- mapM (\p -> openFd p ReadWrite Nothing flags) (primeFiles path cfg)
spares <- mapM (\p -> openFd p mode Nothing flags) (spareFiles path cfg)
lock <- newMVar ()
return . Right $ HECS (V.fromList primes) (V.fromList spares) lock
hecsRead :: Config -> FilePath -> HT -> ByteCount -> FileOffset -> IO (Either Errno B.ByteString)
hecsRead _ _ (HECS primes _ lock) count offset =
withMVar lock . const $ do
bs <- mapM fdReadBS chunks
return . Right . B.concat $ bs
where chunks :: [(Fd, FileOffset, ByteCount)]
chunks = toPhyAddrs primes offset (fromIntegral count)
hecsWrite :: Config -> FilePath -> HT -> B.ByteString -> FileOffset -> IO (Either Errno ByteCount)
hecsWrite _ _ (HECS primes spares lock) src offset =
withMVar lock . const $ do
len <- fmap sum $ mapM fdWriteBS (toPhyChunks primes offset src)
mapM_ (\si -> completeStripe si primes spares) [start..(end len)]
let newSize = offset + fromIntegral len
size <- readFileSize (V.head primes)
when (newSize > size) $ V.forM_ (primes <> spares) (writeFileSize newSize)
return . Right $ len
where stripeSize = V.length primes * defaultChunkSize
start = fromIntegral offset `quot` stripeSize
end n = (fromIntegral offset + fromIntegral n - 1) `quot` stripeSize
hecsFlush :: Config -> FilePath -> HT -> IO Errno
hecsFlush _ _ _ = return eOK
hecsRelease :: Config -> FilePath -> HT -> IO ()
hecsRelease _ _ (HECS primes spares _) = V.mapM_ closeFd (primes <> spares)
hecsSynchronizeFile :: Config -> FilePath -> SyncType -> IO Errno
hecsSynchronizeFile _ _ _ = return eOK
hecsCreateLink :: Config -> FilePath -> FilePath -> IO Errno
hecsCreateLink cfg src dest =
do zipWithM_ createLink (entireFiles src cfg) (entireFiles dest cfg)
return eOK
hecsRemoveLink :: Config -> FilePath -> IO Errno
hecsRemoveLink cfg path =
do mapM_ removeLink $ entireFiles path cfg
return eOK
hecsSetOwnerAndGroup :: Config -> FilePath -> UserID -> GroupID -> IO Errno
hecsSetOwnerAndGroup cfg path uid gid =
do mapM_ (\p -> setOwnerAndGroup p uid gid) $ entireFiles path cfg
return eOK
hecsSetFileSize :: Config -> FilePath -> FileOffset -> IO Errno
hecsSetFileSize cfg path newSize =
do let primes = primeFiles path cfg
spares = spareFiles path cfg
zipWithM_ setFileSize (primes <> spares)
(splitSize (length primes) (length spares) newSize)
forM_ (primes <> spares) $ \f ->
bracket (openFd f WriteOnly Nothing defaultFileFlags) closeFd
(writeFileSize newSize)
return eOK
-- hecsCreateSymbolicLink :: Config -> FilePath -> FilePath -> IO Errno
-- hecsCreateSymbolicLink cfg src dest =
-- do createSymbolicLink src dest
-- return eOK
-- hecsReadSymbolicLink :: Config -> FilePath -> IO (Either Errno FilePath)
-- hecsReadSymbolicLink cfg path =
-- do target <- readSymbolicLink . head $ primeFiles path cfg
-- return (Right target)
-- hecsGetFileSystemStats :: String -> IO (Either Errno FileSystemStats)
-- hecsGetFileSystemStats _ = return (Left eOK)
| comatose/hecs | src/HECS.hs | bsd-3-clause | 8,388 | 0 | 16 | 1,981 | 2,421 | 1,219 | 1,202 | 156 | 3 |
module Tc.TcLiteral where
import Language.Haskell.Exts
import BuiltIn.BuiltInTypes
import Tc.TcMonad
import Utils.ErrMsg
-- type checking literals
tcLiteral :: Literal -> TcM (Context, Type)
tcLiteral (Char _) = return ([], tChar)
tcLiteral (String _) = return ([], tString)
tcLiteral (Int _) = do
v <- newFreshVar
return ([numconstr v], v)
tcLiteral (Frac _) = do
v <- newFreshVar
return ([fracconstr v], v)
tcLiteral x = unsupportedExpErrMsg x | rodrigogribeiro/mptc | src/Tc/TcLiteral.hs | bsd-3-clause | 567 | 0 | 10 | 186 | 185 | 97 | 88 | 15 | 1 |
-- | Code generation for sequential Python.
module Futhark.CodeGen.Backends.SequentialPython
( compileProg,
)
where
import Control.Monad
import qualified Data.Text as T
import qualified Futhark.CodeGen.Backends.GenericPython as GenericPython
import Futhark.CodeGen.Backends.GenericPython.AST
import qualified Futhark.CodeGen.ImpCode.Sequential as Imp
import qualified Futhark.CodeGen.ImpGen.Sequential as ImpGen
import Futhark.IR.SeqMem
import Futhark.MonadFreshNames
-- | Compile the program to Python.
compileProg ::
MonadFreshNames m =>
GenericPython.CompilerMode ->
String ->
Prog SeqMem ->
m (ImpGen.Warnings, T.Text)
compileProg mode class_name =
ImpGen.compileProg
>=> traverse
( GenericPython.compileProg
mode
class_name
GenericPython.emptyConstructor
imports
defines
operations
()
[]
[]
)
where
imports =
[ Import "sys" Nothing,
Import "numpy" $ Just "np",
Import "ctypes" $ Just "ct",
Import "time" Nothing
]
defines = []
operations :: GenericPython.Operations Imp.Sequential ()
operations =
GenericPython.defaultOperations
{ GenericPython.opsCompiler = const $ return (),
GenericPython.opsCopy = copySequentialMemory
}
copySequentialMemory :: GenericPython.Copy Imp.Sequential ()
copySequentialMemory destmem destidx DefaultSpace srcmem srcidx DefaultSpace nbytes _bt =
GenericPython.copyMemoryDefaultSpace destmem destidx srcmem srcidx nbytes
copySequentialMemory _ _ destspace _ _ srcspace _ _ =
error $ "Cannot copy to " ++ show destspace ++ " from " ++ show srcspace
| HIPERFIT/futhark | src/Futhark/CodeGen/Backends/SequentialPython.hs | isc | 1,697 | 0 | 11 | 387 | 372 | 205 | 167 | 45 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
module Yesod.Routes.TH.RouteAttrs
( mkRouteAttrsInstance
) where
import Yesod.Routes.TH.Types
import Yesod.Routes.Class
import Language.Haskell.TH.Syntax
import Data.Set (fromList)
import Data.Text (pack)
#if __GLASGOW_HASKELL__ < 710
import Control.Applicative ((<$>))
#endif
mkRouteAttrsInstance :: Type -> [ResourceTree a] -> Q Dec
mkRouteAttrsInstance typ ress = do
clauses <- mapM (goTree id) ress
return $ instanceD [] (ConT ''RouteAttrs `AppT` typ)
[ FunD 'routeAttrs $ concat clauses
]
goTree :: (Pat -> Pat) -> ResourceTree a -> Q [Clause]
goTree front (ResourceLeaf res) = return <$> goRes front res
goTree front (ResourceParent name _check pieces trees) =
concat <$> mapM (goTree front') trees
where
ignored = (replicate toIgnore WildP ++) . return
toIgnore = length $ filter isDynamic pieces
isDynamic Dynamic{} = True
isDynamic Static{} = False
front' = front . ConP (mkName name) . ignored
goRes :: (Pat -> Pat) -> Resource a -> Q Clause
goRes front Resource {..} =
return $ Clause
[front $ RecP (mkName resourceName) []]
(NormalB $ VarE 'fromList `AppE` ListE (map toText resourceAttrs))
[]
where
toText s = VarE 'pack `AppE` LitE (StringL s)
instanceD :: Cxt -> Type -> [Dec] -> Dec
#if MIN_VERSION_template_haskell(2,11,0)
instanceD = InstanceD Nothing
#else
instanceD = InstanceD
#endif
| erikd/yesod | yesod-core/Yesod/Routes/TH/RouteAttrs.hs | mit | 1,489 | 0 | 12 | 303 | 498 | 265 | 233 | 34 | 2 |
module Foo.Foo where
<resolved>foo = putStrLn "oh no!"
| carymrobbins/intellij-haskforce | tests/gold/resolve/Module00001/Foo.hs | apache-2.0 | 56 | 2 | 5 | 9 | 22 | 11 | 11 | -1 | -1 |
import Paths_yesod_dsl (version)
import Data.Version (showVersion)
import YesodDsl.Parser
import System.Environment
import System.Console.GetOpt
import YesodDsl.Generator
import Control.Monad
data Flag = Version
| JsonPath String
| FayPath String deriving Eq
options :: [OptDescr Flag]
options = [
Option [] ["json"] (ReqArg JsonPath "FILE") "translate DSL definition to JSON object",
Option ['v'] ["version"] (NoArg Version) "print version number"
]
header :: String
header = "Usage: yesod-dsl FILE"
main :: IO ()
main = do
args <- getArgs
case getOpt RequireOrder options args of
(o, (path:_), []) -> main' o path
(o, _, msgs) -> if Version `elem` o
then versionInfo
else error $ concat msgs ++ usageInfo header options
where
versionInfo = putStrLn $ "yesod-dsl " ++ showVersion version
main' o path = do
if Version `elem` o
then versionInfo
else do
mast <- parse path
case mast of
Just ast -> do
generate path $ ast
forM_ o (processFlag ast)
Nothing -> return ()
processFlag ast (JsonPath path) = genJson path ast
processFlag _ _ = return ()
| abrim/yesod-dsl | main/main.hs | bsd-2-clause | 1,387 | 0 | 19 | 508 | 392 | 205 | 187 | 37 | 6 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
#if __GLASGOW_HASKELL__ >= 707
{-# LANGUAGE RoleAnnotations #-}
#endif
--------------------------------------------------------------------
-- |
-- Module : System.Random.PCG
-- Copyright : Copyright (c) 2014-2015, Christopher Chalmers <c.chalmers@me.com>
-- License : BSD3
-- Maintainer : Christopher Chalmers <c.chalmers@me.com>
-- Stability : experimental
-- Portability: CPP, FFI
--
-- Standard PCG Random Number Generator with chosen streams. See
-- <http://www.pcg-random.org> for details.
--
-- @
-- import Control.Monad.ST
-- import System.Random.PCG
--
-- three :: [Double]
-- three = runST $ do
-- g <- create
-- a <- uniform g
-- b <- uniform g
-- c <- uniform g
-- return [a,b,c]
-- @
module System.Random.PCG
( -- * Generator
Gen, GenIO, GenST
, create, createSystemRandom, initialize
, withSystemRandom, withFrozen
-- * Getting random numbers
, Variate (..)
, advance, retract
-- * Frozen generator
, FrozenGen
, save, restore, seed, initFrozen
-- * Type restricted versions
-- ** uniform
, uniformW8, uniformW16, uniformW32, uniformW64
, uniformI8, uniformI16, uniformI32, uniformI64
, uniformF, uniformD, uniformBool
-- ** uniformR
, uniformRW8, uniformRW16, uniformRW32, uniformRW64
, uniformRI8, uniformRI16, uniformRI32, uniformRI64
, uniformRF, uniformRD, uniformRBool
-- ** uniformB
, uniformBW8, uniformBW16, uniformBW32, uniformBW64
, uniformBI8, uniformBI16, uniformBI32, uniformBI64
, uniformBF, uniformBD, uniformBBool
) where
import Control.Applicative
import Control.Monad.Primitive
import Control.Monad.ST
import Data.Data
import Foreign
import GHC.Generics
import System.IO.Unsafe
import System.Random
import System.Random.PCG.Class
-- $setup
-- >>> import System.Random.PCG
-- >>> import System.Random.PCG.Class
-- >>> import Control.Monad
------------------------------------------------------------------------
-- State
------------------------------------------------------------------------
-- | Immutable snapshot of the state of a 'Gen'.
data FrozenGen = FrozenGen {-# UNPACK #-} !Word64 {-# UNPACK #-} !Word64
deriving (Show, Eq, Ord, Data, Typeable, Generic)
-- | Save the state of a 'Gen' in a 'FrozenGen'.
save :: PrimMonad m => Gen (PrimState m) -> m FrozenGen
save (Gen p) = unsafePrimToPrim (peek p)
{-# INLINE save #-}
-- | Restore a 'Gen' from a 'FrozenGen'.
restore :: PrimMonad m => FrozenGen -> m (Gen (PrimState m))
restore s = unsafePrimToPrim $ do
p <- malloc
poke p s
return (Gen p)
{-# INLINE restore #-}
-- | Fixed seed.
seed :: FrozenGen
seed = FrozenGen 0x853c49e6748fea9b 0xda3e39cb94b95bdb
-- | Generate a new seed using two 'Word64's.
--
-- >>> initFrozen 0 0
-- FrozenGen 6364136223846793006 1
initFrozen :: Word64 -> Word64 -> FrozenGen
initFrozen w1 w2 = unsafeDupablePerformIO $ do
p <- malloc
pcg32_srandom_r p w1 w2
peek p <* free p
{-# INLINE initFrozen #-}
instance Storable FrozenGen where
sizeOf _ = 16
{-# INLINE sizeOf #-}
alignment _ = 8
{-# INLINE alignment #-}
poke ptr (FrozenGen x y) = poke ptr' x >> pokeElemOff ptr' 1 y
where ptr' = castPtr ptr
{-# INLINE poke #-}
peek ptr = FrozenGen <$> peek ptr' <*> peekElemOff ptr' 1
where ptr' = castPtr ptr
{-# INLINE peek #-}
------------------------------------------------------------------------
-- PrimMonad interface
------------------------------------------------------------------------
-- | State of the random number generator
newtype Gen s = Gen (Ptr FrozenGen)
deriving (Eq, Ord)
#if __GLASGOW_HASKELL__ >= 707
type role Gen representational
#endif
-- this should be type safe because the Gen cannot escape its PrimMonad
-- | Type alias of 'Gen' specialized to 'IO'.
type GenIO = Gen RealWorld
-- | Type alias of 'Gen' specialized to 'ST'.
type GenST s = Gen s
-- Note this doesn't force it to be in ST. You can write (STGen Realworld)
-- and it'll work in IO. Writing STGen s = Gen (PrimState (ST s)) doesn't
-- solve this.
-- | Create a 'Gen' from a fixed initial 'seed'.
create :: PrimMonad m => m (Gen (PrimState m))
create = restore seed
-- | Initialize a generator with two words.
--
-- >>> initialize 0 0 >>= save
-- FrozenGen 6364136223846793006 1
initialize :: PrimMonad m => Word64 -> Word64 -> m (Gen (PrimState m))
initialize a b = unsafePrimToPrim $ do
p <- malloc
pcg32_srandom_r p a b
return (Gen p)
-- | Seed with system random number. (@\/dev\/urandom@ on Unix-like
-- systems and CryptAPI on Windows).
withSystemRandom :: (GenIO -> IO a) -> IO a
withSystemRandom f = do
w1 <- sysRandom
w2 <- sysRandom
initialize w1 w2 >>= f
-- | Run an action with a frozen generator, returning the result and the
-- new frozen generator.
withFrozen :: FrozenGen -> (forall s. Gen s -> ST s a) -> (a, FrozenGen)
withFrozen s f = runST $ restore s >>= \g -> liftA2 (,) (f g) (save g)
-- | Seed a PRNG with data from the system's fast source of pseudo-random
-- numbers. All the caveats of 'withSystemRandom' apply here as well.
createSystemRandom :: IO GenIO
createSystemRandom = withSystemRandom (return :: GenIO -> IO GenIO)
-- -- | Generate a uniform 'Word32' bounded by the given bound.
-- uniformB :: PrimMonad m => Word32 -> Gen (PrimState m) -> m Word32
-- uniformB u (Gen p) = unsafePrimToPrim $ pcg32_boundedrand_r p u
-- {-# INLINE uniformB #-}
-- | Advance the given generator n steps in log(n) time. (Note that a
-- \"step\" is a single random 32-bit (or less) 'Variate'. Data types
-- such as 'Double' or 'Word64' require two \"steps\".)
--
-- >>> create >>= \g -> replicateM_ 1000 (uniformW32 g) >> uniformW32 g
-- 3640764222
-- >>> create >>= \g -> replicateM_ 500 (uniformD g) >> uniformW32 g
-- 3640764222
-- >>> create >>= \g -> advance 1000 g >> uniformW32 g
-- 3640764222
advance :: PrimMonad m => Word64 -> Gen (PrimState m) -> m ()
advance u (Gen p) = unsafePrimToPrim $ pcg32_advance_r p u
{-# INLINE advance #-}
-- | Retract the given generator n steps in log(2^64-n) time. This
-- is just @advance (-n)@.
--
-- >>> create >>= \g -> replicateM 3 (uniformW32 g)
-- [355248013,41705475,3406281715]
-- >>> create >>= \g -> retract 1 g >> replicateM 3 (uniformW32 g)
-- [19683962,355248013,41705475]
retract :: PrimMonad m => Word64 -> Gen (PrimState m) -> m ()
retract u g = advance (-u) g
{-# INLINE retract #-}
------------------------------------------------------------------------
-- Foreign calls
------------------------------------------------------------------------
-- It shouldn't be too hard to impliment the algorithm in pure haskell.
-- For now just use the c interface.
-- For whatever reason, calling the #defined versions doesn't seem to work
-- so we need to call the low-level api directly
foreign import ccall unsafe "pcg_setseq_64_srandom_r"
pcg32_srandom_r :: Ptr FrozenGen -> Word64 -> Word64 -> IO ()
foreign import ccall unsafe "pcg_setseq_64_xsh_rr_32_random_r"
pcg32_random_r :: Ptr FrozenGen -> IO Word32
foreign import ccall unsafe "pcg_setseq_64_xsh_rr_32_boundedrand_r"
pcg32_boundedrand_r :: Ptr FrozenGen -> Word32 -> IO Word32
foreign import ccall unsafe "pcg_setseq_64_advance_r"
pcg32_advance_r :: Ptr FrozenGen -> Word64 -> IO ()
------------------------------------------------------------------------
-- Instances
------------------------------------------------------------------------
instance (PrimMonad m, s ~ PrimState m) => Generator (Gen s) m where
uniform1 f (Gen p) = unsafePrimToPrim $ f <$> pcg32_random_r p
{-# INLINE uniform1 #-}
uniform2 f (Gen p) = unsafePrimToPrim $ do
w1 <- pcg32_random_r p
w2 <- pcg32_random_r p
return $ f w1 w2
{-# INLINE uniform2 #-}
uniform1B f b (Gen p) = unsafePrimToPrim $ f <$> pcg32_boundedrand_r p b
{-# INLINE uniform1B #-}
instance RandomGen FrozenGen where
next s = unsafeDupablePerformIO $ do
p <- malloc
poke p s
w1 <- pcg32_random_r p
w2 <- pcg32_random_r p
s' <- peek p
free p
return (wordsTo64Bit w1 w2, s')
{-# INLINE next #-}
split s = unsafeDupablePerformIO $ do
p <- malloc
poke p s
w1 <- pcg32_random_r p
w2 <- pcg32_random_r p
w3 <- pcg32_random_r p
w4 <- pcg32_random_r p
w5 <- pcg32_random_r p
w6 <- pcg32_random_r p
w7 <- pcg32_random_r p
w8 <- pcg32_random_r p
pcg32_srandom_r p (wordsTo64Bit w1 w2) (wordsTo64Bit w3 w4)
s1 <- peek p
pcg32_srandom_r p (wordsTo64Bit w5 w6) (wordsTo64Bit w7 w8)
s2 <- peek p
free p
return (s1,s2)
| rrnewton/pcg-random | src/System/Random/PCG.hs | bsd-3-clause | 8,895 | 0 | 12 | 1,752 | 1,665 | 895 | 770 | 136 | 1 |
module CPU.Common (
fetch
, fetch16
, jumpTo
, pushOntoStack
, popFromStack
) where
import CPU
import CPU.Environment (Register16(..))
import CPU.Types (Address, Opcode)
import CPU.Reference (CPUReference(..))
import BitTwiddling (joinBytes, joinBytesM, toBytes)
import Data.Word (Word16)
----- Other common routines
jumpTo :: Address -> CPU s ()
jumpTo addr = writeWord PC addr
incrementPC :: CPU s ()
incrementPC = modifyWord PC (+1)
-- The Gameboy stack is upside down.
-- It starts at the top and moves down the addresses.
pushOntoStack :: Word16 -> CPU s ()
pushOntoStack word = do
modifyWord SP (subtract 2 :: Word16 -> Word16)
let (lowByte, highByte) = toBytes word
addr <- readWord SP
writeMemory (addr + 0) lowByte
writeMemory (addr + 1) highByte
popFromStack :: CPU s Word16
popFromStack = do
addr <- readWord SP
lowByte <- readMemory (addr + 0)
highByte <- readMemory (addr + 1)
modifyWord SP (+2)
return (lowByte `joinBytes` highByte)
fetch :: CPU s Opcode
fetch = do
addr <- readWord PC
incrementPC
readMemory addr
fetch16 :: CPU s Word16
fetch16 = fetch `joinBytesM` fetch
| ChaosCabbage/my-haskell-flailing | src/CPU/Common.hs | bsd-3-clause | 1,222 | 0 | 10 | 309 | 394 | 207 | 187 | 37 | 1 |
module Prime.Factorize where
-- | find prime factorization if all prime factors are below bound
-- warning: uses trial division
easy :: Integer -> Integer -> Maybe [ (Integer, Int) ]
easy bound x = easy_for ( 2 : [ 3, 5 .. bound ] ) x
easy_for tts x = do
t : ts <- return tts
if t * t > x then Just [ (x, 1) ]
else
let ( q, r ) = divMod x t
in if 0 == r then do
fes <- easy_for tts q
return $ bump t fes
else easy_for ts x
bump t ((s,e) : rest) | t == s = (s,e+1) : rest
bump t rest = (t,1) : rest
| florianpilz/autotool | src/Prime/Factorize.hs | gpl-2.0 | 595 | 0 | 14 | 218 | 250 | 131 | 119 | 13 | 3 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module GHC.Storable (module M) where
import "base" GHC.Storable as M
| Ye-Yong-Chi/codeworld | codeworld-base/src/GHC/Storable.hs | apache-2.0 | 739 | 0 | 4 | 136 | 23 | 17 | 6 | 4 | 0 |
module StackTest where
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
import Control.Concurrent
import Control.Exception
import Data.List (intercalate)
import System.Environment
import System.FilePath
import System.Directory
import System.IO
import System.IO.Error
import System.Process
import System.Exit
import System.Info (arch, os)
run' :: FilePath -> [String] -> IO ExitCode
run' cmd args = do
logInfo $ "Running: " ++ cmd ++ " " ++ unwords (map showProcessArgDebug args)
(Nothing, Nothing, Nothing, ph) <- createProcess (proc cmd args)
waitForProcess ph
run :: FilePath -> [String] -> IO ()
run cmd args = do
ec <- run' cmd args
unless (ec == ExitSuccess) $ error $ "Exited with exit code: " ++ show ec
stack' :: [String] -> IO ExitCode
stack' args = do
stack <- getEnv "STACK_EXE"
run' stack args
stack :: [String] -> IO ()
stack args = do
ec <- stack' args
unless (ec == ExitSuccess) $ error $ "Exited with exit code: " ++ show ec
stackErr :: [String] -> IO ()
stackErr args = do
ec <- stack' args
when (ec == ExitSuccess) $ error "stack was supposed to fail, but didn't"
type Repl = ReaderT ReplConnection IO
data ReplConnection
= ReplConnection
{ replStdin :: Handle
, replStdout :: Handle
}
nextPrompt :: Repl ()
nextPrompt = do
(ReplConnection _ handle) <- ask
c <- liftIO $ hGetChar handle
if c == '>'
then do _ <- liftIO $ hGetChar handle
return ()
else nextPrompt
replCommand :: String -> Repl ()
replCommand cmd = do
(ReplConnection input _) <- ask
liftIO $ hPutStrLn input cmd
replGetLine :: Repl String
replGetLine = fmap replStdout ask >>= liftIO . hGetLine
replGetChar :: Repl Char
replGetChar = fmap replStdout ask >>= liftIO . hGetChar
runRepl :: FilePath -> [String] -> ReaderT ReplConnection IO () -> IO ExitCode
runRepl cmd args actions = do
logInfo $ "Running: " ++ cmd ++ " " ++ unwords (map showProcessArgDebug args)
(Just rStdin, Just rStdout, Just rStderr, ph) <-
createProcess (proc cmd args)
{ std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
}
hSetBuffering rStdin NoBuffering
hSetBuffering rStdout NoBuffering
hSetBuffering rStderr NoBuffering
forkIO $ withFile "/tmp/stderr" WriteMode
$ \err -> forever $ catch (hGetChar rStderr >>= hPutChar err)
$ \e -> unless (isEOFError e) $ throw e
runReaderT (nextPrompt >> actions) (ReplConnection rStdin rStdout)
waitForProcess ph
repl :: [String] -> Repl () -> IO ()
repl args action = do
stack <- getEnv "STACK_EXE"
ec <- runRepl stack ("repl":args) action
unless (ec == ExitSuccess) $ return ()
-- TODO: Understand why the exit code is 1 despite running GHCi tests
-- successfully.
-- else error $ "Exited with exit code: " ++ show ec
-- | Run stack with arguments and apply a check to the resulting
-- stderr output if the process succeeded.
stackCheckStderr :: [String] -> (String -> IO ()) -> IO ()
stackCheckStderr args check = do
stack <- getEnv "STACK_EXE"
logInfo $ "Running: " ++ stack ++ " " ++ unwords (map showProcessArgDebug args)
(ec, _, err) <- readProcessWithExitCode stack args ""
hPutStr stderr err
if ec /= ExitSuccess
then error $ "Exited with exit code: " ++ show ec
else check err
doesNotExist :: FilePath -> IO ()
doesNotExist fp = do
logInfo $ "doesNotExist " ++ fp
exists <- doesFileOrDirExist fp
case exists of
(Right msg) -> error msg
(Left _) -> return ()
doesExist :: FilePath -> IO ()
doesExist fp = do
logInfo $ "doesExist " ++ fp
exists <- doesFileOrDirExist fp
case exists of
(Right msg) -> return ()
(Left _) -> error "No file or directory exists"
doesFileOrDirExist :: FilePath -> IO (Either () String)
doesFileOrDirExist fp = do
isFile <- doesFileExist fp
if isFile
then return (Right ("File exists: " ++ fp))
else do
isDir <- doesDirectoryExist fp
if isDir
then return (Right ("Directory exists: " ++ fp))
else return (Left ())
copy :: FilePath -> FilePath -> IO ()
copy src dest = do
logInfo ("Copy " ++ show src ++ " to " ++ show dest)
System.Directory.copyFile src dest
fileContentsMatch :: FilePath -> FilePath -> IO ()
fileContentsMatch f1 f2 = do
doesExist f1
doesExist f2
f1Contents <- readFile f1
f2Contents <- readFile f2
unless (f1Contents == f2Contents) $
error ("contents do not match for " ++ show f1 ++ " " ++ show f2)
logInfo :: String -> IO ()
logInfo = hPutStrLn stderr
-- TODO: use stack's process running utilties? (better logging)
-- for now just copy+modifying this one from System.Process.Log
-- | Show a process arg including speechmarks when necessary. Just for
-- debugging purposes, not functionally important.
showProcessArgDebug :: String -> String
showProcessArgDebug x
| any special x = show x
| otherwise = x
where special '"' = True
special ' ' = True
special _ = False
-- | Extension of executables
exeExt = if isWindows then ".exe" else ""
-- | Is the OS Windows?
isWindows = os == "mingw32"
-- | Is the OS Alpine Linux?
getIsAlpine = doesFileExist "/etc/alpine-release"
-- | Is the architecture ARM?
isARM = arch == "arm"
-- | To avoid problems with GHC version mismatch when a new LTS major
-- version is released, pass this argument to @stack@ when running in
-- a global context. The LTS major version here should match that of
-- the main @stack.yaml@.
defaultResolverArg = "--resolver=lts-8.0"
| mrkkrp/stack | test/integration/lib/StackTest.hs | bsd-3-clause | 5,701 | 0 | 15 | 1,377 | 1,710 | 844 | 866 | 137 | 3 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[TypeRep]{Type - friends' interface}
Note [The Type-related module hierarchy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class
TyCon imports Class
TypeRep
TysPrim imports TypeRep ( including mkTyConTy )
Kind imports TysPrim ( mainly for primitive kinds )
Type imports Kind
Coercion imports Type
-}
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
{-# OPTIONS_HADDOCK hide #-}
-- We expose the relevant stuff from this module via the Type module
module ETA.Types.TypeRep (
TyThing(..),
Type(..),
TyLit(..),
KindOrType, Kind, SuperKind,
PredType, ThetaType, -- Synonyms
-- Functions over types
mkTyConTy, mkTyVarTy, mkTyVarTys,
isLiftedTypeKind, isSuperKind, isTypeVar, isKindVar,
-- Pretty-printing
pprType, pprParendType, pprTypeApp, pprTvBndr, pprTvBndrs,
pprTyThing, pprTyThingCategory, pprSigmaType, pprSigmaTypeExtraCts,
pprTheta, pprForAll, pprUserForAll,
pprThetaArrowTy, pprClassPred,
pprKind, pprParendKind, pprTyLit, suppressKinds,
TyPrec(..), maybeParen, pprTcApp,
pprPrefixApp, pprArrowChain, ppr_type,
-- Free variables
tyVarsOfType, tyVarsOfTypes, closeOverKinds, varSetElemsKvsFirst,
-- * Tidying type related things up for printing
tidyType, tidyTypes,
tidyOpenType, tidyOpenTypes,
tidyOpenKind,
tidyTyVarBndr, tidyTyVarBndrs, tidyFreeTyVars,
tidyOpenTyVar, tidyOpenTyVars,
tidyTyVarOcc,
tidyTopType,
tidyKind,
-- Substitutions
TvSubst(..), TvSubstEnv
) where
#include "HsVersions.h"
import {-# SOURCE #-} ETA.BasicTypes.DataCon( dataConTyCon )
import ETA.BasicTypes.ConLike ( ConLike(..) )
import {-# SOURCE #-} ETA.Types.Type( isPredTy ) -- Transitively pulls in a LOT of stuff, better to break the loop
-- friends:
import ETA.BasicTypes.Var
import ETA.BasicTypes.VarEnv
import ETA.BasicTypes.VarSet
import ETA.BasicTypes.Name
import ETA.BasicTypes.BasicTypes
import ETA.Types.TyCon
import ETA.Types.Class
import ETA.Types.CoAxiom
-- others
import ETA.Prelude.PrelNames
import ETA.Utils.Outputable
import ETA.Utils.FastString
import ETA.Utils.Util
import ETA.Main.DynFlags
-- libraries
import Data.List( mapAccumL, partition )
import qualified Data.Data as Data hiding ( TyCon )
{-
************************************************************************
* *
\subsection{The data type}
* *
************************************************************************
-}
-- | The key representation of types within the compiler
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.lhs
data Type
= TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable)
| AppTy -- See Note [AppTy invariant]
Type
Type -- ^ Type application to something other than a 'TyCon'. Parameters:
--
-- 1) Function: must /not/ be a 'TyConApp',
-- must be another 'AppTy', or 'TyVarTy'
--
-- 2) Argument type
| TyConApp -- See Note [AppTy invariant]
TyCon
[KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
-- Invariant: saturated appliations of 'FunTyCon' must
-- use 'FunTy' and saturated synonyms must use their own
-- constructors. However, /unsaturated/ 'FunTyCon's
-- do appear as 'TyConApp's.
-- Parameters:
--
-- 1) Type constructor being applied to.
--
-- 2) Type arguments. Might not have enough type arguments
-- here to saturate the constructor.
-- Even type synonyms are not necessarily saturated;
-- for example unsaturated type synonyms
-- can appear as the right hand side of a type synonym.
| FunTy
Type
Type -- ^ Special case of 'TyConApp': @TyConApp FunTyCon [t1, t2]@
-- See Note [Equality-constrained types]
| ForAllTy
Var -- Type or kind variable
Type -- ^ A polymorphic type
| LitTy TyLit -- ^ Type literals are similar to type constructors.
deriving (Data.Data, Data.Typeable)
-- NOTE: Other parts of the code assume that type literals do not contain
-- types or type variables.
data TyLit
= NumTyLit Integer
| StrTyLit FastString
deriving (Eq, Ord, Data.Data, Data.Typeable)
type KindOrType = Type -- See Note [Arguments to type constructors]
-- | The key type representing kinds in the compiler.
-- Invariant: a kind is always in one of these forms:
--
-- > FunTy k1 k2
-- > TyConApp PrimTyCon [...]
-- > TyVar kv -- (during inference only)
-- > ForAll ... -- (for top-level coercions)
type Kind = Type
-- | "Super kinds", used to help encode 'Kind's as types.
-- Invariant: a super kind is always of this form:
--
-- > TyConApp SuperKindTyCon ...
type SuperKind = Type
{-
Note [The kind invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~
The kinds
# UnliftedTypeKind
OpenKind super-kind of *, #
can never appear under an arrow or type constructor in a kind; they
can only be at the top level of a kind. It follows that primitive TyCons,
which have a naughty pseudo-kind
State# :: * -> #
must always be saturated, so that we can never get a type whose kind
has a UnliftedTypeKind or ArgTypeKind underneath an arrow.
Nor can we abstract over a type variable with any of these kinds.
k :: = kk | # | ArgKind | (#) | OpenKind
kk :: = * | kk -> kk | T kk1 ... kkn
So a type variable can only be abstracted kk.
Note [Arguments to type constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because of kind polymorphism, in addition to type application we now
have kind instantiation. We reuse the same notations to do so.
For example:
Just (* -> *) Maybe
Right * Nat Zero
are represented by:
TyConApp (PromotedDataCon Just) [* -> *, Maybe]
TyConApp (PromotedDataCon Right) [*, Nat, (PromotedDataCon Zero)]
Important note: Nat is used as a *kind* and not as a type. This can be
confusing, since type-level Nat and kind-level Nat are identical. We
use the kind of (PromotedDataCon Right) to know if its arguments are
kinds or types.
This kind instantiation only happens in TyConApp currently.
Note [Equality-constrained types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type forall ab. (a ~ [b]) => blah
is encoded like this:
ForAllTy (a:*) $ ForAllTy (b:*) $
FunTy (TyConApp (~) [a, [b]]) $
blah
-------------------------------------
Note [PredTy]
-}
-- | A type of the form @p@ of kind @Constraint@ represents a value whose type is
-- the Haskell predicate @p@, where a predicate is what occurs before
-- the @=>@ in a Haskell type.
--
-- We use 'PredType' as documentation to mark those types that we guarantee to have
-- this kind.
--
-- It can be expanded into its representation, but:
--
-- * The type checker must treat it as opaque
--
-- * The rest of the compiler treats it as transparent
--
-- Consider these examples:
--
-- > f :: (Eq a) => a -> Int
-- > g :: (?x :: Int -> Int) => a -> Int
-- > h :: (r\l) => {r} => {l::Int | r}
--
-- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\"
type PredType = Type
-- | A collection of 'PredType's
type ThetaType = [PredType]
{-
(We don't support TREX records yet, but the setup is designed
to expand to allow them.)
A Haskell qualified type, such as that for f,g,h above, is
represented using
* a FunTy for the double arrow
* with a type of kind Constraint as the function argument
The predicate really does turn into a real extra argument to the
function. If the argument has type (p :: Constraint) then the predicate p is
represented by evidence of type p.
************************************************************************
* *
Simple constructors
* *
************************************************************************
These functions are here so that they can be used by TysPrim,
which in turn is imported by Type
-}
mkTyVarTy :: TyVar -> Type
mkTyVarTy = TyVarTy
mkTyVarTys :: [TyVar] -> [Type]
mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
-- | Create the plain type constructor type which has been applied to no type arguments at all.
mkTyConTy :: TyCon -> Type
mkTyConTy tycon = TyConApp tycon []
-- Some basic functions, put here to break loops eg with the pretty printer
isLiftedTypeKind :: Kind -> Bool
isLiftedTypeKind (TyConApp tc []) = tc `hasKey` liftedTypeKindTyConKey
isLiftedTypeKind _ = False
-- | Is this a super-kind (i.e. a type-of-kinds)?
isSuperKind :: Type -> Bool
isSuperKind (TyConApp skc []) = skc `hasKey` superKindTyConKey
isSuperKind _ = False
isTypeVar :: Var -> Bool
isTypeVar v = isTKVar v && not (isSuperKind (varType v))
isKindVar :: Var -> Bool
isKindVar v = isTKVar v && isSuperKind (varType v)
{-
************************************************************************
* *
Free variables of types and coercions
* *
************************************************************************
-}
tyVarsOfType :: Type -> VarSet
-- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
-- tyVarsOfType returns only the free variables of a type
-- For example, tyVarsOfType (a::k) returns {a}, not including the
-- kind variable {k}
tyVarsOfType (TyVarTy v) = unitVarSet v
tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
tyVarsOfType (LitTy {}) = emptyVarSet
tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
`unionVarSet` tyVarsOfType (tyVarKind tyvar)
tyVarsOfTypes :: [Type] -> TyVarSet
tyVarsOfTypes = mapUnionVarSet tyVarsOfType
closeOverKinds :: TyVarSet -> TyVarSet
-- Add the kind variables free in the kinds
-- of the tyvars in the given set
closeOverKinds tvs
= foldVarSet (\tv ktvs -> tyVarsOfType (tyVarKind tv) `unionVarSet` ktvs)
tvs tvs
varSetElemsKvsFirst :: VarSet -> [TyVar]
-- {k1,a,k2,b} --> [k1,k2,a,b]
varSetElemsKvsFirst set
= kvs ++ tvs
where
(kvs, tvs) = partition isKindVar (varSetElems set)
{-
************************************************************************
* *
TyThing
* *
************************************************************************
Despite the fact that DataCon has to be imported via a hi-boot route,
this module seems the right place for TyThing, because it's needed for
funTyCon and all the types in TysPrim.
Note [ATyCon for classes]
~~~~~~~~~~~~~~~~~~~~~~~~~
Both classes and type constructors are represented in the type environment
as ATyCon. You can tell the difference, and get to the class, with
isClassTyCon :: TyCon -> Bool
tyConClass_maybe :: TyCon -> Maybe Class
The Class and its associated TyCon have the same Name.
-}
-- | A typecheckable-thing, essentially anything that has a name
data TyThing
= AnId Id
| AConLike ConLike
| ATyCon TyCon -- TyCons and classes; see Note [ATyCon for classes]
| ACoAxiom (CoAxiom Branched)
deriving (Eq, Ord)
instance Outputable TyThing where
ppr = pprTyThing
pprTyThing :: TyThing -> SDoc
pprTyThing thing = pprTyThingCategory thing <+> quotes (ppr (getName thing))
pprTyThingCategory :: TyThing -> SDoc
pprTyThingCategory (ATyCon tc)
| isClassTyCon tc = ptext (sLit "Class")
| otherwise = ptext (sLit "Type constructor")
pprTyThingCategory (ACoAxiom _) = ptext (sLit "Coercion axiom")
pprTyThingCategory (AnId _) = ptext (sLit "Identifier")
pprTyThingCategory (AConLike (RealDataCon _)) = ptext (sLit "Data constructor")
pprTyThingCategory (AConLike (PatSynCon _)) = ptext (sLit "Pattern synonym")
instance NamedThing TyThing where -- Can't put this with the type
getName (AnId id) = getName id -- decl, because the DataCon instance
getName (ATyCon tc) = getName tc -- isn't visible there
getName (ACoAxiom cc) = getName cc
getName (AConLike cl) = getName cl
{-
************************************************************************
* *
Substitutions
Data type defined here to avoid unnecessary mutual recursion
* *
************************************************************************
-}
-- | Type substitution
--
-- #tvsubst_invariant#
-- The following invariants must hold of a 'TvSubst':
--
-- 1. The in-scope set is needed /only/ to
-- guide the generation of fresh uniques
--
-- 2. In particular, the /kind/ of the type variables in
-- the in-scope set is not relevant
--
-- 3. The substitution is only applied ONCE! This is because
-- in general such application will not reached a fixed point.
data TvSubst
= TvSubst InScopeSet -- The in-scope type and kind variables
TvSubstEnv -- Substitutes both type and kind variables
-- See Note [Apply Once]
-- and Note [Extending the TvSubstEnv]
-- | A substitution of 'Type's for 'TyVar's
-- and 'Kind's for 'KindVar's
type TvSubstEnv = TyVarEnv Type
-- A TvSubstEnv is used both inside a TvSubst (with the apply-once
-- invariant discussed in Note [Apply Once]), and also independently
-- in the middle of matching, and unification (see Types.Unify)
-- So you have to look at the context to know if it's idempotent or
-- apply-once or whatever
{-
Note [Apply Once]
~~~~~~~~~~~~~~~~~
We use TvSubsts to instantiate things, and we might instantiate
forall a b. ty
\with the types
[a, b], or [b, a].
So the substitution might go [a->b, b->a]. A similar situation arises in Core
when we find a beta redex like
(/\ a /\ b -> e) b a
Then we also end up with a substitution that permutes type variables. Other
variations happen to; for example [a -> (a, b)].
***************************************************
*** So a TvSubst must be applied precisely once ***
***************************************************
A TvSubst is not idempotent, but, unlike the non-idempotent substitution
we use during unifications, it must not be repeatedly applied.
Note [Extending the TvSubst]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #tvsubst_invariant# for the invariants that must hold.
This invariant allows a short-cut when the TvSubstEnv is empty:
if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
then (substTy subst ty) does nothing.
For example, consider:
(/\a. /\b:(a~Int). ...b..) Int
We substitute Int for 'a'. The Unique of 'b' does not change, but
nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
This invariant has several crucial consequences:
* In substTyVarBndr, we need extend the TvSubstEnv
- if the unique has changed
- or if the kind has changed
* In substTyVar, we do not need to consult the in-scope set;
the TvSubstEnv is enough
* In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
************************************************************************
* *
Pretty-printing types
Defined very early because of debug printing in assertions
* *
************************************************************************
@pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
defined to use this. @pprParendType@ is the same, except it puts
parens around the type, except for the atomic cases. @pprParendType@
works just by setting the initial context precedence very high.
Note [Precedence in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't keep the fixity of type operators in the operator. So the pretty printer
operates the following precedene structre:
Type constructor application binds more tightly than
Oerator applications which bind more tightly than
Function arrow
So we might see a :+: T b -> c
meaning (a :+: (T b)) -> c
Maybe operator applications should bind a bit less tightly?
Anyway, that's the current story, and it is used consistently for Type and HsType
-}
data TyPrec -- See Note [Prededence in types]
= TopPrec -- No parens
| FunPrec -- Function args; no parens for tycon apps
| TyOpPrec -- Infix operator
| TyConPrec -- Tycon args; no parens for atomic
deriving( Eq, Ord )
maybeParen :: TyPrec -> TyPrec -> SDoc -> SDoc
maybeParen ctxt_prec inner_prec pretty
| ctxt_prec < inner_prec = pretty
| otherwise = parens pretty
------------------
pprType, pprParendType :: Type -> SDoc
pprType ty = ppr_type TopPrec ty
pprParendType ty = ppr_type TyConPrec ty
pprTyLit :: TyLit -> SDoc
pprTyLit = ppr_tylit TopPrec
pprKind, pprParendKind :: Kind -> SDoc
pprKind = pprType
pprParendKind = pprParendType
------------
pprClassPred :: Class -> [Type] -> SDoc
pprClassPred clas tys = pprTypeApp (classTyCon clas) tys
------------
pprTheta :: ThetaType -> SDoc
-- pprTheta [pred] = pprPred pred -- I'm in two minds about this
pprTheta theta = parens (sep (punctuate comma (map (ppr_type TopPrec) theta)))
pprThetaArrowTy :: ThetaType -> SDoc
pprThetaArrowTy [] = empty
pprThetaArrowTy [pred] = ppr_type TyOpPrec pred <+> darrow
-- TyOpPrec: Num a => a -> a does not need parens
-- bug (a :~: b) => a -> b currently does
-- Trac # 9658
pprThetaArrowTy preds = parens (fsep (punctuate comma (map (ppr_type TopPrec) preds)))
<+> darrow
-- Notice 'fsep' here rather that 'sep', so that
-- type contexts don't get displayed in a giant column
-- Rather than
-- instance (Eq a,
-- Eq b,
-- Eq c,
-- Eq d,
-- Eq e,
-- Eq f,
-- Eq g,
-- Eq h,
-- Eq i,
-- Eq j,
-- Eq k,
-- Eq l) =>
-- Eq (a, b, c, d, e, f, g, h, i, j, k, l)
-- we get
--
-- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i,
-- Eq j, Eq k, Eq l) =>
-- Eq (a, b, c, d, e, f, g, h, i, j, k, l)
pprThetaArrowTyExtra :: ThetaType -> SDoc
pprThetaArrowTyExtra [] = text "_" <+> darrow
pprThetaArrowTyExtra preds = parens (fsep (punctuate comma xs)) <+> darrow
where xs = (map (ppr_type TopPrec) preds) ++ [text "_"]
------------------
instance Outputable Type where
ppr ty = pprType ty
instance Outputable TyLit where
ppr = pprTyLit
------------------
-- OK, here's the main printer
ppr_type :: TyPrec -> Type -> SDoc
ppr_type _ (TyVarTy tv) = ppr_tvar tv
ppr_type p (TyConApp tc tys) = pprTyTcApp p tc tys
ppr_type p (LitTy l) = ppr_tylit p l
ppr_type p ty@(ForAllTy {}) = ppr_forall_type p ty
ppr_type p (AppTy t1 t2) = maybeParen p TyConPrec $
ppr_type FunPrec t1 <+> ppr_type TyConPrec t2
ppr_type p fun_ty@(FunTy ty1 ty2)
| isPredTy ty1
= ppr_forall_type p fun_ty
| otherwise
= pprArrowChain p (ppr_type FunPrec ty1 : ppr_fun_tail ty2)
where
-- We don't want to lose synonyms, so we mustn't use splitFunTys here.
ppr_fun_tail (FunTy ty1 ty2)
| not (isPredTy ty1) = ppr_type FunPrec ty1 : ppr_fun_tail ty2
ppr_fun_tail other_ty = [ppr_type TopPrec other_ty]
ppr_forall_type :: TyPrec -> Type -> SDoc
ppr_forall_type p ty
= maybeParen p FunPrec $ ppr_sigma_type True False ty
-- True <=> we always print the foralls on *nested* quantifiers
-- Opt_PrintExplicitForalls only affects top-level quantifiers
-- False <=> we don't print an extra-constraints wildcard
ppr_tvar :: TyVar -> SDoc
ppr_tvar tv -- Note [Infix type variables]
= parenSymOcc (getOccName tv) (ppr tv)
ppr_tylit :: TyPrec -> TyLit -> SDoc
ppr_tylit _ tl =
case tl of
NumTyLit n -> integer n
StrTyLit s -> text (show s)
-------------------
ppr_sigma_type :: Bool -> Bool -> Type -> SDoc
-- First Bool <=> Show the foralls unconditionally
-- Second Bool <=> Show an extra-constraints wildcard
ppr_sigma_type show_foralls_unconditionally extra_cts ty
= sep [ if show_foralls_unconditionally
then pprForAll tvs
else pprUserForAll tvs
, if extra_cts
then pprThetaArrowTyExtra ctxt
else pprThetaArrowTy ctxt
, pprType tau ]
where
(tvs, rho) = split1 [] ty
(ctxt, tau) = split2 [] rho
split1 tvs (ForAllTy tv ty) = split1 (tv:tvs) ty
split1 tvs ty = (reverse tvs, ty)
split2 ps (ty1 `FunTy` ty2) | isPredTy ty1 = split2 (ty1:ps) ty2
split2 ps ty = (reverse ps, ty)
pprSigmaType :: Type -> SDoc
pprSigmaType ty = ppr_sigma_type False False ty
pprSigmaTypeExtraCts :: Bool -> Type -> SDoc
pprSigmaTypeExtraCts = ppr_sigma_type False
pprUserForAll :: [TyVar] -> SDoc
-- Print a user-level forall; see Note [WHen to print foralls]
pprUserForAll tvs
= sdocWithDynFlags $ \dflags ->
ppWhen (any tv_has_kind_var tvs || gopt Opt_PrintExplicitForalls dflags) $
pprForAll tvs
where
tv_has_kind_var tv = not (isEmptyVarSet (tyVarsOfType (tyVarKind tv)))
pprForAll :: [TyVar] -> SDoc
pprForAll [] = empty
pprForAll tvs = forAllLit <+> pprTvBndrs tvs <> dot
pprTvBndrs :: [TyVar] -> SDoc
pprTvBndrs tvs = sep (map pprTvBndr tvs)
pprTvBndr :: TyVar -> SDoc
pprTvBndr tv
| isLiftedTypeKind kind = ppr_tvar tv
| otherwise = parens (ppr_tvar tv <+> dcolon <+> pprKind kind)
where
kind = tyVarKind tv
{-
Note [When to print foralls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mostly we want to print top-level foralls when (and only when) the user specifies
-fprint-explicit-foralls. But when kind polymorphism is at work, that suppresses
too much information; see Trac #9018.
So I'm trying out this rule: print explicit foralls if
a) User specifies -fprint-explicit-foralls, or
b) Any of the quantified type variables has a kind
that mentions a kind variable
This catches common situations, such as a type siguature
f :: m a
which means
f :: forall k. forall (m :: k->*) (a :: k). m a
We really want to see both the "forall k" and the kind signatures
on m and a. The latter comes from pprTvBndr.
Note [Infix type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
With TypeOperators you can say
f :: (a ~> b) -> b
and the (~>) is considered a type variable. However, the type
pretty-printer in this module will just see (a ~> b) as
App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b")
So it'll print the type in prefix form. To avoid confusion we must
remember to parenthesise the operator, thus
(~>) a b -> b
See Trac #2766.
-}
pprTypeApp :: TyCon -> [Type] -> SDoc
pprTypeApp tc tys = pprTyTcApp TopPrec tc tys
-- We have to use ppr on the TyCon (not its name)
-- so that we get promotion quotes in the right place
pprTyTcApp :: TyPrec -> TyCon -> [Type] -> SDoc
-- Used for types only; so that we can make a
-- special case for type-level lists
pprTyTcApp p tc tys
| tc `hasKey` ipClassNameKey
, [LitTy (StrTyLit n),ty] <- tys
= maybeParen p FunPrec $
char '?' <> ftext n <> ptext (sLit "::") <> ppr_type TopPrec ty
| tc `hasKey` consDataConKey
, [_kind,ty1,ty2] <- tys
= sdocWithDynFlags $ \dflags ->
if gopt Opt_PrintExplicitKinds dflags then pprTcApp p ppr_type tc tys
else pprTyList p ty1 ty2
| otherwise
= pprTcApp p ppr_type tc tys
pprTcApp :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> SDoc
-- Used for both types and coercions, hence polymorphism
pprTcApp _ pp tc [ty]
| tc `hasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty)
| tc `hasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty)
pprTcApp p pp tc tys
| isTupleTyCon tc && tyConArity tc == length tys
= pprTupleApp p pp tc tys
| Just dc <- isPromotedDataCon_maybe tc
, let dc_tc = dataConTyCon dc
, isTupleTyCon dc_tc
, let arity = tyConArity dc_tc -- E.g. 3 for (,,) k1 k2 k3 t1 t2 t3
ty_args = drop arity tys -- Drop the kind args
, ty_args `lengthIs` arity -- Result is saturated
= pprPromotionQuote tc <>
(tupleParens (tupleTyConSort dc_tc) $
sep (punctuate comma (map (pp TopPrec) ty_args)))
| otherwise
= sdocWithDynFlags (pprTcApp_help p pp tc tys)
pprTupleApp :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> SDoc
-- Print a saturated tuple
pprTupleApp p pp tc tys
| null tys
, ConstraintTuple <- tupleTyConSort tc
= maybeParen p TopPrec $
ppr tc <+> dcolon <+> ppr (tyConKind tc)
| otherwise
= pprPromotionQuote tc <>
tupleParens (tupleTyConSort tc) (sep (punctuate comma (map (pp TopPrec) tys)))
pprTcApp_help :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> DynFlags -> SDoc
-- This one has accss to the DynFlags
pprTcApp_help p pp tc tys dflags
| not (isSymOcc (nameOccName (tyConName tc)))
= pprPrefixApp p (ppr tc) (map (pp TyConPrec) tys_wo_kinds)
| [ty1,ty2] <- tys_wo_kinds -- Infix, two arguments;
-- we know nothing of precedence though
= pprInfixApp p pp (ppr tc) ty1 ty2
| tc `hasKey` liftedTypeKindTyConKey
|| tc `hasKey` unliftedTypeKindTyConKey
= ASSERT( null tys ) ppr tc -- Do not wrap *, # in parens
| otherwise
= pprPrefixApp p (parens (ppr tc)) (map (pp TyConPrec) tys_wo_kinds)
where
tys_wo_kinds = suppressKinds dflags (tyConKind tc) tys
------------------
suppressKinds :: DynFlags -> Kind -> [a] -> [a]
-- Given the kind of a TyCon, and the args to which it is applied,
-- suppress the args that are kind args
-- C.f. Note [Suppressing kinds] in IfaceType
suppressKinds dflags kind xs
| gopt Opt_PrintExplicitKinds dflags = xs
| otherwise = suppress kind xs
where
suppress (ForAllTy _ kind) (_ : xs) = suppress kind xs
suppress (FunTy _ res) (x:xs) = x : suppress res xs
suppress _ xs = xs
----------------
pprTyList :: TyPrec -> Type -> Type -> SDoc
-- Given a type-level list (t1 ': t2), see if we can print
-- it in list notation [t1, ...].
pprTyList p ty1 ty2
= case gather ty2 of
(arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma
(map (ppr_type TopPrec) (ty1:arg_tys))))
(arg_tys, Just tl) -> maybeParen p FunPrec $
hang (ppr_type FunPrec ty1)
2 (fsep [ colon <+> ppr_type FunPrec ty | ty <- arg_tys ++ [tl]])
where
gather :: Type -> ([Type], Maybe Type)
-- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn]
-- = (tys, Just tl) means ty is of form t1:t2:...tn:tl
gather (TyConApp tc tys)
| tc `hasKey` consDataConKey
, [_kind, ty1,ty2] <- tys
, (args, tl) <- gather ty2
= (ty1:args, tl)
| tc `hasKey` nilDataConKey
= ([], Nothing)
gather ty = ([], Just ty)
----------------
pprInfixApp :: TyPrec -> (TyPrec -> a -> SDoc) -> SDoc -> a -> a -> SDoc
pprInfixApp p pp pp_tc ty1 ty2
= maybeParen p TyOpPrec $
sep [pp TyOpPrec ty1, pprInfixVar True pp_tc <+> pp TyOpPrec ty2]
pprPrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc
pprPrefixApp p pp_fun pp_tys
| null pp_tys = pp_fun
| otherwise = maybeParen p TyConPrec $
hang pp_fun 2 (sep pp_tys)
----------------
pprArrowChain :: TyPrec -> [SDoc] -> SDoc
-- pprArrowChain p [a,b,c] generates a -> b -> c
pprArrowChain _ [] = empty
pprArrowChain p (arg:args) = maybeParen p FunPrec $
sep [arg, sep (map (arrow <+>) args)]
{-
************************************************************************
* *
\subsection{TidyType}
* *
************************************************************************
Tidying is here because it has a special case for FlatSkol
-}
-- | This tidies up a type for printing in an error message, or in
-- an interface file.
--
-- It doesn't change the uniques at all, just the print names.
tidyTyVarBndrs :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyTyVarBndrs env tvs = mapAccumL tidyTyVarBndr env tvs
tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidyTyVarBndr tidy_env@(occ_env, subst) tyvar
= case tidyOccName occ_env occ1 of
(tidy', occ') -> ((tidy', subst'), tyvar')
where
subst' = extendVarEnv subst tyvar tyvar'
tyvar' = setTyVarKind (setTyVarName tyvar name') kind'
name' = tidyNameOcc name occ'
kind' = tidyKind tidy_env (tyVarKind tyvar)
where
name = tyVarName tyvar
occ = getOccName name
-- System Names are for unification variables;
-- when we tidy them we give them a trailing "0" (or 1 etc)
-- so that they don't take precedence for the un-modified name
-- Plus, indicating a unification variable in this way is a
-- helpful clue for users
occ1 | isSystemName name = mkTyVarOcc (occNameString occ ++ "0")
| otherwise = occ
---------------
tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
-- ^ Add the free 'TyVar's to the env in tidy form,
-- so that we can tidy the type they are free in
tidyFreeTyVars (full_occ_env, var_env) tyvars
= fst (tidyOpenTyVars (full_occ_env, var_env) (varSetElems tyvars))
---------------
tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
---------------
tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
-- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
-- using the environment if one has not already been allocated. See
-- also 'tidyTyVarBndr'
tidyOpenTyVar env@(_, subst) tyvar
= case lookupVarEnv subst tyvar of
Just tyvar' -> (env, tyvar') -- Already substituted
Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
---------------
tidyTyVarOcc :: TidyEnv -> TyVar -> TyVar
tidyTyVarOcc (_, subst) tv
= case lookupVarEnv subst tv of
Nothing -> tv
Just tv' -> tv'
---------------
tidyTypes :: TidyEnv -> [Type] -> [Type]
tidyTypes env tys = map (tidyType env) tys
---------------
tidyType :: TidyEnv -> Type -> Type
tidyType _ (LitTy n) = LitTy n
tidyType env (TyVarTy tv) = TyVarTy (tidyTyVarOcc env tv)
tidyType env (TyConApp tycon tys) = let args = tidyTypes env tys
in args `seqList` TyConApp tycon args
tidyType env (AppTy fun arg) = (AppTy $! (tidyType env fun)) $! (tidyType env arg)
tidyType env (FunTy fun arg) = (FunTy $! (tidyType env fun)) $! (tidyType env arg)
tidyType env (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
where
(envp, tvp) = tidyTyVarBndr env tv
---------------
-- | Grabs the free type variables, tidies them
-- and then uses 'tidyType' to work over the type itself
tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
tidyOpenType env ty
= (env', tidyType (trimmed_occ_env, var_env) ty)
where
(env'@(_, var_env), tvs') = tidyOpenTyVars env (varSetElems (tyVarsOfType ty))
trimmed_occ_env = initTidyOccEnv (map getOccName tvs')
-- The idea here was that we restrict the new TidyEnv to the
-- _free_ vars of the type, so that we don't gratuitously rename
-- the _bound_ variables of the type.
---------------
tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
---------------
-- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
tidyTopType :: Type -> Type
tidyTopType ty = tidyType emptyTidyEnv ty
---------------
tidyOpenKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
tidyOpenKind = tidyOpenType
tidyKind :: TidyEnv -> Kind -> Kind
tidyKind = tidyType
| alexander-at-github/eta | compiler/ETA/Types/TypeRep.hs | bsd-3-clause | 33,572 | 0 | 17 | 8,963 | 5,429 | 2,922 | 2,507 | 371 | 5 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-----------------------------------------------------------------
-- Autogenerated by Thrift
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
-- @generated
-----------------------------------------------------------------
module My.Namespacing.Extend.Test.ExtendTestService_Fuzzer (main) where
import qualified My.Namespacing.Extend.Test.Extend_Types
import qualified My.Namespacing.Extend.Test.ExtendTestService_Client as Client
import qualified My.Namespacing.Test.Hsmodule_Types
import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..),
Eq, Show, Ord,
concat, error, fromIntegral, fromEnum, length, map,
maybe, not, null, otherwise, return, show, toEnum,
enumFromTo, Bounded, minBound, maxBound, seq, succ,
pred, enumFrom, enumFromThen, enumFromThenTo,
(.), (&&), (||), (==), (++), ($), (-), (>>=), (>>))
import qualified Control.Applicative as Applicative (ZipList(..))
import Control.Applicative ( (<*>) )
import qualified Control.DeepSeq as DeepSeq
import qualified Control.Exception as Exception
import qualified Control.Monad as Monad ( liftM, ap, when )
import qualified Data.ByteString.Lazy as BS
import Data.Functor ( (<$>) )
import qualified Data.Hashable as Hashable
import qualified Data.Int as Int
import Data.List
import qualified Data.Maybe as Maybe (catMaybes)
import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 )
import qualified Data.Text.Lazy as LT
import qualified Data.Typeable as Typeable ( Typeable )
import qualified Data.HashMap.Strict as Map
import qualified Data.HashSet as Set
import qualified Data.Vector as Vector
import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) )
import qualified Test.QuickCheck as QuickCheck ( elements )
import qualified Thrift
import qualified Thrift.Types as Types
import qualified Thrift.Serializable as Serializable
import qualified Thrift.Arbitraries as Arbitraries
import qualified My.Namespacing.Test.Hsmodule_Types as Hsmodule_Types
import Prelude ((>>), print)
import qualified Prelude as P
import Control.Monad (forM)
import qualified Data.List as L
import Data.Maybe (fromJust)
import qualified Data.Map as Map
import GHC.Int (Int64, Int32)
import Data.ByteString.Lazy (ByteString)
import System.Environment (getArgs)
import Test.QuickCheck (arbitrary)
import Test.QuickCheck.Gen (Gen(..))
import Thrift.FuzzerSupport
handleOptions :: ([Options -> Options], [String], [String]) -> Options
handleOptions (transformers, (serviceName:[]), []) | serviceName `P.elem` serviceNames
= (P.foldl (P.flip ($)) defaultOptions transformers) { opt_service = serviceName }
handleOptions (_, (serviceName:[]), []) | P.otherwise
= P.error $ usage ++ "\nUnknown serviceName " ++ serviceName ++ ", should be one of " ++ (P.show serviceNames)
handleOptions (_, [], _) = P.error $ usage ++ "\nMissing mandatory serviceName to fuzz."
handleOptions (_, _a, []) = P.error $ usage ++ "\nToo many serviceNames, pick one."
handleOptions (_, _, e) = P.error $ usage ++ (P.show e)
main :: IO ()
main = do
args <- getArgs
let config = handleOptions (getOptions args)
fuzz config
selectFuzzer :: Options -> (Options -> IO ())
selectFuzzer (Options _host _port service _timeout _framed _verbose)
= fromJust $ P.lookup service fuzzerFunctions
fuzz :: Options -> IO ()
fuzz config = (selectFuzzer config) config
-- Dynamic content
-- Configuration via command-line parsing
serviceNames :: [String]
serviceNames = ["check"]
fuzzerFunctions :: [(String, (Options -> IO ()))]
fuzzerFunctions = [("check", check_fuzzer)]
-- Random data generation
inf_Hsmodule_Types_HsFoo :: IO [Hsmodule_Types.HsFoo]
inf_Hsmodule_Types_HsFoo = infexamples (Arbitrary.arbitrary :: Gen Hsmodule_Types.HsFoo)
-- Fuzzers and exception handlers
check_fuzzer :: Options -> IO ()
check_fuzzer opts = do
a1 <- Applicative.ZipList <$> inf_Hsmodule_Types_HsFoo
_ <- forM (Applicative.getZipList a1) check_fuzzFunc
return ()
where
check_fuzzFunc a1 = let param = (a1) in
if opt_framed opts
then withThriftDo opts (withFramedTransport opts) (check_fuzzOnce param) (check_exceptionHandler param)
else withThriftDo opts (withHandle opts) (check_fuzzOnce param) (check_exceptionHandler param)
check_exceptionHandler :: (Show a1) => (a1) -> IO ()
check_exceptionHandler (a1) = do
P.putStrLn $ "Got exception on data:"
P.putStrLn $ "(" ++ show a1 ++ ")"
check_fuzzOnce (a1) client = Client.check client a1 >> return ()
| LinusU/fbthrift | thrift/compiler/test/fixtures/namespace/gen-hs/My/Namespacing/Extend/Test/ExtendTestService_Fuzzer.hs | apache-2.0 | 4,936 | 0 | 12 | 806 | 1,320 | 801 | 519 | 92 | 2 |
f a (x:xs) b = x + a + b : f a xs b ; f a [] b = [] | mpickering/hlint-refactor | tests/examples/ListRec3.hs | bsd-3-clause | 51 | 0 | 7 | 21 | 56 | 28 | 28 | 1 | 1 |
--
-- Copyright (c) 2011 Citrix Systems, Inc.
--
-- 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 2 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, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
{-# LANGUAGE PatternGuards #-}
module Migrations.M_5 (migration) where
import UpgradeEngine
import Data.List (foldl')
--
-- BRIAN
--
migration = Migration {
sourceVersion = 5
, targetVersion = 6
, actions = act
}
act :: IO ()
act = do
xformPrimaryJSON $ jsSet "/display-driver-whitelist" (jsBoxString "vga,citrix,intel,RDP,netmeeting")
v4vRules
v4vRules = xformVmJSON xform where
xform tree
| Just t <- typ, t `elem` ["pvm","svm"] = add_rules tree
| otherwise = tree
where
typ = jsUnboxString `fmap` (jsGet "/type" tree)
add_rules tree = foldl' (\t (p,v) -> jsSet p (jsBoxString v) t) tree rules
rules = [ ("/v4v-firewall-rules/0", "myself -> 0:4346709")
, ("/v4v-firewall-rules/1", "myself -> 0:80")
, ("/v4v-firewall-rules/2", "myself:14494 -> 0:4494")
, ("/v4v-firewall-rules/3", "appviewer -> myself:100")
, ("/v4v-firewall-rules/4", "appviewer:11494 -> myself:1494")
]
| jean-edouard/manager | upgrade-db/Migrations/M_5.hs | gpl-2.0 | 1,839 | 0 | 12 | 458 | 280 | 166 | 114 | 23 | 1 |
{-# LANGUAGE TemplateHaskell #-}
{-| The implementation of Ganeti WConfd daemon server.
As TemplateHaskell require that splices be defined in a separate
module, we combine all the TemplateHaskell functionality that HTools
needs in this module (except the one for unittests).
-}
{-
Copyright (C) 2013, 2014 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.WConfd.Server where
import Control.Concurrent (forkIO)
import Control.Exception
import Control.Monad
import Control.Monad.Error
import Ganeti.BasicTypes
import qualified Ganeti.Constants as C
import Ganeti.Daemon
import Ganeti.Daemon.Utils (handleMasterVerificationOptions)
import Ganeti.Logging (logDebug)
import qualified Ganeti.Path as Path
import Ganeti.THH.RPC
import Ganeti.UDSServer
import Ganeti.Errors (formatError)
import Ganeti.Runtime
import Ganeti.Utils
import Ganeti.Utils.Livelock (mkLivelockFile)
import Ganeti.WConfd.ConfigState
import Ganeti.WConfd.ConfigVerify
import Ganeti.WConfd.ConfigWriter
import Ganeti.WConfd.Core
import Ganeti.WConfd.DeathDetection (cleanupLocksTask)
import Ganeti.WConfd.Monad
import Ganeti.WConfd.Persistent
handler :: DaemonHandle -> RpcServer WConfdMonadInt
handler _ = $( mkRpcM exportedFunctions )
-- | Type alias for prepMain results
type PrepResult = (Server, DaemonHandle)
-- | Check function for luxid.
checkMain :: CheckFn ()
checkMain = handleMasterVerificationOptions
-- | Prepare function for luxid.
prepMain :: PrepFn () PrepResult
prepMain _ _ = do
socket_path <- Path.defaultWConfdSocket
cleanupSocket socket_path
s <- describeError "binding to the socket" Nothing (Just socket_path)
$ connectServer serverConfig True socket_path
-- TODO: Lock the configuration file so that running the daemon twice fails?
conf_file <- Path.clusterConfFile
dh <- toErrorBase
. withErrorT (strMsg . ("Initialization of the daemon failed" ++)
. formatError) $ do
ents <- getEnts
(cdata, cstat) <- loadConfigFromFile conf_file
verifyConfigErr cdata
lock <- readPersistent persistentLocks
tempres <- readPersistent persistentTempRes
(_, livelock) <- mkLivelockFile C.wconfLivelockPrefix
mkDaemonHandle conf_file
(mkConfigState cdata)
lock
tempres
(saveConfigAsyncTask conf_file cstat)
(distMCsAsyncTask ents conf_file)
distSSConfAsyncTask
(writePersistentAsyncTask persistentLocks)
(writePersistentAsyncTask persistentTempRes)
livelock
return (s, dh)
serverConfig :: ServerConfig
serverConfig = ServerConfig
-- All the daemons that need to talk to WConfd should be
-- running as the same user - the former master daemon user.
FilePermissions { fpOwner = Just GanetiWConfd
, fpGroup = Just $ ExtraGroup DaemonsGroup
, fpPermissions = 0o0600
}
ConnectConfig { recvTmo = 60
, sendTmo = 60
}
-- | Main function.
main :: MainFn () PrepResult
main _ _ (server, dh) = do
logDebug "Starting the cleanup task"
_ <- forkIO $ runWConfdMonadInt cleanupLocksTask dh
finally
(forever $ runWConfdMonadInt (listener (handler dh) server) dh)
(liftIO $ closeServer server)
-- | Options list and functions.
options :: [OptType]
options =
[ oNoDaemonize
, oNoUserChecks
, oDebug
, oSyslogUsage
, oForceNode
, oNoVoting
, oYesDoIt
]
| mbakke/ganeti | src/Ganeti/WConfd/Server.hs | bsd-2-clause | 4,886 | 0 | 14 | 1,118 | 670 | 367 | 303 | 80 | 1 |
{-
(c) The University of Glasgow 2006
(c) The AQUA Project, Glasgow University, 1996-1998
Printing of Core syntax
-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module PprCore (
pprCoreExpr, pprParendExpr,
pprCoreBinding, pprCoreBindings, pprCoreAlt,
pprCoreBindingWithSize, pprCoreBindingsWithSize,
pprRules
) where
import CoreSyn
import CoreStats (exprStats)
import Literal( pprLiteral )
import Name( pprInfixName, pprPrefixName )
import Var
import Id
import IdInfo
import Demand
import DataCon
import TyCon
import Type
import Coercion
import DynFlags
import BasicTypes
import Util
import Outputable
import FastString
import SrcLoc ( pprUserRealSpan )
{-
************************************************************************
* *
\subsection{Public interfaces for Core printing (excluding instances)}
* *
************************************************************************
@pprParendCoreExpr@ puts parens around non-atomic Core expressions.
-}
pprCoreBindings :: OutputableBndr b => [Bind b] -> SDoc
pprCoreBinding :: OutputableBndr b => Bind b -> SDoc
pprCoreExpr :: OutputableBndr b => Expr b -> SDoc
pprParendExpr :: OutputableBndr b => Expr b -> SDoc
pprCoreBindings = pprTopBinds noAnn
pprCoreBinding = pprTopBind noAnn
pprCoreBindingsWithSize :: [CoreBind] -> SDoc
pprCoreBindingWithSize :: CoreBind -> SDoc
pprCoreBindingsWithSize = pprTopBinds sizeAnn
pprCoreBindingWithSize = pprTopBind sizeAnn
instance OutputableBndr b => Outputable (Bind b) where
ppr bind = ppr_bind noAnn bind
instance OutputableBndr b => Outputable (Expr b) where
ppr expr = pprCoreExpr expr
{-
************************************************************************
* *
\subsection{The guts}
* *
************************************************************************
-}
-- | A function to produce an annotation for a given right-hand-side
type Annotation b = Expr b -> SDoc
-- | Annotate with the size of the right-hand-side
sizeAnn :: CoreExpr -> SDoc
sizeAnn e = ptext (sLit "-- RHS size:") <+> ppr (exprStats e)
-- | No annotation
noAnn :: Expr b -> SDoc
noAnn _ = empty
pprTopBinds :: OutputableBndr a
=> Annotation a -- ^ generate an annotation to place before the
-- binding
-> [Bind a] -- ^ bindings to show
-> SDoc -- ^ the pretty result
pprTopBinds ann binds = vcat (map (pprTopBind ann) binds)
pprTopBind :: OutputableBndr a => Annotation a -> Bind a -> SDoc
pprTopBind ann (NonRec binder expr)
= ppr_binding ann (binder,expr) $$ blankLine
pprTopBind _ (Rec [])
= ptext (sLit "Rec { }")
pprTopBind ann (Rec (b:bs))
= vcat [ptext (sLit "Rec {"),
ppr_binding ann b,
vcat [blankLine $$ ppr_binding ann b | b <- bs],
ptext (sLit "end Rec }"),
blankLine]
ppr_bind :: OutputableBndr b => Annotation b -> Bind b -> SDoc
ppr_bind ann (NonRec val_bdr expr) = ppr_binding ann (val_bdr, expr)
ppr_bind ann (Rec binds) = vcat (map pp binds)
where
pp bind = ppr_binding ann bind <> semi
ppr_binding :: OutputableBndr b => Annotation b -> (b, Expr b) -> SDoc
ppr_binding ann (val_bdr, expr)
= ann expr $$ pprBndr LetBind val_bdr $$
hang (ppr val_bdr <+> equals) 2 (pprCoreExpr expr)
pprParendExpr expr = ppr_expr parens expr
pprCoreExpr expr = ppr_expr noParens expr
noParens :: SDoc -> SDoc
noParens pp = pp
pprOptCo :: Coercion -> SDoc
pprOptCo co = sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressCoercions dflags
then ptext (sLit "...")
else parens (sep [ppr co, dcolon <+> ppr (coercionType co)])
ppr_expr :: OutputableBndr b => (SDoc -> SDoc) -> Expr b -> SDoc
-- The function adds parens in context that need
-- an atomic value (e.g. function args)
ppr_expr _ (Var name) = ppr name
ppr_expr add_par (Type ty) = add_par (ptext (sLit "TYPE") <+> ppr ty) -- Weird
ppr_expr add_par (Coercion co) = add_par (ptext (sLit "CO") <+> ppr co)
ppr_expr add_par (Lit lit) = pprLiteral add_par lit
ppr_expr add_par (Cast expr co)
= add_par $ sep [pprParendExpr expr, ptext (sLit "`cast`") <+> pprOptCo co]
ppr_expr add_par expr@(Lam _ _)
= let
(bndrs, body) = collectBinders expr
in
add_par $
hang (ptext (sLit "\\") <+> sep (map (pprBndr LambdaBind) bndrs) <+> arrow)
2 (pprCoreExpr body)
ppr_expr add_par expr@(App {})
= case collectArgs expr of { (fun, args) ->
let
pp_args = sep (map pprArg args)
val_args = dropWhile isTypeArg args -- Drop the type arguments for tuples
pp_tup_args = pprWithCommas pprCoreExpr val_args
in
case fun of
Var f -> case isDataConWorkId_maybe f of
-- Notice that we print the *worker*
-- for tuples in paren'd format.
Just dc | saturated
, Just sort <- tyConTuple_maybe tc
-> tupleParens sort pp_tup_args
where
tc = dataConTyCon dc
saturated = val_args `lengthIs` idArity f
_ -> add_par (hang (ppr f) 2 pp_args)
_ -> add_par (hang (pprParendExpr fun) 2 pp_args)
}
ppr_expr add_par (Case expr var ty [(con,args,rhs)])
= sdocWithDynFlags $ \dflags ->
if gopt Opt_PprCaseAsLet dflags
then add_par $ -- See Note [Print case as let]
sep [ sep [ ptext (sLit "let! {")
<+> ppr_case_pat con args
<+> ptext (sLit "~")
<+> ppr_bndr var
, ptext (sLit "<-") <+> ppr_expr id expr
<+> ptext (sLit "} in") ]
, pprCoreExpr rhs
]
else add_par $
sep [sep [ptext (sLit "case") <+> pprCoreExpr expr,
ifPprDebug (braces (ppr ty)),
sep [ptext (sLit "of") <+> ppr_bndr var,
char '{' <+> ppr_case_pat con args <+> arrow]
],
pprCoreExpr rhs,
char '}'
]
where
ppr_bndr = pprBndr CaseBind
ppr_expr add_par (Case expr var ty alts)
= add_par $
sep [sep [ptext (sLit "case")
<+> pprCoreExpr expr
<+> ifPprDebug (braces (ppr ty)),
ptext (sLit "of") <+> ppr_bndr var <+> char '{'],
nest 2 (vcat (punctuate semi (map pprCoreAlt alts))),
char '}'
]
where
ppr_bndr = pprBndr CaseBind
-- special cases: let ... in let ...
-- ("disgusting" SLPJ)
{-
ppr_expr add_par (Let bind@(NonRec val_bdr rhs@(Let _ _)) body)
= add_par $
vcat [
hsep [ptext (sLit "let {"), (pprBndr LetBind val_bdr $$ ppr val_bndr), equals],
nest 2 (pprCoreExpr rhs),
ptext (sLit "} in"),
pprCoreExpr body ]
ppr_expr add_par (Let bind@(NonRec val_bdr rhs) expr@(Let _ _))
= add_par
(hang (ptext (sLit "let {"))
2 (hsep [ppr_binding (val_bdr,rhs),
ptext (sLit "} in")])
$$
pprCoreExpr expr)
-}
-- General case (recursive case, too)
ppr_expr add_par (Let bind expr)
= add_par $
sep [hang (ptext keyword) 2 (ppr_bind noAnn bind <+> ptext (sLit "} in")),
pprCoreExpr expr]
where
keyword = case bind of
Rec _ -> (sLit "letrec {")
NonRec _ _ -> (sLit "let {")
ppr_expr add_par (Tick tickish expr)
= sdocWithDynFlags $ \dflags ->
if gopt Opt_PprShowTicks dflags
then add_par (sep [ppr tickish, pprCoreExpr expr])
else ppr_expr add_par expr
pprCoreAlt :: OutputableBndr a => (AltCon, [a] , Expr a) -> SDoc
pprCoreAlt (con, args, rhs)
= hang (ppr_case_pat con args <+> arrow) 2 (pprCoreExpr rhs)
ppr_case_pat :: OutputableBndr a => AltCon -> [a] -> SDoc
ppr_case_pat (DataAlt dc) args
| Just sort <- tyConTuple_maybe tc
= tupleParens sort (pprWithCommas ppr_bndr args)
where
ppr_bndr = pprBndr CaseBind
tc = dataConTyCon dc
ppr_case_pat con args
= ppr con <+> (fsep (map ppr_bndr args))
where
ppr_bndr = pprBndr CaseBind
-- | Pretty print the argument in a function application.
pprArg :: OutputableBndr a => Expr a -> SDoc
pprArg (Type ty)
= sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressTypeApplications dflags
then empty
else ptext (sLit "@") <+> pprParendType ty
pprArg (Coercion co) = ptext (sLit "@~") <+> pprOptCo co
pprArg expr = pprParendExpr expr
{-
Note [Print case as let]
~~~~~~~~~~~~~~~~~~~~~~~~
Single-branch case expressions are very common:
case x of y { I# x' ->
case p of q { I# p' -> ... } }
These are, in effect, just strict let's, with pattern matching.
With -dppr-case-as-let we print them as such:
let! { I# x' ~ y <- x } in
let! { I# p' ~ q <- p } in ...
Other printing bits-and-bobs used with the general @pprCoreBinding@
and @pprCoreExpr@ functions.
-}
instance OutputableBndr Var where
pprBndr = pprCoreBinder
pprInfixOcc = pprInfixName . varName
pprPrefixOcc = pprPrefixName . varName
pprCoreBinder :: BindingSite -> Var -> SDoc
pprCoreBinder LetBind binder
| isTyVar binder = pprKindedTyVarBndr binder
| otherwise = pprTypedLetBinder binder $$
ppIdInfo binder (idInfo binder)
-- Lambda bound type variables are preceded by "@"
pprCoreBinder bind_site bndr
= getPprStyle $ \ sty ->
pprTypedLamBinder bind_site (debugStyle sty) bndr
pprUntypedBinder :: Var -> SDoc
pprUntypedBinder binder
| isTyVar binder = ptext (sLit "@") <+> ppr binder -- NB: don't print kind
| otherwise = pprIdBndr binder
pprTypedLamBinder :: BindingSite -> Bool -> Var -> SDoc
-- For lambda and case binders, show the unfolding info (usually none)
pprTypedLamBinder bind_site debug_on var
= sdocWithDynFlags $ \dflags ->
case () of
_
| not debug_on -- Even dead binders can be one-shot
, isDeadBinder var -> char '_' <+> ppWhen (isId var)
(pprIdBndrInfo (idInfo var))
| not debug_on -- No parens, no kind info
, CaseBind <- bind_site -> pprUntypedBinder var
| suppress_sigs dflags -> pprUntypedBinder var
| isTyVar var -> parens (pprKindedTyVarBndr var)
| otherwise -> parens (hang (pprIdBndr var)
2 (vcat [ dcolon <+> pprType (idType var)
, pp_unf]))
where
suppress_sigs = gopt Opt_SuppressTypeSignatures
unf_info = unfoldingInfo (idInfo var)
pp_unf | hasSomeUnfolding unf_info = ptext (sLit "Unf=") <> ppr unf_info
| otherwise = empty
pprTypedLetBinder :: Var -> SDoc
-- Print binder with a type or kind signature (not paren'd)
pprTypedLetBinder binder
= sdocWithDynFlags $ \dflags ->
case () of
_
| isTyVar binder -> pprKindedTyVarBndr binder
| gopt Opt_SuppressTypeSignatures dflags -> pprIdBndr binder
| otherwise -> hang (pprIdBndr binder) 2 (dcolon <+> pprType (idType binder))
pprKindedTyVarBndr :: TyVar -> SDoc
-- Print a type variable binder with its kind (but not if *)
pprKindedTyVarBndr tyvar
= ptext (sLit "@") <+> pprTvBndr tyvar
-- pprIdBndr does *not* print the type
-- When printing any Id binder in debug mode, we print its inline pragma and one-shot-ness
pprIdBndr :: Id -> SDoc
pprIdBndr id = ppr id <+> pprIdBndrInfo (idInfo id)
pprIdBndrInfo :: IdInfo -> SDoc
pprIdBndrInfo info
= sdocWithDynFlags $ \dflags ->
ppUnless (gopt Opt_SuppressIdInfo dflags) $
info `seq` doc -- The seq is useful for poking on black holes
where
prag_info = inlinePragInfo info
occ_info = occInfo info
dmd_info = demandInfo info
lbv_info = oneShotInfo info
has_prag = not (isDefaultInlinePragma prag_info)
has_occ = not (isNoOcc occ_info)
has_dmd = not $ isTopDmd dmd_info
has_lbv = not (hasNoOneShotInfo lbv_info)
doc = showAttributes
[ (has_prag, ptext (sLit "InlPrag=") <> ppr prag_info)
, (has_occ, ptext (sLit "Occ=") <> ppr occ_info)
, (has_dmd, ptext (sLit "Dmd=") <> ppr dmd_info)
, (has_lbv , ptext (sLit "OS=") <> ppr lbv_info)
]
{-
-----------------------------------------------------
-- IdDetails and IdInfo
-----------------------------------------------------
-}
ppIdInfo :: Id -> IdInfo -> SDoc
ppIdInfo id info
= sdocWithDynFlags $ \dflags ->
ppUnless (gopt Opt_SuppressIdInfo dflags) $
showAttributes
[ (True, pp_scope <> ppr (idDetails id))
, (has_arity, ptext (sLit "Arity=") <> int arity)
, (has_called_arity, ptext (sLit "CallArity=") <> int called_arity)
, (has_caf_info, ptext (sLit "Caf=") <> ppr caf_info)
, (True, ptext (sLit "Str=") <> pprStrictness str_info)
, (has_unf, ptext (sLit "Unf=") <> ppr unf_info)
, (not (null rules), ptext (sLit "RULES:") <+> vcat (map pprRule rules))
] -- Inline pragma, occ, demand, one-shot info
-- printed out with all binders (when debug is on);
-- see PprCore.pprIdBndr
where
pp_scope | isGlobalId id = ptext (sLit "GblId")
| isExportedId id = ptext (sLit "LclIdX")
| otherwise = ptext (sLit "LclId")
arity = arityInfo info
has_arity = arity /= 0
called_arity = callArityInfo info
has_called_arity = called_arity /= 0
caf_info = cafInfo info
has_caf_info = not (mayHaveCafRefs caf_info)
str_info = strictnessInfo info
unf_info = unfoldingInfo info
has_unf = hasSomeUnfolding unf_info
rules = specInfoRules (specInfo info)
showAttributes :: [(Bool,SDoc)] -> SDoc
showAttributes stuff
| null docs = empty
| otherwise = brackets (sep (punctuate comma docs))
where
docs = [d | (True,d) <- stuff]
{-
-----------------------------------------------------
-- Unfolding and UnfoldingGuidance
-----------------------------------------------------
-}
instance Outputable UnfoldingGuidance where
ppr UnfNever = ptext (sLit "NEVER")
ppr (UnfWhen { ug_arity = arity, ug_unsat_ok = unsat_ok, ug_boring_ok = boring_ok })
= ptext (sLit "ALWAYS_IF") <>
parens (ptext (sLit "arity=") <> int arity <> comma <>
ptext (sLit "unsat_ok=") <> ppr unsat_ok <> comma <>
ptext (sLit "boring_ok=") <> ppr boring_ok)
ppr (UnfIfGoodArgs { ug_args = cs, ug_size = size, ug_res = discount })
= hsep [ ptext (sLit "IF_ARGS"),
brackets (hsep (map int cs)),
int size,
int discount ]
instance Outputable UnfoldingSource where
ppr InlineCompulsory = ptext (sLit "Compulsory")
ppr InlineStable = ptext (sLit "InlineStable")
ppr InlineRhs = ptext (sLit "<vanilla>")
instance Outputable Unfolding where
ppr NoUnfolding = ptext (sLit "No unfolding")
ppr (OtherCon cs) = ptext (sLit "OtherCon") <+> ppr cs
ppr (DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = args })
= hang (ptext (sLit "DFun:") <+> ptext (sLit "\\")
<+> sep (map (pprBndr LambdaBind) bndrs) <+> arrow)
2 (ppr con <+> sep (map ppr args))
ppr (CoreUnfolding { uf_src = src
, uf_tmpl=rhs, uf_is_top=top, uf_is_value=hnf
, uf_is_conlike=conlike, uf_is_work_free=wf
, uf_expandable=exp, uf_guidance=g })
= ptext (sLit "Unf") <> braces (pp_info $$ pp_rhs)
where
pp_info = fsep $ punctuate comma
[ ptext (sLit "Src=") <> ppr src
, ptext (sLit "TopLvl=") <> ppr top
, ptext (sLit "Value=") <> ppr hnf
, ptext (sLit "ConLike=") <> ppr conlike
, ptext (sLit "WorkFree=") <> ppr wf
, ptext (sLit "Expandable=") <> ppr exp
, ptext (sLit "Guidance=") <> ppr g ]
pp_tmpl = sdocWithDynFlags $ \dflags ->
ppUnless (gopt Opt_SuppressUnfoldings dflags) $
ptext (sLit "Tmpl=") <+> ppr rhs
pp_rhs | isStableSource src = pp_tmpl
| otherwise = empty
-- Don't print the RHS or we get a quadratic
-- blowup in the size of the printout!
{-
-----------------------------------------------------
-- Rules
-----------------------------------------------------
-}
instance Outputable CoreRule where
ppr = pprRule
pprRules :: [CoreRule] -> SDoc
pprRules rules = vcat (map pprRule rules)
pprRule :: CoreRule -> SDoc
pprRule (BuiltinRule { ru_fn = fn, ru_name = name})
= ptext (sLit "Built in rule for") <+> ppr fn <> colon <+> doubleQuotes (ftext name)
pprRule (Rule { ru_name = name, ru_act = act, ru_fn = fn,
ru_bndrs = tpl_vars, ru_args = tpl_args,
ru_rhs = rhs })
= hang (doubleQuotes (ftext name) <+> ppr act)
4 (sep [ptext (sLit "forall") <+>
sep (map (pprCoreBinder LambdaBind) tpl_vars) <> dot,
nest 2 (ppr fn <+> sep (map pprArg tpl_args)),
nest 2 (ptext (sLit "=") <+> pprCoreExpr rhs)
])
{-
-----------------------------------------------------
-- Tickish
-----------------------------------------------------
-}
instance Outputable id => Outputable (Tickish id) where
ppr (HpcTick modl ix) =
hcat [ptext (sLit "hpc<"),
ppr modl, comma,
ppr ix,
ptext (sLit ">")]
ppr (Breakpoint ix vars) =
hcat [ptext (sLit "break<"),
ppr ix,
ptext (sLit ">"),
parens (hcat (punctuate comma (map ppr vars)))]
ppr (ProfNote { profNoteCC = cc,
profNoteCount = tick,
profNoteScope = scope }) =
case (tick,scope) of
(True,True) -> hcat [ptext (sLit "scctick<"), ppr cc, char '>']
(True,False) -> hcat [ptext (sLit "tick<"), ppr cc, char '>']
_ -> hcat [ptext (sLit "scc<"), ppr cc, char '>']
ppr (SourceNote span _) =
hcat [ ptext (sLit "src<"), pprUserRealSpan True span, char '>']
{-
-----------------------------------------------------
-- Vectorisation declarations
-----------------------------------------------------
-}
instance Outputable CoreVect where
ppr (Vect var e) = hang (ptext (sLit "VECTORISE") <+> ppr var <+> char '=')
4 (pprCoreExpr e)
ppr (NoVect var) = ptext (sLit "NOVECTORISE") <+> ppr var
ppr (VectType False var Nothing) = ptext (sLit "VECTORISE type") <+> ppr var
ppr (VectType True var Nothing) = ptext (sLit "VECTORISE SCALAR type") <+> ppr var
ppr (VectType False var (Just tc)) = ptext (sLit "VECTORISE type") <+> ppr var <+> char '=' <+>
ppr tc
ppr (VectType True var (Just tc)) = ptext (sLit "VECTORISE SCALAR type") <+> ppr var <+>
char '=' <+> ppr tc
ppr (VectClass tc) = ptext (sLit "VECTORISE class") <+> ppr tc
ppr (VectInst var) = ptext (sLit "VECTORISE SCALAR instance") <+> ppr var
| acowley/ghc | compiler/coreSyn/PprCore.hs | bsd-3-clause | 19,663 | 0 | 20 | 5,867 | 5,425 | 2,717 | 2,708 | 348 | 6 |
import qualified Data.Vector as U
import Data.Bits
main = print . U.sum $ unfoldU 10000 k (0::Int)
where
k b = JustS (b :*: b+1) -- enumFromTo
| dolio/vector | old-testsuite/microsuite/unfold.hs | bsd-3-clause | 155 | 0 | 10 | 39 | 67 | 37 | 30 | 4 | 1 |
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE OverloadedStrings #-} -- hah, the test should be renamed...
-- Not actually a problem, we're now requiring overloaded strings, we just need
-- to make the docs more explicit about it.
module YesodCoreTest.NoOverloadedStringsSub where
import Yesod.Core
import Network.Wai
import Yesod.Core.Types
data Subsite = Subsite (forall master. Yesod master => YesodSubRunnerEnv Subsite master (HandlerT master IO) -> Application)
mkYesodSubData "Subsite" [parseRoutes|
/bar BarR GET
/baz BazR GET
/bin BinR GET
/has-one-piece/#Int OnePiecesR GET
/has-two-pieces/#Int/#Int TwoPiecesR GET
/has-three-pieces/#Int/#Int/#Int ThreePiecesR GET
|]
instance Yesod master => YesodSubDispatch Subsite (HandlerT master IO) where
yesodSubDispatch ysre =
f ysre
where
Subsite f = ysreGetSub ysre $ yreSite $ ysreParentEnv ysre
| pikajude/yesod | yesod-core/test/YesodCoreTest/NoOverloadedStringsSub.hs | mit | 1,022 | 0 | 13 | 156 | 146 | 79 | 67 | 15 | 0 |
module CodeGen.Platform
(callerSaves, activeStgRegs, haveRegBase, globalRegMaybe, freeReg)
where
import CmmExpr
import Platform
import Reg
import qualified CodeGen.Platform.ARM as ARM
import qualified CodeGen.Platform.ARM64 as ARM64
import qualified CodeGen.Platform.PPC as PPC
import qualified CodeGen.Platform.PPC_Darwin as PPC_Darwin
import qualified CodeGen.Platform.SPARC as SPARC
import qualified CodeGen.Platform.X86 as X86
import qualified CodeGen.Platform.X86_64 as X86_64
import qualified CodeGen.Platform.NoRegs as NoRegs
-- | Returns 'True' if this global register is stored in a caller-saves
-- machine register.
callerSaves :: Platform -> GlobalReg -> Bool
callerSaves platform
| platformUnregisterised platform = NoRegs.callerSaves
| otherwise
= case platformArch platform of
ArchX86 -> X86.callerSaves
ArchX86_64 -> X86_64.callerSaves
ArchSPARC -> SPARC.callerSaves
ArchARM {} -> ARM.callerSaves
ArchARM64 -> ARM64.callerSaves
arch
| arch `elem` [ArchPPC, ArchPPC_64 ELF_V1, ArchPPC_64 ELF_V2] ->
case platformOS platform of
OSDarwin -> PPC_Darwin.callerSaves
_ -> PPC.callerSaves
| otherwise -> NoRegs.callerSaves
-- | Here is where the STG register map is defined for each target arch.
-- The order matters (for the llvm backend anyway)! We must make sure to
-- maintain the order here with the order used in the LLVM calling conventions.
-- Note that also, this isn't all registers, just the ones that are currently
-- possbily mapped to real registers.
activeStgRegs :: Platform -> [GlobalReg]
activeStgRegs platform
| platformUnregisterised platform = NoRegs.activeStgRegs
| otherwise
= case platformArch platform of
ArchX86 -> X86.activeStgRegs
ArchX86_64 -> X86_64.activeStgRegs
ArchSPARC -> SPARC.activeStgRegs
ArchARM {} -> ARM.activeStgRegs
ArchARM64 -> ARM64.activeStgRegs
arch
| arch `elem` [ArchPPC, ArchPPC_64 ELF_V1, ArchPPC_64 ELF_V2] ->
case platformOS platform of
OSDarwin -> PPC_Darwin.activeStgRegs
_ -> PPC.activeStgRegs
| otherwise -> NoRegs.activeStgRegs
haveRegBase :: Platform -> Bool
haveRegBase platform
| platformUnregisterised platform = NoRegs.haveRegBase
| otherwise
= case platformArch platform of
ArchX86 -> X86.haveRegBase
ArchX86_64 -> X86_64.haveRegBase
ArchSPARC -> SPARC.haveRegBase
ArchARM {} -> ARM.haveRegBase
ArchARM64 -> ARM64.haveRegBase
arch
| arch `elem` [ArchPPC, ArchPPC_64 ELF_V1, ArchPPC_64 ELF_V2] ->
case platformOS platform of
OSDarwin -> PPC_Darwin.haveRegBase
_ -> PPC.haveRegBase
| otherwise -> NoRegs.haveRegBase
globalRegMaybe :: Platform -> GlobalReg -> Maybe RealReg
globalRegMaybe platform
| platformUnregisterised platform = NoRegs.globalRegMaybe
| otherwise
= case platformArch platform of
ArchX86 -> X86.globalRegMaybe
ArchX86_64 -> X86_64.globalRegMaybe
ArchSPARC -> SPARC.globalRegMaybe
ArchARM {} -> ARM.globalRegMaybe
ArchARM64 -> ARM64.globalRegMaybe
arch
| arch `elem` [ArchPPC, ArchPPC_64 ELF_V1, ArchPPC_64 ELF_V2] ->
case platformOS platform of
OSDarwin -> PPC_Darwin.globalRegMaybe
_ -> PPC.globalRegMaybe
| otherwise -> NoRegs.globalRegMaybe
freeReg :: Platform -> RegNo -> Bool
freeReg platform
| platformUnregisterised platform = NoRegs.freeReg
| otherwise
= case platformArch platform of
ArchX86 -> X86.freeReg
ArchX86_64 -> X86_64.freeReg
ArchSPARC -> SPARC.freeReg
ArchARM {} -> ARM.freeReg
ArchARM64 -> ARM64.freeReg
arch
| arch `elem` [ArchPPC, ArchPPC_64 ELF_V1, ArchPPC_64 ELF_V2] ->
case platformOS platform of
OSDarwin -> PPC_Darwin.freeReg
_ -> PPC.freeReg
| otherwise -> NoRegs.freeReg
| acowley/ghc | compiler/codeGen/CodeGen/Platform.hs | bsd-3-clause | 3,868 | 0 | 14 | 813 | 904 | 468 | 436 | 93 | 7 |
{-# LANGUAGE GADTs, ExistentialQuantification #-}
module Escape where
data ExpGADT t where
ExpInt :: Int -> ExpGADT Int
data Hidden = forall t . Hidden (ExpGADT t) (ExpGADT t)
hval = Hidden (ExpInt 0) (ExpInt 1)
-- With the type sig this is ok, but without it maybe
-- should be rejected because the result type is wobbly
-- weird1 :: ExpGADT Int
--
-- And indeed it is rejected by GHC 7.8 because OutsideIn
-- doesn't unify under an equality constraint.
weird1 = case (hval :: Hidden) of Hidden (ExpInt _) a -> a
-- Hidden t (ExpInt (co :: t ~ Int) _ :: ExpGADT t) (a :: ExpGADT t)
weird2 :: ExpGADT Int
weird2 = case (hval :: Hidden) of Hidden (ExpInt _) a -> a
| forked-upstream-packages-for-ghcjs/ghc | testsuite/tests/gadt/gadt-escape1.hs | bsd-3-clause | 678 | 0 | 10 | 143 | 151 | 85 | 66 | 9 | 1 |
module JIT where
import Data.Int
import Data.Word
import Foreign.Ptr ( FunPtr, castFunPtr )
import Control.Monad.Except
import LLVM.General.Target
import LLVM.General.Context
import LLVM.General.CodeModel
import LLVM.General.Module as Mod
import qualified LLVM.General.AST as AST
import LLVM.General.PassManager
import LLVM.General.Transforms
import LLVM.General.Analysis
import qualified LLVM.General.ExecutionEngine as EE
foreign import ccall "dynamic" haskFun :: FunPtr (IO Double) -> (IO Double)
run :: FunPtr a -> IO Double
run fn = haskFun (castFunPtr fn :: FunPtr (IO Double))
jit :: Context -> (EE.MCJIT -> IO a) -> IO a
jit c = EE.withMCJIT c optlevel model ptrelim fastins
where
optlevel = Just 0 -- optimization level
model = Nothing -- code model ( Default )
ptrelim = Nothing -- frame pointer elimination
fastins = Nothing -- fast instruction selection
passes :: PassSetSpec
passes = defaultCuratedPassSetSpec { optLevel = Just 3 }
runJIT :: AST.Module -> IO (Either String AST.Module)
runJIT mod = do
withContext $ \context ->
jit context $ \executionEngine ->
runExceptT $ withModuleFromAST context mod $ \m ->
withPassManager passes $ \pm -> do
-- Optimization Pass
{-runPassManager pm m-}
optmod <- moduleAST m
s <- moduleLLVMAssembly m
putStrLn s
EE.withModuleInEngine executionEngine m $ \ee -> do
mainfn <- EE.getFunction ee (AST.Name "main")
case mainfn of
Just fn -> do
res <- run fn
putStrLn $ "Evaluated to: " ++ show res
Nothing -> return ()
-- Return the optimized module
return optmod | NoxHarmonium/lithium-lang | src/JIT.hs | mit | 1,731 | 0 | 27 | 446 | 482 | 255 | 227 | 42 | 2 |
{-|
Module : TestPrint
Description : The general Printing Test Functions
Copyright : (c) Andrew Burnett 2014-2015
Maintainer : andyburnett88@gmail.com
Stability : experimental
Portability : Unknown
This module provides the general functions required for writing Printing Tests
-}
module TestPrint (
printTest, -- :: (Printer a) => String -> a -> TestTree
TestTree, -- :: TestTree
testGroup, -- :: String -> [TestTree] -> TestTree
printList, -- :: (Printer a) => String -> [a] -> TestTree
defaultMain -- :: [TestTree] -> IO ()
) where
import Test.Tasty.HUnit
import Test.Tasty
import HSat.Printer
{-|
Takes a Printable element and prints it in all its forms
-}
printTest :: (Printer a) => String -> a -> TestTree
printTest str x =
testGroup str [
func "Compact" (compact x),
func "No Unicode" (noUnicode x),
func "Unicode" (unicode x)
]
where
func :: String -> Doc -> TestTree
func str' doc =
testCase str' $ do
putStrLn ""
putDoc doc
putStrLn ""
assertBool "" True
{-|
Takes a list of Printable elements and prints them all in all their forms
-}
printList :: (Printer a) => String -> [a] -> TestTree
printList str xs =
testGroup str $ map (printTest "") xs
| aburnett88/HSat | tests-src/TestPrint.hs | mit | 1,278 | 0 | 10 | 317 | 235 | 124 | 111 | 25 | 1 |
-- simple routines for generating and analyzing combinatorial maps
module Maps where
import Control.Monad.State
import Control.Monad.List
import Data.List
import Data.Maybe
import qualified Data.Tuple as DT
import Util
import Formulas
import Bijections
data OMap = OMap { odarts :: [Int], sigma :: Perm, alpha :: Perm }
deriving Show
data UMap = UMap { udarts :: [Int], x :: Perm, y :: Perm, z :: Perm }
deriving Show
mapOMap :: OMap -> (Int -> Int) -> OMap
mapOMap m f =
OMap { odarts = map f (odarts m),
sigma = map (\(x,y) -> (f x,f y)) (sigma m),
alpha = map (\(x,y) -> (f x,f y)) (alpha m) }
phiOM :: OMap -> Perm
phiOM m = comp (alpha m) (inv (sigma m))
cyclesOM :: OMap -> ([[Int]], [[Int]], [[Int]])
cyclesOM m = (permToCycles (sigma m), permToCycles (alpha m), permToCycles (phiOM m))
verticesOM :: OMap -> [[Int]]
verticesOM m = let (v,e,f) = cyclesOM m in v
edgesOM :: OMap -> [[Int]]
edgesOM m = let (v,e,f) = cyclesOM m in e
facesOM :: OMap -> [[Int]]
facesOM m = let (v,e,f) = cyclesOM m in f
eulerOM :: OMap -> Int
eulerOM m =
let (v,e,f) = (length $ permToCycles (sigma m), length $ permToCycles (alpha m), length $ permToCycles (phiOM m)) in
v-e+f
passportOM :: OMap -> ([Int],[Int],[Int])
passportOM m = passport (sigma m,alpha m,phiOM m)
-- compute the underlying abstract graph of an oriented map (ignore dangling edges)
graphOM :: OMap -> ([Int],[(Int,Int)])
graphOM m =
let vs = map head $ verticesOM m in
let vertexOf i = head $ intersect (orbit (act (sigma m)) i) vs in
(vs, map (\[i,j] -> (vertexOf i,vertexOf j)) (filter ((==2) . length) $ edgesOM m))
-- map dual = exchange vertices and faces
dualOM :: OMap -> OMap
dualOM m = OMap { odarts = odarts m, sigma = comp (inv (sigma m)) (alpha m), alpha = alpha m }
-- hypermap dual = exchange vertices and edges
dualHM :: OMap -> OMap
dualHM m = OMap { odarts = odarts m, sigma = alpha m, alpha = sigma m }
-- unification for unoriented maps (naive version)
naiveUnifyUM :: UMap -> UMap -> [Perm]
naiveUnifyUM m1 m2 =
filter (\p -> x m2 `eqperm` conjugate p (x m1) &&
y m2 `eqperm` conjugate p (y m1) &&
z m2 `eqperm` conjugate p (z m1))
[p | p <- inject (udarts m1) (udarts m2)]
-- unification for unoriented maps (less naive version)
fastUnifyUM :: UMap -> UMap -> [Perm]
fastUnifyUM m1 m2 =
-- first check that they have the same vertex and face passport
let (sigma1,phi1) = (comp (x m1) (y m1), comp (y m1) (z m1)) in
let (sigma2,phi2) = (comp (x m2) (y m2), comp (y m2) (z m2)) in
if clengths sigma1 /= clengths sigma2 ||
clengths phi1 /= clengths phi2 then [] else
-- then try to find a unifier
filter (\p -> x m2 `eqperm` conjugate p (x m1) && y m2 `eqperm` conjugate p (y m1) && z m2 `eqperm` conjugate p (z m1))
[p | p <- residual sigma1 sigma2]
-- unification for oriented maps
naiveUnifyOM :: OMap -> OMap -> [Perm]
naiveUnifyOM m1 m2 =
filter (\p -> sigma m2 `eqperm` conjugate p (sigma m1) &&
alpha m2 `eqperm` conjugate p (alpha m1))
[p | p <- inject (odarts m1) (odarts m2)]
fastUnifyOM :: OMap -> OMap -> [Perm]
fastUnifyOM m1 m2 =
let phi1 = phiOM m1 in
let phi2 = phiOM m2 in
-- first check that they have the same vertex and face passports
if clengths (sigma m1) /= clengths (sigma m2) ||
clengths phi1 /= clengths phi2 then [] else
-- then try to find a unifier
filter (\p -> sigma m2 `eqperm` conjugate p (sigma m1) &&
alpha m2 `eqperm` conjugate p (alpha m1))
[p | p <- residual phi1 phi2]
unifyOMat :: OMap -> OMap -> [(Int,Int)] -> [(Int,Int)] -> [(Int,Int)] -> Maybe [(Int,Int)]
unifyOMat m1 m2 [] [] matching = Just matching
unifyOMat m1 m2 ((d1,d2):remainv) remaine matching =
-- case (lookup d1 matching, lookup d2 (map DT.swap matching)) of
case (lookup d1 matching) of
-- (Just d2',Just d1') -> if d1 == d1' && d2 == d2' then unifyOMat m1 m2 remainv remaine matching else Nothing
(Just d2') -> if d2 == d2' then unifyOMat m1 m2 remainv remaine matching else Nothing
-- (Just _,Nothing) -> Nothing
-- (Nothing,Just _) -> Nothing
(Nothing) ->
let s1d1 = tail $ orbit (act (sigma m1)) d1 in
let s2d2 = tail $ orbit (act (sigma m2)) d2 in
if length s1d1 == length s2d2 then
unifyOMat m1 m2 remainv (zip s1d1 s2d2 ++ remaine) ((d1,d2):matching)
else Nothing
unifyOMat m1 m2 [] ((d1,d2):remaine) matching =
let a1d1 = act (alpha m1) d1 in
let a2d2 = act (alpha m2) d2 in
unifyOMat m1 m2 [(a1d1,a2d2)] remaine ((d1,d2):matching)
-- two maps are equivalent if they have a unifier
equivUM :: UMap -> UMap -> Bool
equivUM m1 m2 = any (\_ -> True) (fastUnifyUM m1 m2)
equivOM :: OMap -> OMap -> Bool
equivOM m1 m2 =
any (\_ -> True) (fastUnifyOM m1 m2)
-- let d1 = head (odarts m1) in
-- any (\d2 -> unifyOMat m1 m2 [(d1,d2)] [(d1,d2)] [] /= Nothing) (odarts m2)
-- two rooted maps are equivalent if they have a unifier which respects the rooting
equivRUM :: UMap -> UMap -> Bool
equivRUM m1 m2 =
let root1 = head (udarts m1) in
let root2 = head (udarts m2) in
any (\p -> act p root1 == root2) (fastUnifyUM m1 m2)
equivROM :: OMap -> OMap -> Bool
equivROM m1 m2 =
let root1 = head (odarts m1) in
let root2 = head (odarts m2) in
-- any (\p -> act p root1 == root2) (fastUnifyOM m1 m2)
unifyOMat m1 m2 [(root1,root2)] [(root1,root2)] [] /= Nothing
-- unoriented maps
genUMap :: Int -> [UMap]
genUMap n =
[UMap {udarts=[1..4*n], x=x, y=y, z=z} |
let x = [(4*i+1,4*i+2) | i <- [0..n-1]] ++ [(4*i+2,4*i+1) | i <- [0..n-1]] ++
[(4*i+3,4*i+4) | i <- [0..n-1]] ++ [(4*i+4,4*i+3) | i <- [0..n-1]],
let z = [(4*i+1,4*i+4) | i <- [0..n-1]] ++ [(4*i+4,4*i+1) | i <- [0..n-1]] ++
[(4*i+3,4*i+2) | i <- [0..n-1]] ++ [(4*i+2,4*i+3) | i <- [0..n-1]],
y <- involute [1..4*n],
isTransitive [x,y,z] [1] [1..4*n]]
-- [length $ nubBy equivRUM $ genUMap n | n <- [1..]] == [3,24,297,...]
-- oriented maps
genOMap :: Int -> [OMap]
genOMap 0 = [OMap {odarts=[],sigma=[],alpha=[]}]
genOMap n =
[OMap {odarts=[1..2*n], sigma=sigma, alpha=alpha} |
let alpha = [(2*i+1,2*i+2) | i <- [0..n-1]] ++ [(2*i+2,2*i+1) | i <- [0..n-1]],
sigma <- permute [1..2*n],
isTransitive [sigma,alpha] [1] [1..2*n]]
-- [length $ nubBy equivOM $ genOMap n | n <- [1..]] == [2,5,20,107,...] == A006867?? or A214816??
-- [length $ nubBy equivROM $ genOMap n | n <- [1..]] == [2,10,74,706,...] == A000698
-- [sum $ map (\m -> length $ permToCycles (sigma m)) $ nubBy equivROM $ genOMap n | n <- [1..]] == [3,19,165,1769,...]
-- generate "intrinsically-rooted" maps, where the root is marked by a single
-- fixed point of the edge involution.
genROM :: Int -> [OMap]
genROM 0 = [OMap {odarts=[0],sigma=[(0,0)],alpha=[(0,0)]}]
genROM n =
[OMap {odarts=odarts',sigma=sigma',alpha=alpha'} |
m <- genOMap n,
let r = 0,
let odarts' = r:odarts m,
let alpha' = (r,r):alpha m,
(c,cs) <- remove $ permToCycles (sigma m),
let sigma' = cyclesToPerm ((r:c):cs)]
-- [length $ nubBy equivOM $ genROM n | n <- [0..]] == [1,2,10,74,...]
genRPM n = [m | m <- genROM n, eulerOM m == 1]
-- [length $ nubBy equivOM $ genRPM n | n <- [0..]] == [1,2,9,54,...]
-- generate rooted maps inductively via Tutte decomposition
genROM_tutte :: Int -> StateT Int [] (Int,OMap)
genROM_tutte 1 = do
r <- freshInt
return (r,OMap {odarts=[r],sigma=[(r,r)],alpha=[(r,r)]})
genROM_tutte n = genROM_isthmic n `mplus` genROM_nonisthmic n
where
genROM_isthmic :: Int -> StateT Int [] (Int,OMap)
genROM_isthmic n = do
i <- lift [1..n-1]
(r1,m1) <- genROM_tutte i
(r2,m2) <- genROM_tutte (n-i)
r <- freshInt
let odarts' = r : odarts m1 ++ odarts m2
let sigma' = [(r,r1)] ++
[(d,if d' == r1 then r else d') | d <- odarts m1, let d' = act (sigma m1) d] ++
sigma m2
let alpha' = [(r,r)] ++
[(r1,r2),(r2,r1)] ++
[(d,d') | d <- odarts m1 \\ [r1], let d' = act (alpha m1) d] ++
[(d,d') | d <- odarts m2 \\ [r2], let d' = act (alpha m2) d]
return (r, OMap { odarts = odarts', sigma = sigma', alpha = alpha' })
genROM_nonisthmic :: Int -> StateT Int [] (Int,OMap)
genROM_nonisthmic n = do
(r1,m1) <- genROM_tutte (n-1)
r2 <- freshInt
r <- freshInt
x <- lift (odarts m1)
let odarts' = r : r2 : odarts m1
let r2' = if act (sigma m1) x == r1 then r else act (sigma m1) x
let sigma' = [(r,r1)] ++ [(x,r2),(r2,r2')] ++
[(d,if d' == r1 then r else d') | d <- odarts m1 \\ [x], let d' = act (sigma m1) d]
let alpha' = [(r,r)] ++
[(r1,r2),(r2,r1)] ++
[(d,d') | d <- odarts m1 \\ [r1], let d' = act (alpha m1) d]
return (r, OMap { odarts = odarts', sigma = sigma', alpha = alpha' })
genROM_tutte' :: Int -> [(Int,OMap)]
genROM_tutte' n = map fst $ runStateT (genROM_tutte n) 0
-- list of darts incident to root vertex
rootDartsROM :: OMap -> [Int]
rootDartsROM m =
let r = head (odarts m) in
orbit (act (sigma m)) r
-- list of edges (rather than darts) incident to root vertex
rootEdgesROM :: OMap -> [[Int]]
rootEdgesROM m =
let r = head (odarts m) in
let ds = orbit (act (sigma m)) r \\ [r] in
equivClassesBy (\d1 d2 -> elem d1 (orbit (act (alpha m)) d2)) ds []
-- list of faces incident to root vertex
rootFacesROM :: OMap -> [[Int]]
rootFacesROM m =
let r = head (odarts m) in
let ds = orbit (act (sigma m)) r \\ [r] in
equivClassesBy (\d1 d2 -> elem d1 (orbit (act (comp (inv (sigma m)) (alpha m))) d2)) ds []
-- list of vertices incident to root face
rootVerticesROM :: OMap -> [[Int]]
rootVerticesROM m =
let r = head (odarts m) in
let ds = orbit (act (phiOM m)) r \\ [r] in
equivClassesBy (\d1 d2 -> elem d1 (orbit (act (sigma m)) d2)) ds []
-- map (length . rootDartsROM) (nubBy equivOM $ genROM 1) == [2,3]
-- map (length . rootEdgesROM) (nubBy equivOM $ genROM 1) == [1,1]
-- map (length . rootDartsROM) (nubBy equivOM $ genROM 2) == [2,3,4,2,4,5,4,5,3,5]
-- map (length . rootEdgesROM) (nubBy equivOM $ genROM 2) == [1,2,2,1,2,2,2,2,2,2]
-- map (length . rootDartsROM) (nubBy equivOM $ genROM 3) == [2,3,3,4,3,2,2,5,2,6,2,2,5,6,2,2,4,5,3,4,2,6,2,3,4,4,3,4,4,6,7,6,7,5,6,3,5,7,3,4,6,7,6,7,5,6,5,7,4,5,6,7,6,7,4,7,4,5,3,5,3,6,7,5,6,5,7,6,7,7,7,7,4,6]
-- map (length . rootEdgesROM) (nubBy equivOM $ genROM 3) == [1,2,2,2,2,1,1,3,1,3,1,1,3,3,1,1,3,3,2,3,1,3,1,2,2,2,2,2,2,3,3,3,3,3,3,2,3,3,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,3,2,3,3,3,3,3,3,3,3,3,3,3,3,3]
-- map (length . rootDartsROM) (nubBy equivOM $ genRPM 2) == [2,3,4,2,4,5,4,5,3]
-- map (length . rootEdgesROM) (nubBy equivOM $ genRPM 2) == [1,2,2,1,2,2,2,2,2]
-- map (length . rootDartsROM) (nubBy equivOM $ genRPM 3) == [2,3,3,4,3,2,2,5,2,6,2,2,5,6,2,2,4,5,3,4,2,3,4,4,3,4,4,6,7,6,7,5,6,3,5,3,4,6,7,6,7,5,6,5,4,5,4,5,3,5,6,6,7,4]
-- map (length . rootEdgesROM) (nubBy equivOM $ genRPM 3) == [1,2,2,2,2,1,1,3,1,3,1,1,3,3,1,1,3,3,2,3,1,2,2,2,2,2,2,3,3,3,3,3,3,2,3,2,2,3,3,3,3,3,3,3,3,3,3,3,2,3,3,3,3,3]
unroot :: OMap -> OMap
unroot m =
let edges = permToCycles (alpha m) in
let (fulledges,hyperedges) = partition (\c -> length c == 2) edges in
case hyperedges of
[[r]] ->
let r' = act (sigma m) r in
OMap { odarts = odarts m \\ [r],
sigma = [(i,if j == r then r' else j) | (i,j) <- sigma m, i /= r],
alpha = cyclesToPerm fulledges }
_ -> error "unroot: alpha must have exactly one fixpoint and n 2-cycles"
-- [length $ nubBy equivOM $ map unroot $ genROM n | n <- [1..]] == [2,5,20,...]
genOM3 :: Int -> [OMap]
genOM3 n =
[OMap {odarts=[1..6*n], sigma=sigma, alpha=alpha} |
let alpha = [(2*i+1,2*i+2) | i <- [0..3*n-1]] ++ [(2*i+2,2*i+1) | i <- [0..3*n-1]],
sigma <- cubic [1..6*n],
isTransitive [sigma,alpha] [1] [1..6*n]]
where
cubic :: [a] -> [[(a,a)]]
cubic [] = return []
cubic (a1:as) = do
(a2,as') <- remove as
(a3,as'') <- remove as'
p <- cubic as''
return ((a1,a2):(a2,a3):(a3,a1):p)
genChordDiagram :: Int -> [OMap]
genChordDiagram n =
[m |
m <- genOM3 n,
let r = head (odarts m),
let rface = orbit (act (phiOM m)) r,
length rface == 2*n,
let vs = verticesOM m,
all (\v -> intersect v rface /= []) vs]
genOM4 :: Int -> [OMap]
genOM4 n =
[OMap {odarts=[1..4*n], sigma=sigma, alpha=alpha} |
let alpha = [(2*i+1,2*i+2) | i <- [0..2*n-1]] ++ [(2*i+2,2*i+1) | i <- [0..2*n-1]],
sigma <- quartic [1..4*n],
isTransitive [sigma,alpha] [1] [1..4*n]]
where
quartic :: [a] -> [[(a,a)]]
quartic [] = return []
quartic (a1:as) = do
(a2,as') <- remove as
(a3,as'') <- remove as'
(a4,as''') <- remove as''
p <- quartic as'''
return ((a1,a2):(a2,a3):(a3,a4):(a4,a1):p)
-- [length $ nubBy equivROM $ genOM4 n | n <- [1..]] == [3,24,...] == ?
-- hypermaps with n darts
genHMap :: Int -> [OMap]
genHMap n =
[OMap {odarts=[1..n], sigma=sigma, alpha=alpha} |
-- we can always use a labelling of the darts in which the cycles of the first
-- permutation are increasing. So, for sigma we just generate a partition of [1..n].
sigma0 <- parts [1..n],
let sigma = cyclesToPerm sigma0,
alpha <- permute [1..n],
isTransitive [sigma,alpha] [1] [1..n]]
-- [length $ nubBy equivOM $ genHMap n | n <- [1..]] == [1,3,7,26,97,...] == A057005
-- [length $ nubBy equivROM $ genHMap n | n <- [1..]] == [1,3,13,71,461,...] == A003319
-- encoding face 2-colored 4-valent maps (in bijection with rooted
-- oriented maps) à la Zinn/Justin-Zuber [arXiv:math-ph/0303049], as
-- hypermaps (sigma,alpha) on 2n darts, satisfying the extra condition
-- that the permutation sigma^{-1}alpha is a fixed-point free
-- involution.
genZJZ :: Int -> [OMap]
genZJZ n = [m | m <- genHMap (2*n), fpfreeInvolution (comp (inv (sigma m)) (alpha m))]
-- [length $ nubBy equivROM $ genZJZ n | n <- [1..]] == [2,10,74,706,...] == A000698
-- [length $ nubBy equivOM $ genZJZ n | n <- [1..]] == [2,5,20,107,...]
-- hypermaps with n darts, in which the first permutation has k cycles
genHMapByCycles :: Int -> Int -> [OMap]
genHMapByCycles n k =
[OMap {odarts=[1..n], sigma=sigma, alpha=alpha} |
sigma0 <- stirling0 k [1..n],
let sigma = cyclesToPerm sigma0,
alpha <- permute [1..n],
isTransitive [sigma,alpha] [1] [1..n]]
-- [length $ nubBy equivOM $ genHMapByCycles n 1 | n <- [1..]] == [1,2,4,10,28,136,...] == A061417
-- [length $ nubBy equivROM $ genHMapByCycles n 1 | n <- [1..]] == [1,2,6,24,120,720,...] == n!
genZJZByCycles :: Int -> Int -> [OMap]
genZJZByCycles n k = [m | m <- genHMapByCycles (2*n) k, fpfreeInvolution (comp (inv (sigma m)) (alpha m))]
-- [length $ nubBy equivROM $ genZJZByCycles n 1 | n <- [1..]] == [1,3,15,105,...] == A001147
-- [length $ nubBy equivROM $ genZJZByCycles n 2 | n <- [1..]] == [1,5,32,260,...]
-- [length $ nubBy equivROM $ genZJZByCycles n 3 | n <- [1..]] == [0,2,22,234,...]
-- [sum [(length $ permToCycles (sigma m)) | m <- nubBy equivROM $ genZJZ n] | n <- [1..]] == [3,19,165,...]
-- [sum [binom 2 (length $ permToCycles (sigma m)) | m <- nubBy equivROM $ genZJZ n] | n <- [1..]] == [1,11,128,...]
-- [sum [binom 3 (length $ permToCycles (sigma m)) | m <- nubBy equivROM $ genZJZ n] | n <- [1..]] == [0,2,42,746,...]
-- a "slightly hypermap" is a hypermap in which all but one white vertex has degree 2. The indices k and n count the number of vertices and the number of ordinary edges, respectively.
genSHMap :: Int -> Int -> [OMap]
genSHMap k n =
[m |
m <- genHMapByCycles (2*n + k) k,
let cs = clengths (alpha m),
sum [1 | c <- cs, c == 2] == n &&
sum [1 | c <- cs, c == k] == 1]
-- EXAMPLES
-- the Petersen graph as an oriented map
petersenOM :: OMap
petersenOM =
OMap {
odarts = [1..30],
sigma = cyclesToPerm [[3*i+1,3*i+2,3*i+3] | i <- [0..9]],
alpha = cyclesToPerm [[1,4],[2,16],[3,14],[5,7],[6,19],[8,10],
[9,22],[11,13],[12,25],[15,28],[17,24],
[18,26],[20,27],[21,29],[23,30]]
}
-- test if the edge corresponding to a dart is a bridge
isBridge :: OMap -> Int -> Bool
isBridge m d =
let d' = act (alpha m) d in
let alpha' = [(x,y) | x <- odarts m, let y = if x == d then d else if x == d' then d' else act (alpha m) x] in
not $ elem d' (transClosure [sigma m, alpha'] [d])
-- test if the edge corresponding to a dart is a loop
isLoop :: OMap -> Int -> Bool
isLoop m d =
let d' = act (alpha m) d in
d /= d' && elem d' (orbit (act (sigma m)) d)
-- test if a map is bridgeless
isBridgeless :: OMap -> Bool
isBridgeless m = not $ any (isBridge m) (odarts m)
-- test if a map is loopless
isLoopless :: OMap -> Bool
isLoopless m = not $ any (isLoop m) (odarts m)
-- [length $ filter (isBridgeless . unroot) (map snd $ genROM_tutte' n) | n <- [1..]] == [1,1,4,27,248,2830,38232,...] == A000699
-- [length $ filter (all (\v -> length v `mod` 2 == 0) . verticesOM . unroot) (map snd $ genROM_tutte' n) | n <- [1..]] == [1,1,4,25,208,2146,26368,...] == A005411
-- check that a map is connected
isConnected :: OMap -> Bool
isConnected m =
if odarts m == [] then True else -- we count the empty map as connected
let r = head (odarts m) in
length (transClosure [sigma m, alpha m] [r]) == length (odarts m)
-- delete a list of darts from a map
deleteDarts :: OMap -> [Int] -> OMap
deleteDarts m ds =
let odarts' = odarts m \\ ds in
let sigma' d = let d' = act (sigma m) d in if elem d' ds then sigma' d' else d' in
let alpha' d = let d' = act (alpha m) d in if elem d' ds then alpha' d' else d' in
OMap {
odarts = odarts',
sigma = [(d,sigma' d) | d <- odarts'],
alpha = [(d,alpha' d) | d <- odarts']
}
-- detach (but don't delete) the darts incident to a vertex
breakVertex :: OMap -> [Int] -> OMap
breakVertex m v =
OMap {
odarts = odarts m,
sigma = [(d,d') | d <- odarts m, let d' = if elem d v then d else act (sigma m) d],
alpha = alpha m
}
-- detach (but don't delete) the darts incident to an edge
breakEdge :: OMap -> [Int] -> OMap
breakEdge m e =
OMap {
odarts = odarts m,
sigma = sigma m,
alpha = [(d,d') | d <- odarts m, let d' = if elem d e then d else act (alpha m) d]
}
-- test if a map is k-vertex-connected
isKVConnected :: Int -> OMap -> Bool
isKVConnected 0 m = True
isKVConnected k m =
flip all (choosek (k-1) (verticesOM m)) $ \(vs,_) ->
isConnected (foldl deleteDarts m vs)
-- test if a map is k-edge-connected
isKEConnected :: Int -> OMap -> Bool
isKEConnected 0 m = True
isKEConnected k m =
flip all (choosek (k-1) (edgesOM m)) $ \(es,_) ->
isConnected (foldl breakEdge m es)
-- more surgery routines...
-- contract an edge
contractEdge :: OMap -> Int -> OMap
contractEdge m d =
let d' = act (alpha m) d in
let v1 = orbit (act (sigma m)) d in
let v2 = orbit (act (sigma m)) d' in
let e = union [d] [d'] in
let v = if elem d' v1 then v1 \\ e
else (v1 \\ [d]) ++ (v2 \\ [d']) in
OMap { odarts = odarts m \\ e,
alpha = [(i, act (alpha m) i) | i <- odarts m \\ e],
sigma = [(i, act (sigma m) i) | i <- (odarts m \\ e) \\ v]
++ cyclesToPerm [v] }
-- perform a depth-first traversal of the darts of a map
dfsOM :: OMap -> Int -> [Int]
dfsOM m r = reverse $ dfs' [] (r : (odarts m \\ [r]))
where
dfs' :: [Int] -> [Int] -> [Int]
dfs' visited [] = visited
dfs' visited (r:unvisited) =
if elem r visited then dfs' visited unvisited else
let r' = act (sigma m) r in
let r'' = act (alpha m) r' in
if elem r' visited then dfs' (r:visited) unvisited else
dfs' (union [r'] [r] ++ visited) (r'':unvisited)
| noamz/linlam-gos | src/Maps.hs | mit | 19,711 | 0 | 24 | 4,565 | 8,028 | 4,292 | 3,736 | 334 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module Propylgraph.Sentences (sentences, pairs) where
import Data.List
import qualified Data.Text.Lazy as T
sentenceTerminators :: [Char]
sentenceTerminators = ".?!"
punctuation :: [Char]
punctuation = "~`$%^&*()_-+=|\\}]{[\"':;/><,"
sentences :: T.Text -> [[T.Text]]
sentences xs = filter (not . null) $ map T.words phrases
where phrases = filter (not . T.null) chunks
chunks = T.split (`elem` sentenceTerminators) $
T.filter (`notElem` punctuation) $
T.toLower xs
diag :: [a] -> [(a, a)]
diag [] = []
diag (_:[]) = []
diag (x:x':xs) = (x, x') : diag (x' : xs)
heads :: [a] -> [(a, [a])]
heads [] = []
heads (x:[]) = [(x, [])]
heads (x:xs) = (x, xs) : heads xs
echelon :: [a] -> [(a, a)]
echelon = (concatMap f) . heads
where f (x, xs) = map (\n -> (x, n)) xs
pairs :: [a] -> ([(a, a)], [(a, a)])
pairs xs = (diag xs, echelon xs)
| TravisWhitaker/Propylgraph | Propylgraph/Sentences.hs | mit | 945 | 0 | 10 | 228 | 474 | 271 | 203 | 27 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Network.HTTP.Conduit
import qualified Data.ByteString.Lazy as L
import Control.Monad.Random
data Ability = Ability
{
aName :: String
, aUri :: String
} deriving (Show)
data Move = Move
{ learnType :: String
, moveName :: String
, moveUri :: String
} deriving (Show)
data Pokemon = Pokemon {
abilities :: [Ability]
, attack :: Int
, catch_rate :: Int
, created :: String
, defense :: String
, exp :: Int
, hp :: Int
, moves :: [Move]
} deriving (Show)
-- generates one of the ORIGINAL AND ONLY 150 random pokemon
randomPokemon :: IO Int
randomPokemon = getStdRandom (randomR (1,150))
-- make a json instance for pokemon and return that type!
getPokemon :: Int -> IO L.ByteString
getPokemon p = simpleHttp $ "http://pokeapi.co/api/v1/pokemon/" ++ show p ++ "/"
getMoves :: L.ByteString -> [Move]
getMoves p = undefined
main = putStrLn $ "You have " ++ show hp ++ " HP"
where hp = 200
| codygman/pokemon-battle | src/Main.hs | mit | 1,019 | 0 | 9 | 255 | 271 | 160 | 111 | 31 | 1 |
{-# LANGUAGE PatternSynonyms #-}
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module JSDOM.Generated.HTMLFieldSetElement
(checkValidity, checkValidity_, reportValidity, reportValidity_,
setCustomValidity, setDisabled, getDisabled, getForm, setName,
getName, getType, getElements, getWillValidate, getValidity,
getValidationMessage, HTMLFieldSetElement(..),
gTypeHTMLFieldSetElement)
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/HTMLFieldSetElement.checkValidity Mozilla HTMLFieldSetElement.checkValidity documentation>
checkValidity :: (MonadDOM m) => HTMLFieldSetElement -> m Bool
checkValidity self
= liftDOM ((self ^. jsf "checkValidity" ()) >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.checkValidity Mozilla HTMLFieldSetElement.checkValidity documentation>
checkValidity_ :: (MonadDOM m) => HTMLFieldSetElement -> m ()
checkValidity_ self
= liftDOM (void (self ^. jsf "checkValidity" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.reportValidity Mozilla HTMLFieldSetElement.reportValidity documentation>
reportValidity :: (MonadDOM m) => HTMLFieldSetElement -> m Bool
reportValidity self
= liftDOM ((self ^. jsf "reportValidity" ()) >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.reportValidity Mozilla HTMLFieldSetElement.reportValidity documentation>
reportValidity_ :: (MonadDOM m) => HTMLFieldSetElement -> m ()
reportValidity_ self
= liftDOM (void (self ^. jsf "reportValidity" ()))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.setCustomValidity Mozilla HTMLFieldSetElement.setCustomValidity documentation>
setCustomValidity ::
(MonadDOM m, ToJSString error) =>
HTMLFieldSetElement -> error -> m ()
setCustomValidity self error
= liftDOM (void (self ^. jsf "setCustomValidity" [toJSVal error]))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.disabled Mozilla HTMLFieldSetElement.disabled documentation>
setDisabled :: (MonadDOM m) => HTMLFieldSetElement -> Bool -> m ()
setDisabled self val
= liftDOM (self ^. jss "disabled" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.disabled Mozilla HTMLFieldSetElement.disabled documentation>
getDisabled :: (MonadDOM m) => HTMLFieldSetElement -> m Bool
getDisabled self = liftDOM ((self ^. js "disabled") >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.form Mozilla HTMLFieldSetElement.form documentation>
getForm :: (MonadDOM m) => HTMLFieldSetElement -> m HTMLFormElement
getForm self = liftDOM ((self ^. js "form") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.name Mozilla HTMLFieldSetElement.name documentation>
setName ::
(MonadDOM m, ToJSString val) => HTMLFieldSetElement -> val -> m ()
setName self val = liftDOM (self ^. jss "name" (toJSVal val))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.name Mozilla HTMLFieldSetElement.name documentation>
getName ::
(MonadDOM m, FromJSString result) =>
HTMLFieldSetElement -> m result
getName self = liftDOM ((self ^. js "name") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.type Mozilla HTMLFieldSetElement.type documentation>
getType ::
(MonadDOM m, FromJSString result) =>
HTMLFieldSetElement -> m result
getType self = liftDOM ((self ^. js "type") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.elements Mozilla HTMLFieldSetElement.elements documentation>
getElements ::
(MonadDOM m) => HTMLFieldSetElement -> m HTMLFormControlsCollection
getElements self
= liftDOM ((self ^. js "elements") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.willValidate Mozilla HTMLFieldSetElement.willValidate documentation>
getWillValidate :: (MonadDOM m) => HTMLFieldSetElement -> m Bool
getWillValidate self
= liftDOM ((self ^. js "willValidate") >>= valToBool)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.validity Mozilla HTMLFieldSetElement.validity documentation>
getValidity ::
(MonadDOM m) => HTMLFieldSetElement -> m ValidityState
getValidity self
= liftDOM ((self ^. js "validity") >>= fromJSValUnchecked)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement.validationMessage Mozilla HTMLFieldSetElement.validationMessage documentation>
getValidationMessage ::
(MonadDOM m, FromJSString result) =>
HTMLFieldSetElement -> m result
getValidationMessage self
= liftDOM ((self ^. js "validationMessage") >>= fromJSValUnchecked)
| ghcjs/jsaddle-dom | src/JSDOM/Generated/HTMLFieldSetElement.hs | mit | 5,776 | 0 | 12 | 759 | 1,168 | 654 | 514 | 73 | 1 |
{-# LANGUAGE ExistentialQuantification, GADTs, RankNTypes #-}
module AlaCarte where
--- Haskell encoding of Runars talk on Monad Coproducts and Free Monads
--- https://dl.dropboxusercontent.com/u/4588997/ReasonablyPriced.pdf
data Interact a where
Ask :: String -> Interact String
Tell :: String -> Interact ()
data User = User
data Auth a where
Login :: (String, String) -> Auth User
Access :: User -> Auth Bool
type Coproduct f g a = Either (f a) (g a)
data Free f a = Return a | forall i. Bind (f i) (i -> Free f a)
instance Functor (Free f) where
--fmap :: (a -> b) -> f a -> f b
fmap g (Return a) = Return (g a)
fmap g (Bind fi h) = Bind fi (\i -> fmap g (h i))
instance Applicative (Free f) where
pure = Return
(Return fab) <*> (Return fa) = Return (fab fa)
(Return fab) <*> (Bind fi g) = Bind fi (\i -> fmap fab (g i))
--(Bind fi g) <*> (Return fa) = Bind fi (\f -> Return (f fa))
--(Bind fi g) <*> (Bind fj h) = error "Undefined"
instance Monad (Free f) where
return = Return
(Return a) >>= g = g a
(Bind fi g) >>= h = Bind (fi) (\j -> (g j) >>= h)
type NatTrans f g = forall a. f a -> g a
or :: NatTrans f g -> NatTrans h g -> NatTrans (Coproduct f h) g
or fg hg = foldE fg hg
foldE :: (a -> c) -> (b -> c) -> Either a b -> c
foldE f g e = case e of
Left a -> f a
Right b -> g b
left :: f a -> Coproduct f g a
left = Left
right :: g a -> Coproduct f g a
right = Right
liftF :: f a -> Free f a
liftF fa = Bind fa Return
ask :: String -> Free Interact String
ask = liftF . Ask
tell :: String -> Free Interact ()
tell = liftF . Tell
| nlim/haskell-playground | src/AlaCarte.hs | mit | 1,643 | 0 | 11 | 446 | 691 | 356 | 335 | 39 | 2 |
module Main where
import Data.List (elemIndex, foldl', inits)
import Data.Maybe (catMaybes)
import Parser
text :: String
text = "abcdefgh" -- should be bfheacgd
scrampeled :: String
scrampeled = "fbgdceah"
main :: IO ()
main = do
insts <- instructions
putStrLn $ "Part 1: " ++ process insts text
putStrLn $ "Part 2: " ++ processInv insts scrampeled
putStrLn "all done"
data Instruction
= SwapPos Int Int
| SwapLetter Char Char
| Rotate Int
| RotateOn Char
| Reverse Int Int
| Move Int Int
deriving Show
process :: [Instruction] -> String -> String
process insts input = foldl' (flip apply) input insts
processInv :: [Instruction] -> String -> String
processInv insts input = foldl' (flip applyInv) input (reverse insts)
apply :: Instruction -> String -> String
apply (SwapPos a b) input =
apply (SwapLetter (input !! a) (input !! b)) input
apply (SwapLetter a b) input =
map swap input
where swap c
| c == a = b
| c == b = a
| otherwise = c
apply (Rotate n) input =
take l $ drop (n `mod` l) $ cycle input
where l = length input
apply (RotateOn c) input =
case elemIndex c input of
Nothing -> input
Just n ->
let r = if n >= 4 then n+2 else n+1
in apply (Rotate $ negate r) input
apply (Reverse a b) input
| a > b = apply (Reverse b a) input
| a <= b =
let (prev,end) = splitAt (b+1) input
(start, mid) = splitAt a prev
in concat [start, reverse mid, end]
apply (Move a b) input =
let (prev,(ca:rest)) = splitAt a input
(prev', end) = splitAt b (prev++rest)
in prev' ++ ca:end
applyInv :: Instruction -> String -> String
applyInv x@(SwapPos _ _) input = apply x input
applyInv x@(SwapLetter _ _) input = apply x input
applyInv (Rotate n) input = apply (Rotate $ negate n) input
applyInv (RotateOn c) input =
head $ [ xs | i <- [0..length input-1]
, let xs = apply (Rotate i) input
, apply (RotateOn c) xs == input ]
applyInv x@(Reverse _ _) input = apply x input
applyInv (Move a b) input = apply (Move b a) input
instructions :: IO [Instruction]
instructions =
catMaybes . map (eval parseInstruction) <$> input
input :: IO [String]
input = lines <$> readFile "input.txt"
parseInstruction :: Parser Instruction
parseInstruction = do
parseOneOf [ swapPosP
, swapLetP
, rotateP
, rotateOnP
, reverseP
, moveP ]
swapPosP :: Parser Instruction
swapPosP = do
parseString "swap position"
a <- parseNumber
parseString "with position"
b <- parseNumber
return $ SwapPos a b
swapLetP :: Parser Instruction
swapLetP = do
parseString "swap letter "
a <- parseChar (const True)
parseString " with letter "
b <- parseChar (const True)
return $ SwapLetter a b
rotateP :: Parser Instruction
rotateP = do
parseString "rotate"
parseWhiteSpaces
lr <- leftRightP
parseWhiteSpaces
n <- parseNumber
parseString "step"
return $ Rotate (lr n)
where leftRightP = parseEither leftP rightP
leftP = parseString "left" >> pure negate
rightP = parseString "right" >> pure id
rotateOnP :: Parser Instruction
rotateOnP = do
parseString "rotate based on position of letter "
c <- parseChar (const True)
return $ RotateOn c
reverseP :: Parser Instruction
reverseP = do
parseString "reverse positions"
a <- parseNumber
parseString "through"
b <- parseNumber
return $ Reverse a b
moveP :: Parser Instruction
moveP = do
parseString "move position"
a <- parseNumber
parseString "to position"
b <- parseNumber
return $ Move a b
----------------------------------------------------------------------
-- test
test :: [String]
test = map (\is -> process is "abcde") $ inits testInstructions
testInv :: String
testInv = processInv testInstructions "decab"
testInstructions =
[ SwapPos 4 0
, SwapLetter 'd' 'b'
, Reverse 0 4
, Rotate 1
, Move 1 4
, Move 3 0
, RotateOn 'b'
, RotateOn 'd'
]
| CarstenKoenig/AdventOfCode2016 | Day21/Main.hs | mit | 3,999 | 0 | 13 | 993 | 1,515 | 746 | 769 | 135 | 3 |
{-#LANGUAGE CPP #-}
module Melchior.Remote.Internal.ParserUtils where
import Control.Monad
#ifdef __UHC_TARGET_JS__
import Data.Char
#else
import Data.Char hiding (isLetter)
#endif
newtype Parser a = Parser (String -> [(a, String)])
parse :: Parser a -> (String -> [(a, String)])
parse (Parser p) = p
instance Monad Parser where
return a = Parser (\cs -> [(a, cs)])
p >>= f = Parser (\cs -> concat [parse (f a) cs' | (a, cs') <- parse p cs])
instance MonadPlus Parser where
mzero = Parser (\cs -> [])
mplus p q = Parser (\cs -> parse p cs ++ parse q cs)
(+++) :: Parser a -> Parser a -> Parser a
p +++ q = Parser (\cs -> case parse (mplus p q) cs of
[] -> []
(x:xs) -> [x])
item :: Parser Char
item = Parser (\cs -> case cs of
"" -> []
(c:cs) -> [(c, cs)])
sat :: (Char -> Bool) -> Parser Char
sat p = do { c <- item; if p c then return c else mzero }
char :: Char -> Parser Char
char c = sat (c ==)
string :: String -> Parser String
string "" = return ""
string (c:cs) = do { char c; string cs; return (c: cs) }
many :: Parser a -> Parser [a]
many p = many1 p +++ return []
many1 :: Parser a -> Parser [a]
many1 p = do { a <- p; as <- many p; return (a:as) }
space :: Parser String
space = many (sat (\x -> any (== x) [' ', '\n', '\r', '\t']))
notSpaceAlpha :: Parser String
notSpaceAlpha = many (sat (\x -> isLetter x && any(/= x) [' ', '\n', '\r', '\t']))
notCloseQuote :: Parser String
notCloseQuote = many (sat (\x -> x /= '"'))
isLetter :: Char -> Bool
isLetter c = ord c <= 122 && ord c >= 65
digit = do {x <- token (sat isDigit); return x }
token :: Parser a -> Parser a
token p = do { a <- p; space; return a }
symb :: String -> Parser String
symb cs = token (string cs)
number :: Parser [Char]
number = many digit | kjgorman/melchior | Melchior/Remote/Internal/ParserUtils.hs | mit | 1,842 | 1 | 13 | 479 | 937 | 491 | 446 | 47 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
module SoOSiM.Components.CodeAdapter where
import SoOSiM
import SoOSiM.Components.Types
data CodeAdapter = CodeAdapter
data Data = Data deriving Typeable
data CA_Cmd = AdaptCode Code DestinationArchitecture
| AdaptContext ThreadContext DestinationArchitecture
| DataStandardisation Data
| DataNativisation Data
deriving Typeable
data CA_Msg = CA_AC (Maybe AdaptedCode)
| CA_SD StandarData
| CA_ND NativeData
deriving Typeable
data AdaptedCode = AdaptedCode deriving Typeable
data StandarData = StandarData deriving Typeable
data NativeData = NativeData deriving Typeable
data CA_State = CA_State
instance ComponentInterface CodeAdapter where
type State CodeAdapter = CA_State
type Receive CodeAdapter = CA_Cmd
type Send CodeAdapter = CA_Msg
initState = const (CA_State)
componentName = const ("Code Adapter")
componentBehaviour = const codeAdapter
codeAdapter ::
CA_State
-> Input CA_Cmd
-> Sim CA_State
codeAdapter caState (Message (AdaptCode c d) retAddr) = do
ac <- case codeType c of
SourceCode -> do
case destinationType d of
RealArchitecture -> do
ac <- adaptCodeFromCodeToPlatform c d
return (Just ac)
IRArchitecture -> do
ac <- adaptCodeFromeCodeToIR c
return (Just ac)
IR -> do
case destinationType d of
RealArchitecture -> do
ac <- adaptCodeFromIRToPlatform c d
return (Just ac)
_ -> return Nothing
Binary -> do
case destinationType d of
RealArchitecture -> do
ac <- adaptCodeFromBinaryToPlatfrom c d
return (Just ac)
IRArchitecture -> do
ac <- adaptCodeFromBinaryToIR c
return (Just ac)
respond CodeAdapter retAddr (CA_AC ac)
yield caState
codeAdapter caState (Message (DataStandardisation d) retAddr) = do
-- doAllTheWorkToStandardisiteInputData
sd <- compute 4 StandarData
respond CodeAdapter retAddr (CA_SD sd)
yield caState
codeAdapter caState (Message (DataNativisation d) retAddr) = do
-- doAllTheWorkToTransformStandardisiteInputDataToNativeRepresentation
nd <- compute 4 NativeData
respond CodeAdapter retAddr (CA_ND nd)
yield caState
codeAdapter caState _ = yield caState
adaptCodeFromCodeToPlatform c d = do
-- doNecessaryTransformations(...);
ac <- compute 4 AdaptedCode
return ac
adaptCodeFromeCodeToIR c = do
-- doNecessaryTransformations(...);
ac <- compute 4 AdaptedCode
return ac
adaptCodeFromIRToPlatform c d = do
-- doNecessaryTransformations(...);
ac <- compute 4 AdaptedCode
return ac
adaptCodeFromBinaryToPlatfrom c d = do
-- doNecessaryTransformations(...);
ac <- compute 4 AdaptedCode
return ac
adaptCodeFromBinaryToIR c = do
-- doNecessaryTransformations(...);
ac <- compute 4 AdaptedCode
return ac
| christiaanb/SoOSiM | src-components/SoOSiM/Components/CodeAdapter.hs | mit | 2,986 | 0 | 20 | 724 | 752 | 362 | 390 | 81 | 6 |
{-# htermination replicateM :: Int -> IO a -> IO [a] #-}
import Monad
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Monad_replicateM_4.hs | mit | 70 | 0 | 3 | 14 | 5 | 3 | 2 | 1 | 0 |
-- |
-- Module: Math.NumberTheory.Powers.Modular
-- Copyright: (c) 2017 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <andrew.lelechenko@gmail.com>
--
-- Modular powers (a. k. a. modular exponentiation).
--
module Math.NumberTheory.Powers.Modular
{-# DEPRECATED "Use Data.Mod or Data.Mod.Word instead" #-}
( powMod
, powModWord
, powModInt
) where
import GHC.Natural (powModNatural)
import qualified GHC.Integer.GMP.Internals as GMP (powModInteger)
import Math.NumberTheory.Utils.FromIntegral
-- | @powMod@ @b@ @e@ @m@ computes (@b^e@) \`mod\` @m@ in effective way.
-- An exponent @e@ must be non-negative, a modulo @m@ must be positive.
-- Otherwise the behaviour of @powMod@ is undefined.
--
-- >>> powMod 2 3 5
-- 3
-- >>> powMod 3 12345678901234567890 1001
-- 1
--
-- See also 'Math.NumberTheory.Moduli.Class.powMod' and 'Math.NumberTheory.Moduli.Class.powSomeMod'.
--
-- For finite numeric types ('Int', 'Word', etc.)
-- modulo @m@ should be such that @m^2@ does not overflow,
-- otherwise the behaviour is undefined. If you
-- need both to fit into machine word and to handle large moduli,
-- take a look at 'powModInt' and 'powModWord'.
--
-- >>> powMod 3 101 (2^60-1 :: Integer) -- correct
-- 1018105167100379328
-- >>> powMod 3 101 (2^60-1 :: Int) -- incorrect due to overflow
-- 1115647832265427613
-- >>> powModInt 3 101 (2^60-1 :: Int) -- correct
-- 1018105167100379328
powMod :: (Integral a, Integral b) => a -> b -> a -> a
powMod x y m
| m <= 0 = error "powModInt: non-positive modulo"
| y < 0 = error "powModInt: negative exponent"
| otherwise = f (x `rem` m) y 1 `mod` m
where
f _ 0 acc = acc
f b e acc = f (b * b `rem` m) (e `quot` 2)
(if odd e then b * acc `rem` m else acc)
{-# INLINE [1] powMod #-}
{-# RULES
"powMod/Integer" powMod = powModInteger
#-}
-- Work around https://ghc.haskell.org/trac/ghc/ticket/14085
powModInteger :: Integer -> Integer -> Integer -> Integer
powModInteger b e m = GMP.powModInteger (b `mod` m) e m
{-# RULES
"powMod/Natural" powMod = powModNatural
"powMod/Word" powMod = powModWord
"powMod/Int" powMod = powModInt
#-}
-- | Specialised version of 'powMod', able to handle large moduli correctly.
--
-- >>> powModWord 3 101 (2^60-1)
-- 1018105167100379328
powModWord :: Word -> Word -> Word -> Word
powModWord b e m = fromInteger $ GMP.powModInteger (toInteger b) (toInteger e) (toInteger m)
-- | Specialised version of 'powMod', able to handle large moduli correctly.
--
-- >>> powModInt 3 101 (2^60-1)
-- 1018105167100379328
powModInt :: Int -> Int -> Int -> Int
powModInt x y m
| m <= 0 = error "powModInt: non-positive modulo"
| y < 0 = error "powModInt: negative exponent"
| otherwise = wordToInt $ powModWord (intToWord (x `mod` m)) (intToWord y) (intToWord m)
| Bodigrim/arithmoi | Math/NumberTheory/Powers/Modular.hs | mit | 2,813 | 0 | 11 | 522 | 490 | 281 | 209 | 32 | 3 |
{- | After "Implementing Functional Languages: a tutorial"
-}
module GMachine
where
import Data.Map (Map)
import qualified Data.Map as Map
data GmState = GmState { code :: GmCode
, stack :: GmStack
, heap :: GmHeap
, globals :: GmGlobals
, stats :: GmStats
}
deriving (Eq, Show)
type GmCode = [Instruction]
data Instruction = Unwind
| Pushglobal Name
| Pushint Int
| Push Int
| Mkap
| Slide Int
deriving (Eq, Show)
type GmStack = [Addr]
type GmHeap = Heap Node
type Heap a = (Int, [Addr], Map Addr a)
hInitial :: Heap a
hInitial = (0, [1..], Map.empty)
hAlloc :: Heap a -> a -> (Heap a, Addr)
hAlloc (size, next:free, cts) n = ((size+1, free, Map.insert next n cts), next)
hLookup :: Heap a -> Addr -> a
hLookup (_, _, cts) a = Map.findWithDefault (error $ "can't find node with address" ++ show a ++ " in heap") a cts
data Node = NNum Int
| NAp Addr Addr
| NGlobal Int GmCode
deriving (Eq, Show)
type GmGlobals = Map Name Addr
type GmStats = Int
statInitial :: GmStats
statInitial = 0
statIncSteps :: GmStats -> GmStats
statIncSteps s = s + 1
statGetSteps :: GmStats -> Int
statGetSteps = id
type Addr = Int
type Name = String
eval :: GmState -> [GmState]
eval state = state : restStates
where
restStates | gmFinal state = []
| otherwise = eval nextState
nextState = doAdmin (step state)
doAdmin :: GmState -> GmState
doAdmin state = state { stats = statIncSteps (stats state) }
gmFinal :: GmState -> Bool
gmFinal (GmState [] _ _ _ _) = True
gmFinal _ = False
step :: GmState -> GmState
step state = dispatch i $ state { code = is }
where
i:is = code state
dispatch :: Instruction -> GmState -> GmState
dispatch (Pushglobal f) = pushglobal f
dispatch (Pushint n) = pushint n
dispatch Mkap = mkap
dispatch (Push n) = push n
dispatch (Slide n) = slide n
dispatch Unwind = unwind
pushglobal :: Name -> GmState -> GmState
pushglobal f state = state { stack = a : stack state }
where
a = Map.findWithDefault (error $ "Undeclared global: " ++ f) f (globals state)
pushint :: Int -> GmState -> GmState
pushint n state = state { stack = a : stack state, heap = heap' }
where
(heap', a) = hAlloc (heap state) (NNum n)
mkap :: GmState -> GmState
mkap state = state { stack = a:as', heap = heap' }
where
(heap', a) = hAlloc (heap state) (NAp a1 a2)
a1:a2:as' = stack state
push :: Int -> GmState -> GmState
push n state = state { stack = a:as }
where
as = stack state
a = getArg (hLookup (heap state) (as !! (n+1)))
getArg :: Node -> Addr
getArg (NAp _ a) = a
getArg n = error $ "wrong node type; expected NAp but found " ++ show n
slide :: Int -> GmState -> GmState
slide n state = state { stack = a : drop n as }
where
a:as = stack state
unwind :: GmState -> GmState
unwind state@(GmState _ (a:as) h _ _) = newState (hLookup h a)
where
newState (NNum _) = state
newState (NAp a1 _) = state { code = [Unwind], stack = a1:a:as }
newState (NGlobal n c)
| length as < n = error "Unwinding with too few arguments"
| otherwise = state { code = c }
| mmakowski/ambc | src/GMachine.hs | mit | 3,402 | 0 | 13 | 1,047 | 1,294 | 694 | 600 | 87 | 3 |
module Lab3 where
-----------------------------------------------------------------------------------------------------------------------------
-- LIST COMPREHENSIONS
------------------------------------------------------------------------------------------------------------------------------
-- ===================================
-- Ex. 0 - 2
-- ===================================
evens :: [Integer] -> [Integer]
evens [] = []
evens [x] = [x]
evens (_:x:xs) = x : evens xs
-- ===================================
-- Ex. 3 - 4
-- ===================================
-- complete the following line with the correct type signature for this function
squares :: Integer -> [Integer]
squares n = [x^2 | x <- [1..n]]
sumSquares :: Integer -> Integer
sumSquares n = sum (squares n)
-- ===================================
-- Ex. 5 - 7
-- ===================================
-- complete the following line with the correct type signature for this function
squares' :: Integer -> Integer -> [Integer]
squares' m n = [x^2 | x <- [(n+1) .. (n+m)]]
sumSquares' :: Integer -> Integer
sumSquares' x = sum . uncurry squares' $ (x, x)
-- ===================================
-- Ex. 8
-- ===================================
coords :: Integer -> Integer -> [(Integer,Integer)]
coords m n = [(x,y)|x<-[0..m], y<-[0..n]]
| AkronCodeClub/edX-FP101x-Oct-2014 | ryan_p/HW1029/lab3.hs | mit | 1,315 | 0 | 10 | 172 | 316 | 181 | 135 | 15 | 1 |
-- | Monadic computations in which you need to be able to
-- short-circuit, in analogy "return" from "classic" programming languages
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Control.Monad.Trans.CircuitT
( CircuitT
, escape
, runCircuitT
)
where
import Control.Applicative
import Control.Monad.Trans.Either
type CircuitT m a = CircuitTW a m a
newtype CircuitTW e m a = CircuitTW (EitherT e m a)
deriving (Functor, Applicative, Monad)
escape :: Monad m => a -> CircuitT m a
escape a = (CircuitTW . EitherT . return . Left) a
runCircuitT :: Functor m => CircuitT m a -> m a
runCircuitT (CircuitTW e) = unEither <$> runEitherT e
unEither :: Either a a -> a
unEither (Left a) = a
unEither (Right a) = a
| k-bx/circuitt | src/Control/Monad/Trans/CircuitT.hs | mit | 748 | 0 | 9 | 160 | 219 | 119 | 100 | 17 | 1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Tests.Sodium.Stream.Salsa20 where
import Tests.Sodium.Stream.Common
import Crypto.Sodium.Hash.Sha256
import Crypto.Sodium.SecureMem
import Crypto.Sodium.Stream.Salsa20
import qualified Data.ByteString as B
import Data.Maybe
import Test.Tasty
import Test.Tasty.HUnit
tests :: TestTree
tests = testGroup "Tests.Sodium.Stream.Salsa20" $
testVector :
mkTests salsa20
testVector :: TestTree -- corresponding to tests/stream2.c
-- and test/stream6.cpp from NaCl
testVector = testCase "vector" $ do
let secondkey = fromJust . mkKey . fromByteString . B.pack $
[ 0xdc,0x90,0x8d,0xda,0x0b,0x93,0x44,0xa9
, 0x53,0x62,0x9b,0x73,0x38,0x20,0x77,0x88
, 0x80,0xf3,0xce,0xb4,0x21,0xbb,0x61,0xb9
, 0x1c,0xbd,0x4c,0x3e,0x66,0x25,0x6c,0xe4]
noncesuffix = fromJust . mkNonce . B.pack $
[0x82,0x19,0xe0,0x03,0x6b,0x7a,0x0b,0x37]
output = stream secondkey noncesuffix 4194304
digest = fromJust . mkDigest . B.pack $
[0x66, 0x2b, 0x9d, 0x0e, 0x34, 0x63, 0x02, 0x91
, 0x56, 0x06, 0x9b, 0x12, 0xf9, 0x18, 0x69, 0x1a
, 0x98, 0xf7, 0xdf, 0xb2, 0xca, 0x03, 0x93, 0xc9
, 0x6b, 0xbf, 0xc6, 0xb1, 0xfb, 0xd6, 0x30, 0xa2]
digest @=? hash output
| dnaq/crypto-sodium | test/Tests/Sodium/Stream/Salsa20.hs | mit | 1,573 | 0 | 14 | 458 | 409 | 255 | 154 | 33 | 1 |
-- Gap in Primes
-- http://www.codewars.com/kata/561e9c843a2ef5a40c0000a4/
module Codewars.G964.GapInPrimes where
import Data.List (find)
import Control.Arrow ((&&&))
gap :: Integer -> Integer -> Integer -> Maybe (Integer, Integer)
gap g m n = find (\(a, b) -> b-a == g) . uncurry zip . (id &&& drop 1) . filter isPrime $ [m..n]
where isPrime n = all (\d -> n `mod` d /= 0) [2 .. floor . sqrt . fromIntegral $ n]
| gafiatulin/codewars | src/5 kyu/GapInPrimes.hs | mit | 421 | 0 | 13 | 80 | 182 | 101 | 81 | 6 | 1 |
module ChatCore.Types where
import Control.Applicative
import Control.Lens (makeClassy)
import Data.Aeson
import qualified Data.ByteString as B
import qualified Data.Text as T
type ChatNetworkName = T.Text
type ChatBufferName = T.Text
-- | Represents a message destination. This can be either a channel or a user.
type ChatDest = T.Text
-- | Represents a message source. This works similarly to Destination. It can be either a channel or a user.
type ChatSource = T.Text
-- | Type representing a user's nick.
type Nick = T.Text
-- | Type representing an IRC channel.
type ChatChan = T.Text
-- | A string identifying a user.
type UserName = T.Text
type ChatUserName = T.Text
type Password = B.ByteString
-- | Represents the status of a network connection.
data ConnectionStatus = Connected | Connecting | Disconnected
deriving (Eq, Show, Read)
instance FromJSON ConnectionStatus where
parseJSON (String "connected") = return Connected
parseJSON (String "connecting") = return Connecting
parseJSON (String "disconnected") = return Disconnected
parseJSON _ = empty
instance ToJSON ConnectionStatus where
toJSON (Connected) = String "connected"
toJSON (Connecting) = String "connecting"
toJSON (Disconnected) = String "disconnected"
-- | Basic information about a chat network.
data ChatNetworkInfo = ChatNetworkInfo
{ _networkName :: ChatNetworkName
, _networkStatus :: ConnectionStatus
, _networkUserNick :: Nick
} deriving (Show)
$(makeClassy ''ChatNetworkInfo)
instance FromJSON ChatNetworkInfo where
parseJSON (Object obj) = ChatNetworkInfo
<$> obj .: "name"
<*> obj .: "status"
<*> obj .: "user_nick"
parseJSON _ = error "Invalid chat network info. Must be an object."
instance ToJSON ChatNetworkInfo where
toJSON (ChatNetworkInfo name status userNick) = object
[ "name" .= name
, "status" .= status
, "user_nick" .= userNick
]
data ChatBufferInfo = ChatBufferInfo
{ _biName :: ChatBufferName
-- , _biType :: ChatBufferType
, _biActive :: Bool -- ^ True if the user is in this channel.
, _biUsers :: [Nick]
} deriving (Show)
| Forkk/ChatCore | ChatCore/Types.hs | mit | 2,266 | 0 | 11 | 537 | 458 | 258 | 200 | -1 | -1 |
-- Ben Eggers
main = putStrLn "Hi, ma!" | BenedictEggers/99problems | Main.hs | mit | 40 | 0 | 5 | 8 | 10 | 5 | 5 | 1 | 1 |
{-# LANGUAGE FlexibleContexts #-}
import System.IO
import Control.Monad.State
import Control.Monad.Writer
import Data.Char (chr, ord, toUpper)
import Data.List (find)
import Data.Ord
-- States of Machine
data MyState = STATE_ERR
| STATE_S0
| STATE_S1
| STATE_I0
| STATE_T1
| STATE_T2
| STATE_T3
| STATE_T4
| STATE_T5
-- Type of action (transaction function)
type ActionFunc = (MyState, String) -> Char -> (MyState, String)
-- Convert MyState to String
myStateToStr :: MyState -> String
myStateToStr STATE_ERR = "STATE_ERR"
myStateToStr STATE_S0 = "STATE_S0"
myStateToStr STATE_S1 = "STATE_S1"
myStateToStr STATE_I0 = "STATE_I0"
myStateToStr STATE_T1 = "STATE_T1"
myStateToStr STATE_T2 = "STATE_T2"
myStateToStr STATE_T3 = "STATE_T3"
myStateToStr STATE_T4 = "STATE_T4"
myStateToStr STATE_T5 = "STATE_T5"
-- There are the terminals, and theirs actions
terminals :: [(Char, ActionFunc)]
terminals = [ ('+', actionS),
('-', actionS),
('.', actionP),
('0', actionZ)
] ++
[((chr (49 + x)), actionD) | x <- [0..8]]
-- Empty action
actionE :: (MyState, String) -> Char -> (MyState, String)
actionE a _ = a
-- S action
actionS :: (MyState, String) -> Char -> (MyState, String)
actionS (STATE_S0, str) c = (STATE_S1, str)
actionS (_,_) _ = myFail
-- P action
actionP :: (MyState, String) -> Char -> (MyState, String)
actionP (STATE_S1, str) c = (STATE_I0, ('0':[c]))
actionP (STATE_T2, str) c = (STATE_T3, str ++ [c])
actionP (STATE_T4, str) c = (STATE_T5, str ++ [c])
actionp (_,_) _ = myFail
-- Z action
actionZ :: (MyState, String) -> Char -> (MyState, String)
actionZ (STATE_S1, str) c = (STATE_T2, str ++ [c])
actionZ (_,_) _ = myFail
-- D action
actionD :: (MyState, String) -> Char -> (MyState, String)
actionD (STATE_I0, str) c = (STATE_T1, str ++ [c])
actionD (STATE_S1, str) c = (STATE_T4, str ++ [c]) --actionD (STATE_S1, str) c = (STATE_T4, str ++ [c])
actionD (STATE_T1, str) c = (STATE_T1, str ++ [c])
actionD (STATE_T3, str) c = (STATE_T3, str ++ [c])
actionD (STATE_T4, str) c = (STATE_T4, str ++ [c])
actionD (STATE_T5, str) c = (STATE_T5, str ++ [c])
actionD (_,_) _ = myFail
-- Fail action
actionFail :: (MyState, String) -> Char -> (MyState, String)
actionFail _ _ = myFail
-- Fail pair
myFail :: (MyState, String)
myFail = (STATE_ERR, "FAIL")
-- Check the final state
isOk :: MyState -> Bool
isOk STATE_ERR = False
isOk STATE_S0 = False
isOk STATE_S1 = False
isOk STATE_I0 = False
isOk _ = True
-- This function calculate the next state, and the output string.
stateMachine :: (MyState, String) -> Char -> (MyState, String)
stateMachine (s, str) c = nextState c
where
nextState :: Char -> (MyState, String)
nextState c = (clearAction (find (\(x, _) -> c == x) terminals)) (s, str) c
where
clearAction :: Maybe (Char, ActionFunc) -> ActionFunc
clearAction (Just (_, f)) = f
clearAction Nothing = actionFail
{-
I have to create this function, because if the input is only 1..9, the program has to append
the ".0" for the calculated string.
-}
checkEnd :: (MyState, String) -> (MyState, String)
{-
This is the logical:
stateMachine (stateMachine (STATE_T4, str) '.') '0'
But the '0' is not digit therefore we have to hack. -}
checkEnd (STATE_T4, str) = actionD (stateMachine (STATE_T4, str) '.') '0'
checkEnd (STATE_I0, _) = myFail
checkEnd (STATE_S0, _) = myFail
checkEnd (STATE_S1, _) = myFail
checkEnd cs = cs
-- This fuction calculate the result
process :: String -> (MyState, String)
process str = foldl stateMachine (firstTerm str, "") str
where
firstTerm :: String -> MyState
firstTerm (c:_)
| c == '+' || c == '-' = STATE_S0
| otherwise = STATE_S1
-- Tis is the main function. The program reads from STDIN and write to STDOUT.
main =
do eof <- isEOF
if eof
then return()
else do inStr <- getLine
putStr (inStr++"\t")
let (s, out) = checkEnd (process inStr)
if isOk s
then putStr "OK "
else putStr ""
--putStr (" " ++ (myStateToStr s) ++ " ")
putStrLn out
main
| zporky/langs-and-paradigms | projects/NT76QQ/haskell/state_machine.hs | mit | 4,461 | 0 | 15 | 1,228 | 1,379 | 787 | 592 | 96 | 3 |
module Stage ( loadObjects ) where
import GameObject
import Data.Complex
import Data.Array
-- loadObjects :: [GameObject]
-- a list of objects that are to newly loaded at this frame.
loadObjects clock isEasy vicViper gameObjects = if hp vicViper<=0 then [] else (case clock of
-- stage layout.
-- just like old BASIC code.
150 -> [freshTurnGearSquad{position=340:+(180)}]
300 -> [freshTurnGearSquad{position=340:+(-180)}]
400 -> [freshTurnGearSquad{position=340:+(180)}]
500 -> [freshTurnGearSquad{position=340:+(-180)}]
633 -> map (\y -> freshStalk{position = 340:+y,hasItem=False }) [-120,120] ++ [freshStalk{position = 340:+0,hasItem=isEasy}]
666 -> map (\y -> freshStalk{position = 340:+y,hasItem=isEasy}) [-130,130] ++ [freshStalk{position = 340:+0,hasItem=False}]
700 -> map (\y -> freshStalk{position = 340:+y,hasItem=False }) [-140,140] ++ [freshStalk{position = 340:+0,hasItem=True}]
733 -> map (\y -> freshStalk{position = 340:+y,hasItem=isEasy}) [-150,150] ++ [freshStalk{position = 340:+0,hasItem=False}]
900 -> [freshTurnGearSquad{position=340:+(-180)}]
1000 -> [freshTurnGearSquad{position=340:+(180)}]
1050 -> map (\y -> freshStalk{position = 340:+y}) [-135,0,135]
1250 -> map (\y -> freshFlyer{position = 340:+y}) [-150,-100]
1300 -> map (\y -> freshFlyer{position = 340:+y,hasItem=True}) [100,150]
1100 -> [freshTurnGearSquad{position=340:+(-180)},freshTurnGearSquad{position=340:+(180)}]
1400 -> [(freshGrashia (-1)){position = 340:+(-185)},(freshGrashia 1){position = 340:+(185)}]
1450 -> [(freshGrashia (-1)){position = 340:+(-185),hasItem=True},(freshGrashia 1){position = 340:+(185)}]
1550 -> [(freshScrambleHatch (-1)){position = 360:+(-200)},(freshScrambleHatch (1)){position = 360:+(200)}]
1700 -> [(freshVolcano (-1)){position=479:+(-200)}]
1900 -> map (\(g,x) -> (freshDucker g){position=x:+g*100}) $ [(1,340),(-1,340)] ++ if not isEasy then [(1,-340),(-1,-340)] else []
1940 -> [(freshLandRoll (1)){position = 340:+(185)}]
1965 -> [(freshLandRoll (1)){position = 340:+(185)}]
1990 -> [(freshLandRoll (1)){position = 340:+(185)}]
2000 -> [(freshGrashia (-1)){position = 340:+(-185)},(freshDucker (-1)){position=(-340):+(-185)}]
2033 -> [(freshGrashia (-1)){position = 340:+(-185)},(freshDucker 1){position=(-340):+(185)}]
2100 -> [(freshScrambleHatch (-1)){position = 360:+(-200)}]
2200 -> [(freshVolcano 1){position=479:+(200)}]
2250 -> map (\y -> freshStalk{position = 340:+y}) [-150,0,150]
2339 -> [(freshGrashia (1)){position = 340:+35},(freshGrashia (-1)){position = 340:+(-185)}]
2433 -> map (\y -> freshFlyer{position = 340:+y}) [-150,0]
2466 -> map (\y -> freshFlyer{position = 340:+y}) [-150,0]
2499 -> map (\y -> freshFlyer{position = 340:+y}) [-150,0]
2620 -> [(freshDucker 1){position=(-340):+(200)}]
2640 -> [(freshDucker 1){position=(-340):+(200),hasItem=True}]
2800 -> map (\(g,x) -> (freshJumper g){position=x:+g*100,velocity=((-3)*signum x):+0}) $ [(1,340),(-1,340)] ++ if not isEasy then [(1,-340),(-1,-340)] else []
2999 -> [(freshVolcano 2){position=479:+(20),velocity=(0:+(-0.5))},(freshVolcano (-2)){position=479:+(-20),velocity=(0:+(0.5))}]
3200 -> concat $ map (\x -> [freshLandScapeGround{position=(479-x):+220},freshLandScapeGround{position=(479-x):+(-220)}]) [320,640]
3210 -> [freshFlyer{position = 340:+150},freshFlyer{position = 340:+100,hasItem=True}]
3290 -> [freshFlyer{position = 340:+(-150)},freshFlyer{position = 340:+(-100),hasItem=True}]
3350 -> map (\g -> (freshLandRoll (g)){position = 340:+(g*185)}) [1,-1] ++ if isRevival then [] else [(freshJumper (1)){position = (-340):+150,velocity=3:+0}]
3400 -> map (\g -> (freshLandRoll (g)){position = 340:+(g*185)}) [1,-1] ++ if isRevival then [] else [(freshJumper (-1)){position = (-340):+(-150),velocity=3:+0}]
3450 -> map (\g -> (freshLandRoll (g)){position = 340:+(g*185)}) [1,-1]
3500 -> [(freshVolcano (-1)){position=479:+(-200)}]
3579 -> [(freshGrashia (-1)){position = 340:+(-100)}]
3639 -> [(freshGrashia (-1)){position = 340:+(-40)}]
3699 -> [(freshGrashia (-1)){position = 340:+(-100)}]
3501 -> [(freshScrambleHatch (1)){position = 360:+(200)}]
3600 -> [(freshScrambleHatch (1)){position = 360:+(200)}]
3582 -> [(freshDucker (-1)){position=(340):+(-200)}]
3612 -> [(freshDucker (-1)){position=(340):+(-200)}]
3642 -> [(freshDucker (-1)){position=(340):+(-200)}]
3672 -> [(freshDucker (-1)){position=(340):+(-200)}]
3702 -> [(freshDucker (-1)){position=(340):+(-200),hasItem=True}]
3703 -> [(freshLandRoll (1)){position=(340):+(185),hasItem=True}]
3820 -> map (\y -> freshFlyer{position = 340:+y}) [-100,100]
3840 -> map (\y -> freshFlyer{position = 340:+y}) [-110,110]
3860 -> map (\y -> freshFlyer{position = 340:+y}) [-120,120]
3880 -> map (\y -> freshFlyer{position = 340:+y,hasItem = isEasy}) [-130,130]
3900 -> [freshTurnGearSquad{position=340:+0}]
4000 -> [(freshTable 1){position=450:+200}]
4033 -> [(freshGrashia (1)){position = 340:+(185)}]
4066 -> [(freshGrashia (1)){position = 340:+(185)}]
4060 -> [(freshGrashia (1)){position = 340:+(40)}]
4110 -> [(freshGrashia (1)){position = 340:+(40)}]
4160 -> [(freshGrashia (1)){position = 340:+(40)}]
4166 -> [(freshGrashia (1)){position = 340:+(185),hasItem=True}]
4200 -> [(freshGrashia (1)){position = 340:+(185),hasItem=True}]
4233 -> [(freshGrashia (1)){position = 340:+(185),hasItem=False}]
4266 -> [(freshGrashia (1)){position = 340:+(185),hasItem=False}]
4150 -> [freshLandScapeGround{position=479:+(-180)}]
4203 -> [(freshJumper (-1)){position = 340:+(-180)}]
4273 -> [(freshJumper (-1)){position = 340:+(-180)}]
4343 -> [(freshJumper (-1)){position = 340:+(-180)}]
4490 -> [(freshTable (-1)){position=450:+(-200)}]
4500 -> [(freshDucker (-1)){position=340:+0}]
4520 -> [(freshDucker (-1)){position=340:+0}]
4540 -> [(freshDucker (-1)){position=340:+0}]
4560 -> [(freshGrashia (-1)){position = 340:+(-185)}]
4580 -> [(freshScrambleHatch (-1)){position = 360:+(-50)}]
4603 -> if isRevival then [] else [(freshDucker 1){position = (-340):+0},(freshJumper (1)){position = (-340):+150,velocity=3:+0}]
4663 -> [(freshDucker 1){position = (-340):+0}]++if isEasy then [] else [(freshJumper (1)){position = (-340):+150,velocity=3:+0}]
4723 -> if isRevival then [] else [(freshDucker 1){position = (-340):+0},(freshJumper (1)){position = (-340):+150,velocity=3:+0}]
4783 -> [(freshDucker 1){position = (-340):+0}]++if isEasy then [] else [(freshJumper (1)){position = (-340):+150,velocity=3:+0}]
4680 -> [(freshScrambleHatch (-1)){position = 360:+(-200)}]
4900 -> map (\y -> freshFlyer{position = 340:+y}) [-100,100]
4930 -> map (\y -> freshFlyer{position = 340:+y}) [-66,66]
4960 -> map (\y -> freshFlyer{position = 340:+y}) [-33,33]
4990 -> map (\y -> freshFlyer{position = 340:+y,hasItem=True}) [0]
5041 -> [(freshDucker (-1)){position = 340:+(-180)}]
5061 -> [(freshDucker (-1)){position = 340:+(-180)}]
5081 -> [(freshDucker (-1)){position = 340:+(-180)}]
5101 -> if isRevival then [] else ([(freshDucker (-1)){position = 340:+(-180)}] ++ if isEasy then [] else [(freshDucker (1)){position = (-340):+(180)}])
5121 -> if isRevival then [] else ([(freshDucker (-1)){position = 340:+(-180)}] ++ if isEasy then [] else [(freshDucker (1)){position = (-340):+(180)}])
5141 -> if isRevival then [] else ([(freshDucker (-1)){position = 340:+(-180)}] ++ if isEasy then [] else [(freshDucker (1)){position = (-340):+(180)}])
5261 -> [freshTurnGearSquad{position=340:+(-150)}]
5364 -> [(freshScrambleHatch (-1)){position = 360:+(-200)}]
5151 -> [(freshDucker (-1)){position = (-340):+(0)}]
5181 -> [(freshDucker (-1)){position = (-340):+(0)}]
5211 -> [(freshDucker (-1)){position = (-340):+(0)}]
5241 -> [(freshDucker (-1)){position = (-340):+(0)}]
5321 -> [(freshDucker (-1)){position = 340:+150}] ++ if isEasy then [] else [(freshJumper (1)){position = (-340):+(180),velocity = 3:+0}]
5361 -> [(freshDucker (-1)){position = 340:+150}]
5401 -> [(freshDucker (-1)){position = 340:+150}]
5441 -> [(freshDucker (-1)){position = 340:+150}] ++ if isEasy then [] else map (\y -> freshStalk{position = 340:+y}) [-140,-70,0]
5461 -> [(freshDucker (-1)){position = 340:+150}]
5451 -> [(freshGrashia (-1)){position = 340:+160,hasItem=True}]
5060 -> [(freshVolcano (-1)){position = 480:+(-100)}]
5200 -> [(freshGrashia (-1)){position = 340:+70}] ++ [(freshDucker (-1)){position = 340:+70}]
5235 -> [(freshGrashia (-1)){position = 340:+40}] ++ [(freshDucker (-1)){position = 340:+40}]
5258 -> [(freshGrashia (-1)){position = 340:+10}] ++ [(freshDucker (-1)){position = 340:+10}]
5285 -> [(freshGrashia (-1)){position = 340:+(-20)}] ++ [(freshDucker (-1)){position = 340:+(-20)}]
5316 -> [(freshGrashia (-1)){position = 340:+(-50)}] ++ [(freshDucker (-1)){position = 340:+(-50)}]
5310 -> [(freshVolcano (1)){position = 480:+(150)}]
5450 -> [(freshGrashia (1)){position = 340:+(-20)}]
5485 -> [(freshGrashia (1)){position = 340:+10}]
5508 -> [(freshGrashia (1)){position = 340:+40}]
5535 -> [(freshGrashia (1)){position = 340:+70}]
5566 -> [(freshGrashia (1)){position = 340:+100}]
5811 -> [(freshDucker (-1)){position = (-340):+0}]
5841 -> [(freshDucker (-1)){position = (-340):+0}]
5871 -> [(freshDucker (-1)){position = (-340):+0}]
5901 -> [(freshDucker (-1)){position = (-340):+0}]
6001 -> if isEasy then [(freshDucker (-1)){position = (-340):+150}] else []
6031 -> if isEasy then [(freshDucker (-1)){position = (-340):+150}] else []
6061 -> if isEasy then [(freshDucker (-1)){position = (-340):+150}] else []
6091 -> if isEasy then [(freshDucker (-1)){position = (-340):+150}] else []
5800 -> [(freshScrambleHatch (-1)){position = 360:+(-200)},(freshScrambleHatch (1)){position = 360:+(200)}]
5950 -> [(freshScrambleHatch (-1)){position = 360:+(-200)},(freshScrambleHatch (1)){position = 360:+(200)}]
6100 -> [(freshScrambleHatch (-1)){position = 360:+(-200)},(freshScrambleHatch (1)){position = 360:+(200)}]
6116 -> [freshSabbathicAgent]
_ -> []) ++
(if(optionCount < powerUpLevels vicViper!4) then
[freshOption{position=position vicViper, optionTag = optionCount+1}]
else []) ++
(if (clock `mod` 320 == 0 && clock>=1280 && clock <= 6400) then
[freshLandScapeGround{position=479:+220},freshLandScapeGround{position=479:+(-220)}]
else [])
where
optionCount = length $ filter (\o -> case o of
Option{} -> True
_ -> False) gameObjects
isRevival = optionCount <= 0
| keqh/Monadius_rewrite | Monadius/Stage.hs | gpl-2.0 | 10,811 | 0 | 23 | 1,710 | 6,364 | 3,657 | 2,707 | 145 | 154 |
{-# OPTIONS -w -O0 #-}
{- |
Module : COL/ATC_COL.der.hs
Description : generated Typeable, ShATermConvertible instances
Copyright : (c) DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : non-portable(overlapping Typeable instances)
Automatic derivation of instances via DrIFT-rule Typeable, ShATermConvertible
for the type(s):
'COL.AS_COL.COL_SIG_ITEM'
'COL.COLSign.COLSign'
-}
{-
Generated by 'genRules' (automatic rule generation for DrIFT). Don't touch!!
dependency files:
COL/AS_COL.hs
COL/COLSign.hs
-}
module COL.ATC_COL () where
import ATerm.Lib
import CASL.AS_Basic_CASL
import CASL.ATC_CASL
import COL.AS_COL
import COL.COLSign
import Common.AS_Annotation
import Common.Id
import Data.Typeable
import qualified Data.Map as Map
import qualified Data.Set as Set
{-! for COL.AS_COL.COL_SIG_ITEM derive : Typeable !-}
{-! for COL.COLSign.COLSign derive : Typeable !-}
{-! for COL.AS_COL.COL_SIG_ITEM derive : ShATermConvertible !-}
{-! for COL.COLSign.COLSign derive : ShATermConvertible !-}
-- Generated by DrIFT, look but don't touch!
_tcCOL_SIG_ITEMTc :: TyCon
_tcCOL_SIG_ITEMTc = mkTyCon "COL.AS_COL.COL_SIG_ITEM"
instance Typeable COL_SIG_ITEM where
typeOf _ = mkTyConApp _tcCOL_SIG_ITEMTc []
instance ShATermConvertible COL_SIG_ITEM where
toShATermAux att0 xv = case xv of
Constructor_items a b -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
return $ addATerm (ShAAppl "Constructor_items" [a', b'] []) att2
Observer_items a b -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
return $ addATerm (ShAAppl "Observer_items" [a', b'] []) att2
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "Constructor_items" [a, b] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
(att2, Constructor_items a' b') }}
ShAAppl "Observer_items" [a, b] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
(att2, Observer_items a' b') }}
u -> fromShATermError "COL_SIG_ITEM" u
instance ShATermConvertible COLSign where
toShATermAux att0 xv = case xv of
COLSign a b -> do
(att1, a') <- toShATerm' att0 a
(att2, b') <- toShATerm' att1 b
return $ addATerm (ShAAppl "COLSign" [a', b'] []) att2
fromShATermAux ix att0 = case getShATerm ix att0 of
ShAAppl "COLSign" [a, b] _ ->
case fromShATerm' a att0 of
{ (att1, a') ->
case fromShATerm' b att1 of
{ (att2, b') ->
(att2, COLSign a' b') }}
u -> fromShATermError "COLSign" u
_tcCOLSignTc :: TyCon
_tcCOLSignTc = mkTyCon "COL.COLSign.COLSign"
instance Typeable COLSign where
typeOf _ = mkTyConApp _tcCOLSignTc []
| nevrenato/Hets_Fork | COL/ATC_COL.hs | gpl-2.0 | 2,897 | 0 | 16 | 616 | 708 | 376 | 332 | 58 | 1 |
import qualified Patat.Main
main :: IO ()
main = Patat.Main.main
| jaspervdj/patat | src/Main.hs | gpl-2.0 | 66 | 0 | 6 | 11 | 25 | 14 | 11 | 3 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Model.BoardInfo
( BoardInfo (..)
) where
import Data.Aeson
import GHC.Generics
import Test.QuickCheck
import Model.Event
data BoardInfo = BoardInfo
{ maxBoardX :: Float
, maxBoardY :: Float
, streamDelay :: Float
, turnDeltaTime :: Float
, networkLatency :: Float
, startTime :: Float
, endTime :: Float
, events :: [Event]
} deriving (Show, Eq, Generic)
instance FromJSON BoardInfo
instance ToJSON BoardInfo
instance Arbitrary BoardInfo where
arbitrary = BoardInfo <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
| massimo-zaniboni/netrobots | robot_examples/haskell-servant/rest_api/lib/Model/BoardInfo.hs | gpl-3.0 | 806 | 0 | 13 | 158 | 174 | 103 | 71 | 25 | 0 |
module MiniMiniLogoSem where
import MiniMiniLogo
import Render
--
-- * Semantics of MiniMiniLogo
--
-- NOTE:
-- * MiniMiniLogo.hs defines the abstract syntax of MiniMiniLogo and some
-- functions for generating MiniMiniLogo programs. It contains the type
-- definitions for Mode, Cmd, and Prog.
-- * Render.hs contains code for rendering the output of a MiniMiniLogo
-- program in HTML5. It contains the types definitions for Point and Line.
-- | A type to represent the current state of the pen.
type State = (Mode,Point)
-- | The initial state of the pen.
start :: State
start = (Up,(0,0))
-- | A function that renders the image to HTML. Only works after you have
-- implemented `prog`. Applying `draw` to a MiniMiniLogo program will
-- produce an HTML file named MiniMiniLogo.html, which you can load in
-- your browswer to view the rendered image.
draw :: Prog -> IO ()
draw p = let (_,ls) = prog p start in toHTML ls
-- Semantic domains:
-- * Cmd: State -> (State, Maybe Line)
-- * Prog: State -> (State, [Line])
-- | Semantic function for Cmd.
--
-- >>> cmd (Pen Down) (Up,(2,3))
-- ((Down,(2,3)),Nothing)
--
-- >>> cmd (Pen Up) (Down,(2,3))
-- ((Up,(2,3)),Nothing)
--
-- >>> cmd (Move 4 5) (Up,(2,3))
-- ((Up,(4,5)),Nothing)
--
-- >>> cmd (Move 4 5) (Down,(2,3))
-- ((Down,(4,5)),Just ((2,3),(4,5)))
--
cmd :: Cmd -> State -> (State, Maybe Line)
cmd (Pen pen_state) (_, new_point) = ((pen_state, new_point), Nothing)
cmd (Move mx my) (Up, (start_point)) = ((Up, (mx, my)), Nothing)
cmd (Move mx my) (Down, (start_x, start_y)) = ((Down, (mx, my)), Just ((start_x, start_y),(mx, my)))
-- | Semantic function for Prog.
--
-- >>> prog (nix 10 10 5 7) start
-- ((Down,(15,10)),[((10,10),(15,17)),((10,17),(15,10))])
--
-- >>> prog (steps 2 0 0) start
-- ((Down,(2,2)),[((0,0),(0,1)),((0,1),(1,1)),((1,1),(1,2)),((1,2),(2,2))])
prog :: Prog -> State -> (State, [Line])
prog [] prog_state = (prog_state, [])
prog prog_list start_state = progLineListHelper prog_list (start_state, [])
-- Helper function to handle keeping track of the line list as we move through the program elements
progLineListHelper :: Prog -> (State, [Line]) -> (State, [Line])
progLineListHelper [] state_and_line_list = state_and_line_list
progLineListHelper (progs_head:progs_tail) (initial_state, initial_line_list) =
let (new_state, new_line_list) = cmd progs_head initial_state in
case new_line_list of
Just new_line_list -> progLineListHelper progs_tail (new_state, initial_line_list ++ [new_line_list])
Nothing -> progLineListHelper progs_tail (new_state, initial_line_list)
--
-- * Extra credit
--
-- | This should be a MiniMiniLogo program that draws an amazing picture.
-- Add as many helper functions as you want.
amazing :: Prog
amazing = undefined
| caperren/Archives | OSU Coursework/CS 381 - Programming Language Fundamentals/Homework 3/MiniMiniLogoSem.perrenc.hs | gpl-3.0 | 2,841 | 0 | 13 | 526 | 519 | 314 | 205 | 24 | 2 |
module IntelBrightness.Core (
maxBrightness,
setBrightness
) where
readInt :: String -> Int
readInt = read
maxBrightness :: String -> IO Int
maxBrightness = fmap readInt . readFile . flip (++) "/max_brightness"
setBrightness :: (Show a) => String -> a -> IO ()
setBrightness path nb = writeFile (path ++ "/brightness") $ show nb
| mcoffin/intel-brightness | IntelBrightness/Core.hs | gpl-3.0 | 344 | 0 | 9 | 68 | 117 | 62 | 55 | 9 | 1 |
-- count the nodes of a n-ary tree
data Tree a = Node a [Tree a]
p70 :: Tree a -> Int
p70 (Node x []) = 1
p70 (Node x xs) = 1 + p70' xs where
p70' [] = 0
p70' (x:xs) = p70 x + p70' xs
| yalpul/CENG242 | H99/70-73/p70c.hs | gpl-3.0 | 202 | 0 | 9 | 68 | 110 | 55 | 55 | 6 | 2 |
import Math.NumberTheory.Moduli ( powerMod )
import Math.NumberTheory.Primes.Sieve ( sieveFrom )
main = let x = 10^9; y = 10^7; n = 10^15::Int in print $
sum $ map (a n) $ takeWhile (<=(x + y)) $ sieveFrom x
where
f (u, v, w) (x, y, _) = (mod (u * x + 13 * v * y) w, mod (u * y + v * x) w, w)
a n p = mod ((2 * (\(x, _, _) -> x) ((\t@(_, _, w) n->
(\(_, v, _) -> v) $ until (\(i, _, _) -> i <= 0) (\(i, u, v) ->
(div i 2, if odd i then f u v else u, f v v)) (n, (1, 0, w), t))
(mod (div (11 * (p + 1)) 2) p, mod (div (3 * (p + 1)) 2) p, p) $
powerMod 2 (n - 1) (p * p - 1)) - 5) * powerMod 6 (-1::Int) p) p
| kkmonlee/Project-Euler-Solutions | Haskell/p492.hs | gpl-3.0 | 680 | 0 | 25 | 233 | 499 | 279 | 220 | 10 | 2 |
{-# 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.AdSense.AdUnits.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- List all ad units in the specified ad client for this AdSense account.
--
-- /See:/ <https://developers.google.com/adsense/management/ AdSense Management API Reference> for @adsense.adunits.list@.
module Network.Google.Resource.AdSense.AdUnits.List
(
-- * REST Resource
AdUnitsListResource
-- * Creating a Request
, adUnitsList
, AdUnitsList
-- * Request Lenses
, aulIncludeInactive
, aulAdClientId
, aulPageToken
, aulMaxResults
) where
import Network.Google.AdSense.Types
import Network.Google.Prelude
-- | A resource alias for @adsense.adunits.list@ method which the
-- 'AdUnitsList' request conforms to.
type AdUnitsListResource =
"adsense" :>
"v1.4" :>
"adclients" :>
Capture "adClientId" Text :>
"adunits" :>
QueryParam "includeInactive" Bool :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "alt" AltJSON :> Get '[JSON] AdUnits
-- | List all ad units in the specified ad client for this AdSense account.
--
-- /See:/ 'adUnitsList' smart constructor.
data AdUnitsList =
AdUnitsList'
{ _aulIncludeInactive :: !(Maybe Bool)
, _aulAdClientId :: !Text
, _aulPageToken :: !(Maybe Text)
, _aulMaxResults :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AdUnitsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aulIncludeInactive'
--
-- * 'aulAdClientId'
--
-- * 'aulPageToken'
--
-- * 'aulMaxResults'
adUnitsList
:: Text -- ^ 'aulAdClientId'
-> AdUnitsList
adUnitsList pAulAdClientId_ =
AdUnitsList'
{ _aulIncludeInactive = Nothing
, _aulAdClientId = pAulAdClientId_
, _aulPageToken = Nothing
, _aulMaxResults = Nothing
}
-- | Whether to include inactive ad units. Default: true.
aulIncludeInactive :: Lens' AdUnitsList (Maybe Bool)
aulIncludeInactive
= lens _aulIncludeInactive
(\ s a -> s{_aulIncludeInactive = a})
-- | Ad client for which to list ad units.
aulAdClientId :: Lens' AdUnitsList Text
aulAdClientId
= lens _aulAdClientId
(\ s a -> s{_aulAdClientId = a})
-- | A continuation token, used to page through ad units. To retrieve the
-- next page, set this parameter to the value of \"nextPageToken\" from the
-- previous response.
aulPageToken :: Lens' AdUnitsList (Maybe Text)
aulPageToken
= lens _aulPageToken (\ s a -> s{_aulPageToken = a})
-- | The maximum number of ad units to include in the response, used for
-- paging.
aulMaxResults :: Lens' AdUnitsList (Maybe Int32)
aulMaxResults
= lens _aulMaxResults
(\ s a -> s{_aulMaxResults = a})
. mapping _Coerce
instance GoogleRequest AdUnitsList where
type Rs AdUnitsList = AdUnits
type Scopes AdUnitsList =
'["https://www.googleapis.com/auth/adsense",
"https://www.googleapis.com/auth/adsense.readonly"]
requestClient AdUnitsList'{..}
= go _aulAdClientId _aulIncludeInactive _aulPageToken
_aulMaxResults
(Just AltJSON)
adSenseService
where go
= buildClient (Proxy :: Proxy AdUnitsListResource)
mempty
| brendanhay/gogol | gogol-adsense/gen/Network/Google/Resource/AdSense/AdUnits/List.hs | mpl-2.0 | 4,134 | 0 | 16 | 969 | 571 | 335 | 236 | 86 | 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.GamesConfiguration.AchievementConfigurations.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns a list of the achievement configurations in this application.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Publishing API Reference> for @gamesConfiguration.achievementConfigurations.list@.
module Network.Google.Resource.GamesConfiguration.AchievementConfigurations.List
(
-- * REST Resource
AchievementConfigurationsListResource
-- * Creating a Request
, achievementConfigurationsList
, AchievementConfigurationsList
-- * Request Lenses
, aclXgafv
, aclUploadProtocol
, aclAccessToken
, aclUploadType
, aclApplicationId
, aclPageToken
, aclMaxResults
, aclCallback
) where
import Network.Google.GamesConfiguration.Types
import Network.Google.Prelude
-- | A resource alias for @gamesConfiguration.achievementConfigurations.list@ method which the
-- 'AchievementConfigurationsList' request conforms to.
type AchievementConfigurationsListResource =
"games" :>
"v1configuration" :>
"applications" :>
Capture "applicationId" Text :>
"achievements" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "pageToken" Text :>
QueryParam "maxResults" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] AchievementConfigurationListResponse
-- | Returns a list of the achievement configurations in this application.
--
-- /See:/ 'achievementConfigurationsList' smart constructor.
data AchievementConfigurationsList =
AchievementConfigurationsList'
{ _aclXgafv :: !(Maybe Xgafv)
, _aclUploadProtocol :: !(Maybe Text)
, _aclAccessToken :: !(Maybe Text)
, _aclUploadType :: !(Maybe Text)
, _aclApplicationId :: !Text
, _aclPageToken :: !(Maybe Text)
, _aclMaxResults :: !(Maybe (Textual Int32))
, _aclCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AchievementConfigurationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'aclXgafv'
--
-- * 'aclUploadProtocol'
--
-- * 'aclAccessToken'
--
-- * 'aclUploadType'
--
-- * 'aclApplicationId'
--
-- * 'aclPageToken'
--
-- * 'aclMaxResults'
--
-- * 'aclCallback'
achievementConfigurationsList
:: Text -- ^ 'aclApplicationId'
-> AchievementConfigurationsList
achievementConfigurationsList pAclApplicationId_ =
AchievementConfigurationsList'
{ _aclXgafv = Nothing
, _aclUploadProtocol = Nothing
, _aclAccessToken = Nothing
, _aclUploadType = Nothing
, _aclApplicationId = pAclApplicationId_
, _aclPageToken = Nothing
, _aclMaxResults = Nothing
, _aclCallback = Nothing
}
-- | V1 error format.
aclXgafv :: Lens' AchievementConfigurationsList (Maybe Xgafv)
aclXgafv = lens _aclXgafv (\ s a -> s{_aclXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
aclUploadProtocol :: Lens' AchievementConfigurationsList (Maybe Text)
aclUploadProtocol
= lens _aclUploadProtocol
(\ s a -> s{_aclUploadProtocol = a})
-- | OAuth access token.
aclAccessToken :: Lens' AchievementConfigurationsList (Maybe Text)
aclAccessToken
= lens _aclAccessToken
(\ s a -> s{_aclAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
aclUploadType :: Lens' AchievementConfigurationsList (Maybe Text)
aclUploadType
= lens _aclUploadType
(\ s a -> s{_aclUploadType = a})
-- | The application ID from the Google Play developer console.
aclApplicationId :: Lens' AchievementConfigurationsList Text
aclApplicationId
= lens _aclApplicationId
(\ s a -> s{_aclApplicationId = a})
-- | The token returned by the previous request.
aclPageToken :: Lens' AchievementConfigurationsList (Maybe Text)
aclPageToken
= lens _aclPageToken (\ s a -> s{_aclPageToken = a})
-- | The maximum number of resource configurations to return in the response,
-- used for paging. For any response, the actual number of resources
-- returned may be less than the specified \`maxResults\`.
aclMaxResults :: Lens' AchievementConfigurationsList (Maybe Int32)
aclMaxResults
= lens _aclMaxResults
(\ s a -> s{_aclMaxResults = a})
. mapping _Coerce
-- | JSONP
aclCallback :: Lens' AchievementConfigurationsList (Maybe Text)
aclCallback
= lens _aclCallback (\ s a -> s{_aclCallback = a})
instance GoogleRequest AchievementConfigurationsList
where
type Rs AchievementConfigurationsList =
AchievementConfigurationListResponse
type Scopes AchievementConfigurationsList =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient AchievementConfigurationsList'{..}
= go _aclApplicationId _aclXgafv _aclUploadProtocol
_aclAccessToken
_aclUploadType
_aclPageToken
_aclMaxResults
_aclCallback
(Just AltJSON)
gamesConfigurationService
where go
= buildClient
(Proxy ::
Proxy AchievementConfigurationsListResource)
mempty
| brendanhay/gogol | gogol-games-configuration/gen/Network/Google/Resource/GamesConfiguration/AchievementConfigurations/List.hs | mpl-2.0 | 6,279 | 0 | 20 | 1,447 | 887 | 512 | 375 | 130 | 1 |
-- Canvas.Hs, control javascript canvas with Haskell
-- Copyright (C) 2013, Lennart Buit, Joost van Doorn, Pim Jager, Martijn Roo,
-- Thijs Scheepers
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
-- USA
{-# LANGUAGE OverloadedStrings #-}
{- |
This module exposes functions to search for directories and files and serve those files
-}
module CanvasHs.Server.Static where
import Paths_canvashs
import Data.Maybe
import Data.List
import Data.List.Split
import System.Directory
import qualified Network.Wai as WAI
import Network.HTTP.Types (status200)
import qualified Data.Text as T
import qualified Blaze.ByteString.Builder as BL (copyByteString)
import qualified Data.ByteString as BS
-- Files to be ignored
ignoreFiles :: [String]
ignoreFiles = ["..","."]
-- | builds WAI responses for requests for static files with a WAI response containing the requested file
-- and its content/type, if the file is in the provided files list
httpget :: [([String], BS.ByteString)] -> WAI.Application
httpget files req = return $ do WAI.ResponseBuilder status200 [("Content-Type", encoding)] $ BL.copyByteString page
where
(encoding, page) | (WAI.pathInfo req) == [] = ("text/html", snd $ files !! 0)
| file == Nothing = ("text/html", "Error 404")
| hasExtension "css" = ("text/css", (fromJust file))
| hasExtension "html" = ("text/html", (fromJust file))
| hasExtension "jpg" = ("image/jpg", (fromJust file))
| hasExtension "png" = ("image/png", (fromJust file))
| hasExtension "js" = ("text/javascript", (fromJust file))
| otherwise = ("", (fromJust file))
file = lookup request files
request = map T.unpack $ WAI.pathInfo req
hasExtension extension = (takeLast (length extension) $ last $ request) == extension
takeLast n xs = (reverse . (take n) . reverse) xs
-- | Gets all the directories in the given path
getDirectories :: String -> IO [FilePath]
getDirectories path = do
dirPath <- getDataFileName path
-- Find files and directories, filter out the ".." and "."
filesAndDirectories <- getDirectoryContents dirPath >>= \x -> return (filter (not.(`elem` ignoreFiles)) x)
directoryExists <- mapM doesDirectoryExist (map ((dirPath++"/")++) filesAndDirectories) --Check if directories exist
return [ (path++"/")++(filesAndDirectories !! i) | i <- [0..(length filesAndDirectories-1)], directoryExists !! i ]
-- | Gets all files within the given directory
getDirectoryFiles :: String -> IO [([String], BS.ByteString)]
getDirectoryFiles path = do
dirPath <- getDataFileName path
filesAndDirectories <- getDirectoryContents dirPath >>= \x -> return (filter (not.(`elem` ignoreFiles)) x)
filesExist <- mapM doesFileExist (map ((dirPath++"/")++) filesAndDirectories)
existingFiles <- return $ [ (filesAndDirectories !! i) | i <- [0..(length filesAndDirectories-1)], filesExist !! i ]
files <- mapM BS.readFile (map ((dirPath++"/")++) existingFiles)
return $ zip (map ((delete "canvashs-client").(splitOn "/").((path++"/")++)) existingFiles) files
| CanvasHS/Canvas.hs | canvashs-module/CanvasHs/Server/Static.hs | lgpl-2.1 | 4,130 | 4 | 15 | 1,030 | 913 | 500 | 413 | 42 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Spark.Core.GroupsSpec where
import Test.Hspec
import Data.Text(Text)
import Spark.Core.Context
import Spark.Core.Functions
import qualified Spark.Core.ColumnFunctions as C
import Spark.Core.Column
import Spark.Core.IntegrationUtilities
import Spark.Core.CollectSpec(run)
import Spark.Core.SimpleAddSpec(xrun)
import Spark.Core.Internal.Groups
sumGroup :: [MyPair] -> [(Text, Int)] -> IO ()
sumGroup l lexp = do
let ds = dataset l
let keys = ds // myKey'
let values = ds // myVal'
let g = groupByKey keys values
let ds2 = g `aggKey` C.sum
l2 <- exec1Def $ collect (asCol ds2)
l2 `shouldBe` lexp
spec :: Spec
spec = do
describe "Integration test - groups on (text, int)" $ do
xrun "empty" $
sumGroup [] []
xrun "one" $
sumGroup [MyPair "x" 1] [("x", 1)]
xrun "two" $
sumGroup [MyPair "x" 1, MyPair "x" 2, MyPair "y" 1] [("x", 3), ("y", 1)]
| tjhunter/karps | haskell/test-integration/Spark/Core/GroupsSpec.hs | apache-2.0 | 970 | 0 | 13 | 186 | 352 | 190 | 162 | 31 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Web.Forms.Login where
import Web.Forms.Common
import Text.Blaze.Html (Html)
import Text.Digestive
import Text.Digestive.Bootstrap
import qualified Data.Text as T
data LoginRequest
= LoginRequest
{ lr_user :: T.Text
, lr_password :: T.Text
} deriving (Show)
loginForm :: Monad m => Form Html m LoginRequest
loginForm =
LoginRequest <$> "name" .: usernameFormlet Nothing
<*> "password" .: passwordFormlet Nothing
loginFormSpec :: FormMeta
loginFormSpec =
FormMeta
{ fm_method = POST
, fm_target = "/login"
, fm_components =
[ FCSection
FormSection
{ fs_title = Nothing
, fs_help = Nothing
, fs_elements =
[ FormElement "name" (Just "Username") (Just "Username") InputText
, FormElement "password" (Just "Password") (Just "Password") InputPassword
]
}
]
, fm_submitValue = "Login"
}
| agrafix/funblog | src/Web/Forms/Login.hs | apache-2.0 | 1,008 | 0 | 14 | 299 | 232 | 134 | 98 | 30 | 1 |
module Integration (tests) where
import Protolude hiding (stdin, stdout, toS)
import Protolude.Conv (toS)
import Crypto.Hash (SHA256(..))
import Data.ByteArray.Encoding (convertFromBase, convertToBase, Base(Base16))
import qualified Data.ByteString as ByteString
import qualified Data.ByteString.Char8 as Char8
import qualified System.IO as IO
import qualified System.Process as Process
import Test.Tasty (TestTree)
import Test.Tasty.Hspec (testSpec, describe, it, shouldBe)
import qualified Crypto.Spake2 as Spake2
import Crypto.Spake2.Group (Group(arbitraryElement))
import Crypto.Spake2.Groups (Ed25519(..))
import qualified Paths_spake2
tests :: IO TestTree
tests = testSpec "Integration" $
describe "python-spake2" $ do
it "Generates the same SPAKE2 session key (symmetric)" $ do
let sideID = "treebeard"
let password = "mellon"
let protocol = Spake2.makeSymmetricProtocol SHA256 Ed25519 blindS (Spake2.SideID sideID)
exchangeWithPython protocol password
[ "--side=S"
, "--side-id=" <> toS sideID
]
it "Generates the same SPAKE2 session key (asymmetric, we are side B)" $ do
let ourSideID = "alliance"
let theirSideID = "horde"
let password = "mellon"
let protocol = Spake2.makeAsymmetricProtocol SHA256 Ed25519 blindA blindB (Spake2.SideID theirSideID) (Spake2.SideID ourSideID) Spake2.SideB
exchangeWithPython protocol password
[ "--side=A"
, "--side-id=" <> toS theirSideID
, "--other-side-id=" <> toS ourSideID
]
it "Generates the same SPAKE2 session key (asymmetric, we are side A)" $ do
let ourSideID = "alliance"
let theirSideID = "horde"
let password = "mellon"
let protocol = Spake2.makeAsymmetricProtocol SHA256 Ed25519 blindA blindB (Spake2.SideID ourSideID) (Spake2.SideID theirSideID) Spake2.SideA
exchangeWithPython protocol password
[ "--side=B"
, "--side-id=" <> toS theirSideID
, "--other-side-id=" <> toS ourSideID
]
where
send h x = Char8.hPutStrLn h (convertToBase Base16 x)
receive h = convertFromBase Base16 <$> ByteString.hGetLine h
blindA = arbitraryElement Ed25519 ("M" :: ByteString)
blindB = arbitraryElement Ed25519 ("N" :: ByteString)
blindS = arbitraryElement Ed25519 ("symmetric" :: ByteString)
exchangeWithPython protocol password args = do
scriptExe <- Paths_spake2.getDataFileName "tests/python/spake2_exchange.py"
let testScript = (Process.proc "python" (scriptExe:("--code=" <> toS password):args))
{ Process.std_in = Process.CreatePipe
, Process.std_out = Process.CreatePipe
, Process.std_err = Process.Inherit -- So we get stack traces printed during test runs.
}
Process.withCreateProcess testScript $
\(Just stdin) (Just stdout) _stderr ph -> do
-- The inter-process protocol is line-based.
IO.hSetBuffering stdin IO.LineBuffering
IO.hSetBuffering stdout IO.LineBuffering
IO.hSetBuffering stderr IO.LineBuffering
(do Right sessionKey <- Spake2.spake2Exchange protocol (Spake2.makePassword password) (send stdin) (receive stdout)
theirSpakeKey <- ByteString.hGetLine stdout
theirSpakeKey `shouldBe` convertToBase Base16 sessionKey) `finally` Process.waitForProcess ph
| jml/haskell-spake2 | tests/Integration.hs | apache-2.0 | 3,430 | 0 | 21 | 774 | 856 | 446 | 410 | 62 | 1 |
import Control.Exception.Base (evaluate)
import Data.Char (digitToInt)
import System.Clock
import System.Environment (getArgs)
import System.IO
input :: Int
input = 100
solution :: Int -> Int
solution n
= sum
. map digitToInt
. show
. product
$ [2..toInteger n]
run :: (a -> b) -> a -> Int -> IO ()
run fun inp iters
| iters <= 0 = return ()
| otherwise = evaluate (fun inp) >> run fun inp (iters-1)
benchmark :: (a -> b) -> a -> Int -> IO Int
benchmark fun inp iters = do
start <- getTime Monotonic
run fun inp iters
end <- getTime Monotonic
let secs = sec end - sec start
let nsecs = nsec end - nsec start
let elapsed = 1000000000 * secs + nsecs
return elapsed
benchmarkLoop :: IO ()
benchmarkLoop = do
line <- getLine
let iters = read line
time <- benchmark solution input iters
print time
hFlush stdout
benchmarkLoop
main = do
args <- getArgs
case args of
[ "-a" ] -> print $ solution input
[] -> benchmarkLoop
| japaric/euler_criterion.rs | problems/020/020.hs | apache-2.0 | 973 | 0 | 11 | 232 | 424 | 203 | 221 | 40 | 2 |
{-# LANGUAGE
QuasiQuotes
, PackageImports
#-}
module ScatterGridderWDep where
import "language-c-quote" Language.C.Syntax
import Language.C.Quote.CUDA
import Language.C.Smart ()
import Text.PrettyPrint.Mainland (
Doc
, ppr
, pretty
)
import Development.Shake
import Development.Shake.FilePath
import Utils
speed_of_light, wstep_correct :: Double
speed_of_light = 299792458.0
wstep_correct = 0.00001
data GCFType =
GCFFixed { maxSupp :: Int }
| GCFVar { halfSuppStep :: Int }
pregridded :: GCFType -> Type
pregridded gcftype = [cty|
struct Pregridded_tag
{
short u;
short v;
$sdecls:(gcf_fields gcftype)
}
|]
where
gcf_fields (GCFFixed _) =
[ [csdecl| int gcf_layer_offset; |]
]
gcf_fields (GCFVar _) =
[ [csdecl| short gcf_layer_index; |]
, [csdecl| short half_supp_size; |]
]
double4c, double3, task_cfg :: Type
double4c = [cty|
struct Double4c_tag
{
typename complexd XX;
typename complexd XY;
typename complexd YX;
typename complexd YY;
}
|]
double3 = [cty|
struct Double3_tag
{
double u;
double v;
double w;
}
|]
task_cfg = [cty|
struct TaskCfg_tag {
double
min_wave_length
, max_inverse_wave_length
, cellsize
, cellsizeWL
, scale
, scaleWL
, w_step
, w_stepWL
, w_shift
, w_shiftWL
;
}
|]
max_supp :: GCFType -> Int -> Int
max_supp (GCFFixed n) _ = n
max_supp (GCFVar half_supp_step) w_planes = (w_planes - 1) * half_supp_step * 2
mkCfgSupport :: GCFType -> Int -> Int -> Func
mkCfgSupport gcftype grid_size w_planes = [cfun|
typename TaskCfg
mkCfg (
double min_u
, double max_u
, double min_v
, double max_v
, double min_w
, double max_w
, double min_freq
, double max_freq
) {
const int uv_shift_in_pixels = ($(max_supp gcftype w_planes) + $grid_size) / 2;
double
min_wavelength = $speed_of_light / max_freq
, max_inverse_wave_length = max_freq / $speed_of_light
, maxx_u = max(max_u, -min_u)
, maxx_v = max(max_v, -min_v)
, maxx0 = max(maxx_u, maxx_v)
, maxx = maxx0 * max_freq / min_freq
, cellsize = maxx / (double)uv_shift_in_pixels
, cellsizeWL = cellsize * max_inverse_wave_length
, scale = (double)uv_shift_in_pixels / maxx
, scaleWL = scale * min_wavelength
, w_step = (max_w - min_w) / (double)$w_planes + $wstep_correct
, w_stepWL = w_step * scaleWL
, w_shift = -min_w
, w_shiftWL = w_shift * scaleWL
;
return (typename TaskCfg) {
min_wavelength
, max_inverse_wave_length
, cellsize
, cellsizeWL
, scale
, scaleWL
, w_step
, w_stepWL
, w_shift
, w_shiftWL
};
}
|]
mkPregrid :: GCFType -> Int -> Int -> Int -> Func
mkPregrid gcftype grid_size w_planes over =
[cfun|
inline
typename Pregridded
pregrid(const typename Double3 * uvw, const typename TaskCfg * cfg) {
double
us = uvw->u * cfg->scaleWL
, vs = uvw->v * cfg->scaleWL
;
int
u = (int)us
, v = (int)vs
, wplane = (int)((uvw->w + cfg->w_shift)/ cfg->w_step)
, uv_shift_in_pixels = ($(max_supp gcftype w_planes) + $grid_size) / 2
;
short
fracu = (short)((double)$overu * (us - (double)u))
, fracv = (short)((double)$overv * (vs - (double)v))
;
return $(ret0 `addFields` extraFields);
}
|]
where
ret0 =
[cexp|
(typename Pregridded) {
u + uv_shift_in_pixels
, v + uv_shift_in_pixels
}
|]
suppOff =
[cexp| (wplane * $overu + fracu) * $overv + fracv |]
extraFields =
case gcftype of
GCFFixed max_s ->
[ suppOff * ex max_s ]
GCFVar half_supp_step ->
[ suppOff
, [cexp| wplane * $half_supp_step |]
]
overu = over
overv = over
mkPregridFixCodeTest :: Doc
mkPregridFixCodeTest = ppr (mkPregrid (GCFFixed 128) 2048 32 8)
mkPregridVarCodeTest :: Doc
mkPregridVarCodeTest = ppr (mkPregrid (GCFVar 5) 2048 32 8)
unit :: GCFType -> Int -> Int -> Int -> [Definition]
unit gcf_type grid_size w_planes over =
[cunit|
$esc:(mkIncs [SI "minmax.h", CI "scatter_gridder.h"])
typedef $ty:double4c Double4c;
typedef $ty:(pregridded gcf_type) Pregridded;
typedef $ty:double3 Double3;
typedef $ty:task_cfg TaskCfg;
$func:(mkCfgSupport gcf_type grid_size w_planes)
$func:(mkPregrid gcf_type grid_size w_planes over)
|]
where
mkCfgCodeFixed, mkCfgCodeVar :: Doc
mkCfgCodeFixed = ppr (unit (GCFFixed 128) 2048 32 8)
mkCfgCodeVar = ppr (unit (GCFVar 5) 2048 32 8)
main :: IO ()
main = shakeArgs shakeOptions $ do
want ["scatter_gridder_fixed.o", "scatter_gridder_var.o"]
mkdep "scatter_gridder_fixed.c" mkCfgCodeFixed
mkdep "scatter_gridder_var.c" mkCfgCodeVar
"*.o" %> \out -> do
let src = out -<.> "c"
need [src]
cmd "gcc -std=gnu11 -c -Wall -o" [out] src
where
mkdep outname src =
outname %> \out -> do
need ["ScatterGridderWDep.hs"] -- look at myself
liftIO $ writeFile out (pretty 80 src)
| SKA-ScienceDataProcessor/RC | MS3/Sketches/CPU_Gridders/ScatterGridderWDep.hs | apache-2.0 | 5,300 | 0 | 15 | 1,538 | 731 | 418 | 313 | 75 | 2 |
{-# LANGUAGE FlexibleContexts #-}
import Control.Applicative
import Data.Either.Unwrap
import Text.Parsec as P
import Data.PGN
import Data.SAN
eol :: Stream s m Char => P.ParsecT s u m Char
eol = P.char '\n'
restOfLine :: Stream s m Char => P.ParsecT s u m String
restOfLine = P.many1 (P.noneOf "\n") <* eol
--spaces = P.many P.space
parseFics = do
p1 <- P.many1 (P.noneOf " ")
string " ("
r1 <- P.many1 P.digit
string ") vs. "
p2 <- P.many1 (P.noneOf " ")
string " ("
r2 <- P.many1 P.digit
P.string ") --- "
date <- restOfLine
description <- restOfLine
eol
string "Move " >> restOfLine
string "---- " >> restOfLine
let crapBtwnMoves = P.many (P.oneOf " ():.0123456789\n")
crapBtwnMoves
moves <- P.many (moveAnnParser <* crapBtwnMoves)
P.many (P.oneOf "{} " P.<|> P.letter)
Left result <- resultOrMoveParser
return $ PGN [
("White", p1),
("Black", p2),
("Event", description)] moves result
main = do
f <- readFile "test"
putStrLn . showPgn . fromRight $ runParser parseFics () "test" f
| dancor/pgn | src/FicsToPgn.hs | bsd-2-clause | 1,049 | 0 | 13 | 226 | 413 | 197 | 216 | 36 | 1 |
module Foundation
( App (..)
, Route (..)
, AppMessage (..)
, resourcesApp
, Handler
, Widget
, Form
, maybeAuth
, requireAuth
, requireAuthId
, module Settings
, module Model
, getExtra
) where
import Prelude
import Yesod
import Yesod.Static
import Yesod.Auth
import Yesod.Auth.BrowserId
import Yesod.Auth.GoogleEmail
import Yesod.Default.Config
import Yesod.Default.Util (addStaticContentExternal)
import Yesod.Form.Jquery
import Network.HTTP.Conduit (Manager)
import qualified Settings
import qualified Database.Persist.Store
import Settings.StaticFiles
import Database.Persist.GenericSql
import Settings (widgetFile, Extra (..))
import Model
import Text.Jasmine (minifym)
import Web.ClientSession (getKey)
import Text.Hamlet (hamletFile)
-- | 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.Store.PersistConfigPool Settings.PersistConfig -- ^ Database connection pool.
, httpManager :: Manager
, persistConfig :: Settings.PersistConfig
}
-- 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/handler
--
-- This function does three things:
--
-- * Creates the route datatype AppRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route App = AppRoute
-- * Creates the value resourcesApp which contains information on the
-- resources declared below. This is used in Handler.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- App. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the AppRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "App" $(parseRoutesFile "config/routes")
type Form x = Html -> MForm App App (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 _ = do
key <- getKey "config/client_session_key.aes"
return . Just $ clientSessionBackend key 120
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
$(widgetFile "normalize")
addStylesheet $ StaticR css_bootstrap_css
$(widgetFile "default-layout")
hamletToRepHtml $(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 base64md5 Settings.staticDir (StaticR . flip StaticRoute [])
-- Place Javascript at bottom of the body tag so the rest of the page loads first
jsLoader _ = BottomOfBody
-- How to run database actions.
instance YesodPersist App where
type YesodPersistBackend App = SqlPersist
runDB f = do
master <- getYesod
Database.Persist.Store.runPool
(persistConfig master)
f
(connPool master)
instance YesodJquery App
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 (credsIdent creds) Nothing
-- You can add other plugins like BrowserID, email or OAuth here
authPlugins _ = [authBrowserId, authGoogleEmail]
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
| seizans/ppl | Foundation.hs | bsd-2-clause | 6,136 | 0 | 17 | 1,328 | 852 | 478 | 374 | -1 | -1 |
module Drasil.GamePhysics.Body where
import Language.Drasil hiding (Symbol(..), Vector, organization, section)
import Language.Drasil.Printers (PrintingInformation(..), defaultConfiguration)
import Database.Drasil (Block(Parallel), ChunkDB, ReferenceDB, SystemInformation(SI),
cdb, rdb, refdb, _authors, _concepts, _constants, _constraints, _datadefs,
_definitions, _defSequence, _inputs, _kind, _outputs, _quants, _sys, _sysinfodb,
_usedinfodb, sampleData)
import Theory.Drasil (qdFromDD)
import Utils.Drasil
import Drasil.DocLang (DerivationDisplay(..), DocSection(..), Emphasis(..),
Field(..), Fields, InclUnits(IncludeUnits), IntroSec(..), IntroSub(..),
RefSec(..), RefTab(..), SCSSub(..), SRSDecl, SSDSec(SSDProg), SSDSub(..),
SolChSpec(SCSProg), TConvention(..), TSIntro(..), Verbosity(Verbose),
OffShelfSolnsSec(..), GSDSec(..), GSDSub(..), TraceabilitySec(TraceabilityProg),
ReqrmntSec(..), ReqsSub(..), AuxConstntSec(..), ProblemDescription(PDProg),
PDSub(..), intro, mkDoc, tsymb, traceMatStandard, solutionLabel)
import qualified Drasil.DocLang.SRS as SRS
import Data.Drasil.Concepts.Computation (algorithm)
import Data.Drasil.Concepts.Documentation as Doc (assumption, concept,
condition, consumer, document, endUser, environment, game, goalStmt, guide,
information, input_, interface, model, object, organization, physical,
physicalSim, physics, problem, product_, project, quantity, realtime,
reference, section_, simulation, software, softwareSys, srsDomains, system,
systemConstraint, sysCont, task, template, user, doccon, doccon', property)
import qualified Data.Drasil.Concepts.Documentation as Doc (srs)
import Data.Drasil.IdeaDicts as Doc (dataDefn, inModel, thModel)
import Data.Drasil.Concepts.Education (frstYr, highSchoolCalculus,
highSchoolPhysics, educon)
import Data.Drasil.Concepts.Software (physLib, softwarecon)
import Data.Drasil.People (alex, luthfi, olu)
import Data.Drasil.SI_Units (metre, kilogram, second, newton, radian,
derived, fundamentals, joule)
import Data.Drasil.Software.Products (openSource, prodtcon, sciCompS, videoGame)
import qualified Data.Drasil.Concepts.PhysicalProperties as CPP (ctrOfMass, dimension)
import qualified Data.Drasil.Concepts.Physics as CP (elasticity, physicCon, rigidBody, collision, damping)
import qualified Data.Drasil.Concepts.Math as CM (cartesian, equation, law,
mathcon, mathcon', rightHand, line, point)
import qualified Data.Drasil.Quantities.Physics as QP (force, time)
import Drasil.GamePhysics.Assumptions (assumptions)
import Drasil.GamePhysics.Changes (likelyChgs, unlikelyChgs)
import Drasil.GamePhysics.Concepts (gamePhysics, acronyms, threeD, twoD)
import Drasil.GamePhysics.DataDefs (dataDefs)
import Drasil.GamePhysics.Goals (goals)
import Drasil.GamePhysics.IMods (iMods, instModIntro)
import Drasil.GamePhysics.References (citations, parnas1972, parnasClements1984)
import Drasil.GamePhysics.Requirements (funcReqs, nonfuncReqs)
import Drasil.GamePhysics.TMods (tMods)
import Drasil.GamePhysics.Unitals (symbolsAll, outputConstraints,
inputSymbols, outputSymbols, inputConstraints, defSymbols)
import Drasil.GamePhysics.GenDefs (generalDefns)
srs :: Document
srs = mkDoc mkSRS for' si
printSetting :: PrintingInformation
printSetting = PI symbMap Equational defaultConfiguration
resourcePath :: String
resourcePath = "../../../datafiles/GamePhysics/"
mkSRS :: SRSDecl
mkSRS = [RefSec $ RefProg intro [TUnits, tsymb tableOfSymbols, TAandA],
IntroSec $ IntroProg para1_introduction_intro (short gamePhysics)
[IPurpose para1_purpose_of_document_intro,
IScope scope,
IChar [] [S "rigid body dynamics", phrase highSchoolCalculus] [],
IOrgSec organizationOfDocumentsIntro inModel (SRS.inModel [] []) EmptyS],
GSDSec $ GSDProg [
SysCntxt [sysCtxIntro, LlC sysCtxFig1, sysCtxDesc, sysCtxList],
UsrChars [userCharacteristicsIntro], SystCons [] []],
SSDSec $ SSDProg
[ SSDProblem $ PDProg probDescIntro []
[ TermsAndDefs Nothing terms
, Goals [S "the kinematic" +:+ plural property :+: S ", and" +:+ plural QP.force +:+
sParen (S "including any" +:+ phrase CP.collision +:+ plural QP.force) +:+
S "applied on a set of" +:+ plural CP.rigidBody]]
, SSDSolChSpec $ SCSProg
[ Assumptions
, TMs [] (Label : stdFields)
, GDs [] ([Label, Units] ++ stdFields) ShowDerivation
, DDs [] ([Label, Symbol, Units] ++ stdFields) ShowDerivation
, IMs [instModIntro] ([Label, Input, Output, InConstraints, OutConstraints] ++ stdFields) ShowDerivation
, Constraints (S "FIXME") inputConstraints
, CorrSolnPpties outputConstraints []
]
],
ReqrmntSec $ ReqsProg [
FReqsSub' [],
NonFReqsSub
],
LCsSec,
UCsSec,
OffShelfSolnsSec $ OffShelfSolnsProg offShelfSols,
TraceabilitySec $ TraceabilityProg $ traceMatStandard si,
AuxConstntSec $ AuxConsProg gamePhysics [],
Bibliography]
where tableOfSymbols = [TSPurpose, TypogConvention[Vector Bold], SymbOrder, VectorUnits]
si :: SystemInformation
si = SI {
_sys = gamePhysics,
_kind = Doc.srs,
_authors = [alex, luthfi, olu],
-- FIXME: The _quants field should be filled in with all the symbols, however
-- #1658 is why this is empty, otherwise we end up with unused (and probably
-- should be removed) symbols. But that's for another time. This is "fine"
-- because _quants are only used relative to #1658 and in code gen. And
-- Gamephysics is not in a place to be able to do codegen.
_quants = [] :: [QuantityDict], -- map qw iMods ++ map qw symbolsAll,
_concepts = [] :: [DefinedQuantityDict],
_definitions = qDefs,
_datadefs = dataDefs,
_inputs = inputSymbols,
_outputs = outputSymbols,
_defSequence = map (\x -> Parallel x []) qDefs,
_constraints = inputConstraints,
_constants = [],
_sysinfodb = symbMap,
_usedinfodb = usedDB,
refdb = refDB,
sampleData = "../../datafiles/GamePhysics/sampleInput.txt"
}
where qDefs = map qdFromDD dataDefs
concIns :: [ConceptInstance]
concIns = assumptions ++ goals ++ likelyChgs ++ unlikelyChgs ++ funcReqs ++ nonfuncReqs
section :: [Section]
section = extractSection srs
stdFields :: Fields
stdFields = [DefiningEquation, Description Verbose IncludeUnits, Notes, Source, RefBy]
--FIXME: Need to be able to print defn for gravitational constant.
refDB :: ReferenceDB
refDB = rdb citations concIns
--FIXME: All named ideas, not just acronyms.
units :: [UnitDefn] -- FIXME
units = map unitWrapper [metre, kilogram, second, joule] ++ map unitWrapper [newton, radian]
symbMap :: ChunkDB
symbMap = cdb (map qw iMods ++ map qw symbolsAll) (map nw symbolsAll
++ map nw acronyms ++ map nw prodtcon ++ map nw generalDefns ++ map nw iMods
++ map nw softwarecon ++ map nw doccon ++ map nw doccon'
++ map nw CP.physicCon ++ map nw educon ++ [nw algorithm] ++ map nw derived
++ map nw fundamentals ++ map nw CM.mathcon ++ map nw CM.mathcon')
(map cw defSymbols ++ srsDomains ++ map cw iMods) units dataDefs
iMods generalDefns tMods concIns section []
usedDB :: ChunkDB
usedDB = cdb ([] :: [QuantityDict]) (map nw symbolsAll ++ map nw acronyms)
([] :: [ConceptChunk]) ([] :: [UnitDefn]) [] [] [] [] [] [] []
--FIXME: The SRS has been partly switched over to the new docLang, so some of
-- the sections below are now redundant. I have not removed them yet, because
-- it makes it easier to test between the two different versions as changes
-- are introduced. Once the SRS is entirely switched to docLang, the redundant
-- sections should be removed.
-- =================================== --
-- SOFTWARE REQUIREMENTS SPECIFICATION --
-- =================================== --
------------------------------
-- Section : INTRODUCTION --
------------------------------
para1_introduction_intro :: Sentence
para1_introduction_intro = foldlSent
[S "Due to the rising cost of developing", plural videoGame `sC`
S "developers are looking for ways to save time and money for their" +:+.
plural project, S "Using an", phrase openSource,
phrase physLib,
S "that is reliable and free will cut down development costs and lead",
S "to better quality", plural product_]
-------------------------------
-- 2.1 : Purpose of Document --
-------------------------------
detailsAndGoal :: [CI]
detailsAndGoal = [thModel, goalStmt]
para1_purpose_of_document_intro :: Sentence
para1_purpose_of_document_intro = para1_purpose_of_document_param gamePhysics
document programDescription (plural game) (map plural detailsAndGoal)
programDescription :: Sentence
programDescription = foldlSent_ [phrase openSource, getAcc twoD,
phrase CP.rigidBody, phrase physLib]
para1_purpose_of_document_param :: (Idea a, NamedIdea b) => a -> b -> Sentence -> Sentence ->
[Sentence] -> Sentence
para1_purpose_of_document_param progName typeOf progDescrip appOf listOf = foldlSent
[S "This", phrase typeOf, S "describes the modeling of an",
progDescrip, S "used for" +:+. appOf, S "The",
foldlList Comma List listOf, S "used in", short progName,
S "are provided. This", phrase typeOf,
S "is intended to be used as a", phrase reference,
S "to provide all necessary", phrase information,
S "to understand and verify the", phrase model]
---------------------------------
-- 2.2 : Scope of Requirements --
---------------------------------
scope :: Sentence
scope = foldlSent_ [S "the", phrase physicalSim `sOf` getAcc twoD,
plural CP.rigidBody, S "acted on by", plural QP.force]
--scope_of_requirements_intro_p2 = EmptyS
{-scope_of_requirements_intro_p2 = foldlSent_ [S "simulates how these",
plural CP.rigidBody, S "interact with one another"]
-}
----------------------------------------------
-- 2.3 : Characteristics of Intended Reader --
----------------------------------------------
-------------------------------------
-- 2.3 : Organization of Documents --
-------------------------------------
organizationOfDocumentsIntro :: Sentence
organizationOfDocumentsIntro = foldlSent
[S "The", phrase organization, S "of this", phrase document,
S "follows the", phrase template, S "for an", getAcc Doc.srs, S "for",
phrase sciCompS, S "proposed by", makeCiteS parnas1972 `sAnd`
makeCiteS parnasClements1984]
--------------------------------------------
-- Section 3: GENERAL SYSTEM DESCRIPTION --
--------------------------------------------
--------------------------
-- 3.1 : System Context --
--------------------------
sysCtxIntro :: Contents
sysCtxIntro = foldlSP
[makeRef2S sysCtxFig1 +:+ S "shows the" +:+. phrase sysCont,
S "A circle represents an external entity outside the" +:+ phrase software
`sC` S "the", phrase user, S "in this case. A rectangle represents the",
phrase softwareSys, S "itself", sParen (short gamePhysics) +:+. EmptyS,
S "Arrows are used to show the data flow between the" +:+ phrase system,
S "and its" +:+ phrase environment]
sysCtxFig1 :: LabelledContent
sysCtxFig1 = llcc (makeFigRef "sysCtxDiag") $ fig (titleize sysCont)
(resourcePath ++ "sysctx.png")
sysCtxDesc :: Contents
sysCtxDesc = foldlSPCol [S "The interaction between the", phrase product_,
S "and the", phrase user, S "is through an application programming" +:+.
phrase interface, S "The responsibilities of the", phrase user,
S "and the", phrase system, S "are as follows"]
sysCtxUsrResp :: [Sentence]
sysCtxUsrResp = [S "Provide initial" +:+ plural condition +:+ S "of the" +:+
phrase physical +:+ S"state of the" +:+ phrase simulation `sC`
plural CP.rigidBody +:+ S "present, and" +:+ plural QP.force +:+.
S "applied to them",
S "Ensure application programming" +:+ phrase interface +:+
S "use complies with the" +:+ phrase user +:+. phrase guide,
S "Ensure required" +:+ phrase software +:+ plural assumption +:+
sParen (makeRef2S $ SRS.assumpt ([]::[Contents]) ([]::[Section])) +:+
S "are appropriate for any particular" +:+
phrase problem +:+ S "the" +:+ phrase software +:+. S "addresses"]
sysCtxSysResp :: [Sentence]
sysCtxSysResp = [S "Determine if the" +:+ plural input_ +:+ S "and" +:+
phrase simulation +:+ S "state satisfy the required" +:+
(phrase physical `sAnd` plural systemConstraint) +:+. sParen(makeRef2S $ SRS.datCon ([]::[Contents]) ([]::[Section])),
S "Calculate the new state of all" +:+ plural CP.rigidBody +:+
S "within the" +:+ phrase simulation +:+ S "at each" +:+
phrase simulation +:+. S "step",
S "Provide updated" +:+ phrase physical +:+ S "state of all" +:+
plural CP.rigidBody +:+ S "at the end of a" +:+ phrase simulation +:+.
S "step"]
sysCtxResp :: [Sentence]
sysCtxResp = [titleize user +:+ S "Responsibilities",
short gamePhysics +:+ S "Responsibilities"]
sysCtxList :: Contents
sysCtxList = UlC $ ulcc $ Enumeration $ bulletNested sysCtxResp $
map bulletFlat [sysCtxUsrResp, sysCtxSysResp]
--------------------------------
-- 3.2 : User Characteristics --
--------------------------------
userCharacteristicsIntro :: Contents
userCharacteristicsIntro = foldlSP
[S "The", phrase endUser `sOf` short gamePhysics,
S "should have an understanding of", phrase frstYr, S "programming",
plural concept `sAnd` S "an understanding of", phrase highSchoolPhysics]
-------------------------------
-- 3.3 : System Constraints --
-------------------------------
---------------------------------------------
-- SECTION 4 : SPECIFIC SYSTEM DESCRIPTION --
---------------------------------------------
-- NOTE: Section 4 remains incomplete. General definitions and instance models
-- have not been encoded.
-------------------------------
-- 4.1 : Problem Description --
-------------------------------
probDescIntro :: Sentence
probDescIntro = foldlSent_
[S "create a", foldlList Comma List $ map S ["simple", "lightweight", "fast", "portable"],
getAcc twoD, phrase CP.rigidBody, phrase physLib `sC` S "which will allow for more accessible",
phrase game, S "development" `sAnd` S "the production of higher quality" +:+. plural product_,
S "Creating a gaming", phrase physLib, S "is a difficult" +:+. phrase task, titleize' game,
S "need", plural physLib, S "that simulate", plural object, S "acting under various", phrase physical,
plural condition `sC` S "while simultaneously being fast and efficient enough to work in soft",
phrase realtime, S "during the" +:+. phrase game, S "Developing a",
phrase physLib, S "from scratch takes a long period" `sOf` phrase QP.time `sAnd`
S "is very costly" `sC` S "presenting barriers of entry which make it difficult for",
phrase game, S "developers to include", phrase Doc.physics, S "in their" +:+.
plural product_, S "There are a few free" `sC` phrase openSource `sAnd` S "high quality",
plural physLib, S "available to be used for", phrase consumer, plural product_,
sParen (makeRef2S $ SRS.offShelfSol ([] :: [Contents]) ([] :: [Section]))]
-----------------------------------------
-- 4.1.1 : Terminology and Definitions --
-----------------------------------------
terms :: [ConceptChunk]
terms = [CP.rigidBody, CP.elasticity, CPP.ctrOfMass, CM.cartesian, CM.rightHand, CM.line, CM.point, CP.damping]
-----------------------------
-- 4.1.2 : Goal Statements --
-----------------------------
--------------------------------------------------
-- 4.2 : Solution Characteristics Specification --
--------------------------------------------------
-------------------------
-- 4.2.1 : Assumptions --
-------------------------
--------------------------------
-- 4.2.2 : Theoretical Models --
--------------------------------
---------------------------------
-- 4.2.3 : General Definitions --
---------------------------------
generalDefinitionsIntro :: Contents
-- general_definitions_GDefs :: [Contents]
generalDefinitionsIntro = foldlSP
[S "This", phrase section_, S "collects the", plural CM.law `sAnd`
plural CM.equation, S "that will be used in deriving the",
plural dataDefn `sC` S "which in turn will be used to build the",
plural inModel]
-- GDefs not yet implemented --
{-
general_definitions_GDefs :: [Contents]
general_definitions_GDefs = map (Definition . General) gDefs)
-}
------------------------------
-- 4.2.4 : Data Definitions --
------------------------------
dataDefinitionsIntro :: Sentence
dataDefinitionsIntro = foldlSent [S "The", phrase CPP.dimension
`sOf` S "each", phrase quantity, S "is also given"]
-----------------------------
-- 4.2.5 : Instance Models --
-----------------------------
------------------------------
-- Collision Diagram --
------------------------------
{-- should be paired with the last instance model for this example
secCollisionDiagram = Paragraph $ foldlSent [ S "This section presents an image",
S "of a typical collision between two 2D rigid bodies labeled A and B,"
S "showing the position of the two objects, the collision normal vector n and",
S "the vectors from the approximate center of mass of each object to the point",
S "of collision P, rAP and rBP. Note that this figure only presents",
S "vertex-to-edge collisions, as per our assumptions (A5)."]
--}
{--fig_1 = Figure (titleize figure +:+ S "1:" +:+ S "Collision between two rigid bodies")
"CollisionDiagram.png" --}
------------------------------
-- SECTION 5 : REQUIREMENTS --
------------------------------
-- in Requirements.hs
-----------------------------------
-- 5.1 : Functional Requirements --
-----------------------------------
--------------------------------------
-- 5.2 : Nonfunctional Requirements --
--------------------------------------
--------------------------------
-- SECTION 6 : LIKELY CHANGES --
--------------------------------
-----------------------------------------
-- SECTION 7 : OFF-THE-SHELF SOLUTIONS --
-----------------------------------------
offShelfSols :: [Contents]
offShelfSols = [offShelfSolsIntro, offShelfSols2DList,
offShelfSolsMid, offShelfSols3DList]
offShelfSolsIntro, offShelfSols2DList,
offShelfSolsMid, offShelfSols3DList :: Contents
offShelfSolsIntro = mkParagraph $ foldlSentCol
[S "As mentioned in", makeRef2S (SRS.probDesc [] []) `sC`
S "there already exist free", phrase openSource, phrase game +:+.
plural physLib, S "Similar", getAcc twoD, plural physLib, S "are"]
offShelfSols2DList = LlC $ enumBullet solutionLabel [S "Box2D: http://box2d.org/",
S "Nape Physics Engine: http://napephys.com/"]
offShelfSolsMid = mkParagraph $ foldl (+:+) EmptyS [S "Free", phrase openSource,
getAcc threeD, phrase game, plural physLib, S "include:"]
offShelfSols3DList = LlC $ enumBullet solutionLabel [
S "Bullet: http://bulletphysics.org/",
S "Open Dynamics Engine: http://www.ode.org/",
S "Newton Game Dynamics: http://newtondynamics.com/"]
-----------------------------------------------------
-- SECTION 8 : Traceability Matrices and Graph --
-----------------------------------------------------
-----------------------------------
-- VALUES OF AUXILIARY CONSTANTS --
-----------------------------------
----------------
-- REFERENCES --
----------------
-- To be added --
| JacquesCarette/literate-scientific-software | code/drasil-example/Drasil/GamePhysics/Body.hs | bsd-2-clause | 19,139 | 0 | 22 | 2,894 | 4,301 | 2,431 | 1,870 | 256 | 1 |
module Downloaders (runDownload, Download) where
import Dep (Dep(Dep))
import Control.Monad.Trans.Maybe
type Download a = MaybeT IO a
runDownload :: Download String -> IO (Maybe String)
runDownload = runMaybeT
| ericmoritz/deps | src/Downloaders.hs | bsd-3-clause | 219 | 0 | 8 | 37 | 69 | 41 | 28 | 6 | 1 |
module Hakyll.Core.DependencyAnalyzer.Tests where
import Control.Arrow (second)
import qualified Data.Set as S
import Data.Monoid (mempty)
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit hiding (Test)
import Hakyll.Core.DirectedGraph
import Hakyll.Core.DependencyAnalyzer
tests :: [Test]
tests =
[ testCase "step [1]" step1
, testCase "step [2]" step2
]
step1 :: Assertion
step1 = Just (S.fromList [1, 2, 5, 6, 7, 8, 9]) @?=
stepAll (makeDependencyAnalyzer graph isOutOfDate prev)
where
node = curry $ second S.fromList
graph = fromList
[ node (8 :: Int) [2, 4, 6]
, node 2 [4, 3]
, node 4 [3]
, node 6 [4]
, node 3 []
, node 9 [5]
, node 5 [7]
, node 1 [7]
, node 7 []
]
prev = fromList
[ node 8 [2, 4, 6]
, node 2 [4, 3]
, node 4 [3]
, node 6 [4]
, node 3 []
, node 9 [5]
, node 5 [7]
, node 1 [7]
, node 7 [8]
]
isOutOfDate = (`elem` [5, 2, 6])
step2 :: Assertion
step2 = Nothing @?= stepAll (makeDependencyAnalyzer graph isOutOfDate mempty)
where
node = curry $ second S.fromList
-- Cycle: 4 -> 7 -> 5 -> 9 -> 4
graph = fromList
[ node (1 :: Int) [6]
, node 2 [3]
, node 3 []
, node 4 [1, 7, 8]
, node 5 [9]
, node 6 [3]
, node 7 [5]
, node 8 [2]
, node 9 [4]
]
isOutOfDate = const True
| sol/hakyll | tests/Hakyll/Core/DependencyAnalyzer/Tests.hs | bsd-3-clause | 1,524 | 0 | 10 | 544 | 600 | 339 | 261 | 52 | 1 |
module Problem51 where
import Data.Digits
import Data.List
isPrime :: Int -> Bool
isPrime n = not (any divisible [2..r])
where r = floor (sqrt (fromIntegral n))
divisible m = n `mod` m == 0
primes :: [Int]
primes = filter isPrime [2..]
findDigitPositions :: Int -> Int -> [Int]
findDigitPositions n d = elemIndices d (digits 10 n)
replaceDigitPositions :: Int -> [Int] -> Int -> Int
replaceDigitPositions n indices d = unDigits 10 $
helper (digits 10 n) indices d
where
helper ds [] _ = ds
helper ds (i:is) d =
take i ds ++ d:helper (drop (i+1) ds) (map (subtract (i+1)) is) d
nPrimeFamily :: Int -> Maybe Int
nPrimeFamily n = find (helper n) primes
where
helper n prime = any (havingNPrimeFamily n prime) [0..(10-n)]
havingNPrimeFamily n prime digit =
case findDigitPositions prime digit of
[] -> False
indices ->
length (filter isPrime familyMembers) == n
where
familyMembers = map (replaceDigitPositions prime indices) [digit..9]
main :: IO ()
main = print (nPrimeFamily 8)
| noraesae/euler | src/Problem51.hs | bsd-3-clause | 1,092 | 0 | 14 | 282 | 459 | 235 | 224 | 28 | 2 |
{-# OPTIONS_GHC -Wall #-}
-- |This module does all the expansions needed to display the prompts
-- (@PS1@ and @PS2@, at least).
module System.Console.ShSh.Prompt ( prompt )
where
import Control.Monad.Trans ( liftIO )
import Data.Char ( chr )
import Data.Maybe ( fromMaybe )
import Data.List ( isPrefixOf )
import System.Environment ( getProgName )
import System.Console.ShSh.Constants ( version )
import System.Console.ShSh.Shell ( Shell, getEnv )
tildeSub :: String -> Shell String
tildeSub s = do home <- getEnv "HOME"
case home of
Just h -> if h `isPrefixOf` s
then return $ '~':drop (length h) s
else return s
Nothing -> return s
expand :: Char -> Shell String
expand 'e' = return [chr 27]
expand 'h' = fromMaybe "" `fmap` getEnv "HOSTNAME"
expand 'H' = (takeWhile (/='.') . fromMaybe "") `fmap` getEnv "HOSTNAME"
expand 's' = liftIO getProgName
expand 'u' = fromMaybe "" `fmap` getEnv "USER"
expand 'v' = return version
expand 'w' = tildeSub =<< fromMaybe "" `fmap` getEnv "PWD"
expand 'W' = tildeSub =<< maybe "" (reverse . takeWhile notSep . reverse)
`fmap` getEnv "PWD"
where notSep c = c /= '/' && c /= '\\'
expand '$' = do uid <- fromMaybe "1" `fmap` getEnv "UID"
return $ case uid of
"0" -> "#"
_ -> "$"
expand '[' = return ""
expand ']' = return ""
expand '\\' = return "\\"
expand x = return ['\\',x]
expandAll :: String -> Shell String -- this is maybe bad recursion, but oh well
expandAll ('\\':c:rest) = expand c >>= \x -> (x++) `fmap` expandAll rest
expandAll (c:rest) = (c:) `fmap` expandAll rest
expandAll "" = return ""
-- |Figure out the prompt. The argument is what we've read so far.
prompt :: String -> Shell String
prompt "" = do -- pwd <- fromMaybe "\\s-\\v\\$ " `fmap` getEnv "PS1"
pwd <- fromMaybe "\\s-\\v: \\w \\$ " `fmap` getEnv "PS1"
expandAll pwd
--return $ pwd ++ " $ "
--Just user <- getEnv "USER"
--Just hostname <- getEnv "HOSTNAME"
--return $ user ++ "@" ++ hostname ++ " " ++ pwd ++ " $ "
prompt _ = do pwd <- fromMaybe "> " `fmap` getEnv "PS2"
expandAll pwd
| shicks/shsh | System/Console/ShSh/Prompt.hs | bsd-3-clause | 2,326 | 0 | 14 | 688 | 676 | 352 | 324 | 45 | 3 |
module StackTest where
import Control.Exception
import Data.List (intercalate)
import System.Environment
import System.FilePath
import System.Directory
import System.IO
import System.Process
import System.Exit
import System.Info (os)
run' :: FilePath -> [String] -> IO ExitCode
run' cmd args = do
logInfo $ "Running: " ++ cmd ++ " " ++ intercalate " " (map showProcessArgDebug args)
(Nothing, Nothing, Nothing, ph) <- createProcess (proc cmd args)
waitForProcess ph
run :: FilePath -> [String] -> IO ()
run cmd args = do
ec <- run' cmd args
if ec == ExitSuccess
then return ()
else error $ "Exited with exit code: " ++ show ec
stack' :: [String] -> IO ExitCode
stack' args = do
stack <- getEnv "STACK_EXE"
run' stack args
stack :: [String] -> IO ()
stack args = do
ec <- stack' args
if ec == ExitSuccess
then return ()
else error $ "Exited with exit code: " ++ show ec
stackErr :: [String] -> IO ()
stackErr args = do
ec <- stack' args
if ec == ExitSuccess
then error "stack was supposed to fail, but didn't"
else return ()
-- | Run stack with arguments and apply a check to the resulting
-- stderr output if the process succeeded.
stackCheckStderr :: [String] -> (String -> IO ()) -> IO ()
stackCheckStderr args check = do
stack <- getEnv "STACK_EXE"
logInfo $ "Running: " ++ stack ++ " " ++ intercalate " " (map showProcessArgDebug args)
(ec, _, err) <- readProcessWithExitCode stack args ""
hPutStr stderr err
if ec /= ExitSuccess
then error $ "Exited with exit code: " ++ show ec
else check err
doesNotExist :: FilePath -> IO ()
doesNotExist fp = do
logInfo $ "doesNotExist " ++ fp
exists <- doesFileOrDirExist fp
case exists of
(Right msg) -> error msg
(Left _) -> return ()
doesExist :: FilePath -> IO ()
doesExist fp = do
logInfo $ "doesExist " ++ fp
exists <- doesFileOrDirExist fp
case exists of
(Right msg) -> return ()
(Left _) -> error "No file or directory exists"
doesFileOrDirExist :: FilePath -> IO (Either () String)
doesFileOrDirExist fp = do
isFile <- doesFileExist fp
if isFile
then return (Right ("File exists: " ++ fp))
else do
isDir <- doesDirectoryExist fp
if isDir
then return (Right ("Directory exists: " ++ fp))
else return (Left ())
copy :: FilePath -> FilePath -> IO ()
copy src dest = do
logInfo ("Copy " ++ show src ++ " to " ++ show dest)
System.Directory.copyFile src dest
fileContentsMatch :: FilePath -> FilePath -> IO ()
fileContentsMatch f1 f2 = do
doesExist f1
doesExist f2
f1Contents <- readFile f1
f2Contents <- readFile f2
if f1Contents == f2Contents
then return ()
else error
("contents do not match for " ++
show f1 ++
" " ++
show f2)
logInfo :: String -> IO ()
logInfo = hPutStrLn stderr
-- TODO: use stack's process running utilties? (better logging)
-- for now just copy+modifying this one from System.Process.Log
-- | Show a process arg including speechmarks when necessary. Just for
-- debugging purposes, not functionally important.
showProcessArgDebug :: String -> String
showProcessArgDebug x
| any special x = show x
| otherwise = x
where special '"' = True
special ' ' = True
special _ = False
-- | Extension of executables
exeExt = if isWindows then ".exe" else ""
-- | Is the OS Windows?
isWindows = os == "mingw32"
-- | Is the OS Mac OS X?
isMacOSX = os == "darwin"
-- | To avoid problems with GHC version mismatch when a new LTS major
-- version is released, pass this argument to @stack@ when running in
-- a global context. The LTS major version here should match that of
-- the main @stack.yaml@.
defaultResolverArg = "--resolver=lts-6.0"
| sjakobi/stack | test/integration/lib/StackTest.hs | bsd-3-clause | 3,929 | 0 | 15 | 1,048 | 1,126 | 555 | 571 | 100 | 3 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * 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.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- 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 Feldspar.Core.Frontend.MutableArray
where
import Language.Syntactic
import Data.List (genericLength)
import Control.Monad (zipWithM_)
import Feldspar.Core.Types
import Feldspar.Core.Constructs
import Feldspar.Core.Constructs.Loop
import Feldspar.Core.Constructs.MutableArray
import Feldspar.Core.Frontend.Mutable
import Feldspar.Core.Frontend.Literal (value)
-- | Create a new 'Mutable' Array and intialize all elements
newArr :: Type a => Data Length -> Data a -> M (Data (MArr a))
newArr = sugarSymC NewArr
-- | Create a new 'Mutable' Array but leave the elements un-initialized
newArr_ :: Type a => Data Length -> M (Data (MArr a))
newArr_ = sugarSymC NewArr_
-- | Create a new 'Mutable' Array and initialize with elements from the
-- list
newListArr :: forall a. Type a => [Data a] -> M (Data (MArr a))
newListArr xs = do arr <- newArr_ (value $ genericLength xs)
zipWithM_ (setArr arr . value) [0..] xs
return arr
-- | Extract the element at index
getArr :: Type a => Data (MArr a) -> Data Index -> M (Data a)
getArr = sugarSymC GetArr
-- | Replace the value at index
setArr :: Type a => Data (MArr a) -> Data Index -> Data a -> M ()
setArr = sugarSymC SetArr
-- | Modify the element at index
modifyArr :: Type a
=> Data (MArr a) -> Data Index -> (Data a -> Data a) -> M ()
modifyArr arr i f = getArr arr i >>= setArr arr i . f
-- | Query the length of the array
arrLength :: Type a => Data (MArr a) -> M (Data Length)
arrLength = sugarSymC ArrLength
-- | Modify all elements
mapArray :: Type a => (Data a -> Data a) -> Data (MArr a) -> M (Data (MArr a))
mapArray f arr = do
len <- arrLength arr
forArr len (flip (modifyArr arr) f)
return arr
forArr :: Syntax a => Data Length -> (Data Index -> M a) -> M ()
forArr = sugarSymC For
-- | Swap two elements
swap :: Type a
=> Data (MArr a) -> Data Index -> Data Index -> M ()
swap a i1 i2 = do
tmp <- getArr a i1
getArr a i2 >>= setArr a i1
setArr a i2 tmp
| emwap/feldspar-language | src/Feldspar/Core/Frontend/MutableArray.hs | bsd-3-clause | 3,670 | 0 | 12 | 749 | 783 | 400 | 383 | 42 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -Wall #-}
module Chan.KickChan (
-- * Kick Channels
KickChan
-- ** Creation
, newKickChan
, kcSize
-- ** Writing
, putKickChan
, invalidateKickChan
-- ** Reading
, KCReader
, newReader
, readNext
, currentLag
-- ** type constraint helpers
, KickChanS
, KickChanV
, KickChanU
, kcUnboxed
, kcStorable
, kcDefault
, KCReaderS
, KCReaderV
, KCReaderU
) where
import Control.Concurrent.MVar
import Control.Concurrent (yield)
import Control.Exception
import Data.Bits
import Data.IORef
import Data.IntMap (IntMap)
import qualified Data.IntMap as IM
import Data.Foldable as Fold
import Data.Maybe (maybeToList)
import Data.Vector.Generic.Mutable (MVector)
import qualified Data.Vector.Generic.Mutable as M
import qualified Data.Vector.Mutable as V
import qualified Data.Vector.Storable.Mutable as S
import qualified Data.Vector.Unboxed.Mutable as U
import Control.Monad.Primitive
#if MIN_VERSION_base(4,6,0)
-- nothing to do here...
#else
atomicModifyIORef' :: IORef a -> (a -> (a,b)) -> IO b
atomicModifyIORef' ref f = do
b <- atomicModifyIORef ref
(\x -> let (a, b) = f x
in (a, a `seq` b))
b `seq` return b
#endif
-- internal structure to hold the channel head
data Position a = Position
{ nSeq :: {-# UNPACK #-} !Int
, waiting :: IntMap [MVar (Maybe a)]
}
{- invariants
- nSeq is the next position to be written (buffer head, initialized to 0)
- nSeq changes monotonically
- the minimum key of the 'waiting' map is >= nSeq.
-
- Use a two-stage commit strategy. Writers first claim a sequence number.
- This causes nSeq to be incremented (so subsequent writers get a new number)
- and inserts the claimed sequence number into the 'waiting' map with an
- empty list. Writers then write to the vector and commit the write, which
- returns a list of readers waiting for that sequence to be written. The
- writer then writes the value to every waiting reader.
-
- Reading uses a similar two-stage process. First the reader checks if the
- value has been committed. If not it blocks, otherwise it reads from the
- buffer and checks if the read position was valid (hasn't been
- over-written).
-}
emptyPosition :: Position a
emptyPosition = Position 0 IM.empty
-- increment a Position, returning the current sequence number or Nothing
-- if the buffer is full
incrPosition :: Int -> Position a -> (Position a,Maybe Int)
incrPosition sz oldP@(Position curSeq pMap) = case IM.minViewWithKey pMap of
Just ((lowKey,_),_)
| lowKey+sz <= curSeq -> (oldP,Nothing)
_ -> (newP,Just curSeq)
where
!newSeq = curSeq+1
newP = Position
{ nSeq = newSeq
, waiting=IM.insertWith (++) curSeq [] pMap
}
-- increment a position by a given value, which must be enough to wrap the
-- buffer. Returns a list of all current waiting readers.
invalidatePosition :: Int -> Position a -> (Position a,[MVar (Maybe a)])
invalidatePosition wrapAmount (Position oldP waiting) = (newP,pList)
where
newP = Position (oldP+wrapAmount) IM.empty
pList = Prelude.concat $ IM.elems waiting
-- | commit a value that's been written to the vector.
commit :: Int -> Position a -> (Position a,[MVar (Maybe a)])
commit seqNum (Position nSeq pMap) = (newP,pList)
where
pList = Prelude.concat $ maybeToList pending
(pending,pMap') = IM.updateLookupWithKey (\_ _ -> Nothing) seqNum pMap
newP = Position nSeq pMap'
data CheckResult = Ok | Invalid
-- check if a value is possibly ready to be read from. If so, return True,
-- else add ourselves to the waiting map on that value.
--
-- if readyOrWait returns True, the value has definitely already been commited
-- (the sequence number has been assigned to a writer but isn't in the pending
-- map). It may have been over-written however.
readyOrWait :: MVar (Maybe a) -> Int -> Position a -> (Position a, Bool)
readyOrWait await readP p@(Position nextP pMap) =
case IM.updateLookupWithKey (\_ xs -> Just $ await:xs) readP pMap of
(Just _waitList,pMap') -> (p { waiting = pMap' }, False)
(Nothing,_)
| readP >= nextP ->
(p{waiting=IM.insert readP [await] pMap} ,False)
| otherwise -> (p,True)
-- we know the value has been committed, we just need to check that it's still
-- valid.
checkWithPosition :: Int -> Int -> Position a -> (Position a, CheckResult)
checkWithPosition sz readP pos@(Position nextP _pMap) =
case nextP-readP of
dif -- result should be ok.
| dif > 0 && dif <= sz -> (pos,Ok)
-- requests that are too old or too far in the future
| otherwise -> (pos,Invalid)
-- | A Channel that drops elements from the end when a 'KCReader' lags too far
-- behind the writer.
data KickChan v a = KickChan
{ kcSz :: {-# UNPACK #-} !Int
, kcPos :: (IORef (Position a))
, kcV :: (v a)
}
{- invariants
- kcSz is a power of 2 - 1
-}
-- | Create a new 'KickChan' of the requested size. The actual size will be
-- rounded up to the next highest power of 2.
-- The stored size will have one subtracted, because that's the value we use
-- for masking, which is the most common operation.
newKickChan :: (MVector v' a, v ~ v' RealWorld) => Int -> IO (KickChan v a)
newKickChan sz = do
kcPos <- newIORef emptyPosition
kcV <- M.new (kcSz+1)
return KickChan {..}
where
kcSz = 2^(ceiling (logBase 2 (fromIntegral $ sz) :: Double) :: Int) - 1
{-# INLINABLE newKickChan #-}
-- | Get the size of a 'KickChan'.
kcSize :: KickChan v a -> Int
kcSize KickChan {kcSz} = kcSz+1
-- | Put a value into a 'KickChan'.
--
-- if there are multiple writers, putKickChan may block if one writer has
-- wrapped around and a write is pending to the underlying storage location.
--
-- putKickChan will never block on readers, instead 'KCReader's will be
-- invalidated if they lag too far behind.
putKickChan :: (MVector v' a, v ~ v' RealWorld) => KickChan v a -> a -> IO ()
putKickChan KickChan {..} x = mask_ $ do
-- none of these actions should raise exceptions of their own.
-- For async exceptions, everything should be uninterruptible,
-- except 'claim', which calls yield. But if an async exception
-- arises at that point it's ok because we haven't actually
-- claimed a sequence number yet, so there's nothing to clean up.
curSeq <- claim
M.unsafeWrite kcV (curSeq .&. kcSz) x
waiting <- atomicModifyIORef' kcPos $ commit curSeq
Fold.mapM_ (\v -> putMVar v (Just x)) waiting
-- these shouldn't be interrupted as the MVars are definitely empty.
where
claim = do
curSeq'm <- atomicModifyIORef' kcPos (incrPosition (kcSz+1))
maybe (yield >> claim) return curSeq'm
{-# INLINE putKickChan #-}
-- | Invalidate all current readers on a channel.
invalidateKickChan :: KickChan v a -> IO ()
invalidateKickChan KickChan {..} = mask_ $ do
waiting <- atomicModifyIORef' kcPos (invalidatePosition $ 2+kcSz)
Fold.mapM_ (flip putMVar Nothing) waiting
-- see comments for putKickChan WRT exceptions.
-- | get a value from a 'KickChan', or 'Nothing' if no longer available.
--
-- if there are no new values, getKickChan will block until a new value is
-- written, or the channel is invalidated.
getKickChan :: (MVector v' a, v ~ v' RealWorld) => KickChan v a -> Int -> IO (Maybe a)
getKickChan KickChan {..} readP = do
await <- newEmptyMVar
-- we don't need any special exception handling. The worst that can
-- happen is we leave an empty MVar in the Position, but in that case
-- the pending write will clear it out.
proceed <- atomicModifyIORef' kcPos $ readyOrWait await readP
if proceed -- value is definitely committed.
then do
x <- M.unsafeRead kcV (readP .&. kcSz)
-- add 1 to kcSize because we store 1-size
result <- atomicModifyIORef' kcPos (checkWithPosition (kcSz+1) readP)
case result of
Ok -> return $ Just x
Invalid -> return Nothing
else takeMVar await
-- | A reader for a 'KickChan'
data KCReader v a = KCReader
{ kcrChan :: {-# UNPACK #-} !(KickChan v a)
, kcrPos :: IORef Int
}
{- invariants
- kcrPos is the position of the most recently read element (initialized to -1)
-}
-- | create a new reader for a 'KickChan'. The reader will be initialized to
-- the head of the KickChan, so that an immediate call to 'readNext' will
-- block (provided no new values have been put into the chan in the meantime).
newReader :: KickChan v a -> IO (KCReader v a)
newReader kcrChan@KickChan{..} = do
(Position writeP _pMap) <- readIORef kcPos
kcrPos <- newIORef (writeP-1)
return KCReader {..}
{-# INLINABLE newReader #-}
-- | get the next value from a 'KCReader'. This function will block if the next
-- value is not yet available.
--
-- if Nothing is returned, the reader has lagged the writer and values have
-- been dropped.
readNext :: (MVector v' a, v ~ v' RealWorld) => KCReader v a -> IO (Maybe a)
readNext (KCReader {..}) = do
readP <- atomicModifyIORef' kcrPos (\lastP -> let p = lastP+1 in (p,p))
getKickChan kcrChan readP
{-# INLINE readNext #-}
-- | The lag between a 'KCReader' and its writer. Mostly useful for
-- determining if a call to 'readNext' will block.
currentLag :: KCReader v a -> IO Int
currentLag KCReader {..} = do
lastRead <- readIORef kcrPos
Position nextWrite pMap <- readIORef $ kcPos kcrChan
return $! nextWrite - lastRead - IM.size pMap - 1
type KickChanU a = KickChan (U.MVector RealWorld) a
type KickChanS a = KickChan (S.MVector RealWorld) a
type KickChanV a = KickChan (V.MVector RealWorld) a
type KCReaderU a = KCReader (U.MVector RealWorld) a
type KCReaderS a = KCReader (S.MVector RealWorld) a
type KCReaderV a = KCReader (V.MVector RealWorld) a
-- | Constrain a KickChan to work with an 'Unboxed' data storage
kcUnboxed :: KickChan (U.MVector RealWorld) a -> KickChan (U.MVector RealWorld) a
kcUnboxed = id
-- | Constrain a KickChan to work with a standard boxed vector data storage
kcDefault :: KickChan (V.MVector RealWorld) a -> KickChan (V.MVector RealWorld) a
kcDefault = id
-- | Constrain a KickChan to work with a 'Storable' data storage
kcStorable :: KickChan (S.MVector RealWorld) a -> KickChan (S.MVector RealWorld) a
kcStorable = id
| JohnLato/kickchan | src/Chan/KickChan.hs | bsd-3-clause | 10,504 | 0 | 15 | 2,228 | 2,223 | 1,204 | 1,019 | 154 | 3 |
{-# LANGUAGE CPP #-}
{-|
Module : Numeric.CatchingExceptions.Num
Description : CatchingExceptions instances of Num etc
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
CatchingExceptions instances of Num etc.
-}
module Numeric.CatchingExceptions.Num
(
)
where
import Prelude
import Text.Printf
import Control.Lens
import qualified Data.Set as Set
import Numeric.CatchingExceptions.Type
import Numeric.CatchingExceptions.Lifts
instance (Eq t, Show t) => Eq (CatchingNumExceptions t) where
c1 == c2 =
case liftCCtoO (==) c1 c2 of
Just res -> res
_ -> error $ printf "error computing values for comparison: %s == %s" (show c1) (show c2)
c1 /= c2 =
case liftCCtoO (/=) c1 c2 of
Just res -> res
_ -> error $ printf "error computing values for comparison: %s /= %s" (show c1) (show c2)
instance (Ord t, Show t) => Ord (CatchingNumExceptions t) where
compare c1 c2 =
case liftCCtoO compare c1 c2 of
Just res -> res
_ -> error $ printf "error computing values for comparison: %s >=< %s" (show c1) (show c2)
instance (Num t, CanTestValid t, Show t) => Num (CatchingNumExceptions t) where
fromInteger = catchingNumExceptions . fromInteger
signum = liftCtoC signum
abs = liftCtoC abs
negate = liftCtoC negate
(+) = liftCCtoC (+)
(*) = liftCCtoC (*)
testNonZero ::
(Eq t, Num t) =>
t -> Maybe (Set.Set NumericalException, Set.Set NumericalException)
testNonZero b
| b == 0 = Just (Set.empty, Set.singleton DivByZero) -- certain error
| otherwise = Nothing
instance
(Fractional t, Eq t, CanTestValid t, Show t)
=>
Fractional (CatchingNumExceptions t)
where
fromRational = catchingNumExceptions . fromRational
(/) = liftCCtoCwithTest (\ _a b -> testNonZero b) (/)
testPositive ::
(Ord t, Num t) =>
t -> Maybe (Set.Set NumericalException, Set.Set NumericalException)
testPositive b
| b <= 0 = Just (Set.empty, Set.singleton $ OutOfRange "not positive") -- certain error
| otherwise = Nothing
testNonNegative ::
(Ord t, Num t) =>
t -> Maybe (Set.Set NumericalException, Set.Set NumericalException)
testNonNegative b
| b < 0 = Just (Set.empty, Set.singleton $ OutOfRange "not non-negative") -- certain error
| otherwise = Nothing
testInUnit ::
(Ord t, Num t) =>
t -> Maybe (Set.Set NumericalException, Set.Set NumericalException)
testInUnit b
| b < -1 || b > 1 = Just (Set.empty, Set.singleton $ OutOfRange "[-1,1]") -- certain error
| otherwise = Nothing
instance
(Floating t, Ord t, Eq t, CanTestValid t, Show t)
=>
Floating (CatchingNumExceptions t)
where
pi = catchingNumExceptions pi
sqrt = liftCtoCwithTest testNonNegative sqrt
exp = liftCtoC exp
log = liftCtoCwithTest testPositive log
sin = liftCtoC sin
cos = liftCtoC cos
asin = liftCtoCwithTest testInUnit asin
acos = liftCtoCwithTest testInUnit acos
atan = liftCtoC atan
sinh = liftCtoC sinh
cosh = liftCtoC cosh
asinh = liftCtoC asinh
acosh = liftCtoC acosh
atanh = liftCtoCwithTest testInUnit atanh
instance
(Real t, CanTestValid t, Show t)
=>
Real (CatchingNumExceptions t)
where
toRational c =
case c ^. numEXC_maybeValue of
Just v -> toRational v
_ -> error $ printf "error computing argument of toRational: %s" (show c)
instance
(RealFrac t, CanTestValid t, Show t)
=>
RealFrac (CatchingNumExceptions t)
where
properFraction c =
case c ^. numEXC_maybeValue of
Just v ->
let (n,r) = properFraction v
in (n, c & numEXC_maybeValue .~ Just r )
_ -> error $ printf "error computing argument of properFraction: %s" (show c)
| michalkonecny/num-exceptions | src/Numeric/CatchingExceptions/Num.hs | bsd-3-clause | 3,747 | 0 | 13 | 842 | 1,197 | 610 | 587 | 92 | 1 |
-- |
-- Module : Data.Git.Diff
-- License : BSD-style
-- Maintainer : Nicolas DI PRIMA <nicolas@di-prima.fr>
-- Stability : experimental
-- Portability : unix
--
-- Basic Git diff methods.
--
module Data.Git.Diff
(
-- * Basic features
BlobContent(..)
, BlobState(..)
, BlobStateDiff(..)
, getDiffWith
-- * Default helpers
, HitDiff(..)
, HitFileContent(..)
, FilteredDiff(..)
, HitFileRef(..)
, HitFileMode(..)
, TextLine(..)
, defaultDiff
, getDiff
) where
import Data.List (find, filter)
import Data.Char (ord)
import Data.Git
import Data.Git.Repository
import Data.Git.Storage
import Data.Git.Storage.Object
import Data.ByteString.Lazy.Char8 as L
import Data.Algorithm.Patience as AP (Item(..), diff)
-- | represents a blob's content (i.e., the content of a file at a given
-- reference).
data BlobContent = FileContent [L.ByteString] -- ^ Text file's lines
| BinaryContent L.ByteString -- ^ Binary content
deriving (Show)
-- | This is a blob description at a given state (revision)
data BlobState = BlobState
{ bsFilename :: EntPath
, bsMode :: ModePerm
, bsRef :: Ref
, bsContent :: BlobContent
}
deriving (Show)
-- | Two 'BlobState' are equal if they have the same filename, i.e.,
--
-- > ((BlobState x _ _ _) == (BlobState y _ _ _)) = (x == y)
instance Eq BlobState where
(BlobState f1 _ _ _) == (BlobState f2 _ _ _) = (f2 == f1)
a /= b = not (a == b)
-- | Represents a file state between two revisions
-- A file (a blob) can be present in the first Tree's revision but not in the
-- second one, then it has been deleted. If only in the second Tree's revision,
-- then it has been created. If it is in the both, maybe it has been changed.
data BlobStateDiff = OnlyOld BlobState
| OnlyNew BlobState
| OldAndNew BlobState BlobState
buildListForDiff :: Git -> Ref -> IO [BlobState]
buildListForDiff git ref = do
commit <- getCommit git ref
tree <- resolveTreeish git $ commitTreeish commit
case tree of
Just t -> do htree <- buildHTree git t
buildTreeList htree []
_ -> error "cannot build a tree from this reference"
where
buildTreeList :: HTree -> EntPath -> IO [BlobState]
buildTreeList [] _ = return []
buildTreeList ((d,n,TreeFile r):xs) pathPrefix = do
content <- catBlobFile r
let isABinary = isBinaryFile content
listTail <- buildTreeList xs pathPrefix
case isABinary of
False -> return $ (BlobState (entPathAppend pathPrefix n) d r (FileContent $ L.lines content)) : listTail
True -> return $ (BlobState (entPathAppend pathPrefix n) d r (BinaryContent content)) : listTail
buildTreeList ((_,n,TreeDir _ subTree):xs) pathPrefix = do
l1 <- buildTreeList xs pathPrefix
l2 <- buildTreeList subTree (entPathAppend pathPrefix n)
return $ l1 ++ l2
catBlobFile :: Ref -> IO L.ByteString
catBlobFile blobRef = do
mobj <- getObjectRaw git blobRef True
case mobj of
Nothing -> error "not a valid object"
Just obj -> return $ oiData obj
getBinaryStat :: L.ByteString -> Double
getBinaryStat bs = L.foldl' (\acc w -> acc + if isBin $ ord w then 1 else 0) 0 bs / (fromIntegral $ L.length bs)
where
isBin :: Int -> Bool
isBin i
| i >= 0 && i <= 8 = True
| i == 12 = True
| i >= 14 && i <= 31 = True
| otherwise = False
isBinaryFile :: L.ByteString -> Bool
isBinaryFile file = let bs = L.take 512 file
in getBinaryStat bs > 0.0
-- | generate a diff list between two revisions with a given diff helper.
--
-- Useful to extract any kind of information from two different revisions.
-- For example you can get the number of deleted files:
--
-- > getdiffwith f 0 head^ head git
-- > where f (OnlyOld _) acc = acc+1
-- > f _ acc = acc
--
-- Or save the list of new files:
--
-- > getdiffwith f [] head^ head git
-- > where f (OnlyNew bs) acc = (bsFilename bs):acc
-- > f _ acc = acc
getDiffWith :: (BlobStateDiff -> a -> a) -- ^ diff helper (State -> accumulator -> accumulator)
-> a -- ^ accumulator
-> Ref -- ^ commit reference (the original state)
-> Ref -- ^ commit reference (the new state)
-> Git -- ^ repository
-> IO a
getDiffWith f acc ref1 ref2 git = do
commit1 <- buildListForDiff git ref1
commit2 <- buildListForDiff git ref2
return $ Prelude.foldr f acc $ doDiffWith commit1 commit2
where
doDiffWith :: [BlobState] -> [BlobState] -> [BlobStateDiff]
doDiffWith [] [] = []
doDiffWith [bs1] [] = [OnlyOld bs1]
doDiffWith [] (bs2:xs2) = (OnlyNew bs2):(doDiffWith [] xs2)
doDiffWith (bs1:xs1) xs2 =
let bs2Maybe = Data.List.find (\x -> x == bs1) xs2
in case bs2Maybe of
Just bs2 -> let subxs2 = Data.List.filter (\x -> x /= bs2) xs2
in (OldAndNew bs1 bs2):(doDiffWith xs1 subxs2)
Nothing -> (OnlyOld bs1):(doDiffWith xs1 xs2)
data TextLine = TextLine
{ lineNumber :: Integer
, lineContent :: L.ByteString
}
instance Eq TextLine where
a == b = (lineContent a) == (lineContent b)
a /= b = not (a == b)
instance Ord TextLine where
compare a b = compare (lineContent a) (lineContent b)
a < b = (lineContent a) < (lineContent b)
a <= b = (lineContent a) <= (lineContent b)
a > b = b < a
a >= b = b <= a
data FilteredDiff = NormalLine (Item TextLine) | Separator
data HitFileContent = NewBinaryFile
| OldBinaryFile
| NewTextFile [TextLine]
| OldTextFile [TextLine]
| ModifiedBinaryFile
| ModifiedFile [FilteredDiff]
| UnModifiedFile
data HitFileMode = NewMode ModePerm
| OldMode ModePerm
| ModifiedMode ModePerm ModePerm
| UnModifiedMode ModePerm
data HitFileRef = NewRef Ref
| OldRef Ref
| ModifiedRef Ref Ref
| UnModifiedRef Ref
-- | This is a proposed diff records for a given file.
-- It contains useful information:
-- * the filename (with its path in the root project)
-- * a file diff (with the Data.Algorithm.Patience method)
-- * the file's mode (i.e. the file priviledge)
-- * the file's ref
data HitDiff = HitDiff
{ hFileName :: EntPath
, hFileContent :: HitFileContent
, hFileMode :: HitFileMode
, hFileRef :: HitFileRef
}
-- | A default Diff getter which returns all diff information (Mode, Content
-- and Binary) with a context of 5 lines.
--
-- > getDiff = getDiffWith (defaultDiff 5) []
getDiff :: Ref
-> Ref
-> Git
-> IO [HitDiff]
getDiff = getDiffWith (defaultDiff 5) []
-- | A default diff helper. It is an example about how you can write your own
-- diff helper or you can use it if you want to get all of differences.
defaultDiff :: Int -- ^ Number of line for context
-> BlobStateDiff
-> [HitDiff] -- ^ Accumulator
-> [HitDiff] -- ^ Accumulator with a new content
defaultDiff _ (OnlyOld old ) acc =
let oldMode = OldMode (bsMode old)
oldRef = OldRef (bsRef old)
oldContent = case bsContent old of
BinaryContent _ -> OldBinaryFile
FileContent l -> OldTextFile (Prelude.zipWith TextLine [1..] l)
in (HitDiff (bsFilename old) oldContent oldMode oldRef):acc
defaultDiff _ (OnlyNew new) acc =
let newMode = NewMode (bsMode new)
newRef = NewRef (bsRef new)
newContent = case bsContent new of
BinaryContent _ -> NewBinaryFile
FileContent l -> NewTextFile (Prelude.zipWith TextLine [1..] l)
in (HitDiff (bsFilename new) newContent newMode newRef):acc
defaultDiff context (OldAndNew old new) acc =
let mode = if (bsMode old) /= (bsMode new) then ModifiedMode (bsMode old) (bsMode new)
else UnModifiedMode (bsMode new)
ref = if (bsRef old) == (bsRef new) then UnModifiedRef (bsRef new)
else ModifiedRef (bsRef old) (bsRef new)
in case (mode, ref) of
((UnModifiedMode _), (UnModifiedRef _)) -> acc
_ -> (HitDiff (bsFilename new) (content ref) mode ref):acc
where content :: HitFileRef -> HitFileContent
content (UnModifiedRef _) = UnModifiedFile
content _ = createDiff (bsContent old) (bsContent new)
createDiff :: BlobContent -> BlobContent -> HitFileContent
createDiff (FileContent a) (FileContent b) =
let linesA = Prelude.zipWith TextLine [1..] a
linesB = Prelude.zipWith TextLine [1..] b
in ModifiedFile $ diffGetContext context (diff linesA linesB)
createDiff _ _ = ModifiedBinaryFile
-- Used by diffGetContext
data HitwebAccu = AccuBottom | AccuTop
-- Context filter
diffGetContext :: Int -> [Item TextLine] -> [FilteredDiff]
diffGetContext 0 list = fmap NormalLine list
diffGetContext context list =
let (_, _, filteredDiff) = Prelude.foldr filterContext (0, AccuBottom, []) list
theList = removeTrailingBoth filteredDiff
in case Prelude.head theList of
(NormalLine (Both l1 _)) -> if (lineNumber l1) > 1 then Separator:theList
else theList
_ -> theList
where -- only keep 'context'. The file is annalyzed from the bottom to the top.
-- The accumulator here is a tuple3 with (the line counter, the
-- direction and the list of elements)
filterContext :: (Item TextLine) -> (Int, HitwebAccu, [FilteredDiff]) -> (Int, HitwebAccu, [FilteredDiff])
filterContext (Both l1 l2) (c, AccuBottom, acc) =
if c < context then (c+1, AccuBottom, (NormalLine (Both l1 l2)):acc)
else (c , AccuBottom, (NormalLine (Both l1 l2))
:((Prelude.take (context-1) acc)
++ [Separator]
++ (Prelude.drop (context+1) acc)))
filterContext (Both l1 l2) (c, AccuTop, acc) =
if c < context then (c+1, AccuTop , (NormalLine (Both l1 l2)):acc)
else (0 , AccuBottom, (NormalLine (Both l1 l2)):acc)
filterContext element (_, _, acc) =
(0, AccuTop, (NormalLine element):acc)
startWithSeparator :: [FilteredDiff] -> Bool
startWithSeparator [] = False
startWithSeparator (Separator:_) = True
startWithSeparator ((NormalLine l):xs) =
case l of
(Both _ _) -> startWithSeparator xs
_ -> False
removeTrailingBoth :: [FilteredDiff] -> [FilteredDiff]
removeTrailingBoth diffList =
let test = startWithSeparator diffList
in if test then Prelude.tail $ Prelude.dropWhile (\a -> not $ startWithSeparator [a]) diffList
else diffList
| NicolasDP/hit | Data/Git/Diff.hs | bsd-3-clause | 11,919 | 0 | 19 | 4,086 | 3,009 | 1,602 | 1,407 | 202 | 11 |
{-# LANGUAGE OverloadedStrings #-}
module Translit.GHC where
import Data.Char
import qualified Data.List as L
import Data.Text (Text)
import qualified Data.Text as T
import Text.Regex.PCRE
fromCharCode :: Int -> Char
fromCharCode = chr
charCodeAt :: Int -> Text -> Int
charCodeAt i t = ord $ T.index t i
replace :: Text -> Text -> Text -> Text
replace = T.replace
split :: Text -> Text -> [Text]
split "" s = map T.singleton (T.unpack s)
split t s = T.splitOn t s
matchI :: Text -> Text -> Maybe [Text]
matchI reg txt = case T.unpack txt =~ T.unpack reg :: (String,String,String,[String]) of
(_,_,_,[a,b,c]) -> Just [undefined, T.pack a, T.pack b, T.pack c]
_ -> Nothing
join :: Text -> [Text] -> Text
join = T.intercalate
ifThenElse :: Bool -> a -> a -> a
ifThenElse a b c = if a then b else c
find :: (a -> Bool) -> [a] -> Maybe a
find = L.find
| bergmark/transliterate | src/Translit/GHC.hs | bsd-3-clause | 924 | 0 | 11 | 236 | 395 | 218 | 177 | 26 | 2 |
{-#LANGUAGE OverloadedStrings #-}
module Main where
import Streaming
import Streaming.Network.TCP
import qualified Streaming.Prelude as S
import qualified Data.ByteString.Streaming as Q
import Control.Concurrent.Async
import qualified Data.ByteString as B
import Data.ByteString (ByteString)
import Data.Word8 (toUpper, _cr)
import Data.Function ((&))
import Options.Applicative
import Control.Applicative
import Control.Monad
import Data.Monoid
serverToUpper :: IO ()
serverToUpper = do
putStrLn "Opening upper-casing service on 4000"
serve (Host "127.0.0.1") "4000" $ \(client,_) ->
toSocket client $ Q.map toUpper $ fromSocket client 4096
serverDoubler :: IO ()
serverDoubler = do
putStrLn "Double server available on 4001"
serve (Host "127.0.0.1") "4001" $ \(connectionSocket, remoteAddr) ->
fromSocket connectionSocket 4096
& Q.toChunks
& S.map (B.concatMap (\x -> B.pack [x,x]))
& Q.fromChunks
& toSocket connectionSocket
clientToUpper :: IO ()
clientToUpper = connect "127.0.0.1" "4000" $ \(connectionSocket,_) -> do
let act1 = toSocket connectionSocket Q.stdin
act2 = Q.stdout (fromSocket connectionSocket 4096)
concurrently act1 act2
return ()
clientPipeline :: IO ()
clientPipeline = do
putStrLn "We will connect stdin to 4000 and 4001 in succession."
putStrLn "Input will thus be uppercased and doubled char-by-char.\n"
connect "127.0.0.1" "4000" $ \(socket1,_) ->
connect "127.0.0.1" "4001" $ \(socket2,_) ->
do let act1 = toSocket socket1 (Q.stdin)
act2 = toSocket socket2 (fromSocket socket1 4096)
act3 = Q.stdout (fromSocket socket2 4096)
runConcurrently $ Concurrently act1 *>
Concurrently act2 *>
Concurrently act3
proxyToUpper :: IO ()
proxyToUpper =
serve (Host "127.0.0.1") "4002" $ \(client, _) ->
connect "127.0.0.1" "4000" $ \(server, _) ->
do let act1 = toSocket server (fromSocket client 4096)
act2 = toSocket client (fromSocket server 4096)
concurrently act1 act2
return ()
proxyAuth :: IO ()
proxyAuth = serve (Host "127.0.0.1") "4003" process
where
process (client, _) =
do from_client <- toSocket client (checkAuth (fromSocket client 4096))
connect "127.0.0.1" "4000" $ \(server,_) ->
do let pipe_forward = toSocket server from_client
pipe_back = toSocket client (fromSocket server 4096)
concurrently pipe_forward pipe_back
return ()
checkAuth :: MonadIO m => Q.ByteString m r -> Q.ByteString m (Q.ByteString m r)
checkAuth p = do
Q.chunk "Username: "
(username,p1) <- lift $ shortLineInput 80 p
Q.chunk "Password: "
(password,p2) <- lift $ shortLineInput 80 p1
if (username, password) `elem` creds
then Q.chunk "Successfully authenticated.\n"
else do Q.chunk "Invalid username/password.\n"
error "Invalid authentication, please log somewhere..."
return p2 -- when using `error`
shortLineInput n bs = do
(bs:>rest) <- Q.toStrict $ Q.break (==10) $ Q.splitAt n bs
return $ (B.filter (/= _cr) bs, Q.drop 1 $ rest >>= id)
creds :: [(ByteString, ByteString)]
creds = [ ("spaceballs", "12345") ]
main :: IO ()
main = join $ execParser (info opts idm) where
opts :: Parser (IO ())
opts = helper <*> subparser stuff where
stuff = mconcat
[ command "ClientPipeline" (info (pure clientPipeline) idm)
, command "ClientToUpper" (info (pure clientToUpper) idm)
, command "ProxyAuth" (info (pure proxyAuth) idm)
, command "ProxyToUpper" (info (pure proxyToUpper) idm)
, command "ServerDouble" (info (pure serverDoubler) idm)
, command "ServerToUpper" (info (pure serverToUpper) idm)
]
| michaelt/streaming-network-tcp-examples | Main.hs | bsd-3-clause | 3,934 | 0 | 18 | 1,008 | 1,247 | 633 | 614 | 91 | 2 |
-- | Main API module
--
-- Use the functions in `Finance.TradeKing.Quotes` for access to the TradeKing API.
--
-- The functions in `Finance.TradeKing.Service` provide lower-level access to the TradeKing API,
-- handling things such as OAuth.
module Finance.TradeKing
(module Finance.TradeKing.Types,
module Finance.TradeKing.Service,
module Finance.TradeKing.Quotes,
module Finance.TradeKing.Config)
where
import Finance.TradeKing.Types
import Finance.TradeKing.Service
import Finance.TradeKing.Quotes
import Finance.TradeKing.Config | tathougies/hstradeking | src/Finance/TradeKing.hs | bsd-3-clause | 578 | 0 | 5 | 100 | 66 | 47 | 19 | 9 | 0 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Tut.Json
( module Tut.Json
) where
import Tut.Misc
import Control.Category1
import Data.Aeson.Types
import qualified Data.Text as T
maybeFieldW :: Object -> Text -> (Value -> Parser a) -> Parser (Maybe a)
maybeFieldW v k p = v .:? k >>= traverse p
textCaseParser :: [(Text, b)] -> Value -> Parser b
textCaseParser xs v = do
t <- (parseJSON v :: Parser Text)
maybe empty return $ lookup t xs
data Field a = Field
{ fieldName :: Text
, fieldParser :: Value -> Parser a
, fieldSemigroup :: a -> a -> a
, fieldDefault :: Maybe a
}
field
:: FromJSON a
=> Text -> Field a
field n = Field n parseJSON const Nothing
fieldWDef
:: FromJSON a
=> Text -> a -> Field a
fieldWDef n d =
(field n)
{ fieldDefault = Just d
}
data MetaConfig f = MetaConfig
{ _topField :: Text
, _configFields :: f Field
, _configFromString :: Text -> (Text, f Maybe)
, _extraConfigs :: Endo [(Text, f Maybe)]
, _nameField :: Text
, _defaultsField :: Text
, _configsField :: Text
}
defaultMetaConfig :: Text -> f Field -> (Text -> f Maybe) -> MetaConfig f
defaultMetaConfig tf flds f =
MetaConfig
{ _topField = tf
, _configFields = flds
, _configFromString = (,) "" . f
, _extraConfigs = mempty
, _nameField = "name"
, _defaultsField = "defaults"
, _configsField = "configs"
}
topField
:: Functor f
=> (Text -> f Text) -> MetaConfig f1 -> f (MetaConfig f1)
topField ff (MetaConfig a b c d e f g) =
fmap (\a' -> MetaConfig a' b c d e f g) (ff a)
configFields
:: Functor f
=> (f1 Field -> f (f1 Field)) -> MetaConfig f1 -> f (MetaConfig f1)
configFields ff (MetaConfig a b c d e f g) =
fmap (\b' -> MetaConfig a b' c d e f g) (ff b)
configFromString
:: Functor f
=> ((Text -> (Text, f1 Maybe)) -> f (Text -> (Text, f1 Maybe)))
-> MetaConfig f1
-> f (MetaConfig f1)
configFromString ff (MetaConfig a b c d e f g) =
fmap (\c' -> MetaConfig a b c' d e f g) (ff c)
extraConfigs
:: Functor f
=> (Endo [(Text, f1 Maybe)] -> f (Endo [(Text, f1 Maybe)]))
-> MetaConfig f1
-> f (MetaConfig f1)
extraConfigs ff (MetaConfig a b c d e f g) =
fmap (\d' -> MetaConfig a b c d' e f g) (ff d)
nameField
:: Functor f
=> (Text -> f Text) -> MetaConfig f1 -> f (MetaConfig f1)
nameField ff (MetaConfig a b c d e f g) =
fmap (\e' -> MetaConfig a b c d e' f g) (ff e)
defaultsField
:: Functor f
=> (Text -> f Text) -> MetaConfig f1 -> f (MetaConfig f1)
defaultsField ff (MetaConfig a b c d e f g) =
fmap (\f' -> MetaConfig a b c d e f' g) (ff f)
configsField
:: Functor f
=> (Text -> f Text) -> MetaConfig f1 -> f (MetaConfig f1)
configsField ff (MetaConfig a b c d e f g) =
fmap (\g' -> MetaConfig a b c d e f g') (ff g)
metaConfig
:: Functor1 f
=> Text -> f Field -> Setter' (f Maybe) (Maybe Text) -> MetaConfig f
metaConfig tf flds l =
defaultMetaConfig tf flds (\t -> set l (Just t) (map1 fieldDefault flds))
class AsParseError e where
parseError :: String -> e
instance AsParseError String where
parseError = ("Error parsing json: " ++)
runParser
:: (MonadError e m, AsParseError e)
=> Parser a -> m a
runParser p = eitherError . left parseError $ parseEither (const p) ()
class AsUndefinedField e where
undefinedField :: Text -> e
instance AsUndefinedField String where
undefinedField = ("Undefined field: " ++) . T.unpack
parseTutMeta
:: forall e m f.
( MonadError e m
, AsParseError e
, AsUndefinedField e
, Traversable_1 f
, Applicative1 f
)
=> MetaConfig f -> Object -> m [(Text, f Identity)]
parseTutMeta cfg o =
runParser configs >>=
(traverse . traverse)
(completeFields . wDefConfigs (map1 fieldDefault fields))
where
fields = (_configFields cfg)
--
configs :: Parser [(Text, f Maybe)]
configs = maybeFieldW o (_topField cfg) parseConfigs .!= withExtraConfigs []
--
withExtraConfigs = appEndo (_extraConfigs cfg)
--
parseConfigs :: Value -> Parser [(Text, f Maybe)]
parseConfigs (String t) =
return $ withExtraConfigs [_configFromString cfg t]
parseConfigs (Object v) = do
d <- maybeFieldW v (_defaultsField cfg) parseConfig .!= pure1 Nothing
cs <- v .:? _configsField cfg .!= [] >>= traverse parseNamed
return $ (fmap . fmap) (wDefConfigs d) (withExtraConfigs cs)
parseConfigs j@(Array _) =
fmap withExtraConfigs $ traverse parseNamed =<< parseJSON j
parseConfigs _ = empty
--
parseNamed :: Value -> Parser (Text, f Maybe)
parseNamed (Object v) = (,) <$> v .: _nameField cfg <*> parseConfigO v
parseNamed _ = empty
--
parseConfig :: Value -> Parser (f Maybe)
parseConfig (Object v) = parseConfigO v
parseConfig _ = empty
--
parseConfigO :: Object -> Parser (f Maybe)
parseConfigO v = traverse_1 (\(Field n p _ _) -> maybeFieldW v n p) fields
--
completeFields =
sequence_1I . lift2_1 (maybeError . undefinedField . fieldName) fields
--
wDefConfigs = flip $ lift3_1 (maybeSemigroup . fieldSemigroup) fields
| aaronvargo/htut | src/Tut/Json.hs | bsd-3-clause | 5,157 | 0 | 14 | 1,232 | 2,134 | 1,092 | 1,042 | 142 | 6 |
{-# LANGUAGE
CPP
, DefaultSignatures
, DeriveDataTypeable
, FlexibleInstances
, FlexibleContexts
, GADTs
, MultiParamTypeClasses
, Rank2Types #-}
#ifdef LANGUAGE_Trustworthy
{-# LANGUAGE Trustworthy #-}
#endif
{-# LANGUAGE
TypeFamilies
, TypeOperators
, UndecidableInstances #-}
{- |
Copyright : (c) Andy Sonnenburg 2013
License : BSD3
Maintainer : andy22286@gmail.com
-}
module Data.Tuple.ByteArray
( ByteArrayTuple
) where
import Control.Applicative
import Control.Monad.Prim
import Data.ByteArraySlice.Unsafe
import Data.Prim.ByteArray
import Data.Tuple.ITuple
import Data.Tuple.ITuple.Proxy
import Data.Tuple.MTuple
import Data.Typeable (Typeable)
newtype ByteArrayTuple s a = ByteArrayTuple (MutableByteArray s) deriving (Eq, Typeable)
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
) => MTuple (ByteArrayTuple s) t m where
thawTuple a = runPrim $ do
array <- newByteArray (byteSizeOf' a)
writeByteOff array 0 (toTuple a)
return $ ByteArrayTuple array
freezeTuple (ByteArrayTuple array) =
runPrim $ fromTuple <$> readByteOff array 0
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
) => MField1 (ByteArrayTuple s) t m where
read1 = unsafeRead offset1
write1 = unsafeWrite offset1
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
) => MField2 (ByteArrayTuple s) t m where
read2 = unsafeRead offset2
write2 = unsafeWrite offset2
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
) => MField3 (ByteArrayTuple s) t m where
read3 = unsafeRead offset3
write3 = unsafeWrite offset3
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
) => MField4 (ByteArrayTuple s) t m where
read4 = unsafeRead offset4
write4 = unsafeWrite offset4
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
) => MField5 (ByteArrayTuple s) t m where
read5 = unsafeRead offset5
write5 = unsafeWrite offset5
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
, ByteArraySlice (Field6 t)
) => MField6 (ByteArrayTuple s) t m where
read6 = unsafeRead offset6
write6 = unsafeWrite offset6
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
, ByteArraySlice (Field6 t)
, ByteArraySlice (Field7 t)
) => MField7 (ByteArrayTuple s) t m where
read7 = unsafeRead offset7
write7 = unsafeWrite offset7
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
, ByteArraySlice (Field6 t)
, ByteArraySlice (Field7 t)
, ByteArraySlice (Field8 t)
) => MField8 (ByteArrayTuple s) t m where
read8 = unsafeRead offset8
write8 = unsafeWrite offset8
instance ( MonadPrim m
, s ~ World m
, ITuple t
, ByteArraySlice (Tuple (ListRep t))
, ByteArraySlice (Field1 t)
, ByteArraySlice (Field2 t)
, ByteArraySlice (Field3 t)
, ByteArraySlice (Field4 t)
, ByteArraySlice (Field5 t)
, ByteArraySlice (Field6 t)
, ByteArraySlice (Field7 t)
, ByteArraySlice (Field8 t)
, ByteArraySlice (Field9 t)
) => MField9 (ByteArrayTuple s) t m where
read9 = unsafeRead offset9
write9 = unsafeWrite offset9
byteSizeOf' :: (ITuple t, ByteArraySlice (Tuple (ListRep t))) => t -> Int
byteSizeOf' = plusByteSize 0 . proxyTuple
unsafeRead :: ( ByteArraySlice a
, MonadPrim m
) => (forall f . f t -> Int) -> ByteArrayTuple (World m) t -> m a
unsafeRead offset t@(ByteArrayTuple array) =
runPrim $ readByteOff array (offset t)
unsafeWrite :: ( ByteArraySlice a
, MonadPrim m
) => (forall f . f t -> Int) -> ByteArrayTuple (World m) t -> a -> m ()
unsafeWrite offset t@(ByteArrayTuple array) a =
runPrim $ writeByteOff array (offset t) a
offset1 :: t a -> Int
offset1 _ = 0
offset2 :: ByteArraySlice (Field1 a) => t a -> Int
offset2 a = plusByteSize (offset1 a) (reproxyField1 a)
offset3 :: ( ByteArraySlice (Field1 a)
, ByteArraySlice (Field2 a)
) => t a -> Int
offset3 a = plusByteSize (offset2 a) (reproxyField2 a)
offset4 :: ( ByteArraySlice (Field1 a)
, ByteArraySlice (Field2 a)
, ByteArraySlice (Field3 a)
) => t a -> Int
offset4 a = plusByteSize (offset3 a) (reproxyField3 a)
offset5 :: ( ByteArraySlice (Field1 a)
, ByteArraySlice (Field2 a)
, ByteArraySlice (Field3 a)
, ByteArraySlice (Field4 a)
) => t a -> Int
offset5 a = plusByteSize (offset4 a) (reproxyField4 a)
offset6 :: ( ByteArraySlice (Field1 a)
, ByteArraySlice (Field2 a)
, ByteArraySlice (Field3 a)
, ByteArraySlice (Field4 a)
, ByteArraySlice (Field5 a)
) => t a -> Int
offset6 a = plusByteSize (offset5 a) (reproxyField5 a)
offset7 :: ( ByteArraySlice (Field1 a)
, ByteArraySlice (Field2 a)
, ByteArraySlice (Field3 a)
, ByteArraySlice (Field4 a)
, ByteArraySlice (Field5 a)
, ByteArraySlice (Field6 a)
) => t a -> Int
offset7 a = plusByteSize (offset6 a) (reproxyField6 a)
offset8 :: ( ByteArraySlice (Field1 a)
, ByteArraySlice (Field2 a)
, ByteArraySlice (Field3 a)
, ByteArraySlice (Field4 a)
, ByteArraySlice (Field5 a)
, ByteArraySlice (Field6 a)
, ByteArraySlice (Field7 a)
) => t a -> Int
offset8 a = plusByteSize (offset7 a) (reproxyField7 a)
offset9 :: ( ByteArraySlice (Field1 a)
, ByteArraySlice (Field2 a)
, ByteArraySlice (Field3 a)
, ByteArraySlice (Field4 a)
, ByteArraySlice (Field5 a)
, ByteArraySlice (Field6 a)
, ByteArraySlice (Field7 a)
, ByteArraySlice (Field8 a)
) => t a -> Int
offset9 a = plusByteSize (offset8 a) (reproxyField8 a)
| sonyandy/var | src/Data/Tuple/ByteArray.hs | bsd-3-clause | 7,545 | 0 | 12 | 2,332 | 2,492 | 1,259 | 1,233 | 208 | 1 |
blah :: [String] -> (Integer, String)
blah (y:x) = (read y, concat x)
main = do
x <- fmap (map (blah . words) . lines) getContents
let mn = minimum (map fst (filter ((/= "") . snd) x))
let mx = maximum (map fst (filter ((/= "") . snd) x))
let scale = mx - mn;
let minFont = 75
let maxFont = 150
flip mapM x $ \(v,s) ->
if s /= "" then do
let ratio = fromInteger (v - mn) / fromInteger (scale)
let fontSize = ratio * (maxFont - minFont) + minFont
let t = takeWhile (/= '.') s
putStrLn $ "<a style='font-size:" ++ show fontSize ++ "%;' href='/" ++ t ++ ".html' >" ++ drop 1(dropWhile (/= '/') t) ++ "</a>"
else return ()
| liamoc/liamoc.net | clouds.hs | bsd-3-clause | 666 | 0 | 18 | 176 | 352 | 178 | 174 | 16 | 2 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
-- |
-- Module : Data.Array.Nikola.Language.Optimize.Simpl
-- Copyright : (c) Geoffrey Mainland 2012
-- License : BSD-style
--
-- Maintainer : Geoffrey Mainland <mainland@apeiron.net>
-- Stability : experimental
-- Portability : non-portable
module Data.Array.Nikola.Language.Optimize.Simpl (simpl) where
import Prelude hiding (mapM)
import Control.Applicative (Applicative, pure)
import Text.PrettyPrint.Mainland
import Data.Array.Nikola.Language.Generic
import Data.Array.Nikola.Language.Optimize.Monad
import Data.Array.Nikola.Language.Optimize.Subst
import Data.Array.Nikola.Language.Syntax
simpl :: AST a -> a -> O a
simpl ExpA (VarE v) = lookupSubst VarA v ExpA (return (VarE v))
simpl ExpA (UnopE op e) = do e' <- simpl ExpA e
go op e'
where
go :: Unop -> Exp -> O Exp
go SqrtF (ConstE (FloatC i)) = pure $ ConstE (FloatC (sqrt i))
go RecipF (ConstE (FloatC i)) = pure $ ConstE (FloatC (1/i))
go SqrtF (ConstE (DoubleC i)) = pure $ ConstE (DoubleC (sqrt i))
go RecipF (ConstE (DoubleC i)) = pure $ ConstE (DoubleC (1/i))
go op e = return $ UnopE op e
simpl ExpA (BinopE op e1 e2) = do e1' <- simpl ExpA e1
e2' <- simpl ExpA e2
go op e1' e2'
where
go :: Binop -> Exp -> Exp -> O Exp
go EqO (ConstE c1) (ConstE c2) = pure $ ConstE (liftOrd2 (==) c1 c2)
go NeO (ConstE c1) (ConstE c2) = pure $ ConstE (liftOrd2 (/=) c1 c2)
go GtO (ConstE c1) (ConstE c2) = pure $ ConstE (liftOrd2 (>) c1 c2)
go GeO (ConstE c1) (ConstE c2) = pure $ ConstE (liftOrd2 (>=) c1 c2)
go LtO (ConstE c1) (ConstE c2) = pure $ ConstE (liftOrd2 (<) c1 c2)
go LeO (ConstE c1) (ConstE c2) = pure $ ConstE (liftOrd2 (<=) c1 c2)
go MaxO (ConstE c1) (ConstE c2) = pure $ ConstE (liftMinMax2 max c1 c2)
go MinO (ConstE c1) (ConstE c2) = pure $ ConstE (liftMinMax2 min c1 c2)
go AddN (ConstE c) e2
| c `equalTo` 0 = pure e2
go AddN (ConstE i) (ConstE j) = pure $ ConstE (liftNum2 (+) i j)
go AddN e1 (BinopE AddN e2 e3) = simpl ExpA (BinopE AddN (BinopE AddN e1 e2) e3)
go AddN e1 e2@(ConstE {}) = simpl ExpA (BinopE AddN e2 e1)
go SubN (ConstE i) (ConstE j) = pure $ ConstE (liftNum2 (-) i j)
go SubN e1 (ConstE c)
| c `equalTo` 0 = pure e2
| otherwise = simpl ExpA (BinopE AddN (ConstE (liftNum negate c)) e1)
go MulN (ConstE c) e2
| c `equalTo` 0 = pure $ ConstE (liftNum (const 0) c)
| c `equalTo` 1 = pure e2
go MulN (ConstE i) (ConstE j) = pure $ ConstE (liftNum2 (*) i j)
go MulN e1 e2@(ConstE {}) = simpl ExpA (BinopE MulN e2 e1)
go MulN e1 (BinopE MulN e2 e3) = simpl ExpA (BinopE MulN (BinopE MulN e1 e2) e3)
go QuotI e1 (ConstE c)
| c `equalTo` 1 = pure e1
go RemI e1 (ConstE c)
| c `equalTo` 1 = pure e1
go DivF e1 (ConstE c) = simpl ExpA (BinopE MulN e1 (ConstE c'))
where
c' :: Const
c' = liftFractional (1.0/) c
go DivF (ConstE c) e2
| c `equalTo` 1 = simpl ExpA (UnopE RecipF e2)
-- Default
go op e1 e2 = return $ BinopE op e1 e2
simpl ExpA (CallE (LamE [] e) []) =
case finalReturn e of
(Nothing, Nothing) -> fail "internal error: empty kernel"
(Nothing, Just e) -> simpl ExpA (ReturnE e)
(Just m, Nothing) -> traverseFam simpl ExpA (CallE (LamE [] m) [])
(Just m, Just e) -> traverseFam simpl ExpA (SeqE (CallE (LamE [] m) []) (ReturnE e))
where
finalReturn :: Exp -> (Maybe Exp, Maybe Exp)
finalReturn (ReturnE e) = (Nothing, Just e)
finalReturn (SeqE m1 (ReturnE e)) = (Just m1, Just e)
finalReturn (SeqE m1 m2) = case finalReturn m2 of
(Nothing, maybe_e) -> (Just m1, maybe_e)
(Just m2, maybe_e) -> (Just (SeqE m1 m2), maybe_e)
finalReturn m = (Just m, Nothing)
simpl w a = traverseFam simpl w a
equalTo :: Const -> Integer -> Bool
equalTo (Int8C n1) n2 = n1 == fromIntegral n2
equalTo (Int16C n1) n2 = n1 == fromIntegral n2
equalTo (Int32C n1) n2 = n1 == fromIntegral n2
equalTo (Int64C n1) n2 = n1 == fromIntegral n2
equalTo (Word8C n1) n2 = n1 == fromIntegral n2
equalTo (Word16C n1) n2 = n1 == fromIntegral n2
equalTo (Word32C n1) n2 = n1 == fromIntegral n2
equalTo (Word64C n1) n2 = n1 == fromIntegral n2
equalTo (FloatC n1) n2 = n1 == fromIntegral n2
equalTo (DoubleC n1) n2 = n1 == fromIntegral n2
equalTo c n = errordoc $
text "internal error: equalTo:" <+>
ppr c <+> ppr n
liftOrd2 :: (forall a . Ord a => a -> a -> Bool)
-> Const -> Const -> Const
liftOrd2 op c1 c2 =
go c1 c2
where
go :: Const -> Const -> Const
go (BoolC c1) (BoolC c2) = BoolC (op c1 c2)
go (Int8C c1) (Int8C c2) = BoolC (op c1 c2)
go (Int16C c1) (Int16C c2) = BoolC (op c1 c2)
go (Int32C c1) (Int32C c2) = BoolC (op c1 c2)
go (Int64C c1) (Int64C c2) = BoolC (op c1 c2)
go (Word8C c1) (Word8C c2) = BoolC (op c1 c2)
go (Word16C c1) (Word16C c2) = BoolC (op c1 c2)
go (Word32C c1) (Word32C c2) = BoolC (op c1 c2)
go (Word64C c1) (Word64C c2) = BoolC (op c1 c2)
go (FloatC c1) (FloatC c2) = BoolC (op c1 c2)
go (DoubleC c1) (DoubleC c2) = BoolC (op c1 c2)
go c1 c2 = errordoc $
text "internal error: liftOrd2:" <+>
ppr c1 <+> ppr c2
liftMinMax2 :: (forall a . Ord a => a -> a -> a)
-> Const -> Const -> Const
liftMinMax2 op c1 c2 =
go c1 c2
where
go :: Const -> Const -> Const
go (BoolC c1) (BoolC c2) = BoolC (op c1 c2)
go (Int8C c1) (Int8C c2) = Int8C (op c1 c2)
go (Int16C c1) (Int16C c2) = Int16C (op c1 c2)
go (Int32C c1) (Int32C c2) = Int32C (op c1 c2)
go (Int64C c1) (Int64C c2) = Int64C (op c1 c2)
go (Word8C c1) (Word8C c2) = Word8C (op c1 c2)
go (Word16C c1) (Word16C c2) = Word16C (op c1 c2)
go (Word32C c1) (Word32C c2) = Word32C (op c1 c2)
go (Word64C c1) (Word64C c2) = Word64C (op c1 c2)
go (FloatC c1) (FloatC c2) = FloatC (op c1 c2)
go (DoubleC c1) (DoubleC c2) = DoubleC (op c1 c2)
go c1 c2 = errordoc $
text "internal error: liftMinMax2:" <+>
ppr c1 <+> ppr c2
liftNum :: (forall a . Num a => a -> a)
-> Const -> Const
liftNum op c =
go c
where
go :: Const -> Const
go (Int8C c) = Int8C (op c)
go (Int16C c) = Int16C (op c)
go (Int32C c) = Int32C (op c)
go (Int64C c) = Int64C (op c)
go (Word8C c) = Word8C (op c)
go (Word16C c) = Word16C (op c)
go (Word32C c) = Word32C (op c)
go (Word64C c) = Word64C (op c)
go (FloatC c) = FloatC (op c)
go (DoubleC c) = DoubleC (op c)
go c = errordoc $
text "internal error: liftNum:" <+>
ppr c
liftNum2 :: (forall a . Num a => a -> a -> a)
-> Const -> Const -> Const
liftNum2 op c1 c2 =
go c1 c2
where
go :: Const -> Const -> Const
go (Int8C c1) (Int8C c2) = Int8C (op c1 c2)
go (Int16C c1) (Int16C c2) = Int16C (op c1 c2)
go (Int32C c1) (Int32C c2) = Int32C (op c1 c2)
go (Int64C c1) (Int64C c2) = Int64C (op c1 c2)
go (Word8C c1) (Word8C c2) = Word8C (op c1 c2)
go (Word16C c1) (Word16C c2) = Word16C (op c1 c2)
go (Word32C c1) (Word32C c2) = Word32C (op c1 c2)
go (Word64C c1) (Word64C c2) = Word64C (op c1 c2)
go (FloatC c1) (FloatC c2) = FloatC (op c1 c2)
go (DoubleC c1) (DoubleC c2) = DoubleC (op c1 c2)
go c1 c2 = errordoc $
text "internal error: liftNum2:" <+>
ppr c1 <+> ppr c2
liftFractional :: (forall a . Fractional a => a -> a)
-> Const -> Const
liftFractional op c =
go c
where
go :: Const -> Const
go (FloatC c) = FloatC (op c)
go (DoubleC c) = DoubleC (op c)
go c = errordoc $
text "internal error: liftFractional:" <+>
ppr c
{-
liftIntegral2 :: (forall a . Integral a => a -> a -> a)
-> Const -> Const -> Const
liftIntegral2 op c1 c2 =
go c1 c2
where
go :: Const -> Const -> Const
go (Int8C c1) (Int8C c2) = Int8C (op c1 c2)
go (Int16C c1) (Int16C c2) = Int16C (op c1 c2)
go (Int32C c1) (Int32C c2) = Int32C (op c1 c2)
go (Int64C c1) (Int64C c2) = Int64C (op c1 c2)
go (Word8C c1) (Word8C c2) = Word8C (op c1 c2)
go (Word16C c1) (Word16C c2) = Word16C (op c1 c2)
go (Word32C c1) (Word32C c2) = Word32C (op c1 c2)
go (Word64C c1) (Word64C c2) = Word64C (op c1 c2)
go c1 c2 = errordoc $
text "internal error: liftIntegral2:" <+>
ppr c1 <+> ppr c2
liftFractional2 :: (forall a . Fractional a => a -> a -> a)
-> Const -> Const -> Const
liftFractional2 op c1 c2 =
go c1 c2
where
go :: Const -> Const -> Const
go (FloatC c1) (FloatC c2) = FloatC (op c1 c2)
go (DoubleC c1) (DoubleC c2) = DoubleC (op c1 c2)
go c1 c2 = errordoc $
text "internal error: liftFractional2:" <+>
ppr c1 <+> ppr c2
liftFloating2 :: (forall a . Floating a => a -> a -> a)
-> Const -> Const -> Const
liftFloating2 op c1 c2 =
go c1 c2
where
go :: Const -> Const -> Const
go (FloatC c1) (FloatC c2) = FloatC (op c1 c2)
go (DoubleC c1) (DoubleC c2) = DoubleC (op c1 c2)
go c1 c2 = errordoc $
text "internal error: liftFloating2:" <+>
ppr c1 <+> ppr c2
-}
| mainland/nikola | src/Data/Array/Nikola/Language/Optimize/Simpl.hs | bsd-3-clause | 10,409 | 0 | 15 | 3,780 | 3,904 | 1,940 | 1,964 | 169 | 34 |
module Sexy.Instances.Applicative.IO () where
import Sexy.Data (IO(..))
import Sexy.Classes (Applicative(..))
import Sexy.Instances.Functor.IO ()
import Sexy.Instances.Pure.IO ()
instance Applicative IO where
-- (<*>) :: IO (a -> b) -> IO a -> IO b
(IO f) <*> (IO x) =
IO (\rw -> let (# rw', f' #) = f rw
(# rw'', x' #) = x rw'
in (# rw'', f' x' #))
| DanBurton/sexy | src/Sexy/Instances/Applicative/IO.hs | bsd-3-clause | 395 | 0 | 13 | 108 | 144 | 82 | 62 | -1 | -1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StandaloneDeriving #-}
module GenerateSketch where
import Data.Char
import Data.Data
import Data.Functor
import Data.List
import Language.ArrayForth.Opcode
import Language.ArrayForth.Program
import Text.Printf
import qualified Conditions
import Conditions (Condition (..))
import SketchQQ
deriving instance Typeable Opcode
deriving instance Data Opcode
-- | Settings that control how the problem gets synthesized.
data Settings =
Settings { supportedOpcodes :: [Opcode]
, inputs :: [Condition]
, outputs :: [Condition]
, prefix :: FilePath -- ^ the prefix to use to import instrs.sk
, literalHoles :: Bool -- ^ allow literal numbers in sketch?
, holes :: Int -- ^ number of holes in sketch
, bits :: Int -- ^ number of bits in Forth words
} deriving (Show)
-- | The usual set of supported instructions. Pretty much anything
-- without a literal address encoded in the instruction.
--
-- MultiplyStep is also not supported, but it should be in the
-- future.
supported :: [Opcode]
supported = [ FetchP
, FetchPlus
, FetchB
, Fetch
, StoreP
, StorePlus
, StoreB
, Store
, Times2
, Div2
, Not
, Plus
, And
, Or
, Drop
, Dup
, Pop
, Over
, ReadA
, Nop
, Push
, SetB
, SetA
]
harness :: Settings -> Program -> String
harness settings@Settings {..} spec = [sketch|
include "$prefix-instrs.sk";
pragma options "--bnd-int-range 1000";
struct Ret {
$fields;
}
|Ret| spec($arguments) {
reset();
int step = 0;
$assignments;
$specProgram;
return |Ret|($retVals);
}
|Ret| sketch($arguments) implements spec {
reset();
int step = 0;
$assignments;
$holesSk
return |Ret|($retVals);
}
|]
where specProgram = program bits spec
holesSk = genHoles settings holes
fields = Conditions.fields outputs
arguments = Conditions.arguments inputs
assignments = Conditions.fieldAssignments inputs
retVals = Conditions.returnedValues outputs
callOpcode :: Opcode -> String
callOpcode instr = let (f:rest) = showConstr $ toConstr instr in toLower f : rest ++ "(step)"
callLiteral :: Int -> F18Word -> String
callLiteral bitSize = printf "loadLiteral({%s}, step)" . Conditions.toBits bitSize
call :: Int -> Instruction -> String
call _ (Opcode op) = callOpcode op
call bitSize (Number n) = callLiteral bitSize n
call _ op = error $ "Specs with jumps, labels or holes are not supported! Instr " ++ show op ++ " is invalid"
program :: Int -> Program -> String
program bits = intercalate ";\n " . map (\ op -> "step = " ++ call bits op)
genHoles :: Settings -> Int -> String
genHoles Settings { supportedOpcodes, literalHoles } n =
drop 2 . unlines $ replicate n [sketch|
step = {| $opcodeCalls $literalHole |};
|]
where opcodeCalls = intercalate " | " $ map callOpcode supportedOpcodes
literalHole | literalHoles = "| loadLiteral(??, step)"
| otherwise = ""
| TikhonJelvis/array-forth-sketch | src/GenerateSketch.hs | bsd-3-clause | 3,643 | 0 | 10 | 1,173 | 644 | 363 | 281 | 77 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving, TemplateHaskell #-}
module Haskcord.Resource.User
where
import Control.Lens
import Data.Aeson
import Data.HashMap (lookup)
import Data.Word
import Haskcord.Resource.Base
import Haskcord.Resource.Id
data UserResource = UserResource {
_userResourceId :: UserId
, _userResourceName :: T.Text
, _userResourceDiscriminator :: T.Text
, _userResourceAvatarHash :: T.Text
, _userResourceBot :: Bool
, _userResourceMfaEnabled :: Bool
, _userResourceVerifiedEmail :: Maybe Bool
, _userResourceEmail :: Maybe T.Text
}
deriving (Show, Read, Eq)
class FromJSON UserResource where
parseJSON (Object v) = UserResource
<$> v .: "id"
<*> v .: "username"
<*> v .: "discriminator"
<*> v .: "avatar"
<*> v .: "bot"
<*> v .: "mfa_enabled"
<*> v .:? "verified"
<*> v .:? "email"
parseJSON _ = empty
instance Resource UserResource where
syncResource user v = UserResource {
_userResourceId = userResourceId user
, _userResourceName = fromMaybe (view userResourceName user) (lookup "username" v)
, _userResourceDiscriminator = fromMaybe (view userResourceDiscriminator user) (lookup "discriminator" v)
, _userResourceAvatarHash = fromMaybe (view userResourceAvatarHash user) (lookup "avatar" v)
, _userResourceBot = fromMaybe (view userResourceBot user) (lookup "bot" v)
, _userResourceMfaEnabled = fromMaybe (view userResourceMfaEnabled user) (lookup "mfa_enabled" v)
, _userResourceVerifiedEmail = fromMaybe (view userResourceVerifiedEmail user) (Just <$> lookup "verified" v)
, _userResourceEmail = fromMaybe (view userEmail user) (Just <$> lookup "email" v)
}
| swagcod/haskcord | src/Haskcord/Resource/User.hs | bsd-3-clause | 1,778 | 0 | 22 | 395 | 452 | 244 | 208 | -1 | -1 |
{-
- Program1.hs
- By Steven Smith
-}
{-# LANGUAGE OverloadedStrings, RecursiveDo #-}
module Program1 where
import SpirV.Builder.Raw
program1 :: Builder ()
program1 = mdo
std450 <- extInstImport "GLSL.std.450"
memoryModel Logical GLSL450
progName <- string "program1"
float32 <- typeFloat 32
f_1 <- constant float32 [1065353216]
f_2 <- constant float32 [1073741824]
vecf4 <- typeVector float32 4
scaleConst <- constantComposite vecf4 [f_1, f_1, f_2, f_1]
bool <- typeBool
ptrBool <- typePointer StorageUniformConstant bool
cond <- variable ptrBool StorageUniformConstant Nothing
ptrVecf4Out <- typePointer StorageOutput vecf4
color <- variable ptrVecf4Out StorageOutput Nothing
ptrVecf4In <- typePointer StorageInput vecf4
color1 <- variable ptrVecf4In StorageInput Nothing
decorate color1 Smooth
uint32 <- typeInt 32 Unsigned
ui_5 <- constant uint32 [5]
array5vecf4 <- typeArray vecf4 ui_5
int32 <- typeInt 32 Signed
structS <- typeStruct [bool, array5vecf4, int32]
ptrStructS <- typePointer StorageUniformConstant structS
s <- variable ptrStructS StorageUniformConstant Nothing
color2 <- variable ptrVecf4In StorageInput Nothing
decorate color2 Noperspective
ptrVecf4Uni <- typePointer StorageUniformConstant vecf4
multiplier <- variable ptrVecf4Uni StorageUniformConstant Nothing
void <- typeVoid
fnVoid <- typeFunction void []
main' <- function void [] fnVoid
entryPoint Fragment main'
label1 <- label
ptrVecf4Fn <- typePointer StorageFunction vecf4
scale <- variable ptrVecf4Fn StorageFunction Nothing
ptrIntFn <- typePointer StorageFunction int32
i <- variable ptrIntFn StorageFunction Nothing
store scale scaleConst MemoryNormal
ifCond <- load bool cond MemoryNormal
selectionMerge branchEnd []
branchConditional ifCond ifTrue ifFalse Nothing
ifTrue <- label
color1Val <- load vecf4 color1 MemoryNormal
i_1 <- constant int32 [1]
i_2 <- constant int32 [2]
s_v_2 <- accessChain ptrVecf4Uni s [i_1, i_2]
v <- load vecf4 s_v_2 MemoryNormal
color' <- fAdd vecf4 color1Val v
store color color' MemoryNormal
branch branchEnd
ifFalse <- label
color2Val <- load vecf4 color2 MemoryNormal
sqrtColor2 <- extInst vecf4 std450 28 [color2Val]
scaleVal <- load vecf4 scale MemoryNormal
color'' <- fMul vecf4 sqrtColor2 scaleVal
store color color'' MemoryNormal
branch branchEnd
branchEnd <- label
i_0 <- constant int32 [0]
store i i_0 MemoryNormal
branch forStart
forStart <- label
iVal <- load int32 i MemoryNormal
i_4 <- constant int32 [4]
forCond <- sLessThan bool iVal i_4
loopMerge forEnd []
branchConditional forCond forBody forEnd Nothing
forBody <- label
multiplierVal <- load vecf4 multiplier MemoryNormal
colorVal <- load vecf4 color MemoryNormal
color''' <- fMul vecf4 multiplierVal colorVal
store color color''' MemoryNormal
iVal' <- load int32 i MemoryNormal
iInc <- iAdd int32 iVal' i_1
store i iInc MemoryNormal
branch forStart
forEnd <- label
branch mainEnd
mainEnd <- label
return_
functionEnd
| stevely/hspirv | test/src/Program1.hs | bsd-3-clause | 3,247 | 0 | 9 | 736 | 956 | 416 | 540 | 85 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
-- {-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DataKinds #-}
-- {-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- {-# OPTIONS_GHC -fno-warn-orphans #-}
-- {-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
-- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-}
-- {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
-- |
-- Copyright : (c) Andreas Reuleaux 2015
-- License : BSD2
-- Maintainer: Andreas Reuleaux <rx@a-rx.info>
-- Stability : experimental
-- Portability: non-portable
--
-- This module provides Pire's Text to String conversion functions
module Pire.String2Text where
import Pire.Syntax.Expr
import Pire.Syntax.Ex
import Pire.Syntax.Decl
import Pire.Syntax.Telescope
import Pire.Syntax.Constructor
import Pire.Syntax.Modules
import Pire.Syntax.ConstructorNames
import Pire.Syntax.Nm
import Pire.Syntax.Ws
import Pire.Syntax.Token
import qualified Data.Set as S
import Data.Bifunctor
-- import Control.Applicative
import qualified Data.Text as T
class S2T a b | a -> b where
s2t :: a -> b
instance S2T (Ws String) (Ws T.Text) where
s2t = fmap T.pack
instance S2T (Token 'ModuleTokTy String) (Token 'ModuleTokTy T.Text) where
s2t = fmap T.pack
instance S2T (Token 'WhereTy String) (Token 'WhereTy T.Text) where
s2t = fmap T.pack
string2textExpr :: Expr String String -> Ex
string2textExpr = bimap T.pack T.pack
instance S2T (Expr String String) Ex where
s2t = string2textExpr
-- needed only later for Navigation/textual -> navigating to matches
instance S2T (Match String String) (Match T.Text T.Text) where
s2t = bimap T.pack T.pack
string2textDecl :: Decl String String -> Decl T.Text T.Text
string2textDecl = bimap T.pack T.pack
instance S2T (Decl String String) (Decl T.Text T.Text) where
s2t = string2textDecl
instance S2T [Decl String String] [Decl T.Text T.Text] where
s2t = map string2textDecl
string2textImport :: ModuleImport String -> ModuleImport T.Text
string2textImport = fmap T.pack
instance S2T (ModuleImport String) (ModuleImport T.Text) where
s2t = string2textImport
instance S2T [ModuleImport String] [ModuleImport T.Text] where
s2t = fmap string2textImport
string2textConstructorNames :: ConstructorNames String -> ConstructorNames T.Text
string2textConstructorNames (ConstructorNames tcons dcons) =
ConstructorNames (S.map T.pack tcons) (S.map T.pack dcons)
instance S2T (ConstructorNames String) (ConstructorNames T.Text) where
s2t = string2textConstructorNames
instance S2T (Nm1 String) (Nm1 T.Text) where
s2t = fmap T.pack
string2textM :: Module String String -> Module T.Text T.Text
string2textM (Module nm mimports mdecls constructors) =
Module (s2t nm) (s2t mimports) (s2t mdecls) (s2t constructors)
string2textM (Module_
leadingWhiteSpace
mtoken
nm
whereToken
mimports
mdecls
constructors) =
Module_ (s2t leadingWhiteSpace) (s2t mtoken) (s2t nm) (s2t whereToken) (s2t mimports) (s2t mdecls) (s2t constructors)
-- todo: make Module a Bifunctor
-- string2textM m@(Module_ {..}) = bimap T.unpack T.unpack m
instance S2T (Module String String ) (Module T.Text T.Text) where
s2t = string2textM
string2textTele :: Telescope String String -> Telescope T.Text T.Text
string2textTele = bimap T.pack T.pack
instance S2T (Telescope String String) (Telescope T.Text T.Text) where
s2t = string2textTele
instance S2T (ConstructorDef String String) (ConstructorDef T.Text T.Text) where
s2t = bimap T.pack T.pack
| reuleaux/pire | src/Pire/String2Text.hs | bsd-3-clause | 3,932 | 0 | 8 | 722 | 987 | 523 | 464 | 74 | 1 |
{-- snippet CannotShow --}
data CannotShow = CannotShow
deriving (Show)
-- will not compile, since CannotShow is not an instance of Show
data CannotDeriveShow = CannotDeriveShow CannotShow
deriving (Show)
data OK = OK
instance Show OK where
show _ = "OK"
data ThisWorks = ThisWorks OK
deriving (Show)
{-- /snippet CannotShow --}
| binesiyu/ifl | examples/ch06/AutomaticDerivation.hs | mit | 394 | 0 | 6 | 117 | 73 | 41 | 32 | 9 | 0 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Foo where
import Foreign.C.Types
foreign export ccall hs_fact :: CInt -> CInt
hs_fact :: CInt -> CInt
hs_fact 0 = 1
hs_fact n = n * hs_fact (n - 1)
| ttakamura/sandbox | ffi/haskell2/foo.hs | mit | 200 | 0 | 8 | 38 | 64 | 36 | 28 | 7 | 1 |
module FP.Quiz where
import FP.Check
import FP.Conf
import FP.Instance
import FP.Roll
import FP.Expression
import Autolib.Size
import Autolib.ToDoc
import Autolib.TES.Identifier
import Control.Monad ( guard )
import Inter.Quiz
import Inter.Types
import Debug
import Data.Array
instance Generator FPTypeCheck Conf ( Expression Identifier, TI ) where
generator p conf key = nice_problem conf
instance Project FPTypeCheck ( Expression Identifier, TI ) TI where
project p ( x , ti ) = ti
make :: Make
make = quiz FPTypeCheck FP.Conf.example
| florianpilz/autotool | src/FP/Quiz.hs | gpl-2.0 | 559 | 0 | 7 | 98 | 166 | 94 | 72 | -1 | -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.