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
--data List a = Empty | Cons a (List a) deriving (Show, Read, Eq, Ord) --data List a = Empty | Cons { listHead :: a, listTail :: List a} deriving (Show, Read, Eq, Ord) infixr 5 :-: data List a = Empty | a :-: (List a) deriving (Show, Read, Eq, Ord) infixr 5 .++ (.++) :: List a -> List a -> List a Empty .++ ys = ys (x :-: xs) .++ ys = x :-: (xs .++ ys)
RAFIRAF/HASKELL
myList.hs
mit
355
0
8
83
116
62
54
6
1
{-# LANGUAGE OverloadedStrings #-} module Text.HTML.Haskpress ( makeSlide , nextSlide , slideToHtml , genSlides , renderSlides , renderFromFile , renderFromFileToFile ) where import qualified Data.ByteString.Lazy as L import Text.Blaze.Html5 hiding (map) import Text.Blaze.Html5.Attributes import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A import Text.Blaze.Html.Renderer.Utf8 (renderHtml) import Data.Monoid (mconcat) import Control.Monad (mzero, liftM) import Data.Aeson import Control.Applicative ((<$>), (<*>)) import Data.Text.Encoding (encodeUtf8) import System.IO data Slide = Slide Position Transform Content Id data Transform = Transform Scale [Rotation] data Rotation = Rotation Direction String data Position = Position Int Int Int data Direction = X | Y | Z deriving (Eq) type Content = Html type Scale = Int type Id = Maybe String instance FromJSON Slide where parseJSON (Object v) = Slide <$> (v .: "position") <*> (v .:? "transform" .!= defaultTransform) <*> liftM (preEscapedToHtml :: String -> Html) (v .: "content") <*> (v .:? "id") parseJSON _ = mzero instance FromJSON Position where parseJSON (Object v) = Position <$> v .: "x" <*> v .: "y" <*> v .:? "z" .!= 0 parseJSON _ = mzero instance FromJSON Transform where parseJSON (Object v) = Transform <$> v .:? "scale" .!= defaultScale <*> v .:? "rotations" .!= [] parseJSON _ = mzero instance FromJSON Rotation where parseJSON (Object v) = Rotation <$> v .: "direction" .!= Z <*> v .: "val" parseJSON _ = mzero instance FromJSON Direction where parseJSON (String v) = do case v of "x" -> return X "y" -> return Y "z" -> return Z _ -> return Z parseJSON _ = mzero defaultPosition :: Position defaultPosition = Position 0 0 0 offsetPosition :: Position -> Direction -> Int -> Position offsetPosition (Position x y z) X offset = Position (x + offset) y z offsetPosition (Position x y z) Y offset = Position x (y + offset) z offsetPosition (Position x y z) Z offset = Position x y (z + offset) offsetPosition' :: Position -> Position -> Position offsetPosition' (Position x y z) (Position x' y' z') = (Position (x+x') (y+y') (z+z')) positionXY :: Int -> Int -> Position positionXY x y = offsetPosition (offsetPosition defaultPosition X x) Y y defaultScale :: Scale defaultScale = 1 offsetScale :: Scale -> Float -> Scale offsetScale s offset = round $ fromIntegral s * offset defaultTransform :: Transform defaultTransform = Transform defaultScale [] makeSlide :: Position -> Transform -> Content -> Id -> Slide makeSlide p t c i = Slide p t c i rotationDirection :: [Rotation] -> Direction -> AttributeValue rotationDirection [] _ = toValue ("0" :: String) rotationDirection ((Rotation d r):rs) d' | d == d' = toValue r | otherwise = rotationDirection rs d' slideToHtml :: Slide -> Html slideToHtml (Slide (Position x y z) (Transform scale rotations) content Nothing) = H.div ! class_ "step slide" ! dataAttribute "x" (toValue x) ! dataAttribute "y" (toValue y) ! dataAttribute "z" (toValue z) ! dataAttribute "rotate-x" (rotationDirection rotations X) ! dataAttribute "rotate-y" (rotationDirection rotations Y) ! dataAttribute "rotate-z" (rotationDirection rotations Z) ! dataAttribute "scale" (toValue scale) $ toHtml content slideToHtml (Slide (Position x y z) (Transform scale rotations) content (Just idString)) = H.div ! class_ "step slide" ! A.id (toValue idString) ! dataAttribute "x" (toValue x) ! dataAttribute "y" (toValue y) ! dataAttribute "z" (toValue z) ! dataAttribute "rotate-x" (rotationDirection rotations X) ! dataAttribute "rotate-y" (rotationDirection rotations Y) ! dataAttribute "rotate-z" (rotationDirection rotations Z) ! dataAttribute "scale" (toValue scale) $ toHtml content nextSlide :: Slide -> Position -> Float -> [Rotation] -> Content -> Id -> Slide nextSlide (Slide p (Transform scale _) _ _) p' scale' rotations content id = makeSlide (offsetPosition' p p') (Transform (offsetScale scale scale') rotations) content id combineSlides :: [Slide] -> Html combineSlides ss = mconcat $ map slideToHtml ss slidesFromFile :: String -> IO (Maybe [Slide]) slidesFromFile filename = do withFile filename ReadMode (\h -> do json <- L.hGetContents h let slides = decode json return slides) genSlides :: [Slide] -> Html genSlides ss = docTypeHtml $ do H.head $ do H.title $ "SLIDE!!!" genImpressCSS body ! class_ "impress-not-supported" $ do H.div ! class_ "fallback-message" $ do p $ "Your browser is old! Please get the latest version of Chrome, Safari, or Firefox" H.div ! A.id "impress" $ do combineSlides ss genImpressScript genImpressScript :: Html genImpressScript = do script ! src "js/impress.js" $ "" script $ "impress().init();" genImpressCSS :: Html genImpressCSS = do link ! href "css/impress-demo.css" ! rel "stylesheet" renderSlides :: Html -> L.ByteString renderSlides = renderHtml renderFromFile :: String -> IO L.ByteString renderFromFile filename = do slides <- slidesFromFile filename case slides of Nothing -> return "" Just slides' -> return (renderSlides . genSlides $ slides') renderFromFileToFile :: String -> String -> IO () renderFromFileToFile infile outfile = do withFile infile ReadMode (\inHandle -> do json <- L.hGetContents inHandle let slides = decode json case slides of Nothing -> return () Just slides' -> withFile outfile WriteMode (\h -> do let htmlString = (renderSlides . genSlides $ slides') L.hPut h htmlString))
rokob/haskpress
src/Text/HTML/Haskpress.hs
mit
5,741
0
25
1,185
1,991
1,012
979
145
2
module Data.SemVer ( module Data.SemVer.Types, module Data.SemVer.Parser ) where import Data.SemVer.Types import Data.SemVer.Parser
adnelson/semver-range
src/Data/SemVer.hs
mit
139
0
5
20
34
23
11
5
0
module Database.Toxic.Streams where import Database.Toxic.Types import Data.Function import Data.List (foldl', sortBy) import qualified Data.Map.Strict as M import qualified Data.Text as T import qualified Data.Vector as V import qualified Text.Show.Text as T nullStream :: Stream nullStream = Stream { streamHeader = V.empty, streamRecords = [] } -- | Summing two streams acts on the set of records but does not change the header. Examples include union, intersect, except operations. -- | As a result, all streams must match in size and type. -- TODO: Add asserts for size and type sumStreams :: QuerySumOperation -> ArrayOf Stream -> Stream sumStreams op streams = if V.null streams then nullStream else let header = streamHeader $ V.head streams records = case op of QuerySumUnionAll -> unionAllRecords $ V.map streamRecords streams in Stream { streamHeader = header, streamRecords = records } -- | Creates a new record by appending all the columns from each record crossJoinRecords :: ArrayOf Record -> Record crossJoinRecords records = let extractValues (Record values) = values in Record $ V.concatMap extractValues records -- | Creates a new stream with a header that combines the headers of the constituents. -- | Variable x in stream n assigned the name '$n.x'. crossJoinStreams :: ArrayOf Stream -> Stream crossJoinStreams streams = let getNewName idx name = T.cons '$' $ T.append (T.show idx) $ T.cons '.' $ name getNewNames idx names = V.map (getNewName idx) names :: ArrayOf T.Text getNewColumns idx columns = let names = V.map columnName columns newNames = getNewNames idx names in V.zipWith (\column newName -> Column { columnName = newName, columnType = columnType column }) columns newNames :: ArrayOf Column header = V.concatMap id $ V.imap getNewColumns $ V.map streamHeader streams :: ArrayOf Column records = let recordSets = sequence $ V.toList $ V.map streamRecords streams :: [[ Record ]] combinedRecords = map (crossJoinRecords . V.fromList) recordSets :: [ Record ] in combinedRecords in Stream { streamHeader = header, streamRecords = records } -- | Multiplying two streams creates a new stream with the header being a union of the constituent streams' headers, and the records being a function of the -- | cartesian product. Examples include SQL join. multiplyStreams :: QueryProductOperation -> ArrayOf Stream -> Stream multiplyStreams op streams = case op of QueryProductCrossJoin -> crossJoinStreams streams unionAllRecords :: ArrayOf (SetOf Record) -> SetOf Record unionAllRecords recordss = concat $ V.toList recordss accumulateRecord :: ArrayOf AggregateFunction -> AggregateRow -> Record -> AggregateRow accumulateRecord aggregates (AggregateRow states) (Record values) = AggregateRow $ V.zipWith3 aggregateAccumulate aggregates values states finalizeRow :: ArrayOf AggregateFunction -> AggregateRow -> Record finalizeRow aggregates (AggregateRow states) = Record $ V.zipWith aggregateFinalize aggregates states finalize :: ArrayOf AggregateFunction -> PendingSummarization -> Summarization finalize aggregates summarization = M.map (finalizeRow aggregates) summarization -- | Feeds an incoming stream of keys and values into a collection of aggregate functions. -- | There is a one-to-one relationship between each record's values and the -- | aggregate functions. summarizeByKey :: SetOf (PrimaryKey, Record) -> ArrayOf AggregateFunction -> Summarization summarizeByKey rows aggregates = let initialStates = AggregateRow $ V.map aggregateInitialize aggregates accumulateTuple :: PendingSummarization -> (PrimaryKey, Record) -> PendingSummarization accumulateTuple summarization (key, inputs) = let states = M.findWithDefault initialStates key summarization newStates = accumulateRecord aggregates states inputs in M.insert key newStates summarization finalStates :: PendingSummarization finalStates = foldl' accumulateTuple M.empty rows finalRecords :: Summarization finalRecords = finalize aggregates finalStates in finalRecords orderBy :: Stream -> (Record -> Record -> Ordering) -> Stream orderBy stream order= stream { streamRecords = sortBy order $ streamRecords stream } orderByMultiple :: Stream -> ArrayOf (Record -> Record -> Ordering) -> Stream orderByMultiple stream orderFunctions = let order :: Record -> Record -> Ordering order a b = let orderings = V.map (\f -> f a b) orderFunctions in V.foldr' thenCmp EQ orderings in orderBy stream order thenCmp :: Ordering -> Ordering -> Ordering thenCmp EQ o2 = o2 thenCmp o1 _ = o1 orderFunctionFromStreamOrder :: Int -> StreamOrder -> (Record -> Record -> Ordering) orderFunctionFromStreamOrder index streamOrder = let indexRecord (Record xs) = xs V.! index in case streamOrder of Unordered -> \a b -> EQ Ascending -> compare `on` indexRecord Descending -> flip compare `on` indexRecord orderByColumns :: Stream -> ArrayOf (Int, StreamOrder) -> Stream orderByColumns stream orders = let orderFunctionByIndex :: (Int, StreamOrder) -> (Record -> Record -> Ordering) orderFunctionByIndex (column, streamOrder) = orderFunctionFromStreamOrder column streamOrder in orderByMultiple stream $ V.map orderFunctionByIndex orders singleton_stream :: Column -> Value -> Stream singleton_stream column value = let header = V.singleton column records = [ Record $ V.singleton value ] in Stream { streamHeader = header, streamRecords = records } single_column_stream :: Column -> [ Value ] -> Stream single_column_stream column values = let header = V.singleton column records = map (Record . V.singleton) values in Stream { streamHeader = header, streamRecords = records }
MichaelBurge/ToxicSludgeDB
src/Database/Toxic/Streams.hs
mit
6,166
0
16
1,407
1,482
771
711
116
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- TODO: rewrite this abomination -- TODO: move to separate project -- | HMAC middleware (for Github webhook calls) to filter requests that do not -- have the correct signature generated with the shared secret. module HmacMiddleware ( hmacAuth , AuthSettings (..) , defaultAuthSettings , HashAlgorithm , SHA1 ) where import Control.Monad.IO.Class (MonadIO, liftIO) import Crypto.Hash import Crypto.MAC.HMAC import Data.ByteArray (ByteArrayAccess) import qualified Data.ByteArray as BA import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Base16 as BSB16 import qualified Data.ByteString.Char8 as BS8 import qualified Data.ByteString.Lazy.Char8 as SL8 import Data.CaseInsensitive (CI) import Data.IORef import Data.Word8 (_equal) import qualified Network.HTTP.Types as Http import Network.Wai -- ---------------------------------------------- -- | Settings for the middleware. data AuthSettings hash = AuthSettings { authHeader :: CI ByteString -- ^ Name of the header containing the HMAC-signature , authSecret :: ByteString -- ^ Secret for HMAC calculation , authCheck :: Request -> IO Bool -- ^ If this request should be checked or just pass through , authFail :: AuthException -> Application -- ^ What to do if authentication fails , authHash :: hash -- ^ HMAC signing algorithm } -- | Auth failures. data AuthException = MissingHeader -- ^ The header containing the signature is missing | MalformedSignature -- ^ The signature does not have the expected format | SignatureMismatch -- ^ The signature does not match (maybe using a different secret) deriving Show -- ---------------------------------------------- -- | HMAC authentication middleware. hmacAuth :: forall hash . HashAlgorithm hash => AuthSettings hash -> Middleware hmacAuth cfg app req resp = do shouldBeChecked <- authCheck cfg req mayPass <- if shouldBeChecked then check else return $ Right (req, resp) case mayPass of Left e -> authFail cfg e req resp Right (req', resp') -> app req' resp' where check = case lookup "x-hub-signature" $ requestHeaders req of Nothing -> return $ Left MissingHeader Just headerVal -> -- XXX: eww if cipher == "sha1" && BS.length sigWithEqSign == 40+1 then checkSignature signature else return $ Left MalformedSignature where (cipher, sigWithEqSign) = BS.span (_equal /=) headerVal signature = BS.tail sigWithEqSign checkSignature sig = do (req', reqSig) <- calculateSignature cfg req if reqSig == sig then return $ Right (req', resp) else return $ Left SignatureMismatch -- ---------------------------------------------- -- | The default settings, which work for Github webhook events defaultAuthSettings :: ByteString -> AuthSettings SHA1 defaultAuthSettings secret = AuthSettings { authHeader = "x-hub-signature" , authSecret = secret , authFail = \_exc _req f -> f $ responseLBS Http.status403 [] "" , authCheck = \_req -> return True , authHash = SHA1 -- XXX: already covered } -- ---------------------------------------------- -- | Calculates the HMAC signature and returns the unconsumed request body. -- -- The request's message body is consumed to calculate the signature. -- A new request with a new body is therefore created. -- -- /Note/: The request body has been consumed and cannot be used anymore. calculateSignature :: forall m hash . ( MonadIO m, HashAlgorithm hash ) => AuthSettings hash -> Request -> m (Request, ByteString) calculateSignature cfg req = do (req', body) <- liftIO $ getRequestBody req let bodyStrict = SL8.toStrict . SL8.fromChunks $ body let HMAC hashed = hmac (authSecret cfg) bodyStrict :: HMAC hash return (req', toHexByteString hashed) -- digestToHexByteString hashed with cryptohash (2 less deps...) -- | Get (and consume) the request body and create a new request with a new body -- which is ready to be consumed. -- -- Taken from: @wai-extra/src/Network/Wai/Middleware/RequestLogger.hs@. getRequestBody :: Request -> IO (Request, [BS8.ByteString]) getRequestBody req = do let loop front = do bs <- requestBody req if BS8.null bs then return $ front [] else loop $ front . (bs:) body <- loop id ichunks <- newIORef body let rbody = atomicModifyIORef ichunks $ \chunks -> case chunks of [] -> ([], BS8.empty) x:y -> (y, x) let req' = req { requestBody = rbody } return (req', body) -- | Return the hexadecimal representation of the digest. toHexByteString :: ByteArrayAccess a => a -> ByteString toHexByteString = BSB16.encode . BA.convert
UlfS/ghmm
app/HmacMiddleware.hs
mit
5,149
0
17
1,311
1,014
563
451
91
6
{-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RecordWildCards #-} module Foundation where import Import.NoFoundation import Database.Persist.Sql (ConnectionPool, runSqlPool) import Text.Hamlet (hamletFile) import Text.Jasmine (minifym) import Yesod.Auth.BrowserId (authBrowserId) import Yesod.Auth.Message (AuthMessage (InvalidLogin)) import Yesod.Default.Util (addStaticContentExternal) import Yesod.Core.Types (Logger) import qualified Yesod.Core.Unsafe as Unsafe import qualified Data.CaseInsensitive as CI import qualified Data.Text.Encoding as TE import Yesod.Auth.Message as Msg import qualified Yesod.Auth.Account as Acc import qualified Yesod.Auth.Account.Message as AccMsg import Yesod.Auth.Facebook.ServerSide import qualified Facebook as FB import qualified Yesod.Facebook as YF import Language.Haskell.TH (runIO, litE, stringL) import Data.Acid import qualified Hajong.Database as G import qualified Hajong.Connections as G import Control.Concurrent.Extra (Lock, withLock) import qualified Network.WebSockets as WS import Handler.SendMail import qualified Network.Mail.Mime as Mime import qualified Data.ByteString.Lazy.Char8 as C8 import Data.Text (strip) import Data.Digest.Pure.MD5 (md5) -- | The foundation datatype 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 { appSettings :: AppSettings , appStatic :: Static -- ^ Settings for static file serving. , appConnPool :: ConnectionPool -- ^ Database connection pool. , appHttpManager :: Manager , appLogger :: Logger , appGameState :: AcidState G.ServerDB , appGameLock :: Lock , appGameIn :: MVar G.InternalEvent , appGameOut :: MVar G.InternalResult } mkYesodData "App" $(parseRoutesFile "config/routes") type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) instance Yesod App where -- Controls the base of generated URLs. For more information on modifying, -- see: https://github.com/yesodweb/yesod/wiki/Overriding-approot approot = ApprootMaster $ appRoot . appSettings makeSessionBackend _ = Just <$> defaultClientSessionBackend (14 * 24 * 60) -- timeout in minutes "config/client_session_key.aes" -- Yesod Middleware allows you to run code before and after each handler function. -- The defaultYesodMiddleware adds the response header "Vary: Accept, Accept-Language" and performs authorization checks. -- The defaultCsrfMiddleware: -- a) Sets a cookie with a CSRF token in it. -- b) Validates that incoming write requests include that token in either a header or POST parameter. -- For details, see the CSRF documentation in the Yesod.Core.Handler module of the yesod-core package. yesodMiddleware = defaultCsrfMiddleware . defaultYesodMiddleware defaultLayout widget = do master <- getYesod mmsg <- getMessage route <- getCurrentRoute mapair <- maybeAuthPair let development = #if DEVELOPMENT True #else False #endif pc <- widgetToPageContent $ do addStylesheet $ StaticR css_normalize_css addStylesheet $ StaticR css_main_css addScript $ StaticR js_jquery_1_11_1_min_js addScript $ StaticR js_modernizr_2_6_2_respond_1_1_0_min_js $(widgetFile "default-layout") withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") authRoute _ = Just $ AuthR LoginR -- Routes not requiring authentication. isAuthorized (AuthR _) _ = return Authorized isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized isAuthorized HomeR _ = return Authorized isAuthorized SupportR _ = return Authorized isAuthorized SupportThankYouR _ = return Authorized isAuthorized _ _ = requireAuthId >> return Authorized -- 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 ext mime content = do master <- getYesod let staticDir = appStaticDir $ appSettings master addStaticContentExternal minifym genFileName staticDir (StaticR . flip StaticRoute []) ext mime content where -- Generate a unique filename based on the content itself genFileName lbs = "autogen-" ++ base64md5 lbs -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog app _source level = appShouldLogAll (appSettings app) || level == LevelWarn || level == LevelError makeLogger = return . appLogger jsLoader _ = BottomOfBody -- TODO -- urlRenderOverride y (StaticR s) = -- Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s -- urlRenderOverride _ _ = Nothing instance YesodPersist App where type YesodPersistBackend App = SqlBackend runDB = defaultRunDB (appDatabaseConf . appSettings) appConnPool instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner appConnPool -- 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 -- Useful when writing code that is re-usable outside of the Handler context. -- An example is background jobs that send email. -- This can also be useful for writing code that works across multiple Yesod applications. instance HasHttpManager App where getHttpManager = appHttpManager unsafeHandler :: App -> Handler a -> IO a unsafeHandler = Unsafe.fakeHandlerGetLogger appLogger -- Note: Some functionality previously present in the scaffolding has been -- moved to documentation in the Wiki. Following are some hopefully helpful -- links: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email -- https://github.com/yesodweb/yesod/wiki/Serve-static-files-from-a-separate-domain -- https://github.com/yesodweb/yesod/wiki/i18n-messages-in-the-scaffolding -- * Email instance YesodSES App where getSES = getsYesod $ appSES . appSettings appMailFooter :: Text appMailFooter = unlines [ "\n\n-------------------------------" , "This is an automatic email from funjong.org. You can reply to this" , "address." , "" , " http://funjong.org" ] instance Acc.AccountSendEmail App where sendVerifyEmail username addr url = do Entity _ User{..} <- runDB $ getBy404 $ UniqueUsername username let subject = "Verify your email address" body = unlines [ "Welcome, " ++ userDisplayName ++ "!" , "" , "You have created an account at funjong.org. Your username is: " ++ userUsername , "Follow the link below to verify your email address" , "" , " " ++ url , "" , "If you have any questions, please contact 'info at funjong dot org' or" , "file a support request at http://funjong.org/support." , appMailFooter ] let mail = Mime.simpleMail' (Address (Just userDisplayName) addr) (error "supplied elsewhere") subject (fromStrict body) renderSendMail [addr] mail sendNewPasswordEmail username addr url = do Entity _ User{..} <- runDB $ getBy404 $ UniqueUsername username let subject = "Password reset request" body = unlines [ "Someone requested a password request for this address on funjong.org." , "" , "Click the link below to reset your password:" , "\n " ++ url ++ "\n" , "If you did not request a password reset, you may safely ignore this email." , appMailFooter ] let mail = Mime.simpleMail' (Address (Just userDisplayName) addr) (error "snpplied elsewhere") subject (fromStrict body) renderSendMail [addr] mail -- * Auth loggedIn :: Handler Bool loggedIn = isJust <$> maybeAuthId myLoginWidget :: Widget myLoginWidget = do setTitleI Msg.LoginTitle master <- getYesod let [fb, acc] = map (flip apLogin AuthR) $ authPlugins master [whamlet| <div.auth-wrapper> ^{fb} <hr> ^{acc} |] requireUserId :: Handler UserId requireUserId = fmap (entityKey . snd) requireAuthPair instance YesodAuth App where type AuthId App = Acc.Username -- :: Text getAuthId (Creds "account" username _) = return (Just username) getAuthId c@(Creds "fb" cId cExtra) = do -- create the User persist entry if it doesn't exist. -- If it exists, update fbUserId <-- TODO token <- getUserAccessToken case token of Nothing -> return Nothing Just token -> do fbUser <- YF.runYesodFbT $ FB.getUser "me" [("fields", "name,email")] (Just token) let fbUserId = FB.idCode $ FB.userId fbUser fbUserEmail = maybe (fbUserId `mappend` "@facebook.com") id $ FB.userEmail fbUser displayName = maybe fbUserId id $ FB.userName fbUser mUserInDB <- runDB $ selectFirst [UserFbUserId ==. Just fbUserId] [] userInDB <- case mUserInDB of Nothing -> let newUser = (Acc.userCreate displayName fbUserEmail "" "") { userUsername = fbUserId , userVerified = True , userFbUserId = Just fbUserId } in runDB (insert newUser) >> return newUser Just (Entity _ v) -> return v return $ Just (userUsername userInDB) loginDest _ = HomeR logoutDest _ = HomeR authPlugins _ = [ myFacebookPlugin, myAccountPlugin ] loginHandler = lift . authLayout $ myLoginWidget authHttpManager _ = error "No manager needed" -- onLogin = setMessageI NowLoggedIn onLogout = setMessage "You have logged out" maybeAuthId = lookupSession credsKey instance YesodAuthPersist App where type AuthEntity App = Entity User getAuthEntity = runDB . getBy . UniqueUsername -- ** Account myAccountPlugin :: AuthPlugin App myAccountPlugin = Acc.accountPlugin { apLogin = myAccountLoginWidget } where myAccountLoginWidget tm = do ((_,widget), enctype) <- liftHandlerT $ runFormPost $ renderDivs Acc.loginForm [whamlet| <div .login-account> <form method=post enctype=#{enctype} action=@{tm Acc.loginFormPostTargetR}> ^{widget} <input.btn-full type=submit value=_{LoginTitle}> <p> <a.btn.btn-alt.btn-half href="@{tm Acc.newAccountR}">_{Msg.RegisterLong} <a.btn.btn-alt.btn-half href="@{tm Acc.resetPasswordR}">_{AccMsg.MsgForgotPassword} |] myResetPasswordWidget :: Widget myResetPasswordWidget = do muname <- liftHandlerT maybeAuthId let myResetPasswordForm = areq textField userSettings muname userSettings = FieldSettings (SomeMessage AccMsg.MsgUsername) Nothing (Just "username") Nothing [] ((_,widget), enctype) <- liftHandlerT $ runFormPost $ renderDivs myResetPasswordForm [whamlet| <div .auth-wrapper> <h1>Reset password <div .resetPasswordDiv> <form method=post enctype=#{enctype} action=@{AuthR Acc.resetPasswordR}> ^{widget} <input.btn.btn-full type=submit value=_{Msg.SendPasswordResetEmail}> |] instance Acc.YesodAuthAccount (Acc.AccountPersistDB App User) App where runAccountDB = Acc.runAccountPersistDB getNewAccountR = lift $ do whenM loggedIn $ do setMessage "You are already logged in" >> redirect HomeR ((_,widget), enctype) <- runFormPost $ renderDivs Acc.newAccountForm authLayout $ do setTitleI Msg.RegisterLong [whamlet| <div.auth-wrapper> ^{apLogin myFacebookPlugin AuthR} <i>Or create a separate account below <div .newaccountDiv> <form method=post enctype=#{enctype} action=@{AuthR Acc.newAccountR}> ^{widget} <input .btn.btn-full type=submit value=_{Msg.Register}> <a .btn.btn-alt.btn-full href=@{AuthR Acc.resetPasswordR}>Forgot password? |] getResetPasswordR = lift $ authLayout $ do setTitleI Msg.PasswordResetTitle myResetPasswordWidget -- ** Facebook myFacebookPlugin :: AuthPlugin App myFacebookPlugin = defPlugin { apLogin = \tm -> [whamlet| <div.login-facebook>^{apLogin defPlugin tm} |] } where defPlugin = authFacebook ["email"] instance YF.YesodFacebook App where fbCredentials = appFacebookCredentials . appSettings fbHttpManager = getHttpManager -- * Extra utilities compileTime :: Text compileTime = $(runIO getCurrentTime >>= litE . stringL . show) goGame :: G.InternalEvent -> Handler G.InternalResult goGame ev = do App{..} <- getYesod liftIO $ withLock appGameLock $ do putMVar appGameIn ev takeMVar appGameOut -- | Used to higlight navigation links isNavOf :: Text -> Maybe (Route App) -> Bool isNavOf "game" (Just LobbyR) = True isNavOf "game" (Just (PlayR _)) = True isNavOf "support" (Just SupportR) = True isNavOf "support" (Just (SupportWithUuidR _)) = True isNavOf "history" (Just GamesR) = True isNavOf "history" (Just (ViewR _ _ _ _)) = True isNavOf "personal" (Just PersonalR) = True isNavOf _ _ = False userProfilePicture :: User -> Text userProfilePicture User{..} | Just fbId <- userFbUserId = "http://graph.facebook.com/" ++ fbId ++ "/picture?type=square" | otherwise = "http://www.gravatar.com/avatar/" ++ hashEmail userEmailAddress -- | for gravatar hashEmail :: Text -> Text hashEmail = md5sum . toLower . strip where md5sum :: Text -> Text md5sum = tshow . md5 . C8.pack . unpack -- | List of text fields. textListField :: Field Handler [Text] textListField = Field { fieldParse = \xs _ -> return (Right $ Just xs) , fieldView = error "Not viewable" , fieldEnctype = UrlEncoded }
SimSaladin/hajong
hajong-site/Foundation.hs
mit
14,676
0
24
3,637
2,731
1,453
1,278
-1
-1
module Y2016.M08.D26.Exercise where import Control.Monad.Writer import Data.Map (Map) import Data.Time import Control.DList import Control.Presentation (laxmi) import Data.Monetary.Currency import Data.Monetary.USD import Y2016.M08.D25.Exercise {-- Similarity? or Disparity? Yesterday we looked at bitcoin, a currency. ("Currency" means "now"-ness) There has been speculation that price-fluxuation of bitcoin and of gold are similar, see, e.g.: https://annrhefn.wordpress.com/2016/07/16/the-bitcoin-halving-quantitative-tightening-and-paving-the-road-to-mass-adoption/ Okay, that's an assertion. Let's show that there is either similarity or disparity ... or neither ... OR BOTH! ... between gold and bitcoin, but to show any similarity, you have to know both as a basis. Yesterday's exercise established a 5-year basis for bitcoin. Today we will establish a 5-year basis for gold. Located in this directory is the historical 5-year weekly gold prices in USD, or at the URL: https://raw.githubusercontent.com/geophf/1HaskellADay/master/exercises/HAD/Y2016/M08/D26/gold-prices-usd-5-yr-weekly.csv credit: this chart is (heavily curtailed) extracted from URL: http://www.gold.org/research/download-the-gold-price-since-1978#package Read in the 5-year history of gold and answer the questions similar to yesterday's exercise for bitcoin, but this time for gold. --} data Gold = AU Rational deriving (Eq, Ord) instance Show Gold where show (AU g) = "AU " ++ laxmi 2 g instance Currency Gold where value = undefined type GoldPrices = Map Day USD readGoldPriceHistory :: FilePath -> IO GoldPrices readGoldPriceHistory = undefined -- so, with that, what is the value of an ounce of gold in USD on any given day? pricePerOz :: GoldPrices -> Day -> Maybe USD pricePerOz = undefined -- say you have more than an ounce. What is the total value of your gold? goldPrice :: GoldPrices -> Gold -> Day -> Maybe USD goldPrice = undefined -- what is the value of all your gold 'today,' given that today is the latest -- day recorded in your GoldPrices-Map? currentGoldPrice :: GoldPrices -> Gold -> Maybe USD currentGoldPrice = undefined -- of course, it would be helpful to formalize 'today' as a 'thing': today :: GoldPrices -> Day today = undefined -- returns the last day recorded in GoldPrices {-- With the above, answer the following questions For a period of x years, investing $1000/month into escrow, and buying gold when you are able (you must buy at least 3 ounce bars of gold in a purchase), 1. How many ounces of gold did you purchase? 2. How much money did you invest in these purchases? (what was your cost) 3. What is the current value of your gold? You then should be able to determine whether gold is a profitable investment. Answer the above 3 questions for scenarios of 5 years, 2 years, and 1 year --} monthlyAUinv :: GoldPrices -> USD -> Day -> Maybe Gold monthlyAUinv prices monthlyinvest startingFrom = undefined -- 5 year: accumulated cost, oz AU, current AU value -- 2 year: accumulated cost, oz AU, current AU value -- 1 year: accumulated cost, oz AU, current AU value -- BONUS ----------------------------------------------------------------- -- Do the above, but record each purchase (of 3 oz of AU) into a log data Purchase = Buy { oz :: Gold, costPerOz :: USD } deriving Show auditiedMonthlyAUinv :: GoldPrices -> USD -> Day -> Writer (DList Purchase) Gold auditiedMonthlyAUinv prices monthlyinvest startingFrom = undefined -- BONUS-BONUS ------------------------------------------------------------ -- Also load in yesterday's bitcoin price-history, save out a CSV-file -- that has both gold and bitcoin prices, reconciling differences in dates, -- if any. Chart bitcoin's prices vs. gold's chartBTCvsAU :: BitCoinPrices -> GoldPrices -> FilePath -> IO () chartBTCvsAU btc au savetofilenamed = undefined
geophf/1HaskellADay
exercises/HAD/Y2016/M08/D26/Exercise.hs
mit
3,868
0
10
617
383
217
166
32
1
module CipherTest where import Cipher import Test.Hspec import Test.QuickCheck genSafeChar :: Gen Char genSafeChar = elements $ ['a'..'z'] ++ ['A'..'Z'] genSafeString :: Gen String genSafeString = listOf genSafeChar genTuple :: Gen (String, String) genTuple = do a <- listOf genSafeChar b <- listOf genSafeChar return (a, b) main :: IO () main = hspec $ do it "unCaesar after caesar should be the identity" $ do forAll genSafeString $ \word -> length word > 0 ==> (unCaesar $ caesar word) == word it "unVigenere after vigenere should be the identity" $ do forAll genTuple $ \(word, pass) -> length word > 0 && length pass > 0 ==> (unVigenere (vigenere word pass) pass) == word
mudphone/HaskellBook
src/CipherTest.hs
mit
721
0
18
159
257
129
128
-1
-1
module Raskell.Parser.RubyParser ( rubyToken , parens , add , numeric , expr , parseRubySource ) where import Text.Parsec import Text.Parsec.String (Parser) import Text.Parsec.Char import Control.Monad (void) import Raskell.Parser.FunctionsAndTypesForParsing (regularParse, parseWithEof, parseWithLeftOver) import Raskell.Parser.RbStrings import qualified Raskell.ASTNodes as AST import Raskell.Parser.Whitespace (lexeme, whitespace) import Data.Char {- stmt ::= nop | rubyToken = expr expr ::= rubyToken | const | unop expr | expr duop expr rubyToken ::= rubyword const ::= rubyword unop ::= rubyword rubyword ::= letter { letter | digit | underscore } -} expr :: Parser AST.Expr expr = term' `chainl1` plus where plus = do void $ lexeme $ char '+' return AST.BPlus term' = term expr term :: Parser AST.Expr -> Parser AST.Expr term expr' = numeric <|> rbString <|> rubyToken <|> parens' expr' numeric :: Parser AST.Expr numeric = try numericFloat <|> numericInt numericInt :: Parser AST.Expr numericInt = do x <- rubyNumber return $ AST.Int $ read x numericFloat :: Parser AST.Expr numericFloat = do x <- rubyNumber void $ lexeme $ char '.' y <- rubyNumber return $ AST.Float $ read (x ++ "." ++ y) rubyNumber :: Parser String rubyNumber = do n <- lexeme $ many1 nums return $ filter (/= '_') n where nums = digit <|> char '_' rubyToken :: Parser AST.Expr rubyToken = do fc <- lexeme firstChar rest <- lexeme $ many varChars args <- many expr return $ AST.Token (fc : rest) args where firstChar = oneOf lcLetters varChars = oneOf (lcLetters ++ ucLetters ++ numbers) lcLetters = '_' : ['a'..'z'] ucLetters = ['A'..'Z'] numbers = ['0'..'9'] parens :: Parser AST.Expr parens = parens' expr parens' :: Parser AST.Expr -> Parser AST.Expr parens' expr' = do void $ lexeme $ char '(' e <- expr' void $ lexeme $ char ')' return $ AST.Parens e add :: Parser AST.Expr add = do lhs <- lexeme (term expr) void $ lexeme $ char '+' rhs <- lexeme expr return $ AST.BPlus lhs rhs parseRubySource :: String -> AST.Expr parseRubySource s = unbox $ parse (whitespace >> expr) "" s where unbox :: Either ParseError a -> a unbox (Left _) = error "failed" unbox (Right a) = a
joshsz/raskell
src/Raskell/Parser/RubyParser.hs
mit
2,353
0
11
558
775
393
382
74
2
{-# LANGUAGE OverloadedStrings #-} module Style where import Data.Maybe (mapMaybe, maybe, isJust, fromJust) import Data.Function (on) import Data.List (sortBy, find) import qualified Data.HashMap.Strict as HM import qualified Data.HashSet as HS import qualified Data.Text as T import Dom import CSS type PropertyMap = HM.HashMap T.Text Value -- instead of building a tree with references to the DOM, we'll -- just augment the DOM tree with PropertyMaps type StyledNode = NTree (NodeType,PropertyMap) -- this is kind of problematic, we end up computing Specificity twice -- but carrying the specificity around in the Rule might be weird too? -- TODO: look into changing this type MatchedRule = (Specificity, Rule) data Display = Inline | Block | DisplayNone deriving (Eq) -- if name exists, return its specified value value :: StyledNode -> T.Text -> Maybe Value value (NTree node _) name = HM.lookup name (snd node) -- return the specified value of the first property in ks to exist -- or def if no properties match lookup :: StyledNode -> [T.Text] -> Value -> Value lookup s ks def = maybe def (fromJust . value s) (find (isJust . value s) ks) -- look up the display value of a node display :: StyledNode -> Display display n = case value n "display" of Just (Keyword "block") -> Block Just (Keyword "none") -> DisplayNone _ -> Inline -- check if a selector matches an element matches :: ElementData -> Selector -> Bool matches e sl@Simple{} = matchSimple e sl -- matchSimple returns False if any selector field that exists -- does not match the given element matchSimple :: ElementData -> Selector -> Bool matchSimple e (Simple Nothing Nothing c) = matchClasses e c matchSimple e (Simple (Just n) Nothing c) = matchNames e n && matchClasses e c matchSimple e (Simple Nothing (Just i) c) = matchId e i && matchClasses e c matchSimple e (Simple (Just n) (Just i) c) = matchNames e n && matchId e i && matchClasses e c matchNames (ElementData nm _) n = n == nm matchId e i = findID e == Just i matchClasses e [] = True matchClasses e c = all (flip HS.member (classes e)) c -- matchSimple e@(ElementData nm _) (Simple n i c) = -- let x = fmap (==nm) n -- y = if i == Nothing then Nothing else Just $ i == (findID e) -- z = if not $ null c then all (flip HS.member (classes e)) c else True -- in case (x,y,z) of -- (Nothing, Nothing, b3) -> b3 -- (Nothing, Just b2, b3) -> b2 && b3 -- (Just b1, Nothing, b3) -> b1 && b3 -- (Just b1, Just b2, b3) -> b1 && b2 && b3 -- find the first rule that matches the given element matchRule :: ElementData -> Rule -> Maybe MatchedRule matchRule e r@(Rule selectors _) = do s <- find (matches e) selectors return (spec s, r) -- get all of the rules from a stylesheet that match the given element matchingRules :: ElementData -> Stylesheet -> [MatchedRule] matchingRules e (Stylesheet rules) = mapMaybe (matchRule e) rules -- Build a map of all the properties attached to an Element specifiedValues :: ElementData -> Stylesheet -> PropertyMap specifiedValues e s = HM.fromList $ concatMap expand rules where rules = sortBy (compare `on` fst) $ matchingRules e s expand (_,Rule _ ds) = map (\(Declaration n v) -> (n,v)) ds -- traverse the DOM, attaching PropertyMaps to each Node to -- create a styled tree styleTree :: Node -> Stylesheet -> StyledNode styleTree root stylesheet = fmap style root where style e@(Element e') = (e, specifiedValues e' stylesheet) style t@(Text _) = (t, HM.empty)
Hrothen/Hubert
src/Style.hs
mit
3,717
0
11
905
943
504
439
53
3
module Galua.Util.SmallVec where import Data.Vector(Vector) import qualified Data.Vector as Vector import Data.Vector.Mutable (IOVector) import qualified Data.Vector.Mutable as IOVector import Control.Monad(replicateM_) data SmallVec a = Vec0 | Vec1 a | Vec2 a a | VecMany {-# UNPACK #-} !(Vector a) -- ^ at least 3 -- | Is this a vector with exactly 2 elements. isVec2 :: SmallVec a -> Maybe (a,a) isVec2 vs = case vs of Vec2 a b -> Just (a,b) _ -> Nothing {-# INLINE isVec2 #-} -- | Generate a vector of the given lenght, using the IO function -- to initialize it. generateM :: Int -> (Int -> IO a) -> IO (SmallVec a) generateM n f = case n of 0 -> return Vec0 1 -> Vec1 <$> f 0 2 -> Vec2 <$> f 0 <*> f 1 _ -> VecMany <$> Vector.generateM n f {-# INLINE generateM #-} (++) :: SmallVec a -> SmallVec a -> SmallVec a xs ++ ys = case xs of Vec0 -> ys Vec1 x -> cons x ys Vec2 x y -> case ys of Vec0 -> xs Vec1 a -> VecMany (Vector.fromListN 3 [x,y,a]) Vec2 a b -> VecMany (Vector.fromListN 4 [x,y,a,b]) VecMany vs -> VecMany (Vector.cons x (Vector.cons y vs)) VecMany vs -> case ys of Vec0 -> xs Vec1 a -> VecMany (Vector.snoc vs a) Vec2 a b -> VecMany (Vector.snoc (Vector.snoc vs a) b) VecMany ws -> VecMany (vs Vector.++ ws) {-# INLINE (++) #-} drop :: Int -> SmallVec a -> SmallVec a drop n xs = case xs of Vec0 -> Vec0 Vec1 {} -> if n > 0 then Vec0 else xs Vec2 x _ | n > 1 -> Vec0 | n > 0 -> vec1 x | otherwise -> xs VecMany v | n1 < 1 -> Vec0 | n1 == 1 -> Vec1 (Vector.unsafeLast v) | n1 == 2 -> Vec2 (Vector.unsafeIndex v (l - 2)) (Vector.unsafeLast v) | otherwise -> VecMany (Vector.drop n v) where l = Vector.length v n1 = l - n {-# INLINE drop #-} iForM_ :: SmallVec a -> (Int -> a -> IO ()) -> IO () iForM_ vs f = case vs of Vec0 -> return () Vec1 x -> f 0 x Vec2 x y -> f 0 x >> f 1 y VecMany xs -> Vector.forM_ (Vector.indexed xs) (uncurry f) {-# INLINE iForM_ #-} forM_ :: SmallVec a -> (a -> IO ()) -> IO () forM_ vs f = case vs of Vec0 -> return () Vec1 x -> f x Vec2 x y -> f x >> f y VecMany xs -> Vector.forM_ xs f {-# INLINE forM_ #-} padForM_ :: SmallVec a -> Int -> a -> (a -> IO ()) -> IO () padForM_ vs n d f = case vs of Vec0 -> replicateM_ n (f d) Vec1 x -> do if n == 0 then return () else f x replicateM_ (n - 1) (f d) Vec2 x y -> case n of 0 -> return () 1 -> f x _ -> f x >> f y >> replicateM_ (n - 2) (f d) VecMany xs -> do Vector.forM_ (Vector.take n xs) f replicateM_ (n - Vector.length xs) (f d) {-# INLINE padForM_ #-} ipadForM_ :: SmallVec a -> Int -> a -> (Int -> a -> IO ()) -> IO () ipadForM_ vs n d f = case vs of Vec0 -> useDefault 0 Vec1 x -> do if n == 0 then return () else f 0 x useDefault 1 Vec2 x y -> case n of 0 -> return () 1 -> f 0 x _ -> f 0 x >> f 1 y >> useDefault 2 VecMany xs -> do Vector.forM_ (Vector.indexed (Vector.take n xs)) (uncurry f) useDefault (Vector.length xs) where useDefault i = mapM_ (`f` d) [ i .. n - 1 ] {-# INLINE ipadForM_ #-} thaw :: SmallVec a -> IO (IOVector a) thaw vs = case vs of Vec0 -> IOVector.new 0 Vec1 x -> do v <- IOVector.new 1 IOVector.unsafeWrite v 0 x return v Vec2 x y -> do v <- IOVector.new 2 IOVector.unsafeWrite v 0 x IOVector.unsafeWrite v 1 y return v VecMany xs -> Vector.thaw xs {-# INLINE thaw #-} freeze :: IOVector a -> IO (SmallVec a) freeze v = case IOVector.length v of 0 -> return Vec0 1 -> Vec1 <$> IOVector.unsafeRead v 0 2 -> Vec2 <$> IOVector.unsafeRead v 0 <*> IOVector.unsafeRead v 1 _ -> VecMany <$> Vector.freeze v {-# INLINE freeze #-} unsafeIndex :: SmallVec a -> Int -> a unsafeIndex vs n = case vs of Vec0 -> error "Index out of bounds." Vec1 x -> x Vec2 x y -> if n == 0 then x else y VecMany xs -> Vector.unsafeIndex xs n {-# INLINE unsafeIndex #-} indexWithDefault :: SmallVec a -> a -> Int -> a indexWithDefault vs a n = case vs of Vec0 -> a Vec1 x -> if n == 0 then x else a Vec2 x y -> if n == 0 then x else if n == 1 then y else a VecMany v -> case v Vector.!? n of Nothing -> a Just x -> x {-# INLINE indexWithDefault #-} length :: SmallVec a -> Int length vs = case vs of Vec0 -> 0 Vec1 {} -> 1 Vec2 {} -> 2 VecMany xs -> Vector.length xs {-# INLINE length #-} cons :: a -> SmallVec a -> SmallVec a cons a vs = case vs of Vec0 -> Vec1 a Vec1 x -> Vec2 a x Vec2 x y -> VecMany (Vector.fromListN 3 [a,x,y]) VecMany xs -> VecMany (Vector.cons a xs) {-# INLINE cons #-} uncons :: SmallVec a -> Maybe (a,SmallVec a) uncons vs = case vs of Vec0 -> Nothing Vec1 x -> Just (x,Vec0) Vec2 x y -> Just (x,Vec1 y) VecMany xs -> Just (Vector.unsafeHead xs, fromVector (Vector.tail xs)) {-# INLINE uncons #-} maybeHead :: SmallVec a -> a -> a maybeHead v a = case v of Vec0 -> a Vec1 x -> x Vec2 x _ -> x VecMany xs -> Vector.unsafeHead xs {-# INLINE maybeHead #-} empty :: SmallVec a empty = Vec0 {-# INLINE empty #-} vec1 :: a -> SmallVec a vec1 = Vec1 {-# INLINE vec1 #-} vec2 :: a -> a -> SmallVec a vec2 = Vec2 {-# INLINE vec2 #-} vec3 :: a -> a -> a -> SmallVec a vec3 a b c = VecMany (Vector.fromListN 3 [a,b,c]) {-# INLINE vec3 #-} fromList :: [a] -> SmallVec a fromList xs = case xs of [] -> Vec0 [x] -> Vec1 x [x,y] -> Vec2 x y _ -> VecMany (Vector.fromList xs) fromVector :: Vector a -> SmallVec a fromVector vs = case Vector.length vs of 0 -> Vec0 1 -> Vec1 (Vector.unsafeHead vs) 2 -> Vec2 (Vector.unsafeHead vs) (Vector.unsafeIndex vs 1) _ -> VecMany vs toList :: SmallVec a -> [a] toList vs = case vs of Vec0 -> [] Vec1 x -> [x] Vec2 x y -> [x,y] VecMany xs -> Vector.toList xs
GaloisInc/galua
galua-rts/src/Galua/Util/SmallVec.hs
mit
6,796
0
16
2,572
2,741
1,339
1,402
205
10
module Colour ( fromHSV )where import Graphics.Gloss type HSV = (Double, Double, Double) -- [0,360] \times [0,1] \times [0,1] -- from: https://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB fromHSV :: HSV -> Color fromHSV (_,0,v) = toC (v,v,v) fromHSV (_,_,0) = toC (0,0,0) fromHSV (h,s,v) = toC $ case hi of 0 -> (v,x,m) 1 -> (x,v,m) 2 -> (m,v,x) 3 -> (m,x,v) 4 -> (x,m,v) _ -> (v,m,x) where hi = floor (h/60) :: Int f = h/60 - fromIntegral hi m = v * (1-s) x = if hi `mod` 2 == 0 then v * (1- (1-f)*s) else v * (1- f*s) toC :: RealFrac a => (a, a, a) -> Color toC (r,g,b) = makeColorI (fr r) (fr g) (fr b) 255 where fr = floor . (*255)
lesguillemets/fibonacci_word_fractal.hs
src/Colour.hs
mit
892
0
13
375
409
236
173
24
7
{-# LANGUAGE OverloadedStrings #-} module Codec.Soten.PostProcess.TriangulateTest where import Test.Hspec import Control.Lens ((&), (^.), (%~), (.~)) import qualified Data.Vector as V import Linear import Codec.Soten.PostProcess.Triangulate import Codec.Soten.Scene import Codec.Soten.Scene.Mesh faces = V.fromList [Face (V.fromList [0, 1, 2, 3])] validMesh = newMesh & meshFaces .~ faces triangulateTest :: Spec triangulateTest = do describe "Triangulate post process" $ do context "Changes primitive types" $ do let scene = newScene & sceneMeshes .~ V.singleton validMesh fixedSceneMesh = V.head $ (apply scene) ^. sceneMeshes primitiveTypes = fixedSceneMesh ^. meshPrimitiveTypes it "Removes primitive type polygon" $ do (PrimitiveTriangle `V.elem` primitiveTypes ) `shouldBe` True it "Adds primitive type triange" $ do (PrimitivePolygone `V.elem` primitiveTypes ) `shouldBe` False
triplepointfive/soten
test/Codec/Soten/PostProcess/TriangulateTest.hs
mit
959
0
19
184
263
151
112
23
1
import Control.Monad module IO_inside where definitions = undefined
Muzietto/geiesmonads
haskell/IO_inside/IO_inside.hs
mit
76
0
5
16
18
9
9
-1
-1
{-# htermination any :: (a -> Bool) -> [a] -> Bool #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_any_1.hs
mit
55
0
2
12
3
2
1
1
0
module Discussion.Eval where import Discussion.Data -------------------------------------------------------------------------------- -- subst v t t' -- tの中に登場するvをt'で置き換える subst :: Var -> Term -> Term -> Term subst v t (App ts) = App $ map (subst v t) ts subst v t l@(Lambda vs t') | v `elem` vs = l | otherwise = Lambda vs $ subst v t t' subst _ _ j@(Joint _) = j subst _ _ f@(Func _) = f subst v t v'@(VarT v'') | v == v'' = Joint t | otherwise = v' removeJoint :: Term -> Term removeJoint (App ts) = App $ map removeJoint ts removeJoint (Lambda vs t) = Lambda vs $ removeJoint t removeJoint (Joint t) = t removeJoint t = t --------------------------------------------------------------------------------
todays-mitsui/discussion
src/Discussion/Eval.hs
mit
803
0
8
190
290
146
144
17
1
fib 1 = 1 fib 2 = 1 fib x = fib(x-1) + fib(x-2) hoge (n) | n < 10 = -100 | n >= 10 = 100 hage [] = [] hage (x:xs) = hoge(x):hage(xs) qsort [] = [] qsort (m:xs) = qsort low ++ [m] ++ qsort high where low = [ x | x <- xs, x < m ] high = [ x | x <- xs, x > m ] sortFile "" = [] sortFile text = unlines $ map show $ qsort $ map (\x -> read x::Int) $ lines text main = do text <- readFile "./q_1_1.data" writeFile "./q_1_1.out" $ sortFile text
ttakamura/sandbox
pearls/q_1_1/q_1_1.hs
mit
486
0
10
156
307
152
155
16
1
module Shapes ( Point(..) , Shape(..) , area ) where data Point = Point Float Float deriving(Show) data Shape = Circle Point Float | Rectangle Point Point deriving (Show) area :: Shape -> Float area (Circle _ r) = pi * r ^ 2 area (Rectangle (Point x1 y1) (Point x2 y2)) = (abs $ x2 - x1) * (abs $ y2 - y1)
weswilliams/learn-haskell
src/shape/shape.hs
mit
313
0
9
71
157
87
70
10
1
module CodeGen.SerializeCode where import Data.List import Data.Serialize import GHC.Generics import Data.Name import Data.Schema import CodeGen.HaskellCode import Server.NutleyInstance import Data.Types import CodeGen.Join import CodeGen.Metadata.Metadata import CodeGen.NutleyQuery import CodeGen.Metadata.SimpleRecord serializedName q = (name q) ++ "_serialize" stringResultName q = (name q) ++ "_stringResult" stringsInstantiateName q = (name q) ++ "_stringsInstantiate" serializeCode :: NutleyQuery -> [HaskellFunction] serializeCode q@(InstantiateQuery db) = [{-Fun (serializedName q) (FunType [BaseType "InstanceID", t_LazyByteString] $ tc_IO $ t_NutleyInstance) $ Lam (Mlp [Ltp "instID", Ltp "inData"]) $ (c_1 (name q) (Lit "instID")) +=<<+ (c_1 "fromEither" $ c_1 "decodeLazy" $ Lit "inData"),-} codeSimpleRecordStrListsToTuple db, Fun (stringsInstantiateName q) (FunType [BaseType "InstanceID", tc_List $ tc_List $ tc_Maybe $ t_String] $ tc_ErrorT t_IO t_NutleyInstance) $ Lam (Mlp [Ltp "instID", Ltp "inData"]) $ Do [(Ltp "tps",c_1 "EitherT" $ c_1 "return" $ c_1 (strListToTupleName db) $ Lit "inData"), (USp,c_2 (name q) (Lit "instID") $ Lit "tps")] ] serializeCode q@(SectionQuery _ _) = [{-Fun (serializedName q) (FunType [t_NutleyInstance] $ tc_IO $ t_LazyByteString) $ Lam (Mlp [Ltp "instID"]) $ c_2 "fmap" (Lit "encodeLazy") $ c_1 (name q) $ Lit "instID",-} Fun (stringResultName q) (FunType [t_NutleyInstance] $ tc_ErrorT t_IO $ t_String) $ Lam (Mlp [Ltp "instID"]) $ c_2 "fmap" (c_2 "cim" (Lit "\"\\n\"") (Lit "show")) $ c_1 (name q) $ Lit "instID"] serializeCode _ = []
jvictor0/JoSQL
CodeGen/SerializeCode.hs
mit
1,687
0
15
303
449
232
217
33
1
{-# LANGUAGE OverloadedStrings #-} module Parser.Simple where import Core import Language.GoLite.Parser.SimpleStmts assign :: SpecWith () assign = do let parseAssign = parseOnly (fmap bareStmt $ assignStmt >>= unSemiP) it "parses increments and decrements" $ do parseAssign "x++;" `shouldBe` r (increment (variable "x")) parseAssign "x--;" `shouldBe` r (decrement (variable "x")) parseAssign "x ++" `shouldSatisfy` isRight it "does not parse mangled/missing increment or decrement operators" $ do parseAssign "x+ +" `shouldSatisfy` isLeft parseAssign "x+" `shouldSatisfy` isLeft parseAssign "x- -" `shouldSatisfy` isLeft parseAssign "x-" `shouldSatisfy` isLeft parseAssign "x" `shouldSatisfy` isLeft it "does not parse increment/decrements missing an expression" $ do parseAssign "++" `shouldSatisfy` isLeft parseAssign "--" `shouldSatisfy` isLeft it "does not parse an increment/decrement with a semi expression" $ do parseAssign "x\n++" `shouldSatisfy` isLeft parseAssign "x;++" `shouldSatisfy` isLeft it "parses a single or a multiple assignment" $ do parseAssign "a = a" `shouldBe` r (assignment [variable "a"] Assign [variable "a"]) parseAssign "a, b = b, a" `shouldBe` r (assignment [variable "a", variable "b"] Assign [variable "b", variable "a"]) it "parses an assignment op" $ do parseAssign "a += a" `shouldBe` r (assignment [variable "a"] PlusEq [variable "a"]) it "parses assignment on addressable operand" $ do parseAssign "struc.selector++" `shouldBe` r (increment (selector (variable "struc") "selector")) parseAssign "arrayz[0]++" `shouldBe` r (increment (index (variable "arrayz") (int 0))) parseAssign "*p++" `shouldBe` r (increment (Fix $ UnaryOp Dereference (variable "p"))) it "does not parse an assignment if the operand is not addressable" $ do parseAssign "(a + a) >>= 3" `shouldSatisfy` isLeft parseAssign "-a /= 3" `shouldSatisfy` isLeft parseAssign "6.nothing++" `shouldSatisfy` isLeft parseAssign "[]int(nope) *= 2" `shouldSatisfy` isLeft parseAssign "([]int(nope))[2]--" `shouldSatisfy` isLeft parseAssign "a.([]int) &= 127" `shouldSatisfy` isLeft parseAssign "a[:]++" `shouldSatisfy` isLeft parseAssign "g()++" `shouldSatisfy` isLeft parseAssign "`literally`--" `shouldSatisfy` isLeft it "does not parse an assignment with no expression on either side" $ do parseAssign "= a" `shouldSatisfy` isLeft parseAssign "= a, b" `shouldSatisfy` isLeft parseAssign "+= a" `shouldSatisfy` isLeft parseAssign "+= a, b" `shouldSatisfy` isLeft parseAssign "a =" `shouldSatisfy` isLeft parseAssign "a, b =" `shouldSatisfy` isLeft parseAssign "a +=" `shouldSatisfy` isLeft parseAssign "a, b +=" `shouldSatisfy` isLeft it "does not parse an assignment with a missing or non-assign operator" $ do parseAssign "a a" `shouldSatisfy` isLeft parseAssign "a << a" `shouldSatisfy` isLeft it "does not parse when the operator has an explicit semi" $ do parseAssign "a =; a" `shouldSatisfy` isLeft parseAssign "a +=; a" `shouldSatisfy` isLeft parseAssign "a =\n a" `shouldSatisfy` isRight parseAssign "a +=\n a" `shouldSatisfy` isRight it "does not parse when any expression but the rightmost has a semi" $ do parseAssign "a; = a" `shouldSatisfy` isLeft parseAssign "a\n = a" `shouldSatisfy` isLeft parseAssign "a;, b = a" `shouldSatisfy` isLeft parseAssign "a\n, b = a" `shouldSatisfy` isLeft parseAssign "a = a;, b" `shouldSatisfy` isLeft parseAssign "a += a;, b" `shouldSatisfy` isLeft it "does not parse when the rightmost expression does not have a semi" $ do parseAssign "a = a {}" `shouldSatisfy` isLeft parseAssign "a += a {}" `shouldSatisfy` isLeft it "does not parse when the number of operands differs on each side" $ do parseAssign "a, b = 1" `shouldSatisfy` isLeft parseAssign "a = 1, 2" `shouldSatisfy` isLeft parseAssign "a, b += 1" `shouldSatisfy` isLeft parseAssign "a += 1, 2" `shouldSatisfy` isLeft it "does not parse when there is more than one operand in an assign-op" $ do parseAssign "a, b += 3, 4" `shouldSatisfy` isLeft parseAssign "a, b = 3, 4" `shouldSatisfy` isRight shortVariableDeclaration :: SpecWith () shortVariableDeclaration = do let parseShortVarDecl = parseOnly (fmap bareStmt $ shortVarDeclP >>= unSemiP) it "parses one or multiple variable declarations" $ do parseShortVarDecl "x := 2" `shouldBe` r (shortVarDecl ["x"] [int 2]) parseShortVarDecl "x, y := 2, 3" `shouldBe` r (shortVarDecl ["x", "y"] [int 2, int 3]) it "does not parse when the := operator is not present" $ do parseShortVarDecl "x 2" `shouldSatisfy` isLeft parseShortVarDecl "x, y 2, 3" `shouldSatisfy` isLeft it "does not parse when elements on the left-hand side are not idents" $ do parseShortVarDecl "1 := 2" `shouldSatisfy` isLeft parseShortVarDecl "x, 1 := 2, 3" `shouldSatisfy` isLeft it "does not parse when either side has no elements" $ do parseShortVarDecl "x :=" `shouldSatisfy` isLeft parseShortVarDecl ":= 2" `shouldSatisfy` isLeft it "does not parse when sides have differing lengths" $ do parseShortVarDecl "x, y := 1" `shouldSatisfy` isLeft parseShortVarDecl "x := 1, 2" `shouldSatisfy` isLeft it "does not parse when any identifier has a semi" $ do parseShortVarDecl "x; := 1" `shouldSatisfy` isLeft parseShortVarDecl "x\n := 1" `shouldSatisfy` isLeft parseShortVarDecl "x, y;, z := 1, 2, 3" `shouldSatisfy` isLeft parseShortVarDecl "x, y\n, z := 1, 2, 3" `shouldSatisfy` isLeft parseShortVarDecl "x, y; := 1, 2" `shouldSatisfy` isLeft parseShortVarDecl "x, y\n:= 1, 2" `shouldSatisfy` isLeft it "does not parse when any expression but the last has a semi" $ do parseShortVarDecl "x, y := 1;, 2" `shouldSatisfy` isLeft parseShortVarDecl "x, y:= 1\n, 2" `shouldSatisfy` isLeft parseShortVarDecl "x, y, z := 1, 2;, 3" `shouldSatisfy` isLeft parseShortVarDecl "x, y, z := 1, 2\n, 3" `shouldSatisfy` isLeft it "does not parse when the last expression doesn't have a semi" $ do parseShortVarDecl "x := 1 {}" `shouldSatisfy` isLeft parseShortVarDecl "x, y := 1, 2 {}" `shouldSatisfy` isLeft expressionStatement :: SpecWith() expressionStatement = do let parseExprStmt = parseOnly (fmap bareStmt $ exprStmtP >>= unSemiP) it "parses function calls as statements" $ do parseExprStmt "f();" `shouldBe` (r (exprStmt (call (variable "f") Nothing []))) it "requires a semi on the expression" $ do parseExprStmt "f() {}" `shouldSatisfy` isLeft it "does not parse other expressions as statements" $ do parseExprStmt "aVariable;" `shouldSatisfy` isLeft parseExprStmt "2;" `shouldSatisfy` isLeft parseExprStmt "1.1;" `shouldSatisfy` isLeft parseExprStmt "\"StringLit\"" `shouldSatisfy` isLeft parseExprStmt "aStruct.aField;" `shouldSatisfy` isLeft parseExprStmt "[]typ(convert);" `shouldSatisfy` isLeft parseExprStmt "indexing[2];" `shouldSatisfy` isLeft parseExprStmt "binary + operator" `shouldSatisfy` isLeft parseExprStmt "-unaryMinus" `shouldSatisfy` isLeft parseExprStmt "slice[low:high]" `shouldSatisfy` isLeft parseExprStmt "slice[low:high:max]" `shouldSatisfy` isLeft parseExprStmt "assertion.([]typ)" `shouldSatisfy` isLeft simpleStatement :: SpecWith () simpleStatement = do let parseSimpleStmt = parseOnly (fmap bareStmt $ simpleStmt >>= unSemiP) it "parses any kind of simple statement" $ do parseSimpleStmt "x := 2" `shouldSatisfy` isRight parseSimpleStmt "f()" `shouldSatisfy` isRight parseSimpleStmt "x = 2" `shouldSatisfy` isRight parseSimpleStmt "x += 2" `shouldSatisfy` isRight parseSimpleStmt ";" `shouldSatisfy` isRight parseSimpleStmt "" `shouldSatisfy` isLeft
djeik/goto
test/Parser/Simple.hs
mit
8,542
0
18
2,165
1,890
916
974
152
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-datasource-lambdaconfig.html module Stratosphere.ResourceProperties.AppSyncDataSourceLambdaConfig where import Stratosphere.ResourceImports -- | Full data type definition for AppSyncDataSourceLambdaConfig. See -- 'appSyncDataSourceLambdaConfig' for a more convenient constructor. data AppSyncDataSourceLambdaConfig = AppSyncDataSourceLambdaConfig { _appSyncDataSourceLambdaConfigLambdaFunctionArn :: Val Text } deriving (Show, Eq) instance ToJSON AppSyncDataSourceLambdaConfig where toJSON AppSyncDataSourceLambdaConfig{..} = object $ catMaybes [ (Just . ("LambdaFunctionArn",) . toJSON) _appSyncDataSourceLambdaConfigLambdaFunctionArn ] -- | Constructor for 'AppSyncDataSourceLambdaConfig' containing required -- fields as arguments. appSyncDataSourceLambdaConfig :: Val Text -- ^ 'asdslcLambdaFunctionArn' -> AppSyncDataSourceLambdaConfig appSyncDataSourceLambdaConfig lambdaFunctionArnarg = AppSyncDataSourceLambdaConfig { _appSyncDataSourceLambdaConfigLambdaFunctionArn = lambdaFunctionArnarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-appsync-datasource-lambdaconfig.html#cfn-appsync-datasource-lambdaconfig-lambdafunctionarn asdslcLambdaFunctionArn :: Lens' AppSyncDataSourceLambdaConfig (Val Text) asdslcLambdaFunctionArn = lens _appSyncDataSourceLambdaConfigLambdaFunctionArn (\s a -> s { _appSyncDataSourceLambdaConfigLambdaFunctionArn = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/AppSyncDataSourceLambdaConfig.hs
mit
1,652
0
13
164
174
100
74
23
1
module Two where import Data.List import Data.Ord fak :: Int -> Int -> Int fak i j = foldl1 (*) [i..j] is_prime :: Int -> Bool is_prime p | p == 2 = True | even p = False | otherwise = looper 3 where looper i | i*i > p = True | 0 == rem p i = False | otherwise = looper $ i+2 prime :: Int -> Bool prime p | even p = False | otherwise = looper 3 where looper i | i*i > p = True | 0 == rem p i = False | otherwise = looper $ i + 2 next_prime :: Int -> Int next_prime p | p < 2 = 2 | p == 2 = 3 | even p = next_prime $ succ p | is_prime $ p + 2 = p + 2 | otherwise = next_prime $ p + 2 primes :: [Int] primes = iterate next_prime 2 sum_pfactors :: Int -> Int sum_pfactors p = looper 0 p 0 where looper :: Int -> Int -> Int -> Int looper m n res | (i * i) > n = res + n | 0 == rem n i = looper 0 (div n i) (res + i) | otherwise = looper (succ m) n res where i = (primes !! m) comb :: Int -> Int -> Int comb n k = div (fak (succ k) n) (fak 1 (n - k)) euler231 :: Int euler231 = larger - smaller where larger :: Int larger = foldl1 (+) $ map sum_pfactors [15000001..20000000] smaller :: Int smaller = foldl1 (+) $ map sum_pfactors [2..5000000] merge :: [Int] -> [Int] -> [Int] merge xs [] = xs merge [] ys = ys merge (x:xs) (y:ys) | x == y = x : (merge xs ys) | x <= y = x : (merge xs (y:ys)) | otherwise = y : (merge (x:xs) ys) hamming :: [Int] -> Int -> [Int] hamming xs lim = looper xs xs [] where looper l1 [] _ = l1 looper l1 (l: []) pl = if pred then l1 else looper woka xs l1 where waku = takeWhile (<= lim) $ map (* l) l1 woka = merge l1 waku pred = length l1 == length pl looper l1 (l: ls) pl = looper (merge l1 waku) ls pl where waku = takeWhile (<= lim) $ map (* l) l1 euler204 :: Int -> Int euler204 lim = length $ hamming (takeWhile (<= 100) primes) lim combinations :: (Ord a, Eq a, Num a) => [a] -> Int -> [[a]] combinations [] _ = [] combinations xs n | n == 1 = map (\x -> [x]) xs | otherwise = [sort $ x:y | x <- xs, y <- combinations (delete x xs) (pred n)] kpermute :: Integral a => [a] -> Int -> [[a]] kpermute [] _ = [] kpermute xs n | n == 1 = map (\x -> [x]) xs | otherwise = [x:y | x <- xs, y <- kpermute (delete x xs) (pred n)] selipin :: a -> Int -> [a] -> [a] selipin elm idx xs = (take (pred idx) xs) ++ [elm] ++ (drop (pred idx) xs) colnum :: [Int] -> Int colnum [] = 0 colnum (x: []) = x colnum xs = looper xs 0 where looper (x: []) res = (10 * res) + x looper (x: xs) res = looper xs $ (10 * res) + x genPrimes :: Int -> Int -> [Int] genPrimes dig n = filter (>= 10^n) res where bast = delete dig [0..9] l = take n $ repeat dig res = [colnum $ selipin x i l | x <- bast , i <- [1.. succ n]] genNumbers :: Int -> Int -> Int -> [Int] genNumbers dig ndig tdig | tdig <= ndig = take tdig $ repeat dig | tdig - ndig == 1 = filter (>= 10^ndig) res | otherwise = looper bres $ succ ndig where bast = delete dig [0..9] bres = [selipin x i l | x <- bast, i <- [1..succ ndig]] l = take ndig $ repeat dig res = map colnum bres looper xs n | n >= tdig = filter (>= 10^ (pred tdig)) $ map colnum xs | otherwise = looper lres $ succ n where lres = [selipin x i ls | x <- bast, i <- [1..succ $ length $ head xs], ls <- xs] findPrimes :: Int -> Int -> Int -> Int findPrimes dig tdig ndig | null tmp = findPrimes dig tdig $ pred ndig | otherwise = sum tmp where res = nub $ genNumbers dig ndig tdig tmp = filter prime res sol111 :: Int -> Int sol111 t = sum $ map (\x -> findPrimes x t (pred t)) [0..9] numcol :: Int -> [Int] numcol n = if n < 10 then [n] else (numcol $ div n 10) ++ [rem n 10] genResults :: Int -> Int -> [Int] genResults dig tdig | null temp = looper bas | otherwise = temp where temp = filter prime bas bas = genPrimes dig tdig looper xs | null tmp = looper bas1 | otherwise = tmp where brak = map numcol xs bas1 = [colnum $ selipin x i l | x <- (delete dig [0..9]), i <- [1..succ $ length $ head brak], l <- brak] tmp = filter prime bas1 sol145 :: Int -> Int sol145 lim = length $ filter (\x -> all odd $ bar x) [1..pred lim] where bar i = if 0 /= head basa then numcol $ sum [i, colnum basa] else [2] where basa = reverse $ numcol i sol145b :: Int -> Int sol145b lim = looper 1 0 where looper :: Int -> Int -> Int looper i res | i >= lim = res | valid i = looper (succ i) (succ res) | otherwise = looper (succ i) res where valid i | rem i 10 == 0 = False | all odd pri = True | otherwise = False where pri = numcol $ sum [i, colnum $ reverse $ numcol i]
zeniuseducation/poly-euler
haskell/next/two.hs
epl-1.0
5,229
0
15
1,887
2,624
1,313
1,311
149
4
{-# LANGUAGE TupleSections #-} {-# LANGUAGE NoImplicitPrelude #-} module Handler.Home where import Import import Handler.Util import qualified Data.Map.Strict as Map -- The GET handler displays the form getHomeR :: Handler Html getHomeR = do -- Generate the form to be displayed (widget, enctype) <- generateFormPost $ loanForm initLoan initErrors defaultLayout $ displayInputForm MsgCalculator widget enctype >> abstractWidget initLoan = Loan confClassic 0 0 Nothing 0 Nothing Nothing Nothing Nothing Nothing loanForm :: Loan -> LoanErrors -> Html -> MForm Handler (FormResult Loan, Widget) loanForm l le = renderLoan l le $ Loan <$> areq (selectFieldList loans) (mkFieldSettings MsgLoan fieldLoan) (Just $ loanS l) <*> areq amountField (mkFieldSettings MsgPrincipal fieldPrincipal) (Just $ principalS l) <*> areq durationField (mkFieldSettings MsgDuration fieldDuration) (Just $ durationS l) <*> aopt amountField (mkFieldSettings MsgBalloon fieldBalloon) (Just $ balloonS l) <*> areq rateField (mkFieldSettings MsgInterestRate fieldRate) (Just $ rateS l) <*> aopt durationField (mkFieldSettings MsgDeferrment fieldDeferrment) (Just $ delayS l) <*> aopt durationField (mkFieldSettings MsgMaxExtDur fieldExtDur) (Just $ extDurS l) <*> aopt rateField (mkFieldSettings MsgExtRate fieldExtRate) (Just $ extRateS l) <*> aopt amountField (mkFieldSettings MsgFeeAmt fieldFeeAmt) (Just $ feeAmountS l) <*> aopt rateField (mkFieldSettings MsgFeePercent fieldFeePercent) (Just $ feePercentS l) where loans :: [(Text, ClassicCalcConf)] loans = map (pack . ccConfName &&& id) confList mkFieldSettings :: AppMessage -> Text -> FieldSettings App mkFieldSettings msg field = "" {fsLabel = SomeMessage msg ,fsId = Just field} -- | Important for first rendering! isHidden :: ClassicCalcConf -> Text -> Bool -> Bool isHidden l id isErr | not (isUnfoldedBalloon $ clType l) && id == fieldExtRate && not isErr = True | not (isSecuredBalloon $ clType l) && id == fieldExtRate && not isErr = True | not (isBalloon $ clType l) && id == fieldBalloon && not isErr = True | id == fieldExtDur = True -- TODO: fix it, field useless. | otherwise = False renderLoan :: (Show a) => Loan -> LoanErrors -> FormRender Handler a -- | Render a form into a series of tr tags. Note that, in order to allow -- you to add extra rows to the table, this function does /not/ wrap up -- the resulting HTML in a table tag; you must do that yourself. renderLoan l lErr aform fragment = do (res, views') <- aFormToForm aform let views = views' [] loan = loanS l let widget = [whamlet| $newline never $if null views \#{fragment} <div .span6> <table .table> $forall (isFirst, view) <- addIsFirst views <tr ##{fvId view <> "tr"} :fvRequired view:.required :not $ fvRequired view:.optional :isJust $ fvErrors view:.errors :isHidden loan (fvId view) (isJust $ fvErrors view):.hide> <td> $if isFirst \#{fragment} <label ##{fvId view <> "Label"} for=#{fvId view}>#{fvLabel view} $maybe tt <- fvTooltip view <div .tooltip>#{tt} <td>^{fvInput view} $maybe err <- Map.lookup (fvId view) lErr <p .errors>_{err} $maybe err <- fvErrors view <td>#{err} $nothing <td ##{fvId view <> "output"} .warnings> <tr> <td> <td> <button .btn .btn-primary .btn-large>_{MsgCalculate} <td> <div .span3> <div .loan-info-box> <h5> <img src=@{StaticR help_about_png}> # <span #fieldLoanExplanationTitle> # <p #fieldLoanExplanation .small> # <div .span3> <div .loan-info-box> <h5> <img src=@{StaticR help_about_png}> # <span #fieldLoanParamTitle>_{MsgParam} <p #fieldLoanParam .small> <table .table> <col .td-half-table> <col .td-half-table> <tr .small> <td>_{MsgLoanKind} <td #fieldLoanKind> <tr .small> <td>_{MsgMinFstInstDur} <td #fieldMinFstInstDur> <tr .small> <td>_{MsgERType} <td #fieldERType> <tr .small> <td>_{MsgMaxDur} <td #fieldMaxDur> <tr .small> <td>_{MsgMinInstAmt} <td #fieldMinInstAmt> <tr .small> <td>_{MsgInstAdj} <td #fieldInstAdj> |] return (res, widget) where addIsFirst [] = [] addIsFirst (x:y) = (True, x) : map (False, ) y displayInputForm :: AppMessage -> Widget -> Enctype -> Widget displayInputForm title widget enctype = do setTitleI title [whamlet| <h1> _{title} <p> _{MsgInitial} <form method=post action="@{LoanR}#result" enctype=#{enctype}> <div .row-fluid .show-gird> ^{widget} |] abstractWidget :: Widget abstractWidget = [whamlet| <h3>_{MsgYALC} <p>_{MsgNotExactly} <p>_{MsgLongText} |] {- <p> <a href=@{StaticR haslo_pdf} .btn .btn-large> <img src=@{StaticR application_pdf_png}> _{MsgDownloadPaper} -}
bartoszw/yelca
Handler/Home.hs
gpl-2.0
6,627
0
18
2,783
908
463
445
-1
-1
-- Dragon.hs -- La curva dragón -- José A. Alonso Jiménez <jalonso@us.es> -- Sevilla, 24 de Mayo de 2014 -- --------------------------------------------------------------------- module Tema_26.Dragon2 where import Graphics.Gloss -- import System.IO main :: IO () main = do display (InWindow "Dragon" (500,500) (20,20)) white (dragon 1) dragon :: Int -> Picture dragon 0 = Line [(-200,0),(200,0)] dragon n = Pictures [Translate (-100) 100 (Rotate 45 sub)] --, -- Translate 100 100 (Rotate 135 sub)] where sub = Scale r r (dragon (n-1)) r = (fromIntegral 1) /(sqrt 2)
jaalonso/I1M-Cod-Temas
src/Tema_26/Dragon2.hs
gpl-2.0
610
0
11
127
194
108
86
9
1
-- grid is a game written in Haskell -- Copyright (C) 2018 karamellpelle@hotmail.com -- -- This file is part of grid. -- -- grid is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- grid is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with grid. If not, see <http://www.gnu.org/licenses/>. -- module LevelTools.Output ( outputEdit, ) where import MyPrelude import Game import Game.Grid.Output import Game.Grid.GridData import LevelTools.EditWorld import Game.LevelPuzzleMode.Output.Fancy.Draw import Game.Grid.Output.Draw import OpenGL as GL import qualified Graphics.Rendering.OpenGL as GL import Game.Data.Color import Data.List import Game.Helpers.Shade -- tmp import Graphics.UI.GLFW import OpenGL.Helpers as GL import OpenGL.Helpers.Drawings as GL outputEdit :: s -> EditWorld -> b -> MEnv' (s, EditWorld, b) outputEdit s edit b = do gamedata <- resourceGameData (swth, shth) <- screenSize (wth, hth) <- screenShape io $ do glViewport 0 0 (fI swth) (fI shth) -- 3D -- let proj = mat4Perspective valuePerspectiveFOVY (wth / hth) valuePerspectiveNear valuePerspectiveFar modv = mat4SceneCamera $ editGrid edit projmodv = proj `mappend` modv glEnable gl_DEPTH_TEST glEnable gl_CULL_FACE setProjModV proj modv let colormap = griddataColorMap $ gamedataGridData gamedata room = scontentRoom $ editSemiContent edit drawSpaceBoxColor $ colormapAt colormap room -- ground drawMyGround edit -- orig drawOrigo drawCurrentRoom gamedata (editSemiContent edit) room -- draw type drawTypeNode gamedata edit -- 2D -- let proj = mat4Ortho2D 0 (fI swth) (- fI shth) 0 glDisable gl_CULL_FACE glDisable gl_DEPTH_TEST setProjModV proj mempty drawEditText edit return (s, edit, b) -------------------------------------------------------------------------------- -- origo drawOrigo = do glPushMatrix glColor4f 0.0 0.8 0.8 0.7 glLineWidth 2.0 glBegin gl_LINES glVertex3f 0 0 0 glVertex3f 0.5 0 0 glEnd glLineWidth 1.0 glColor4f 1.0 1.0 1.0 0.7 --glTranslatef 0.0 GL.scaleXYZ 0.05 GL.drawSphere glPopMatrix -------------------------------------------------------------------------------- -- drawMyGround drawMyGround edit = do let Node x0 y0 z0 = cameraNode $ gridCamera $ editGrid edit Node x1 y1 z1 = cameraNodeIdeal $ gridCamera $ editGrid edit alpha = cameraNodeAlpha $ gridCamera $ editGrid edit x = smooth x0 x1 $ rTF alpha y = smooth y0 y1 $ rTF alpha z = smooth z0 z1 $ rTF alpha -- tmp glColor4f 1 1 1 0.4 glBegin gl_LINES forM_ [-radius..radius] $ \r -> do glVertex3f (x + fI r) y (z - fI radius) glVertex3f (x + fI r) y (z + fI radius) forM_ [-radius..radius] $ \r -> do glVertex3f (x - fI radius) y (z + fI r) glVertex3f (x + fI radius) y (z + fI r) glEnd -- where smooth x x' a = (1.0 - a) * (fI x) + a * (fI x') radius = 5 :: Int -------------------------------------------------------------------------------- -- drawCurrentRoom drawCurrentRoom gd scontent room = do case find (\r -> sroomRoomIx r == room) (scontentRooms scontent) of Nothing -> return () Just r -> do mapM_ (drawWall 1.0 gd) $ sroomWall r mapM_ (drawDotPlain 1.0 gd) $ sroomDotPlain r mapM_ (drawDotBonus 1.0 gd) $ sroomDotBonus r mapM_ (drawDotTele 1.0 gd) $ sroomDotTele r mapM_ (drawDotFinish 1.0 gd) $ sroomDotFinish r -------------------------------------------------------------------------------- -- drawEditText drawEditText edit = io $ do glColor4f 1 1 1 1 drawStrings $ [ "Message: " ++ editMessage edit, "PuzzleTag: " ++ show (levelPuzzleTag $ editLevel edit), "Segments: " ++ show (levelSegments $ editLevel edit), "Room: " ++ show (scontentRoom $ editSemiContent edit), "Node: " ++ showNode (editNode edit) ] ++ strsType (editEditType edit) where drawStrings strs = do --foldM (\y str -> drawString 0 y str >> return (y + 20)) 20 strs foldM (\y str -> drawString 0 y str >> return (y - 20)) (-20) strs drawString x y str = do glPushMatrix glTranslatef (rTF x) (rTF y) 0.0 renderString Fixed8x16 str glPopMatrix strsType TypeDotPlain = do [ "TypeDotPlain", "Size: " ++ show (dotplainSize $ editDotPlain edit), "Room: " ++ show (dotplainRoom $ editDotPlain edit) ] strsType TypeDotBonus = do [ "TypeDotBonus", "Size: " ++ show (dotbonusSize $ editDotBonus edit), "Add: " ++ show (dotbonusAdd $ editDotBonus edit) ] strsType TypeDotTele = do [ "TypeDotTele", "Size: " ++ show (dotteleSize $ editDotTele edit) ] strsType TypeDotFinish = do [ "TypeDotFinish" ] strsType TypeWall = do [ "TypeWall", "IsDouble: " ++ show (wallIsDouble $ editWall edit) ] strsType _ = do [ "(no type)" ] showNode (Node x y z) = show x ++ " " ++ show y ++ " " ++ show z -------------------------------------------------------------------------------- -- drawTypeNode drawTypeNode gd edit = case editEditType edit of TypeDotPlain -> drawTypeDotPlain gd edit TypeDotBonus -> drawTypeDotBonus gd edit TypeDotTele -> drawTypeDotTele gd edit TypeDotFinish -> drawTypeDotFinish gd edit TypeWall -> drawTypeWall gd edit _ -> return () where alpha = 0.6 drawTypeDotPlain gamedata edit = do let colormap = griddataColorMap $ gamedataGridData gamedata let Color r g b a = colormapAt colormap $ dotplainRoom $ editDotPlain edit let Node x y z = editNode edit glPushMatrix glColor4f r g b (alpha * a) glTranslatef (fI x) (fI y) (fI z) GL.scaleXYZ 0.1 GL.drawSphere glPopMatrix drawTypeDotBonus gamedata edit = do let Node x y z = editNode edit glPushMatrix glColor4f 0.5 0.5 0.7 alpha glTranslatef (fI x) (fI y) (fI z) GL.scaleXYZ 0.1 GL.drawCube glPopMatrix drawTypeDotTele gamedata edit = case editPushedNodes edit of (n:ns) -> do let Node x y z = n Node x' y' z' = editNode edit glPushMatrix glColor4f 0.1 0.1 0.8 1.0 glTranslatef (fI x) (fI y) (fI z) GL.scaleXYZ 0.07 GL.drawCube glPopMatrix glPushMatrix glColor4f 0.8 0.1 0.1 alpha glTranslatef (fI x') (fI y') (fI z') GL.scaleXYZ 0.07 GL.drawCube glPopMatrix [] -> do let Node x y z = editNode edit glPushMatrix glColor4f 0.1 0.1 0.8 alpha glTranslatef (fI x) (fI y) (fI z) GL.scaleXYZ 0.07 GL.drawCube glPopMatrix drawTypeDotFinish gamedata edit = do let Node x y z = editNode edit glPushMatrix glColor4f 1.0 1.0 1.0 alpha glTranslatef (fI x) (fI y) (fI z) GL.scaleXYZ 0.2 GL.drawSphere glPopMatrix drawTypeWall gamedata edit = case editPushedNodes edit of (n0:n1:ns) -> do let Node x0 y0 z0 = n0 Node x1 y1 z1 = n1 Node x2 y2 z2 = editNode edit glPushMatrix glColor4f 1.0 1.0 1.0 1.0 glTranslatef (fI x0) (fI y0) (fI z0) GL.scaleXYZ 0.05 GL.drawSphere glPopMatrix glPushMatrix glColor4f 1.0 1.0 1.0 1.0 glTranslatef (fI x1) (fI y1) (fI z1) GL.scaleXYZ 0.05 GL.drawSphere glPopMatrix glPushMatrix glColor4f 1.0 1.0 1.0 alpha glTranslatef (fI x2) (fI y2) (fI z2) GL.scaleXYZ 0.05 GL.drawSphere glPopMatrix (n0:ns) -> do let Node x0 y0 z0 = n0 Node x1 y1 z1 = editNode edit glPushMatrix glColor4f 1.0 1.0 1.0 1.0 glTranslatef (fI x0) (fI y0) (fI z0) GL.scaleXYZ 0.05 GL.drawSphere glPopMatrix glPushMatrix glColor4f 1.0 1.0 1.0 alpha glTranslatef (fI x1) (fI y1) (fI z1) GL.scaleXYZ 0.05 GL.drawSphere glPopMatrix [] -> do let Node x0 y0 z0 = editNode edit glPushMatrix glColor4f 1.0 1.0 1.0 alpha glTranslatef (fI x0) (fI y0) (fI z0) GL.scaleXYZ 0.05 GL.drawSphere glPopMatrix {- -- setup scene (wth, hth) <- setupScreen let projection = mat4Perspective valueModePerspectiveFOVY (wth / hth) valueModePerspectiveNear valueModePerspectiveFar modelview = sceneCamera $ editGrid edit -- 3D shade3D projection modelview drawGround mempty --(editNode edit) -- tmp io $ do glColor4f 1 1 1 1 glPushMatrix glScalef 0.08 0.08 0.08 GL.drawSphere glPopMatrix -- forM_ (editLevelDots edit) $ drawDot modelview shade3DModelview modelview forM_ (editLevelWalls edit) $ drawWall modelview -- draw pushed nodes forM_ (editPushedNodes edit) $ \(Node x y z) -> do shade3DModelview $ mat4Translate3 modelview (fromIntegral x) (fromIntegral y) (fromIntegral z) -- tmp io $ do glPushMatrix GL.color4 0 0 1 1 GL.scaleXYZ 0.11 GL.drawSphere glPopMatrix -- -- draw node let Node x y z = editNode edit shade3DModelview $ mat4Translate3 modelview (fromIntegral x) (fromIntegral y) (fromIntegral z) -- tmp io $ do glPushMatrix GL.color4 0 1 0 1 GL.scaleXYZ 0.05 GL.drawSphere glPopMatrix -- -- 2D -- negate in y-direction, since GLFW draws from bottom and up (wth, hth) <- screenSize (projection, modelview) <- shade2D (fromIntegral wth) (-(fromIntegral hth)) io $ glColor4f 1 1 1 1 drawStrings modelview $ [ "name: " ++ editLevelName edit, "max segments: " ++ show (editLevelMaxSegments edit), "eat ord: " ++ if editIsEatOrd edit then (show $ editEatOrd edit) else "Nothing", "type: " ++ show (editType edit), "type value: " ++ show (editTypeValue edit), "node: " ++ show (editNode edit) ] return b drawStrings :: Mat4 -> [String] -> MEnv' () drawStrings modelview strs = do foldM (\y str -> drawString modelview 0 y str >> return (y - 20)) (-20) strs return () drawString modelview x y str = do shade2DModelview $ mat4Translate2 modelview (realToFrac x) (realToFrac y) io $ renderString Fixed8x16 str -------------------------------------------------------------------------------- -- -- | draw wall into world drawWall modelview wall = io $ do glDisable gl_CULL_FACE let Node n0 n1 n2 = wallNode wall Node x0 x1 x2 = wallX wall Node y0 y1 y2 = wallY wall -- tmp glColor4f 0 0 1 0.15 glBegin gl_TRIANGLE_STRIP glVertex3f (fromIntegral $ n0) (fromIntegral $ n1) (fromIntegral $ n2) glVertex3f (fromIntegral $ n0 + x0) (fromIntegral $ n1 + x1) (fromIntegral $ n2 + x2) glVertex3f (fromIntegral $ n0 + y0) (fromIntegral $ n1 + y1) (fromIntegral $ n2 + y2) glVertex3f (fromIntegral $ n0 + x0 + y0) (fromIntegral $ n1 + x1 + y1) (fromIntegral $ n2 + x2 + y2) glEnd -- -- | draw dot into world drawDot modelview dot = do case dotSpeciality dot of DotSimple -> drawSimpleDot modelview dot DotTele node' -> drawTeleDot modelview dot node' DotBonus n -> drawBonusDot modelview dot n drawSimpleDot modelview dot = do let Node x y z = dotNode dot shade3DModelview $ mat4Translate3 modelview (fromIntegral x) (fromIntegral y) (fromIntegral z) -- tmp io $ do glPushMatrix glColor4f 1 0.9 0 1 GL.scaleXYZ 0.1 GL.drawSphere glPopMatrix -- drawTeleDot modelview dot node' = do let Node x y z = dotNode dot shade3DModelview $ mat4Translate3 modelview (fromIntegral x) (fromIntegral y) (fromIntegral z) -- tmp io $ do glPushMatrix GL.scaleXYZ (0.125) glColor4f 0.78125 0.6328125 0.78125 0.2 GL.drawCube glPopMatrix -- let Node x' y' z' = node' shade3DModelview $ mat4Translate3 modelview (fromIntegral x') (fromIntegral y') (fromIntegral z') -- tmp io $ do glPushMatrix GL.scaleXYZ (0.100) GL.color4 0.88125 0.6328125 0.68125 0.2 GL.drawCube glPopMatrix -- drawBonusDot modelview dot n = do let Node x y z = dotNode dot shade3DModelview $ mat4Translate3 modelview (fromIntegral x) (fromIntegral y) (fromIntegral z) -- tmp io $ do glPushMatrix GL.scaleXYZ 0.08 case dotEatOrd dot of Nothing -> GL.color4 1 0 1 0.2 Just ord' -> GL.color4 1 0 0.6 1 GL.drawSphere glPopMatrix -- -}
karamellpelle/grid
designer/source/LevelTools/Output.hs
gpl-3.0
15,329
1
15
5,825
2,752
1,293
1,459
223
9
module Main where import Control.Applicative import Control.Monad import Data.List (lookup) import System.Console.Quickterm main = qtMain myQtProgram myQtProgram = program [ command "install" $ cmdInstall <$> flags [ ("--bindir" , Just "/default/bindir" ) , ("--docdir" , Just "/default/docdir" ) , ("--datadir" , Just "/default/datadir" ) , ("--builddir", Just "/default/builddir") , ("--foo" , Nothing ) ] , section "sandbox" [ command_ "init" cmdSandboxInit , command_ "--help" cmdSandboxHelp -- TODO: should be a built-in command , command_ "--snapshot" cmdSandboxSnapshot ] ] -- |Simple application module. cmdSandboxSnapshot :: IO () cmdSandboxSnapshot = do putStrLn "Creating a snapshot..." putStrLn "Done!" putStrLn "" -- |Simple application module. cmdSandboxHelp :: IO () cmdSandboxHelp = do putStrLn "Help description for sandbox commands" putStrLn "" -- |Simple application module. cmdSandboxInit :: IO () cmdSandboxInit = do putStrLn "Initializing a sandbox..." putStrLn "Done!" putStrLn "" -- |Application module with complex cmd-line parameters. cmdInstall :: [(String,String)] -> IO () cmdInstall c = do putStrLn "Starting installation with" print c putStrLn "Installation done!" putStrLn ""
SamuelSchlesinger/Quickterm
src/demo/Main.hs
gpl-3.0
1,353
0
11
308
305
155
150
37
1
module Dsgen.GUIState ( GUI(..), GUIState(..), CardListRow(..), readGUI, getGUIState, mkSetSelectOptions, cardListAppend, cardListRemove ) where import Control.Monad.Error import Control.Monad.Trans(liftIO) import Data.List((\\), sort) import Graphics.UI.Gtk import Dsgen.Cards import Dsgen.SetSelect -- | Holds all the relevant widgets from the UI. data GUI = GUI { -- Sources dominionCheckButton :: CheckButton, intrigueCheckButton :: CheckButton, seasideCheckButton :: CheckButton, alchemyCheckButton :: CheckButton, prosperityCheckButton :: CheckButton, cornucopiaCheckButton :: CheckButton, hinterlandsCheckButton :: CheckButton, darkAgesCheckButton :: CheckButton, guildsCheckButton :: CheckButton, envoyCheckButton :: CheckButton, blackMarketCheckButton :: CheckButton, governorCheckButton :: CheckButton, stashCheckButton :: CheckButton, walledVillageCheckButton :: CheckButton, customCheckButton :: CheckButton, -- Emphasis emphasisCheckButton :: CheckButton, emphasisComboBox :: ComboBox, -- Filters actionFilterCheckButton :: CheckButton, complexityFilterCheckButton :: CheckButton, complexityFilterComboBox :: ComboBox, -- Rules costVarietyRuleCheckButton :: CheckButton, interactivityRuleCheckButton :: CheckButton, interactivityRuleComboBox :: ComboBox, reactionRuleCheckButton :: CheckButton, reactionRuleComboBox :: ComboBox, trasherRuleCheckButton :: CheckButton, trasherRuleComboBox :: ComboBox, -- Additions colPlatAdditionCheckButton :: CheckButton, sheltersAdditionCheckButton :: CheckButton, sheltersAdditionComboBox :: ComboBox, -- Card lists and other output widgets randomCardsTreeView :: TreeView, randomCardsListStore :: ListStore CardListRow, manualCardsTreeView :: TreeView, manualCardsListStore :: ListStore CardListRow, vetoedCardsTreeView :: TreeView, vetoedCardsListStore :: ListStore CardListRow, colPlatLabel :: Label, sheltersLabel :: Label, -- Output window input widgets addManualCardButton :: Button, rmvManualCardsButton :: Button, addVetoedCardButton :: Button, rmvVetoedCardsButton :: Button, selectSetButton :: Button, pickCountComboBox :: ComboBox, -- Containers mainNotebook :: Notebook } {- | Holds the state of all GUI widgets which we might be interested in reading, and the actual widgets we might be interested in modifying -} data GUIState = GUIState { -- Sources dominionCheckedState :: Bool, intrigueCheckedState :: Bool, seasideCheckedState :: Bool, alchemyCheckedState :: Bool, prosperityCheckedState :: Bool, cornucopiaCheckedState :: Bool, hinterlandsCheckedState :: Bool, darkAgesCheckedState :: Bool, guildsCheckedState :: Bool, envoyCheckedState :: Bool, blackMarketCheckedState :: Bool, governorCheckedState :: Bool, stashCheckedState :: Bool, walledVillageCheckedState :: Bool, customCheckedState :: Bool, -- Emphasis emphasisCheckedState :: Bool, emphasisValue :: Int, -- Filters actionFilterCheckedState :: Bool, complexityFilterCheckedState :: Bool, complexityFilterValue :: Int, -- Rules costVarietyRuleCheckedState :: Bool, interactivityRuleCheckedState :: Bool, interactivityRuleValue :: Int, reactionRuleCheckedState :: Bool, reactionRuleValue :: Int, trasherRuleCheckedState :: Bool, trasherRuleValue :: Int, -- Additions colPlatAdditionCheckedState :: Bool, sheltersAdditionCheckedState :: Bool, sheltersAdditionValue :: Int, -- Card lists randomCardsList :: [Card], manualCardsList :: [Card], vetoedCardsList :: [Card], -- Pick count pickCountValue :: Int } deriving (Show) data CardListRow = CardListRow { col1 :: String, col2 :: String, col3 :: String } deriving (Read, Show) -- | Create a 'GUI' object based on the contents of a Glade Builder. readGUI :: Builder -> IO GUI readGUI b = do -- Sources dominionCB <- liftIO $ builderGetObject b castToCheckButton "dominionCheckButton" intrigueCB <- liftIO $ builderGetObject b castToCheckButton "intrigueCheckButton" seasideCB <- liftIO $ builderGetObject b castToCheckButton "seasideCheckButton" alchemyCB <- liftIO $ builderGetObject b castToCheckButton "alchemyCheckButton" prosperityCB <- liftIO $ builderGetObject b castToCheckButton "prosperityCheckButton" cornucopiaCB <- liftIO $ builderGetObject b castToCheckButton "cornucopiaCheckButton" hinterlandsCB <- liftIO $ builderGetObject b castToCheckButton "hinterlandsCheckButton" darkAgesCB <- liftIO $ builderGetObject b castToCheckButton "darkAgesCheckButton" guildsCB <- liftIO $ builderGetObject b castToCheckButton "guildsCheckButton" envoyCB <- liftIO $ builderGetObject b castToCheckButton "envoyCheckButton" blackMarketCB <- liftIO $ builderGetObject b castToCheckButton "blackMarketCheckButton" governorCB <- liftIO $ builderGetObject b castToCheckButton "governorCheckButton" stashCB <- liftIO $ builderGetObject b castToCheckButton "stashCheckButton" walledVillageCB <- liftIO $ builderGetObject b castToCheckButton "walledVillageCheckButton" customCB <- liftIO $ builderGetObject b castToCheckButton "customCheckButton" -- Emphasis emphasisCB <- liftIO $ builderGetObject b castToCheckButton "emphasisCheckButton" emphasisCBX <- liftIO $ builderGetObject b castToComboBox "emphasisComboBox" -- Filters actionFilterCB <- liftIO $ builderGetObject b castToCheckButton "actionFilterCheckButton" complexityFilterCB <- liftIO $ builderGetObject b castToCheckButton "complexityFilterCheckButton" complexityFilterCBX <- liftIO $ builderGetObject b castToComboBox "complexityFilterComboBox" -- Rules costVarietyRuleCB <- liftIO $ builderGetObject b castToCheckButton "costVarietyRuleCheckButton" interactivityRuleCB <- liftIO $ builderGetObject b castToCheckButton "interactivityRuleCheckButton" interactivityRuleCBX <- liftIO $ builderGetObject b castToComboBox "interactivityRuleComboBox" reactionRuleCB <- liftIO $ builderGetObject b castToCheckButton "reactionRuleCheckButton" reactionRuleCBX <- liftIO $ builderGetObject b castToComboBox "reactionRuleComboBox" trasherRuleCB <- liftIO $ builderGetObject b castToCheckButton "trasherRuleCheckButton" trasherRuleCBX <- liftIO $ builderGetObject b castToComboBox "trasherRuleComboBox" -- Additions colPlatAdditionCB <- liftIO $ builderGetObject b castToCheckButton "colPlatAdditionCheckButton" sheltersAdditionCB <- liftIO $ builderGetObject b castToCheckButton "sheltersAdditionCheckButton" sheltersAdditionCBX <- liftIO $ builderGetObject b castToComboBox "sheltersAdditionComboBox" -- Card lists and other output widgets randomCardsTV <- liftIO $ builderGetObject b castToTreeView "randomCardsTreeView" randomCardsLS <- liftIO $ cardListCreate randomCardsTV manualCardsTV <- liftIO $ builderGetObject b castToTreeView "manualCardsTreeView" manualCardsLS <- liftIO $ cardListCreate manualCardsTV vetoedCardsTV <- liftIO $ builderGetObject b castToTreeView "vetoedCardsTreeView" vetoedCardsLS <- liftIO $ cardListCreate vetoedCardsTV colPlatL <- liftIO $ builderGetObject b castToLabel "colPlatLabel" sheltersL <- liftIO $ builderGetObject b castToLabel "sheltersLabel" -- Output window input widgets addManualCardB <- liftIO $ builderGetObject b castToButton "addManualCardButton" rmvManualCardsB <- liftIO $ builderGetObject b castToButton "rmvManualCardsButton" addVetoedCardB <- liftIO $ builderGetObject b castToButton "addVetoedCardButton" rmvVetoedCardsB <- liftIO $ builderGetObject b castToButton "rmvVetoedCardsButton" selectSetB <- liftIO $ builderGetObject b castToButton "selectSetButton" pickCountCBX <- liftIO $ builderGetObject b castToComboBox "pickCountComboBox" -- Containers mainNB <- liftIO $ builderGetObject b castToNotebook "mainNotebook" return $ GUI { -- Sources dominionCheckButton = dominionCB, intrigueCheckButton = intrigueCB, seasideCheckButton = seasideCB, alchemyCheckButton = alchemyCB, prosperityCheckButton = prosperityCB, cornucopiaCheckButton = cornucopiaCB, hinterlandsCheckButton = hinterlandsCB, darkAgesCheckButton = darkAgesCB, guildsCheckButton = guildsCB, envoyCheckButton = envoyCB, blackMarketCheckButton = blackMarketCB, governorCheckButton = governorCB, stashCheckButton = stashCB, walledVillageCheckButton = walledVillageCB, customCheckButton = customCB, -- Emphasis emphasisCheckButton = emphasisCB, emphasisComboBox = emphasisCBX, -- Filters actionFilterCheckButton = actionFilterCB, complexityFilterCheckButton = complexityFilterCB, complexityFilterComboBox = complexityFilterCBX, -- Rules costVarietyRuleCheckButton = costVarietyRuleCB, interactivityRuleCheckButton = interactivityRuleCB, interactivityRuleComboBox = interactivityRuleCBX, reactionRuleCheckButton = reactionRuleCB, reactionRuleComboBox = reactionRuleCBX, trasherRuleCheckButton = trasherRuleCB, trasherRuleComboBox = trasherRuleCBX, -- Additions colPlatAdditionCheckButton = colPlatAdditionCB, sheltersAdditionCheckButton = sheltersAdditionCB, sheltersAdditionComboBox = sheltersAdditionCBX, -- Card lists and other output widgets randomCardsTreeView = randomCardsTV, randomCardsListStore = randomCardsLS, manualCardsTreeView = manualCardsTV, manualCardsListStore = manualCardsLS, vetoedCardsTreeView = vetoedCardsTV, vetoedCardsListStore = vetoedCardsLS, colPlatLabel = colPlatL, sheltersLabel = sheltersL, -- Output window input widgets addManualCardButton = addManualCardB, rmvManualCardsButton = rmvManualCardsB, addVetoedCardButton = addVetoedCardB, rmvVetoedCardsButton = rmvVetoedCardsB, selectSetButton = selectSetB, pickCountComboBox = pickCountCBX, -- Containers mainNotebook = mainNB } -- | Create a 'GUIState' object based on the contents of a 'GUI' object. getGUIState :: GUI -> [Card] -> IO GUIState getGUIState gui cs = do -- Sources dominionCS <- toggleButtonGetActive $ dominionCheckButton gui intrigueCS <- toggleButtonGetActive $ intrigueCheckButton gui seasideCS <- toggleButtonGetActive $ seasideCheckButton gui alchemyCS <- toggleButtonGetActive $ alchemyCheckButton gui prosperityCS <- toggleButtonGetActive $ prosperityCheckButton gui cornucopiaCS <- toggleButtonGetActive $ cornucopiaCheckButton gui hinterlandsCS <- toggleButtonGetActive $ hinterlandsCheckButton gui darkAgesCS <- toggleButtonGetActive $ darkAgesCheckButton gui guildsCS <- toggleButtonGetActive $ guildsCheckButton gui envoyCS <- toggleButtonGetActive $ envoyCheckButton gui blackMarketCS <- toggleButtonGetActive $ blackMarketCheckButton gui governorCS <- toggleButtonGetActive $ governorCheckButton gui stashCS <- toggleButtonGetActive $ stashCheckButton gui walledVillageCS <- toggleButtonGetActive $ walledVillageCheckButton gui customCS <- toggleButtonGetActive $ customCheckButton gui -- Emphasis emphasisCS <- toggleButtonGetActive $ emphasisCheckButton gui emphasisV <- comboBoxGetActive $ emphasisComboBox gui -- Filters actionFilterCS <- toggleButtonGetActive $ actionFilterCheckButton gui complexityFilterCS <- toggleButtonGetActive $ complexityFilterCheckButton gui complexityFilterV <- comboBoxGetActive $ complexityFilterComboBox gui -- Rules costVarietyRuleCS <- toggleButtonGetActive $ costVarietyRuleCheckButton gui interactivityRuleCS <- toggleButtonGetActive $ interactivityRuleCheckButton gui interactivityRuleV <- comboBoxGetActive $ interactivityRuleComboBox gui reactionRuleCS <- toggleButtonGetActive $ reactionRuleCheckButton gui reactionRuleV <- comboBoxGetActive $ reactionRuleComboBox gui trasherRuleCS <- toggleButtonGetActive $ trasherRuleCheckButton gui trasherRuleV <- comboBoxGetActive $ trasherRuleComboBox gui -- Additions colPlatAdditionCS <- toggleButtonGetActive $ colPlatAdditionCheckButton gui sheltersAdditionCS <- toggleButtonGetActive $ sheltersAdditionCheckButton gui sheltersAdditionV <- comboBoxGetActive $ sheltersAdditionComboBox gui -- Card lists randomCardNames <- getAllCardNames $ randomCardsListStore gui let randomCL = filter (\c -> elem (cardName c) randomCardNames) cs manualCardNames <- getAllCardNames $ manualCardsListStore gui let manualCL = filter (\c -> elem (cardName c) manualCardNames) cs vetoedCardNames <- getAllCardNames $ vetoedCardsListStore gui let vetoedCL = filter (\c -> elem (cardName c) vetoedCardNames) cs -- Pick count pickCountV <- comboBoxGetActive $ pickCountComboBox gui return $ GUIState { -- Sources dominionCheckedState = dominionCS, intrigueCheckedState = intrigueCS, seasideCheckedState = seasideCS, alchemyCheckedState = alchemyCS, prosperityCheckedState = prosperityCS, cornucopiaCheckedState = cornucopiaCS, hinterlandsCheckedState = hinterlandsCS, darkAgesCheckedState = darkAgesCS, guildsCheckedState = guildsCS, envoyCheckedState = envoyCS, blackMarketCheckedState = blackMarketCS, governorCheckedState = governorCS, stashCheckedState = stashCS, walledVillageCheckedState = walledVillageCS, customCheckedState = customCS, -- Emphasis emphasisCheckedState = emphasisCS, emphasisValue = emphasisV, -- Filters actionFilterCheckedState = actionFilterCS, complexityFilterCheckedState = complexityFilterCS, complexityFilterValue = complexityFilterV, -- Rules costVarietyRuleCheckedState = costVarietyRuleCS, interactivityRuleCheckedState = interactivityRuleCS, interactivityRuleValue = interactivityRuleV, reactionRuleCheckedState = reactionRuleCS, reactionRuleValue = reactionRuleV, trasherRuleCheckedState = trasherRuleCS, trasherRuleValue = trasherRuleV, -- Additions colPlatAdditionCheckedState = colPlatAdditionCS, sheltersAdditionCheckedState = sheltersAdditionCS, sheltersAdditionValue = sheltersAdditionV, -- Card lists randomCardsList = randomCL, manualCardsList = manualCL, vetoedCardsList = vetoedCL, -- Pick count pickCountValue = pickCountV } -- | Builds a 'SetSelectOptions' object based on the GUI state and a card pool. mkSetSelectOptions :: GUIState -> [Card] -> SetSelectOptions mkSetSelectOptions gst cs = SetSelectOptions { ssoPickCount = pickCount - (length manualCards), -- TODO: Non-hardcode 10 ssoPool = (cs \\ manualCards) \\ (vetoedCardsList gst), ssoManualPicks = manualCards, ssoSources = sources, ssoEmphasis = emphasis, ssoFilters = filters, ssoRules = rules, ssoColPlatAddition = colPlat, ssoSheltersAddition = shelters } where pickCount = (pickCountValue gst) + 8 manualCards = manualCardsList gst sources = concat [ (if dominionCheckedState gst then [Dominion] else []), (if intrigueCheckedState gst then [Intrigue] else []), (if alchemyCheckedState gst then [Alchemy] else []), (if seasideCheckedState gst then [Seaside] else []), (if prosperityCheckedState gst then [Prosperity] else []), (if cornucopiaCheckedState gst then [Cornucopia] else []), (if hinterlandsCheckedState gst then [Hinterlands] else []), (if darkAgesCheckedState gst then [DarkAges] else []), (if guildsCheckedState gst then [Guilds] else []), (if envoyCheckedState gst then [EnvoyPromo] else []), (if blackMarketCheckedState gst then [BlackMarketPromo] else []), (if governorCheckedState gst then [GovernorPromo] else []), (if stashCheckedState gst then [StashPromo] else []), (if walledVillageCheckedState gst then [WalledVillagePromo] else []), (if customCheckedState gst then [Custom] else []) ] emphasis = if not $ emphasisCheckedState gst then NoEmphasis else case emphasisValue gst of 0 -> RandomEmphasis 1 -> DominionEmphasis 2 -> IntrigueEmphasis 3 -> SeasideEmphasis 4 -> AlchemyEmphasis 5 -> ProsperityEmphasis 6 -> CornucopiaEmphasis 7 -> HinterlandsEmphasis 8 -> DarkAgesEmphasis 9 -> GuildsEmphasis filters = concat [ (if actionFilterCheckedState gst then [actionFilter] else []), (if complexityFilterCheckedState gst then [complexityFilter $ convertComplexityFilterValue $ complexityFilterValue gst] else []) ] rules = concat [ (if reactionRuleCheckedState gst then [reactionRule $ convertReactionRuleValue $ reactionRuleValue gst] else []), (if trasherRuleCheckedState gst then [trasherRule $ convertTrasherRuleValue $ trasherRuleValue gst] else []), (if interactivityRuleCheckedState gst then [interactivityRule $ convertInteractivityRuleValue $ interactivityRuleValue gst] else []), (if costVarietyRuleCheckedState gst then [costVarietyRule] else []) ] colPlat = if colPlatAdditionCheckedState gst then RandomColPlat else NoColPlat shelters = if not $ sheltersAdditionCheckedState gst then NoShelters else case sheltersAdditionValue gst of 0 -> SheltersWithDarkAges 1 -> RandomShelters convertComplexityFilterValue v = case v of 0 -> LowComplexityOnly 1 -> MediumComplexityOrLower 2 -> HighComplexityOrLower convertReactionRuleValue v = case v of 0 -> RequireMoat 1 -> RequireBlocker 2 -> RequireReaction convertTrasherRuleValue v = case v of 0 -> TrasherWithCurse 1 -> AlwaysTrasher convertInteractivityRuleValue v = v + 1 cardListCreate :: TreeView -> IO (ListStore CardListRow) cardListCreate tv = do lst <- listStoreNew ([] :: [CardListRow]) addColumn tv lst col1 "Name" addColumn tv lst col2 "Cost" addColumn tv lst col3 "Source" treeViewSetModel tv lst return lst where addColumn tv lst f name = do col <- treeViewColumnNew rend <- cellRendererTextNew treeViewColumnSetTitle col name treeViewColumnPackStart col rend True cellLayoutSetAttributes col rend lst (\row -> [ cellText := f row ]) treeViewColumnSetExpand col True treeViewAppendColumn tv col cardListAppend :: ListStore CardListRow -> Card -> IO () cardListAppend lst c = do listStoreAppend lst $ CardListRow { col1 = cardName c, col2 = displayAmount (cardCost c), col3 = show (cardSource c) } return () cardListRemove :: ListStore CardListRow -> Int -> IO () cardListRemove lst n = do listStoreRemove lst n return () {- Helper functions -} -- | Gets all strings in the first column of a 'TreeModel'. getAllCardNames :: ListStore CardListRow -> IO [String] getAllCardNames lst = do size <- listStoreGetSize lst getAllValues size 0 where getAllValues n i = if i >= n then return [] else do val <- listStoreGetValue lst i ((col1 val) :) `liftM` (getAllValues n (i+1)) -- | Gets a 'TreeModel' from a 'TreeView', throwing an error if no model exists. getTreeModel :: TreeViewClass self => self -> IO TreeModel getTreeModel tv = do tmm <- treeViewGetModel tv return $ maybe (error "No model defined for TreeView") id tmm
pshendry/dsgen
src/Dsgen/GUIState.hs
gpl-3.0
21,963
0
15
6,081
4,021
2,172
1,849
386
40
{-| Module : DoublyLinkedTree License : GPL Maintainer : helium@cs.uu.nl Stability : experimental Portability : portable In a doubly linked, every node has access to its parent and its children. At each node, extra information (attributes) can be stored. -} module Helium.StaticAnalysis.Miscellaneous.DoublyLinkedTree where import Helium.Utils.Utils (internalError) data DoublyLinkedTree attributes = DoublyLinkedTree { parent :: Maybe (DoublyLinkedTree attributes) , attribute :: attributes , children :: [DoublyLinkedTree attributes] } root :: a -> [DoublyLinkedTree a] -> DoublyLinkedTree a root = DoublyLinkedTree Nothing node :: DoublyLinkedTree a -> a -> [DoublyLinkedTree a] -> DoublyLinkedTree a node p = DoublyLinkedTree (Just p) selectChild :: Int -> DoublyLinkedTree a -> DoublyLinkedTree a selectChild i tree = case drop i (children tree) of [] -> internalError "TypeInferDoublyLinkedTreenceInfo.hs" "selectChild" "no such child" hd:_ -> hd selectRoot :: DoublyLinkedTree a -> DoublyLinkedTree a selectRoot tree = maybe tree selectRoot (parent tree)
roberth/uu-helium
src/Helium/StaticAnalysis/Miscellaneous/DoublyLinkedTree.hs
gpl-3.0
1,260
0
11
341
244
126
118
17
2
contramap :: (c' -> c) -> (c -> LimD) -> (c' -> LimD) contramap f u = u . f
hmemcpy/milewski-ctfp-pdf
src/content/2.2/code/haskell/snippet02.hs
gpl-3.0
76
0
8
20
49
26
23
2
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Sound.Tidal.Simple where import Sound.Tidal.Control (chop, hurry) import Sound.Tidal.Core ((#), (|*), (<~), silence, rev) import Sound.Tidal.Params (crush, gain, pan, speed, s) import Sound.Tidal.ParseBP (parseBP_E) import Sound.Tidal.Pattern (ControlPattern) import GHC.Exts ( IsString(..) ) instance {-# OVERLAPPING #-} IsString ControlPattern where fromString = s . parseBP_E crunch :: ControlPattern -> ControlPattern crunch = (# crush 3) scratch :: ControlPattern -> ControlPattern scratch = rev . chop 32 louder :: ControlPattern -> ControlPattern louder = (|* gain 1.2) quieter :: ControlPattern -> ControlPattern quieter = (|* gain 0.8) silent :: ControlPattern -> ControlPattern silent = const silence skip :: ControlPattern -> ControlPattern skip = (0.25 <~) left :: ControlPattern -> ControlPattern left = (# pan 0) right :: ControlPattern -> ControlPattern right = (# pan 1) higher :: ControlPattern -> ControlPattern higher = (|* speed 1.5) lower :: ControlPattern -> ControlPattern lower = (|* speed 0.75) faster :: ControlPattern -> ControlPattern faster = hurry 2 slower :: ControlPattern -> ControlPattern slower = hurry 0.5
d0kt0r0/Tidal
src/Sound/Tidal/Simple.hs
gpl-3.0
1,263
41
6
189
385
215
170
35
1
module Tests.TemplateHaskell where import QHaskell.MyPrelude import Language.Haskell.TH.Syntax add :: Word32 -> Word32 -> Word32 add = (+) dbl :: Q (TExp (Word32 -> Word32)) dbl = [||\ x -> add x x ||] compose :: Q (TExp ((tb -> tc) -> (ta -> tb) -> ta -> tc)) compose = [|| \ x2 -> \ x1 -> \ x0 -> x2 (x1 x0) ||] four :: Q (TExp Word32) four = [|| ($$compose $$dbl $$dbl) 1 ||]
shayan-najd/QHaskell
Tests/TemplateHaskell.hs
gpl-3.0
398
6
14
96
201
112
89
-1
-1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Content.Returnaddress.Insert -- 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) -- -- Inserts a return address for the Merchant Center account. -- -- /See:/ <https://developers.google.com/shopping-content/v2/ Content API for Shopping Reference> for @content.returnaddress.insert@. module Network.Google.Resource.Content.Returnaddress.Insert ( -- * REST Resource ReturnaddressInsertResource -- * Creating a Request , returnaddressInsert , ReturnaddressInsert -- * Request Lenses , ri1Xgafv , ri1MerchantId , ri1UploadProtocol , ri1AccessToken , ri1UploadType , ri1Payload , ri1Callback ) where import Network.Google.Prelude import Network.Google.ShoppingContent.Types -- | A resource alias for @content.returnaddress.insert@ method which the -- 'ReturnaddressInsert' request conforms to. type ReturnaddressInsertResource = "content" :> "v2.1" :> Capture "merchantId" (Textual Word64) :> "returnaddress" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] ReturnAddress :> Post '[JSON] ReturnAddress -- | Inserts a return address for the Merchant Center account. -- -- /See:/ 'returnaddressInsert' smart constructor. data ReturnaddressInsert = ReturnaddressInsert' { _ri1Xgafv :: !(Maybe Xgafv) , _ri1MerchantId :: !(Textual Word64) , _ri1UploadProtocol :: !(Maybe Text) , _ri1AccessToken :: !(Maybe Text) , _ri1UploadType :: !(Maybe Text) , _ri1Payload :: !ReturnAddress , _ri1Callback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ReturnaddressInsert' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ri1Xgafv' -- -- * 'ri1MerchantId' -- -- * 'ri1UploadProtocol' -- -- * 'ri1AccessToken' -- -- * 'ri1UploadType' -- -- * 'ri1Payload' -- -- * 'ri1Callback' returnaddressInsert :: Word64 -- ^ 'ri1MerchantId' -> ReturnAddress -- ^ 'ri1Payload' -> ReturnaddressInsert returnaddressInsert pRi1MerchantId_ pRi1Payload_ = ReturnaddressInsert' { _ri1Xgafv = Nothing , _ri1MerchantId = _Coerce # pRi1MerchantId_ , _ri1UploadProtocol = Nothing , _ri1AccessToken = Nothing , _ri1UploadType = Nothing , _ri1Payload = pRi1Payload_ , _ri1Callback = Nothing } -- | V1 error format. ri1Xgafv :: Lens' ReturnaddressInsert (Maybe Xgafv) ri1Xgafv = lens _ri1Xgafv (\ s a -> s{_ri1Xgafv = a}) -- | The Merchant Center account to insert a return address for. ri1MerchantId :: Lens' ReturnaddressInsert Word64 ri1MerchantId = lens _ri1MerchantId (\ s a -> s{_ri1MerchantId = a}) . _Coerce -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ri1UploadProtocol :: Lens' ReturnaddressInsert (Maybe Text) ri1UploadProtocol = lens _ri1UploadProtocol (\ s a -> s{_ri1UploadProtocol = a}) -- | OAuth access token. ri1AccessToken :: Lens' ReturnaddressInsert (Maybe Text) ri1AccessToken = lens _ri1AccessToken (\ s a -> s{_ri1AccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ri1UploadType :: Lens' ReturnaddressInsert (Maybe Text) ri1UploadType = lens _ri1UploadType (\ s a -> s{_ri1UploadType = a}) -- | Multipart request metadata. ri1Payload :: Lens' ReturnaddressInsert ReturnAddress ri1Payload = lens _ri1Payload (\ s a -> s{_ri1Payload = a}) -- | JSONP ri1Callback :: Lens' ReturnaddressInsert (Maybe Text) ri1Callback = lens _ri1Callback (\ s a -> s{_ri1Callback = a}) instance GoogleRequest ReturnaddressInsert where type Rs ReturnaddressInsert = ReturnAddress type Scopes ReturnaddressInsert = '["https://www.googleapis.com/auth/content"] requestClient ReturnaddressInsert'{..} = go _ri1MerchantId _ri1Xgafv _ri1UploadProtocol _ri1AccessToken _ri1UploadType _ri1Callback (Just AltJSON) _ri1Payload shoppingContentService where go = buildClient (Proxy :: Proxy ReturnaddressInsertResource) mempty
brendanhay/gogol
gogol-shopping-content/gen/Network/Google/Resource/Content/Returnaddress/Insert.hs
mpl-2.0
5,198
0
18
1,234
802
465
337
117
1
{-# LANGUAGE OverloadedStrings #-} module Controller.Register ( passwordResetHandler , viewPasswordReset , postPasswordReset , registerHandler , viewRegister , postRegister , resendInvestigatorHandler , resendInvestigator ) where import Control.Applicative ((<$>)) import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as BSB import qualified Data.ByteString.Char8 as BSC import Data.Monoid ((<>)) import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TLE import Network.HTTP.Types.Method (methodGet, methodPost) import qualified Network.HTTP.Types.Method as HTM import Servant (FromHttpApiData(..)) import Ops import Has import Service.Mail import Static.Fillin import Model.Permission import Model.Id import Model.Party import Model.Identity import Model.Token import HTTP.Form.Deform import HTTP.Path.Parser import Action import Controller.Paths import Controller.Form import Controller.Permission import Controller.Party import Controller.Token import Controller.Angular import View.Register resetPasswordMail :: Either BS.ByteString SiteAuth -> T.Text -> (Maybe TL.Text -> TL.Text) -> Handler () resetPasswordMail (Left email) subj body = sendMail [Left email] [] subj (body Nothing) resetPasswordMail (Right auth) subj body = do tok <- loginTokenId =<< createLoginToken auth True req <- peek sendMail [Right $ view auth] [] subj (body $ Just $ TLE.decodeLatin1 $ BSB.toLazyByteString $ actionURL (Just req) viewLoginToken (HTML, tok) []) registerHandler :: API -> HTM.Method -> [(BS.ByteString, BS.ByteString)] -> Action registerHandler api method _ | method == methodGet && api == HTML = viewRegisterAction | method == methodPost = postRegisterAction api | otherwise = error "unhandled api/method combo" -- TODO: better error viewRegister :: ActionRoute () viewRegister = action GET (pathHTML </< "user" </< "register") $ \() -> viewRegisterAction viewRegisterAction :: Action viewRegisterAction = withAuth $ do angular maybeIdentity (peeks $ blankForm . htmlRegister) (\_ -> peeks $ otherRouteResponse [] viewParty (HTML, TargetProfile)) postRegister :: ActionRoute API postRegister = action POST (pathAPI </< "user" </< "register") postRegisterAction data RegisterRequest = RegisterRequest T.Text (Maybe T.Text) BSC.ByteString (Maybe T.Text) Bool postRegisterAction :: API -> Action postRegisterAction = \api -> withoutAuth $ do reg <- runForm ((api == HTML) `thenUse` htmlRegister) $ do name <- "sortname" .:> (deformRequired =<< deform) prename <- "prename" .:> deformNonEmpty deform email <- "email" .:> emailTextForm affiliation <- "affiliation" .:> deformNonEmpty deform agreement <- "agreement" .:> (deformCheck "You must consent to the user agreement." id =<< deform) let _ = RegisterRequest name prename email affiliation agreement let p = blankParty { partyRow = (partyRow blankParty) { partySortName = name , partyPreName = prename , partyAffiliation = affiliation } , partyAccount = Just a } a = Account { accountParty = p , accountEmail = email } return a auth <- maybe (SiteAuth <$> addAccount reg <*> pure Nothing <*> pure mempty) return =<< lookupSiteAuthByEmail False (accountEmail reg) resetPasswordMail (Right auth) "Databrary account created" $ \(Just url) -> "Thank you for registering Databrary. with Please use this link to complete your registration:\n\n" <> url <> "\n\n\ \By clicking the above link, you also indicate that you have read and understand the Databrary Access agreement and all of it's Annexes here: https://databrary.org/about/agreement.html\n\n\ \Once you've validated your e-mail, you will be able to request authorization to be granted full access to Databrary. \n" focusIO $ staticSendInvestigator (view auth) return $ okResponse [] $ "Your confirmation email has been sent to '" <> accountEmail reg <> "'." resendInvestigator :: ActionRoute (Id Party) resendInvestigator = action POST (pathHTML >/> pathId </< "investigator") $ \i -> resendInvestigatorHandler [("partyId", (BSC.pack . show) i)] resendInvestigatorHandler :: [(BS.ByteString, BS.ByteString)] -> Action resendInvestigatorHandler params = withAuth $ do -- TODO: handle POST only let paramId = maybe (error "partyId missing") TE.decodeUtf8 (lookup "partyId" params) let i = either (error . show) Id (parseUrlPiece paramId) checkMemberADMIN p <- getParty (Just PermissionREAD) (TargetParty i) focusIO $ staticSendInvestigator p return $ okResponse [] ("sent" :: String) passwordResetHandler :: API -> HTM.Method -> [(BS.ByteString, BS.ByteString)] -> Action passwordResetHandler api method _ | method == methodGet && api == HTML = viewPasswordResetAction | method == methodPost = postPasswordResetAction api | otherwise = error "unhandled api/method combo" -- TODO: better error viewPasswordReset :: ActionRoute () viewPasswordReset = action GET (pathHTML </< "user" </< "password") $ \() -> viewPasswordResetAction viewPasswordResetAction :: Action viewPasswordResetAction = withoutAuth $ do angular peeks $ blankForm . htmlPasswordReset postPasswordReset :: ActionRoute API postPasswordReset = action POST (pathAPI </< "user" </< "password") postPasswordResetAction data PasswordResetRequest = PasswordResetRequest BSC.ByteString postPasswordResetAction :: API -> Action postPasswordResetAction = \api -> withoutAuth $ do PasswordResetRequest email <- runForm ((api == HTML) `thenUse` htmlPasswordReset) $ PasswordResetRequest <$> ("email" .:> emailTextForm) auth <- lookupPasswordResetAccount email resetPasswordMail (maybe (Left email) Right auth) "Databrary password reset" $ ("Someone (hopefully you) has requested to reset the password for the Databrary account associated with this email address. If you did not request this, let us know (by replying to this message) or simply ignore it.\n\n" <>) . maybe "Unfortunately, no Databrary account was found for this email address. You can try again with a different email address, or reply to this email for assistance.\n" ("Otherwise, you may use this link to reset your Databrary password:\n\n" <>) return $ okResponse [] $ "Your password reset information has been sent to '" <> email <> "'."
databrary/databrary
src/Controller/Register.hs
agpl-3.0
6,524
0
20
1,157
1,640
866
774
129
1
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, TypeFamilies #-} module Coercion where -- Start basic class Add a b where type SumTy a b add :: a -> b -> SumTy a b instance Add Integer Double where type SumTy Integer Double = Double add x y = fromIntegral x + y instance Add Double Integer where type SumTy Double Integer = Double add x y = x + fromIntegral y instance (Num a) => Add a a where type SumTy a a = a add x y = x + y -- End basic -- Start recursive instance (Add Integer a) => Add Integer [a] where type SumTy Integer [a] = [SumTy Integer a] add x y = map (add x) y -- End recursive -- A variation for heterogeneous lists -- Start Cons class Cons a b where type ResTy a b cons :: a -> [b] -> [ResTy a b] instance Cons Integer Double where type ResTy Integer Double = Double cons x ys = fromIntegral x : ys -- ... -- End Cons instance Cons Double Integer where type ResTy Double Integer = Double cons x ys = x : map fromIntegral ys instance Cons a a where type ResTy a a = a cons x ys = x : ys tcons = cons three $ cons two $ cons two $ [one] where one = 1::Integer two = 2.0::Double three = 3::Integer
egaburov/funstuff
Haskell/fun-with-types/codes/Coercion.hs
apache-2.0
1,206
0
10
302
442
235
207
33
1
{- Copyright (c) Facebook, Inc. and its affiliates. 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 CPP #-} {-# LANGUAGE FlexibleInstances #-} -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- module Thrift.Transport.HttpClient ( module Thrift.Transport , HttpClient (..) , openHttpClient ) where import Thrift.Transport import Thrift.Transport.IOBuffer import Network.URI import Network.HTTP hiding (port, host) import Data.Maybe (fromJust) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (mempty) #endif import Control.Exception (throw) import qualified Data.ByteString.Lazy as LBS -- | 'HttpClient', or THttpClient implements the Thrift Transport -- | Layer over http or https. data HttpClient = HttpClient { hstream :: HandleStream LBS.ByteString, uri :: URI, writeBuffer :: WriteBuffer, readBuffer :: ReadBuffer } uriAuth :: URI -> URIAuth uriAuth = fromJust . uriAuthority host :: URI -> String host = uriRegName . uriAuth port :: URI -> Int port uri_ = if portStr == mempty then httpPort else read portStr where portStr = dropWhile (== ':') $ uriPort $ uriAuth uri_ httpPort = 80 -- | Use 'openHttpClient' to create an HttpClient connected to @uri@ openHttpClient :: URI -> IO HttpClient openHttpClient uri_ = do stream <- openTCPConnection (host uri_) (port uri_) wbuf <- newWriteBuffer rbuf <- newReadBuffer return $ HttpClient stream uri_ wbuf rbuf instance Transport HttpClient where tClose = close . hstream tPeek = peekBuf . readBuffer tRead = readBuf . readBuffer tWrite = writeBuf . writeBuffer tFlush hclient = do body <- flushBuf $ writeBuffer hclient let request = Request { rqURI = uri hclient, rqHeaders = [ mkHeader HdrContentType "application/x-thrift", mkHeader HdrContentLength $ show $ LBS.length body], rqMethod = POST, rqBody = body } res <- sendHTTP (hstream hclient) request case res of Right response -> fillBuf (readBuffer hclient) (rspBody response) Left _ -> throw $ TransportExn "THttpConnection: HTTP failure from server" TE_UNKNOWN return () tIsOpen _ = return True
facebook/fbthrift
thrift/lib/hs/Thrift/Transport/HttpClient.hs
apache-2.0
3,626
0
16
879
549
305
244
59
2
{-# LANGUAGE BangPatterns #-} module Main where import Prelude hiding (concat, filter) import Data.Alpino.Model.Conduit import Data.Conduit (Sink, runResourceT, ($=), ($$)) import qualified Data.Conduit.Binary as CB import qualified Data.Conduit.List as CL import System.IO (stdin) import Text.Printf (printf) sumCount :: (Monad m, Fractional a, Integral b) => Sink a m (a, b) sumCount = CL.fold handleCtx (0, 0) where handleCtx (!scoreSum, !ctxs) score = (scoreSum + score, ctxs + 1) main :: IO () main = do (scoreSum, scoreLen) <- runResourceT (CB.sourceHandle stdin $= CB.lines $= bsToTrainingInstance $= groupByKey $= bestScore $$ sumCount) :: IO (Double, Int) putStrLn $ printf "Contexts: %d" scoreLen putStrLn $ printf "Oracle: %.4f" (scoreSum / fromIntegral scoreLen)
danieldk/alpino-tools
utils/model_oracle.hs
apache-2.0
853
0
16
188
283
161
122
20
1
module Spake2 (tests) where import Protolude hiding (group) import Test.Tasty (TestTree) import Test.Tasty.Hspec (testSpec, describe, it, shouldBe, shouldNotBe) import Crypto.Hash (SHA256(..)) import qualified Crypto.Spake2 as Spake2 import qualified Crypto.Spake2.Group as Group import Crypto.Spake2.Groups (Ed25519(..)) tests :: IO TestTree tests = testSpec "Spake2" $ do describe "Asymmetric protocol" $ do it "Produces matching session keys when passwords match" $ do let password = Spake2.makePassword "abc" let idA = Spake2.SideID "side-a" let idB = Spake2.SideID "side-b" let protocolA = defaultAsymmetricProtocol idA idB Spake2.SideA let protocolB = defaultAsymmetricProtocol idA idB Spake2.SideB (Right aSessionKey, Right bSessionKey) <- (protocolA, password) `versus` (protocolB, password) aSessionKey `shouldBe` bSessionKey it "Produces differing session keys when passwords do not match" $ do let password1 = Spake2.makePassword "abc" let password2 = Spake2.makePassword "cba" let idA = Spake2.SideID "" let idB = Spake2.SideID "" let protocolA = defaultAsymmetricProtocol idA idB Spake2.SideA let protocolB = defaultAsymmetricProtocol idA idB Spake2.SideB (Right aSessionKey, Right bSessionKey) <- (protocolA, password1) `versus` (protocolB, password2) aSessionKey `shouldNotBe` bSessionKey describe "Symmetric protocol" $ do it "Produces matching session keys when passwords match" $ do let password = Spake2.makePassword "abc" let protocol = defaultSymmetricProtocol (Spake2.SideID "") (Right sessionKey1, Right sessionKey2) <- (protocol, password) `versus` (protocol, password) sessionKey1 `shouldBe` sessionKey2 it "Produces differing session keys when passwords do not match" $ do let password1 = Spake2.makePassword "abc" let password2 = Spake2.makePassword "cba" let protocol = defaultSymmetricProtocol (Spake2.SideID "") (Right sessionKey1, Right sessionKey2) <- (protocol, password1) `versus` (protocol, password2) sessionKey1 `shouldNotBe` sessionKey2 where defaultAsymmetricProtocol = Spake2.makeAsymmetricProtocol SHA256 group m n m = Group.arbitraryElement group ("M" :: ByteString) n = Group.arbitraryElement group ("N" :: ByteString) defaultSymmetricProtocol = Spake2.makeSymmetricProtocol SHA256 group s s = Group.arbitraryElement group ("symmetric" :: ByteString) group = Ed25519 -- | Run protocol A with password A against protocol B with password B. versus (protocolA, passwordA) (protocolB, passwordB) = do aOutVar <- newEmptyMVar bOutVar <- newEmptyMVar concurrently (Spake2.spake2Exchange protocolA passwordA (putMVar aOutVar) (Right <$> readMVar bOutVar)) (Spake2.spake2Exchange protocolB passwordB (putMVar bOutVar) (Right <$> readMVar aOutVar))
jml/haskell-spake2
tests/Spake2.hs
apache-2.0
2,925
0
20
566
809
415
394
52
1
{-# LANGUAGE RecordWildCards #-} module Grouping(Grouping(..), grouping) where import Data.Maybe import Data.List import System.FilePath data Grouping = Grouping {grpFile :: FilePath ,grpParts :: [(String, String)] -- (part name, part nice name), must be in file order ,grpGroups :: [(String, [String])] -- (group nice name, parts included) } -- Create a sample stream which is suitable for feeding to part_grouping.py grouping :: Grouping -> [String] grouping Grouping{..} = -- name of the file [grpFile] ++ -- do you want to give nice names for the parts ["1"] ++ -- nice names for each part map snd grpParts ++ -- how many groups do you have [show $ length grpGroups] ++ -- groups and their nice names concat [["grp" ++ show i, name] | (i,(name,_)) <- zip [1..] grpGroups] ++ -- name of the whole thing [takeBaseName grpFile] ++ -- indexes of each group map show [1..length grpGroups] ++ -- index of group, number of parts, index of parts concat [ show i : show (length parts) : map (show . indPart) parts | (i,(_,parts)) <- zip [1..] grpGroups , let indPart p = fromJust $ findIndex ((==) p . fst) grpParts ]
ndmitchell/fossilizer
Grouping.hs
apache-2.0
1,231
0
16
309
332
188
144
21
1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TupleSections #-} module Tetris.Coord where import Data.Bool import Data.Eq import Data.Function (($),(.)) import Data.Functor (fmap) import Data.Int import Data.List ((++)) import Data.Maybe import Data.Ord import GHC.Enum (Bounded,minBound,maxBound) import GHC.Num import GHC.Show data Column = Zero | One | Two | Three | Four | Five | Six | Seven | Eight | Nine deriving (Eq,Ord) instance Bounded Column where minBound = Zero maxBound = Nine allColumns :: [Column] allColumns = [Zero,One,Two,Three,Four,Five,Six,Seven,Eight,Nine] data Row = Digit Column | Ten Column | Twenty | TwentyOne deriving (Eq,Ord) instance Bounded Row where minBound = Digit minBound maxBound = TwentyOne allRows :: [Row] allRows = Digit `fmap` allColumns ++ Ten `fmap` allColumns ++ [Twenty,TwentyOne] -- | Safer Enum assuming i is a set smaller than Int class IntSubset i where toInt :: i -> Int fromInt :: Int -> Maybe i fromTo :: i -> i -> [i] fromTo x y = catMaybes $ fmap fromInt [toInt x..toInt y] succ,pred :: i -> Maybe i succ = fromInt . (+ 1) . toInt pred = fromInt . (\x -> x - 1) . toInt instance IntSubset Column where toInt Zero = 0 toInt One = 1 toInt Two = 2 toInt Three = 3 toInt Four = 4 toInt Five = 5 toInt Six = 6 toInt Seven = 7 toInt Eight = 8 toInt Nine = 9 fromInt 0 = Just Zero fromInt 1 = Just One fromInt 2 = Just Two fromInt 3 = Just Three fromInt 4 = Just Four fromInt 5 = Just Five fromInt 6 = Just Six fromInt 7 = Just Seven fromInt 8 = Just Eight fromInt 9 = Just Nine fromInt _ = Nothing instance IntSubset Row where toInt (Digit c) = toInt c toInt (Ten c) = 10 + toInt c toInt Twenty = 20 toInt TwentyOne = 21 fromInt i | i >= 0 && i <= 9 = Digit `fmap` (fromInt i ::Maybe Column) | i >= 10 && i <= 19 = Ten `fmap` (fromInt (i-10)::Maybe Column) | i == 20 = Just Twenty | i == 21 = Just TwentyOne | otherwise = Nothing instance Show Column where show = show . toInt instance Show Row where show = show . toInt type Coord = (Row,Column) succRow,predRow,succColumn,predColumn :: Coord -> Maybe Coord succRow (r,c) = (,c) `fmap` succ r predRow (r,c) = (,c) `fmap` pred r succColumn (r,c) = (r,) `fmap` succ c predColumn (r,c) = (r,) `fmap` pred c
melrief/tetris
src/Tetris/Coord.hs
apache-2.0
2,411
0
11
620
999
547
452
76
1
------------------------------------------------------------------------------- -- Estructuras de Datos. 2º Curso. ETSI Informática. UMA -- -- (completa y sustituye los siguientes datos) -- Titulación: Grado en Ingeniería Informática -- Alumno: GUTIÉRREZ OJEDA, ANTONIO -- Fecha de entrega: DIA | MES | AÑO -- -- Relación de Ejercicios 1. Ejercicios resueltos: .......... -- ------------------------------------------------------------------------------- import Test.QuickCheck --Funciones de apuntes para probar twice :: (Num a) => a -> a twice x = x + x square :: Integer -> Integer square x = x * x pythagoras :: Integer -> Integer -> Integer pythagoras x y = square x + square y maxInteger :: Integer -> Integer -> Integer maxInteger x y = if x >= y then x else y second :: Integer -> Integer -> Integer second x y = y succPred :: Int -> (Int,Int) succPred x = (x+1,x-1) sing :: (Ord a, Num a) => a -> a sing x | x > 0 = 1 | x < 0 = -1 | otherwise = 0 --Ejercicio 1-- --A-- esTerna :: Integer -> Integer -> Integer -> Bool esTerna x y z = if (square x + square y) == square z then True else False --B-- terna :: Integer -> Integer -> (Integer,Integer,Integer) terna x y | x > y = (square x - square y, 2*x*y,square x + square y) | otherwise = error "No cumple las condiciones" --C y D-- p_ternas x y = x>0 && y>0 && x>y ==> esTerna l1 l2 h where (l1,l2,h) = terna x y --Ejercicio 2-- intercambia :: (a,b) -> (b,a) intercambia (x,y) = (y,x) --Ejercicio 3-- --A-- ordena2 :: Ord a => (a,a) -> (a,a) ordena2 (x,y) = if x > y then (y,x) else (x,y) p1_ordena2 x y = enOrden (ordena2 (x,y)) where enOrden (x,y) = x<=y --Main> quickCheck p1_ordena2 --OK, passed 100 tests. p2_ordena2 x y = mismosElementos (x,y) (ordena2 (x,y)) where mismosElementos (x,y) (z,v) = (x==z && y==v) || (x==v && y==z) --Main> quickCheck p2_ordena2 --OK, passed 100 tests. --B-- ordena3 :: Ord a => (a,a,a) -> (a,a,a) ordena3 (x,y,z) | x > y = ordena3 (y,x,z) | y > z = ordena3 (x,z,y) | otherwise = (x,y,z) --C-- p1_ordena3 x y z = enOrden (ordena3 (x,y,z)) where enOrden (x,y,z) = x<=y && y<=z --Main> quickCheck p1_ordena3 --OK, passed 100 tests. p2_ordena3 x y z = mismosElementos (x,y,z) (ordena3 (x,y,z)) where mismosElementos (x,y,z) (a,b,c) = (x==a && y==b && z==c) || (x==b && y==a && z==c) || (x==a && y==c && z==b) || (x==c && y==b && z==a) --Main> quickCheck p1_ordena3 --OK, passed 100 tests. --Ejercicio 4-- --A-- max2 :: Ord a => a -> a -> a max2 x y | x >= y = x | otherwise = y --B-- p1_max2 x y = True ==> max2 x y == x || max2 x y == y p2_max2 x y = True ==> max2 x y >= x || max2 x y >= y p3_max2 x y = x >= y ==> max2 x y == x p4_max2 x y = y >= x ==> max2 x y == y ---OK, passed 100 tests. --Ejercicio 5-- entre :: Ord a => a -> (a,a) -> Bool entre x (a,b) | x >= a && x <= b = True | otherwise = False --Ejercicio 6-- iguales3 :: Eq a => (a,a,a) -> Bool iguales3 (x,y,z) | x==y && x==z = True | otherwise = False --Ejercicio 7-- --A-- type TotalSegundos = Integer type Horas = Integer type Minutos = Integer type Segundos = Integer descomponer :: TotalSegundos -> (Horas,Minutos,Segundos) descomponer x = (horas, minutos, segundos) where (horas,resto) = divMod x 3600 (minutos,segundos) = divMod resto 60 --B-- p_descomponer x = x>=0 ==> h*3600 + m*60 + s == x && entre m (0,59) && entre s (0,59) where (h,m,s) = descomponer x --OK, passed 100 tests. --Ejercicio 8-- unEuro :: Double unEuro = 166.386 --A-- pesetasAEuros :: Double -> Double pesetasAEuros x = x / unEuro --B-- eurosAPesetas :: Double -> Double eurosAPesetas x = x * unEuro --C-- p_inversas x = eurosAPesetas (pesetasAEuros x) == x --Failed! Falsifiable (after 21 tests and 1075 shrinks):5.0e-324 --No se cumple por el redondeo --Ejercicio 9-- infix 4 ~= (~=) :: Double -> Double -> Bool x ~= y = abs (x-y) < epsilon where epsilon = 1/1000 p1_inversas x = eurosAPesetas (pesetasAEuros x) ~= x --OK, passed 100 tests. --Ejercicio 20-- --A-- raices :: (Ord a, Floating a) => a -> a -> a -> (a,a) raices a b c | discriminante >= 0 = ((-b + raizDis)/(2*a),(-b -raizDis)/(2*a) ) | otherwise = error "No existen raices reales" where discriminante = b^2 - 4*a*c raizDis = sqrt discriminante --B-- p2_raíces a b c = (b^2 - 4*a*c >= 0) && (a/=0) ==> esRaíz r1 && esRaíz r2 where (r1,r2) = raices a b c esRaíz r = a*r^2 + b*r + c ~= 0 --OK, passed 100 tests. --Ejercicio 11-- esMultiplo :: (Integral a) => a -> a -> Bool esMultiplo x y | mod x y == 0 = True | otherwise = False --Ejercicio 12-- infixl 1 ==>> (==>>) :: Bool -> Bool -> Bool False ==>> y = True True ==>> y = False --Ejercicio 13-- esBisiesto :: Integer -> Bool esBisiesto x | ((mod x 4 == 0) && (mod x 100 /=0)) || ((mod x 100 ==0) && (mod x 400 == 0)) = True | otherwise = False --Ejercicio 14-- --A-- potencia :: Integer -> Integer -> Integer potencia b n | n == 0 = 1 | n > 0 = b * potencia b (n-1) | otherwise = b --B-- potencia' :: Integer -> Integer -> Integer potencia' b n | n == 0 = 1 | mod n 2 == 0 = potencia' b (div n 2) * potencia' b (div n 2) | otherwise = b * ( potencia b (div (n-1) 2) * potencia b (div (n-1) 2) ) --C-- p_pot b n = n>=0 ==> potencia b n == sol && potencia' b n == sol where sol = b^n --OK, passed 100 tests. --D-- --Ejercicio 15-- factorial :: Integer -> Integer factorial x | x == 0 = 1 | x > 0 = x * factorial (x-1) --Ejercicio 16-- --A-- divideA :: Integer -> Integer -> Bool divideA x y | mod y x == 0 = True | otherwise = False --B-- p1_divideA x y = y/=0 && y `divideA` x ==> div x y * y == x --Gave up! Passed only 91 tests. --C-- p2_divideA x y z = z/=0 && z `divideA` x && z `divideA` y ==> z `divideA` (x+y) == True --Gave up! Passed only 61 tests. --Ejercicio 17-- mediana :: Ord a => (a,a,a,a,a) -> a mediana (x,y,z,t,u) | x > y = mediana (y,x,z,t,u) | y > z = mediana (x,z,y,t,u) | z > t = mediana (x,y,t,z,u) | t > u = mediana (x,y,z,u,t) | otherwise = z
Saeron/haskell
AGO-Rel1-1-17.hs
apache-2.0
6,374
2
13
1,703
2,890
1,534
1,356
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -Wall #-} module CabalBrew.Paths ( cellar ) where import Filesystem.Path.CurrentOS import Prelude hiding (FilePath, concat) cellar :: FilePath cellar = concat ["/usr", "local", "Cellar"]
erochest/cabal-brew
CabalBrew/Paths.hs
apache-2.0
292
0
6
84
53
34
19
8
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QStyleOptionTabV2.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:16 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QStyleOptionTabV2 ( QqStyleOptionTabV2(..) ,QqStyleOptionTabV2_nf(..) ,qStyleOptionTabV2_delete ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqStyleOptionTabV2 x1 where qStyleOptionTabV2 :: x1 -> IO (QStyleOptionTabV2 ()) instance QqStyleOptionTabV2 (()) where qStyleOptionTabV2 () = withQStyleOptionTabV2Result $ qtc_QStyleOptionTabV2 foreign import ccall "qtc_QStyleOptionTabV2" qtc_QStyleOptionTabV2 :: IO (Ptr (TQStyleOptionTabV2 ())) instance QqStyleOptionTabV2 ((QStyleOptionTab t1)) where qStyleOptionTabV2 (x1) = withQStyleOptionTabV2Result $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionTabV21 cobj_x1 foreign import ccall "qtc_QStyleOptionTabV21" qtc_QStyleOptionTabV21 :: Ptr (TQStyleOptionTab t1) -> IO (Ptr (TQStyleOptionTabV2 ())) instance QqStyleOptionTabV2 ((QStyleOptionTabV2 t1)) where qStyleOptionTabV2 (x1) = withQStyleOptionTabV2Result $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionTabV22 cobj_x1 foreign import ccall "qtc_QStyleOptionTabV22" qtc_QStyleOptionTabV22 :: Ptr (TQStyleOptionTabV2 t1) -> IO (Ptr (TQStyleOptionTabV2 ())) class QqStyleOptionTabV2_nf x1 where qStyleOptionTabV2_nf :: x1 -> IO (QStyleOptionTabV2 ()) instance QqStyleOptionTabV2_nf (()) where qStyleOptionTabV2_nf () = withObjectRefResult $ qtc_QStyleOptionTabV2 instance QqStyleOptionTabV2_nf ((QStyleOptionTab t1)) where qStyleOptionTabV2_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionTabV21 cobj_x1 instance QqStyleOptionTabV2_nf ((QStyleOptionTabV2 t1)) where qStyleOptionTabV2_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QStyleOptionTabV22 cobj_x1 instance QqiconSize (QStyleOptionTabV2 a) (()) where qiconSize x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionTabV2_iconSize cobj_x0 foreign import ccall "qtc_QStyleOptionTabV2_iconSize" qtc_QStyleOptionTabV2_iconSize :: Ptr (TQStyleOptionTabV2 a) -> IO (Ptr (TQSize ())) instance QiconSize (QStyleOptionTabV2 a) (()) where iconSize x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionTabV2_iconSize_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QStyleOptionTabV2_iconSize_qth" qtc_QStyleOptionTabV2_iconSize_qth :: Ptr (TQStyleOptionTabV2 a) -> Ptr CInt -> Ptr CInt -> IO () qStyleOptionTabV2_delete :: QStyleOptionTabV2 a -> IO () qStyleOptionTabV2_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QStyleOptionTabV2_delete cobj_x0 foreign import ccall "qtc_QStyleOptionTabV2_delete" qtc_QStyleOptionTabV2_delete :: Ptr (TQStyleOptionTabV2 a) -> IO ()
keera-studios/hsQt
Qtc/Gui/QStyleOptionTabV2.hs
bsd-2-clause
3,322
0
12
474
774
405
369
-1
-1
module Context(module Context.Types ,module Context.Language) where import Context.Types import Context.Language
lih/Alpha
src/Context.hs
bsd-2-clause
128
0
5
25
28
18
10
4
0
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, OverloadedStrings #-} module Web.PathPieces ( PathPiece (..) , PathMultiPiece (..) -- * Deprecated , toSinglePiece , toMultiPiece , fromSinglePiece , fromMultiPiece ) where import Data.Int (Int8, Int16, Int32, Int64) import Data.Word (Word, Word8, Word16, Word32, Word64) import qualified Data.Text as S import qualified Data.Text.Lazy as L import qualified Data.Text.Read import Data.Time (Day) import Control.Exception (assert) class PathPiece s where fromPathPiece :: S.Text -> Maybe s toPathPiece :: s -> S.Text instance PathPiece String where fromPathPiece = Just . S.unpack toPathPiece = S.pack instance PathPiece S.Text where fromPathPiece = Just toPathPiece = id instance PathPiece L.Text where fromPathPiece = Just . L.fromChunks . return toPathPiece = S.concat . L.toChunks parseIntegral :: (Integral a, Bounded a, Ord a) => S.Text -> Maybe a parseIntegral s = n where n = case Data.Text.Read.signed Data.Text.Read.decimal s of Right (i, "") | i <= top && i >= bot -> Just (fromInteger i) _ -> Nothing Just witness = n top = toInteger (maxBound `asTypeOf` witness) bot = toInteger (minBound `asTypeOf` witness) instance PathPiece Integer where fromPathPiece s = case Data.Text.Read.signed Data.Text.Read.decimal s of Right (i, "") -> Just i _ -> Nothing toPathPiece = S.pack . show instance PathPiece Int where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Int8 where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Int16 where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Int32 where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Int64 where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Word where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Word8 where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Word16 where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Word32 where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Word64 where fromPathPiece = parseIntegral toPathPiece = S.pack . show instance PathPiece Bool where fromPathPiece t = case filter (null . snd) $ reads $ S.unpack t of (a, s):_ -> assert (null s) (Just a) _ -> Nothing toPathPiece = S.pack . show instance PathPiece Day where fromPathPiece t = case reads $ S.unpack t of [(a,"")] -> Just a _ -> Nothing toPathPiece = S.pack . show instance (PathPiece a) => PathPiece (Maybe a) where fromPathPiece s = case S.stripPrefix "Just " s of Just r -> Just `fmap` fromPathPiece r _ -> case s of "Nothing" -> Just Nothing _ -> Nothing toPathPiece m = case m of Just s -> "Just " `S.append` toPathPiece s _ -> "Nothing" class PathMultiPiece s where fromPathMultiPiece :: [S.Text] -> Maybe s toPathMultiPiece :: s -> [S.Text] instance PathPiece a => PathMultiPiece [a] where fromPathMultiPiece = mapM fromPathPiece toPathMultiPiece = map toPathPiece {-# DEPRECATED toSinglePiece "Use toPathPiece instead of toSinglePiece" #-} toSinglePiece :: PathPiece p => p -> S.Text toSinglePiece = toPathPiece {-# DEPRECATED fromSinglePiece "Use fromPathPiece instead of fromSinglePiece" #-} fromSinglePiece :: PathPiece p => S.Text -> Maybe p fromSinglePiece = fromPathPiece {-# DEPRECATED toMultiPiece "Use toPathMultiPiece instead of toMultiPiece" #-} toMultiPiece :: PathMultiPiece ps => ps -> [S.Text] toMultiPiece = toPathMultiPiece {-# DEPRECATED fromMultiPiece "Use fromPathMultiPiece instead of fromMultiPiece" #-} fromMultiPiece :: PathMultiPiece ps => [S.Text] -> Maybe ps fromMultiPiece = fromPathMultiPiece
MaxGabriel/path-pieces
Web/PathPieces.hs
bsd-2-clause
4,122
0
15
954
1,167
629
538
110
2
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE TemplateHaskell #-} -------------------------------------------------------------------- -- | -- Copyright : (c) McGraw Hill Financial 2013, 2014 -- License : BSD2 -- Maintainer: Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability: non-portable -- -- Data structures representing parsed modules and their components, -- aside from those already in 'Ermine.Syntax.Term' et al. -------------------------------------------------------------------- module Ermine.Syntax.Module ( Privacy(..) , _Private , _Public , Explicit(Explicit) , HasExplicit(..) , ImportsInScope(..) , AsImportsInScope(..) , importScopeExplicits , Import(Import) , ImportResolution(..) , HasImportResolution(..) , ResolvedTerms(..) , ResolvedTypes(..) , HasImport(..) , importScope' , FixityDeclLevel(..) , FixityDecl(FixityDecl) , HasFixityDecl(..) , Statement(..) , AsStatement(..) , Module(Module) , HasModule(..) , HasFixities(..) , ModuleHead(ModuleHead) , HasModuleHead(..) ) where import Control.Applicative ((<$>), (<*>)) import Control.Lens import Data.Bytes.Serial import Data.Bifoldable import Data.Binary import Data.Bitraversable import Data.Foldable (Foldable) import Data.Map (Map) import Data.Serialize import Data.Data hiding (DataType) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Data.HashSet (HashSet) import qualified Data.HashSet as HS import Data.Ix import Data.Monoid (Monoid(..)) import Data.Text import Data.Void import Ermine.Builtin.Term (PreBody()) import Ermine.Syntax.Class import Ermine.Syntax.Data import Ermine.Syntax.Global as Global import Ermine.Syntax.ModuleName import Ermine.Syntax.Term import Ermine.Syntax.Type import GHC.Generics hiding (moduleName) -- | Whether a name is visible to importers of a module, or a module -- is reexported from its importer. data Privacy = Private | Public deriving (Eq,Ord,Show,Read,Enum,Bounded,Ix,Generic,Typeable,Data) makePrisms ''Privacy instance Serial Privacy instance Binary Privacy where put = serialize get = deserialize instance Serialize Privacy where put = serialize get = deserialize -- | An explicitly-listed name in an import/export statement. data Explicit g = Explicit { _explicitGlobal :: g -- ^ the full original name , _explicitIsType :: Bool -- ^ whether to import a type, not term , _explicitLocal :: Maybe String -- ^ the 'as' renaming, if any } deriving (Eq,Ord,Show,Read,Functor,Foldable,Traversable,Typeable) makeClassy ''Explicit data ImportsInScope g = Using [Explicit g] -- ^ list of names requested to import | Hiding [Explicit g] -- ^ list of names requested to hide (hiding [] == import everything) deriving (Eq,Ord,Show,Read,Functor,Foldable,Traversable,Typeable) makeClassyPrisms ''ImportsInScope importScopeExplicits :: Lens (ImportsInScope g) (ImportsInScope h) [Explicit g] [Explicit h] importScopeExplicits f (Using ex) = Using <$> f ex importScopeExplicits f (Hiding ex) = Hiding <$> f ex -- | An import/export statement. data Import g = Import -- TODO: add a location { _importPrivacy :: Privacy -- ^ whether to reexport the symbols , _importModule :: ModuleName -- ^ what module to import , _importAs :: Maybe String -- ^ the 'as' qualifier suffix , _importScope :: ImportsInScope g -- ^ what imports are brought into scope } deriving (Eq,Ord,Show,Read,Functor,Foldable,Traversable,Typeable) makeClassy ''Import -- | A type-changing alternative to the classy lenses. importScope' :: Lens (Import g) (Import h) (ImportsInScope g) (ImportsInScope h) importScope' f (imp@Import {_importScope = sc}) = f sc <&> \sc' -> imp {_importScope = sc'} type GlobalMap = HashMap Text (HashSet Global) gmUnion :: GlobalMap -> GlobalMap -> GlobalMap gmUnion = HM.unionWith HS.union newtype ResolvedTerms = ResolvedTerms GlobalMap deriving (Eq, Show) newtype ResolvedTypes = ResolvedTypes GlobalMap deriving (Eq, Show) data ImportResolution = ImportResolution {_resolvedImports :: [Import Global] ,_resolvedTerms :: ResolvedTerms ,_resolvedTypes :: ResolvedTypes } deriving (Eq, Show) makeClassy ''ImportResolution instance Monoid ResolvedTerms where mempty = ResolvedTerms HM.empty (ResolvedTerms m1) `mappend` (ResolvedTerms m2) = ResolvedTerms $ m1 `gmUnion` m2 instance Monoid ResolvedTypes where mempty = ResolvedTypes HM.empty (ResolvedTypes m1) `mappend` (ResolvedTypes m2) = ResolvedTypes $ m1 `gmUnion` m2 instance Monoid ImportResolution where mempty = ImportResolution mempty mempty mempty (ImportResolution is tms typs) `mappend` (ImportResolution is' tms' typs') = ImportResolution (is++is') (tms `mappend` tms') (typs `mappend` typs') -- | Whether the fixity declaration is a type or term level operator. data FixityDeclLevel = TypeLevel | TermLevel deriving (Show, Eq, Data, Typeable) -- | A fixity declaration statement. data FixityDecl = FixityDecl { _fixityDeclType :: FixityDeclLevel -- ^ whether these are type or term operators , _fixityDeclFixity :: Global.Fixity -- ^ direction & precedence , _fixityDeclNames :: [Text] -- ^ the names to assign fixities to } deriving (Show, Eq, Data, Typeable) makeClassy ''FixityDecl {- data InstanceDecl = InstanceDecl { _instanceDeclClass :: Class , _instanceDeclDefaults :: ClassBinding } deriving (Show, Typeable) -} -- | Combine top-level statements into a single type. data Statement t a = FixityDeclStmt FixityDecl | DataTypeStmt Privacy (DataType () t) | SigStmt Privacy [a] (Annot Void t) | TermStmt Privacy a [PreBody (Annot Void t) a] | ClassStmt a (Class () t) deriving (Show, Eq) makeClassyPrisms ''Statement data Module = Module { mn :: ModuleName , _moduleImports :: ImportResolution , _moduleFixities :: [FixityDecl] , _moduleData :: [(Privacy, DataType () Text)] -- TODO: support type not just data , _moduleBindings :: [(Privacy, Text, Binding (Annot Void Text) Text)] , _moduleClasses :: Map Text (Class () Text) -- , _moduleInstances :: Map Head () } deriving (Show, Typeable) instance HasModuleName Module where moduleName f m = f (mn m) <&> \mn' -> m { mn = mn' } class HasModule t where module_ :: Lens' t Module moduleImports :: Lens' t ImportResolution moduleFixities :: Lens' t [FixityDecl] moduleData :: Lens' t [(Privacy, DataType () Text)] moduleBindings :: Lens' t [(Privacy, Text, Binding (Annot Void Text) Text)] moduleClasses :: Lens' t (Map Text (Class () Text)) moduleImports = module_.moduleImports moduleFixities = module_.moduleFixities moduleData = module_.moduleData moduleBindings = module_.moduleBindings moduleClasses = module_.moduleClasses makeLensesWith ?? ''Module $ classyRules & createClass .~ False & lensClass .~ \_ -> Just (''HasModule, 'module_) class HasFixities a where fixityDecls :: Lens' a [FixityDecl] instance (a ~ FixityDecl) => HasFixities [a] where fixityDecls = id instance HasFixities Module where fixityDecls = moduleFixities -- | The part of the module we can parse without knowing what's in the -- imported/exported modules, and the remainder text. data ModuleHead imp txt = ModuleHead { _moduleHeadName :: ModuleName , _moduleHeadImports :: [imp] , _moduleHeadText :: txt } deriving (Eq, Ord, Show, Read, Data, Functor, Foldable, Traversable, Generic, Typeable) makeClassy ''ModuleHead instance HasModuleName (ModuleHead imp txt) where moduleName = moduleHeadName instance Bifunctor ModuleHead where bimap = bimapDefault instance Bifoldable ModuleHead where bifoldMap = bifoldMapDefault instance Bitraversable ModuleHead where bitraverse f g (ModuleHead n im tx) = ModuleHead n <$> traverse f im <*> g tx
PipocaQuemada/ermine
src/Ermine/Syntax/Module.hs
bsd-2-clause
8,219
0
13
1,467
2,054
1,173
881
186
1
{-# LANGUAGE Rank2Types #-} {-# LANGUAGE OverloadedStrings #-} module HTTPUtils ( sendHTTPRequest , methodGet , methodPost ) where import Aliases import MonadImports import qualified Control.Exception as E import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Internal as BS import qualified Network (withSocketsDo) import qualified Network.CGI (formDecode) import qualified Network.HTTP.Conduit as HTTP type RequestModifier = HTTP.Request -> HTTP.Request methodPost :: RequestModifier methodPost r = r { HTTP.method = "POST" } methodGet :: RequestModifier methodGet r = r { HTTP.method = "GET" } sendHTTPRequest :: String -> [(BS.ByteString, BS.ByteString)] -> RequestModifier -> RequestModifier -> EIO (HTTP.Response L.ByteString) sendHTTPRequest url params addHeaders specifyMethod = bimapEitherT displayException' id . EitherT . liftIO . E.try . Network.withSocketsDo $ do req <- (addHeaders . specifyMethod . HTTP.urlEncodedBody params) <$> HTTP.parseUrl url HTTP.newManager HTTP.tlsManagerSettings >>= HTTP.httpLbs req where displayException' :: E.SomeException -> String displayException' = E.displayException
bgwines/hueue
lib/HTTPUtils.hs
bsd-3-clause
1,267
0
13
232
307
176
131
37
1
{------------------------------------------------------------------------------ Control.Monad.Operational Example: Koen Claessen's Poor Man's Concurrency Monad http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.39.8039 ------------------------------------------------------------------------------} {-# LANGUAGE GADTs, Rank2Types #-} module PoorMansConcurrency where import Control.Monad import Control.Monad.Operational import Control.Monad.Trans hiding (lift) {------------------------------------------------------------------------------ A concurrency monad runs several processes in parallel and supports two primitive operations fork -- fork a new process stop -- halt the current one We want this to be a monad transformer, so we also need a function lift This time, however, we cannot use the monad transformer version ProgramT because this will leave no room for interleaving different computations of the base monad. ------------------------------------------------------------------------------} data ProcessI m a where Lift :: m a -> ProcessI m a Stop :: ProcessI m a Fork :: Process m () -> ProcessI m () type Process m a = Program (ProcessI m) a stop = singleton Stop fork = singleton . Fork lift = singleton . Lift -- interpreter runProcess :: Monad m => Process m a -> m () runProcess m = schedule [m] where schedule :: Monad m => [Process m a] -> m () schedule [] = return () schedule (x:xs) = run (view x) xs run :: Monad m => ProgramView (ProcessI m) a -> [Process m a] -> m () run (Return _) xs = return () -- process finished run (Lift m :>>= k) xs = m >>= \a -> -- switch process schedule (xs ++ [k a]) run (Stop :>>= k) xs = schedule xs -- process halts run (Fork p :>>= k) xs = schedule (xs ++ [x2,x1]) -- fork new process where x1 = k (); x2 = p >>= k -- example -- > runProcess example -- warning: runs indefinitely example :: Process IO () example = do write "Start!" fork (loop "fish") loop "cat" write = lift . putStr loop s = write s >> loop s
HeinrichApfelmus/operational
doc/examples/PoorMansConcurrency.hs
bsd-3-clause
2,233
0
13
559
506
262
244
32
5
-- | An implementation of Knuth-Bendix ordering. {-# LANGUAGE PatternGuards, BangPatterns #-} module Twee.KBO(lessEq, lessIn, lessEqSkolem, Sized(..), Weighted(..)) where import Twee.Base hiding (lessEq, lessIn, lessEqSkolem) import Twee.Equation import Twee.Constraints hiding (lessEq, lessIn, lessEqSkolem) import qualified Data.Map.Strict as Map import Data.Map.Strict(Map) import Data.Maybe import Control.Monad import Twee.Utils lessEqSkolem :: (Function f, Sized f, Weighted f) => Term f -> Term f -> Bool lessEqSkolem !t !u | m < n = True | m > n = False where m = size t n = size u lessEqSkolem (App x Empty) _ | x == minimal = True lessEqSkolem _ (App x Empty) | x == minimal = False lessEqSkolem (Var x) (Var y) = x <= y lessEqSkolem (Var _) _ = True lessEqSkolem _ (Var _) = False lessEqSkolem (App (F _ f) ts) (App (F _ g) us) = case compare f g of LT -> True GT -> False EQ -> let loop Empty Empty = True loop (Cons t ts) (Cons u us) | t == u = loop ts us | otherwise = lessEqSkolem t u in loop ts us -- | Check if one term is less than another in KBO. {-# SCC lessEq #-} lessEq :: (Function f, Sized f, Weighted f) => Term f -> Term f -> Bool lessEq (App f Empty) _ | f == minimal = True lessEq (Var x) (Var y) | x == y = True lessEq _ (Var _) = False lessEq (Var x) t = x `elem` vars t lessEq t@(App f ts) u@(App g us) = (st < su || (st == su && f << g) || (st == su && f == g && lexLess ts us)) && xs `lessVars` ys where lexLess Empty Empty = True lexLess (Cons t ts) (Cons u us) | t == u = lexLess ts us | otherwise = lessEq t u && case unify t u of Nothing -> True Just sub | not (allSubst (\_ (Cons t Empty) -> isMinimal t) sub) -> error "weird term inequality" | otherwise -> lexLess (subst sub ts) (subst sub us) lexLess _ _ = error "incorrect function arity" xs = weightedVars t ys = weightedVars u st = size t su = size u [] `lessVars` _ = True ((x,k1):xs) `lessVars` ((y,k2):ys) | x == y = k1 <= k2 && xs `lessVars` ys | x > y = ((x,k1):xs) `lessVars` ys _ `lessVars` _ = False -- | Check if one term is less than another in a given model. -- See "notes/kbo under assumptions" for how this works. {-# SCC lessIn #-} lessIn :: (Function f, Sized f, Weighted f) => Model f -> Term f -> Term f -> Maybe Strictness lessIn model t u = case sizeLessIn model t u of Nothing -> Nothing Just Strict -> Just Strict Just Nonstrict -> lexLessIn model t u sizeLessIn :: (Function f, Sized f, Weighted f) => Model f -> Term f -> Term f -> Maybe Strictness sizeLessIn model t u = case minimumIn model m of Just l | l > -k -> Just Strict | l == -k -> Just Nonstrict _ -> Nothing where (k, m) = add 1 u (add (-1) t (0, Map.empty)) add a (App f ts) (k, m) = foldr (add (a * argWeight f)) (k + a * size f, m) (unpack ts) add a (Var x) (k, m) = (k, Map.insertWith (+) x a m) minimumIn :: (Function f, Sized f) => Model f -> Map Var Integer -> Maybe Integer minimumIn model t = liftM2 (+) (fmap sum (mapM minGroup (varGroups model))) (fmap sum (mapM minOrphan (Map.toList t))) where minGroup (lo, xs, mhi) | all (>= 0) sums = Just (sum coeffs * size lo) | otherwise = case mhi of Nothing -> Nothing Just hi -> let coeff = negate (minimum coeffs) in Just $ sum coeffs * size lo + coeff * (size lo - size hi) where coeffs = map (\x -> Map.findWithDefault 0 x t) xs sums = scanr1 (+) coeffs minOrphan (x, k) | varInModel model x = Just 0 | k < 0 = Nothing | otherwise = Just k lexLessIn :: (Function f, Sized f, Weighted f) => Model f -> Term f -> Term f -> Maybe Strictness lexLessIn _ t u | t == u = Just Nonstrict lexLessIn cond t u | Just a <- fromTerm t, Just b <- fromTerm u, Just x <- lessEqInModel cond a b = Just x | Just a <- fromTerm t, any isJust [ lessEqInModel cond a b | v <- properSubterms u, Just b <- [fromTerm v]] = Just Strict lexLessIn cond (App f ts) (App g us) | f == g = loop ts us | f << g = Just Strict | otherwise = Nothing where loop Empty Empty = Just Nonstrict loop (Cons t ts) (Cons u us) | t == u = loop ts us | otherwise = case lessIn cond t u of Nothing -> Nothing Just Strict -> Just Strict Just Nonstrict -> let Just sub = unify t u in loop (subst sub ts) (subst sub us) loop _ _ = error "incorrect function arity" lexLessIn _ t _ | isMinimal t = Just Nonstrict lexLessIn _ _ _ = Nothing class Sized a where -- | Compute the size. size :: a -> Integer class Weighted f where argWeight :: f -> Integer instance (Weighted f, Labelled f) => Weighted (Fun f) where argWeight = argWeight . fun_value weightedVars :: (Weighted f, Labelled f) => Term f -> [(Var, Integer)] weightedVars t = collate sum (loop 1 t) where loop k (Var x) = [(x, k)] loop k (App f ts) = concatMap (loop (k * argWeight f)) (unpack ts) instance (Labelled f, Sized f) => Sized (Fun f) where size = size . fun_value instance (Labelled f, Sized f, Weighted f) => Sized (TermList f) where size = aux 0 where aux n Empty = n aux n (Cons (App f t) u) = aux (n + size f + argWeight f * size t) u aux n (Cons (Var _) t) = aux (n+1) t instance (Labelled f, Sized f, Weighted f) => Sized (Term f) where size = size . singleton instance (Labelled f, Sized f, Weighted f) => Sized (Equation f) where size (x :=: y) = size x + size y
nick8325/kbc
src/Twee/KBO.hs
bsd-3-clause
5,771
0
21
1,723
2,711
1,343
1,368
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module NLP.Albemarle.Test.Fixture where import Prelude hiding (words, lines, readFile) import Test.Hspec import Data.List hiding (words, lines) import Data.Text (Text, words, lines) import Data.Text.IO (readFile) import qualified Data.IntMap.Strict as IntMap import qualified NLP.Albemarle.Tokens as Tokens import qualified NLP.Albemarle.Dict as Dict --import qualified NLP.Albemarle.GloVe as GloVe import Lens.Micro.TH data Fixture = Fixture { _docs :: [[Text]], _dict :: Dict.Dict --_glove :: IntMap GloVe.ContextVector } makeLenses ''Fixture generate :: IO Fixture generate = do docs <- (fmap.fmap) Tokens.wordTokenize $ fmap lines $ readFile "kjv.lines.txt" return $ Fixture { _docs = docs, _dict = Dict.dictifyDefault docs }
SeanTater/albemarle
test/NLP/Albemarle/Test/Fixture.hs
bsd-3-clause
829
0
12
132
213
130
83
24
1
module Ebitor.Language ( parseKeyEvents ) where import Control.Monad import Data.Char import Data.Foldable (foldr', foldr1) import Data.List (nub) import Data.Maybe import Text.Parsec import Text.Parsec.Char import Text.Parsec.Text import qualified Data.Text as T import Ebitor.Events ichar :: Char -> Parser Char ichar c = char (toLower c) <|> char (toUpper c) istring :: String -> Parser String istring s = liftM reverse $ foldr' collect (return "") $ reverse $ map ichar s where collect a b = do { s <- b ; liftM (:s) a } tryChoice [] = choice [] tryChoice (x:[]) = choice [x] tryChoice ls = choice (map try $ init ls) <|> last ls choiceIstrings = tryChoice . map istring bracketed :: Parser a -> Parser a bracketed = between (char '<') (char '>') escape :: Parser Key escape = do choiceIstrings ["Escape", "Esc"] return KEsc enter :: Parser Key enter = do choiceIstrings ["Enter", "Return", "CR"] return KEnter backspace :: Parser Key backspace = do choiceIstrings ["Backspace", "BS"] return KBS up :: Parser Key up = do istring "Up" return KUp down :: Parser Key down = do istring "Down" return KDown left :: Parser Key left = do istring "Left" return KLeft right :: Parser Key right = do istring "Right" return KRight upLeft :: Parser Key upLeft = do istring "UpLeft" return KUpLeft upRight :: Parser Key upRight = do istring "UpRight" return KUpRight downLeft :: Parser Key downLeft = do istring "DownLeft" return KDownLeft downRight :: Parser Key downRight = do istring "DownRight" return KDownRight center :: Parser Key center = do istring "Center" return KCenter function :: Parser Key function = do ichar 'F' d <- many1 digit return $ KFun $ read d backTab :: Parser Key backTab = do istring "BackTab" return KBackTab home :: Parser Key home = do istring "Home" return KHome pageUp :: Parser Key pageUp = do istring "PageUp" return KPageUp pageDown :: Parser Key pageDown = do istring "PageDown" return KPageDown delete :: Parser Key delete = do choiceIstrings ["Delete", "Del"] return KDel begin :: Parser Key begin = do istring "Begin" return KBegin end :: Parser Key end = do istring "End" return KEnd prtScr :: Parser Key prtScr = do istring "PrtScr" return KPrtScr pause :: Parser Key pause = do istring "Pause" return KPause insert :: Parser Key insert = do choiceIstrings ["Insert", "Ins"] return KIns menu :: Parser Key menu = do istring "Menu" return KMenu charKey :: Parser Key charKey = do c <- try (escaped $ char '<') <|> try (escaped $ char '\\') <|> noneOf "<" return $ KChar c where escaped c = do { char '\\' ; c } specialKey :: Parser Key specialKey = tryChoice [ escape, enter, backspace, up, down, left, right, upLeft , upRight, downLeft, downRight, center, function, home , pageUp, pageDown, delete, begin, end, prtScr, pause , insert, menu ] shift :: Parser Modifier shift = do choiceIstrings ["Shift", "S"] return MShift control :: Parser Modifier control = do choiceIstrings ["Control", "Ctrl", "C"] return MCtrl meta :: Parser Modifier meta = do choiceIstrings ["Meta", "M"] return MMeta alt :: Parser Modifier alt = do choiceIstrings ["Alt", "A"] return MAlt modifier :: Parser Modifier modifier = tryChoice [shift, control, meta, alt] modifiedKeyCombo :: Parser Event modifiedKeyCombo = do mods <- many1 $ try modifier' key <- tryChoice [specialKey, charKey] return $ EvKey key $ nub mods where modifier' = do { m <- modifier ; char '-' ; return m } unmodifiedKeyCombo :: Parser Event unmodifiedKeyCombo = do key <- tryChoice [bracketed specialKey, charKey] return $ EvKey key [] keyCombo :: Parser Event keyCombo = tryChoice [bracketed modifiedKeyCombo, unmodifiedKeyCombo] parseKeyEvents :: T.Text -> Either ParseError [Event] parseKeyEvents = parse (many1 keyCombo) "Key events"
benekastah/ebitor
src/Ebitor/Language.hs
bsd-3-clause
4,112
0
13
1,012
1,500
733
767
162
1
{-# LANGUAGE BangPatterns, ExplicitForAll, TypeOperators, MagicHash #-} {-# OPTIONS -fno-warn-orphans #-} module Data.Array.Repa.Operators.Reduction ( foldS, foldP, reduceLTS , foldAllS, foldAllP , sumS, sumP , sumAllS, sumAllP , equalsS, equalsP) where import Data.Array.Repa.Base import Data.Array.Repa.Index import Data.Array.Repa.Eval import Data.Array.Repa.Repr.Unboxed import Data.Array.Repa.Operators.Mapping as R import Data.Array.Repa.Shape as S import qualified Data.Vector.Unboxed as V import qualified Data.Vector.Unboxed.Mutable as M import Prelude hiding (sum) import qualified Data.Array.Repa.Eval.Reduction as E import Data.Array.Repa.Repr.LazyTreeSplitting import qualified Data.Rope as RP import Control.Monad.Par import System.IO.Unsafe import GHC.Exts import Control.DeepSeq -- fold ---------------------------------------------------------------------- -- | Sequential reduction of the innermost dimension of an arbitrary rank array. -- -- Combine this with `transpose` to fold any other dimension. foldS :: (Shape sh, Source r a, Elt a, Unbox a) => (a -> a -> a) -> a -> Array r (sh :. Int) a -> Array U sh a foldS f z arr = arr `deepSeqArray` let sh@(sz :. n') = extent arr !(I# n) = n' in unsafePerformIO $ do mvec <- M.unsafeNew (S.size sz) E.foldS mvec (\ix -> arr `unsafeIndex` fromIndex sh (I# ix)) f z n !vec <- V.unsafeFreeze mvec now $ fromUnboxed sz vec {-# INLINE [1] foldS #-} -- | Parallel reduction of the innermost dimension of an arbitray rank array. -- -- The first argument needs to be an associative sequential operator. -- The starting element must be neutral with respect to the operator, for -- example @0@ is neutral with respect to @(+)@ as @0 + a = a@. -- These restrictions are required to support parallel evaluation, as the -- starting element may be used multiple times depending on the number of threads. foldP :: (Shape sh, Source r a, Elt a, Unbox a, Monad m) => (a -> a -> a) -> a -> Array r (sh :. Int) a -> m (Array U sh a) foldP f z arr = arr `deepSeqArray` let sh@(sz :. n) = extent arr in case rank sh of -- specialise rank-1 arrays, else one thread does all the work. -- We can't match against the shape constructor, -- otherwise type error: (sz ~ Z) -- 1 -> do x <- foldAllP f z arr now $ fromUnboxed sz $ V.singleton x _ -> now $ unsafePerformIO $ do mvec <- M.unsafeNew (S.size sz) E.foldP mvec (\ix -> arr `unsafeIndex` fromIndex sh ix) f z n !vec <- V.unsafeFreeze mvec now $ fromUnboxed sz vec {-# INLINE [1] foldP #-} -- foldAll -------------------------------------------------------------------- -- | Sequential reduction of an array of arbitrary rank to a single scalar value. -- foldAllS :: (Shape sh, Source r a, Elt a, Unbox a) => (a -> a -> a) -> a -> Array r sh a -> a foldAllS f z arr = arr `deepSeqArray` let !ex = extent arr !(I# n) = size ex in E.foldAllS (\ix -> arr `unsafeIndex` fromIndex ex (I# ix)) f z n {-# INLINE [1] foldAllS #-} -- | Parallel reduction of an array of arbitrary rank to a single scalar value. -- -- The first argument needs to be an associative sequential operator. -- The starting element must be neutral with respect to the operator, -- for example @0@ is neutral with respect to @(+)@ as @0 + a = a@. -- These restrictions are required to support parallel evaluation, as the -- starting element may be used multiple times depending on the number of threads. foldAllP :: (Shape sh, Source r a, Elt a, Unbox a, Monad m) => (a -> a -> a) -> a -> Array r sh a -> m a foldAllP f z arr = arr `deepSeqArray` let sh = extent arr n = size sh in return $ unsafePerformIO $ E.foldAllP (\ix -> arr `unsafeIndex` fromIndex sh ix) f z n {-# INLINE [1] foldAllP #-} -- sum ------------------------------------------------------------------------ -- | Sequential sum the innermost dimension of an array. sumS :: (Shape sh, Source r a, Num a, Elt a, Unbox a) => Array r (sh :. Int) a -> Array U sh a sumS = foldS (+) 0 {-# INLINE [3] sumS #-} -- | Parallel sum the innermost dimension of an array. sumP :: (Shape sh, Source r a, Num a, Elt a, Unbox a, Monad m) => Array r (sh :. Int) a -> m (Array U sh a) sumP = foldP (+) 0 {-# INLINE [3] sumP #-} -- sumAll --------------------------------------------------------------------- -- | Sequential sum of all the elements of an array. sumAllS :: (Shape sh, Source r a, Elt a, Unbox a, Num a) => Array r sh a -> a sumAllS = foldAllS (+) 0 {-# INLINE [3] sumAllS #-} -- | Parallel sum all the elements of an array. sumAllP :: (Shape sh, Source r a, Elt a, Unbox a, Num a, Monad m) => Array r sh a -> m a sumAllP = foldAllP (+) 0 {-# INLINE [3] sumAllP #-} -- Equality ------------------------------------------------------------------ instance (Shape sh, Eq sh, Source r a, Eq a) => Eq (Array r sh a) where (==) arr1 arr2 = extent arr1 == extent arr2 && (foldAllS (&&) True (R.zipWith (==) arr1 arr2)) -- | Check whether two arrays have the same shape and contain equal elements, -- in parallel. equalsP :: (Shape sh, Eq sh, Source r1 a, Source r2 a, Eq a, Monad m) => Array r1 sh a -> Array r2 sh a -> m Bool equalsP arr1 arr2 = do same <- foldAllP (&&) True (R.zipWith (==) arr1 arr2) return $ (extent arr1 == extent arr2) && same -- | Check whether two arrays have the same shape and contain equal elements, -- sequentially. equalsS :: (Shape sh, Eq sh, Source r1 a, Source r2 a, Eq a) => Array r1 sh a -> Array r2 sh a -> Bool equalsS arr1 arr2 = extent arr1 == extent arr2 && (foldAllS (&&) True (R.zipWith (==) arr1 arr2)) reduceLTS :: (Shape sh, Source L a, NFData a) => (a -> a -> a) -> a -> Array L sh a -> a reduceLTS f z rope = runPar $ RP.reduceLTS f z (toRope rope)
kairne/repa-lts
Data/Array/Repa/Operators/Reduction.hs
bsd-3-clause
6,302
79
22
1,701
1,789
964
825
-1
-1
module Errors where import Control.Monad (when) import System.Exit (exitWith, ExitCode(..)) exitWithError :: String -> IO a exitWithError s = putStrLn s >> exitWith (ExitFailure 1) -- -- Adds a new line on the end of the error message. -- exitWithErrorIf :: Bool -> String -> IO () exitWithErrorIf condition reason = when condition $ do putStrLn reason exitWith (ExitFailure 1) -- A version that doesn't add a trailing new line exitWithErrorIf' :: Bool -> String -> IO () exitWithErrorIf' condition reason = when condition $ do putStr reason exitWith (ExitFailure 1) exitWithErrorIfM :: IO Bool -> String -> IO () exitWithErrorIfM ioCond reason = ioCond >>= \b -> exitWithErrorIf b reason
sseefried/task
src/Errors.hs
bsd-3-clause
704
0
10
126
222
111
111
15
1
module HasOffers.API.Brand.Application where import Data.Text import GHC.Generics import Data.Aeson import Control.Applicative import Network.HTTP.Client import qualified Data.ByteString.Char8 as BS import HasOffers.API.Common -------------------------------------------------------------------------------- addAffiliateTier params = Call "Application" "addAffiliateTier" "POST" [ Param "data" True $ getParam params 0 ] addHostname params = Call "Application" "addHostname" "POST" [ Param "data" True $ getParam params 0 ] addOfferCategory params = Call "Application" "addOfferCategory" "POST" [ Param "data" True $ getParam params 0 ] addOfferGroup params = Call "Application" "addOfferGroup" "POST" [ Param "data" True $ getParam params 0 ] changeAdvertiserApiKey params = Call "Application" "addOfferCategory" "POST" [ Param "id" True $ getParam params 0 ] changeAffiliateApiKey params = Call "Application" "addOfferGroup" "POST" [ Param "id" True $ getParam params 0 ] changeNetworkApiKey params = Call "Application" "changeNetworkApiKey" "POST" [ ] createAdvertiserApiKey params = Call "Application" "createAdvertiserApiKey" "POST" [ Param "data" True $ getParam params 0 ] -- Deprecated, v1 key createAffiliateApiKey params = Call "Application" "createAffiliateApiKey" "POST" [ Param "data" True $ getParam params 0 ] decryptUnsubHash params = Call "Application" "decryptUnsubHash" "GET" [ Param "data" True $ getParam params 0 ] findAdvertiserApiKey params = Call "Application" "findAdvertiserApiKey" "GET" [ Param "api_key" True $ getParam params 0 ] findAdvertiserApiKeyByAdvertiserId params = Call "Application" "findAdvertiserApiKeyByAdvertiserId" "GET" [ Param "advertiser_id" True $ getParam params 0 ] findAffiliateApiKey params = Call "Application" "findAffiliateApiKey" "GET" [ Param "api_key" True $ getParam params 0 ] findAffiliateApiKeyByAffiliateId params = Call "Application" "findAffiliateApiKeyByAffiliateId" "GET" [ Param "affiliate_id" True $ getParam params 0 ] findAllAdvertiserApiKeys params = Call "Application" "findAllAdvertiserApiKeys" "GET" [ Param "filters" False $ getParam params 0 , Param "fields" False $ getParam params 1 , Param "contain" False $ getParam params 2 ] findAllAffiliateApiKeys params = Call "Application" "findAllAffiliateApiKeys" "GET" [ Param "filters" False $ getParam params 0 , Param "fields" False $ getParam params 1 , Param "contain" False $ getParam params 2 ] findAllAffiliateTierAffiliateIds params = Call "Application" "findAllAffiliateTierAffiliateIds" "GET" [ Param "id" True $ getParam params 0 ] findAllAffiliateTiers params = Call "Application" "findAllAffiliateTiers" "GET" [ Param "filters" False $ getParam params 0 , Param "fields" False $ getParam params 1 ] findAllBrowsers params = Call "Application" "findAllBrowsers" "GET" [ ] findAllCountries params = Call "Application" "findAllCountries" "GET" [ ] findAllHostnames params = Call "Application" "findAllHostnames" "GET" [ Param "filters" False $ getParam params 0 , Param "fields" False $ getParam params 1 ] findAllOfferCategories params = Call "Application" "findAllOfferCategories" "GET" [ Param "filters" False $ getParam params 0 , Param "fields" False $ getParam params 1 , Param "sort" False $ getParam params 2 ] findAllOfferCategoryOfferIds params = Call "Application" "findAllOfferCategoryOfferIds" "GET" [ Param "id" False $ getParam params 0 ] findAllOfferGroups params = Call "Application" "findAllOfferGroups" "GET" [ Param "filters" False $ getParam params 0 , Param "fields" False $ getParam params 1 ] findAllPermissions params = Call "Application" "findAllPermissions" "GET" [ ] findAllRegions params = Call "Application" "findAllRegions" "GET" [ ] findAllTimezones params = Call "Application" "findAllTimezones" "GET" [ ] findBrowserById params = Call "Application" "findBrowserById" "GET" [ Param "id" True $ getParam params 0 ] findCountryByCode params = Call "Application" "findCountryByCode" "GET" [ Param "code" True $ getParam params 0 ] findPermissionById params = Call "Application" "findPermissionById" "GET" [ Param "id" True $ getParam params 0 ] findPermissionByName params = Call "Application" "findPermissionByName" "GET" [ Param "name" True $ getParam params 0 ] findPermissionsByGroup params = Call "Application" "findPermissionsByGroup" "GET" [ Param "group" True $ getParam params 0 ] findTimezoneById params = Call "Application" "findTimezoneById" "GET" [ Param "id" True $ getParam params 0 ] findUserAuthIps params = Call "Application" "findUserAuthIps" "GET" [ Param "filters" False $ getParam params 0 , Param "sort" False $ getParam params 1 , Param "limit" False $ getParam params 2 , Param "page" False $ getParam params 3 , Param "fields" False $ getParam params 4 ] generateAllUnsubLinks params = Call "Application" "generateAllUnsubLinks" "POST" [ Param "users" True $ getParam params 0 ] getAccountInformation params = Call "Application" "getAccountInformation" "GET" [ ] getActiveOfferCategoryCount params = Call "Application" "getActiveOfferCategoryCount" "GET" [ ] getBrand params = Call "Application" "getBrand" "GET" [ ] getBrandInformation params = Call "Application" "getBrandInformation" "GET" [ ] getCountryRegions params = Call "Application" "getCountryRegions" "POST" [ Param "code" True $ getParam params 0 ] getPoFile params = Call "Application" "getPoFile" "POST" [ Param "laanguage" True $ getParam params 0 ] getTimezone params = Call "Application" "getTimezone" "GET" [ ] -- csv upload importAdvertisers params = undefined -- csv upload importOffers params = undefined resetPassword params = Call "Application" "resetPassword" "POST" [ Param "email" True $ getParam params 0 ]
kelecorix/api-hasoffers
src/HasOffers/API/Brand/Application.hs
bsd-3-clause
7,256
0
8
2,334
1,587
760
827
238
1
module Text.ICalendar.DataType.Duration ( durationType ) where -- haskell platform libraries import Control.Applicative ((<$>)) import Data.Time.Clock (DiffTime, secondsToDiffTime) import Text.Parsec.String import Text.Parsec.Combinator import Text.Parsec.Char import Text.Parsec.Prim -- native libraries import Text.ICalendar.Parser.Combinator durationType :: Parser DiffTime durationType = do signed <- toSign <$> option '+' (char '+' <|> char '-') char 'P' totalSecs <- durDateTime <|> durWeek lineBreak return . secondsToDiffTime $ signed totalSecs -- private functions durDateTime :: Parser Integer durDateTime = do daySecs <- 86400 `secondsPer` interval 'D' char 'T' hourSecs <- 3600 `secondsPer` interval 'H' minSecs <- 60 `secondsPer` interval 'M' secs <- 1 `secondsPer` interval 'S' return $ daySecs + hourSecs + minSecs + secs durWeek :: Parser Integer durWeek = 604800 `secondsPer` interval 'W' interval :: Char -> Parser Integer interval i = option "0" (try . manyTill digit $ char i) >>= return . read secondsPer :: Integer -> (Parser Integer -> Parser Integer) secondsPer mult = (<$>) (* mult) toSign :: Char -> (Integer -> Integer) toSign '-' = (*) (-1) toSign _ = id
Jonplussed/iCalendar
src/Text/ICalendar/DataType/Duration.hs
bsd-3-clause
1,252
0
12
239
404
214
190
33
1
{-# LANGUAGE ScopedTypeVariables #-} module Main where import DynFlags import GHC import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.List import Data.Maybe import Data.Time.Calendar import Data.Time.Clock import Exception import HeaderInfo import HscTypes import Outputable import StringBuffer import System.Directory import System.Environment import System.Process import System.IO import Text.Printf main :: IO () main = do libdir:args <- getArgs createDirectoryIfMissing False "outdir" runGhc (Just libdir) $ do dflags0 <- getSessionDynFlags (dflags1, xs, warn) <- parseDynamicFlags dflags0 $ map noLoc $ [ "-outputdir", "./outdir" , "-fno-diagnostics-show-caret" ] ++ args _ <- setSessionDynFlags dflags1 -- This test fails on purpose to check if the error message mentions -- the source file and not the intermediary preprocessor input file -- even when no preprocessor is in use. Just a sanity check. go "Error" ["A"] -- ^ ^-- targets -- ^-- test name [("A" -- this module's name , "" -- pragmas , [] -- imports/non exported decls , [("x", "z")] -- exported decls , OnDisk -- write this module to disk? ) ] forM_ [OnDisk, InMemory] $ \sync -> -- This one fails unless CPP actually preprocessed the source go ("CPP_" ++ ppSync sync) ["A"] [( "A" , "{-# LANGUAGE CPP #-}" , ["#define y 1"] , [("x", "y")] , sync ) ] -- These check if on-disk modules can import in-memory targets and -- vice-verca. forM_ (words "DD MM DM MD") $ \sync@[a_sync, b_sync] -> do dep <- return $ \y -> [( "A" , "{-# LANGUAGE CPP #-}" , ["import B"] , [("x", "y")] , readSync a_sync ), ( "B" , "{-# LANGUAGE CPP #-}" , [] , [("y", y)] , readSync b_sync ) ] go ("Dep_" ++ sync ++ "_AB") ["A", "B"] (dep "()") -- This checks if error messages are correctly referring to the real -- source file and not the temp preprocessor input file. go ("Dep_Error_" ++ sync ++ "_AB") ["A", "B"] (dep "z") -- Try with only one target, this is expected to fail with a module -- not found error where module B is not OnDisk. go ("Dep_Error_" ++ sync ++ "_A") ["A"] (dep "z") return () data Sync = OnDisk -- | Write generated module to disk | InMemory -- | Only fill in targetContents. ppSync OnDisk = "D" ppSync InMemory = "M" readSync 'D' = OnDisk readSync 'M' = InMemory go label targets mods = do liftIO $ createDirectoryIfMissing False "./outdir" setTargets []; _ <- load LoadAllTargets liftIO $ hPutStrLn stderr $ "== " ++ label t <- liftIO getCurrentTime setTargets =<< catMaybes <$> mapM (mkTarget t) mods ex <- gtry $ load LoadAllTargets case ex of Left ex -> liftIO $ hPutStrLn stderr $ show (ex :: SourceError) Right _ -> return () mapM_ (liftIO . cleanup) mods liftIO $ removeDirectoryRecursive "./outdir" where mkTarget t mod@(name,_,_,_,sync) = do src <- liftIO $ genMod mod return $ if not (name `elem` targets) then Nothing else Just $ Target { targetId = TargetFile (name++".hs") Nothing , targetAllowObjCode = False , targetContents = case sync of OnDisk -> Nothing InMemory -> Just ( stringToStringBuffer src , t ) } genMod :: (String, String, [String], [(String, String)], Sync) -> IO String genMod (mod, pragmas, internal, binders, sync) = do case sync of OnDisk -> writeFile (mod++".hs") src InMemory -> return () return src where exports = intercalate ", " $ map fst binders decls = map (\(b,v) -> b ++ " = " ++ v) binders src = unlines $ [ pragmas , "module " ++ mod ++ " ("++ exports ++") where" ] ++ internal ++ decls cleanup :: (String, String, [String], [(String, String)], Sync) -> IO () cleanup (mod,_,_,_,OnDisk) = removeFile (mod++".hs") cleanup _ = return ()
sdiehl/ghc
testsuite/tests/ghc-api/target-contents/TargetContents.hs
bsd-3-clause
4,330
0
20
1,363
1,187
645
542
107
4
module Geordi.FileBackend where import qualified Data.ByteString.Lazy as L import Network.Wai.Parse newtype FileBackend a = FB (BackEnd a) lbsBackend :: FileBackend L.ByteString lbsBackend = FB $ lbsBackEnd tempFileBackend :: FileBackend FilePath tempFileBackend = FB $ tempFileBackEnd
liamoc/geordi
Geordi/FileBackend.hs
bsd-3-clause
289
0
7
38
72
43
29
8
1
import Blaze.ByteString.Builder.Char8 import Data.Monoid ((<>)) import Data.Text as T import Text.Strapped import Text.Strapped.Render import Text.Strapped.Parser import Text.Parsec import Text.Parsec.String data MyData = MyData ParsedExpression deriving (Show) -- | Process MyData in the RenderT monad when it is rendered. instance Block MyData where process (MyData ex) = do config <- getConfig lit <- reduceExpression ex return $ fromString "MyData ->" <> (renderOutput config lit) <> fromString "<- MyData" -- | Parse out MyData using Parsec parseMyData :: ParserM MyData parseMyData = do tagStart >> spaces >> (string "MyData") >> spaces >> parseExpression (spaces >> tagEnd) >>= (return . MyData) main :: IO () main = do case templateStoreFromList config [("mydata", "testing... {$ MyData lookup $}")] of Left e -> print e Right ts -> do r <- render (config {templateStore = ts}) (varBucket "lookup" $ LitVal $ LitText $ T.pack "Cooolio") "mydata" print r where config = defaultConfig {customParsers = [BlockParser parseMyData]}
hansonkd/StrappedTemplates
examples/custom_parser.hs
bsd-3-clause
1,128
0
18
244
332
174
158
26
2
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} --------------------------------------------------------------- -- | -- Module : Data.Minecraft.Release19.Protocol -- Copyright : (c) 2016 Michael Carpenter -- License : BSD3 -- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com> -- Stability : experimental -- Portability : portable -- --------------------------------------------------------------- module Data.Minecraft.Release19.Protocol ( ServerBoundHandshakingPacket (..) , ClientBoundStatusPacket (..) , ServerBoundStatusPacket (..) , ClientBoundLoginPacket (..) , ServerBoundLoginPacket (..) , ClientBoundPlayPacket (..) , ServerBoundPlayPacket (..) ) where import Data.Attoparsec.ByteString import Data.ByteString as B import Data.ByteString.Builder as BB import Data.Int import Data.Fixed import Data.Minecraft.Types import Data.NBT import Data.Serialize hiding (putByteString,getByteString) import Data.Text as T import Data.UUID import Data.Word data ServerBoundHandshakingPacket = ServerBoundSetProtocol VarInt Text Word16 VarInt | ServerBoundLegacyServerListPing Word8 deriving (Show,Eq) data ClientBoundStatusPacket = ClientBoundServerInfo Text | ClientBoundPing Int64 deriving (Show,Eq) data ServerBoundStatusPacket = ServerBoundPingStart | ServerBoundPing Int64 deriving (Show,Eq) data ClientBoundLoginPacket = ClientBoundDisconnect Text | ClientBoundEncryptionBegin Text Buffer Buffer | ClientBoundSuccess Text Text | ClientBoundCompress VarInt deriving (Show,Eq) data ServerBoundLoginPacket = ServerBoundLoginStart Text | ServerBoundEncryptionBegin Buffer Buffer deriving (Show,Eq) data ClientBoundPlayPacket = ClientBoundSpawnEntity VarInt UUID Int8 Double Double Double Int8 Int8 Int32 Int16 Int16 Int16 | ClientBoundSpawnEntityExperienceOrb VarInt Double Double Double Int16 | ClientBoundSpawnEntityWeather VarInt Int8 Double Double Double | ClientBoundSpawnEntityLiving VarInt UUID Word8 Double Double Double Int8 Int8 Int8 Int16 Int16 Int16 EntityMetadata | ClientBoundSpawnEntityPainting VarInt UUID Text Position Word8 | ClientBoundNamedEntitySpawn VarInt UUID Double Double Double Int8 Int8 EntityMetadata | ClientBoundAnimation VarInt Word8 | ClientBoundStatistics Array | ClientBoundBlockBreakAnimation VarInt Position Int8 | ClientBoundTileEntityData Position Word8 (Maybe NBT) | ClientBoundBlockAction Position Word8 Word8 VarInt | ClientBoundBlockChange Position VarInt | ClientBoundBossBar UUID VarInt (Maybe Text) (Maybe Float) (Maybe VarInt) (Maybe VarInt) (Maybe Word8) | ClientBoundDifficulty Word8 | ClientBoundTabComplete Array | ClientBoundChat Text Int8 | ClientBoundMultiBlockChange Int32 Int32 Array | ClientBoundTransaction Int8 Int16 Bool | ClientBoundCloseWindow Word8 | ClientBoundOpenWindow Word8 Text Text Word8 (Maybe Int32) | ClientBoundWindowItems Word8 Array | ClientBoundCraftProgressBar Word8 Int16 Int16 | ClientBoundSetSlot Int8 Int16 Slot | ClientBoundSetCooldown VarInt VarInt | ClientBoundCustomPayload Text RestBuffer | ClientBoundNamedSoundEffect Text VarInt Int32 Int32 Int32 Float Word8 | ClientBoundKickDisconnect Text | ClientBoundEntityStatus Int32 Int8 | ClientBoundExplosion Float Float Float Float Array Float Float Float | ClientBoundUnloadChunk Int32 Int32 | ClientBoundGameStateChange Word8 Float | ClientBoundKeepAlive VarInt | ClientBoundMapChunk Int32 Int32 Bool VarInt Buffer | ClientBoundWorldEvent Int32 Position Int32 Bool | ClientBoundWorldParticles Int32 Bool Float Float Float Float Float Float Float Int32 (Maybe Array) | ClientBoundLogin Int32 Word8 Int8 Word8 Word8 Text Bool | ClientBoundMap VarInt Int8 Bool Array Int8 (Maybe Int8) (Maybe Int8) (Maybe Int8) (Maybe Buffer) | ClientBoundRelEntityMove VarInt Int16 Int16 Int16 Bool | ClientBoundEntityMoveLook VarInt Int16 Int16 Int16 Int8 Int8 Bool | ClientBoundEntityLook VarInt Int8 Int8 Bool | ClientBoundEntity VarInt | ClientBoundVehicleMove Double Double Double Float Float | ClientBoundOpenSignEntity Position | ClientBoundAbilities Int8 Float Float | ClientBoundCombatEvent VarInt (Maybe VarInt) (Maybe VarInt) (Maybe Int32) (Maybe Text) | ClientBoundPlayerInfo VarInt Array | ClientBoundPosition Double Double Double Float Float Int8 VarInt | ClientBoundBed VarInt Position | ClientBoundEntityDestroy Array | ClientBoundRemoveEntityEffect VarInt Int8 | ClientBoundResourcePackSend Text Text | ClientBoundRespawn Int32 Word8 Word8 Text | ClientBoundEntityHeadRotation VarInt Int8 | ClientBoundWorldBorder VarInt (Maybe Double) (Maybe Double) (Maybe Double) (Maybe Double) (Maybe Double) (Maybe VarInt) (Maybe VarInt) (Maybe VarInt) (Maybe VarInt) | ClientBoundCamera VarInt | ClientBoundHeldItemSlot Int8 | ClientBoundScoreboardDisplayObjective Int8 Text | ClientBoundEntityMetadata VarInt EntityMetadata | ClientBoundAttachEntity Int32 Int32 | ClientBoundEntityVelocity VarInt Int16 Int16 Int16 | ClientBoundEntityEquipment VarInt VarInt Slot | ClientBoundExperience Float VarInt VarInt | ClientBoundUpdateHealth Float VarInt Float | ClientBoundScoreboardObjective Text Int8 (Maybe Text) (Maybe Text) | ClientBoundSetPassengers VarInt Array | ClientBoundTeams Text Int8 (Maybe Text) (Maybe Text) (Maybe Text) (Maybe Int8) (Maybe Text) (Maybe Text) (Maybe Int8) (Maybe Array) | ClientBoundScoreboardScore Text Int8 Text (Maybe VarInt) | ClientBoundSpawnPosition Position | ClientBoundUpdateTime Int64 Int64 | ClientBoundTitle VarInt (Maybe Text) (Maybe Int32) (Maybe Int32) (Maybe Int32) | ClientBoundUpdateSign Position Text Text Text Text | ClientBoundSoundEffect VarInt VarInt Int32 Int32 Int32 Float Word8 | ClientBoundPlayerlistHeader Text Text | ClientBoundCollect VarInt VarInt | ClientBoundEntityTeleport VarInt Double Double Double Int8 Int8 Bool | ClientBoundEntityUpdateAttributes VarInt Array | ClientBoundEntityEffect VarInt Int8 Int8 VarInt Int8 deriving (Show,Eq) data ServerBoundPlayPacket = ServerBoundTeleportConfirm VarInt | ServerBoundTabComplete Text Bool (Maybe Position) | ServerBoundChat Text | ServerBoundClientCommand VarInt | ServerBoundSettings Text Int8 VarInt Bool Word8 VarInt | ServerBoundTransaction Int8 Int16 Bool | ServerBoundEnchantItem Int8 Int8 | ServerBoundWindowClick Word8 Int16 Int8 Int16 Int8 Slot | ServerBoundCloseWindow Word8 | ServerBoundCustomPayload Text RestBuffer | ServerBoundUseEntity VarInt VarInt (Maybe Float) (Maybe Float) (Maybe Float) (Maybe VarInt) | ServerBoundKeepAlive VarInt | ServerBoundPosition Double Double Double Bool | ServerBoundPositionLook Double Double Double Float Float Bool | ServerBoundLook Float Float Bool | ServerBoundFlying Bool | ServerBoundVehicleMove Double Double Double Float Float | ServerBoundSteerBoat Bool Bool | ServerBoundAbilities Int8 Float Float | ServerBoundBlockDig Int8 Position Int8 | ServerBoundEntityAction VarInt VarInt VarInt | ServerBoundSteerVehicle Float Float Word8 | ServerBoundResourcePackReceive Text VarInt | ServerBoundHeldItemSlot Int16 | ServerBoundSetCreativeSlot Int16 Slot | ServerBoundUpdateSign Position Text Text Text Text | ServerBoundArmAnimation VarInt | ServerBoundSpectate UUID | ServerBoundBlockPlace Position VarInt VarInt Int8 Int8 Int8 | ServerBoundUseItem VarInt deriving (Show,Eq) instance Serialize ServerBoundHandshakingPacket where put (ServerBoundSetProtocol protocolVersion serverHost serverPort nextState) = do putWord8 0x00 putVarInt protocolVersion putText serverHost putWord16 serverPort putVarInt nextState put (ServerBoundLegacyServerListPing payload) = do putWord8 0xfe putWord8 payload get = do packetId <- getWord8 case packetId of 0x00 -> do protocolVersion <- getVarInt serverHost <- getText serverPort <- getWord16 nextState <- getVarInt return $ ServerBoundSetProtocol protocolVersion serverHost serverPort nextState 0xfe -> do payload <- getWord8 return $ ServerBoundLegacyServerListPing payload instance Serialize ClientBoundStatusPacket where put (ClientBoundServerInfo response) = do putWord8 0x00 putText response put (ClientBoundPing time) = do putWord8 0x01 putInt64 time get = do packetId <- getWord8 case packetId of 0x00 -> do response <- getText return $ ClientBoundServerInfo response 0x01 -> do time <- getInt64 return $ ClientBoundPing time instance Serialize ServerBoundStatusPacket where put (ServerBoundPingStart ) = do putWord8 0x00 put (ServerBoundPing time) = do putWord8 0x01 putInt64 time get = do packetId <- getWord8 case packetId of 0x00 -> do return $ ServerBoundPingStart 0x01 -> do time <- getInt64 return $ ServerBoundPing time instance Serialize ClientBoundLoginPacket where put (ClientBoundDisconnect reason) = do putWord8 0x00 putText reason put (ClientBoundEncryptionBegin serverId publicKey verifyToken) = do putWord8 0x01 putText serverId putBuffer publicKey putBuffer verifyToken put (ClientBoundSuccess uuid username) = do putWord8 0x02 putText uuid putText username put (ClientBoundCompress threshold) = do putWord8 0x03 putVarInt threshold get = do packetId <- getWord8 case packetId of 0x00 -> do reason <- getText return $ ClientBoundDisconnect reason 0x01 -> do serverId <- getText publicKey <- getBuffer verifyToken <- getBuffer return $ ClientBoundEncryptionBegin serverId publicKey verifyToken 0x02 -> do uuid <- getText username <- getText return $ ClientBoundSuccess uuid username 0x03 -> do threshold <- getVarInt return $ ClientBoundCompress threshold instance Serialize ServerBoundLoginPacket where put (ServerBoundLoginStart username) = do putWord8 0x00 putText username put (ServerBoundEncryptionBegin sharedSecret verifyToken) = do putWord8 0x01 putBuffer sharedSecret putBuffer verifyToken get = do packetId <- getWord8 case packetId of 0x00 -> do username <- getText return $ ServerBoundLoginStart username 0x01 -> do sharedSecret <- getBuffer verifyToken <- getBuffer return $ ServerBoundEncryptionBegin sharedSecret verifyToken instance Serialize ClientBoundPlayPacket where put (ClientBoundSpawnEntity entityId objectUUID pType x y z pitch yaw intField velocityX velocityY velocityZ) = do putWord8 0x00 putVarInt entityId putUUID objectUUID putInt8 pType putDouble x putDouble y putDouble z putInt8 pitch putInt8 yaw putInt32 intField putInt16 velocityX putInt16 velocityY putInt16 velocityZ put (ClientBoundSpawnEntityExperienceOrb entityId x y z count) = do putWord8 0x01 putVarInt entityId putDouble x putDouble y putDouble z putInt16 count put (ClientBoundSpawnEntityWeather entityId pType x y z) = do putWord8 0x02 putVarInt entityId putInt8 pType putDouble x putDouble y putDouble z put (ClientBoundSpawnEntityLiving entityId entityUUID pType x y z yaw pitch headPitch velocityX velocityY velocityZ metadata) = do putWord8 0x03 putVarInt entityId putUUID entityUUID putWord8 pType putDouble x putDouble y putDouble z putInt8 yaw putInt8 pitch putInt8 headPitch putInt16 velocityX putInt16 velocityY putInt16 velocityZ putEntityMetadata metadata put (ClientBoundSpawnEntityPainting entityId entityUUID title location direction) = do putWord8 0x04 putVarInt entityId putUUID entityUUID putText title putPosition location putWord8 direction put (ClientBoundNamedEntitySpawn entityId playerUUID x y z yaw pitch metadata) = do putWord8 0x05 putVarInt entityId putUUID playerUUID putDouble x putDouble y putDouble z putInt8 yaw putInt8 pitch putEntityMetadata metadata put (ClientBoundAnimation entityId animation) = do putWord8 0x06 putVarInt entityId putWord8 animation put (ClientBoundStatistics entries) = do putWord8 0x07 putArray entries put (ClientBoundBlockBreakAnimation entityId location destroyStage) = do putWord8 0x08 putVarInt entityId putPosition location putInt8 destroyStage put (ClientBoundTileEntityData location action nbtData) = do putWord8 0x09 putPosition location putWord8 action case nbtData of Just nbtData' -> putNBT nbtData' Nothing -> return () put (ClientBoundBlockAction location byte1 byte2 blockId) = do putWord8 0x0a putPosition location putWord8 byte1 putWord8 byte2 putVarInt blockId put (ClientBoundBlockChange location pType) = do putWord8 0x0b putPosition location putVarInt pType put (ClientBoundBossBar entityUUID action title health color dividers flags) = do putWord8 0x0c putUUID entityUUID putVarInt action case title of Just title' -> putText title' Nothing -> return () case health of Just health' -> putFloat health' Nothing -> return () case color of Just color' -> putVarInt color' Nothing -> return () case dividers of Just dividers' -> putVarInt dividers' Nothing -> return () case flags of Just flags' -> putWord8 flags' Nothing -> return () put (ClientBoundDifficulty difficulty) = do putWord8 0x0d putWord8 difficulty put (ClientBoundTabComplete matches) = do putWord8 0x0e putArray matches put (ClientBoundChat message position) = do putWord8 0x0f putText message putInt8 position put (ClientBoundMultiBlockChange chunkX chunkZ records) = do putWord8 0x10 putInt32 chunkX putInt32 chunkZ putArray records put (ClientBoundTransaction windowId action accepted) = do putWord8 0x11 putInt8 windowId putInt16 action putBool accepted put (ClientBoundCloseWindow windowId) = do putWord8 0x12 putWord8 windowId put (ClientBoundOpenWindow windowId inventoryType windowTitle slotCount entityId) = do putWord8 0x13 putWord8 windowId putText inventoryType putText windowTitle putWord8 slotCount case entityId of Just entityId' -> putInt32 entityId' Nothing -> return () put (ClientBoundWindowItems windowId items) = do putWord8 0x14 putWord8 windowId putArray items put (ClientBoundCraftProgressBar windowId property value) = do putWord8 0x15 putWord8 windowId putInt16 property putInt16 value put (ClientBoundSetSlot windowId slot item) = do putWord8 0x16 putInt8 windowId putInt16 slot putSlot item put (ClientBoundSetCooldown itemID cooldownTicks) = do putWord8 0x17 putVarInt itemID putVarInt cooldownTicks put (ClientBoundCustomPayload channel pData) = do putWord8 0x18 putText channel putRestBuffer pData put (ClientBoundNamedSoundEffect soundName soundCategory x y z volume pitch) = do putWord8 0x19 putText soundName putVarInt soundCategory putInt32 x putInt32 y putInt32 z putFloat volume putWord8 pitch put (ClientBoundKickDisconnect reason) = do putWord8 0x1a putText reason put (ClientBoundEntityStatus entityId entityStatus) = do putWord8 0x1b putInt32 entityId putInt8 entityStatus put (ClientBoundExplosion x y z radius affectedBlockOffsets playerMotionX playerMotionY playerMotionZ) = do putWord8 0x1c putFloat x putFloat y putFloat z putFloat radius putArray affectedBlockOffsets putFloat playerMotionX putFloat playerMotionY putFloat playerMotionZ put (ClientBoundUnloadChunk chunkX chunkZ) = do putWord8 0x1d putInt32 chunkX putInt32 chunkZ put (ClientBoundGameStateChange reason gameMode) = do putWord8 0x1e putWord8 reason putFloat gameMode put (ClientBoundKeepAlive keepAliveId) = do putWord8 0x1f putVarInt keepAliveId put (ClientBoundMapChunk x z groundUp bitMap chunkData) = do putWord8 0x20 putInt32 x putInt32 z putBool groundUp putVarInt bitMap putBuffer chunkData put (ClientBoundWorldEvent effectId location pData global) = do putWord8 0x21 putInt32 effectId putPosition location putInt32 pData putBool global put (ClientBoundWorldParticles particleId longDistance x y z offsetX offsetY offsetZ particleData particles pData) = do putWord8 0x22 putInt32 particleId putBool longDistance putFloat x putFloat y putFloat z putFloat offsetX putFloat offsetY putFloat offsetZ putFloat particleData putInt32 particles case pData of Just pData' -> putArray pData' Nothing -> return () put (ClientBoundLogin entityId gameMode dimension difficulty maxPlayers levelType reducedDebugInfo) = do putWord8 0x23 putInt32 entityId putWord8 gameMode putInt8 dimension putWord8 difficulty putWord8 maxPlayers putText levelType putBool reducedDebugInfo put (ClientBoundMap itemDamage scale trackingPosition icons columns rows x y pData) = do putWord8 0x24 putVarInt itemDamage putInt8 scale putBool trackingPosition putArray icons putInt8 columns case rows of Just rows' -> putInt8 rows' Nothing -> return () case x of Just x' -> putInt8 x' Nothing -> return () case y of Just y' -> putInt8 y' Nothing -> return () case pData of Just pData' -> putBuffer pData' Nothing -> return () put (ClientBoundRelEntityMove entityId dX dY dZ onGround) = do putWord8 0x25 putVarInt entityId putInt16 dX putInt16 dY putInt16 dZ putBool onGround put (ClientBoundEntityMoveLook entityId dX dY dZ yaw pitch onGround) = do putWord8 0x26 putVarInt entityId putInt16 dX putInt16 dY putInt16 dZ putInt8 yaw putInt8 pitch putBool onGround put (ClientBoundEntityLook entityId yaw pitch onGround) = do putWord8 0x27 putVarInt entityId putInt8 yaw putInt8 pitch putBool onGround put (ClientBoundEntity entityId) = do putWord8 0x28 putVarInt entityId put (ClientBoundVehicleMove x y z yaw pitch) = do putWord8 0x29 putDouble x putDouble y putDouble z putFloat yaw putFloat pitch put (ClientBoundOpenSignEntity location) = do putWord8 0x2a putPosition location put (ClientBoundAbilities flags flyingSpeed walkingSpeed) = do putWord8 0x2b putInt8 flags putFloat flyingSpeed putFloat walkingSpeed put (ClientBoundCombatEvent event duration playerId entityId message) = do putWord8 0x2c putVarInt event case duration of Just duration' -> putVarInt duration' Nothing -> return () case playerId of Just playerId' -> putVarInt playerId' Nothing -> return () case entityId of Just entityId' -> putInt32 entityId' Nothing -> return () case message of Just message' -> putText message' Nothing -> return () put (ClientBoundPlayerInfo action pData) = do putWord8 0x2d putVarInt action putArray pData put (ClientBoundPosition x y z yaw pitch flags teleportId) = do putWord8 0x2e putDouble x putDouble y putDouble z putFloat yaw putFloat pitch putInt8 flags putVarInt teleportId put (ClientBoundBed entityId location) = do putWord8 0x2f putVarInt entityId putPosition location put (ClientBoundEntityDestroy entityIds) = do putWord8 0x30 putArray entityIds put (ClientBoundRemoveEntityEffect entityId effectId) = do putWord8 0x31 putVarInt entityId putInt8 effectId put (ClientBoundResourcePackSend url hash) = do putWord8 0x32 putText url putText hash put (ClientBoundRespawn dimension difficulty gamemode levelType) = do putWord8 0x33 putInt32 dimension putWord8 difficulty putWord8 gamemode putText levelType put (ClientBoundEntityHeadRotation entityId headYaw) = do putWord8 0x34 putVarInt entityId putInt8 headYaw put (ClientBoundWorldBorder action radius x z oldRadius newRadius speed portalBoundary warningTime warningBlocks) = do putWord8 0x35 putVarInt action case radius of Just radius' -> putDouble radius' Nothing -> return () case x of Just x' -> putDouble x' Nothing -> return () case z of Just z' -> putDouble z' Nothing -> return () case oldRadius of Just oldRadius' -> putDouble oldRadius' Nothing -> return () case newRadius of Just newRadius' -> putDouble newRadius' Nothing -> return () case speed of Just speed' -> putVarInt speed' Nothing -> return () case portalBoundary of Just portalBoundary' -> putVarInt portalBoundary' Nothing -> return () case warningTime of Just warningTime' -> putVarInt warningTime' Nothing -> return () case warningBlocks of Just warningBlocks' -> putVarInt warningBlocks' Nothing -> return () put (ClientBoundCamera cameraId) = do putWord8 0x36 putVarInt cameraId put (ClientBoundHeldItemSlot slot) = do putWord8 0x37 putInt8 slot put (ClientBoundScoreboardDisplayObjective position name) = do putWord8 0x38 putInt8 position putText name put (ClientBoundEntityMetadata entityId metadata) = do putWord8 0x39 putVarInt entityId putEntityMetadata metadata put (ClientBoundAttachEntity entityId vehicleId) = do putWord8 0x3a putInt32 entityId putInt32 vehicleId put (ClientBoundEntityVelocity entityId velocityX velocityY velocityZ) = do putWord8 0x3b putVarInt entityId putInt16 velocityX putInt16 velocityY putInt16 velocityZ put (ClientBoundEntityEquipment entityId slot item) = do putWord8 0x3c putVarInt entityId putVarInt slot putSlot item put (ClientBoundExperience experienceBar level totalExperience) = do putWord8 0x3d putFloat experienceBar putVarInt level putVarInt totalExperience put (ClientBoundUpdateHealth health food foodSaturation) = do putWord8 0x3e putFloat health putVarInt food putFloat foodSaturation put (ClientBoundScoreboardObjective name action displayText pType) = do putWord8 0x3f putText name putInt8 action case displayText of Just displayText' -> putText displayText' Nothing -> return () case pType of Just pType' -> putText pType' Nothing -> return () put (ClientBoundSetPassengers entityId passengers) = do putWord8 0x40 putVarInt entityId putArray passengers put (ClientBoundTeams team mode name prefix suffix friendlyFire nameTagVisibility collisionRule color players) = do putWord8 0x41 putText team putInt8 mode case name of Just name' -> putText name' Nothing -> return () case prefix of Just prefix' -> putText prefix' Nothing -> return () case suffix of Just suffix' -> putText suffix' Nothing -> return () case friendlyFire of Just friendlyFire' -> putInt8 friendlyFire' Nothing -> return () case nameTagVisibility of Just nameTagVisibility' -> putText nameTagVisibility' Nothing -> return () case collisionRule of Just collisionRule' -> putText collisionRule' Nothing -> return () case color of Just color' -> putInt8 color' Nothing -> return () case players of Just players' -> putArray players' Nothing -> return () put (ClientBoundScoreboardScore itemName action scoreName value) = do putWord8 0x42 putText itemName putInt8 action putText scoreName case value of Just value' -> putVarInt value' Nothing -> return () put (ClientBoundSpawnPosition location) = do putWord8 0x43 putPosition location put (ClientBoundUpdateTime age time) = do putWord8 0x44 putInt64 age putInt64 time put (ClientBoundTitle action text fadeIn stay fadeOut) = do putWord8 0x45 putVarInt action case text of Just text' -> putText text' Nothing -> return () case fadeIn of Just fadeIn' -> putInt32 fadeIn' Nothing -> return () case stay of Just stay' -> putInt32 stay' Nothing -> return () case fadeOut of Just fadeOut' -> putInt32 fadeOut' Nothing -> return () put (ClientBoundUpdateSign location text1 text2 text3 text4) = do putWord8 0x46 putPosition location putText text1 putText text2 putText text3 putText text4 put (ClientBoundSoundEffect soundId soundCatagory x y z volume pitch) = do putWord8 0x47 putVarInt soundId putVarInt soundCatagory putInt32 x putInt32 y putInt32 z putFloat volume putWord8 pitch put (ClientBoundPlayerlistHeader header footer) = do putWord8 0x48 putText header putText footer put (ClientBoundCollect collectedEntityId collectorEntityId) = do putWord8 0x49 putVarInt collectedEntityId putVarInt collectorEntityId put (ClientBoundEntityTeleport entityId x y z yaw pitch onGround) = do putWord8 0x4a putVarInt entityId putDouble x putDouble y putDouble z putInt8 yaw putInt8 pitch putBool onGround put (ClientBoundEntityUpdateAttributes entityId properties) = do putWord8 0x4b putVarInt entityId putArray properties put (ClientBoundEntityEffect entityId effectId amplifier duration hideParticles) = do putWord8 0x4c putVarInt entityId putInt8 effectId putInt8 amplifier putVarInt duration putInt8 hideParticles get = do packetId <- getWord8 case packetId of 0x00 -> do entityId <- getVarInt objectUUID <- getUUID pType <- getInt8 x <- getDouble y <- getDouble z <- getDouble pitch <- getInt8 yaw <- getInt8 intField <- getInt32 velocityX <- getInt16 velocityY <- getInt16 velocityZ <- getInt16 return $ ClientBoundSpawnEntity entityId objectUUID pType x y z pitch yaw intField velocityX velocityY velocityZ 0x01 -> do entityId <- getVarInt x <- getDouble y <- getDouble z <- getDouble count <- getInt16 return $ ClientBoundSpawnEntityExperienceOrb entityId x y z count 0x02 -> do entityId <- getVarInt pType <- getInt8 x <- getDouble y <- getDouble z <- getDouble return $ ClientBoundSpawnEntityWeather entityId pType x y z 0x03 -> do entityId <- getVarInt entityUUID <- getUUID pType <- getWord8 x <- getDouble y <- getDouble z <- getDouble yaw <- getInt8 pitch <- getInt8 headPitch <- getInt8 velocityX <- getInt16 velocityY <- getInt16 velocityZ <- getInt16 metadata <- getEntityMetadata return $ ClientBoundSpawnEntityLiving entityId entityUUID pType x y z yaw pitch headPitch velocityX velocityY velocityZ metadata 0x04 -> do entityId <- getVarInt entityUUID <- getUUID title <- getText location <- getPosition direction <- getWord8 return $ ClientBoundSpawnEntityPainting entityId entityUUID title location direction 0x05 -> do entityId <- getVarInt playerUUID <- getUUID x <- getDouble y <- getDouble z <- getDouble yaw <- getInt8 pitch <- getInt8 metadata <- getEntityMetadata return $ ClientBoundNamedEntitySpawn entityId playerUUID x y z yaw pitch metadata 0x06 -> do entityId <- getVarInt animation <- getWord8 return $ ClientBoundAnimation entityId animation 0x07 -> do entries <- getArray return $ ClientBoundStatistics entries 0x08 -> do entityId <- getVarInt location <- getPosition destroyStage <- getInt8 return $ ClientBoundBlockBreakAnimation entityId location destroyStage 0x09 -> do location <- getPosition action <- getWord8 let nbtData = case of _ -> return $ ClientBoundTileEntityData location action nbtData 0x0a -> do location <- getPosition byte1 <- getWord8 byte2 <- getWord8 blockId <- getVarInt return $ ClientBoundBlockAction location byte1 byte2 blockId 0x0b -> do location <- getPosition pType <- getVarInt return $ ClientBoundBlockChange location pType 0x0c -> do entityUUID <- getUUID action <- getVarInt let title = case action of 0 -> 3 -> _ -> let health = case action of 0 -> 2 -> _ -> let color = case action of 0 -> 4 -> _ -> let dividers = case action of 0 -> 4 -> _ -> let flags = case action of 0 -> 5 -> _ -> return $ ClientBoundBossBar entityUUID action title health color dividers flags 0x0d -> do difficulty <- getWord8 return $ ClientBoundDifficulty difficulty 0x0e -> do matches <- getArray return $ ClientBoundTabComplete matches 0x0f -> do message <- getText position <- getInt8 return $ ClientBoundChat message position 0x10 -> do chunkX <- getInt32 chunkZ <- getInt32 records <- getArray return $ ClientBoundMultiBlockChange chunkX chunkZ records 0x11 -> do windowId <- getInt8 action <- getInt16 accepted <- getBool return $ ClientBoundTransaction windowId action accepted 0x12 -> do windowId <- getWord8 return $ ClientBoundCloseWindow windowId 0x13 -> do windowId <- getWord8 inventoryType <- getText windowTitle <- getText slotCount <- getWord8 let entityId = case inventoryType of EntityHorse -> _ -> return $ ClientBoundOpenWindow windowId inventoryType windowTitle slotCount entityId 0x14 -> do windowId <- getWord8 items <- getArray return $ ClientBoundWindowItems windowId items 0x15 -> do windowId <- getWord8 property <- getInt16 value <- getInt16 return $ ClientBoundCraftProgressBar windowId property value 0x16 -> do windowId <- getInt8 slot <- getInt16 item <- getSlot return $ ClientBoundSetSlot windowId slot item 0x17 -> do itemID <- getVarInt cooldownTicks <- getVarInt return $ ClientBoundSetCooldown itemID cooldownTicks 0x18 -> do channel <- getText pData <- getRestBuffer return $ ClientBoundCustomPayload channel pData 0x19 -> do soundName <- getText soundCategory <- getVarInt x <- getInt32 y <- getInt32 z <- getInt32 volume <- getFloat pitch <- getWord8 return $ ClientBoundNamedSoundEffect soundName soundCategory x y z volume pitch 0x1a -> do reason <- getText return $ ClientBoundKickDisconnect reason 0x1b -> do entityId <- getInt32 entityStatus <- getInt8 return $ ClientBoundEntityStatus entityId entityStatus 0x1c -> do x <- getFloat y <- getFloat z <- getFloat radius <- getFloat affectedBlockOffsets <- getArray playerMotionX <- getFloat playerMotionY <- getFloat playerMotionZ <- getFloat return $ ClientBoundExplosion x y z radius affectedBlockOffsets playerMotionX playerMotionY playerMotionZ 0x1d -> do chunkX <- getInt32 chunkZ <- getInt32 return $ ClientBoundUnloadChunk chunkX chunkZ 0x1e -> do reason <- getWord8 gameMode <- getFloat return $ ClientBoundGameStateChange reason gameMode 0x1f -> do keepAliveId <- getVarInt return $ ClientBoundKeepAlive keepAliveId 0x20 -> do x <- getInt32 z <- getInt32 groundUp <- getBool bitMap <- getVarInt chunkData <- getBuffer return $ ClientBoundMapChunk x z groundUp bitMap chunkData 0x21 -> do effectId <- getInt32 location <- getPosition pData <- getInt32 global <- getBool return $ ClientBoundWorldEvent effectId location pData global 0x22 -> do particleId <- getInt32 longDistance <- getBool x <- getFloat y <- getFloat z <- getFloat offsetX <- getFloat offsetY <- getFloat offsetZ <- getFloat particleData <- getFloat particles <- getInt32 let pData = case particleId of 37 -> 36 -> 38 -> _ -> return $ ClientBoundWorldParticles particleId longDistance x y z offsetX offsetY offsetZ particleData particles pData 0x23 -> do entityId <- getInt32 gameMode <- getWord8 dimension <- getInt8 difficulty <- getWord8 maxPlayers <- getWord8 levelType <- getText reducedDebugInfo <- getBool return $ ClientBoundLogin entityId gameMode dimension difficulty maxPlayers levelType reducedDebugInfo 0x24 -> do itemDamage <- getVarInt scale <- getInt8 trackingPosition <- getBool icons <- getArray columns <- getInt8 let rows = case columns of 0 -> _ -> let x = case columns of 0 -> _ -> let y = case columns of 0 -> _ -> let pData = case columns of 0 -> _ -> return $ ClientBoundMap itemDamage scale trackingPosition icons columns rows x y pData 0x25 -> do entityId <- getVarInt dX <- getInt16 dY <- getInt16 dZ <- getInt16 onGround <- getBool return $ ClientBoundRelEntityMove entityId dX dY dZ onGround 0x26 -> do entityId <- getVarInt dX <- getInt16 dY <- getInt16 dZ <- getInt16 yaw <- getInt8 pitch <- getInt8 onGround <- getBool return $ ClientBoundEntityMoveLook entityId dX dY dZ yaw pitch onGround 0x27 -> do entityId <- getVarInt yaw <- getInt8 pitch <- getInt8 onGround <- getBool return $ ClientBoundEntityLook entityId yaw pitch onGround 0x28 -> do entityId <- getVarInt return $ ClientBoundEntity entityId 0x29 -> do x <- getDouble y <- getDouble z <- getDouble yaw <- getFloat pitch <- getFloat return $ ClientBoundVehicleMove x y z yaw pitch 0x2a -> do location <- getPosition return $ ClientBoundOpenSignEntity location 0x2b -> do flags <- getInt8 flyingSpeed <- getFloat walkingSpeed <- getFloat return $ ClientBoundAbilities flags flyingSpeed walkingSpeed 0x2c -> do event <- getVarInt let duration = case event of 1 -> _ -> let playerId = case event of 2 -> _ -> let entityId = case event of 1 -> 2 -> _ -> let message = case event of 2 -> _ -> return $ ClientBoundCombatEvent event duration playerId entityId message 0x2d -> do action <- getVarInt pData <- getArray return $ ClientBoundPlayerInfo action pData 0x2e -> do x <- getDouble y <- getDouble z <- getDouble yaw <- getFloat pitch <- getFloat flags <- getInt8 teleportId <- getVarInt return $ ClientBoundPosition x y z yaw pitch flags teleportId 0x2f -> do entityId <- getVarInt location <- getPosition return $ ClientBoundBed entityId location 0x30 -> do entityIds <- getArray return $ ClientBoundEntityDestroy entityIds 0x31 -> do entityId <- getVarInt effectId <- getInt8 return $ ClientBoundRemoveEntityEffect entityId effectId 0x32 -> do url <- getText hash <- getText return $ ClientBoundResourcePackSend url hash 0x33 -> do dimension <- getInt32 difficulty <- getWord8 gamemode <- getWord8 levelType <- getText return $ ClientBoundRespawn dimension difficulty gamemode levelType 0x34 -> do entityId <- getVarInt headYaw <- getInt8 return $ ClientBoundEntityHeadRotation entityId headYaw 0x35 -> do action <- getVarInt let radius = case action of 0 -> _ -> let x = case action of 2 -> 3 -> _ -> let z = case action of 2 -> 3 -> _ -> let oldRadius = case action of 1 -> 3 -> _ -> let newRadius = case action of 1 -> 3 -> _ -> let speed = case action of 1 -> 3 -> _ -> let portalBoundary = case action of 3 -> _ -> let warningTime = case action of 4 -> 3 -> _ -> let warningBlocks = case action of 5 -> 3 -> _ -> return $ ClientBoundWorldBorder action radius x z oldRadius newRadius speed portalBoundary warningTime warningBlocks 0x36 -> do cameraId <- getVarInt return $ ClientBoundCamera cameraId 0x37 -> do slot <- getInt8 return $ ClientBoundHeldItemSlot slot 0x38 -> do position <- getInt8 name <- getText return $ ClientBoundScoreboardDisplayObjective position name 0x39 -> do entityId <- getVarInt metadata <- getEntityMetadata return $ ClientBoundEntityMetadata entityId metadata 0x3a -> do entityId <- getInt32 vehicleId <- getInt32 return $ ClientBoundAttachEntity entityId vehicleId 0x3b -> do entityId <- getVarInt velocityX <- getInt16 velocityY <- getInt16 velocityZ <- getInt16 return $ ClientBoundEntityVelocity entityId velocityX velocityY velocityZ 0x3c -> do entityId <- getVarInt slot <- getVarInt item <- getSlot return $ ClientBoundEntityEquipment entityId slot item 0x3d -> do experienceBar <- getFloat level <- getVarInt totalExperience <- getVarInt return $ ClientBoundExperience experienceBar level totalExperience 0x3e -> do health <- getFloat food <- getVarInt foodSaturation <- getFloat return $ ClientBoundUpdateHealth health food foodSaturation 0x3f -> do name <- getText action <- getInt8 let displayText = case action of 0 -> 2 -> _ -> let pType = case action of 0 -> 2 -> _ -> return $ ClientBoundScoreboardObjective name action displayText pType 0x40 -> do entityId <- getVarInt passengers <- getArray return $ ClientBoundSetPassengers entityId passengers 0x41 -> do team <- getText mode <- getInt8 let name = case mode of 0 -> 2 -> _ -> let prefix = case mode of 0 -> 2 -> _ -> let suffix = case mode of 0 -> 2 -> _ -> let friendlyFire = case mode of 0 -> 2 -> _ -> let nameTagVisibility = case mode of 0 -> 2 -> _ -> let collisionRule = case mode of 0 -> 2 -> _ -> let color = case mode of 0 -> 2 -> _ -> let players = case mode of 0 -> 4 -> 3 -> _ -> return $ ClientBoundTeams team mode name prefix suffix friendlyFire nameTagVisibility collisionRule color players 0x42 -> do itemName <- getText action <- getInt8 scoreName <- getText let value = case action of 1 -> _ -> return $ ClientBoundScoreboardScore itemName action scoreName value 0x43 -> do location <- getPosition return $ ClientBoundSpawnPosition location 0x44 -> do age <- getInt64 time <- getInt64 return $ ClientBoundUpdateTime age time 0x45 -> do action <- getVarInt let text = case action of 0 -> 1 -> _ -> let fadeIn = case action of 2 -> _ -> let stay = case action of 2 -> _ -> let fadeOut = case action of 2 -> _ -> return $ ClientBoundTitle action text fadeIn stay fadeOut 0x46 -> do location <- getPosition text1 <- getText text2 <- getText text3 <- getText text4 <- getText return $ ClientBoundUpdateSign location text1 text2 text3 text4 0x47 -> do soundId <- getVarInt soundCatagory <- getVarInt x <- getInt32 y <- getInt32 z <- getInt32 volume <- getFloat pitch <- getWord8 return $ ClientBoundSoundEffect soundId soundCatagory x y z volume pitch 0x48 -> do header <- getText footer <- getText return $ ClientBoundPlayerlistHeader header footer 0x49 -> do collectedEntityId <- getVarInt collectorEntityId <- getVarInt return $ ClientBoundCollect collectedEntityId collectorEntityId 0x4a -> do entityId <- getVarInt x <- getDouble y <- getDouble z <- getDouble yaw <- getInt8 pitch <- getInt8 onGround <- getBool return $ ClientBoundEntityTeleport entityId x y z yaw pitch onGround 0x4b -> do entityId <- getVarInt properties <- getArray return $ ClientBoundEntityUpdateAttributes entityId properties 0x4c -> do entityId <- getVarInt effectId <- getInt8 amplifier <- getInt8 duration <- getVarInt hideParticles <- getInt8 return $ ClientBoundEntityEffect entityId effectId amplifier duration hideParticles instance Serialize ServerBoundPlayPacket where put (ServerBoundTeleportConfirm teleportId) = do putWord8 0x00 putVarInt teleportId put (ServerBoundTabComplete text assumeCommand lookedAtBlock) = do putWord8 0x01 putText text putBool assumeCommand case lookedAtBlock of Just lookedAtBlock' -> putPosition lookedAtBlock' Nothing -> return () put (ServerBoundChat message) = do putWord8 0x02 putText message put (ServerBoundClientCommand actionId) = do putWord8 0x03 putVarInt actionId put (ServerBoundSettings locale viewDistance chatFlags chatColors skinParts mainHand) = do putWord8 0x04 putText locale putInt8 viewDistance putVarInt chatFlags putBool chatColors putWord8 skinParts putVarInt mainHand put (ServerBoundTransaction windowId action accepted) = do putWord8 0x05 putInt8 windowId putInt16 action putBool accepted put (ServerBoundEnchantItem windowId enchantment) = do putWord8 0x06 putInt8 windowId putInt8 enchantment put (ServerBoundWindowClick windowId slot mouseButton action mode item) = do putWord8 0x07 putWord8 windowId putInt16 slot putInt8 mouseButton putInt16 action putInt8 mode putSlot item put (ServerBoundCloseWindow windowId) = do putWord8 0x08 putWord8 windowId put (ServerBoundCustomPayload channel pData) = do putWord8 0x09 putText channel putRestBuffer pData put (ServerBoundUseEntity target mouse x y z hand) = do putWord8 0x0a putVarInt target putVarInt mouse case x of Just x' -> putFloat x' Nothing -> return () case y of Just y' -> putFloat y' Nothing -> return () case z of Just z' -> putFloat z' Nothing -> return () case hand of Just hand' -> putVarInt hand' Nothing -> return () put (ServerBoundKeepAlive keepAliveId) = do putWord8 0x0b putVarInt keepAliveId put (ServerBoundPosition x y z onGround) = do putWord8 0x0c putDouble x putDouble y putDouble z putBool onGround put (ServerBoundPositionLook x y z yaw pitch onGround) = do putWord8 0x0d putDouble x putDouble y putDouble z putFloat yaw putFloat pitch putBool onGround put (ServerBoundLook yaw pitch onGround) = do putWord8 0x0e putFloat yaw putFloat pitch putBool onGround put (ServerBoundFlying onGround) = do putWord8 0x0f putBool onGround put (ServerBoundVehicleMove x y z yaw pitch) = do putWord8 0x10 putDouble x putDouble y putDouble z putFloat yaw putFloat pitch put (ServerBoundSteerBoat unknown1 unknown2) = do putWord8 0x11 putBool unknown1 putBool unknown2 put (ServerBoundAbilities flags flyingSpeed walkingSpeed) = do putWord8 0x12 putInt8 flags putFloat flyingSpeed putFloat walkingSpeed put (ServerBoundBlockDig status location face) = do putWord8 0x13 putInt8 status putPosition location putInt8 face put (ServerBoundEntityAction entityId actionId jumpBoost) = do putWord8 0x14 putVarInt entityId putVarInt actionId putVarInt jumpBoost put (ServerBoundSteerVehicle sideways forward jump) = do putWord8 0x15 putFloat sideways putFloat forward putWord8 jump put (ServerBoundResourcePackReceive hash result) = do putWord8 0x16 putText hash putVarInt result put (ServerBoundHeldItemSlot slotId) = do putWord8 0x17 putInt16 slotId put (ServerBoundSetCreativeSlot slot item) = do putWord8 0x18 putInt16 slot putSlot item put (ServerBoundUpdateSign location text1 text2 text3 text4) = do putWord8 0x19 putPosition location putText text1 putText text2 putText text3 putText text4 put (ServerBoundArmAnimation hand) = do putWord8 0x1a putVarInt hand put (ServerBoundSpectate target) = do putWord8 0x1b putUUID target put (ServerBoundBlockPlace location direction hand cursorX cursorY cursorZ) = do putWord8 0x1c putPosition location putVarInt direction putVarInt hand putInt8 cursorX putInt8 cursorY putInt8 cursorZ put (ServerBoundUseItem hand) = do putWord8 0x1d putVarInt hand get = do packetId <- getWord8 case packetId of 0x00 -> do teleportId <- getVarInt return $ ServerBoundTeleportConfirm teleportId 0x01 -> do text <- getText assumeCommand <- getBool let lookedAtBlock = case of _ -> return $ ServerBoundTabComplete text assumeCommand lookedAtBlock 0x02 -> do message <- getText return $ ServerBoundChat message 0x03 -> do actionId <- getVarInt return $ ServerBoundClientCommand actionId 0x04 -> do locale <- getText viewDistance <- getInt8 chatFlags <- getVarInt chatColors <- getBool skinParts <- getWord8 mainHand <- getVarInt return $ ServerBoundSettings locale viewDistance chatFlags chatColors skinParts mainHand 0x05 -> do windowId <- getInt8 action <- getInt16 accepted <- getBool return $ ServerBoundTransaction windowId action accepted 0x06 -> do windowId <- getInt8 enchantment <- getInt8 return $ ServerBoundEnchantItem windowId enchantment 0x07 -> do windowId <- getWord8 slot <- getInt16 mouseButton <- getInt8 action <- getInt16 mode <- getInt8 item <- getSlot return $ ServerBoundWindowClick windowId slot mouseButton action mode item 0x08 -> do windowId <- getWord8 return $ ServerBoundCloseWindow windowId 0x09 -> do channel <- getText pData <- getRestBuffer return $ ServerBoundCustomPayload channel pData 0x0a -> do target <- getVarInt mouse <- getVarInt let x = case mouse of 2 -> _ -> let y = case mouse of 2 -> _ -> let z = case mouse of 2 -> _ -> let hand = case mouse of 0 -> 2 -> _ -> return $ ServerBoundUseEntity target mouse x y z hand 0x0b -> do keepAliveId <- getVarInt return $ ServerBoundKeepAlive keepAliveId 0x0c -> do x <- getDouble y <- getDouble z <- getDouble onGround <- getBool return $ ServerBoundPosition x y z onGround 0x0d -> do x <- getDouble y <- getDouble z <- getDouble yaw <- getFloat pitch <- getFloat onGround <- getBool return $ ServerBoundPositionLook x y z yaw pitch onGround 0x0e -> do yaw <- getFloat pitch <- getFloat onGround <- getBool return $ ServerBoundLook yaw pitch onGround 0x0f -> do onGround <- getBool return $ ServerBoundFlying onGround 0x10 -> do x <- getDouble y <- getDouble z <- getDouble yaw <- getFloat pitch <- getFloat return $ ServerBoundVehicleMove x y z yaw pitch 0x11 -> do unknown1 <- getBool unknown2 <- getBool return $ ServerBoundSteerBoat unknown1 unknown2 0x12 -> do flags <- getInt8 flyingSpeed <- getFloat walkingSpeed <- getFloat return $ ServerBoundAbilities flags flyingSpeed walkingSpeed 0x13 -> do status <- getInt8 location <- getPosition face <- getInt8 return $ ServerBoundBlockDig status location face 0x14 -> do entityId <- getVarInt actionId <- getVarInt jumpBoost <- getVarInt return $ ServerBoundEntityAction entityId actionId jumpBoost 0x15 -> do sideways <- getFloat forward <- getFloat jump <- getWord8 return $ ServerBoundSteerVehicle sideways forward jump 0x16 -> do hash <- getText result <- getVarInt return $ ServerBoundResourcePackReceive hash result 0x17 -> do slotId <- getInt16 return $ ServerBoundHeldItemSlot slotId 0x18 -> do slot <- getInt16 item <- getSlot return $ ServerBoundSetCreativeSlot slot item 0x19 -> do location <- getPosition text1 <- getText text2 <- getText text3 <- getText text4 <- getText return $ ServerBoundUpdateSign location text1 text2 text3 text4 0x1a -> do hand <- getVarInt return $ ServerBoundArmAnimation hand 0x1b -> do target <- getUUID return $ ServerBoundSpectate target 0x1c -> do location <- getPosition direction <- getVarInt hand <- getVarInt cursorX <- getInt8 cursorY <- getInt8 cursorZ <- getInt8 return $ ServerBoundBlockPlace location direction hand cursorX cursorY cursorZ 0x1d -> do hand <- getVarInt return $ ServerBoundUseItem hand
oldmanmike/hs-minecraft-protocol
src/Data/Minecraft/Release19/Protocol.hs
bsd-3-clause
53,029
112
14
15,962
12,535
5,806
6,729
-1
-1
{-# LANGUAGE CPP #-} module Main ( main ) where import Control.Monad ( mplus, mzero ) import Control.Monad.Search import Data.Semigroup as Sem #if MIN_VERSION_tasty_hspec(1,1,7) import Test.Hspec #endif import Test.Tasty import Test.Tasty.Hspec data Side = L | R deriving (Eq, Show) newtype C = C Int deriving (Eq, Ord, Show) instance Sem.Semigroup C where (C l) <> (C r) = C (l + r) instance Monoid C where mempty = C 0 #if !(MIN_VERSION_base(4,11,0)) mappend = (<>) #endif testSearch :: Search C Side -> [(C, Side)] testSearch = runSearch testSearchIO :: SearchT C IO Side -> IO (Maybe (C, Side)) testSearchIO = runSearchBestT infiniteSearch :: Monad m => SearchT C m Side infiniteSearch = return L `mplus` (cost' (C 1) >> infiniteSearch) spec :: IO TestTree spec = testSpec "Control.Monad.Search" $ do it "Monad return generates one result" $ testSearch (return L) `shouldBe` [ (C 0, L) ] it "MonadPlus mzero has no result" $ testSearch mzero `shouldBe` [] it "MonadPlus left identity law" $ testSearch (mzero `mplus` return L) `shouldBe` [ (C 0, L) ] it "MonadPlus right identity law" $ testSearch (return L `mplus` mzero) `shouldBe` [ (C 0, L) ] it "MonadPlus left distribution law" $ testSearch (return L `mplus` return R) `shouldBe` [ (C 0, L), (C 0, R) ] it "Results are ordered by cost" $ do testSearch (return L `mplus` (cost' (C 1) >> return R)) `shouldBe` [ (C 0, L), (C 1, R) ] testSearch ((cost' (C 1) >> return L) `mplus` return R) `shouldBe` [ (C 0, R), (C 1, L) ] it "Collapse suppresses results with higher cost" $ testSearch ((collapse >> return L) `mplus` (cost' (C 1) >> return R)) `shouldBe` [ (C 0, L) ] it "Collapse can be limited in scope" $ testSearch (seal ((collapse >> return L) `mplus` (cost' (C 1) >> return R)) `mplus` (cost' (C 2) >> return R)) `shouldBe` [ (C 0, L), (C 2, R) ] it "Results are generated lazily" $ do head (testSearch (return L `mplus` (cost' (C 1) >> error "not lazy right"))) `shouldBe` (C 0, L) head (testSearch ((cost' (C 1) >> error "not lazy left") `mplus` return R)) `shouldBe` (C 0, R) it "Results are generated lazily (infinite)" $ head (testSearch infiniteSearch) `shouldBe` (C 0, L) it "Results are generated in constant space / linear time" $ testSearch infiniteSearch !! 10000 `shouldBe` (C 10000, L) it "Results are generated lazily in IO" $ do testSearchIO (return L `mplus` (cost' (C 1) >> error "not lazy right")) `shouldReturn` Just (C 0, L) testSearchIO ((cost' (C 1) >> error "not lazy left") `mplus` return R) `shouldReturn` Just (C 0, R) it "Results are generated lazily in IO (infinite)" $ testSearchIO infiniteSearch `shouldReturn` Just (C 0, L) main :: IO () main = do spec' <- spec defaultMain spec'
ennocramer/monad-dijkstra
test/Main.hs
bsd-3-clause
3,250
0
21
1,041
1,197
629
568
73
1
{-# LANGUAGE NoMonomorphismRestriction #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE RecordWildCards #-} module Main where ------------------------------------------------------------------- import qualified Control.Exception.Lifted as E import Control.Monad (when) import qualified Data.ByteString as B import qualified Data.DList as DL import Data.List (intersperse) import qualified Data.Text as T import qualified Data.Text.IO as T import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef) import Control.Monad (void) import Git (withRepository) import Git.Libgit2 (lgFactory) import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Trans.Control (MonadBaseControl) import Options.Applicative (execParser) import Data.Version (showVersion) import System.Process (createProcess, proc, CreateProcess(std_in), StdStream(..), waitForProcess, env) import System.Environment (getEnvironment) import System.IO (hClose, Handle, stderr, stdin, stdout) import System.Exit (exitFailure) import GHC.IO.Exception (IOErrorType(ResourceVanished), IOException(ioe_type)) ---- import Paths_fancydiff (version) import Fancydiff.Lib (tryDiffWithSourceHighlight, commitHighlight, getHighlighterByFilename, getHighlighterFunc, getHighlighterFuncByFilename) import Fancydiff.Formatting (fshow) import qualified Fancydiff.SourceHighlight as SH import Fancydiff.AnsiFormatting (ansiFormatting) import Fancydiff.HTMLFormatting ( htmlFormatting , mkHtmlFormat , HTMLStyle(..) , HTMLFormat(fmtCSS) ) import Lib.Text (safeDecode) import Lib.Git (git') import qualified Spec as Spec import qualified Internal.Version as V import Internal.Opts ------------------------------------------------------------------- iterHandleLines :: (MonadBaseControl IO m, MonadIO m) => Handle -> (B.ByteString -> m ()) -> m () -> m () iterHandleLines handle onLine onEnd = loop where loop = do let g = do l <- liftIO $ B.hGetLine handle return $ Just l onErr = \(e :: E.SomeException) -> do when (not ("end of file" `T.isSuffixOf` (T.pack $ show e))) $ do liftIO $ print e return $ Nothing r <- E.catch g onErr case r of Nothing -> onEnd Just line -> onLine line >> loop groupHandleByPred :: (MonadBaseControl IO m, MonadIO m) => Handle -> (B.ByteString -> Bool) -> ([B.ByteString] -> m ()) -> m () groupHandleByPred handle pred' cb = do linesI <- liftIO $ newIORef DL.empty let onLine line = do when (pred' line) $ flush liftIO $ modifyIORef' linesI (flip DL.snoc line) onEnd = flush flush = do lines' <- fmap DL.toList $ liftIO $ readIORef linesI liftIO $ writeIORef linesI DL.empty when (not . null $ lines' ) $ do cb lines' iterHandleLines handle onLine onEnd getVersion :: T.Text getVersion = T.concat [T.pack $ showVersion version, V.version] mainOpts :: Opts -> IO () mainOpts opts@Opts{..} = do if | optGetVersion -> T.putStrLn $ T.concat ["Fancydiff ", getVersion] | optTestingMode -> Spec.main mainOpts opts | otherwise -> case optCommand of Nothing -> do T.hPutStrLn stderr $ "fancydiff: no command specified (see --help)" exitFailure Just cmnd -> case optPager of Nothing -> onCmd (fmtToFunc optOutputFormat optPalette) cmnd stdout Just Less -> do curEnv <- getEnvironment (Just handleOutToLess, _, _, handle) <- createProcess (proc "less" ["-R"]) { std_in = CreatePipe , env = Just (("LESSANSIENDCHARS", "mK") : curEnv) } let act = do onCmd (fmtToFunc optOutputFormat optPalette) cmnd handleOutToLess act `E.catch` resourceVanished hClose handleOutToLess `E.catch` resourceVanished _ <- waitForProcess handle return () where fmtToFunc ANSI theme = ansiFormatting theme fmtToFunc (HTML htmlstyle) theme = let func fl = htmlFormatting format fl format = mkHtmlFormat htmlstyle theme in func fmtToFunc Meta _ = fshow resourceVanished e = if ioe_type e == ResourceVanished then return () else ioError e formatOne fmt content outHandle func = do let highlighted = func (safeDecode content) case highlighted of Left err -> do T.hPutStrLn stderr $ T.pack err exitFailure Right ok -> liftIO $ T.hPutStr outHandle $ fmt ok formatOneHighlighter fmt outHandle highlighter = do content <- B.hGetContents stdin formatOne fmt content outHandle (getHighlighterFunc highlighter) onCmd _ (Setup onlyAliases isLocal) _ = do let git'print params = do T.putStrLn $ T.concat $ ["Running: "] ++ (intersperse " " $ map onParam params) git' params onParam param | T.filter (== ' ') param == "" = param | otherwise = T.concat ["\"", param, "\""] gitconfig p = if isLocal then git'print $ ["config"] ++ p else git'print $ ["config", "--global"] ++ p case onlyAliases of False -> do gitconfig ["color.diff", "off"] gitconfig ["pager.log", "fancydiff stdin --pager=less"] gitconfig ["pager.show", "fancydiff stdin --pager=less"] gitconfig ["pager.diff", "fancydiff stdin --pager=less"] True -> do gitconfig ["alias.log-fancy", "!git -c color.diff=off -c pager.log='fancydiff stdin --pager=less' log $@"] gitconfig ["alias.show-fancy", "!git -c color.diff=off -c pager.show='fancydiff stdin --pager=less' show $@"] gitconfig ["alias.diff-fancy", "!git -c color.diff=off -c pager.diff='fancydiff stdin --pager=less' diff $@"] putStrLn "You are now ready to use Fancydiff" onCmd _ MakeSCSS outHandle = do case fmtCSS $ mkHtmlFormat HTMLSCSS optPalette of Just css -> do T.hPutStr outHandle css return () Nothing -> return () onCmd fmt (OneFile filepath exitStatusForUnrecognizedFile) outHandle = do let highlighter = getHighlighterByFilename (T.pack filepath) let highlighterFunc = getHighlighterFuncByFilename (T.pack filepath) case (exitStatusForUnrecognizedFile, highlighter) of (True, SH.Generic) -> exitFailure _ -> do content <- B.readFile filepath formatOne fmt content outHandle highlighterFunc onCmd fmt (Stdin Nothing Nothing) outHandle = do let path = "." withRepository lgFactory path $ do let diffStart = B.isPrefixOf "diff " commitStart = B.isPrefixOf "commit " groupHandleByPred stdin (\l -> diffStart l || commitStart l) $ \lineList -> do let chunk = safeDecode $ B.concat $ concat $ map (\x -> [x, "\n"]) lineList firstLine = head lineList res <- if | diffStart firstLine -> tryDiffWithSourceHighlight chunk | commitStart firstLine -> commitHighlight chunk | otherwise -> tryDiffWithSourceHighlight chunk liftIO $ T.hPutStr outHandle $ fmt res return () onCmd fmt (Stdin (Just highlighter) Nothing) outHandle = do formatOneHighlighter fmt outHandle highlighter onCmd fmt (Stdin _ (Just filename)) outHandle = do let highlighter = getHighlighterByFilename $ T.pack filename case highlighter of SH.Generic -> exitFailure _ -> formatOneHighlighter fmt outHandle highlighter main :: IO () main = void $ execParser optsParser >>= mainOpts
da-x/fancydiff
app/Main.hs
bsd-3-clause
10,321
0
24
4,480
2,234
1,138
1,096
176
21
{- <TEST> {- MISSING HASH #-} -- {-# MISSING HASH #-} <COMMENT> {- INLINE X -} {- INLINE Y -} -- {-# INLINE Y #-} {- INLINE[~k] f -} -- {-# INLINE[~k] f #-} {- NOINLINE Y -} -- {-# NOINLINE Y #-} {- UNKNOWN Y -} <COMMENT> INLINE X </TEST> -} module Hint.Comment(commentHint) where import Hint.Type import Data.Char import Data.List.Extra import Refact.Types(Refactoring(ModifyComment)) import GHC.Types.SrcLoc import GHC.Parser.Annotation import GHC.Util directives :: [String] directives = words $ "LANGUAGE OPTIONS_GHC INCLUDE WARNING DEPRECATED MINIMAL INLINE NOINLINE INLINABLE " ++ "CONLIKE LINE SPECIALIZE SPECIALISE UNPACK NOUNPACK SOURCE" commentHint :: ModuHint commentHint _ m = concatMap chk (ghcComments m) where chk :: LEpaComment -> [Idea] chk comm | isMultiline, "#" `isSuffixOf` s && not ("#" `isPrefixOf` s) = [grab "Fix pragma markup" comm $ '#':s] | isMultiline, name `elem` directives = [grab "Use pragma syntax" comm $ "# " ++ trim s ++ " #"] where isMultiline = isCommentMultiline comm s = commentText comm name = takeWhile (\x -> isAlphaNum x || x == '_') $ trimStart s chk _ = [] grab :: String -> LEpaComment -> String -> Idea grab msg o@(L pos _) s2 = let s1 = commentText o loc = RealSrcSpan (anchor pos) Nothing in rawIdea Suggestion msg loc (f s1) (Just $ f s2) [] (refact loc) where f s = if isCommentMultiline o then "{-" ++ s ++ "-}" else "--" ++ s refact loc = [ModifyComment (toRefactSrcSpan loc) (f s2)]
ndmitchell/hlint
src/Hint/Comment.hs
bsd-3-clause
1,659
0
15
463
450
237
213
29
3
{-# LANGUAGE OverloadedStrings #-} module Cda.Handlers where -- import qualified Snap.Core as S import Control.Monad.IO.Class as LIO import Snap.Core import Snap import Snap.Util.FileUploads import Snap.Snaplet import Snap.Snaplet.Heist -- import Snap.Snaplet.Session -- import qualified Data.ByteString as BS -- import qualified Data.ByteString.Char8 as S -- import qualified Data.String.UTF8 as T8 -- import Data.String.Conversions -- import Data.Maybe ( fromJust ) -- import qualified Data.Text as T -- import Heist -- import Data.Monoid -- import qualified Heist.Interpreted as I -- import qualified Heist.Compiled as C -- import qualified Text.XmlHtml as X -- import Control.Applicative -- import Text.Digestive -- import Text.Digestive.Heist -- import qualified Text.Digestive.Snap as DS -- import qualified Data.Aeson as A -- import System.Directory -- getTemporaryDirectory :: IO FilePath import qualified Data.Text as T import Text.XML.Expat.Tree -- import Text.XML.Expat.Format import Text.XML.Expat.Proc -- import System.Environment -- import System.Exit import System.IO import qualified Data.ByteString.Lazy as L import Data.Maybe ( fromJust, maybe ) -- import Control.Monad -- import Data.Monoid -- import qualified Text.XML.Expat.Lens.Unqualified as XL -- import Control.Lens -- import Data.Default (def) import Heist import qualified Heist.Compiled as C import qualified Heist.Compiled.LowLevel as LL import Application ------------------------------------------------------------------------ cdaBase :: AppHandler () cdaBase = cRender "index" uploadHandler :: Handler App App () uploadHandler = method GET $ cRender "upload" maxMb = 2 megaByte = 2^(20::Int) cdaDefaultPolicy :: UploadPolicy cdaDefaultPolicy = setMaximumFormInputSize (maxMb * megaByte) defaultUploadPolicy cdaPerPartPolicy :: PartInfo -> PartUploadPolicy cdaPerPartPolicy _ = allowWithMaximumSize (maxMb * megaByte) {- data PartInfo = PartInfo { partFieldName :: !ByteString , partFileName :: !(Maybe ByteString) , partContentType :: !ByteString } -} -- createDirectoryIfMissing:: Bool -> FilePath -> IO () and -- getAppUserDataDirectory :: String -> IO FilePath. tempDir::String tempDir = "tmp" cdaUploadHandler :: (Monad m, MonadIO m) => [(PartInfo, Either PolicyViolationException FilePath)] -> m (Maybe T.Text) cdaUploadHandler xs = handleOne $ head (filter wanted xs) where wanted (_ , Right _) = True wanted (_ , Left _) = False handleOne (partInfo, Right filepath) = cdaRender partInfo filepath cdaRender:: (Monad m, MonadIO m) => PartInfo -> FilePath -> m (Maybe T.Text) cdaRender partInfo filepath = do inputText <- LIO.liftIO $ L.readFile filepath let (xml, mErr) = parse defaultParseOptions inputText :: (UNode T.Text, Maybe XMLParseError) case mErr of Nothing -> return Nothing Just err -> return $ Just $ T.pack $ "XML parse failed: "++ show err runtimeUpload :: (Monad m, MonadSnap m, MonadIO m) => RuntimeSplice m (Maybe T.Text) runtimeUpload = do s <- lift $ handleFileUploads tempDir cdaDefaultPolicy cdaPerPartPolicy cdaUploadHandler return s uplRTSplices :: (Monad m, MonadSnap m) => Splices (C.Splice m) uplRTSplices = do "upload" ## runtimeValue runtimeUpload -- "runtimeB" ## runtimeValue runtimeB runtimeValue :: Monad m => RuntimeSplice m (Maybe T.Text) -> C.Splice m runtimeValue runtime = do -- a compiled splice for a static template (will be used in the Nothing case) nothing <- C.callTemplate "success" promise <- LL.newEmptyPromise valueSplice <- getValueSplice (LL.getPromise promise) -- The 'do' block below has a value of type: -- RuntimeSplice n Builder -> DList (Chunk n) let builder = C.yieldRuntime $ do value <- runtime case value of -- in the Nothing case we convert the template splice to a builder Nothing -> C.codeGen nothing -- in the Just case we put the extracted Text value in a promise -- first, then convert the compiled value splice to a builder Just v -> do LL.putPromise promise v C.codeGen valueSplice -- our builder has the type DList (Chunk n), and remember that: -- type Splice n = HeistT n IO (DList (Chunk n)) -- so returning this value to the current monad finally creates the fully -- compiled splice we needed return builder getValueSplice :: Monad m => RuntimeSplice m T.Text -> C.Splice m getValueSplice = C.withSplices template local where template = C.callTemplate "parser_error" local = "error" ## C.pureSplice . C.textSplice $ id {- ------------------------------------------------------------------------------- -- | Handle Ajax page ajaxHandler :: Handler App Ajax () ajaxHandler = do page <- getParam "page" case page of Just page -> let p = ("ajax/"::BS.ByteString) <> page in render p Nothing -> return () ------------------------------------------------------------------------------- -}
SLikhachev/pureCdaViewer
snaplets/cda/src/Cda/arx/_cmp_Handlers.hs
bsd-3-clause
5,088
0
19
1,006
907
491
416
-1
-1
{-# LANGUAGE OverloadedStrings #-} module Trombone.Db.Execute ( SqlT , runDb , collection , item , executeCount , void , toJsonVal ) where import Control.Arrow ( second ) import Control.Exception ( Exception, SomeException(..), fromException ) import Control.Exception.Lifted ( try ) import Control.Monad ( liftM ) import Control.Monad.Logger ( NoLoggingT, runNoLoggingT ) import Control.Monad.Trans.Resource import Data.Aeson import Data.Conduit import Data.List import Data.List.Utils ( split ) import Data.Maybe ( fromMaybe, listToMaybe ) import Data.Scientific ( fromFloatDigits ) import Data.Text ( Text, pack ) import Data.Text.Encoding ( decodeUtf8 ) import Database.Persist import Database.Persist.Postgresql import Database.PostgreSQL.Simple ( SqlError(..), ExecStatus(..) ) import GHC.IO.Exception import Text.ParserCombinators.ReadP import Text.Read.Lex hiding ( String, Number ) import qualified Data.Conduit.List as CL import qualified Data.HashMap.Strict as HMS import qualified Data.List.Utils as U import qualified Data.Vector as Vect -- | Database monad transformer stack. type SqlT = SqlPersistT (ResourceT (NoLoggingT IO)) -- | Run a database query and return the result in the IO monad. -- -- Example use: -- runDb (collection "SELECT * FROM customer") pool >>= print runDb :: SqlT a -> ConnectionPool -> IO a runDb sql = catchExceptions . runNoLoggingT . runResourceT . runSqlPool sql source :: Text -> Source SqlT [PersistValue] {-# INLINE source #-} source = flip rawQuery [] conduit :: Monad m => [Text] -> Conduit [PersistValue] m Value conduit xs = CL.map $ Object . HMS.fromList . zip xs . map toJsonVal collection :: Text -> [Text] -> SqlT [Value] collection q xs = source q $$ conduit xs =$ CL.consume item :: Text -> [Text] -> SqlT (Maybe Value) item q = liftM listToMaybe . collection q executeCount :: Text -> SqlT Int executeCount query = liftM fromIntegral $ rawExecuteCount query [] void :: Text -> SqlT () {-# INLINE void #-} void query = rawExecute query [] catchExceptions :: IO a -> IO a catchExceptions sql = try sql >>= excp where excp (Right r) = return r excp (Left (IOError _ _ _ m _ _)) | "PGRES_FATAL_ERROR" `isInfixOf` m = let s = U.replace "\"))" "" $ unescape $ U.split "ERROR:" m !! 1 in error ("PGRES_FATAL_ERROR: " ++ s) | otherwise = error $ head $ lines m unescape :: String -> String unescape xs | [] <- r = [] | [(a,_)] <- r = a where r = readP_to_S (manyTill lexChar eof) xs ------------------------------------------------------------------------------- -- Type conversion helper functions ------------------------------------------------------------------------------- -- | Translate a PersistValue to a JSON Value. toJsonVal :: PersistValue -> Value toJsonVal pv = case pv of PersistText t -> String t PersistBool b -> Bool b PersistByteString b -> String $ decodeUtf8 b PersistInt64 n -> Number $ fromIntegral n PersistDouble d -> Number $ fromFloatDigits d PersistRational r -> Number $ fromRational r PersistMap m -> fromMap m PersistUTCTime u -> showV u PersistTimeOfDay t -> showV t PersistDay d -> showV d PersistList xs -> fromList_ xs PersistNull -> Null _ -> String "[unsupported SQL type]" where showV :: Show a => a -> Value showV = String . pack . show fromList_ :: [PersistValue] -> Value {-# INLINE fromList_ #-} fromList_ = Array . Vect.fromList . map toJsonVal fromMap :: [(Text, PersistValue)] -> Value {-# INLINE fromMap #-} fromMap = Object . HMS.fromList . map (second toJsonVal)
johanneshilden/trombone
Trombone/Db/Execute.hs
bsd-3-clause
4,422
0
16
1,499
1,111
592
519
86
13
module Main where import Test.DocTest main :: IO () main = doctest ["Util/Sort.hs"]
exKAZUu/haskell-dev-env
Test/Doctests.hs
bsd-3-clause
86
0
6
15
30
17
13
4
1
{-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} ------------------------------------------------------------------------------ -- | -- Module : Cmd -- Copyright : (C) 2014 Samuli Thomasson -- License : BSD-style (see the file LICENSE) -- Maintainer : Samuli Thomasson <samuli.thomasson@paivola.fi> -- Stability : experimental -- Portability : non-portable ------------------------------------------------------------------------------ module Cmd where import ClassyPrelude import System.Console.CmdArgs import Database.Persist.Quasi (psToDBName, lowerCaseSettings) import Data.Aeson (FromJSON, ToJSON) import Data.Aeson.TH (deriveJSON, Options(..), defaultOptions) #define __COMMON_FLAGS configFile, dbFile, hummingUser :: Maybe Text #define __ANIMU_FILTERS \ watchingStatusFilter :: [WatchingStatus], \ titleStatusFilter :: [TitleStatus], \ matching :: [Text], \ ignoring :: [Text] -- | Misnamed command line data Animu = Status { __COMMON_FLAGS , services :: [Service] , createConfig :: Bool } | Search { __COMMON_FLAGS, __ANIMU_FILTERS , services :: [Service] , terms :: [Text] , category :: Category } | Sync { __COMMON_FLAGS, __ANIMU_FILTERS , services :: [Service] , noDownload :: Bool } | Mv { __COMMON_FLAGS , terms :: [Text] , dest :: Maybe Text } | Import { __COMMON_FLAGS , terms :: [Text] , dest :: Maybe Text , noMove :: Bool , recursive :: Bool } | Set { __COMMON_FLAGS , terms :: [Text] , services :: [Service] , status :: WatchingStatus } | Inc { __COMMON_FLAGS , terms :: [Text] , count :: Int } | List { __COMMON_FLAGS, __ANIMU_FILTERS } | Check { __COMMON_FLAGS, __ANIMU_FILTERS , services :: [Service] , autofix :: Bool , addWith :: WatchingStatus , force :: Bool } | Watch { __COMMON_FLAGS , terms :: [Text] , till :: Int , next :: Int } | Files { __COMMON_FLAGS } deriving (Data, Typeable) data TitleStatus = FinishedAiring | CurrentlyAiring | NotYetAired deriving (Enum, Bounded, Typeable, Data) data WatchingStatus = PlanToWatch | Watching | Completed | OnHold | Dropped deriving (Enum, Bounded, Eq, Typeable, Data) data Service = Library | Nyaa | Hummingbird | Bakabt deriving (Show, Eq, Enum, Bounded, Typeable, Data) newtype Category = Category Text deriving (Data, Typeable, Show, FromJSON, ToJSON) -- Instances -- | Note that this instance stands for humming and db encoding as well instance Show WatchingStatus where show Watching = "currently-watching" show PlanToWatch = "plan-to-watch" show Completed = "completed" show OnHold = "on-hold" show Dropped = "dropped" instance Show TitleStatus where show FinishedAiring = "Finished Airing" show CurrentlyAiring = "Currently Airing" show NotYetAired = "Not Yet Aired" instance Default Category where def = Category "anime_eng" $(deriveJSON defaultOptions{fieldLabelModifier = unpack . psToDBName lowerCaseSettings . pack} ''TitleStatus) $(deriveJSON defaultOptions{fieldLabelModifier = unpack . psToDBName lowerCaseSettings . pack} ''WatchingStatus) -- * cmdargs config -- #define __COMMON \ configFile = def &= help "Specify a different configuration file" &= typFile &= explicit &= name "config", \ dbFile = def &= help "Specify different database file" &= typFile &= explicit &= name "database", \ hummingUser = def &= help "Hummingbird.me username" &= typ "USERNAME" &= explicit &= name "humming-username" #define __SERVICES services = enum \ [ [] &= ignore \ , [Library] &= help "Enable library actions" &= explicit &= name "library" &= name "L" \ , [Hummingbird] &= help "Enable hummingbird actions" &= explicit &= name "hummingbird" &= name "H" \ , [Nyaa] &= help "Enable nyaa actions" &= explicit &= name "nyaa" &= name "N" \ , [Bakabt] &= help "Enable bakabt actions" &= explicit &= name "bakabt" &= name "B" \ ] #define __FILTERS \ matching = def &= help "Operate only on matching items" &= typPattern \ , ignoring = def &= help "Do nothing with matching items" &= typPattern \ , watchingStatusFilter = enum \ [ [] &= ignore \ , [Watching] &= help "Show watching (default)" &= explicit &= name "watching" &= name "w" \ , [PlanToWatch] &= help "Show plan-to-watch" &= explicit &= name "plan-to-watch" &= name "p" \ , [Completed] &= help "Show completed" &= explicit &= name "completed" &= name "c" \ , [OnHold] &= help "Show on-hold" &= explicit &= name "on-hold" &= name "o" \ , [Dropped] &= help "Show dropped" &= explicit &= name "dropped" &= name "d" \ , [PlanToWatch .. Dropped] &= help "Show all" &= explicit &= name "any-status" &= name "a" \ ] \ , titleStatusFilter = enum \ [ [] &= ignore \ , [FinishedAiring] &= help "Finished airing" &= explicit &= name "finished" \ , [CurrentlyAiring] &= help "Currently airing" &= explicit &= name "airing" \ , [NotYetAired] &= help "Not yet aired" &= explicit &= name "not-yet-aired" \ ] cmdConf :: Animu cmdConf = modes -- NOTE: refrain from specfifying the same field twice with same -- annotations; it breaks stuff in unexpected ways. [ Status { __COMMON, __SERVICES , createConfig = def &= help "Create the configuration file" &= explicit &= name "create-config" } &= help "General status" &= auto , Search { __FILTERS , terms = def &= typQuery &= args , category = def &= help "The category to search in (nyaa.eu only)" &= typ "CATEGORY" &= explicit &= name "category" &= name "C" } &= help "Search for something in your library or online" &= details [ "Examples:" , " animu search kenzen robo Search `kenzen robo` in library" , " animu search --nyaa bleach Search `blearch` in nyaa.eu" ] , Sync { noDownload = def &= help "Don't download anything" } &= help "Synchronize library with hummingbird.me, or check new episodes from nyaa.eu." &= details [ "Hummingbird: Synchronize library entries" , "Nyaa: Search and download new episodes of ongoing series" , " ...or 'all' to sync both." ] , Import { terms = def &= typTargets &= args , noMove = def &= help "Move to destination? (default: no)" , recursive = def &= help "Traverse to subdirectories?" , dest = def &= help "Destination (default: anime_dir)" } &= help "Import some directory contents" , Mv { dest = def &= help "Destination (default: anime_dir)" } &= help "Move files" , Set { status = Watching &= argPos 0 } &= help "Set status of titles in hummingbird.me" , Inc { count = 1 &= help "Icrease watched count by n" } &= help "Increase watched count of TARGET" , List { } &= help "List library entries" , Check { autofix = False &= help "Attempt to fix stuff automatically" , addWith = Completed &= help "Status to add new entries with (default = completed)" &= name "add-with" , force = def &= help "Set the status of --add-with even when all files aren't present" } &= help "Integrity checks between the local database and filesystem." , Watch { till = def &= help "Watch until nth episode" , next = def &= help "Watch next n episodes" } &= help "Watch episodes" , Files { } &= help "List files known to animu" ] &= verbosity where typPattern = typ "PATTERN" typTargets = typ "TARGETS" typQuery = typ "QUERY"
SimSaladin/animu-watch
src/Cmd.hs
bsd-3-clause
9,088
2
17
3,282
1,162
672
490
-1
-1
module AI.Gameplay ( nMCTSRounds, bestMove ) where import AI.MCTS mctsRound :: (Board b) => GameTree b -> IO (GameTree b) mctsRound tree = explore tree >>= return . snd nMCTSRounds :: (Board b) => Int -> GameTree b -> IO (GameTree b) nMCTSRounds n tree = loopFor n tree where loopFor n tree = if n > 0 then mctsRound tree >>= loopFor (n - 1) else return tree bestMove :: (Board b) => GameTree b -> GameTree b bestMove (Tree _ subtrees) = maximumBy compareTree subtrees where compareTree (Tree node1 _) (Tree node2 _) = compareNode node1 node2 compareNode (Node {score = s1, visits = v1}) (Node {score = s2, visits = v2}) = compare (s1' / v1') (s2' / v2') where s1' = fromIntegral s1 :: Double v1' = fromIntegral v1 :: Double s2' = fromIntegral s2 :: Double v2' = fromIntegral v2 :: Double -- TODO: -- functions for updating gametree according to human IO moves
rudyardrichter/MCTS
old/source/AI/Gameplay.hs
mit
1,010
0
11
308
352
184
168
21
2
-- | Basic color helpers for prettifying console output. {-# LANGUAGE OverloadedStrings #-} module Hledger.Utils.Color ( color, bgColor, Color(..), ColorIntensity(..) ) where import System.Console.ANSI -- | Wrap a string in ANSI codes to set and reset foreground colour. color :: ColorIntensity -> Color -> String -> String color int col s = setSGRCode [SetColor Foreground int col] ++ s ++ setSGRCode [] -- | Wrap a string in ANSI codes to set and reset background colour. bgColor :: ColorIntensity -> Color -> String -> String bgColor int col s = setSGRCode [SetColor Background int col] ++ s ++ setSGRCode []
ony/hledger
hledger-lib/Hledger/Utils/Color.hs
gpl-3.0
627
0
9
115
149
82
67
12
1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="it-IT"> <title>TLS Debug | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/tlsdebug/src/main/javahelp/org/zaproxy/zap/extension/tlsdebug/resources/help_it_IT/helpset_it_IT.hs
apache-2.0
971
92
29
160
402
213
189
-1
-1
-- | -- Module : $Header$ -- Copyright : (c) 2013-2015 Galois, Inc. -- License : BSD3 -- Maintainer : cryptol@galois.com -- Stability : provisional -- Portability : portable {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE FlexibleContexts #-} module Cryptol.Symbolic.Prims where import Data.List (genericDrop, genericReplicate, genericSplitAt, genericTake, sortBy, transpose) import Data.Ord (comparing) import Cryptol.Eval.Value (BitWord(..)) import Cryptol.Prims.Eval (binary, unary, tlamN) import Cryptol.Symbolic.Value import Cryptol.TypeCheck.AST (QName(..),Name(..),Decl(..),mkModName) import Cryptol.TypeCheck.Solver.InfNat(Nat'(..), nMul) import Cryptol.Utils.Panic import Cryptol.ModuleSystem.Name (Ident, pack, preludeName) import qualified Data.SBV.Dynamic as SBV import qualified Data.Map as Map #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif traverseSnd :: Functor f => (a -> f b) -> (t, a) -> f (t, b) traverseSnd f (x, y) = (,) x <$> f y -- Primitives ------------------------------------------------------------------ evalPrim :: Decl -> Value evalPrim Decl { dName = QName (Just m) (Name prim), .. } | m == preludeName, Just val <- Map.lookup prim primTable = val evalPrim Decl { .. } = panic "Eval" [ "Unimplemented primitive", show dName ] -- See also Cryptol.Prims.Eval.primTable primTable :: Map.Map Ident Value primTable = Map.fromList $ map (\(n, v) -> (pack n, v)) [ ("True" , VBit SBV.svTrue) , ("False" , VBit SBV.svFalse) , ("demote" , ecDemoteV) -- Converts a numeric type into its corresponding value. -- { val, bits } (fin val, fin bits, bits >= width val) => [bits] , ("+" , binary (arithBinary SBV.svPlus)) -- {a} (Arith a) => a -> a -> a , ("-" , binary (arithBinary SBV.svMinus)) -- {a} (Arith a) => a -> a -> a , ("*" , binary (arithBinary SBV.svTimes)) -- {a} (Arith a) => a -> a -> a , ("/" , binary (arithBinary SBV.svQuot)) -- {a} (Arith a) => a -> a -> a , ("%" , binary (arithBinary SBV.svRem)) -- {a} (Arith a) => a -> a -> a , ("^^" , binary (arithBinary sExp)) -- {a} (Arith a) => a -> a -> a , ("lg2" , unary (arithUnary sLg2)) -- {a} (Arith a) => a -> a , ("negate" , unary (arithUnary SBV.svUNeg)) , ("<" , binary (cmpBinary cmpLt cmpLt SBV.svFalse)) , (">" , binary (cmpBinary cmpGt cmpGt SBV.svFalse)) , ("<=" , binary (cmpBinary cmpLtEq cmpLtEq SBV.svTrue)) , (">=" , binary (cmpBinary cmpGtEq cmpGtEq SBV.svTrue)) , ("==" , binary (cmpBinary cmpEq cmpEq SBV.svTrue)) , ("!=" , binary (cmpBinary cmpNotEq cmpNotEq SBV.svFalse)) , ("&&" , binary (logicBinary SBV.svAnd SBV.svAnd)) , ("||" , binary (logicBinary SBV.svOr SBV.svOr)) , ("^" , binary (logicBinary SBV.svXOr SBV.svXOr)) , ("complement" , unary (logicUnary SBV.svNot SBV.svNot)) , ("zero" , VPoly zeroV) , ("<<" , -- {m,n,a} (fin n) => [m] a -> [n] -> [m] a tlam $ \m -> tlam $ \_ -> tlam $ \a -> VFun $ \xs -> VFun $ \y -> case xs of VWord x -> VWord (SBV.svShiftLeft x (fromVWord y)) _ -> let shl :: Integer -> Value shl i = case numTValue m of Inf -> dropV i xs Nat j | i >= j -> replicateV j a (zeroV a) | otherwise -> catV (dropV i xs) (replicateV i a (zeroV a)) in selectV shl y) , (">>" , -- {m,n,a} (fin n) => [m] a -> [n] -> [m] a tlam $ \m -> tlam $ \_ -> tlam $ \a -> VFun $ \xs -> VFun $ \y -> case xs of VWord x -> VWord (SBV.svShiftRight x (fromVWord y)) _ -> let shr :: Integer -> Value shr i = case numTValue m of Inf -> catV (replicateV i a (zeroV a)) xs Nat j | i >= j -> replicateV j a (zeroV a) | otherwise -> catV (replicateV i a (zeroV a)) (takeV (j - i) xs) in selectV shr y) , ("<<<" , -- {m,n,a} (fin m, fin n) => [m] a -> [n] -> [m] a tlam $ \m -> tlam $ \_ -> tlam $ \_ -> VFun $ \xs -> VFun $ \y -> case xs of VWord x -> VWord (SBV.svRotateLeft x (fromVWord y)) _ -> let rol :: Integer -> Value rol i = catV (dropV k xs) (takeV k xs) where k = i `mod` finTValue m in selectV rol y) , (">>>" , -- {m,n,a} (fin m, fin n) => [m] a -> [n] -> [m] a tlam $ \m -> tlam $ \_ -> tlam $ \_ -> VFun $ \xs -> VFun $ \y -> case xs of VWord x -> VWord (SBV.svRotateRight x (fromVWord y)) _ -> let ror :: Integer -> Value ror i = catV (dropV k xs) (takeV k xs) where k = (- i) `mod` finTValue m in selectV ror y) , ("#" , -- {a,b,d} (fin a) => [a] d -> [b] d -> [a + b] d tlam $ \_ -> tlam $ \_ -> tlam $ \_ -> VFun $ \v1 -> VFun $ \v2 -> catV v1 v2) , ("splitAt" , -- {a,b,c} (fin a) => [a+b] c -> ([a]c,[b]c) tlam $ \(finTValue -> a) -> tlam $ \_ -> tlam $ \_ -> VFun $ \v -> VTuple [takeV a v, dropV a v]) , ("join" , tlam $ \ parts -> tlam $ \ each -> tlam $ \ a -> lam (joinV parts each a)) , ("split" , ecSplitV) , ("reverse" , tlam $ \a -> tlam $ \b -> lam $ \(fromSeq -> xs) -> toSeq a b (reverse xs)) , ("transpose" , tlam $ \a -> tlam $ \b -> tlam $ \c -> lam $ \((map fromSeq . fromSeq) -> xs) -> case numTValue a of Nat 0 -> let v = toSeq a c [] in case numTValue b of Nat n -> toSeq b (tvSeq a c) $ genericReplicate n v Inf -> VStream $ repeat v _ -> toSeq b (tvSeq a c) $ map (toSeq a c) $ transpose xs) , ("@" , -- {n,a,i} (fin i) => [n]a -> [i] -> a tlam $ \_ -> tlam $ \a -> tlam $ \_ -> VFun $ \(fromSeq -> xs) -> VFun $ \y -> let err = zeroV a -- default for out-of-bounds accesses in atV err xs y) , ("@@" , -- {n,a,m,i} (fin i) => [n]a -> [m][i] -> [m]a tlam $ \_ -> tlam $ \a -> tlam $ \_ -> tlam $ \_ -> VFun $ \(fromSeq -> xs) -> VFun $ \ys -> let err = zeroV a -- default for out-of-bounds accesses in mapV (isTBit a) (atV err xs) ys) , ("!" , -- {n,a,i} (fin n, fin i) => [n]a -> [i] -> a tlam $ \_ -> tlam $ \a -> tlam $ \_ -> VFun $ \(fromSeq -> xs) -> VFun $ \y -> let err = zeroV a -- default for out-of-bounds accesses in atV err (reverse xs) y) , ("!!" , -- {n,a,m,i} (fin n, fin i) => [n]a -> [m][i] -> [m]a tlam $ \_ -> tlam $ \a -> tlam $ \_ -> tlam $ \_ -> VFun $ \(fromSeq -> xs) -> VFun $ \ys -> let err = zeroV a -- default for out-of-bounds accesses in mapV (isTBit a) (atV err (reverse xs)) ys) , ("fromThen" , fromThenV) , ("fromTo" , fromToV) , ("fromThenTo" , fromThenToV) , ("infFrom" , tlam $ \(finTValue -> bits) -> lam $ \(fromVWord -> first) -> toStream [ VWord (SBV.svPlus first (literalSWord (fromInteger bits) i)) | i <- [0 ..] ]) , ("infFromThen" , -- {a} (fin a) => [a] -> [a] -> [inf][a] tlam $ \_ -> lam $ \(fromVWord -> first) -> lam $ \(fromVWord -> next) -> toStream (map VWord (iterate (SBV.svPlus (SBV.svMinus next first)) first))) -- {at,len} (fin len) => [len][8] -> at , ("error" , tlam $ \at -> tlam $ \(finTValue -> _len) -> VFun $ \_msg -> zeroV at) -- error/undefined, is arbitrarily translated to 0 , ("pmult" , -- {a,b} (fin a, fin b) => [a] -> [b] -> [max 1 (a + b) - 1] tlam $ \(finTValue -> i) -> tlam $ \(finTValue -> j) -> VFun $ \v1 -> VFun $ \v2 -> let k = max 1 (i + j) - 1 mul _ [] ps = ps mul as (b:bs) ps = mul (SBV.svFalse : as) bs (ites b (as `addPoly` ps) ps) xs = map fromVBit (fromSeq v1) ys = map fromVBit (fromSeq v2) zs = take (fromInteger k) (mul xs ys [] ++ repeat SBV.svFalse) in VSeq True (map VBit zs)) , ("pdiv" , -- {a,b} (fin a, fin b) => [a] -> [b] -> [a] tlam $ \(finTValue -> i) -> tlam $ \_ -> VFun $ \v1 -> VFun $ \v2 -> let xs = map fromVBit (fromSeq v1) ys = map fromVBit (fromSeq v2) zs = take (fromInteger i) (fst (mdp (reverse xs) (reverse ys)) ++ repeat SBV.svFalse) in VSeq True (map VBit (reverse zs))) , ("pmod" , -- {a,b} (fin a, fin b) => [a] -> [b+1] -> [b] tlam $ \_ -> tlam $ \(finTValue -> j) -> VFun $ \v1 -> VFun $ \v2 -> let xs = map fromVBit (fromSeq v1) ys = map fromVBit (fromSeq v2) zs = take (fromInteger j) (snd (mdp (reverse xs) (reverse ys)) ++ repeat SBV.svFalse) in VSeq True (map VBit (reverse zs))) , ("random" , panic "Cryptol.Symbolic.Prims.evalECon" [ "can't symbolically evaluae ECRandom" ]) ] selectV :: (Integer -> Value) -> Value -> Value selectV f v = sel 0 bits where bits = map fromVBit (fromSeq v) -- index bits in big-endian order sel :: Integer -> [SBool] -> Value sel offset [] = f offset sel offset (b : bs) = iteValue b m1 m2 where m1 = sel (offset + 2 ^ length bs) bs m2 = sel offset bs atV :: Value -> [Value] -> Value -> Value atV def vs i = case i of VSeq True (map fromVBit -> bits) -> -- index bits in big-endian order case foldr weave vs bits of [] -> def y : _ -> y VWord x -> foldr f def (zip [0 .. 2 ^ SBV.svBitSize x - 1] vs) where k = SBV.svKind x f (n, v) y = iteValue (SBV.svEqual x (SBV.svInteger k n)) v y _ -> evalPanic "Cryptol.Symbolic.Prims.selectV" ["Invalid index argument"] where weave :: SBool -> [Value] -> [Value] weave _ [] = [] weave b [x1] = [iteValue b def x1] weave b (x1 : x2 : xs) = iteValue b x2 x1 : weave b xs replicateV :: Integer -- ^ number of elements -> TValue -- ^ type of element -> Value -- ^ element -> Value replicateV n (toTypeVal -> TVBit) x = VSeq True (genericReplicate n x) replicateV n _ x = VSeq False (genericReplicate n x) nth :: a -> [a] -> Int -> a nth def [] _ = def nth def (x : xs) n | n == 0 = x | otherwise = nth def xs (n - 1) nthV :: Value -> Value -> Integer -> Value nthV err v n = case v of VStream xs -> nth err xs (fromInteger n) VSeq _ xs -> nth err xs (fromInteger n) VWord x -> let i = SBV.svBitSize x - 1 - fromInteger n in if i < 0 then err else VBit (SBV.svTestBit x i) _ -> err mapV :: Bool -> (Value -> Value) -> Value -> Value mapV isBit f v = case v of VSeq _ xs -> VSeq isBit (map f xs) VStream xs -> VStream (map f xs) _ -> panic "Cryptol.Symbolic.Prims.mapV" [ "non-mappable value" ] catV :: Value -> Value -> Value catV xs (VStream ys) = VStream (fromSeq xs ++ ys) catV (VWord x) ys = VWord (SBV.svJoin x (fromVWord ys)) catV xs (VWord y) = VWord (SBV.svJoin (fromVWord xs) y) catV (VSeq b xs) (VSeq _ ys) = VSeq b (xs ++ ys) catV _ _ = panic "Cryptol.Symbolic.Prims.catV" [ "non-concatenable value" ] dropV :: Integer -> Value -> Value dropV 0 xs = xs dropV n xs = case xs of VSeq b xs' -> VSeq b (genericDrop n xs') VStream xs' -> VStream (genericDrop n xs') VWord w -> VWord $ SBV.svExtract (SBV.svBitSize w - 1 - fromInteger n) 0 w _ -> panic "Cryptol.Symbolic.Prims.dropV" [ "non-droppable value" ] takeV :: Integer -> Value -> Value takeV n xs = case xs of VWord w -> VWord $ SBV.svExtract (SBV.svBitSize w - 1) (SBV.svBitSize w - fromInteger n) w VSeq b xs' -> VSeq b (genericTake n xs') VStream xs' -> VSeq b (genericTake n xs') where b = case xs' of VBit _ : _ -> True _ -> False _ -> panic "Cryptol.Symbolic.Prims.takeV" [ "non-takeable value" ] -- | Make a numeric constant. -- { val, bits } (fin val, fin bits, bits >= width val) => [bits] ecDemoteV :: Value ecDemoteV = tlam $ \valT -> tlam $ \bitT -> case (numTValue valT, numTValue bitT) of (Nat v, Nat bs) -> VWord (literalSWord (fromInteger bs) v) _ -> evalPanic "Cryptol.Prove.evalECon" ["Unexpected Inf in constant." , show valT , show bitT ] -- Type Values ----------------------------------------------------------------- -- | An easy-to-use alternative representation for type `TValue`. data TypeVal = TVBit | TVSeq Int TypeVal | TVStream TypeVal | TVTuple [TypeVal] | TVRecord [(Name, TypeVal)] | TVFun TypeVal TypeVal toTypeVal :: TValue -> TypeVal toTypeVal ty | isTBit ty = TVBit | Just (n, ety) <- isTSeq ty = case numTValue n of Nat w -> TVSeq (fromInteger w) (toTypeVal ety) Inf -> TVStream (toTypeVal ety) | Just (aty, bty) <- isTFun ty = TVFun (toTypeVal aty) (toTypeVal bty) | Just (_, tys) <- isTTuple ty = TVTuple (map toTypeVal tys) | Just fields <- isTRec ty = TVRecord [ (n, toTypeVal aty) | (n, aty) <- fields ] | otherwise = panic "Cryptol.Symbolic.Prims.toTypeVal" [ "bad TValue" ] -- Arith ----------------------------------------------------------------------- type Binary = TValue -> Value -> Value -> Value type Unary = TValue -> Value -> Value -- | Models functions of type `{a} (Arith a) => a -> a -> a` arithBinary :: (SWord -> SWord -> SWord) -> Binary arithBinary op = loop . toTypeVal where loop ty l r = case ty of TVBit -> evalPanic "arithBinop" ["Invalid arguments"] TVSeq _ TVBit -> VWord (op (fromVWord l) (fromVWord r)) TVSeq _ t -> VSeq False (zipWith (loop t) (fromSeq l) (fromSeq r)) TVStream t -> VStream (zipWith (loop t) (fromSeq l) (fromSeq r)) TVTuple ts -> VTuple (zipWith3 loop ts (fromVTuple l) (fromVTuple r)) TVRecord fs -> VRecord [ (f, loop t (lookupRecord f l) (lookupRecord f r)) | (f, t) <- fs ] TVFun _ t -> VFun (\x -> loop t (fromVFun l x) (fromVFun r x)) -- | Models functions of type `{a} (Arith a) => a -> a` arithUnary :: (SWord -> SWord) -> Unary arithUnary op = loop . toTypeVal where loop ty v = case ty of TVBit -> evalPanic "arithUnary" ["Invalid arguments"] TVSeq _ TVBit -> VWord (op (fromVWord v)) TVSeq _ t -> VSeq False (map (loop t) (fromSeq v)) TVStream t -> VStream (map (loop t) (fromSeq v)) TVTuple ts -> VTuple (zipWith loop ts (fromVTuple v)) TVRecord fs -> VRecord [ (f, loop t (lookupRecord f v)) | (f, t) <- fs ] TVFun _ t -> VFun (\x -> loop t (fromVFun v x)) sExp :: SWord -> SWord -> SWord sExp x y = go (reverse (unpackWord y)) -- bits in little-endian order where go [] = literalSWord (SBV.svBitSize x) 1 go (b : bs) = SBV.svIte b (SBV.svTimes x s) s where a = go bs s = SBV.svTimes a a -- | Ceiling (log_2 x) sLg2 :: SWord -> SWord sLg2 x = go 0 where lit n = literalSWord (SBV.svBitSize x) n go i | i < SBV.svBitSize x = SBV.svIte (SBV.svLessEq x (lit (2^i))) (lit (toInteger i)) (go (i + 1)) | otherwise = lit (toInteger i) -- Cmp ------------------------------------------------------------------------- cmpValue :: (SBool -> SBool -> a -> a) -> (SWord -> SWord -> a -> a) -> (Value -> Value -> a -> a) cmpValue fb fw = cmp where cmp v1 v2 k = case (v1, v2) of (VRecord fs1, VRecord fs2) -> let vals = map snd . sortBy (comparing fst) in cmpValues (vals fs1) (vals fs2) k (VTuple vs1 , VTuple vs2 ) -> cmpValues vs1 vs2 k (VBit b1 , VBit b2 ) -> fb b1 b2 k (VWord w1 , VWord w2 ) -> fw w1 w2 k (VSeq _ vs1 , VSeq _ vs2 ) -> cmpValues vs1 vs2 k (VStream {} , VStream {} ) -> panic "Cryptol.Symbolic.Prims.cmpValue" [ "Infinite streams are not comparable" ] (VFun {} , VFun {} ) -> panic "Cryptol.Symbolic.Prims.cmpValue" [ "Functions are not comparable" ] (VPoly {} , VPoly {} ) -> panic "Cryptol.Symbolic.Prims.cmpValue" [ "Polymorphic values are not comparable" ] (VWord w1 , _ ) -> fw w1 (fromVWord v2) k (_ , VWord w2 ) -> fw (fromVWord v1) w2 k (_ , _ ) -> panic "Cryptol.Symbolic.Prims.cmpValue" [ "type mismatch" ] cmpValues (x1 : xs1) (x2 : xs2) k = cmp x1 x2 (cmpValues xs1 xs2 k) cmpValues _ _ k = k cmpEq :: SWord -> SWord -> SBool -> SBool cmpEq x y k = SBV.svAnd (SBV.svEqual x y) k cmpNotEq :: SWord -> SWord -> SBool -> SBool cmpNotEq x y k = SBV.svOr (SBV.svNotEqual x y) k cmpLt, cmpGt :: SWord -> SWord -> SBool -> SBool cmpLt x y k = SBV.svOr (SBV.svLessThan x y) (cmpEq x y k) cmpGt x y k = SBV.svOr (SBV.svGreaterThan x y) (cmpEq x y k) cmpLtEq, cmpGtEq :: SWord -> SWord -> SBool -> SBool cmpLtEq x y k = SBV.svAnd (SBV.svLessEq x y) (cmpNotEq x y k) cmpGtEq x y k = SBV.svAnd (SBV.svGreaterEq x y) (cmpNotEq x y k) cmpBinary :: (SBool -> SBool -> SBool -> SBool) -> (SWord -> SWord -> SBool -> SBool) -> SBool -> Binary cmpBinary fb fw b _ty v1 v2 = VBit (cmpValue fb fw v1 v2 b) -- Logic ----------------------------------------------------------------------- errorV :: String -> TValue -> Value errorV msg = go . toTypeVal where go ty = case ty of TVBit -> VBit (error msg) TVSeq n t -> VSeq False (replicate n (go t)) TVStream t -> VStream (repeat (go t)) TVTuple ts -> VTuple [ go t | t <- ts ] TVRecord fs -> VRecord [ (n, go t) | (n, t) <- fs ] TVFun _ t -> VFun (const (go t)) zeroV :: TValue -> Value zeroV = go . toTypeVal where go ty = case ty of TVBit -> VBit SBV.svFalse TVSeq n TVBit -> VWord (literalSWord n 0) TVSeq n t -> VSeq False (replicate n (go t)) TVStream t -> VStream (repeat (go t)) TVTuple ts -> VTuple [ go t | t <- ts ] TVRecord fs -> VRecord [ (n, go t) | (n, t) <- fs ] TVFun _ t -> VFun (const (go t)) -- | Join a sequence of sequences into a single sequence. joinV :: TValue -> TValue -> TValue -> Value -> Value joinV parts each a v = let len = toNumTValue (numTValue parts `nMul` numTValue each) in toSeq len a (concatMap fromSeq (fromSeq v)) -- | Split implementation. ecSplitV :: Value ecSplitV = tlam $ \ parts -> tlam $ \ each -> tlam $ \ a -> lam $ \ v -> let mkChunks f = map (toFinSeq a) $ f $ fromSeq v in case (numTValue parts, numTValue each) of (Nat p, Nat e) -> VSeq False $ mkChunks (finChunksOf p e) (Inf , Nat e) -> toStream $ mkChunks (infChunksOf e) _ -> evalPanic "splitV" ["invalid type arguments to split"] -- | Split into infinitely many chunks infChunksOf :: Integer -> [a] -> [[a]] infChunksOf each xs = let (as,bs) = genericSplitAt each xs in as : infChunksOf each bs -- | Split into finitely many chunks finChunksOf :: Integer -> Integer -> [a] -> [[a]] finChunksOf 0 _ _ = [] finChunksOf parts each xs = let (as,bs) = genericSplitAt each xs in as : finChunksOf (parts - 1) each bs -- | Merge two values given a binop. This is used for and, or and xor. logicBinary :: (SBool -> SBool -> SBool) -> (SWord -> SWord -> SWord) -> Binary logicBinary bop op = loop . toTypeVal where loop ty l r = case ty of TVBit -> VBit (bop (fromVBit l) (fromVBit r)) TVSeq _ TVBit -> VWord (op (fromVWord l) (fromVWord r)) TVSeq _ t -> VSeq False (zipWith (loop t) (fromSeq l) (fromSeq r)) TVStream t -> VStream (zipWith (loop t) (fromSeq l) (fromSeq r)) TVTuple ts -> VTuple (zipWith3 loop ts (fromVTuple l) (fromVTuple r)) TVRecord fs -> VRecord [ (f, loop t (lookupRecord f l) (lookupRecord f r)) | (f, t) <- fs ] TVFun _ t -> VFun (\x -> loop t (fromVFun l x) (fromVFun r x)) logicUnary :: (SBool -> SBool) -> (SWord -> SWord) -> Unary logicUnary bop op = loop . toTypeVal where loop ty v = case ty of TVBit -> VBit (bop (fromVBit v)) TVSeq _ TVBit -> VWord (op (fromVWord v)) TVSeq _ t -> VSeq False (map (loop t) (fromSeq v)) TVStream t -> VStream (map (loop t) (fromSeq v)) TVTuple ts -> VTuple (zipWith loop ts (fromVTuple v)) TVRecord fs -> VRecord [ (f, loop t (lookupRecord f v)) | (f, t) <- fs ] TVFun _ t -> VFun (\x -> loop t (fromVFun v x)) -- @[ 0, 1 .. ]@ fromThenV :: Value fromThenV = tlamN $ \ first -> tlamN $ \ next -> tlamN $ \ bits -> tlamN $ \ len -> case (first, next, len, bits) of (Nat first', Nat next', Nat len', Nat bits') -> let nums = enumFromThen first' next' lit i = VWord (literalSWord (fromInteger bits') i) in VSeq False (genericTake len' (map lit nums)) _ -> evalPanic "fromThenV" ["invalid arguments"] -- @[ 0 .. 10 ]@ fromToV :: Value fromToV = tlamN $ \ first -> tlamN $ \ lst -> tlamN $ \ bits -> case (first, lst, bits) of (Nat first', Nat lst', Nat bits') -> let nums = enumFromThenTo first' (first' + 1) lst' len = 1 + (lst' - first') lit i = VWord (literalSWord (fromInteger bits') i) in VSeq False (genericTake len (map lit nums)) _ -> evalPanic "fromThenV" ["invalid arguments"] -- @[ 0, 1 .. 10 ]@ fromThenToV :: Value fromThenToV = tlamN $ \ first -> tlamN $ \ next -> tlamN $ \ lst -> tlamN $ \ bits -> tlamN $ \ len -> case (first, next, lst, len, bits) of (Nat first', Nat next', Nat lst', Nat len', Nat bits') -> let nums = enumFromThenTo first' next' lst' lit i = VWord (literalSWord (fromInteger bits') i) in VSeq False (genericTake len' (map lit nums)) _ -> evalPanic "fromThenV" ["invalid arguments"] -- Polynomials ----------------------------------------------------------------- -- TODO: Data.SBV.BitVectors.Polynomials should export ites, addPoly, -- and mdp (the following definitions are copied from that module) -- | Add two polynomials addPoly :: [SBool] -> [SBool] -> [SBool] addPoly xs [] = xs addPoly [] ys = ys addPoly (x:xs) (y:ys) = SBV.svXOr x y : addPoly xs ys ites :: SBool -> [SBool] -> [SBool] -> [SBool] ites s xs ys | Just t <- SBV.svAsBool s = if t then xs else ys | True = go xs ys where go [] [] = [] go [] (b:bs) = SBV.svIte s SBV.svFalse b : go [] bs go (a:as) [] = SBV.svIte s a SBV.svFalse : go as [] go (a:as) (b:bs) = SBV.svIte s a b : go as bs -- conservative over-approximation of the degree degree :: [SBool] -> Int degree xs = walk (length xs - 1) $ reverse xs where walk n [] = n walk n (b:bs) | Just t <- SBV.svAsBool b = if t then n else walk (n-1) bs | True = n -- over-estimate mdp :: [SBool] -> [SBool] -> ([SBool], [SBool]) mdp xs ys = go (length ys - 1) (reverse ys) where degTop = degree xs go _ [] = error "SBV.Polynomial.mdp: Impossible happened; exhausted ys before hitting 0" go n (b:bs) | n == 0 = (reverse qs, rs) | True = let (rqs, rrs) = go (n-1) bs in (ites b (reverse qs) rqs, ites b rs rrs) where degQuot = degTop - n ys' = replicate degQuot SBV.svFalse ++ ys (qs, rs) = divx (degQuot+1) degTop xs ys' -- return the element at index i; if not enough elements, return false -- N.B. equivalent to '(xs ++ repeat false) !! i', but more efficient idx :: [SBool] -> Int -> SBool idx [] _ = SBV.svFalse idx (x:_) 0 = x idx (_:xs) i = idx xs (i-1) divx :: Int -> Int -> [SBool] -> [SBool] -> ([SBool], [SBool]) divx n _ xs _ | n <= 0 = ([], xs) divx n i xs ys' = (q:qs, rs) where q = xs `idx` i xs' = ites q (xs `addPoly` ys') xs (qs, rs) = divx (n-1) (i-1) xs' (tail ys')
beni55/cryptol
src/Cryptol/Symbolic/Prims.hs
bsd-3-clause
25,379
0
34
8,565
9,649
4,978
4,671
534
12
module DPH.Arbitrary ( module DPH.Arbitrary.Int , module DPH.Arbitrary.Vector , module DPH.Arbitrary.Perm , module DPH.Arbitrary.Selector , module DPH.Arbitrary.SliceSpec , module DPH.Arbitrary.ArrayExp , module DPH.Arbitrary.Array , module DPH.Arbitrary.Joint , module DPH.Arbitrary.Segd) where import DPH.Arbitrary.Int import DPH.Arbitrary.Vector import DPH.Arbitrary.Perm import DPH.Arbitrary.Selector import DPH.Arbitrary.SliceSpec import DPH.Arbitrary.ArrayExp import DPH.Arbitrary.Array import DPH.Arbitrary.Joint import DPH.Arbitrary.Segd
mainland/dph
dph-test/framework/DPH/Arbitrary.hs
bsd-3-clause
618
0
5
120
125
86
39
19
0
module ShowComments where import qualified Github.Issues.Comments as Github import Data.List (intercalate) main = do possibleComments <- Github.comments "thoughtbot" "paperclip" 635 case possibleComments of (Left error) -> putStrLn $ "Error: " ++ show error (Right issues) -> putStrLn $ intercalate "\n\n" $ map formatComment issues formatComment comment = (Github.githubOwnerLogin $ Github.issueCommentUser comment) ++ " commented " ++ (show $ Github.fromDate $ Github.issueCommentUpdatedAt comment) ++ "\n" ++ (Github.issueCommentBody comment)
jwiegley/github
samples/Issues/Comments/ShowComments.hs
bsd-3-clause
590
0
12
111
166
85
81
14
2
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Taken quite directly from the Peyton Jones/Lester paper. -} {-# LANGUAGE CPP #-} -- | A module concerned with finding the free variables of an expression. module CoreFVs ( -- * Free variables of expressions and binding groups exprFreeVars, exprFreeVarsDSet, exprFreeIds, exprsFreeVars, exprsFreeVarsList, bindFreeVars, -- * Selective free variables of expressions InterestingVarFun, exprSomeFreeVars, exprsSomeFreeVars, -- * Free variables of Rules, Vars and Ids varTypeTyCoVars, varTypeTyCoVarsAcc, idUnfoldingVars, idFreeVars, dIdFreeVars, idRuleAndUnfoldingVars, idRuleAndUnfoldingVarsDSet, idFreeVarsAcc, idRuleVars, idRuleRhsVars, stableUnfoldingVars, ruleRhsFreeVars, ruleFreeVars, rulesFreeVars, rulesFreeVarsDSet, ruleLhsFreeIds, vectsFreeVars, expr_fvs, -- * Orphan names orphNamesOfType, orphNamesOfCo, orphNamesOfAxiom, orphNamesOfTypes, orphNamesOfCoCon, exprsOrphNames, orphNamesOfFamInst, -- * Core syntax tree annotation with free variables FVAnn, -- annotation, abstract CoreExprWithFVs, -- = AnnExpr Id FVAnn CoreExprWithFVs', -- = AnnExpr' Id FVAnn CoreBindWithFVs, -- = AnnBind Id FVAnn CoreAltWithFVs, -- = AnnAlt Id FVAnn freeVars, -- CoreExpr -> CoreExprWithFVs freeVarsOf, -- CoreExprWithFVs -> DIdSet freeVarsOfType, -- CoreExprWithFVs -> TyCoVarSet freeVarsOfAnn, freeVarsOfTypeAnn, exprTypeFV -- CoreExprWithFVs -> Type ) where #include "HsVersions.h" import CoreSyn import Id import IdInfo import NameSet import UniqFM import Literal ( literalType ) import Name import VarSet import Var import Type import TyCoRep import TyCon import CoAxiom import FamInstEnv import TysPrim( funTyConName ) import Coercion import Maybes( orElse ) import Util import BasicTypes( Activation ) import Outputable import FV {- ************************************************************************ * * \section{Finding the free variables of an expression} * * ************************************************************************ This function simply finds the free variables of an expression. So far as type variables are concerned, it only finds tyvars that are * free in type arguments, * free in the type of a binder, but not those that are free in the type of variable occurrence. -} -- | Find all locally-defined free Ids or type variables in an expression -- returning a non-deterministic set. exprFreeVars :: CoreExpr -> VarSet exprFreeVars = runFVSet . exprFreeVarsAcc -- | Find all locally-defined free Ids or type variables in an expression -- returning a composable FV computation. See Note [FV naming coventions] in FV -- for why export it. exprFreeVarsAcc :: CoreExpr -> FV exprFreeVarsAcc = filterFV isLocalVar . expr_fvs -- | Find all locally-defined free Ids or type variables in an expression -- returning a deterministic set. exprFreeVarsDSet :: CoreExpr -> DVarSet exprFreeVarsDSet = runFVDSet . exprFreeVarsAcc -- | Find all locally-defined free Ids in an expression exprFreeIds :: CoreExpr -> IdSet -- Find all locally-defined free Ids exprFreeIds = exprSomeFreeVars isLocalId -- | Find all locally-defined free Ids or type variables in several expressions -- returning a non-deterministic set. exprsFreeVars :: [CoreExpr] -> VarSet exprsFreeVars = runFVSet . exprsFreeVarsAcc -- | Find all locally-defined free Ids or type variables in several expressions -- returning a composable FV computation. See Note [FV naming coventions] in FV -- for why export it. exprsFreeVarsAcc :: [CoreExpr] -> FV exprsFreeVarsAcc exprs = mapUnionFV exprFreeVarsAcc exprs -- | Find all locally-defined free Ids or type variables in several expressions -- returning a deterministically ordered list. exprsFreeVarsList :: [CoreExpr] -> [Var] exprsFreeVarsList = runFVList . exprsFreeVarsAcc -- | Find all locally defined free Ids in a binding group bindFreeVars :: CoreBind -> VarSet bindFreeVars (NonRec b r) = runFVSet $ filterFV isLocalVar $ rhs_fvs (b,r) bindFreeVars (Rec prs) = runFVSet $ filterFV isLocalVar $ addBndrs (map fst prs) (mapUnionFV rhs_fvs prs) -- | Finds free variables in an expression selected by a predicate exprSomeFreeVars :: InterestingVarFun -- ^ Says which 'Var's are interesting -> CoreExpr -> VarSet exprSomeFreeVars fv_cand e = runFVSet $ filterFV fv_cand $ expr_fvs e -- | Finds free variables in several expressions selected by a predicate exprsSomeFreeVars :: InterestingVarFun -- Says which 'Var's are interesting -> [CoreExpr] -> VarSet exprsSomeFreeVars fv_cand es = runFVSet $ filterFV fv_cand $ mapUnionFV expr_fvs es -- Comment about obselete code -- We used to gather the free variables the RULES at a variable occurrence -- with the following cryptic comment: -- "At a variable occurrence, add in any free variables of its rule rhss -- Curiously, we gather the Id's free *type* variables from its binding -- site, but its free *rule-rhs* variables from its usage sites. This -- is a little weird. The reason is that the former is more efficient, -- but the latter is more fine grained, and a makes a difference when -- a variable mentions itself one of its own rule RHSs" -- Not only is this "weird", but it's also pretty bad because it can make -- a function seem more recursive than it is. Suppose -- f = ...g... -- g = ... -- RULE g x = ...f... -- Then f is not mentioned in its own RHS, and needn't be a loop breaker -- (though g may be). But if we collect the rule fvs from g's occurrence, -- it looks as if f mentions itself. (This bites in the eftInt/eftIntFB -- code in GHC.Enum.) -- -- Anyway, it seems plain wrong. The RULE is like an extra RHS for the -- function, so its free variables belong at the definition site. -- -- Deleted code looked like -- foldVarSet add_rule_var var_itself_set (idRuleVars var) -- add_rule_var var set | keep_it fv_cand in_scope var = extendVarSet set var -- | otherwise = set -- SLPJ Feb06 addBndr :: CoreBndr -> FV -> FV addBndr bndr fv fv_cand in_scope acc = (varTypeTyCoVarsAcc bndr `unionFV` -- Include type variables in the binder's type -- (not just Ids; coercion variables too!) FV.delFV bndr fv) fv_cand in_scope acc addBndrs :: [CoreBndr] -> FV -> FV addBndrs bndrs fv = foldr addBndr fv bndrs expr_fvs :: CoreExpr -> FV expr_fvs (Type ty) fv_cand in_scope acc = tyCoVarsOfTypeAcc ty fv_cand in_scope acc expr_fvs (Coercion co) fv_cand in_scope acc = tyCoVarsOfCoAcc co fv_cand in_scope acc expr_fvs (Var var) fv_cand in_scope acc = oneVar var fv_cand in_scope acc expr_fvs (Lit _) fv_cand in_scope acc = noVars fv_cand in_scope acc expr_fvs (Tick t expr) fv_cand in_scope acc = (tickish_fvs t `unionFV` expr_fvs expr) fv_cand in_scope acc expr_fvs (App fun arg) fv_cand in_scope acc = (expr_fvs fun `unionFV` expr_fvs arg) fv_cand in_scope acc expr_fvs (Lam bndr body) fv_cand in_scope acc = addBndr bndr (expr_fvs body) fv_cand in_scope acc expr_fvs (Cast expr co) fv_cand in_scope acc = (expr_fvs expr `unionFV` tyCoVarsOfCoAcc co) fv_cand in_scope acc expr_fvs (Case scrut bndr ty alts) fv_cand in_scope acc = (expr_fvs scrut `unionFV` tyCoVarsOfTypeAcc ty `unionFV` addBndr bndr (mapUnionFV alt_fvs alts)) fv_cand in_scope acc where alt_fvs (_, bndrs, rhs) = addBndrs bndrs (expr_fvs rhs) expr_fvs (Let (NonRec bndr rhs) body) fv_cand in_scope acc = (rhs_fvs (bndr, rhs) `unionFV` addBndr bndr (expr_fvs body)) fv_cand in_scope acc expr_fvs (Let (Rec pairs) body) fv_cand in_scope acc = addBndrs (map fst pairs) (mapUnionFV rhs_fvs pairs `unionFV` expr_fvs body) fv_cand in_scope acc --------- rhs_fvs :: (Id, CoreExpr) -> FV rhs_fvs (bndr, rhs) = expr_fvs rhs `unionFV` bndrRuleAndUnfoldingVarsAcc bndr -- Treat any RULES as extra RHSs of the binding --------- exprs_fvs :: [CoreExpr] -> FV exprs_fvs exprs = mapUnionFV expr_fvs exprs tickish_fvs :: Tickish Id -> FV tickish_fvs (Breakpoint _ ids) = someVars ids tickish_fvs _ = noVars {- ************************************************************************ * * \section{Free names} * * ************************************************************************ -} -- | Finds the free /external/ names of an expression, notably -- including the names of type constructors (which of course do not show -- up in 'exprFreeVars'). exprOrphNames :: CoreExpr -> NameSet -- There's no need to delete local binders, because they will all -- be /internal/ names. exprOrphNames e = go e where go (Var v) | isExternalName n = unitNameSet n | otherwise = emptyNameSet where n = idName v go (Lit _) = emptyNameSet go (Type ty) = orphNamesOfType ty -- Don't need free tyvars go (Coercion co) = orphNamesOfCo co go (App e1 e2) = go e1 `unionNameSet` go e2 go (Lam v e) = go e `delFromNameSet` idName v go (Tick _ e) = go e go (Cast e co) = go e `unionNameSet` orphNamesOfCo co go (Let (NonRec _ r) e) = go e `unionNameSet` go r go (Let (Rec prs) e) = exprsOrphNames (map snd prs) `unionNameSet` go e go (Case e _ ty as) = go e `unionNameSet` orphNamesOfType ty `unionNameSet` unionNameSets (map go_alt as) go_alt (_,_,r) = go r -- | Finds the free /external/ names of several expressions: see 'exprOrphNames' for details exprsOrphNames :: [CoreExpr] -> NameSet exprsOrphNames es = foldr (unionNameSet . exprOrphNames) emptyNameSet es {- ********************************************************************** %* * orphNamesXXX %* * %********************************************************************* -} orphNamesOfTyCon :: TyCon -> NameSet orphNamesOfTyCon tycon = unitNameSet (getName tycon) `unionNameSet` case tyConClass_maybe tycon of Nothing -> emptyNameSet Just cls -> unitNameSet (getName cls) orphNamesOfType :: Type -> NameSet orphNamesOfType ty | Just ty' <- coreView ty = orphNamesOfType ty' -- Look through type synonyms (Trac #4912) orphNamesOfType (TyVarTy _) = emptyNameSet orphNamesOfType (LitTy {}) = emptyNameSet orphNamesOfType (TyConApp tycon tys) = orphNamesOfTyCon tycon `unionNameSet` orphNamesOfTypes tys orphNamesOfType (ForAllTy bndr res) = unitNameSet funTyConName -- NB! See Trac #8535 `unionNameSet` orphNamesOfType (binderType bndr) `unionNameSet` orphNamesOfType res orphNamesOfType (AppTy fun arg) = orphNamesOfType fun `unionNameSet` orphNamesOfType arg orphNamesOfType (CastTy ty co) = orphNamesOfType ty `unionNameSet` orphNamesOfCo co orphNamesOfType (CoercionTy co) = orphNamesOfCo co orphNamesOfThings :: (a -> NameSet) -> [a] -> NameSet orphNamesOfThings f = foldr (unionNameSet . f) emptyNameSet orphNamesOfTypes :: [Type] -> NameSet orphNamesOfTypes = orphNamesOfThings orphNamesOfType orphNamesOfCo :: Coercion -> NameSet orphNamesOfCo (Refl _ ty) = orphNamesOfType ty orphNamesOfCo (TyConAppCo _ tc cos) = unitNameSet (getName tc) `unionNameSet` orphNamesOfCos cos orphNamesOfCo (AppCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (ForAllCo _ kind_co co) = orphNamesOfCo kind_co `unionNameSet` orphNamesOfCo co orphNamesOfCo (CoVarCo _) = emptyNameSet orphNamesOfCo (AxiomInstCo con _ cos) = orphNamesOfCoCon con `unionNameSet` orphNamesOfCos cos orphNamesOfCo (UnivCo p _ t1 t2) = orphNamesOfProv p `unionNameSet` orphNamesOfType t1 `unionNameSet` orphNamesOfType t2 orphNamesOfCo (SymCo co) = orphNamesOfCo co orphNamesOfCo (TransCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (NthCo _ co) = orphNamesOfCo co orphNamesOfCo (LRCo _ co) = orphNamesOfCo co orphNamesOfCo (InstCo co arg) = orphNamesOfCo co `unionNameSet` orphNamesOfCo arg orphNamesOfCo (CoherenceCo co1 co2) = orphNamesOfCo co1 `unionNameSet` orphNamesOfCo co2 orphNamesOfCo (KindCo co) = orphNamesOfCo co orphNamesOfCo (SubCo co) = orphNamesOfCo co orphNamesOfCo (AxiomRuleCo _ cs) = orphNamesOfCos cs orphNamesOfProv :: UnivCoProvenance -> NameSet orphNamesOfProv UnsafeCoerceProv = emptyNameSet orphNamesOfProv (PhantomProv co) = orphNamesOfCo co orphNamesOfProv (ProofIrrelProv co) = orphNamesOfCo co orphNamesOfProv (PluginProv _) = emptyNameSet orphNamesOfProv (HoleProv _) = emptyNameSet orphNamesOfCos :: [Coercion] -> NameSet orphNamesOfCos = orphNamesOfThings orphNamesOfCo orphNamesOfCoCon :: CoAxiom br -> NameSet orphNamesOfCoCon (CoAxiom { co_ax_tc = tc, co_ax_branches = branches }) = orphNamesOfTyCon tc `unionNameSet` orphNamesOfCoAxBranches branches orphNamesOfAxiom :: CoAxiom br -> NameSet orphNamesOfAxiom axiom = orphNamesOfTypes (concatMap coAxBranchLHS $ fromBranches $ coAxiomBranches axiom) `extendNameSet` getName (coAxiomTyCon axiom) orphNamesOfCoAxBranches :: Branches br -> NameSet orphNamesOfCoAxBranches = foldr (unionNameSet . orphNamesOfCoAxBranch) emptyNameSet . fromBranches orphNamesOfCoAxBranch :: CoAxBranch -> NameSet orphNamesOfCoAxBranch (CoAxBranch { cab_lhs = lhs, cab_rhs = rhs }) = orphNamesOfTypes lhs `unionNameSet` orphNamesOfType rhs -- | orphNamesOfAxiom collects the names of the concrete types and -- type constructors that make up the LHS of a type family instance, -- including the family name itself. -- -- For instance, given `type family Foo a b`: -- `type instance Foo (F (G (H a))) b = ...` would yield [Foo,F,G,H] -- -- Used in the implementation of ":info" in GHCi. orphNamesOfFamInst :: FamInst -> NameSet orphNamesOfFamInst fam_inst = orphNamesOfAxiom (famInstAxiom fam_inst) {- ************************************************************************ * * \section[freevars-everywhere]{Attaching free variables to every sub-expression} * * ************************************************************************ -} -- | Those variables free in the right hand side of a rule returned as a -- non-deterministic set ruleRhsFreeVars :: CoreRule -> VarSet ruleRhsFreeVars (BuiltinRule {}) = noFVs ruleRhsFreeVars (Rule { ru_fn = _, ru_bndrs = bndrs, ru_rhs = rhs }) = runFVSet $ filterFV isLocalVar $ addBndrs bndrs (expr_fvs rhs) -- See Note [Rule free var hack] -- | Those variables free in the both the left right hand sides of a rule -- returned as a non-deterministic set ruleFreeVars :: CoreRule -> VarSet ruleFreeVars = runFVSet . ruleFreeVarsAcc -- | Those variables free in the both the left right hand sides of a rule -- returned as FV computation ruleFreeVarsAcc :: CoreRule -> FV ruleFreeVarsAcc (BuiltinRule {}) = noVars ruleFreeVarsAcc (Rule { ru_fn = _do_not_include -- See Note [Rule free var hack] , ru_bndrs = bndrs , ru_rhs = rhs, ru_args = args }) = filterFV isLocalVar $ addBndrs bndrs (exprs_fvs (rhs:args)) -- | Those variables free in the both the left right hand sides of rules -- returned as FV computation rulesFreeVarsAcc :: [CoreRule] -> FV rulesFreeVarsAcc = mapUnionFV ruleFreeVarsAcc -- | Those variables free in the both the left right hand sides of rules -- returned as a deterministic set rulesFreeVarsDSet :: [CoreRule] -> DVarSet rulesFreeVarsDSet rules = runFVDSet $ rulesFreeVarsAcc rules idRuleRhsVars :: (Activation -> Bool) -> Id -> VarSet -- Just the variables free on the *rhs* of a rule idRuleRhsVars is_active id = mapUnionVarSet get_fvs (idCoreRules id) where get_fvs (Rule { ru_fn = fn, ru_bndrs = bndrs , ru_rhs = rhs, ru_act = act }) | is_active act -- See Note [Finding rule RHS free vars] in OccAnal.hs = delFromUFM fvs fn -- Note [Rule free var hack] where fvs = runFVSet $ filterFV isLocalVar $ addBndrs bndrs (expr_fvs rhs) get_fvs _ = noFVs -- | Those variables free in the right hand side of several rules rulesFreeVars :: [CoreRule] -> VarSet rulesFreeVars rules = mapUnionVarSet ruleFreeVars rules ruleLhsFreeIds :: CoreRule -> VarSet -- ^ This finds all locally-defined free Ids on the left hand side of a rule ruleLhsFreeIds (BuiltinRule {}) = noFVs ruleLhsFreeIds (Rule { ru_bndrs = bndrs, ru_args = args }) = runFVSet $ filterFV isLocalId $ addBndrs bndrs (exprs_fvs args) {- Note [Rule free var hack] (Not a hack any more) ~~~~~~~~~~~~~~~~~~~~~~~~~ We used not to include the Id in its own rhs free-var set. Otherwise the occurrence analyser makes bindings recursive: f x y = x+y RULE: f (f x y) z ==> f x (f y z) However, the occurrence analyser distinguishes "non-rule loop breakers" from "rule-only loop breakers" (see BasicTypes.OccInfo). So it will put this 'f' in a Rec block, but will mark the binding as a non-rule loop breaker, which is perfectly inlinable. -} -- |Free variables of a vectorisation declaration vectsFreeVars :: [CoreVect] -> VarSet vectsFreeVars = mapUnionVarSet vectFreeVars where vectFreeVars (Vect _ rhs) = runFVSet $ filterFV isLocalId $ expr_fvs rhs vectFreeVars (NoVect _) = noFVs vectFreeVars (VectType _ _ _) = noFVs vectFreeVars (VectClass _) = noFVs vectFreeVars (VectInst _) = noFVs -- this function is only concerned with values, not types {- ************************************************************************ * * \section[freevars-everywhere]{Attaching free variables to every sub-expression} * * ************************************************************************ The free variable pass annotates every node in the expression with its NON-GLOBAL free variables and type variables. -} data FVAnn = FVAnn { fva_fvs :: DVarSet -- free in expression , fva_ty_fvs :: DVarSet -- free only in expression's type , fva_ty :: Type -- expression's type } -- | Every node in a binding group annotated with its -- (non-global) free variables, both Ids and TyVars, and type. type CoreBindWithFVs = AnnBind Id FVAnn -- | Every node in an expression annotated with its -- (non-global) free variables, both Ids and TyVars, and type. type CoreExprWithFVs = AnnExpr Id FVAnn type CoreExprWithFVs' = AnnExpr' Id FVAnn -- | Every node in an expression annotated with its -- (non-global) free variables, both Ids and TyVars, and type. type CoreAltWithFVs = AnnAlt Id FVAnn freeVarsOf :: CoreExprWithFVs -> DIdSet -- ^ Inverse function to 'freeVars' freeVarsOf (FVAnn { fva_fvs = fvs }, _) = fvs -- | Extract the vars free in an annotated expression's type freeVarsOfType :: CoreExprWithFVs -> DTyCoVarSet freeVarsOfType (FVAnn { fva_ty_fvs = ty_fvs }, _) = ty_fvs -- | Extract the type of an annotated expression. (This is cheap.) exprTypeFV :: CoreExprWithFVs -> Type exprTypeFV (FVAnn { fva_ty = ty }, _) = ty -- | Extract the vars reported in a FVAnn freeVarsOfAnn :: FVAnn -> DIdSet freeVarsOfAnn = fva_fvs -- | Extract the type-level vars reported in a FVAnn freeVarsOfTypeAnn :: FVAnn -> DTyCoVarSet freeVarsOfTypeAnn = fva_ty_fvs noFVs :: VarSet noFVs = emptyVarSet aFreeVar :: Var -> DVarSet aFreeVar = unitDVarSet unionFVs :: DVarSet -> DVarSet -> DVarSet unionFVs = unionDVarSet unionFVss :: [DVarSet] -> DVarSet unionFVss = unionDVarSets delBindersFV :: [Var] -> DVarSet -> DVarSet delBindersFV bs fvs = foldr delBinderFV fvs bs delBinderFV :: Var -> DVarSet -> DVarSet -- This way round, so we can do it multiple times using foldr -- (b `delBinderFV` s) removes the binder b from the free variable set s, -- but *adds* to s -- -- the free variables of b's type -- -- This is really important for some lambdas: -- In (\x::a -> x) the only mention of "a" is in the binder. -- -- Also in -- let x::a = b in ... -- we should really note that "a" is free in this expression. -- It'll be pinned inside the /\a by the binding for b, but -- it seems cleaner to make sure that a is in the free-var set -- when it is mentioned. -- -- This also shows up in recursive bindings. Consider: -- /\a -> letrec x::a = x in E -- Now, there are no explicit free type variables in the RHS of x, -- but nevertheless "a" is free in its definition. So we add in -- the free tyvars of the types of the binders, and include these in the -- free vars of the group, attached to the top level of each RHS. -- -- This actually happened in the defn of errorIO in IOBase.hs: -- errorIO (ST io) = case (errorIO# io) of -- _ -> bottom -- where -- bottom = bottom -- Never evaluated delBinderFV b s = (s `delDVarSet` b) `unionFVs` dVarTypeTyCoVars b -- Include coercion variables too! varTypeTyCoVars :: Var -> TyCoVarSet -- Find the type/kind variables free in the type of the id/tyvar varTypeTyCoVars var = runFVSet $ varTypeTyCoVarsAcc var dVarTypeTyCoVars :: Var -> DTyCoVarSet -- Find the type/kind/coercion variables free in the type of the id/tyvar dVarTypeTyCoVars var = runFVDSet $ varTypeTyCoVarsAcc var varTypeTyCoVarsAcc :: Var -> FV varTypeTyCoVarsAcc var = tyCoVarsOfTypeAcc (varType var) idFreeVars :: Id -> VarSet idFreeVars id = ASSERT( isId id) runFVSet $ idFreeVarsAcc id dIdFreeVars :: Id -> DVarSet dIdFreeVars id = runFVDSet $ idFreeVarsAcc id idFreeVarsAcc :: Id -> FV -- Type variables, rule variables, and inline variables idFreeVarsAcc id = ASSERT( isId id) varTypeTyCoVarsAcc id `unionFV` idRuleAndUnfoldingVarsAcc id bndrRuleAndUnfoldingVarsAcc :: Var -> FV bndrRuleAndUnfoldingVarsAcc v | isTyVar v = noVars | otherwise = idRuleAndUnfoldingVarsAcc v idRuleAndUnfoldingVars :: Id -> VarSet idRuleAndUnfoldingVars id = runFVSet $ idRuleAndUnfoldingVarsAcc id idRuleAndUnfoldingVarsDSet :: Id -> DVarSet idRuleAndUnfoldingVarsDSet id = runFVDSet $ idRuleAndUnfoldingVarsAcc id idRuleAndUnfoldingVarsAcc :: Id -> FV idRuleAndUnfoldingVarsAcc id = ASSERT( isId id) idRuleVarsAcc id `unionFV` idUnfoldingVarsAcc id idRuleVars ::Id -> VarSet -- Does *not* include CoreUnfolding vars idRuleVars id = runFVSet $ idRuleVarsAcc id idRuleVarsAcc :: Id -> FV idRuleVarsAcc id = ASSERT( isId id) someVars (dVarSetElems $ ruleInfoFreeVars (idSpecialisation id)) idUnfoldingVars :: Id -> VarSet -- Produce free vars for an unfolding, but NOT for an ordinary -- (non-inline) unfolding, since it is a dup of the rhs -- and we'll get exponential behaviour if we look at both unf and rhs! -- But do look at the *real* unfolding, even for loop breakers, else -- we might get out-of-scope variables idUnfoldingVars id = runFVSet $ idUnfoldingVarsAcc id idUnfoldingVarsAcc :: Id -> FV idUnfoldingVarsAcc id = stableUnfoldingVarsAcc (realIdUnfolding id) `orElse` noVars stableUnfoldingVars :: Unfolding -> Maybe VarSet stableUnfoldingVars unf = runFVSet `fmap` stableUnfoldingVarsAcc unf stableUnfoldingVarsAcc :: Unfolding -> Maybe FV stableUnfoldingVarsAcc unf = case unf of CoreUnfolding { uf_tmpl = rhs, uf_src = src } | isStableSource src -> Just (filterFV isLocalVar $ expr_fvs rhs) DFunUnfolding { df_bndrs = bndrs, df_args = args } -> Just (filterFV isLocalVar $ FV.delFVs (mkVarSet bndrs) $ exprs_fvs args) -- DFuns are top level, so no fvs from types of bndrs _other -> Nothing {- ************************************************************************ * * \subsection{Free variables (and types)} * * ************************************************************************ -} freeVars :: CoreExpr -> CoreExprWithFVs -- ^ Annotate a 'CoreExpr' with its (non-global) free type and value variables at every tree node freeVars = go where go :: CoreExpr -> CoreExprWithFVs go (Var v) = (FVAnn fvs ty_fvs (idType v), AnnVar v) where -- ToDo: insert motivating example for why we *need* -- to include the idSpecVars in the FV list. -- Actually [June 98] I don't think it's necessary -- fvs = fvs_v `unionVarSet` idSpecVars v (fvs, ty_fvs) | isLocalVar v = (aFreeVar v `unionFVs` ty_fvs, dVarTypeTyCoVars v) | otherwise = (emptyDVarSet, emptyDVarSet) go (Lit lit) = (FVAnn emptyDVarSet emptyDVarSet (literalType lit), AnnLit lit) go (Lam b body) = ( FVAnn { fva_fvs = b_fvs `unionFVs` (b `delBinderFV` body_fvs) , fva_ty_fvs = b_fvs `unionFVs` (b `delBinderFV` body_ty_fvs) , fva_ty = mkFunTy b_ty body_ty } , AnnLam b body' ) where body'@(FVAnn { fva_fvs = body_fvs, fva_ty_fvs = body_ty_fvs , fva_ty = body_ty }, _) = go body b_ty = idType b b_fvs = tyCoVarsOfTypeDSet b_ty go (App fun arg) = ( FVAnn { fva_fvs = freeVarsOf fun' `unionFVs` freeVarsOf arg' , fva_ty_fvs = tyCoVarsOfTypeDSet res_ty , fva_ty = res_ty } , AnnApp fun' arg' ) where fun' = go fun fun_ty = exprTypeFV fun' arg' = go arg res_ty = applyTypeToArg fun_ty arg go (Case scrut bndr ty alts) = ( FVAnn { fva_fvs = (bndr `delBinderFV` alts_fvs) `unionFVs` freeVarsOf scrut2 `unionFVs` tyCoVarsOfTypeDSet ty -- don't need to look at (idType bndr) -- b/c that's redundant with scrut , fva_ty_fvs = tyCoVarsOfTypeDSet ty , fva_ty = ty } , AnnCase scrut2 bndr ty alts2 ) where scrut2 = go scrut (alts_fvs_s, alts2) = mapAndUnzip fv_alt alts alts_fvs = unionFVss alts_fvs_s fv_alt (con,args,rhs) = (delBindersFV args (freeVarsOf rhs2), (con, args, rhs2)) where rhs2 = go rhs go (Let (NonRec binder rhs) body) = ( FVAnn { fva_fvs = freeVarsOf rhs2 `unionFVs` body_fvs `unionFVs` runFVDSet (bndrRuleAndUnfoldingVarsAcc binder) -- Remember any rules; cf rhs_fvs above , fva_ty_fvs = freeVarsOfType body2 , fva_ty = exprTypeFV body2 } , AnnLet (AnnNonRec binder rhs2) body2 ) where rhs2 = go rhs body2 = go body body_fvs = binder `delBinderFV` freeVarsOf body2 go (Let (Rec binds) body) = ( FVAnn { fva_fvs = delBindersFV binders all_fvs , fva_ty_fvs = freeVarsOfType body2 , fva_ty = exprTypeFV body2 } , AnnLet (AnnRec (binders `zip` rhss2)) body2 ) where (binders, rhss) = unzip binds rhss2 = map go rhss rhs_body_fvs = foldr (unionFVs . freeVarsOf) body_fvs rhss2 binders_fvs = runFVDSet $ mapUnionFV idRuleAndUnfoldingVarsAcc binders all_fvs = rhs_body_fvs `unionFVs` binders_fvs -- The "delBinderFV" happens after adding the idSpecVars, -- since the latter may add some of the binders as fvs body2 = go body body_fvs = freeVarsOf body2 go (Cast expr co) = ( FVAnn (freeVarsOf expr2 `unionFVs` cfvs) (tyCoVarsOfTypeDSet to_ty) to_ty , AnnCast expr2 (c_ann, co) ) where expr2 = go expr cfvs = tyCoVarsOfCoDSet co c_ann = FVAnn cfvs (tyCoVarsOfTypeDSet co_ki) co_ki co_ki = coercionType co Just (_, to_ty) = splitCoercionType_maybe co_ki go (Tick tickish expr) = ( FVAnn { fva_fvs = tickishFVs tickish `unionFVs` freeVarsOf expr2 , fva_ty_fvs = freeVarsOfType expr2 , fva_ty = exprTypeFV expr2 } , AnnTick tickish expr2 ) where expr2 = go expr tickishFVs (Breakpoint _ ids) = mkDVarSet ids tickishFVs _ = emptyDVarSet go (Type ty) = ( FVAnn (tyCoVarsOfTypeDSet ty) (tyCoVarsOfTypeDSet ki) ki , AnnType ty) where ki = typeKind ty go (Coercion co) = ( FVAnn (tyCoVarsOfCoDSet co) (tyCoVarsOfTypeDSet ki) ki , AnnCoercion co) where ki = coercionType co
mcschroeder/ghc
compiler/coreSyn/CoreFVs.hs
bsd-3-clause
30,188
0
14
8,131
5,531
2,977
2,554
405
12
{-# Language DeriveFunctor #-} -- | Accords in just intonation Gm with 14/8 beat. module Main where import Csound.Base import Color(marimbaSynth) instr (amp, cps) = sig amp * env * osc (sig cps) where env = once $ lins [0.00001, 30, 1, 50, 0.5, 100, 0.00001] en :: Sco a -> Sco a en = str (1/8) -- volumes baseVolume = 0.35 v3 = baseVolume * 0.8 v2 = baseVolume * 0.7 v1 = baseVolume * 0.5 -- pitches (Gm + Ab) baseTone = 391.995 -- G -- phrygian scale: sTTTsTT tones = [1, 16/15, 6/5, 4/3, 3/2, 8/5, 9/5] cpsMap f x = fmap phi x where phi (amp, cps) = (amp, f cps) lo1, hi1 :: Functor f => f (a, Int) -> f (a, Int) lo1 = cpsMap (\x -> x - 7) hi1 = cpsMap (\x -> x + 7) trip2cps = cpsMap t2cps t2cps :: Int -> D t2cps n = double $ (2 ^^ oct) * baseTone * tones !! step where (oct, step) = divMod n 7 data Trip a = Trip { lead :: [a] , body :: (a, a) } deriving (Functor) -- single lead trip lead = Trip (repeat lead) -- main left/right hand pattern -- the first accent is a bit louder than other ones. v3 vs v2 rhp :: Trip a -> Sco (D, a) rhp (Trip leads (a, b)) = en $ mel $ zipWith ($) [triple v3, triple v2, quatra, doub, doub] leads where triple acc lead = firstLead acc [lead, a, b] quatra lead = firstLead v3 [lead, a, b, a] doub lead = firstLead v2 [lead, a] lhp :: Trip a -> Sco (D, a) lhp (Trip leads (a, b)) = en $ mel $ zipWith ($) [triple v3, triple v2, quatra, quatra] leads where triple acc lead = firstLead acc [lead, a, b] quatra lead = firstLead v2 [lead, a, b, a] firstLead :: D -> [a] -> Sco (D, a) firstLead accVol (a:as) = melMap temp $ (accVol, a) : fmap (\x -> (v1, x)) as bass = fmap (\x -> x - 7) -- First part tr = trip 4 (2, 0) -- left tonic tl = bass $ trip 0 (2, 4) -- right tonic t = (0, 2, 4) firstPart = loopBy 2 $ har [leftHand1, rightHand1] rightHand1 = melMap rhp' [ t , (0, 2, 5) , (0, 1, 5) , t , t , (1, 2, 3) , (0, 2, 3) , t] rhp' (a, b, c) = rhp $ trip c (b, a) leftHand1 = melMap lhp' [ (0, 2, 3) , (0, 2, 5) , (1, 2, 5) , t , (0, 2, 3) , (1, 2, 3) , (-2, 1, 3) , t] lhp' (a, b, c) = lhp $ bass $ trip a (b, c) -- Second part secondPart = loopBy 2 $ har [leftHand2, rightHand2] leftHand2 = loopBy 2 $ melMap lhp' [ (-2, 1, 2) , (-3, 1, 2)] rightHand2 = mel [ t, e, t, s ] where p a b (star1, star2) = rhp $ Trip [a, a, b, star1, star2] (2, 0) t = p 4 4 (4, 4) e = p 4 5 (4, 4) s = p 4 4 (9, 7) -- all tot = mel [loopBy 2 firstPart, secondPart, firstPart] res = str 1.7 $ sco (onCps marimbaSynth) $ sustain 0.35 $ loopBy 4 $ trip2cps $ tot main = dac $ mix res
isomorphism/csound-expression
examples/Gm.hs
bsd-3-clause
2,875
0
12
953
1,399
791
608
77
1
module PolymorhicIn1 where f :: [a] -> a f ((x : xs)) = case xs of xs@[] -> x xs@(b_1 : b_2) -> x f ((x : xs)) = x
SAdams601/HaRe
old/testing/introCase/PolymorphicIn1_TokOut.hs
bsd-3-clause
146
0
10
61
83
47
36
7
2
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} -- | Resolving a build plan for a set of packages in a given Stackage -- snapshot. module Stack.BuildPlan ( BuildPlanException (..) , MiniBuildPlan(..) , MiniPackageInfo(..) , Snapshots (..) , getSnapshots , loadMiniBuildPlan , resolveBuildPlan , findBuildPlan , ToolMap , getToolMap , shadowMiniBuildPlan , parseCustomMiniBuildPlan ) where import Control.Applicative import Control.Exception (assert) import Control.Monad (liftM, forM) import Control.Monad.Catch import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (asks) import Control.Monad.State.Strict (State, execState, get, modify, put) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Crypto.Hash.SHA256 as SHA256 import Data.Aeson.Extended (FromJSON (..), withObject, withText, (.:), (.:?), (.!=)) import Data.Binary.VersionTagged (taggedDecodeOrLoad) import Data.ByteString (ByteString) import qualified Data.ByteString.Base16 as B16 import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import Data.Either (partitionEithers) import qualified Data.Foldable as F import qualified Data.HashMap.Strict as HM import Data.IntMap (IntMap) import qualified Data.IntMap as IntMap import Data.List (intercalate) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe, mapMaybe) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time (Day) import qualified Data.Traversable as Tr import Data.Typeable (Typeable) import Data.Yaml (decodeEither', decodeFileEither) import Distribution.PackageDescription (GenericPackageDescription, flagDefault, flagManual, flagName, genPackageFlags, executables, exeName, library, libBuildInfo, buildable) import qualified Distribution.Package as C import qualified Distribution.PackageDescription as C import qualified Distribution.Version as C import Distribution.Text (display) import Network.HTTP.Download import Network.HTTP.Types (Status(..)) import Network.HTTP.Client (checkStatus) import Path import Path.IO import Prelude -- Fix AMP warning import Stack.Constants import Stack.Fetch import Stack.GhcPkg import Stack.Package import Stack.PackageIndex import Stack.Types import Stack.Types.StackT import System.Directory (canonicalizePath) import qualified System.FilePath as FP data BuildPlanException = UnknownPackages (Path Abs File) -- stack.yaml file (Map PackageName (Maybe Version, (Set PackageName))) -- truly unknown (Map PackageName (Set PackageIdentifier)) -- shadowed | SnapshotNotFound SnapName deriving (Typeable) instance Exception BuildPlanException instance Show BuildPlanException where show (SnapshotNotFound snapName) = unlines [ "SnapshotNotFound " ++ snapName' , "Non existing resolver: " ++ snapName' ++ "." , "For a complete list of available snapshots see https://www.stackage.org/snapshots" ] where snapName' = show $ renderSnapName snapName show (UnknownPackages stackYaml unknown shadowed) = unlines $ unknown' ++ shadowed' where unknown' :: [String] unknown' | Map.null unknown = [] | otherwise = concat [ ["The following packages do not exist in the build plan:"] , map go (Map.toList unknown) , case mapMaybe goRecommend $ Map.toList unknown of [] -> [] rec -> ("Recommended action: modify the extra-deps field of " ++ toFilePath stackYaml ++ " to include the following:") : (rec ++ ["Note: further dependencies may need to be added"]) , case mapMaybe getNoKnown $ Map.toList unknown of [] -> [] noKnown -> [ "There are no known versions of the following packages:" , intercalate ", " $ map packageNameString noKnown ] ] where go (dep, (_, users)) | Set.null users = packageNameString dep go (dep, (_, users)) = concat [ packageNameString dep , " (used by " , intercalate ", " $ map packageNameString $ Set.toList users , ")" ] goRecommend (name, (Just version, _)) = Just $ "- " ++ packageIdentifierString (PackageIdentifier name version) goRecommend (_, (Nothing, _)) = Nothing getNoKnown (name, (Nothing, _)) = Just name getNoKnown (_, (Just _, _)) = Nothing shadowed' :: [String] shadowed' | Map.null shadowed = [] | otherwise = concat [ ["The following packages are shadowed by local packages:"] , map go (Map.toList shadowed) , ["Recommended action: modify the extra-deps field of " ++ toFilePath stackYaml ++ " to include the following:"] , extraDeps , ["Note: further dependencies may need to be added"] ] where go (dep, users) | Set.null users = concat [ packageNameString dep , " (internal stack error: this should never be null)" ] go (dep, users) = concat [ packageNameString dep , " (used by " , intercalate ", " $ map (packageNameString . packageIdentifierName) $ Set.toList users , ")" ] extraDeps = map (\ident -> "- " ++ packageIdentifierString ident) $ Set.toList $ Set.unions $ Map.elems shadowed -- | Determine the necessary packages to install to have the given set of -- packages available. -- -- This function will not provide test suite and benchmark dependencies. -- -- This may fail if a target package is not present in the @BuildPlan@. resolveBuildPlan :: (MonadThrow m, MonadIO m, MonadReader env m, HasBuildConfig env, MonadLogger m, HasHttpManager env, MonadBaseControl IO m,MonadCatch m) => EnvOverride -> MiniBuildPlan -> (PackageName -> Bool) -- ^ is it shadowed by a local package? -> Map PackageName (Set PackageName) -- ^ required packages, and users of it -> m ( Map PackageName (Version, Map FlagName Bool) , Map PackageName (Set PackageName) ) resolveBuildPlan menv mbp isShadowed packages | Map.null (rsUnknown rs) && Map.null (rsShadowed rs) = return (rsToInstall rs, rsUsedBy rs) | otherwise = do cache <- getPackageCaches menv let maxVer = Map.fromListWith max $ map toTuple $ Map.keys cache unknown = flip Map.mapWithKey (rsUnknown rs) $ \ident x -> (Map.lookup ident maxVer, x) bconfig <- asks getBuildConfig throwM $ UnknownPackages (bcStackYaml bconfig) unknown (rsShadowed rs) where rs = getDeps mbp isShadowed packages data ResolveState = ResolveState { rsVisited :: Map PackageName (Set PackageName) -- ^ set of shadowed dependencies , rsUnknown :: Map PackageName (Set PackageName) , rsShadowed :: Map PackageName (Set PackageIdentifier) , rsToInstall :: Map PackageName (Version, Map FlagName Bool) , rsUsedBy :: Map PackageName (Set PackageName) } toMiniBuildPlan :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m) => CompilerVersion -- ^ Compiler version -> Map PackageName Version -- ^ cores -> Map PackageName (Version, Map FlagName Bool) -- ^ non-core packages -> m MiniBuildPlan toMiniBuildPlan compilerVersion corePackages packages = do $logInfo "Caching build plan" -- Determine the dependencies of all of the packages in the build plan. We -- handle core packages specially, because some of them will not be in the -- package index. For those, we allow missing packages to exist, and then -- remove those from the list of dependencies, since there's no way we'll -- ever reinstall them anyway. (cores, missingCores) <- addDeps True compilerVersion $ fmap (, Map.empty) corePackages (extras, missing) <- addDeps False compilerVersion packages assert (Set.null missing) $ return MiniBuildPlan { mbpCompilerVersion = compilerVersion , mbpPackages = Map.unions [ fmap (removeMissingDeps (Map.keysSet cores)) cores , extras , Map.fromList $ map goCore $ Set.toList missingCores ] } where goCore (PackageIdentifier name version) = (name, MiniPackageInfo { mpiVersion = version , mpiFlags = Map.empty , mpiPackageDeps = Set.empty , mpiToolDeps = Set.empty , mpiExes = Set.empty , mpiHasLibrary = True }) removeMissingDeps cores mpi = mpi { mpiPackageDeps = Set.intersection cores (mpiPackageDeps mpi) } -- | Add in the resolved dependencies from the package index addDeps :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, MonadThrow m, HasConfig env, MonadBaseControl IO m, MonadCatch m) => Bool -- ^ allow missing -> CompilerVersion -- ^ Compiler version -> Map PackageName (Version, Map FlagName Bool) -> m (Map PackageName MiniPackageInfo, Set PackageIdentifier) addDeps allowMissing compilerVersion toCalc = do menv <- getMinimalEnvOverride platform <- asks $ configPlatform . getConfig (resolvedMap, missingIdents) <- if allowMissing then do (missingNames, missingIdents, m) <- resolvePackagesAllowMissing menv (Map.keysSet idents0) Set.empty assert (Set.null missingNames) $ return (m, missingIdents) else do m <- resolvePackages menv (Map.keysSet idents0) Set.empty return (m, Set.empty) let byIndex = Map.fromListWith (++) $ flip map (Map.toList resolvedMap) $ \(ident, rp) -> (indexName $ rpIndex rp, [( ident , rpCache rp , maybe Map.empty snd $ Map.lookup (packageIdentifierName ident) toCalc )]) res <- forM (Map.toList byIndex) $ \(indexName', pkgs) -> withCabalFiles indexName' pkgs $ \ident flags cabalBS -> do (_warnings,gpd) <- readPackageUnresolvedBS Nothing cabalBS let packageConfig = PackageConfig { packageConfigEnableTests = False , packageConfigEnableBenchmarks = False , packageConfigFlags = flags , packageConfigCompilerVersion = compilerVersion , packageConfigPlatform = platform } name = packageIdentifierName ident pd = resolvePackageDescription packageConfig gpd exes = Set.fromList $ map (ExeName . S8.pack . exeName) $ executables pd notMe = Set.filter (/= name) . Map.keysSet return (name, MiniPackageInfo { mpiVersion = packageIdentifierVersion ident , mpiFlags = flags , mpiPackageDeps = notMe $ packageDependencies pd , mpiToolDeps = Map.keysSet $ packageToolDependencies pd , mpiExes = exes , mpiHasLibrary = maybe False (buildable . libBuildInfo) (library pd) }) return (Map.fromList $ concat res, missingIdents) where idents0 = Map.fromList $ map (\(n, (v, f)) -> (PackageIdentifier n v, Left f)) $ Map.toList toCalc -- | Resolve all packages necessary to install for getDeps :: MiniBuildPlan -> (PackageName -> Bool) -- ^ is it shadowed by a local package? -> Map PackageName (Set PackageName) -> ResolveState getDeps mbp isShadowed packages = execState (mapM_ (uncurry goName) $ Map.toList packages) ResolveState { rsVisited = Map.empty , rsUnknown = Map.empty , rsShadowed = Map.empty , rsToInstall = Map.empty , rsUsedBy = Map.empty } where toolMap = getToolMap mbp -- | Returns a set of shadowed packages we depend on. goName :: PackageName -> Set PackageName -> State ResolveState (Set PackageName) goName name users = do -- Even though we could check rsVisited first and short-circuit things -- earlier, lookup in mbpPackages first so that we can produce more -- usable error information on missing dependencies rs <- get put rs { rsUsedBy = Map.insertWith Set.union name users $ rsUsedBy rs } case Map.lookup name $ mbpPackages mbp of Nothing -> do modify $ \rs' -> rs' { rsUnknown = Map.insertWith Set.union name users $ rsUnknown rs' } return Set.empty Just mpi -> case Map.lookup name (rsVisited rs) of Just shadowed -> return shadowed Nothing -> do put rs { rsVisited = Map.insert name Set.empty $ rsVisited rs } let depsForTools = Set.unions $ mapMaybe (flip Map.lookup toolMap) (Set.toList $ mpiToolDeps mpi) let deps = Set.filter (/= name) (mpiPackageDeps mpi <> depsForTools) shadowed <- fmap F.fold $ Tr.forM (Set.toList deps) $ \dep -> if isShadowed dep then do modify $ \rs' -> rs' { rsShadowed = Map.insertWith Set.union dep (Set.singleton $ PackageIdentifier name (mpiVersion mpi)) (rsShadowed rs') } return $ Set.singleton dep else do shadowed <- goName dep (Set.singleton name) let m = Map.fromSet (\_ -> Set.singleton $ PackageIdentifier name (mpiVersion mpi)) shadowed modify $ \rs' -> rs' { rsShadowed = Map.unionWith Set.union m $ rsShadowed rs' } return shadowed modify $ \rs' -> rs' { rsToInstall = Map.insert name (mpiVersion mpi, mpiFlags mpi) $ rsToInstall rs' , rsVisited = Map.insert name shadowed $ rsVisited rs' } return shadowed -- | Look up with packages provide which tools. type ToolMap = Map ByteString (Set PackageName) -- | Map from tool name to package providing it getToolMap :: MiniBuildPlan -> Map ByteString (Set PackageName) getToolMap mbp = Map.unionsWith Set.union {- We no longer do this, following discussion at: https://github.com/commercialhaskell/stack/issues/308#issuecomment-112076704 -- First grab all of the package names, for times where a build tool is -- identified by package name $ Map.fromList (map (packageNameByteString &&& Set.singleton) (Map.keys ps)) -} -- And then get all of the explicit executable names $ concatMap goPair (Map.toList ps) where ps = mbpPackages mbp goPair (pname, mpi) = map (flip Map.singleton (Set.singleton pname) . unExeName) $ Set.toList $ mpiExes mpi -- | Download the 'Snapshots' value from stackage.org. getSnapshots :: (MonadThrow m, MonadIO m, MonadReader env m, HasHttpManager env, HasStackRoot env, HasConfig env) => m Snapshots getSnapshots = askLatestSnapshotUrl >>= parseUrl . T.unpack >>= downloadJSON -- | Most recent Nightly and newest LTS version per major release. data Snapshots = Snapshots { snapshotsNightly :: !Day , snapshotsLts :: !(IntMap Int) } deriving Show instance FromJSON Snapshots where parseJSON = withObject "Snapshots" $ \o -> Snapshots <$> (o .: "nightly" >>= parseNightly) <*> (fmap IntMap.unions $ mapM parseLTS $ map snd $ filter (isLTS . fst) $ HM.toList o) where parseNightly t = case parseSnapName t of Left e -> fail $ show e Right (LTS _ _) -> fail "Unexpected LTS value" Right (Nightly d) -> return d isLTS = ("lts-" `T.isPrefixOf`) parseLTS = withText "LTS" $ \t -> case parseSnapName t of Left e -> fail $ show e Right (LTS x y) -> return $ IntMap.singleton x y Right (Nightly _) -> fail "Unexpected nightly value" -- | Load up a 'MiniBuildPlan', preferably from cache loadMiniBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, HasGHCVariant env, MonadBaseControl IO m, MonadCatch m) => SnapName -> m MiniBuildPlan loadMiniBuildPlan name = do path <- configMiniBuildPlanCache name let fp = toFilePath path taggedDecodeOrLoad fp $ liftM buildPlanFixes $ do bp <- loadBuildPlan name toMiniBuildPlan (siCompilerVersion $ bpSystemInfo bp) (siCorePackages $ bpSystemInfo bp) (fmap goPP $ bpPackages bp) where goPP pp = ( ppVersion pp , pcFlagOverrides $ ppConstraints pp ) -- | Some hard-coded fixes for build plans, hopefully to be irrelevant over -- time. buildPlanFixes :: MiniBuildPlan -> MiniBuildPlan buildPlanFixes mbp = mbp { mbpPackages = Map.fromList $ map go $ Map.toList $ mbpPackages mbp } where go (name, mpi) = (name, mpi { mpiFlags = goF (packageNameString name) (mpiFlags mpi) }) goF "persistent-sqlite" = Map.insert $(mkFlagName "systemlib") False goF "yaml" = Map.insert $(mkFlagName "system-libyaml") False goF _ = id -- | Load the 'BuildPlan' for the given snapshot. Will load from a local copy -- if available, otherwise downloading from Github. loadBuildPlan :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasHttpManager env, HasStackRoot env) => SnapName -> m BuildPlan loadBuildPlan name = do env <- ask let stackage = getStackRoot env file' <- parseRelFile $ T.unpack file let fp = stackage </> $(mkRelDir "build-plan") </> file' $logDebug $ "Decoding build plan from: " <> T.pack (toFilePath fp) eres <- liftIO $ decodeFileEither $ toFilePath fp case eres of Right bp -> return bp Left e -> do $logDebug $ "Decoding build plan from file failed: " <> T.pack (show e) createTree (parent fp) req <- parseUrl $ T.unpack url $logSticky $ "Downloading " <> renderSnapName name <> " build plan ..." $logDebug $ "Downloading build plan from: " <> url _ <- download req { checkStatus = handle404 } fp $logStickyDone $ "Downloaded " <> renderSnapName name <> " build plan." liftIO (decodeFileEither $ toFilePath fp) >>= either throwM return where file = renderSnapName name <> ".yaml" reponame = case name of LTS _ _ -> "lts-haskell" Nightly _ -> "stackage-nightly" url = rawGithubUrl "fpco" reponame "master" file handle404 (Status 404 _) _ _ = Just $ SomeException $ SnapshotNotFound name handle404 _ _ _ = Nothing -- | Find the set of @FlagName@s necessary to get the given -- @GenericPackageDescription@ to compile against the given @BuildPlan@. Will -- only modify non-manual flags, and will prefer default values for flags. -- Returns @Nothing@ if no combination exists. checkBuildPlan :: (MonadLogger m, MonadThrow m, MonadIO m, MonadReader env m, HasConfig env, MonadCatch m) => Map PackageName Version -- ^ locally available packages -> MiniBuildPlan -> GenericPackageDescription -> m (Either DepErrors (Map PackageName (Map FlagName Bool))) checkBuildPlan locals mbp gpd = do platform <- asks (configPlatform . getConfig) return $ loop platform flagOptions where packages = Map.union locals $ fmap mpiVersion $ mbpPackages mbp loop _ [] = assert False $ Left Map.empty loop platform (flags:rest) | Map.null errs = Right $ if Map.null flags then Map.empty else Map.singleton (packageName pkg) flags | null rest = Left errs | otherwise = loop platform rest where errs = checkDeps (packageName pkg) (packageDeps pkg) packages pkg = resolvePackage pkgConfig gpd pkgConfig = PackageConfig { packageConfigEnableTests = True , packageConfigEnableBenchmarks = True , packageConfigFlags = flags , packageConfigCompilerVersion = compilerVersion , packageConfigPlatform = platform } compilerVersion = mbpCompilerVersion mbp flagName' = fromCabalFlagName . flagName -- Avoid exponential complexity in flag combinations making us sad pandas. -- See: https://github.com/commercialhaskell/stack/issues/543 maxFlagOptions = 128 flagOptions = take maxFlagOptions $ map Map.fromList $ mapM getOptions $ genPackageFlags gpd getOptions f | flagManual f = [(flagName' f, flagDefault f)] | flagDefault f = [ (flagName' f, True) , (flagName' f, False) ] | otherwise = [ (flagName' f, False) , (flagName' f, True) ] -- | Checks if the given package dependencies can be satisfied by the given set -- of packages. Will fail if a package is either missing or has a version -- outside of the version range. checkDeps :: PackageName -- ^ package using dependencies, for constructing DepErrors -> Map PackageName VersionRange -> Map PackageName Version -> DepErrors checkDeps myName deps packages = Map.unionsWith mappend $ map go $ Map.toList deps where go :: (PackageName, VersionRange) -> DepErrors go (name, range) = case Map.lookup name packages of Nothing -> Map.singleton name DepError { deVersion = Nothing , deNeededBy = Map.singleton myName range } Just v | withinRange v range -> Map.empty | otherwise -> Map.singleton name DepError { deVersion = Just v , deNeededBy = Map.singleton myName range } type DepErrors = Map PackageName DepError data DepError = DepError { deVersion :: !(Maybe Version) , deNeededBy :: !(Map PackageName VersionRange) } instance Monoid DepError where mempty = DepError Nothing Map.empty mappend (DepError a x) (DepError b y) = DepError (maybe a Just b) (Map.unionWith C.intersectVersionRanges x y) -- | Find a snapshot and set of flags that is compatible with the given -- 'GenericPackageDescription'. Returns 'Nothing' if no such snapshot is found. findBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, HasGHCVariant env, MonadBaseControl IO m) => [GenericPackageDescription] -> [SnapName] -> m (Maybe (SnapName, Map PackageName (Map FlagName Bool))) findBuildPlan gpds0 = loop where loop [] = return Nothing loop (name:names') = do mbp <- loadMiniBuildPlan name $logInfo $ "Checking against build plan " <> renderSnapName name res <- mapM (checkBuildPlan localNames mbp) gpds0 case partitionEithers res of ([], flags) -> return $ Just (name, Map.unions flags) (errs, _) -> do $logInfo "" $logInfo "* Build plan did not match your requirements:" displayDepErrors $ Map.unionsWith mappend errs $logInfo "" loop names' localNames = Map.fromList $ map (fromCabalIdent . C.package . C.packageDescription) gpds0 fromCabalIdent (C.PackageIdentifier name version) = (fromCabalPackageName name, fromCabalVersion version) displayDepErrors :: MonadLogger m => DepErrors -> m () displayDepErrors errs = F.forM_ (Map.toList errs) $ \(depName, DepError mversion neededBy) -> do $logInfo $ T.concat [ " " , T.pack $ packageNameString depName , case mversion of Nothing -> " not found" Just version -> T.concat [ " version " , T.pack $ versionString version , " found" ] ] F.forM_ (Map.toList neededBy) $ \(user, range) -> $logInfo $ T.concat [ " - " , T.pack $ packageNameString user , " requires " , T.pack $ display range ] $logInfo "" shadowMiniBuildPlan :: MiniBuildPlan -> Set PackageName -> (MiniBuildPlan, Map PackageName MiniPackageInfo) shadowMiniBuildPlan (MiniBuildPlan cv pkgs0) shadowed = (MiniBuildPlan cv $ Map.fromList met, Map.fromList unmet) where pkgs1 = Map.difference pkgs0 $ Map.fromSet (\_ -> ()) shadowed depsMet = flip execState Map.empty $ mapM_ (check Set.empty) (Map.keys pkgs1) check visited name | name `Set.member` visited = error $ "shadowMiniBuildPlan: cycle detected, your MiniBuildPlan is broken: " ++ show (visited, name) | otherwise = do m <- get case Map.lookup name m of Just x -> return x Nothing -> case Map.lookup name pkgs1 of Nothing | name `Set.member` shadowed -> return False -- In this case, we have to assume that we're -- constructing a build plan on a different OS or -- architecture, and therefore different packages -- are being chosen. The common example of this is -- the Win32 package. | otherwise -> return True Just mpi -> do let visited' = Set.insert name visited ress <- mapM (check visited') (Set.toList $ mpiPackageDeps mpi) let res = and ress modify $ \m' -> Map.insert name res m' return res (met, unmet) = partitionEithers $ map toEither $ Map.toList pkgs1 toEither pair@(name, _) = wrapper pair where wrapper = case Map.lookup name depsMet of Just True -> Left Just False -> Right Nothing -> assert False Right parseCustomMiniBuildPlan :: (MonadIO m, MonadCatch m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m) => Path Abs File -- ^ stack.yaml file location -> T.Text -> m MiniBuildPlan parseCustomMiniBuildPlan stackYamlFP url0 = do yamlFP <- getYamlFP url0 yamlBS <- liftIO $ S.readFile $ toFilePath yamlFP let yamlHash = S8.unpack $ B16.encode $ SHA256.hash yamlBS binaryFilename <- parseRelFile $ yamlHash ++ ".bin" customPlanDir <- getCustomPlanDir let binaryFP = customPlanDir </> $(mkRelDir "bin") </> binaryFilename taggedDecodeOrLoad (toFilePath binaryFP) $ do cs <- either throwM return $ decodeEither' yamlBS let addFlags :: PackageIdentifier -> (PackageName, (Version, Map FlagName Bool)) addFlags (PackageIdentifier name ver) = (name, (ver, fromMaybe Map.empty $ Map.lookup name $ csFlags cs)) toMiniBuildPlan (csCompilerVersion cs) Map.empty (Map.fromList $ map addFlags $ Set.toList $ csPackages cs) where getCustomPlanDir = do root <- asks $ configStackRoot . getConfig return $ root </> $(mkRelDir "custom-plan") -- Get the path to the YAML file getYamlFP url = case parseUrl $ T.unpack url of Just req -> getYamlFPFromReq url req Nothing -> getYamlFPFromFile url getYamlFPFromReq url req = do let hashStr = S8.unpack $ B16.encode $ SHA256.hash $ encodeUtf8 url hashFP <- parseRelFile $ hashStr ++ ".yaml" customPlanDir <- getCustomPlanDir let cacheFP = customPlanDir </> $(mkRelDir "yaml") </> hashFP _ <- download req cacheFP return cacheFP getYamlFPFromFile url = do fp <- liftIO $ canonicalizePath $ toFilePath (parent stackYamlFP) FP.</> T.unpack (fromMaybe url $ T.stripPrefix "file://" url <|> T.stripPrefix "file:" url) parseAbsFile fp data CustomSnapshot = CustomSnapshot { csCompilerVersion :: !CompilerVersion , csPackages :: !(Set PackageIdentifier) , csFlags :: !(Map PackageName (Map FlagName Bool)) } instance FromJSON CustomSnapshot where parseJSON = withObject "CustomSnapshot" $ \o -> CustomSnapshot <$> ((o .: "compiler") >>= \t -> case parseCompilerVersion t of Nothing -> fail $ "Invalid compiler: " ++ T.unpack t Just compilerVersion -> return compilerVersion) <*> o .: "packages" <*> o .:? "flags" .!= Map.empty
kairuku/stack
src/Stack/BuildPlan.hs
bsd-3-clause
31,313
0
32
10,568
7,500
3,846
3,654
588
5
module Foo where import Data.Kind (Type) data Foo (a :: Type) = Foo a
sdiehl/ghc
testsuite/tests/parser/should_fail/readFail036.hs
bsd-3-clause
72
0
6
16
30
19
11
-1
-1
module StateMonad () where type State = Int data ST a = S (State -> (a, State)) {-@ data ST a <p1 :: State -> Prop, p2 :: State -> Prop> = S (x::(f:State<p1> -> (a, State<p2>))) @-} {-@ fresh :: ST <{\v -> v>=0}, {\v -> v>=0}> Int @-} fresh :: ST Int fresh = S $ \n -> (n, n-1)
mightymoose/liquidhaskell
tests/neg/state0.hs
bsd-3-clause
306
0
9
90
70
43
27
5
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE FlexibleInstances #-} module Reflex.Cocos2d.Builder.Class ( Time , NodeBuilder(..) , (-<<) , (-<) ) where import Control.Monad.Trans import Control.Monad.Trans.Control import Reflex import Reflex.State import Graphics.UI.Cocos2d (Size) import Graphics.UI.Cocos2d.Node type Time = Float -- ^ in seconds class (Reflex t, Monad m) => NodeBuilder t m | m -> t where getParent :: m Node -- | Execute an action with a different parent withParent :: Node -> m a -> m a getWindowSize :: m (Size Float) -- | Ticks for each frame getFrameTicks :: m (Event t Time) instance NodeBuilder t m => NodeBuilder t (PostBuildT t m) where getParent = lift getParent withParent n m = do pb <- getPostBuild lift $ withParent n (runPostBuildT m pb) getWindowSize = lift getWindowSize getFrameTicks = lift getFrameTicks instance NodeBuilder t m => NodeBuilder t (AccStateT t f s m) where getParent = lift getParent withParent n m = restoreT . return =<< liftWith (\run -> withParent n (run m)) getWindowSize = lift getWindowSize getFrameTicks = lift getFrameTicks -- * Compositions -- | Embed -- e.g., @nodeBuilder -<< child@ infixr 2 -<< (-<<) :: (NodePtr n, NodeBuilder t m) => m n -> m a -> m (n, a) (-<<) node child = do n <- node a <- withParent (toNode n) child return (n, a) -- | Embed with result from first computation thrown away after adding the child infixr 2 -< (-<) :: (NodePtr n, NodeBuilder t m) => m n -> m a -> m a (-<) node child = snd <$> (node -<< child)
lynnard/reflex-cocos2d
src/Reflex/Cocos2d/Builder/Class.hs
mit
1,650
0
12
372
527
285
242
45
1
{-# LANGUAGE OverloadedStrings #-} module Main where import Lens.Micro ((.~)) import Control.Arrow (second) import Data.Yaml (decodeFileEither, prettyPrintParseException) import Paths_DBPnet (version) import Data.Version (showVersion) import Text.Printf (printf) import Options.Applicative import Data.Default import Shelly hiding (FilePath, withTmpDir) import qualified Data.Text as T import qualified Data.Matrix.Unboxed as MU import DBPnet.ReadCount import DBPnet.Correlation import DBPnet.Network import DBPnet.Utils import DBPnet.Constants data Options = Options { input :: FilePath , output :: FilePath , loop :: Maybe FilePath , lambda :: Double , chrSize :: String , pValue :: Double } deriving (Show, Read) parser :: Parser Options parser = Options <$> argument str (metavar "INPUT") <*> strOption ( long "output" <> short 'o' <> value "DBPnet_output" <> metavar "OUTPUT" ) <*> (optional . strOption) ( long "loop" <> short 'l' <> metavar "LOOP_FILE" <> help "a file providing chromosome long range interactions" ) <*> option auto ( short 'r' <> metavar "LAMBDA" <> value 0.3 <> help "cutoff used in glasso algorithm, default: 0.3" ) <*> strOption ( long "chrom_size" <> short 'c' <> metavar "CHROM_SIZE" ) <*> option auto ( long "pvalue" <> short 'p' <> value 0.3 <> help "p-value cutoff for peak calling, default: 0.3" <> metavar "PVALUE" ) defaultMain :: Options -> IO () defaultMain (Options inFl outDir lp cutoff chrsize pvalue) = do chr <- case chrsize of "hg19" -> return hg19ChrSize "mm10" -> return mm10ChrSize _ -> readChrSize chrsize r <- decodeFileEither inFl case r of Left e -> error $ prettyPrintParseException e Right input -> do let output2D = outDir ++ "/Network_2D/" output3D = outDir ++ "/Network_3D/" output2D3D = outDir ++ "/Network_2D_Plus_3D/" shelly $ mkdir_p $ fromText $ T.pack output2D shelly $ mkdir_p $ fromText $ T.pack output3D shelly $ mkdir_p $ fromText $ T.pack output2D3D withTmpDir outDir $ \tmp -> do rc <- readCount input tmp $ chromSize .~ chr $ def cis <- second zeroNeg <$> cisCorMat rc -- Output network built with 2D correlation only outputResults output2D (fst cis) (buildNetwork (snd cis) cutoff) ("2D_correlation", snd cis) Nothing input case lp of Just l -> do t <- second zeroNeg <$> transCorMat rc l -- Output network built with 3D correlation only outputResults output3D (fst t) (buildNetwork (snd t) cutoff) ("3D_correlation", snd t) Nothing input let hybrid = cisTransCombine cis t -- Output network built with 2d and 3d correlation outputResults output2D3D (fst hybrid) (buildNetwork (snd hybrid) cutoff) ("2D_correlation", snd cis) (Just ("3D_correlation", snd t)) input Nothing -> return () where zeroNeg = MU.map (\x -> if x < 0 then 0 else x) main :: IO () main = execParser opts >>= defaultMain where opts = info (helper <*> parser) ( fullDesc <> header (printf "DBPnet-v%s" (showVersion version)) )
kaizhang/DBPnet
src/Main.hs
mit
3,717
0
25
1,293
975
492
483
92
6
module Raindrops (convert) where m :: [(Int, String)] m = [ (3, "Pling"), (5, "Plang"), (7, "Plong")] convert :: Int -> String convert n = w where s = concatMap (\(a, b) -> if n `mod` a == 0 then b else "") m w = if s == "" then show n else s
c19/Exercism-Haskell
raindrops/Raindrops.hs
mit
261
0
12
73
136
82
54
10
3
-- |Netrium is Copyright Anthony Waite, Dave Hewett, Shaun Laurens & Contributors 2009-2018, and files herein are licensed -- |under the MIT license, the text of which can be found in license.txt -- module Main where import Contract (Contract, Time) import Interpreter import DecisionTree import Observations import Paths_netrium import Data.Maybe import Data.Monoid import Control.Monad import qualified Data.Map as Map import Data.Version import System.Environment import System.Exit import System.Console.GetOpt import System.FilePath import Text.XML.HaXml.Namespaces (localName) import Text.XML.HaXml.Types import Text.XML.HaXml.Pretty (document) import Text.XML.HaXml.XmlContent import Text.PrettyPrint.HughesPJ (render) data OutputMode = XmlOutput | TextOutput data Options = Options { optMode :: OutputMode , optTrace :: Bool , optTest :: Bool , optVersion :: Bool } defaultOptions = Options { optMode = XmlOutput , optTrace = False , optTest = False , optVersion = False } options :: [OptDescr (Options -> Options)] options = [Option [] ["xml"] (NoArg (\ opts -> opts { optMode = XmlOutput })) "Output in xml format (this is the default)" ,Option [] ["text"] (NoArg (\ opts -> opts { optMode = TextOutput })) "Output as readable text" ,Option [] ["trace"] (NoArg (\ opts -> opts { optTrace = True })) "Output a trace of contract steps (--text mode only)" ,Option [] ["tests"] (NoArg (\ opts -> opts { optTest = True })) "Run internal tests as well" ,Option [] ["version"] (NoArg (\ opts -> opts { optVersion = True })) "Print version information" ] main :: IO () main = do plainArgs <- getArgs let (optMods, args, errs) = getOpt Permute options plainArgs let opts = foldl (flip ($)) defaultOptions optMods case args of _ | optVersion opts -> printVersion [contract, observations] | null errs -> simulate opts contract observations output where output = addExtension contract "xml" [contract, observations, output] | null errs -> simulate opts contract observations output _ -> exit exit :: IO () exit = do p <- getProgName let txt = "Usage: " ++ p ++ " <contract.xml> <observations.xml> [<output.xml>]\n\n" ++ "Flags:" putStrLn (usageInfo txt options) exitFailure printVersion :: IO () printVersion = do p <- getProgName putStrLn $ "netrium " ++ p ++ " version " ++ showVersion version simulate :: Options -> FilePath -> FilePath -> FilePath -> IO () simulate opts contractFile observationsFile outputFile = do contract <- fReadXml contractFile (SimulationInputs startTime mStopTime mStopWait valObsvns condObsvns optionsTaken choicesMade simState) <- fReadXml observationsFile let initialState = case simState of Nothing -> Left contract Just st -> Right st simenv = SimEnv valObsvns condObsvns optionsTaken choicesMade simout = runContract simenv startTime mStopTime mStopWait initialState when (optTest opts) $ case testRunContract simenv startTime contract of Nothing -> return () Just err -> fail ("internal tests failed: " ++ err) case optMode opts of XmlOutput -> writeFile outputFile (renderContractRunXml simout) TextOutput -> putStr (renderContractRun simout') where simout' | optTrace opts = simout | otherwise = simout { simTrace = TEs [] } renderContractRun :: SimOutputs -> String renderContractRun (SimOutputs (TEs trace) (TEs outs) stopReason stopTime residualContract _ mWaitInfo) = unlines $ [ "============ Contract trace: ============" | not (null trace) ] ++ [ show time' ++ ": " ++ msg | (time', msg) <- trace ] ++ [ "\n============ Contract output: ============" ] ++ [ show out | out <- outs ] ++ [ "\n============ Contract result: ============" , show stopReason , show stopTime ] ++ case mWaitInfo of Nothing -> [] Just (WaitInfo obss mHorizon opts) -> [ "\n============ Horizon: ============" | isJust mHorizon ] ++ [ show horizon | horizon <- maybeToList mHorizon ] ++ [ "\n============ Wait conditions: ============" | not (null obss) ] ++ [ show obs | obs <- obss ] ++ [ "\n============ Available options: ============" | not (null opts) ] ++ [ show opt | opt <- opts ] renderContractRunXml :: SimOutputs -> String renderContractRunXml (SimOutputs _ outs stopReason stopTime residualContract simState mWaitInfo) = render (document (Document prolog emptyST body [])) where prolog = Prolog (Just (XMLDecl "1.0" Nothing Nothing)) [] Nothing [] body = Elem (N "SimulationResult") [] $ toContents (fromTimedEvents outs) ++ toContents stopReason ++ toContents stopTime ++ toContents residualContract ++ toContents simState ++ toContents mWaitInfo data SimulationInputs = SimulationInputs Time (Maybe Time) StopWait (Observations Double) (Observations Bool) (Choices ()) (Choices Bool) (Maybe ProcessState) instance HTypeable SimulationInputs where toHType _ = Defined "ChoiceSeries" [] [] instance XmlContent SimulationInputs where parseContents = do e@(Elem t _ _) <- element ["SimulationInputs"] commit $ interior e $ case localName t of "SimulationInputs" -> do startTime <- parseContents mStopTime <- parseContents mStopWait <- parseContents obsSeriess <- parseContents choiceSeries <- parseContents simState <- parseContents let (valObsvns, condObsvns) = convertObservationSeries obsSeriess (optionsTaken, choicesMade) = convertChoiceSeries choiceSeries return (SimulationInputs startTime mStopTime mStopWait valObsvns condObsvns optionsTaken choicesMade simState) where convertObservationSeries :: [ObservationSeries] -> (Observations Double, Observations Bool) convertObservationSeries obsSeriess = (valObsvns, condObsvns) where valObsvns = Map.fromList [ (var, toTimeSeries ts) | ObservationsSeriesDouble var ts <- obsSeriess ] condObsvns = Map.fromList [ (var, toTimeSeries ts) | ObservationsSeriesBool var ts <- obsSeriess ] convertChoiceSeries :: ChoiceSeries -> (Choices (), Choices Bool) convertChoiceSeries (ChoiceSeries choiceSeriesXml) = (optionsTaken, choicesMade) where optionsTaken = Map.fromListWith mergeEventsBiased [ (cid, TEs [(t,())]) | (t, AnytimeChoice cid) <- choiceSeries ] choicesMade = Map.fromListWith mergeEventsBiased [ (cid, TEs [(t,v)]) | (t, OrChoice cid v) <- choiceSeries ] TEs choiceSeries = toTimedEvents choiceSeriesXml toContents (SimulationInputs startTime mStopTime mStopWait valObsvns condObsvns optionsTaken choicesMade simState) = [mkElemC "SimulationInputs" $ toContents startTime ++ toContents mStopTime ++ toContents mStopWait ++ toContents obsSeriess ++ toContents choiceSeries ++ toContents simState] where obsSeriess = [ ObservationsSeriesDouble var (fromTimeSeries ts) | (var, ts) <- Map.toList valObsvns ] ++ [ ObservationsSeriesBool var (fromTimeSeries ts) | (var, ts) <- Map.toList condObsvns ] choiceSeries = ChoiceSeries $ fromTimedEvents $ TEs $ [ (t, AnytimeChoice cid) | (cid, TEs tes) <- Map.toList optionsTaken , (t, ()) <- tes ] ++ [ (t, OrChoice cid v) | (cid, TEs tes) <- Map.toList choicesMade , (t, v) <- tes ] ------------------------------------------------------------------------------- -- testing -- -- Check: -- * contract and process state can round trip via xml ok -- * trace from single stepping is the same as running from scratch testRunContract :: SimEnv -> Time -> Contract -> Maybe String testRunContract simenv startTime contract | simStopReason overallOut /= simStopReason finalStep = Just $ show (simStopReason overallOut, simStopReason finalStep) | simStopTime overallOut /= simStopTime finalStep = Just $ show (simStopTime overallOut, simStopTime finalStep) | simOutputs overallOut /= foldr1 mergeEventsBiased (map simOutputs steps) = Just $ "outputs do not match:\n" ++ show (simOutputs overallOut) ++ "\nvs:\n" ++ show (foldr1 mergeEventsBiased (map simOutputs steps)) | simTrace overallOut /= foldr1 mergeEventsBiased (map simTrace steps) = Just $ "trace does not match:\n" ++ show (simTrace overallOut) ++ "\nvs:\n" ++ show (foldr1 mergeEventsBiased (map simTrace steps)) | not (all checkXmlRoundTrip steps) = Just "xml round trip failure" | otherwise = Nothing where steps = contractWaitSteps simenv startTime contract finalStep = last steps overallOut = runContract simenv startTime Nothing NoStop (Left contract) checkXmlRoundTrip simOut = roundTripProperty (simStopContract simOut) && roundTripProperty (simStopState simOut) roundTripProperty :: (XmlContent a, Eq a) => a -> Bool roundTripProperty x = readXml (showXml False x) == Right x contractWaitSteps :: SimEnv -> Time -> Contract -> [SimOutputs] contractWaitSteps simenv startTime contract = remainingSteps step0 where step0 = runContract simenv startTime Nothing StopFirstWait (Left contract) remainingSteps out | simStopReason out == StoppedWait = out : remainingSteps out' | otherwise = out : [] where resumeState@(PSt resumeTime _ _) = simStopState out out' = runContract simenv resumeTime Nothing StopNextWait (Right resumeState)
netrium/Netrium
tool/Simulate.hs
mit
10,953
0
17
3,456
2,789
1,418
1,371
225
4
module Calc where import ExprT import Parser eval :: ExprT -> Integer eval (Lit x) = x eval (Add x y) = (eval x) + (eval y) eval (Mul x y) = (eval x) * (eval y) evalStr :: String -> Maybe Integer evalStr x = case parseExp Lit Add Mul x of Nothing -> Nothing Just y -> Just (eval y) class Expr expr where lit :: Integer -> expr add :: expr -> expr -> expr mul :: expr -> expr -> expr instance Expr ExprT where lit x = Lit x add x y= Add x y mul x y= Mul x y reify :: ExprT -> ExprT reify = id instance Expr Integer where lit x = x add x y= x + y mul x y= x * y instance Expr Bool where lit x = x > 0 add x y= x || y mul x y= x && y newtype MinMax = MinMax Integer deriving (Eq, Show) newtype Mod7 = Mod7 Integer deriving (Eq, Show) instance Expr MinMax where lit x = MinMax x add (MinMax x) (MinMax y) = MinMax (max x y) mul (MinMax x) (MinMax y) = MinMax (min x y) instance Expr Mod7 where lit x = Mod7 (x `mod` 7) add (Mod7 x) (Mod7 y) = Mod7 ((x + y) `mod` 7) mul (Mod7 x) (Mod7 y) = Mod7 ((x * y) `mod` 7) testExp :: Expr a => Maybe a testExp = parseExp lit add mul "(3 * -4) + 5"
gscalzo/HaskellTheHardWay
cis194/week5/Calc.hs
mit
1,222
0
10
392
615
314
301
41
2
{-- Copyright (c) 2012 Gorka Suárez García Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --} -- *************************************************************** -- Module: MathUtil -- This module contains math utility functions. -- *************************************************************** module MathUtil where import qualified Data.List as List -- *************************************************************** -- Checks if a conversion from an integral value to -- double is secure or not. checkSecureConversion :: (Integral a) => a -> Bool checkSecureConversion x = truncate y == x where y = fromIntegral x :: Double -- Checks if the integral a is multiple of b. multipleOf :: (Integral a) => a -> a -> Bool multipleOf a b = (mod a b) == 0 -- Checks if the integral a is multiple of all the numbers -- inside the list bs. multipleOfList :: (Integral a) => a -> [a] -> Bool multipleOfList a bs = and [multipleOf a x | x <- bs] -- *************************************************************** -- Calculates the integer square root in a fast way. squareRoot :: (Integral a) => a -> a squareRoot x = truncate $ sqrt $ (fromIntegral x :: Double) -- Calculates the integer square root in a secure way. squareRoot' :: (Integral a) => a -> a squareRoot' v = if checkSecureConversion v then squareRoot v else secureSquareRoot v -- Finds a range of values to find the integer square root. findSqrtRange :: (Integral a) => a -> a -> (a, a) findSqrtRange v br = fsr 0 1 where shift 1 = 2 shift x = x ^ 2 fsr prev next = if (next + br) ^ 2 < v then fsr next (shift next) else (br + prev, br + next) -- Calculates the integer square root in a secure way. secureSquareRoot :: (Integral a) => a -> a secureSquareRoot v = if v < 2 then v else step 0 where step lwr = if nlwr ^ 2 == v then nlwr else if nupr ^ 2 == v then nupr else if nupr - nlwr > 1 then step nlwr else nlwr where (nlwr, nupr) = findSqrtRange v lwr -- *************************************************************** -- Checks if a number is prime or not. isPrime :: (Integral a) => a -> Bool isPrime 2 = True isPrime n = not $ or [multipleOf n x | x <- 2:[3,5..upperLimit]] where upperLimit = squareRoot n + 1 -- The list of prime numbers. primesList = [x | x <- [1..], isPrime x] -- The list of prime numbers, without number 1. primesList' = [x | x <- [2..], isPrime x] -- *************************************************************** -- Gets the prime factors of a number. getFactors :: (Integral a) => a -> [a] getFactors number = reverse $ getFactors' number -- Gets the prime factors of a number. The result is reversed. getFactors' :: (Integral a) => a -> [a] getFactors' 1 = [1] getFactors' number = gf number [x | x <- [2..], isPrime x] [1] where gf n (p:ps) rs = if p > n then rs else if multipleOf n p then gf (div n p) (p:ps) (p:rs) else gf n ps rs -- Gets the prime factors of a number, without number one. -- The result is reversed. getFactors'' :: (Integral a) => a -> [a] getFactors'' 1 = [1] getFactors'' number = gf number [x | x <- [2..], isPrime x] [] where gf n (p:ps) rs = if p > n then rs else if multipleOf n p then gf (div n p) (p:ps) (p:rs) else gf n ps rs -- Groups a given sorted list of factors. groupFactors :: (Integral a) => [a] -> [[a]] groupFactors [] = [] groupFactors lst = gf lst (head lst) [] [] where gf [] v ac rs = rs ++ [ac] gf (x:xs) v ac rs = if x == v then gf xs v (x:ac) rs else gf xs x [x] (rs ++ [ac]) -- *************************************************************** -- The multi-node tree data type. data Tree a = Empty | Node a (TreeList a) deriving Show type TreeList a = [Tree a] -- Calculates the number of nodes inside a tree. treeLength :: Tree a -> Int treeLength Empty = 0 treeLength t = f t where f Empty = 0 f (Node x []) = 1 f (Node x ns) = 1 + sum [f n | n <- ns] -- Makes subgroups from a factors list of the same number. makeFactorsGroups :: (Integral a) => [a] -> [[a]] makeFactorsGroups [] = [] makeFactorsGroups [x] = [[x]] makeFactorsGroups xs = [drop n xs | n <- [0..length xs - 1]] -- Makes a divisors multi-node tree. makeDivisorsTree :: (Integral a) => [[a]] -> Tree a makeDivisorsTree [] = Empty makeDivisorsTree [x] = Node (product x) [] makeDivisorsTree (x:xs) = Node (product x) (mdst xs []) where mdst [] rs = rs mdst (y:ys) rs = mdst ys (rs ++ ns) where yg = makeFactorsGroups y ns = [makeDivisorsTree (z:ys) | z <- yg] -- Uses a multi-node tree to obtain the divisors. getDivisorsFromTree :: (Integral a) => a -> Tree a -> [a] getDivisorsFromTree _ Empty = [] getDivisorsFromTree v (Node x []) = [div v x] getDivisorsFromTree v (Node x ys) = r:rs where r = div v x rs = concat [getDivisorsFromTree r y | y <- ys] -- *************************************************************** -- Gets the divisors of a number. getDivisors :: (Integral a) => a -> [a] getDivisors n = [x | x <- [1..n], multipleOf n x] -- Gets the divisors of a number from a factors list. getDivisorsFromFactors :: (Integral a) => [a] -> [a] getDivisorsFromFactors [] = [] getDivisorsFromFactors [x] = [x] getDivisorsFromFactors lst = rs where dt = makeDivisorsTree $ groupFactors lst rs = getDivisorsFromTree (product lst) dt -- Gets the divisors of a number from a factors list. getDivisorsFromFactors' :: (Integral a) => [a] -> [a] getDivisorsFromFactors' lst = List.nub victims where victims = [product x | x <- List.subsequences lst] -- Gets the divisors of a number from a factors list. getSortedDivisorsFromFactors :: (Integral a) => [a] -> [a] getSortedDivisorsFromFactors lst = List.sort victims where victims = getDivisorsFromFactors lst -- Gets the divisors of a number from a factors list. getSortedDivisorsFromFactors' :: (Integral a) => [a] -> [a] getSortedDivisorsFromFactors' lst = List.sort victims where victims = getDivisorsFromFactors' lst -- *************************************************************** -- Calculates a quadratic equation. quadraticEquation :: (Floating a) => a -> a -> a -> (a, a) quadraticEquation a b c = (r1, r2) where aux = sqrt (b ^ 2 - 4 * a * c) r1 = (-b + aux) / (2 * a) r2 = (-b - aux) / (2 * a) -- Calculates an integer quadratic equation. quadraticEquation' :: (Integral a) => a -> a -> a -> (a, a) quadraticEquation' a b c = (r1, r2) where aux = squareRoot (b ^ 2 - 4 * a * c) r1 = div (-b + aux) (2 * a) r2 = div (-b - aux) (2 * a) -- *************************************************************** -- Gets the triangle number of a position in the sequence. getTriangleNumber :: Integer -> Integer getTriangleNumber n = if n < 0 then 0 else div (n * (n + 1)) 2 -- Gets the position in the sequence of a triangle number. triangleNumberEquation :: Integer -> Integer triangleNumberEquation n = div (aux - 1) 2 where aux = squareRoot' (1 + 8 * n) -- Validates if a number is a triangle number or returns 0. fromTriangleNumber :: Integer -> Integer fromTriangleNumber n = if n == getTriangleNumber r then r else 0 where r = triangleNumberEquation n -- Checks if a number is a triangle number. isTriangleNumber :: Integer -> Bool isTriangleNumber n = n == getTriangleNumber r where r = triangleNumberEquation n -- Gets the nearest triangle numbers of a value. getTriangleNumbersNear :: Integer -> (Integer, Integer) getTriangleNumbersNear n = (r, r + 1) where r = triangleNumberEquation n -- ***************************************************************
gorkinovich/Haskell
Modules/MathUtil.hs
mit
8,997
0
12
2,172
2,475
1,334
1,141
133
5
module OpenAI.Gym.Prelude ( module P ) where import Control.Monad as P import Control.Monad.Loops as P import Control.Monad.Trans.Except as P (runExceptT) import Data.Aeson as P import Data.HashMap.Strict as P (HashMap) import Data.Proxy as P import Data.Text as P (Text) import GHC.Generics as P import Network.HTTP.Client as P hiding (Proxy, responseBody, responseStatus) import Servant.API as P import Servant.Client as P import Servant.HTML.Lucid as P (HTML)
Lucsanszky/gym-http-api
binding-hs/src/OpenAI/Gym/Prelude.hs
mit
770
0
5
370
135
95
40
15
0
module C07.Geometry(sphereVolume, sphereArea, cubeVolume, cubeArea, cuboidArea, cuboidVolume) where sphereVolume :: Float -> Float sphereVolume radius = (4.0 / 3.0) * pi * (radius ^ 3) sphereArea :: Float -> Float sphereArea radius = 4 * pi * (radius ^ 2) cubeVolume :: Float -> Float cubeVolume side = cuboidVolume side side side cubeArea :: Float -> Float cubeArea side = cuboidArea side side side cuboidVolume :: Float -> Float -> Float -> Float cuboidVolume a b c = rectangleArea a b * c cuboidArea :: Float -> Float -> Float -> Float cuboidArea a b c = rectangleArea a b * 2 + rectangleArea a c * 2 + rectangleArea c b * 2 rectangleArea :: Float -> Float -> Float rectangleArea a b = a * b
Sgoettschkes/learning
haskell/LearnYouAHaskell/C07/Geometry.hs
mit
740
0
10
173
274
143
131
15
1
{-# LANGUAGE OverloadedStrings #-} module Web.JsonParser where import qualified Data.Text as T import Data.Time import Data.Maybe import Web.Utils import Model.Types checkJson :: [Maybe T.Text] -> Maybe [T.Text] checkJson xs | null $ filter isNothing xs = Just (map fromJust xs) | otherwise = Nothing jsonToPost :: [(T.Text, T.Text)] -> Maybe Post jsonToPost params = case chkp of Nothing -> Nothing Just pars -> createPost pars dummyTime dummyTime where chkp = checkJson $ findParams params ["title", "categories", "content", "type", "access"] createPost :: [T.Text] -> UTCTime -> UTCTime -> Maybe Post createPost postParam crtTime modTime | isNothing ty || isNothing ac = Nothing | otherwise = Just $ Post (procTitle $ postParam !! 0) (procCategories $ postParam !! 1) (postParam !! 2) crtTime modTime (fromJust ty) (fromJust ac) where ty = (textToInt $ postParam !! 3) ac = (textToInt $ postParam !! 4) procTitle "" = Nothing procTitle text = Just text procCategories "" = Nothing procCategories text = Just $ T.splitOn ", " text dummyTime :: UTCTime dummyTime = parseTimeOrError True defaultTimeLocale "%d.%m.%Y %H:%M" "01.01.2000 00:00"
elfeck/elfeckcom
src/Web/JsonParser.hs
mit
1,368
0
10
401
414
214
200
35
3
{-# LANGUAGE PackageImports #-} {-# OPTIONS_GHC -fno-warn-dodgy-exports -fno-warn-unused-imports #-} -- | Reexports "Data.Bitraversable.Compat" -- from a globally unique namespace. module Data.Bitraversable.Compat.Repl ( module Data.Bitraversable.Compat ) where import "this" Data.Bitraversable.Compat
haskell-compat/base-compat
base-compat/src/Data/Bitraversable/Compat/Repl.hs
mit
304
0
5
31
28
21
7
5
0
module LearnParsers where import Text.Trifecta stop :: Parser a stop = unexpected "Stop" one = char '1' one' = one >> stop -- read two characters, '1', and '2' oneTwo = char '1' >> char '2' -- read two characters, '1' and '2', then die oneTwo' = oneTwo >> stop testParse :: Parser Char -> IO () testParse p = print $ parseString p mempty "123" testParseStr :: Parser String -> String -> IO () testParseStr p s = print $ parseString p mempty s pNL s = putStrLn ('\n' : s) main = do pNL "stop:" testParse stop pNL "one:" testParse one pNL "one':" testParse one' pNL "oneTwo:" testParse oneTwo pNL "oneTwo':" testParse oneTwo' -- Exercises: Parsing Practice -- 1. There’s a combinator that’ll let us mark that we expect an input stream to -- be “finished” at a particular point in our parser. In the parsers library -- this is simply called eof (end-of-file) and is in the Text.Parser.Combinators -- module. See if you can make the one and oneTwo parsers fail because they -- didn’t exhaust the input stream! myMain = do pNL "one with fail:" testParse (one >> eof >> stop) pNL "oneTwo with fail:" testParse (oneTwo >> eof >> stop) -- 2. Use string to make a Parser that parses “1”,“12”, and “123” out of the -- example input respectively. Try combining it with stop too. That is, a single -- parser should be able to parse all three of those strings. myMain2 = do pNL "string 1" testParseStr (string "1") "1" pNL "string 12" testParseStr (string "12") "12" pNL "string 123" testParseStr (string "123") "123" -- 3. Try writing a Parser that does what string does, but using char. stringParser (s:ss) = foldl (>>) (char s) $ fmap char ss myMain3 = do pNL "using custom string parser" testParse (stringParser "123")
diminishedprime/.org
reading-list/haskell_programming_from_first_principles/24_03.hs
mit
1,793
0
10
368
415
195
220
40
1
{-# LANGUAGE OverloadedStrings #-} module Main where import System.Environment import Parser import Eval import Pretty import Syntax import qualified Data.Text as T import qualified Data.Text.IO as T hoistError :: Either Error (Term, Type) -> T.Text hoistError ex = case ex of Left err -> T.pack $ "\ESC[1;31mError: \ESC[0m" ++ err Right (x,y) -> T.pack $ ppterm x ++ ":" ++ pptype y main :: IO () main = do (file:_) <- getArgs contents' <- readFile file let program = parseProgram "<from file>" contents' case program of Left err -> print err Right ast -> mapM_ (T.putStrLn . hoistError . typeAndEval) ast
kellino/TypeSystems
typedArith/Main.hs
mit
669
0
14
163
226
118
108
22
2
module Main where import Lambda main :: IO () main = do _ <- putStrLn "Enter term" input <- getContents let term = parseTerm input _ <- putStrLn (seq term "Parsed term:") _ <- putStrLn . show $ term _ <- putStrLn "" _ <- putStrLn $ "Size: " ++ (show . getSize $ term) _ <- putStrLn "" let freeVariables = getFreeVariables term _ <- printSeparateLines "free variables" freeVariables let redexes = getRedexes term _ <- printSeparateLines "redexes" redexes return () printSeparateLines :: (Show a, Foldable t) => String -> t a -> IO () printSeparateLines s xs = do _ <- putStrLn ((show . length $ xs) ++ " " ++ s ++ ":") _ <- mapM_ (putStrLn . (++ "\n") . show) xs return () parseTerm :: String -> Term String parseTerm = read
scott-fleischman/lambda-calculus
haskell/lambda/app/Main.hs
mit
763
0
15
176
320
151
169
24
1
module Carter where import qualified Data.ByteString.Lazy as BL import qualified Data.Foldable as F import Data.Csv.Streaming type BaseballStats = (BL.ByteString, Int, BL.ByteString, Int) baseballStats :: BL.ByteString -> Records BaseballStats baseballStats = decode NoHeader fourth :: (a, b , c, d) -> d fourth (_, _ , _, d) = d summer :: (a, b, c, Int) -> Int -> Int summer = (+) . fourth getAtBatsSum :: FilePath -> IO Int getAtBatsSum battingCsv = do csvData <- BL.readFile battingCsv return $ F.foldr summer 0 (baseballStats csvData)
mjamesruggiero/carter
src/Carter.hs
mit
553
0
10
99
202
117
85
15
1
{-# LANGUAGE GADTs, LambdaCase, OverloadedStrings, StandaloneDeriving #-} module Language.RobotC.Data.Program ( RobotC , R , Stmt (..) , Expr (..) , Var (..) , ArrayVar (..) , IndexVar (..) , Ident, unIdent, mkIdent ) where import Prelude as P import Control.Monad.Trans.Writer import Data.String import Language.RobotC.Data.Types as R type RobotC = Writer [Stmt] () type R = Expr data Stmt where ExprStmt :: Expr t -> Stmt Block :: [Stmt] -> Stmt Call0v :: Ident -> Stmt Call1v :: Ident -> Expr a -> Stmt Call2v :: Ident -> Expr a -> Expr b -> Stmt Call3v :: Ident -> Expr a -> Expr b -> Expr c -> Stmt Assign :: Var t -> Expr t -> Stmt IndexAssign :: IndexVar t -> Expr t -> Stmt AddAssign, SubAssign, MultAssign :: Num t => Var t -> Expr t -> Stmt IntDivAssign :: Integral t => Var t -> Expr t -> Stmt FracDivAssign :: Fractional t => Var t -> Expr t -> Stmt ModAssign :: Integral t => Var t -> Expr t -> Stmt BitAndAssign, BitOrAssign, BitXorAssign :: Integral t => Var t -> Expr t -> Stmt LShiftAssign, RShiftAssign :: Integral t => Var t -> Expr t -> Stmt Incr, Decr :: Num t => Var t -> Stmt Dec :: Var t -> Expr t -> Stmt ArrayDec :: ArrayVar t -> [Expr t] -> Stmt While :: Expr Bool -> Stmt -> Stmt If :: Expr Bool -> Stmt -> Stmt IfElse :: Expr Bool -> Stmt -> Stmt -> Stmt deriving instance Show Stmt data Expr t where Lit :: RType t => t -> Expr t NotExpr :: Expr Bool -> Expr Bool AndExpr, OrExpr :: Expr Bool -> Expr Bool -> Expr Bool EqExpr, NotEqExpr :: Expr t -> Expr t -> Expr Bool LTExpr, LTEqExpr, GTExpr, GTEqExpr :: Num t => Expr t -> Expr t -> Expr Bool AddExpr, SubExpr, MultExpr :: Num t => Expr t -> Expr t -> Expr t IntDivExpr :: Integral t => Expr t -> Expr t -> Expr t FracDivExpr :: Fractional t => Expr t -> Expr t -> Expr t ModExpr :: Integral t => Expr t -> Expr t -> Expr t NegExpr :: Num t => Expr t -> Expr t BitAndExpr, BitOrExpr, BitXorExpr :: Integral t => Expr t -> Expr t -> Expr t LShiftExpr, RShiftExpr :: Integral t => Expr t -> Expr t -> Expr t VarExpr :: Var t -> Expr t IndexVarExpr :: IndexVar t -> Expr t Call0 :: Ident -> Expr t Call1 :: Ident -> Expr a -> Expr t Call2 :: Ident -> Expr a -> Expr b -> Expr t Call3 :: Ident -> Expr a -> Expr b -> Expr c -> Expr t CondExpr :: Expr Bool -> Expr t -> Expr t -> Expr t deriving instance Show (Expr t) instance (Num t, RType t) => Num (Expr t) where (+) = ifLit2 (+) AddExpr (-) = ifLit2 (-) SubExpr (*) = ifLit2 (*) MultExpr negate = ifLit1 negate NegExpr abs = ifLit1 abs $ Call1 "abs" signum = ifLit1 signum $ Call1 "sgn" fromInteger = Lit . fromInteger instance (Fractional t, RType t) => Fractional (Expr t) where (/) = ifLit2 (/) FracDivExpr fromRational = Lit . fromRational instance (Floating t, RType t) => Floating (Expr t) where pi = Lit pi exp = ifLit1 exp $ Call1 "exp" log = ifLit1 log $ Call1 "log" sqrt = ifLit1 sqrt $ Call1 "sqrt" (**) = ifLit2 (**) $ Call2 "pow" logBase = ifLit2 logBase $ \b x -> log x / log b sin = ifLit1 sin $ Call1 "sin" cos = ifLit1 cos $ Call1 "cos" tan = ifLit1 tan $ Call1 "tan" asin = ifLit1 asin $ Call1 "asin" acos = ifLit1 acos $ Call1 "acos" atan = ifLit1 atan $ Call1 "atan" sinh = ifLit1 sinh $ error "sinh not yet implemented" cosh = ifLit1 cosh $ error "cosh not yet implemented" tanh = ifLit1 tanh $ error "tanh not yet implemented" asinh = ifLit1 asinh $ error "asinh not yet implemented" acosh = ifLit1 acosh $ error "acosh not yet implemented" atanh = ifLit1 atanh $ error "atanh not yet implemented" instance (IsString t, RType t) => IsString (Expr t) where fromString = Lit . fromString ifLit1 :: RType b => (a -> b) -> (Expr a -> Expr b) -> Expr a -> Expr b ifLit1 lit notLit = \case Lit x -> Lit $ lit x x -> notLit x ifLit2 :: RType c => (a -> b -> c) -> (Expr a -> Expr b -> Expr c) -> Expr a -> Expr b -> Expr c ifLit2 lit notLit = curry $ \case (Lit x, Lit y) -> Lit $ lit x y (x, y) -> notLit x y data Var t where Var :: (RType t) => Ident -> Var t deriving instance Show (Var t) instance RType t => IsString (Var t) where fromString = Var . mkIdent data ArrayVar t where ArrayVar :: RType t => Ident -> ArrayVar t deriving instance Show (ArrayVar t) instance RType t => IsString (ArrayVar t) where fromString = ArrayVar . mkIdent data IndexVar t where IndexVar :: (RType t, Integral i) => ArrayVar t -> Expr i -> IndexVar t deriving instance Show (IndexVar t) newtype Ident = Ident { unIdent :: P.String } deriving (Show) instance IsString Ident where fromString = mkIdent mkIdent :: P.String -> Ident mkIdent (x:xs) | x `elem` '_' : ['A'..'Z'] ++ ['a'..'z'] , all (`elem` '_' : ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9']) xs = Ident (x:xs) mkIdent x = error $ show x ++ " is not a valid RobotC identifier"
qsctr/haskell-robotc
src/Language/RobotC/Data/Program.hs
mit
5,043
26
13
1,339
2,118
1,068
1,050
-1
-1
module ReverseWordsTests where import ReverseWords import Test.Hspec tests :: SpecWith () tests = describe "ReverseWords" $ it "should work for the provided examples" $ do reverseWords "Hello World" `shouldBe` "World Hello" reverseWords "Hello CodeEval" `shouldBe` "CodeEval Hello"
RaphMad/CodeEval
test/ReverseWordsTests.hs
mit
299
0
9
54
65
34
31
8
1
{-# OPTIONS_GHC -w #-} {-# LANGUAGE RebindableSyntax, NoImplicitPrelude #-} -- | -- Module : Control.Delimited.Tutorial -- Copyright : (c) Oleg Kiselyov 2007-2013, (c) Austin Seipp 2012-2013 -- License : MIT -- -- Maintainer : mad.one@gmail.com -- Stability : experimental -- Portability : portable -- -- This module provides an introductory tutorial in the -- \"Introduction\" section and beyond, followed by examples. Finally, -- there's some discussion behind the theory and design of the -- library, with references. -- module Control.Delimited.Tutorial ( -- * Introduction -- $intro -- * An primer on continuations -- $callcc-primer -- ** Delimited -- $primer-delimcc -- * Examples -- $examples -- ** Simple answer-type modification -- $example-simple -- ** First-class @printf@ -- $example-printf -- ** Walking binary trees -- $example-btrees -- * Other notes -- $othernotes -- ** Indexed monads -- $pmonads -- ** Using @do@-notation -- $donotation -- ** Rank-2 typing -- $rankntypes -- * Further reading -- $morereading -- * References -- $refs ) where import Control.Indexed.Prelude import Control.Delimited {- $intro @asai@ is a minimal library for /delimited continuations/, a \'slice\' of a continuation that can be invoked as a function and composed. -} {- $callcc-primer Continuations are a well known abstraction for 'picking up where you left off.' When you use @call/cc@ traditionally in something like scheme, you pass it a function @f@ which receives a function @k@, and when @k@ is invoked you 'call the continuation' and return where @call/cc@ left off. In this sense, @k@ is a reification of the state you were in when you invoked @f@. But there is another type of continuation: a delimited one. With delimited continuations, it is possible to exert control over the exact /frame/ of the computation that is captured. By being able to slice just small execution contexts, we can compose delimited continuations very easily. In the same way that continuations form a monad, so do delimited continuations. This package provides a delimited continuation monad which implements truly polymorphic @shift@ and @reset@ operators, via /answer type polymorphism/, which allows the results of a delimited computation to vary. This implementation (using indexed monads) was first implemented by - and this package derived from - Oleg Kiselyov [1]. It directly implements the typing rules of Kenichi Asai's lambda/shift calculus [2], featuring answer type polymorphism and modification. A general tutorial on delimited continuations in OchaCaml (with code in Haskell and OCaml) from Asai/Kiselyov is available [3]. A more traditional delimited continuation monad is available in the @CC-delcont@ package [4]. The @CC-delcont@ tutorial [5] serves as a basis for this tutorial (thanks to Dan Doel!) -} {- $primer-delimcc Let us consider the expression: -} {- $examples In the subsequent sections, we'll cover some examples of using this library in a few simple forms, which should form a basis for reasoning about how to use it. The same ideas should apply to other delimited continuation libraries or interfaces (i.e. scheme, ocaml, ochacaml, etc.) -} {- $example-simple Basic answer type modification is very simple to demonstrate. Consider that we @shift@ some computation and discard the continuation @k@. Then the answer type of the enclosing @'reset'@ changes to the return type of the @shift@ed block. For example: >>> runDelim $ reset $ shift2 (\_ -> returnI "hello") !>>= \r -> returnI (r + 1) "hello" Here, the initial answer type of the enclosing @'reset'@ is initially @Int@, because the return of the reset is @Int@. However, we use @'shift2'@, which changes the answer type by /discarding/ the delimited continuation, and simply returning a @'String'@. On the other hand, it is also clear when the answer type is polymorphic and cannot be changed. Instead consider this example: >>> :t runDelim $ reset $ shift2 (\k -> returnI k) !>>= \r -> returnI (r + (1::Int)) runDelim $ reset $ shift2 (\k -> returnI k) !>>= \r -> returnI (r + (1::Int)) :: Int -> Delim s s Int Here, the answer type is /not/ changed by the call to @'shift2'@: the continuation k is not discarded, but returned. This \'carries'\ the answer type variables with the value, enforcing the input and output answer types are the same. And so if we were to invoke @k@, then the answer type of the @'reset'@ may still only be 'Int': that is the only type of value we may place in the hole left by @'shift2'@. -} {- $example-printf We will now write a simple, typesafe @printf@ function using delimited continuations. The key observation is that when we write a term like: @ printf \"foo %s bar %d\" x y @ we are actually filling in /holes/ in place of the @%s@ and @%d@ specifiers. Instead, we can write a type safe formatter that 'fills in' the holes correctly by construction. Let us first define formatting functions that will properly convert arguments to a @'String'@. The trivial one for a @'String'@ itself is obvious: @ str :: String -> String str = id @ We may also write one for @'Int'@s: @ int :: Int -> String int = show @ We observe that a call to @printf@ is similar to delimiting the computation of the format string argument. So we define @printf@ as: @ printf p = 'reset' p @ Now we will define a type-safe formatter, that will \'plug\' the value into our string properly: @ fmt to = 'shift2' (\\k -> 'returnI' (k . to)) @ When we call @fmt@, we will /abort/ back to the enclosing @'reset'@, returning a function. The function is @k . to@, which will convert our value to a @'String'@ and plug it into the enclosing hole that @fmt@ left behind. Now we will define some operators for chaining these function returns, and concatenating the string results: @ f $$ x = f '!>>=' ($ x) infixl 1 $$ f ^$ g = 'liftIxM2' (++) f g run = 'runDelim' @ Now, we can write: @ test1 :: String test1 = run $ printf ('returnI' \"hello world!\") @ And more interestingly: @ test2 :: String test2 = run $ sprintf (fmt int) $$ 1 @ We may also format multiple arguments in a type safe manner, by concatenating the formatters with @^$@ and passing arguments via @$$@: @ test3, test4 :: String test3 = run $ sprintf ('returnI' \"goodbye \" ^$ fmt str ^$ 'returnI' \"!\") $$ \"world\" test4 = run $ sprintf (fmt str ^$ 'returnI' \" = \" ^$ fmt int) $$ \"x\" $$ 3 @ It is an error to pass a value of an incorrect type to the corresponding formatter. The full code is available in @examples/Printf.hs@. -} {- $example-btrees Here, we will... @ [-\# LANGUAGE RankNTypes \#-] module Tree where import Control.Delimited \-- Binary trees data Tree a = Leaf | Node (Tree a) (Tree a) a deriving (Show, Eq) make_tree :: Int -> Tree Int make_tree j = go j 1 where go 0 _ = Leaf go i x = Node (go (i-1) $ 2*x) (go (i-1) $ 2*x+1) x tree1 = make_tree 3 tree2 = make_tree 4 \-- Coroutines as monadic lists. data Coro a = Done | Resume a (forall s. 'Delim' s s (Coro a)) walk_tree x = 'runDelim' (walk_tree' x '!>>' 'returnI' Done) walk_tree' Leaf = 'returnI' () walk_tree' (Node l r x) = walk_tree' l '!>>' yield x '!>>' walk_tree' r where yield n = 'shift2' (\\k -> 'returnI' $ Resume n $ k ()) walk1 :: Show a => Tree a -> IO () walk1 t = go (walk_tree t) where go Done = return () go (Resume x k) = print x >> go ('runDelim' k) @ The full code is available in @examples/Tree.hs@. -} {- $othernotes Here we discuss some of the design aspects of the library, particularly for those wondering why we need indexed (or /indexed/) monads, and how we can reconcile this with @do@-notation. -} {- $pmonads While reading this tutorial, you may wonder why we use special operators (like '!>>=' that mimmick 'Prelude.>>=') for delimited computations, instead of regular operators from the 'Monad' typeclass. The reason for this is that in order to ensure the answer type of delimited computation is polymorphic, we need the monad to \'carry\' the answer types around. Consider the vanilla 'Monad' typeclass. It is defined like this (with explicit kind signatures): @ class 'Monad' (m :: * -> *) where ... @ The @m@ type constructor abstracts over a single type variable. It is possible to make types with multiple type variables an instance of 'Monad' of course, but their non-abstracted type variables must be fixed. As an example, considering the instance for @'Either' e@: @ instance 'Monad' ('Either' e) where ... @ Note the type variable @e@ is fixed over the definition of a term of type @'Either' e :: * -> *@. If you have something like: @ thing :: a -> 'Either' String a thing a = do ... @ Then in the body we may say: @ x <- Left \"oh no!\" @ But we can never say: @ x <- Left False @ because @e@ is fixed to 'String'. Another example is that the 'Control.Monad.State.State' monad always has a fixed state type, and it may never change over the course of the computation. Indexed monads solve this problem by \'expanding\' the kind of @m@ in the 'Monad' typeclass. The result is 'IxMonad', which is defined as: @ class 'IxMonad' (m :: * -> * -> * -> *) where 'returnI' :: t -> m a a t ('!>>=') :: m b g s -> (s -> m a b t) -> m a g t @ Note the new type variables: these represent the input and output answer types of a delimited computation. We can see that 'returnI' is fully polymorphic in its answer type: a statement of @returnI foo@ in a 'Delim' simply does not change the answer type at all. Note the answer types present in 'Control.Indexed.Monad.!>>=': we have an answer type of @a b@ and @b g@, meaning we can get an overall answer type of @a g@. This polymorphism in the definition of 'Control.Indexed.Monad.!>>=' is what gives us answer type polymorphism: it means delimited computations may change the output answer type. -} {- $donotation It's possible to use GHC's @RebindableSyntax@ extension to re-define @do@ notation to use the 'IxMonad' type class. Begin your module by hiding the regular 'Monad' methods, and then redefine 'Prelude.>>=' and 'Prelude.return'. Feel free to redefine other operators too. Here's an example (you'll need to fix the @LANGUAGE@ pragma yourself on the first line, since Haddock eats it otherwise): @ [-\# LANGUAGE RebindableSyntax \#-] module Foo where import Control.Indexed.Prelude import Control.Delimited \-- After importing the indexed prelude, we can use do notation \-- Lifting ordinary monads io1 :: IO () io1 = 'runI' $ do 'lift' $ putStrLn \"hi!\" 'lift' $ putStrLn \"hi!\" return () test1 :: String test1 = 'runDelim' $ 'reset' $ do r <- 'shift1' (const $ return \"hello\") return (r + 1) \-- This is equivalent to the OchaCaml term: \-- reset (fun () -> 1 + shift (fun _ -> \"hello\")) ;; @ See @examples/Simple.hs@ (included in the distribution) for several more examples. -} {- $rankntypes This package requires GHC's @RankNTypes@ extension, as it uses a rank-2 type for the definition of the @shift@ operators 'shift2' and 'shift3'. The original implementation by Kiselyov is Haskell98 (he defines @shift@ as the 'shift1' provided in this package, as opposed to 'shift2' which matches the typing rules of the lambda/shift calculus.) Strictly speaking, the rank-2 type is probably not necessary, but it is not very controversial either, and it makes the intent much clearer. For a lot of cases, you will need to use @RankNTypes@ if you want to abstract over the answer type variables properly (for example, in a recursive data structure.) -} {- $morereading Lorem ipsum... -} {- $refs 1. /Genuine shift\reset in Haskell98/, by Kiselyov, on /haskell-cafe/: <http://okmij.org/ftp/continuations/implementations.html#genuine-shift> 2. /Polymorphic Delimited Continuations/, by Asai, Kameyama in /APLAS '07/: <http://logic.cs.tsukuba.ac.jp/~kam/paper/aplas07.pdf> 3. /Introduction to programming with shift and reset/, by Kiselyov, Asai, in /CW2011/: <http://okmij.org/ftp/continuations/index.html#tutorial> 4. /CC-delcont: Delimited continuations and dynamically scoped variables/: <http://hackage.haskell.org/package/CC-delcont> 5. /CC-delcont introduction/: <http://www.haskell.org/haskellwiki/Library/CC-delcont#CC-delcont> -}
thoughtpolice/hs-asai
src/Control/Delimited/Tutorial.hs
mit
12,533
0
4
2,504
76
69
7
6
0
-- Compile with `ghc -o hello hello.hs` import System.Environment greeter :: String -> String greeter s = "Hello, " ++ s main :: IO () main = putStrLn $ greeter "plexus"
pxlpnk/xhelloworlds
haskell/hello.hs
mit
173
0
6
34
50
26
24
5
1
{-# LANGUAGE QuasiQuotes #-} module View.Equipment where import Model import View.Helpers import View.Layout equipmentListView :: [Entity Equipment] -> Html equipmentListView equipment = layout [shamlet| <a href="/equipment/new">Add Equipment <ul> $forall Entity key e <- equipment <li> #{equipmentMake e} #{equipmentModel e} #{equipmentSerialNumber e} #{equipmentReplacementCost e} <a href="/equipment/#{key}/edit">Edit |] equipmentNewView :: View Text -> Html equipmentNewView view = layout [shamlet| <form action="/equipment" method="POST"> ^{equipmentFields view} <input type="submit" value="save"> |] equipmentEditView :: Entity Equipment -> View Text -> Html equipmentEditView (Entity id _) view = layout [shamlet| <form action="/equipment/#{id}" method="POST"> ^{equipmentFields view} <input type="submit" value="save"> |] equipmentFields :: View Text -> Html equipmentFields view = [shamlet| ^{textField "make" "Make" view} ^{textField "model" "Model" view} ^{textField "serialNumber" "Serial Number" view} ^{textField "replacementCost" "Replacement Cost" view} |]
flipstone/glados
src/View/Equipment.hs
mit
1,173
0
7
221
145
82
63
13
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.CSSRuleList ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.CSSRuleList #else module Graphics.UI.Gtk.WebKit.DOM.CSSRuleList #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.CSSRuleList #else import Graphics.UI.Gtk.WebKit.DOM.CSSRuleList #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/CSSRuleList.hs
mit
440
0
5
39
33
26
7
4
0
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} -- ------------------------------------------------------------ module Control.Monad.ReaderStateIOError ( module Control.Monad.ReaderStateIOError ) where import Control.Applicative import Control.Monad import Control.Monad.Error import Control.Monad.Reader import Control.Monad.State import System.IO.Error -- ------------------------------------------------------------ -- | -- reader state io error monad implemented directly without any monad transformers newtype ReaderStateIOError env state res = RSIO ( env -> state -> IO (Either String res, state) ) instance Functor (ReaderStateIOError env state) where fmap = liftM instance Applicative (ReaderStateIOError env state) where pure = return (<*>) = ap instance Monad (ReaderStateIOError env state) where return v = RSIO $ \ _e s -> return (Right v, s) RSIO cmd >>= f = RSIO $ \ e s -> do (r', ! s') <- cmd e s either (\ err -> return (Left err, s')) (\ x -> let RSIO cmd2 = f x in cmd2 e s') $ r' instance MonadIO (ReaderStateIOError env state) where liftIO a = RSIO $ \ _e s -> do r <- tryIOError a return ( either (Left . show) Right r , s ) instance MonadState state (ReaderStateIOError env state) where get = RSIO $ \ _e s -> return (Right s, s) put s = RSIO $ \ _e _s -> return (Right (), s) instance MonadReader env (ReaderStateIOError env state) where ask = RSIO $ \ e s -> return (Right e, s) local f (RSIO cmd) = RSIO $ \ e s -> cmd (f e) s instance MonadError String (ReaderStateIOError env state) where throwError err = RSIO $ \ _e s -> return (Left err, s) catchError (RSIO cmd) h = RSIO $ \ e s -> do (r', ! s') <- cmd e s either (\ err -> runReaderStateIOError (h err) e s) (\ x -> return (Right x, s')) $ r' modifyIO :: (state -> IO state) -> ReaderStateIOError env state () modifyIO f = do s0 <- get s1 <- liftIO (f s0) put s1 runReaderStateIOError :: ReaderStateIOError env state res -> env -> state -> IO (Either String res, state) runReaderStateIOError (RSIO cmd) e s = cmd e s -- ------------------------------------------------------------
ichistmeinname/holumbus
src/Control/Monad/ReaderStateIOError.hs
mit
2,765
4
18
1,000
807
420
387
57
1
-- | -- Module: Control.GUI -- Copyright: (c) 2015 Schell Scivally -- License: MIT -- Maintainer: Schell Scivally <efsubenovex@gmail.com> -- -- GUI's goal is to abstract over graphical user interfaces, assurring -- they are renderable, dynamic (they change over their domain) and eventually -- produce a value. -- -- A GUI is a monadic 'spline' with an iteration value that can be -- concatenated. What this means is that a GUI is essentially a user -- experience that eventually produces a value and those GUIs can be -- combined to produce a product value. {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE TupleSections #-} module Control.GUI ( -- * Creation -- $creation gui, -- * Transformation -- $transformation transformGUI, -- * Reexports module S, ) where import Control.Varying as S import Control.Varying.Spline as S import Control.Arrow (first) import Control.Monad import Data.Renderable import Data.Monoid -------------------------------------------------------------------------------- -- $creation -- In order to create a spline you must first have a datatype with a 'Composite' -- instance. Then you must create a 'varying' value of that datatype -- describing how it will change over the domain of user input and time. -- Also needed is an event stream that eventually ends the user's interaction. -- The idea is that your interface varies over time and user input but -- eventually produces a result value that can be used in a monadic -- sequence. -------------------------------------------------------------------------------- -- | Create a spline describing an interface that eventually produces a value. -- The type used to represent the user interface must have a 'Composite' -- instance. This allows GUIs to be layered graphically since separate -- GUI's iteration values can all be combined after being broken down into -- transformed primitives. gui :: (Monad m, Monad n, Monoid (f (t, Element n r t)), Composite a f n r t) => Var m i a -- ^ The stream of a changing user interface. -> Var m i (Event b) -- ^ The event stream that concludes a user\'s interaction. When this -- stream produces an event the interaction will end and the spline -- will conclude. -> SplineT f i (t, Element n r t) m (a,b) gui v ve = SplineT $ t ~> var (uncurry f) where t = (,) <$> v <*> ve f a e = let ui = composite a in case e of NoEvent -> Step ui NoEvent Event b -> Step ui $ Event (a, b) -------------------------------------------------------------------------------- -- $transformation -- Simply put - here we are applying some kind of transformation to your -- renderable interface. This most likely a standard two or three dimensional -- affine transformation. Since the transformation also changes over the -- same domain it\'s possible to tween GUIs. -------------------------------------------------------------------------------- -- | Transforms a GUI. transformGUI :: (Monad m, Monoid t, Functor f, Monoid (f (t,d))) => Var m i t -> SplineT f i (t, d) m b -> SplineT f i (t, d) m b transformGUI vt g = mapOutput vf g where vf = vt ~> var f f t = fmap (first (mappend t))
schell/gooey
src/Control/GUI.hs
mit
3,430
0
14
731
482
278
204
31
2
module Grammar.Common.List where import Grammar.Common.Types import qualified Data.Map.Strict as Map addIndex :: [a] -> [Int :* a] addIndex = zip [0..] addReverseIndex :: [a] -> [Int :* a] addReverseIndex = snd . foldr go (0, []) where go x (i, xs) = (i + 1, (i, x) : xs) groupPairs :: Ord k => [k :* v] -> [k :* [v]] groupPairs = Map.assocs . foldr go Map.empty where go (k, v) m = case Map.lookup k m of Just vs -> Map.insert k (v : vs) m Nothing -> Map.insert k [v] m groupConsecutivePairs :: Eq k => [k :* v] -> [k :* [v]] groupConsecutivePairs = foldr go [] where go (k, v) [] = [(k, [v])] go (k, v) ((k', vs) : xs) | k == k' = (k', v : vs) : xs go (k, v) xs = (k, [v]) : xs contextualize :: Int -> [a] -> [a :* [a] :* [a]] contextualize n = contextualizeAccum n [] contextualizeAccum :: Int -> [a] -> [a] -> [a :* [a] :* [a]] contextualizeAccum _ _ [] = [] contextualizeAccum n ps (x : xs) = (x, (take n ps, take n xs)) : contextualizeAccum n (take n (x : ps)) xs
ancientlanguage/haskell-analysis
grammar/src/Grammar/Common/List.hs
mit
1,001
0
12
236
584
322
262
-1
-1