code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module DFS where import Prelude hiding (pred) import Data.List ((\\), sort) import GraphClass class (Node n, Ord n) => DFSNode n instance (Node n, Ord n) => DFSNode n dfs :: (Graph g n, DFSNode n) => (n -> Bool) -> g -> n -> [n] dfs pred graph begin = reverse $ dfs' [begin] [begin] where dfs' (x:xs) visited | pred x = visited | otherwise = case unvisitedNodes x visited of [] -> dfs' xs visited (v:_) -> dfs' (v:x:xs) (v:visited) dfs' [] visited = visited unvisitedNodes x visited = sort (adjacentNodes graph x \\ visited) dfsTraverse :: (Graph g n, DFSNode n) => g -> n -> [n] dfsTraverse graph begin = dfs (const False) graph begin dfsSearch :: (Graph g n, DFSNode n) => g -> n -> n -> [n] dfsSearch graph begin end = dfs (== end) graph begin
shouya/thinking-dumps
graph/DFS.hs
mit
929
0
14
262
396
208
188
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module IHaskell.Display.Widgets.Selection.SelectMultiple ( -- * The SelectMultiple Widget SelectMultiple -- * Constructor , mkSelectMultiple ) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Control.Monad (void) import Data.Aeson import Data.IORef (newIORef) import qualified Data.Scientific as Sci import qualified Data.Vector as V import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common import IHaskell.Display.Widgets.Layout.LayoutWidget import IHaskell.Display.Widgets.Style.DescriptionStyle -- | A 'SelectMultiple' represents a SelectMultiple widget from IPython.html.widgets. type SelectMultiple = IPythonWidget 'SelectMultipleType -- | Create a new SelectMultiple widget mkSelectMultiple :: IO SelectMultiple mkSelectMultiple = do -- Default properties, with a random uuid wid <- U.random layout <- mkLayout dstyle <- mkDescriptionStyle let multipleSelectionAttrs = defaultMultipleSelectionWidget "SelectMultipleView" "SelectMultipleModel" layout $ StyleWidget dstyle selectMultipleAttrs = (Rows =:: Just 5) :& RNil widgetState = WidgetState $ multipleSelectionAttrs <+> selectMultipleAttrs stateIO <- newIORef widgetState let widget = IPythonWidget wid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the widget return widget instance IHaskellWidget SelectMultiple where getCommUUID = uuid comm widget val _ = case nestedObjectLookup val ["state", "index"] of Just (Array indices) -> do let indicesList = map (\(Number x) -> Sci.coefficient x) $ V.toList indices void $ setField' widget Indices indicesList triggerSelection widget _ -> pure ()
gibiansky/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Selection/SelectMultiple.hs
mit
2,254
0
19
494
414
230
184
46
1
{-# LANGUAGE BangPatterns, DataKinds, DeriveDataTypeable, FlexibleInstances, MultiParamTypeClasses #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module Hadoop.Protos.YarnServerResourceManagerServiceProtos.RefreshUserToGroupsMappingsResponseProto (RefreshUserToGroupsMappingsResponseProto(..)) where import Prelude ((+), (/)) import qualified Prelude as Prelude' import qualified Data.Typeable as Prelude' import qualified Data.Data as Prelude' import qualified Text.ProtocolBuffers.Header as P' data RefreshUserToGroupsMappingsResponseProto = RefreshUserToGroupsMappingsResponseProto{} deriving (Prelude'.Show, Prelude'.Eq, Prelude'.Ord, Prelude'.Typeable, Prelude'.Data) instance P'.Mergeable RefreshUserToGroupsMappingsResponseProto where mergeAppend RefreshUserToGroupsMappingsResponseProto RefreshUserToGroupsMappingsResponseProto = RefreshUserToGroupsMappingsResponseProto instance P'.Default RefreshUserToGroupsMappingsResponseProto where defaultValue = RefreshUserToGroupsMappingsResponseProto instance P'.Wire RefreshUserToGroupsMappingsResponseProto where wireSize ft' self'@(RefreshUserToGroupsMappingsResponseProto) = case ft' of 10 -> calc'Size 11 -> P'.prependMessageSize calc'Size _ -> P'.wireSizeErr ft' self' where calc'Size = 0 wirePut ft' self'@(RefreshUserToGroupsMappingsResponseProto) = case ft' of 10 -> put'Fields 11 -> do P'.putSize (P'.wireSize 10 self') put'Fields _ -> P'.wirePutErr ft' self' where put'Fields = do Prelude'.return () wireGet ft' = case ft' of 10 -> P'.getBareMessageWith update'Self 11 -> P'.getMessageWith update'Self _ -> P'.wireGetErr ft' where update'Self wire'Tag old'Self = case wire'Tag of _ -> let (field'Number, wire'Type) = P'.splitWireTag wire'Tag in P'.unknown field'Number wire'Type old'Self instance P'.MessageAPI msg' (msg' -> RefreshUserToGroupsMappingsResponseProto) RefreshUserToGroupsMappingsResponseProto where getVal m' f' = f' m' instance P'.GPB RefreshUserToGroupsMappingsResponseProto instance P'.ReflectDescriptor RefreshUserToGroupsMappingsResponseProto where getMessageInfo _ = P'.GetMessageInfo (P'.fromDistinctAscList []) (P'.fromDistinctAscList []) reflectDescriptorInfo _ = Prelude'.read "DescriptorInfo {descName = ProtoName {protobufName = FIName \".hadoop.yarn.RefreshUserToGroupsMappingsResponseProto\", haskellPrefix = [MName \"Hadoop\",MName \"Protos\"], parentModule = [MName \"YarnServerResourceManagerServiceProtos\"], baseName = MName \"RefreshUserToGroupsMappingsResponseProto\"}, descFilePath = [\"Hadoop\",\"Protos\",\"YarnServerResourceManagerServiceProtos\",\"RefreshUserToGroupsMappingsResponseProto.hs\"], isGroup = False, fields = fromList [], descOneofs = fromList [], keys = fromList [], extRanges = [], knownKeys = fromList [], storeUnknown = False, lazyFields = False, makeLenses = False}" instance P'.TextType RefreshUserToGroupsMappingsResponseProto where tellT = P'.tellSubMessage getT = P'.getSubMessage instance P'.TextMsg RefreshUserToGroupsMappingsResponseProto where textPut msg = Prelude'.return () textGet = Prelude'.return P'.defaultValue
alexbiehl/hoop
hadoop-protos/src/Hadoop/Protos/YarnServerResourceManagerServiceProtos/RefreshUserToGroupsMappingsResponseProto.hs
mit
3,338
1
16
560
554
291
263
55
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.PopStateEvent (js_getState, getState, PopStateEvent, castToPopStateEvent, gTypePopStateEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"state\"]" js_getState :: JSRef PopStateEvent -> IO (JSRef a) -- | <https://developer.mozilla.org/en-US/docs/Web/API/PopStateEvent.state Mozilla PopStateEvent.state documentation> getState :: (MonadIO m) => PopStateEvent -> m (JSRef a) getState self = liftIO (js_getState (unPopStateEvent self))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/PopStateEvent.hs
mit
1,315
6
9
152
370
234
136
22
1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} module IHaskell.Display.Widgets.String.TextArea ( -- * The TextArea Widget TextArea, -- * Constructor mkTextArea) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Data.Aeson import qualified Data.HashMap.Strict as HM import Data.IORef (newIORef) import Data.Text (Text) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common -- | A 'TextArea' represents a Textarea widget from IPython.html.widgets. type TextArea = IPythonWidget TextAreaType -- | Create a new TextArea widget mkTextArea :: IO TextArea mkTextArea = do -- Default properties, with a random uuid uuid <- U.random let strAttrs = defaultStringWidget "TextareaView" "TextareaModel" wgtAttrs = (ChangeHandler =:: return ()) :& RNil widgetState = WidgetState $ strAttrs <+> wgtAttrs stateIO <- newIORef widgetState let widget = IPythonWidget uuid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen widget $ toJSON widgetState -- Return the widget return widget instance IHaskellDisplay TextArea where display b = do widgetSendView b return $ Display [] instance IHaskellWidget TextArea where getCommUUID = uuid comm widget (Object dict1) _ = do let key1 = "sync_data" :: Text key2 = "value" :: Text Just (Object dict2) = HM.lookup key1 dict1 Just (String value) = HM.lookup key2 dict2 setField' widget StringValue value triggerChange widget
sumitsahrawat/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/String/TextArea.hs
mit
1,883
0
14
441
386
210
176
42
1
{-# htermination foldM :: (a -> b -> [] a) -> a -> [b] -> [] a #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_foldM_1.hs
mit
81
0
3
21
5
3
2
1
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedLabels #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NoImplicitPrelude #-} {-# OPTIONS_GHC -Wall #-} -- | Common web page input elements, often with bootstrap scaffolding. module Web.Rep.Html.Input ( Input (..), InputType (..), ) where import Data.Text (split) import Lucid import Lucid.Base import NumHask.Prelude hiding (for_) import Web.Rep.Html -- | something that might exist on a web page and be a front-end input to computations. data Input a = Input { -- | underlying value inputVal :: a, -- | label suggestion inputLabel :: Maybe Text, -- | name//key//id of the Input inputId :: Text, -- | type of html input inputType :: InputType } deriving (Eq, Show, Generic) -- | Various types of web page inputs, encapsulating practical bootstrap class functionality data InputType = Slider [Attribute] | TextBox | TextBox' | TextArea Int | ColorPicker | ChooseFile | Dropdown [Text] | DropdownMultiple [Text] Char | DropdownSum [Text] | Datalist [Text] Text | Checkbox Bool | Toggle Bool (Maybe Text) | Button deriving (Eq, Show, Generic) instance (ToHtml a) => ToHtml (Input a) where toHtml (Input v l i (Slider satts)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ ( [ type_ "range", class__ " form-control-range form-control-sm custom-range jsbClassEventChange", id_ i, value_ (pack $ show $ toHtml v) ] <> satts ) ) toHtml (Input v l i TextBox) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ [ type_ "text", class__ "form-control form-control-sm jsbClassEventInput", id_ i, value_ (pack $ show $ toHtmlRaw v) ] ) toHtml (Input v l i TextBox') = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ [ type_ "text", class__ "form-control form-control-sm jsbClassEventFocusout", id_ i, value_ (pack $ show $ toHtmlRaw v) ] ) toHtml (Input v l i (TextArea rows)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> with textarea_ [ rows_ (pack $ show rows), class__ "form-control form-control-sm jsbClassEventInput", id_ i ] (toHtmlRaw v) ) toHtml (Input v l i ColorPicker) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ [ type_ "color", class__ "form-control form-control-sm jsbClassEventInput", id_ i, value_ (pack $ show $ toHtml v) ] ) toHtml (Input _ l i ChooseFile) = with div_ [class__ "form-group-sm"] (maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l) <> input_ [ type_ "file", class__ "form-control-file form-control-sm jsbClassEventChooseFile", id_ i ] toHtml (Input v l i (Dropdown opts)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> with select_ [ class__ "form-control form-control-sm jsbClassEventInput", id_ i ] opts' ) where opts' = mconcat $ ( \o -> with option_ ( bool [] [selected_ "selected"] (toText (toHtml o) == toText (toHtml v)) ) (toHtml o) ) <$> opts toHtml (Input vs l i (DropdownMultiple opts sep)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> with select_ [ class__ "form-control form-control-sm jsbClassEventChangeMultiple", multiple_ "multiple", id_ i ] opts' ) where opts' = mconcat $ ( \o -> with option_ ( bool [] [selected_ "selected"] (any (\v -> toText (toHtml o) == toText (toHtml v)) (Data.Text.split (== sep) (toText (toHtml vs)))) ) (toHtml o) ) <$> opts toHtml (Input v l i (DropdownSum opts)) = with div_ [class__ "form-group-sm sumtype-group"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> with select_ [ class__ "form-control form-control-sm jsbClassEventInput jsbClassEventShowSum", id_ i ] opts' ) where opts' = mconcat $ ( \o -> with option_ (bool [] [selected_ "selected"] (toText (toHtml o) == toText (toHtml v))) (toHtml o) ) <$> opts toHtml (Input v l i (Datalist opts listId)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ [ type_ "text", class__ "form-control form-control-sm jsbClassEventInput", id_ i, list_ listId -- the datalist concept in html assumes initial state is a null -- and doesn't present the list if it has a value alreadyx -- , value_ (show $ toHtml v) ] <> with datalist_ [id_ listId] ( mconcat $ ( \o -> with option_ ( bool [] [selected_ "selected"] (toText (toHtml o) == toText (toHtml v)) ) (toHtml o) ) <$> opts ) ) -- FIXME: How can you refactor to eliminate this polymorphic wart? toHtml (Input _ l i (Checkbox checked)) = with div_ [class__ "form-check form-check-sm"] ( input_ ( [ type_ "checkbox", class__ "form-check-input jsbClassEventCheckbox", id_ i ] <> bool [] [checked_] checked ) <> maybe mempty (with label_ [for_ i, class__ "form-check-label mb-0"] . toHtml) l ) toHtml (Input _ l i (Toggle pushed lab)) = with div_ [class__ "form-group-sm"] ( maybe mempty (with label_ [for_ i, class__ "mb-0"] . toHtml) l <> input_ ( [ type_ "button", class__ "btn btn-primary btn-sm jsbClassEventToggle", data_ "toggle" "button", id_ i, makeAttribute "aria-pressed" (bool "false" "true" pushed) ] <> maybe [] (\l' -> [value_ l']) lab <> bool [] [checked_] pushed ) ) toHtml (Input _ l i Button) = with div_ [class__ "form-group-sm"] ( input_ [ type_ "button", id_ i, class__ "btn btn-primary btn-sm jsbClassEventButton", value_ (fromMaybe "button" l) ] ) toHtmlRaw = toHtml
tonyday567/lucid-page
src/Web/Rep/Html/Input.hs
mit
7,932
0
22
3,280
2,059
1,056
1,003
214
0
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.DataCue (js_newDataCue, newDataCue, js_newDataCue', newDataCue', js_setData, setData, js_getData, getData, js_setValue, setValue, js_getValue, getValue, js_getType, getType, DataCue, castToDataCue, gTypeDataCue) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"WebKitDataCue\"]()" js_newDataCue :: IO DataCue -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue Mozilla WebKitDataCue documentation> newDataCue :: (MonadIO m) => m DataCue newDataCue = liftIO (js_newDataCue) foreign import javascript unsafe "new window[\"WebKitDataCue\"]($1,\n$2, $3, $4)" js_newDataCue' :: Double -> Double -> JSVal -> JSString -> IO DataCue -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue Mozilla WebKitDataCue documentation> newDataCue' :: (MonadIO m, ToJSString type') => Double -> Double -> JSVal -> type' -> m DataCue newDataCue' startTime endTime value type' = liftIO (js_newDataCue' startTime endTime value (toJSString type')) foreign import javascript unsafe "$1[\"data\"] = $2;" js_setData :: DataCue -> Nullable ArrayBuffer -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.data Mozilla WebKitDataCue.data documentation> setData :: (MonadIO m, IsArrayBuffer val) => DataCue -> Maybe val -> m () setData self val = liftIO (js_setData (self) (maybeToNullable (fmap toArrayBuffer val))) foreign import javascript unsafe "$1[\"data\"]" js_getData :: DataCue -> IO (Nullable ArrayBuffer) -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.data Mozilla WebKitDataCue.data documentation> getData :: (MonadIO m) => DataCue -> m (Maybe ArrayBuffer) getData self = liftIO (nullableToMaybe <$> (js_getData (self))) foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue :: DataCue -> JSVal -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.value Mozilla WebKitDataCue.value documentation> setValue :: (MonadIO m) => DataCue -> JSVal -> m () setValue self val = liftIO (js_setValue (self) val) foreign import javascript unsafe "$1[\"value\"]" js_getValue :: DataCue -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.value Mozilla WebKitDataCue.value documentation> getValue :: (MonadIO m) => DataCue -> m JSVal getValue self = liftIO (js_getValue (self)) foreign import javascript unsafe "$1[\"type\"]" js_getType :: DataCue -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/WebKitDataCue.type Mozilla WebKitDataCue.type documentation> getType :: (MonadIO m, FromJSString result) => DataCue -> m result getType self = liftIO (fromJSString <$> (js_getType (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/DataCue.hs
mit
3,658
50
11
547
889
507
382
56
1
{-# htermination (absRatio :: Ratio MyInt -> Ratio MyInt) #-} import qualified Prelude data MyBool = MyTrue | MyFalse data List a = Cons a (List a) | Nil data MyInt = Pos Nat | Neg Nat ; data Nat = Succ Nat | Zero ; data Ordering = LT | EQ | GT ; data Ratio a = CnPc a a; primNegInt :: MyInt -> MyInt; primNegInt (Pos x) = Neg x; primNegInt (Neg x) = Pos x; negateMyInt :: MyInt -> MyInt negateMyInt = primNegInt; absReal0 x MyTrue = negateMyInt x; otherwise :: MyBool; otherwise = MyTrue; absReal1 x MyTrue = x; absReal1 x MyFalse = absReal0 x otherwise; fromIntMyInt :: MyInt -> MyInt fromIntMyInt x = x; primCmpNat :: Nat -> Nat -> Ordering; primCmpNat Zero Zero = EQ; primCmpNat Zero (Succ y) = LT; primCmpNat (Succ x) Zero = GT; primCmpNat (Succ x) (Succ y) = primCmpNat x y; primCmpInt :: MyInt -> MyInt -> Ordering; primCmpInt (Pos Zero) (Pos Zero) = EQ; primCmpInt (Pos Zero) (Neg Zero) = EQ; primCmpInt (Neg Zero) (Pos Zero) = EQ; primCmpInt (Neg Zero) (Neg Zero) = EQ; primCmpInt (Pos x) (Pos y) = primCmpNat x y; primCmpInt (Pos x) (Neg y) = GT; primCmpInt (Neg x) (Pos y) = LT; primCmpInt (Neg x) (Neg y) = primCmpNat y x; compareMyInt :: MyInt -> MyInt -> Ordering compareMyInt = primCmpInt; esEsOrdering :: Ordering -> Ordering -> MyBool esEsOrdering LT LT = MyTrue; esEsOrdering LT EQ = MyFalse; esEsOrdering LT GT = MyFalse; esEsOrdering EQ LT = MyFalse; esEsOrdering EQ EQ = MyTrue; esEsOrdering EQ GT = MyFalse; esEsOrdering GT LT = MyFalse; esEsOrdering GT EQ = MyFalse; esEsOrdering GT GT = MyTrue; not :: MyBool -> MyBool; not MyTrue = MyFalse; not MyFalse = MyTrue; fsEsOrdering :: Ordering -> Ordering -> MyBool fsEsOrdering x y = not (esEsOrdering x y); gtEsMyInt :: MyInt -> MyInt -> MyBool gtEsMyInt x y = fsEsOrdering (compareMyInt x y) LT; absReal2 x = absReal1 x (gtEsMyInt x (fromIntMyInt (Pos Zero))); absReal x = absReal2 x; absMyInt :: MyInt -> MyInt absMyInt = absReal; absRatio :: Ratio MyInt -> Ratio MyInt absRatio (CnPc x y) = CnPc (absMyInt x) y;
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/basic_haskell/abs_1.hs
mit
2,053
0
11
432
854
460
394
58
1
{-# LANGUAGE InstanceSigs #-} module RealWorld where import Control.Applicative import Control.Monad import Control.Monad.Reader import Control.Monad.State import Control.Monad.Writer import Data.Functor import Data.Monoid import Data.Maybe import System.Random -- All monads are applicatives, and all applicatives are functors. -- Not all functors are applicatives and not all applicatives are monads. {- The Reader Functor fmap :: (a -> b) -> (r -> a) -> (r -> b) f g instance Functor ((->) r) where fmap f g = f . g or fmap = (.) -} newtype Mystery r a = Mystery { solve :: r -> a } instance Functor (Mystery r) where fmap f m = Mystery $ f . solve m -- or fmap f (Mystery ra) = Mystery $ f . ra -- Note - fmap f x = pure f <*> x instance Applicative (Mystery r) where pure :: a -> Mystery r a pure a = Mystery $ \ r -> a -- or Mystery . const (<*>) :: Mystery r (a -> b) -> Mystery r a -> Mystery r b Mystery rab <*> Mystery ra = Mystery $ \r -> rab r (ra r) -- Note - fmap f xs = xs >>= return . f instance Monad (Mystery r) where return :: a -> Mystery r a return = pure (>>=) :: Mystery r a -> (a -> Mystery r b) -> Mystery r b Mystery ra >>= aRb = Mystery $ \r -> solve (aRb (ra r)) r {- The Reader Monad newtype Reader r a = Reader { runReader :: r -> a } ask :: MonadReader r m => m r -} circA :: Reader Int Int circA = do mpI <- ask return (mpI * 10 * 10) cylA :: Reader Int Int cylA = do mpI <- ask return (mpI * 10 * 10 * 20) addCAndCl :: Reader Int Int addCAndCl = do cA <- circA lA <- cylA return (cA + lA) -------------------- bookWorm :: Reader Int Int bookWorm = do val <- ask return $ (+) 1 val -- bookWorm' :: Reader Int Int bookWorm' = fmap (1 +) ask bookWorm'' :: Reader Int Int bookWorm'' = (1 +) <$> ask -- (10 +) . (runReader ask) $ 10 -- f . g {- Writer Monad data Writer w a = Writer {runWriter :: (a, w)} -} half :: Int -> Writer String Int half x = do tell ("I just halved " ++ show x ++ "! ") return (x `div` 2) ho = runWriter $ half 200 >>= half >>= half fib :: Int -> Int -> Writer String Int fib a b = do tell ( "Adding " ++ show a ++ " to " ++ show b ++ ". ") return (a+ b) main = do let a = runWriter $ fib 10 20 >>= fib 30 >>= fib 40 print (fst a) -- State Monad -- Write as well as read -- s == state , a == result state -> (result, modified state) -- data State s a = State {runState :: s -> (a, s)} -- return a = State $ \s -> (a,s) greeter :: State String String greeter = do name <- get put "Pandey" return ("Hello " ++ name ++ "!") gee = runState greeter "Alok" newtype Distaste s a = Distaste { runDistaste :: s -> (a, s) } -- Functor instance Functor (Distaste s) where fmap :: (a -> b) -> Distaste s a -> Distaste s b fmap f (Distaste g) = Distaste $ \ s -> mapp f (g s) where mapp f (x, y) = (f x, y) -- instance Applicative (Distaste s) where pure a = Distaste (\s -> (a,s)) mf <*> xs = Distaste $ \s0 -> let (f, s1) = runDistaste mf s0 (x, s2) = runDistaste xs s1 in (f x, s2) -- instance Monad (Distaste s) where return a = Distaste (\s -> (a,s)) Distaste mf >>= mg = Distaste (\s -> let (r,s1) = mf s Distaste c2 = mg r in c2 s1) -- State eg fizzBuzz :: Integer -> String fizzBuzz n | n `mod` 15 == 0 = "FizzBuzz" | n`mod`5 == 0 = "Fizz" | n`mod`3 == 0 = "Buzz" | otherwise = show n addResult :: Integer -> State [String] () addResult n = do xs <- get let result = fizzBuzz n put (result : xs) fizzbuzzList :: [Integer] -> [String] fizzbuzzList list = execState (mapM_ addResult list) [] train :: IO () train = mapM_ putStrLn $ reverse $ fizzbuzzList [1..10] foo :: Int -> State [String] () foo n = do st <- get let b | n > 5 = "High" | n < 5 = "Low" | otherwise = "Equal" put (b : st) bar :: Int -> State [String] () bar n = do st <- get let b | n > 5 = "High" | n < 5 = "Low" | otherwise = "Equal" put ([b]) -- goo :: String -> State [String] () goo n = do st <- get let b | n == "Max" = "High" | otherwise = "Equal" put (b : st) -- execState (mapM_ breeze [2,7,11,3,5]) [] -- ["Equal","Low","High","High","Low"] -- runState (mapM_ breeze [2,7,11,3,5]) []-- -- evalState :: State s a -> s -> a -- ((),["Equal","Low","High","High","Low"]) -- -- :t sequenceA $ fmap breeze [3,6] (mapM == traverse) -- also -- execState (sequenceA $ concat $ (:) <$> [foo 2] <*> [[foo 8]] ) [] -- as -- instance Traversable [] where -- traverse f = List.foldr cons_f (pure []) -- where cons_f x ys = (:) <$> f x <*> ys -- traverse f = sequenceA . fmap f sequenceAholla us = foldr (\u v -> (:) <$> u <*> v) (pure []) us -- sequenceAholla ([ Just 2, Just 3, Just 4]) --- Just [2,3,4] mytraverse f = foldr cons_f (pure []) where cons_f x ys = (:) <$> f x <*> ys more :: State () [Int] more = traverse pure [1..4] showMore = print (evalState more ()) sure :: State () [String] sure = traverse pure ["al", "kl"] predictor :: Int -> State [String] Int predictor n = do st <- get let b | mod n 2 == 0 = "even" | mod n 2 == 1 = "odd" | otherwise = "Whoa" put (b : st) return (n + 1) -- return (n+1) -- runState (traverse predictor [1..10]) [] ---- ([2,3,4,5,6,7,8,9,10,11],["even","odd","even","odd","even","odd","even","odd","even","odd"]) -- make return n -- runState (predictor 1 >>= predictor >>= predictor) [] ---- (4,["odd","even","odd"]) -- incrementor :: Int -> State [Maybe Int] (Maybe Int) -- incrementor n = do -- st <- get -- put $ Just n : st -- let old = case st of -- [] -> Just (n + 1) -- xs -> case head xs of -- (Just x) -> if x + 1 == n then Nothing else Just (n + 1) -- Nothing -> Nothing -- return old incrementor :: Int -> State [Maybe Int] () incrementor n = do st <- get case st of [] -> put $ Just (n + 1) : st xs -> if summation xs + 1 > n then put $ Nothing : st else put $ Just (n + 1) : st where summation = sum . catMaybes {-- Also using fold incrementor :: [Int] -> Int -> [Int] incrementor st n = if null st || n >= sum st + 1 then n + 1 : st else st res = reverse $ foldl' incrementor mempty [1,2,4,5] --} boo = do let scanMap f = scanr ((:) . f) [] print $ scanMap (\x -> x + 1) [1..5]
alokpndy/haskell-learn
src/monads/monadThree.hs
mit
6,949
0
15
2,292
2,122
1,090
1,032
141
3
module Physics.Scenes.FourBoxesTwoStatic where import Linear.Epsilon import Linear.V2 import Physics.Constraint import Physics.Contact import Physics.External import Physics.Geometry import Physics.Object import Physics.World import Physics.Scenes.Scene boxA :: (Fractional a, Eq a) => PhysicalObj a boxA = PhysicalObj { _physObjVel = V2 1 0 , _physObjRotVel = 0 , _physObjPos = V2 (-5) 0 , _physObjRotPos = 0 , _physObjHull = rectangleHull 4 4 , _physObjInvMass = toInvMass2 (2, 1) } boxB :: (Fractional a, Eq a) => PhysicalObj a boxB = PhysicalObj { _physObjVel = V2 (-4) 0 , _physObjRotVel = 0 , _physObjPos = V2 5 2 , _physObjRotPos = 0 , _physObjHull = rectangleHull 2 2 , _physObjInvMass = toInvMass2 (1, 0.5) } boxC :: (Fractional a, Eq a) => PhysicalObj a boxC = PhysicalObj { _physObjVel = V2 0 0 , _physObjRotVel = 0 , _physObjPos = V2 0 (-6) , _physObjRotPos = 0 , _physObjHull = rectangleHull 18 1 , _physObjInvMass = toInvMass2 (0, 0) } boxD :: (Fractional a, Eq a) => PhysicalObj a boxD = PhysicalObj { _physObjVel = V2 0 0 , _physObjRotVel = 0 , _physObjPos = V2 (-5) (-4) , _physObjRotPos = 0 , _physObjHull = rectangleHull 0.4 3 , _physObjInvMass = toInvMass2 (1, 0) } boxA' :: (Fractional a, Eq a) => WorldObj a boxA' = WorldObj boxA 0.2 boxB' :: (Fractional a, Eq a) => WorldObj a boxB' = WorldObj boxB 0.2 boxC' :: (Fractional a, Eq a) => WorldObj a boxC' = WorldObj boxC 0.2 boxD' :: (Fractional a, Eq a) => WorldObj a boxD' = WorldObj boxD 0.2 world :: (Fractional a, Eq a) => World (WorldObj a) world = fromList [boxA', boxB', boxC', boxD'] externals :: (Physical n a, Epsilon n, Floating n, Ord n) => [External n a] externals = [constantAccel (V2 0 (-2))] contactBehavior :: (Floating a) => ContactBehavior a contactBehavior = ContactBehavior 0.01 0.02 scene :: (Physical a p, Epsilon a, Floating a, Ord a, Eq a) => Scene a p scene = Scene world externals contactBehavior
ublubu/shapes-demo
src/Physics/Scenes/FourBoxesTwoStatic.hs
mit
2,289
0
10
723
769
425
344
54
1
module Spear.Sys.Store.ID ( ID , IDStore , emptyIDStore , newID , freeID ) where import Data.Vector.Unboxed as U import Control.Monad.State -- test import Text.Printf -- test type ID = Int data IDStore = IDStore { assigned :: Vector Bool -- ^ A bit array indicating used IDs. , last :: Int -- ^ The greatest ID assigned so far. } deriving Show -- | Create an empty ID store. emptyIDStore :: IDStore emptyIDStore = IDStore U.empty (-1) -- | Request an ID from the ID store. newID :: IDStore -> (ID, IDStore) newID store@(IDStore assigned last) = if last == U.length assigned - 1 then case findIndex (==False) assigned of Just i -> assign i store Nothing -> newID $ IDStore (assigned U.++ U.replicate (max 1 last + 1) False) last else assign (last+1) store -- Assign the given ID in the ID store. assign :: ID -> IDStore -> (ID, IDStore) assign i (IDStore assigned last) = let assigned' = assigned // [(i,True)] in (i, IDStore assigned' (max last i)) -- | Free the given ID from the ID store. freeID :: ID -> IDStore -> IDStore freeID i (IDStore assigned last) = let assigned' = assigned // [(i,False)] in if i == last then case findLastIndex (==True) assigned' of Just j -> IDStore assigned' j Nothing -> IDStore assigned' 0 else IDStore assigned' last findLastIndex :: Unbox a => (a -> Bool) -> Vector a -> Maybe Int findLastIndex p v = findLastIndex' p v Nothing 0 where findLastIndex' p v current i = if i >= U.length v then current else if p $ v U.! i then let x = Just i in x `seq` findLastIndex' p v x (i+1) else findLastIndex' p v current (i+1) -- test test :: IO () test = evalStateT test' emptyIDStore test' :: StateT IDStore IO () test' = do x <- request y <- request z <- request w <- request free y request free w request a <- request free a request return () request :: StateT IDStore IO ID request = do store <- get let (i, store') = newID store put store' lift $ printf "ID requested, got %d; %s\n" i (show store') return i free :: ID -> StateT IDStore IO () free i = do store <- get let store' = freeID i store put store' lift $ printf "ID %d freed; %s\n" i (show store')
jeannekamikaze/Spear
Spear/Sys/Store/ID.hs
mit
2,492
0
16
807
847
432
415
71
3
module SuperUserSpark.Check.TestUtils where import TestImport import SuperUserSpark.Bake.Gen () import SuperUserSpark.Bake.Types import SuperUserSpark.Check.Gen () import SuperUserSpark.Check.Internal import SuperUserSpark.Check.Types import SuperUserSpark.CoreTypes import SuperUserSpark.Diagnose.Types -- * Test utils for checkDeployment shouldBeImpossible' :: DiagnosedDeployment -> Expectation shouldBeImpossible' dd = checkDeployment dd `shouldSatisfy` impossibleDeployment shouldBeImpossibleDeployment :: [CheckResult] -> Expectation shouldBeImpossibleDeployment dd = bestResult dd `shouldSatisfy` impossibleDeployment -- * Test utils for checkSingle isDirty :: CheckResult -> Bool isDirty Dirty{} = True isDirty _ = False isReady :: CheckResult -> Bool isReady (Ready _) = True isReady _ = False isDone :: CheckResult -> Bool isDone AlreadyDone = True isDone _ = False isImpossible :: CheckResult -> Bool isImpossible (Impossible _) = True isImpossible _ = False shouldBeDirty :: DiagnosedFp -> DiagnosedFp -> DeploymentKind -> CleanupInstruction -> Expectation shouldBeDirty src dst kind eci = case checkSingle src dst kind of Dirty _ ins ci -> do ci `shouldBe` eci let tp = dropTrailingPathSeparator . toFilePath let checkCopyDeployment isrc idst expectation = do tp isrc `shouldBe` toPath (diagnosedFilePath src) tp idst `shouldBe` toPath (diagnosedFilePath dst) expectation `shouldBe` kind case ins of CopyFile isrc idst -> checkCopyDeployment isrc idst CopyDeployment CopyDir isrc idst -> checkCopyDeployment isrc idst CopyDeployment LinkFile isrc idst -> checkCopyDeployment isrc idst LinkDeployment LinkDir isrc idst -> checkCopyDeployment isrc idst LinkDeployment t -> expectationFailure $ unlines [ "checkSingle" , show src , show dst , show kind , "should be dirty but is" , show t ] shouldBeReady :: DiagnosedFp -> DiagnosedFp -> DeploymentKind -> Expectation shouldBeReady src dst kind = checkSingle src dst kind `shouldSatisfy` isReady shouldBeDone :: DiagnosedFp -> DiagnosedFp -> DeploymentKind -> Expectation shouldBeDone src dst kind = checkSingle src dst kind `shouldSatisfy` isDone shouldBeImpossible :: DiagnosedFp -> DiagnosedFp -> DeploymentKind -> Expectation shouldBeImpossible src dst kind = checkSingle src dst kind `shouldSatisfy` isImpossible validWith :: Diagnostics -> Gen DiagnosedFp validWith d = D <$> genValid <*> pure d <*> genValid
NorfairKing/super-user-spark
test/SuperUserSpark/Check/TestUtils.hs
mit
2,802
0
18
736
661
342
319
67
5
{-# OPTIONS_GHC -fno-warn-orphans #-} module Graphics.Urho3D.Math.Color( Color(..) , rgb , rgba , HasRComp(..) , HasGComp(..) , HasBComp(..) , HasAComp(..) , colorContext ) where import qualified Language.C.Inline as C import qualified Language.C.Inline.Cpp as C import Graphics.Urho3D.Creatable import Graphics.Urho3D.Math.Internal.Color import Graphics.Urho3D.Monad import Data.Monoid import Foreign import Text.RawString.QQ import Control.Lens C.context (C.cppCtx <> colorCntx) C.include "<Urho3D/Math/Color.h>" C.using "namespace Urho3D" colorContext :: C.Context colorContext = colorCntx C.verbatim [r| template <class T> class Traits { public: struct AlignmentFinder { char a; T b; }; enum {AlignmentOf = sizeof(AlignmentFinder) - sizeof(T)}; }; |] -- | Helper to use default alpha rgb :: Float -> Float -> Float -> Color rgb rc gc bc = Color rc gc bc 1 -- | Helpwer for Color rgba :: Float -> Float -> Float -> Float -> Color rgba = Color instance Storable Color where sizeOf _ = fromIntegral $ [C.pure| int { (int)sizeof(Color) } |] alignment _ = fromIntegral $ [C.pure| int { (int)Traits<Color>::AlignmentOf } |] peek ptr = do vr <- realToFrac <$> [C.exp| float { $(Color* ptr)->r_ } |] vg <- realToFrac <$> [C.exp| float { $(Color* ptr)->g_ } |] vb <- realToFrac <$> [C.exp| float { $(Color* ptr)->b_ } |] va <- realToFrac <$> [C.exp| float { $(Color* ptr)->a_ } |] return $ Color vr vg vb va poke ptr (Color vr vg vb va) = [C.block| void { $(Color* ptr)->r_ = $(float vr'); $(Color* ptr)->g_ = $(float vg'); $(Color* ptr)->b_ = $(float vb'); $(Color* ptr)->a_ = $(float va'); } |] where vr' = realToFrac vr vg' = realToFrac vg vb' = realToFrac vb va' = realToFrac va instance Num Color where c1 + c2 = Color (c1^.rComp + c2^.rComp) (c1^.gComp + c2^.gComp) (c1^.bComp + c2^.bComp) (c1^.aComp + c2^.aComp) c1 - c2 = Color (c1^.rComp - c2^.rComp) (c1^.gComp - c2^.gComp) (c1^.bComp - c2^.bComp) (c1^.aComp - c2^.aComp) c1 * c2 = Color (c1^.rComp * c2^.rComp) (c1^.gComp * c2^.gComp) (c1^.bComp * c2^.bComp) (c1^.aComp * c2^.aComp) abs c = Color (abs $ c^.rComp) (abs $ c^.gComp) (abs $ c^.bComp) (abs $ c^.aComp) signum c = Color (signum $ c^.rComp) (signum $ c^.gComp) (signum $ c^.bComp) (signum $ c^.aComp) fromInteger i = Color (fromIntegral i) (fromIntegral i) (fromIntegral i) 1 instance Creatable (Ptr Color) where type CreationOptions (Ptr Color) = Color newObject = liftIO . new deleteObject = liftIO . free
Teaspot-Studio/Urho3D-Haskell
src/Graphics/Urho3D/Math/Color.hs
mit
2,586
0
10
543
886
486
400
-1
-1
module Analys where import Tree import Data.List kLimited :: AttainTree -> Chip kLimited (AttainTree (Marking mark) _ subTr) = let curMax = maximum mark subTrMax = case subTr of Tree pairs -> if null pairs then Num 0 else maximum $ map (kLimited . snd) pairs Degenerate -> Num 0 in max curMax subTrMax -- Сеть сохраняема, если количество фишек во всех переходах одинаково isSelfLife :: AttainTree -> Bool isSelfLife tree@(AttainTree (Marking mark) _ _) = let withoutOmega = notElem Omega findCount = sum . map (\(Num i) -> i) isSelfLife' count (AttainTree (Marking m) _ subTr) = withoutOmega m && count == findCount m && case subTr of Degenerate -> True Tree pairs -> all (isSelfLife' count . snd) pairs in withoutOmega mark && isSelfLife' (findCount mark) tree -- Переход потенциально жив, если его можно запустить isTransferPotentiallyAlife :: AttainTree -> TransferNum -> Bool isTransferPotentiallyAlife (AttainTree _ _ (Tree pairs)) t = let (curTranses, subTrees) = unzip pairs in elem t curTranses || any (`isTransferPotentiallyAlife` t) subTrees isTransferPotentiallyAlife (AttainTree _ _ Degenerate) _ = False -- Переход жив, если он разрешен в каждой разрешенной маркировке isTransferAlife :: AttainTree -> TransferNum -> Bool isTransferAlife (AttainTree _ _ Degenerate) _ = True isTransferAlife (AttainTree _ _ (Tree pairs)) t = let (curTranses, subTrees) = unzip pairs in elem t curTranses && all (`isTransferAlife` t) subTrees -- Переход устойчив, если из каждой маркировки, -- В которую мы по нему пришли, -- Его можно снова запустить -- Не будет работать, если маркировка -- помечена как уже существующая, и, при этом, -- достигли мы её не с помощью этого перехода -- (тогда переход может оказаться нестабильным) -- !!!!!!!!!! неправильно isTransferStable :: AttainTree -> TransferNum -> Bool isTransferStable (AttainTree _ _ Degenerate) _ = True isTransferStable (AttainTree _ _ (Tree pairs)) t = let branch = filter ((== t) . fst) pairs --Найдем наш переход is = not $ null branch isExist (AttainTree _ _ (Tree ps)) = elem t $ map fst ps isExist (AttainTree _ _ Degenerate) = True isStillStable (AttainTree _ _ tree) = case tree of Degenerate -> True (Tree ps) -> all (isExist . snd) ps -- all of snd ps has t -- elem t $ map fst ps in all ((`isTransferStable` t) . snd) pairs && (not is || all (isStillStable . snd) branch) analys :: Petri -> AttainTree -> [String] analys petri tree = let kLimit = "\"limited\": " ++ case kLimited tree of Omega -> "false," Num i -> "К = " ++ show i safety = "\"safe\": " ++ case kLimited tree of Num 1 -> "true," _ -> "false," selfLife = "\"save\": " ++ if isSelfLife tree then "true," else "false," transfsNum = [1..length petri] potVitalityTransfers = zip transfsNum (map (isTransferPotentiallyAlife tree) transfsNum) potentVitality = "\"transfers_potential_aliveness\": [" ++ init (concatMap (\(n, is) -> if is then "\"t" ++ show n ++ "\"" ++ "," else show "") potVitalityTransfers) ++ "]," vitalityTransfers = zip transfsNum (map (isTransferAlife tree) transfsNum) vitalityTrans = "\"transfers_aliveness\": [" ++ intercalate ", " (map ((\n -> "\"t" ++ show n) . fst) (filter snd vitalityTransfers)) ++ "]," webVitality = "\"net_aliveness\": " ++ if all snd vitalityTransfers then "true," else "false," transferStability = zip transfsNum (map (isTransferStable tree) transfsNum) pTransStable = "\"transfers_stability\": [" ++ intercalate ", " (map ((\n -> "\"t" ++ show n) . fst) (filter snd transferStability)) ++ "]," pWebStable = "\"net_stability\": " ++ if all snd transferStability then "true" else "false" in [kLimit, safety, selfLife, potentVitality, vitalityTrans, webVitality, pTransStable, pWebStable] growAndGetInfo :: Petri -> [Int] -> String growAndGetInfo transfers mark = let petriMark = Marking [Num i | i <- mark] tree = findTree transfers petriMark settings = analys transfers tree in "{\"tree\": {" ++ show tree ++ "}" ++ ", " ++ concat settings ++ "}"
NickolayStorm/PetriNet
Analys.hs
mit
5,468
0
20
1,772
1,305
671
634
95
7
{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE TupleSections #-} -- |CSP example for "bring items to the other shore"-type of problems: -- Items i1,...,in are on one side of the shore and there's a boat -- with limited passenger size. The aim is to transport all items -- to the other side without leaving certain conflicting items -- (e.g. a wolf and a sheep) unattended (e.g without a farmer). module Algorithms.SimpleCSP.Examples.Wolf where import Algorithms.SimpleCSP import Prelude.Unicode import Control.Monad import Data.List import Data.List.Unicode -- |Position of a boat. data Boat = West | East deriving (Eq, Show, Read, Enum, Ord) -- |Objects on the shore. data Object = Wolf | Goat | Cabbage | Fire | Stick | Farmer deriving (Eq, Show, Read, Enum, Ord) type Objects = ([Object], [Object]) type GameState = (Objects, Boat) -- |Nondeterminisitically moves between 1 and n items via boat to the other side, -- always, taking the Farmer. nextMove :: GameMove Int GameState nextMove boatSize x = case x of ((w,e),West) → liftM (,East) (transport w e) ((w,e),East) → liftM (\(e',w') → ((w',e'),West)) (transport e w) where transport from to = do passengers ← chooseBetween 1 boatSize from let from' = from \\ (Farmer:passengers) to' = nub $ Farmer:passengers ++ to return (from', to') -- |Returns true iff all items have arrived on the eastern side. goalState :: Int → GameState → Bool goalState _ (([],_),East) = True goalState _ _ = False -- |Solves the simple problem of a 2-passenger boat and -- a farmer, a wolf, a goat, and a cabbage. problem1 :: [Plan GameState] problem1 = doPlan nextMove goalState constraints1 boatSize1 begin1 -- |Solves the more complex version: a 3-passenger boat, -- and a farmer, a wolf, a goat, a cabbage, a fire and a stick. problem2 :: [Plan GameState] problem2 = doPlan nextMove goalState constraints2 boatSize2 begin2 boatSize1 :: Int boatSize1 = 1 boatSize2 :: Int boatSize2 = 2 begin1 :: GameState begin1 = (([Wolf, Goat, Cabbage, Farmer], []), West) begin2 :: GameState begin2 = (([Wolf, Goat, Cabbage, Stick, Fire, Farmer], []), West) wolfGoatNotAlone :: Constraint Int GameState wolfGoatNotAlone _ ((w,e),_) = c' w ∧ c' e where c' set | Wolf ∈ set ∧ Goat ∈ set ∧ Farmer ∉ set = False | otherwise = True cabbageGoatNotAlone :: Constraint Int GameState cabbageGoatNotAlone _ ((w,e),_) = c' w ∧ c' e where c' set | Goat ∈ set ∧ Cabbage ∈ set ∧ Farmer ∉ set = False | otherwise = True fireStickNotAlone :: Constraint Int GameState fireStickNotAlone _ ((w,e),_) = c' w ∧ c' e where c' set | Fire ∈ set ∧ Stick ∈ set ∧ Farmer ∉ set = False | otherwise = True wolfStickNotAlone :: Constraint Int GameState wolfStickNotAlone _ ((w,e),_) = c' w ∧ c' e where c' set | Wolf ∈ set ∧ Stick ∈ set ∧ Farmer ∉ set = False | otherwise = True farmerWithBoat :: Constraint Int GameState farmerWithBoat _ ((w,_),West) = Farmer ∈ w farmerWithBoat _ ((_,e),East) = Farmer ∈ e constraints1 :: Constraint Int GameState constraints1 = constraints [wolfGoatNotAlone, cabbageGoatNotAlone, farmerWithBoat] constraints2 :: Constraint Int GameState constraints2 = constraints [wolfGoatNotAlone, cabbageGoatNotAlone, fireStickNotAlone, wolfStickNotAlone, farmerWithBoat] -- |Prints a plan to the console. printPlan :: Plan GameState → IO () printPlan p = void $ foldM1 printStep $ reverse p where printStep :: GameState -> GameState -> IO GameState printStep (prev, b1) (cur,b2) = do let dir = case (b1,b2) of (East,West) → putStr " <== " _ → putStr " ==> " w = putStr $ show $ fst prev e = putStr $ show $ snd prev movement = putStr $ show $ fst prev ∆ fst cur sequence_ [w,dir,movement,dir,e, putStrLn ""] return (cur,b2)
ombocomp/CSP
Algorithms/SimpleCSP/Examples/Wolf.hs
mit
4,449
0
15
1,353
1,235
673
562
81
2
{-# LANGUAGE TemplateHaskell , LambdaCase , RankNTypes #-} module AppDefs where import Control.Lens import Control.Monad.Reader import Control.Monad.State import Control.Monad.Trans.Either import Control.Concurrent.STM.TQueue import qualified Graphics.UI.GLFW as GLFW import qualified Graphics.Rendering.OpenGL as GL import GLFWHelpers import FrameBuffer import QuadRendering import qualified BoundedSequence as BS import Experiment -- Some definitions and utilities split out from the App module data AppState = AppState { _asCurTick :: !Double , _asLastEscPress :: !Double , _asFrameTimes :: !(BS.BoundedSequence Double) , _asFrameIdx :: !Int , _asVSync :: !Bool , _asExperiment :: !AnyExperiment , _asExperimentDesc :: !String } data AppEnv = AppEnv { _aeWindow :: !GLFW.Window , _aeGLFWEventsQueue :: !(TQueue GLFWEvent) , _aeFontTexture :: !GL.TextureObject , _aeFB :: !FrameBuffer , _aeQR :: !QuadRenderer , _aeExperiments :: ![AnyWithExperiment] } makeLenses ''AppState makeLenses ''AppEnv -- Our application runs in a reader / state / either / IO transformer stack data ExpResult = ExpNext | ExpPrev | ExpExit deriving (Show, Eq, Enum) type AppT m = EitherT ExpResult (StateT AppState (ReaderT AppEnv m)) type AppIO = AppT IO -- Run a computation in the State monad with the current experiment as its state. Store the -- final state back into ours. Note that we can't write this with the 'zoom' combinator -- from lens as we can't define a lens for an existential type runExperimentState :: (forall e m. (Experiment e, MonadIO m, MonadState e m) => m a) -> AppIO a runExperimentState f = use asExperiment >>= \case (AnyExperiment e) -> do (r, e') <- liftIO . flip runStateT e $ f asExperiment .= AnyExperiment e' return r
blitzcode/rust-exp
hs-src/AppDefs.hs
mit
2,210
0
14
737
406
230
176
68
1
-- import Control.Monad import Control.Exception import System.Directory (doesFileExist) import System.Environment import System.Exit import qualified Data.Text as T import qualified Data.List as List -- iff :: Bool -> a -> a -> a iff True x _ = x iff False _ y = y -- strings_join :: String -> [String] -> String strings_join delim [] = "" strings_join delim (x:[]) = x strings_join delim (x:xs) = x ++ delim ++ (strings_join delim xs) -- texts_uniq :: [T.Text] -> [T.Text] texts_uniq [] = [] texts_uniq (x:xs) = let xs_uniq = (texts_uniq xs) in iff (x `elem` xs_uniq) (xs_uniq) ([x] ++ xs_uniq) -- getEnvOrEmpty :: String -> IO String getEnvOrEmpty name = getEnv name `catch` -- "(e :: IOException)" is for hinting exception type (\e -> let _ = (e :: IOException) in return "") -- find_exe_paths :: String -> IO [String] find_exe_paths prog = do -- 8f1kRCu env_pathext <- getEnvOrEmpty "PATHEXT" -- 4fpQ2RB iff (env_pathext == "") -- then -- 9dqlPRg (return []) -- else (do -- 6qhHTHF -- Split into a list of extensions let ext_s = T.splitOn (T.pack ";") (T.pack env_pathext) -- 2pGJrMW -- Strip let ext_s_2 = map T.strip ext_s -- 2gqeHHl -- Remove empty let ext_s_3 = filter (\x -> x /= (T.pack "")) ext_s_2 -- 2zdGM8W -- Convert to lowercase let ext_s_4 = map T.toLower ext_s_3 -- 2fT8aRB -- Uniquify let ext_s_5 = texts_uniq ext_s_4 -- 4ysaQVN env_path <- getEnvOrEmpty "PATH" -- 5gGwKZL let dir_path_s = iff (env_path == "") -- then -- 7bVmOKe -- Go ahead with "dir_path_s" being empty [] -- else -- 6mPI0lg -- Split into a list of paths (T.splitOn (T.pack ";") (T.pack env_path)) -- 5rT49zI -- Insert empty dir path to the beginning. -- -- Empty dir handles the case that "prog" is a path, either -- relative or absolute. See code 7rO7NIN. let dir_path_s2 = [T.pack ""] ++ dir_path_s -- 2klTv20 -- Uniquify let dir_path_s3 = texts_uniq dir_path_s2 -- 9gTU1rI -- Check if "prog" ends with one of the file extension in -- "ext_s_5". -- -- "ext_s_5" are all in lowercase, ensured at 2zdGM8W. let prog_lc = T.toLower (T.pack prog) let prog_has_ext = any (`T.isSuffixOf` prog_lc) ext_s_5 -- 6bFwhbv exe_path_s <- liftM List.concat ( (`mapM` dir_path_s3) (\dir_path -> do -- 7rO7NIN -- Synthesize a path let path = iff (dir_path == T.pack "") (T.pack prog) (T.concat [ dir_path ,(T.pack "\\") ,(T.pack prog) ]) -- "exe_path" is used at 4bm0d25. -- Its value being empty string means file not exist. exe_path <- -- 6kZa5cq -- If "prog" ends with executable file extension iff prog_has_ext -- then (do file_exists <- (doesFileExist (T.unpack path)) -- 3whKebE iff file_exists -- then -- 2ffmxRF (return path) -- else (return (T.pack "")) ) -- else (return (T.pack "")) -- 2sJhhEV -- Assume user has omitted the file extension exe_path_s <- liftM List.concat ( (`mapM` ext_s_5) (\ext -> do -- 6k9X6GP -- Synthesize a path with one of the file -- extensions in PATHEXT let path_2 = (T.concat [path, ext]) file_exists_2 <- (doesFileExist (T.unpack path_2)) -- 6kabzQg iff file_exists_2 -- then -- 7dui4cD (return [path_2]) -- else (return []) ) ) -- 4bm0d25 iff (exe_path == (T.pack "")) -- then (return exe_path_s) -- then (return ([exe_path] ++ exe_path_s)) -- ) ) -- 8swW6Av -- Uniquify let exe_path_s2 = texts_uniq exe_path_s -- Convert from Text to String let exe_path_s3 = map T.unpack exe_path_s2 -- 7y3JlnS return exe_path_s3 ) -- 4zKrqsC -- Program entry main = do -- arg_s <- getArgs -- let arg_cnt = length arg_s -- 9mlJlKg -- If not exactly one command argument is given iff (arg_cnt /= 1) -- then (do -- 7rOUXFo -- Print program usage let usage = strings_join "\n" [ "Usage: aoikwinwhich PROG", "", "#/ PROG can be either name or path", "aoikwinwhich notepad.exe", "aoikwinwhich C:\\Windows\\notepad.exe", "", "#/ PROG can be either absolute or relative", "aoikwinwhich C:\\Windows\\notepad.exe", "aoikwinwhich Windows\\notepad.exe", "", "#/ PROG can be either with or without extension", "aoikwinwhich notepad.exe", "aoikwinwhich notepad", "aoikwinwhich C:\\Windows\\notepad.exe", "aoikwinwhich C:\\Windows\\notepad\n" ] putStr usage -- 3nqHnP7 exitWith (ExitFailure 1) ) -- else (do -- 9m5B08H -- Get executable name or path let prog = head arg_s -- 8ulvPXM -- Find executable paths exe_path_s <- find_exe_paths prog -- 5fWrcaF -- If has found none iff (length exe_path_s == 0) -- then (do -- 3uswpx0 exitWith (ExitFailure 2) ) -- else -- If has found some (do -- 9xPCWuS -- Print to stdout putStrLn (strings_join "\n" exe_path_s) -- 4s1yY1b exitWith (ExitSuccess) ) )
AoiKuiyuyou/AoikWinWhich-Haskell
src/aoikwinwhich/aoikwinwhich.hs
mit
8,400
0
32
4,655
1,301
704
597
107
1
{-# LANGUAGE BangPatterns #-} module Util.BitSet( BitSet(), EnumBitSet(..), toWord, fromWord ) where import Data.List(foldl') import Data.Bits import Data.Word import Data.Monoid import Util.SetLike import Util.HasSize newtype BitSet = BitSet Word deriving(Eq,Ord) instance Monoid BitSet where mempty = BitSet 0 mappend (BitSet a) (BitSet b) = BitSet (a .|. b) mconcat ss = foldl' mappend mempty ss instance Unionize BitSet where BitSet a `difference` BitSet b = BitSet (a .&. complement b) BitSet a `intersection` BitSet b = BitSet (a .&. b) type instance Elem BitSet = Int instance Collection BitSet where -- type Elem BitSet = Int singleton i = BitSet (bit i) fromList ts = BitSet (foldl' setBit 0 ts) toList (BitSet w) = f w 0 where f 0 _ = [] f w n = if even w then f (w `shiftR` 1) (n + 1) else n:f (w `shiftR` 1) (n + 1) type instance Key BitSet = Elem BitSet instance SetLike BitSet where keys bs = toList bs delete i (BitSet v) = BitSet (clearBit v i) member i (BitSet v) = testBit v i insert i (BitSet v) = BitSet (v .|. bit i) sfilter fn (BitSet w) = f w 0 0 where f 0 _ r = BitSet r f w n r = if even w || not (fn n) then f w1 n1 r else f w1 n1 (setBit r n) where !n1 = n + 1 !w1 = w `shiftR` 1 instance IsEmpty BitSet where isEmpty (BitSet n) = n == 0 instance HasSize BitSet where size (BitSet n) = f 0 n where f !c 0 = c f !c !v = f (c + 1) (v .&. (v - 1)) {- instance SetLike BitSet where BitSet a `difference` BitSet b = BitSet (a .&. complement b) BitSet a `intersection` BitSet b = BitSet (a .&. b) BitSet a `disjoint` BitSet b = ((a .&. b) == 0) BitSet a `isSubsetOf` BitSet b = (a .|. b) == b sempty = BitSet 0 union (BitSet a) (BitSet b) = BitSet (a .|. b) unions ss = foldl' union sempty ss instance BuildSet Int BitSet where insert i (BitSet v) = BitSet (v .|. bit i) singleton i = BitSet (bit i) fromList ts = BitSet (foldl' setBit 0 ts) instance ModifySet Int BitSet where delete i (BitSet v) = BitSet (clearBit v i) member i (BitSet v) = testBit v i toList (BitSet w) = f w 0 where f 0 _ = [] f w n = if even w then f (w `shiftR` 1) (n + 1) else n:f (w `shiftR` 1) (n + 1) sfilter fn (BitSet w) = f w 0 0 where f 0 _ r = BitSet r f w n r = if even w || not (fn n) then f w1 n1 r else f w1 n1 (setBit r n) where !n1 = n + 1 !w1 = w `shiftR` 1 -} instance Show BitSet where showsPrec n bs = showsPrec n (toList bs) newtype EnumBitSet a = EBS BitSet deriving(Monoid,Unionize,HasSize,Eq,Ord,IsEmpty) type instance Elem (EnumBitSet a) = a instance Enum a => Collection (EnumBitSet a) where singleton i = EBS $ singleton (fromEnum i) fromList ts = EBS $ fromList (map fromEnum ts) toList (EBS w) = map toEnum $ toList w type instance Key (EnumBitSet a) = Elem (EnumBitSet a) instance Enum a => SetLike (EnumBitSet a) where delete (fromEnum -> i) (EBS v) = EBS $ delete i v member (fromEnum -> i) (EBS v) = member i v insert (fromEnum -> i) (EBS v) = EBS $ insert i v sfilter f (EBS v) = EBS $ sfilter (f . toEnum) v {- instance Enum a => BuildSet a (EnumBitSet a) where fromList xs = EnumBitSet $ fromList (map fromEnum xs) insert x (EnumBitSet s) = EnumBitSet $ insert (fromEnum x) s singleton x = EnumBitSet $ singleton (fromEnum x) instance Enum a => ModifySet a (EnumBitSet a) where toList (EnumBitSet s) = map toEnum $ toList s member x (EnumBitSet s) = member (fromEnum x) s delete x (EnumBitSet s) = EnumBitSet $ delete (fromEnum x) s sfilter fn (EnumBitSet s) = EnumBitSet $ sfilter (fn . toEnum) s instance (Enum a,Show a) => Show (EnumBitSet a) where showsPrec n bs = showsPrec n (toList bs) -} toWord :: BitSet -> Word toWord (BitSet w) = w fromWord :: Word -> BitSet fromWord w = BitSet w
dec9ue/jhc_copygc
src/Util/BitSet.hs
gpl-2.0
3,994
0
12
1,112
1,093
555
538
-1
-1
{-| A history-aware add command to help with data entry. Note: this might not be sensible, but add has some aspirations of being both user-friendly and pipeable/scriptable and for this reason informational messages are mostly written to stderr rather than stdout. -} module Hledger.Cli.Add where import Control.Exception (throw) import Control.Monad import Control.Monad.Trans (liftIO) import Data.Char (toUpper) import Data.List import Data.Maybe import Data.Time.Calendar import Safe (headMay) import System.Console.Haskeline (InputT, runInputT, defaultSettings, setComplete, getInputLine) import System.Console.Haskeline.Completion import System.IO ( stderr, hPutStrLn, hPutStr ) import System.IO.Error import Text.ParserCombinators.Parsec import Text.Printf import qualified Data.Foldable as Foldable (find) import qualified Data.Set as Set import Hledger import Prelude hiding (putStr, putStrLn, appendFile) import Hledger.Utils.UTF8 (putStr, putStrLn, appendFile) import Hledger.Cli.Options import Hledger.Cli.Register (postingsReportAsText) import Hledger.Cli.Utils {- | Information used as the basis for suggested account names, amounts, etc in add prompt -} data PostingState = PostingState { psJournal :: Journal, psAccept :: AccountName -> Bool, psSuggestHistoricalAmount :: Bool, psHistory :: Maybe [Posting]} -- | Read transactions from the terminal, prompting for each field, -- and append them to the journal file. If the journal came from stdin, this -- command has no effect. add :: CliOpts -> Journal -> IO () add opts j | f == "-" = return () | otherwise = do hPrintf stderr "Adding transactions to journal file \"%s\".\n" f hPutStrLn stderr $ "To complete a transaction, enter . (period) at an account prompt.\n" ++"To stop adding transactions, enter . at a date prompt, or control-d/control-c." today <- getCurrentDay getAndAddTransactions j opts today `catch` (\e -> unless (isEOFError e) $ ioError e) where f = journalFilePath j -- | Read a number of transactions from the command line, prompting, -- validating, displaying and appending them to the journal file, until -- end of input (then raise an EOF exception). Any command-line arguments -- are used as the first transaction's description. getAndAddTransactions :: Journal -> CliOpts -> Day -> IO () getAndAddTransactions j opts defaultDate = do (t, d) <- getTransaction j opts defaultDate j <- journalAddTransaction j opts t getAndAddTransactions j opts d -- | Read a transaction from the command line, with history-aware prompting. getTransaction :: Journal -> CliOpts -> Day -> IO (Transaction,Day) getTransaction j opts defaultDate = do today <- getCurrentDay datestr <- runInteractionDefault $ askFor "date, or . to end" (Just $ showDate defaultDate) (Just $ \s -> null s || s == "." || isRight (parse (smartdate >> many spacenonewline >> eof) "" $ lowercase s)) when (datestr == ".") $ ioError $ mkIOError eofErrorType "" Nothing Nothing description <- runInteractionDefault $ askFor "description" (Just "") Nothing let historymatches = transactionsSimilarTo j (patterns_ $ reportopts_ opts) description bestmatch | null historymatches = Nothing | otherwise = Just $ snd $ head historymatches bestmatchpostings = maybe Nothing (Just . tpostings) bestmatch date = fixSmartDate today $ fromparse $ (parse smartdate "" . lowercase) datestr accept x = x == "." || (not . null) x && if no_new_accounts_ opts then isJust $ Foldable.find (== x) ant else True where (ant,_,_,_) = groupPostings $ journalPostings j getpostingsandvalidate = do ps <- getPostings (PostingState j accept True bestmatchpostings) [] let t = nulltransaction{tdate=date ,tstatus=False ,tdescription=description ,tpostings=ps } retry msg = do liftIO $ hPutStrLn stderr $ "\n" ++ msg ++ "please re-enter." getpostingsandvalidate either retry (return . flip (,) date) $ balanceTransaction Nothing t -- imprecise balancing unless (null historymatches) (liftIO $ do hPutStrLn stderr "Similar transactions found, using the first for defaults:\n" hPutStr stderr $ concatMap (\(n,t) -> printf "[%3d%%] %s" (round $ n*100 :: Int) (show t)) $ take 3 historymatches) getpostingsandvalidate -- fragile -- | Read postings from the command line until . is entered, using any -- provided historical postings and the journal context to guess defaults. getPostings :: PostingState -> [Posting] -> IO [Posting] getPostings st enteredps = do let bestmatch | isNothing historicalps = Nothing | n <= length ps = Just $ ps !! (n-1) | otherwise = Nothing where Just ps = historicalps defaultaccount = maybe Nothing (Just . showacctname) bestmatch ordot | null enteredps || length enteredrealps == 1 = "" | otherwise = ", or . to record" account <- runInteraction j $ askFor (printf "account %d%s" n ordot) defaultaccount (Just accept) if account=="." then if null enteredps then do hPutStrLn stderr $ "\nPlease enter some postings first." getPostings st enteredps else return enteredps else do let defaultacctused = Just account == defaultaccount historicalps' = if defaultacctused then historicalps else Nothing bestmatch' | isNothing historicalps' = Nothing | n <= length ps = Just $ ps !! (n-1) | otherwise = Nothing where Just ps = historicalps' defaultamountstr | isJust bestmatch' && suggesthistorical = Just historicalamountstr | n > 1 = Just balancingamountstr | otherwise = Nothing where historicalamountstr = showMixedAmountWithPrecision p $ pamount $ fromJust bestmatch' balancingamountstr = showMixedAmountWithPrecision p $ negate $ sum $ map pamount enteredrealps -- what should this be ? -- 1 maxprecision (show all decimal places or none) ? -- 2 maxprecisionwithpoint (show all decimal places or .0 - avoids some but not all confusion with thousands separators) ? -- 3 canonical precision for this commodity in the journal ? -- 4 maximum precision entered so far in this transaction ? -- 5 3 or 4, whichever would show the most decimal places ? -- I think 1 or 4, whichever would show the most decimal places p = maxprecisionwithpoint amountstr <- runInteractionDefault $ askFor (printf "amount %d" n) defaultamountstr validateamount let amount = fromparse $ runParser (someamount <|> return missingamt) ctx "" amountstr amount' = fromparse $ runParser (someamount <|> return missingamt) nullctx "" amountstr defaultamtused = Just (showMixedAmount amount) == defaultamountstr commodityadded | c == cwithnodef = Nothing | otherwise = c where c = maybemixedamountcommodity amount cwithnodef = maybemixedamountcommodity amount' maybemixedamountcommodity = maybe Nothing (Just . commodity) . headMay . amounts p = nullposting{paccount=stripbrackets account, pamount=amount, ptype=postingtype account} st' = if defaultamtused then st else st{psHistory = historicalps', psSuggestHistoricalAmount = False} when (isJust commodityadded) $ liftIO $ hPutStrLn stderr $ printf "using default commodity (%s)" (symbol $ fromJust commodityadded) getPostings st' (enteredps ++ [p]) where j = psJournal st historicalps = psHistory st ctx = jContext j accept = psAccept st suggesthistorical = psSuggestHistoricalAmount st n = length enteredps + 1 enteredrealps = filter isReal enteredps showacctname p = showAccountName Nothing (ptype p) $ paccount p postingtype ('[':_) = BalancedVirtualPosting postingtype ('(':_) = VirtualPosting postingtype _ = RegularPosting stripbrackets = dropWhile (`elem` "([") . reverse . dropWhile (`elem` "])") . reverse validateamount = Just $ \s -> (null s && not (null enteredrealps)) || isRight (runParser (someamount>>many spacenonewline>>eof) ctx "" s) -- | Prompt for and read a string value, optionally with a default value -- and a validator. A validator causes the prompt to repeat until the -- input is valid. May also raise an EOF exception if control-d is pressed. askFor :: String -> Maybe String -> Maybe (String -> Bool) -> InputT IO String askFor prompt def validator = do l <- fmap (maybe eofErr id) $ getInputLine $ prompt ++ maybe "" showdef def ++ ": " let input = if null l then fromMaybe l def else l case validator of Just valid -> if valid input then return input else askFor prompt def validator Nothing -> return input where showdef s = " [" ++ s ++ "]" eofErr = throw $ mkIOError eofErrorType "end of input" Nothing Nothing -- | Append this transaction to the journal's file, and to the journal's -- transaction list. journalAddTransaction :: Journal -> CliOpts -> Transaction -> IO Journal journalAddTransaction j@Journal{jtxns=ts} opts t = do let f = journalFilePath j appendToJournalFileOrStdout f $ showTransaction t when (debug_ opts) $ do putStrLn $ printf "\nAdded transaction to %s:" f putStrLn =<< registerFromString (show t) return j{jtxns=ts++[t]} -- | Append a string, typically one or more transactions, to a journal -- file, or if the file is "-", dump it to stdout. Tries to avoid -- excess whitespace. appendToJournalFileOrStdout :: FilePath -> String -> IO () appendToJournalFileOrStdout f s | f == "-" = putStr s' | otherwise = appendFile f s' where s' = "\n" ++ ensureOneNewlineTerminated s -- | Replace a string's 0 or more terminating newlines with exactly one. ensureOneNewlineTerminated :: String -> String ensureOneNewlineTerminated = (++"\n") . reverse . dropWhile (=='\n') . reverse -- | Convert a string of journal data into a register report. registerFromString :: String -> IO String registerFromString s = do d <- getCurrentDay j <- readJournal' s return $ postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts d) j where opts = defreportopts{empty_=True} -- | Return a similarity measure, from 0 to 1, for two strings. -- This is Simon White's letter pairs algorithm from -- http://www.catalysoft.com/articles/StrikeAMatch.html -- with a modification for short strings. compareStrings :: String -> String -> Double compareStrings "" "" = 1 compareStrings (_:[]) "" = 0 compareStrings "" (_:[]) = 0 compareStrings (a:[]) (b:[]) = if toUpper a == toUpper b then 1 else 0 compareStrings s1 s2 = 2.0 * fromIntegral i / fromIntegral u where i = length $ intersect pairs1 pairs2 u = length pairs1 + length pairs2 pairs1 = wordLetterPairs $ uppercase s1 pairs2 = wordLetterPairs $ uppercase s2 wordLetterPairs = concatMap letterPairs . words letterPairs (a:b:rest) = [a,b] : letterPairs (b:rest) letterPairs _ = [] compareDescriptions :: [Char] -> [Char] -> Double compareDescriptions s t = compareStrings s' t' where s' = simplify s t' = simplify t simplify = filter (not . (`elem` "0123456789")) transactionsSimilarTo :: Journal -> [String] -> String -> [(Double,Transaction)] transactionsSimilarTo j apats s = sortBy compareRelevanceAndRecency $ filter ((> threshold).fst) [(compareDescriptions s $ tdescription t, t) | t <- ts] where compareRelevanceAndRecency (n1,t1) (n2,t2) = compare (n2,tdate t2) (n1,tdate t1) ts = jtxns $ filterJournalTransactionsByAccount apats j threshold = 0 runInteraction :: Journal -> InputT IO a -> IO a runInteraction j m = do let cc = completionCache j runInputT (setComplete (accountCompletion cc) defaultSettings) m runInteractionDefault :: InputT IO a -> IO a runInteractionDefault m = do runInputT (setComplete noCompletion defaultSettings) m -- A precomputed list of all accounts previously entered into the journal. type CompletionCache = [AccountName] completionCache :: Journal -> CompletionCache completionCache j = -- Only keep unique account names. Set.toList $ Set.fromList [paccount p | t <- jtxns j, p <- tpostings t] accountCompletion :: CompletionCache -> CompletionFunc IO accountCompletion cc = completeWord Nothing "" -- don't break words on whitespace, since account names -- can contain spaces. $ \s -> return $ map simpleCompletion $ filter (s `isPrefixOf`) cc
Lainepress/hledger
hledger/Hledger/Cli/Add.hs
gpl-3.0
13,414
0
21
3,526
3,272
1,673
1,599
217
7
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TypeSynonymInstances, FlexibleContexts, NoMonomorphismRestriction #-} import System.IO import System.Exit import XMonad import XMonad.Config.Gnome import XMonad.Util.Run(spawnPipe) import XMonad.Util.CustomKeys import XMonad.Util.Font import XMonad.Util.WindowProperties import XMonad.Actions.CycleWS import XMonad.Actions.GridSelect import XMonad.Layout.Tabbed import XMonad.Layout.Named import XMonad.Layout.NoBorders import XMonad.Layout.WindowNavigation import XMonad.Layout.PerWorkspace import XMonad.Layout.Fullscreen import XMonad.Layout.SubLayouts import XMonad.Layout.Reflect import XMonad.Layout.LayoutModifier import XMonad.Layout.Grid import XMonad.Hooks.ManageDocks import XMonad.Hooks.EwmhDesktops import XMonad.Hooks.SetWMName import XMonad.Hooks.DynamicLog import qualified Data.Map as M import qualified XMonad.StackSet as S myConf = gnomeConfig -- CONFIGURAZIONE TASTI; GLOBAL ENV; SETTARE myMask COME CI SI TROVA MEGLIO -- altMask = mod1Mask winMask = mod4Mask myMask = altMask myNB = "#0000FF" myFC = "#FF0000" -- CONFIGURAZIONE CARINA DEI WORKSPACES: CON NOME F:n -- myWorkspaces = (miscs 8) ++ ["fullscreen", "im"] where miscs = map (("F" ++) . show) . (flip take) [1..] isFullscreen = (== "fullscreen") -- KEYBINDING IN FUNZIONE A myMask -- myKeys conf = M.fromList $[ ((myMask, xK_F5), spawn $ XMonad.terminal conf ), ((myMask, xK_F5), spawn "xterm"), ((myMask, xK_F2), spawn "dmenu_run -fn -misc-fixed-*-r-*-*-15-*-*-*-*-*-*-* "), ((myMask, xK_F8), spawn "xbacklight -dec 10"), ((myMask, xK_F9), spawn "xbacklight -inc 10"), ((myMask .|. controlMask, xK_r), spawn "xmonad --restart"), --Utile quando si è un modalità di debug -- ((myMask, xK_l), spawn "xscreensaver-command -lock"), ((controlMask .|. shiftMask, xK_F12), io (exitWith ExitSuccess) ), ((myMask .|. controlMask, xK_Left), prevWS), ((myMask .|. controlMask, xK_Right), nextWS), ((myMask, xK_space), sendMessage NextLayout), ((myMask, xK_Tab), windows S.focusDown), ((myMask .|. controlMask .|. shiftMask, xK_Left), shiftToPrev), ((myMask .|. controlMask .|. shiftMask, xK_Right), shiftToNext), ((winMask .|. altMask , xK_k ) , sendMessage Shrink), ((winMask .|. altMask , xK_l ) , sendMessage Expand), ((myMask, xK_w), goToSelected defaultGSConfig) ] -- CONFIGURAZIONE DEL LAYOUT -- myLayout = windowNavigation $ fullscreen $ normal where normal = tallLayout ||| wideLayout ||| tabbedLayout fullscreen = onWorkspace "fullscreen" fullscreenLayout im = onWorkspace "im" imLayout tallLayout = named "tall" $ avoidStruts $ subTabbed $ basicLayout wideLayout = named "wide" $ avoidStruts $ subTabbed $ Mirror basicLayout tabbedLayout = named "tab" $ avoidStruts $ noBorders simpleTabbed fullscreenLayout = named "fullscreen" $ noBorders Full basicLayout = Tall nmaster delta ratio where nmaster = 1 delta = 3/100 ratio = 1/2 -- ROSTER PER IM-LAYOUT -- imLayout = avoidStruts $ reflectHoriz $ withIMs ratio rosters chatLayout where chatLayout = Grid ratio = 1/6 rosters = [skypeRoster, pidginRoster] pidginRoster = And (ClassName "Pidgin") (Role "buddy_list") skypeRoster = (ClassName "Skype") `And` (Not (Title "Options")) `And` (Not (Role "Chats")) `And` (Not (Role "CallWindowForm")) data AddRosters a = AddRosters Rational [Property] deriving (Read, Show) --instance LayoutModifier AddRosters Window where -- modifyLayout (AddRosters ratio props) = applyIMs ratio props -- modifierDescription _ = "IMs" withIMs :: LayoutClass l a => Rational -> [Property] -> l a -> ModifiedLayout AddRosters l a withIMs ratio props = ModifiedLayout $ AddRosters ratio props gridIMs :: Rational -> [Property] -> ModifiedLayout AddRosters Grid a gridIMs ratio props = withIMs ratio props Grid hasAnyProperty :: [Property] -> Window -> X Bool hasAnyProperty [] _ = return False hasAnyProperty (p:ps) w = do b <- hasProperty p w if b then return True else hasAnyProperty ps w --applyIMs :: (LayoutClass a b) => Rational --applyIMs :: (LayoutClass l Window) => -- Rational -- -> [Property] -- -> S.Workspace WorkspaceId (l Window) Window -- -> Rectangle -- -> X ([(Window, Rectangle)], Maybe (l Window)) --applyIMs ratio props wksp rect = do --let stack = S.stack wksp --let ws = S.integrate' $ stack --rosters <- filterM (hasAnyProperty props) ws --let n = fromIntegral $ length rosters --let (rostersRect, chatsRect) = splitHorizontallyBy (n * ratio) rect --let rosterRects = splitHorizontally n rostersRect --let filteredStack = stack >>= S.filter (`notElem` rosters) --(a,b) <- runLayout (wksp {S.stack = filteredStack}) chatsRect --return (zip rosters rosterRects ++ a, b) -- MAIN -- main = do xmproc <- spawnPipe "xmobar" xmonad $ myConf { logHook = dynamicLogWithPP xmobarPP{ ppOutput = hPutStrLn xmproc , ppLayout = const "" , ppTitle = xmobarColor "green" "" . shorten 80 } >> ewmhDesktopsLogHook >> setWMName "LG3D" , keys = myKeys , layoutHook = myLayout , workspaces = myWorkspaces , normalBorderColor = myNB , focusedBorderColor = myFC }
algebrato/Pad39A
xmonad.hs
gpl-3.0
5,254
56
16
942
1,318
755
563
97
2
-- -- Copyright (C) 2011 Kiel Friedt -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- cs 381, Summer 2010, homework 0 -- kiel friedt module Hw0 where hello :: String hello = "Hello World!" -- betweenOneAndTen that returns True if its argument is between 1 and 10 inclusive. betweenOneAndTen :: Int -> Bool betweenOneAndTen x = x <= 10 && x >= 1 --Type signature for a function inInterval, which returns True if the third argument is in between the first two (inclusively). inInterval :: Int->Int->Int->Bool inInterval lo hi x = (x >= lo && x <= hi) -- betweenOneAndTwenty using inInterval function betweenOneAndTwenty :: Int->Bool betweenOneAndTwenty x = inInterval 1 20 x --takes in a int value and returns value in polynomial poly :: Int->Int poly x = 4*x*x + 2*x +17 --Factorial recurrence relation. fact :: Integer->Integer fact 0 = 1 fact n = n * fact (n-1) -- two functions: pick and choose using fact pick :: Integer->Integer->Integer pick n k = fact n `div` fact (n - k) choose :: Integer->Integer->Integer choose n k = fact n `div` (fact (n-k) * fact k) --Guard Expressions rec :: Int->Int rec 0 = 11 rec 1 = 22 rec n | even n = n * rec(n-1) + rec(n-1) | otherwise = rec(n-1) * rec(n-2) mod1 :: Int->Int->Int mod1 n x = mod n x -- type signature and function rec2 for the recurrence rec2 :: Int->Int rec2 n | n == 0 = 44 | ((mod n 3) == 0 && (mod n 2) /= 0) = n*n*rec2(n-1) | otherwise = n*rec2(n-1) --function rec3 for the same recurrence as rec2 except use a guard expressions and no if-then-else expressions. rec3 :: Int->Int rec3 0 = 44 rec3 n | ((mod n 3) == 0 && (mod n 2) /= 0) = n*n*rec2(n-1) rec3 n = n*rec2(n-1) -- squares 15 fifteenSquared :: Int fifteenSquared = 15 * 15
kielfriedt/Languages
Hw0.hs
gpl-3.0
2,397
61
11
527
683
369
314
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.FirebaseHosting.Types.Product -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.FirebaseHosting.Types.Product where import Network.Google.FirebaseHosting.Types.Sum import Network.Google.Prelude -- | The \`Status\` type defines a logical error model that is suitable for -- different programming environments, including REST APIs and RPC APIs. It -- is used by [gRPC](https:\/\/github.com\/grpc). Each \`Status\` message -- contains three pieces of data: error code, error message, and error -- details. You can find out more about this error model and how to work -- with it in the [API Design -- Guide](https:\/\/cloud.google.com\/apis\/design\/errors). -- -- /See:/ 'status' smart constructor. data Status = Status' { _sDetails :: !(Maybe [StatusDetailsItem]) , _sCode :: !(Maybe (Textual Int32)) , _sMessage :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Status' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sDetails' -- -- * 'sCode' -- -- * 'sMessage' status :: Status status = Status' {_sDetails = Nothing, _sCode = Nothing, _sMessage = Nothing} -- | A list of messages that carry the error details. There is a common set -- of message types for APIs to use. sDetails :: Lens' Status [StatusDetailsItem] sDetails = lens _sDetails (\ s a -> s{_sDetails = a}) . _Default . _Coerce -- | The status code, which should be an enum value of google.rpc.Code. sCode :: Lens' Status (Maybe Int32) sCode = lens _sCode (\ s a -> s{_sCode = a}) . mapping _Coerce -- | A developer-facing error message, which should be in English. Any -- user-facing error message should be localized and sent in the -- google.rpc.Status.details field, or localized by the client. sMessage :: Lens' Status (Maybe Text) sMessage = lens _sMessage (\ s a -> s{_sMessage = a}) instance FromJSON Status where parseJSON = withObject "Status" (\ o -> Status' <$> (o .:? "details" .!= mempty) <*> (o .:? "code") <*> (o .:? "message")) instance ToJSON Status where toJSON Status'{..} = object (catMaybes [("details" .=) <$> _sDetails, ("code" .=) <$> _sCode, ("message" .=) <$> _sMessage]) -- | The response message for Operations.ListOperations. -- -- /See:/ 'listOperationsResponse' smart constructor. data ListOperationsResponse = ListOperationsResponse' { _lorNextPageToken :: !(Maybe Text) , _lorOperations :: !(Maybe [Operation]) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ListOperationsResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'lorNextPageToken' -- -- * 'lorOperations' listOperationsResponse :: ListOperationsResponse listOperationsResponse = ListOperationsResponse' {_lorNextPageToken = Nothing, _lorOperations = Nothing} -- | The standard List next-page token. lorNextPageToken :: Lens' ListOperationsResponse (Maybe Text) lorNextPageToken = lens _lorNextPageToken (\ s a -> s{_lorNextPageToken = a}) -- | A list of operations that matches the specified filter in the request. lorOperations :: Lens' ListOperationsResponse [Operation] lorOperations = lens _lorOperations (\ s a -> s{_lorOperations = a}) . _Default . _Coerce instance FromJSON ListOperationsResponse where parseJSON = withObject "ListOperationsResponse" (\ o -> ListOperationsResponse' <$> (o .:? "nextPageToken") <*> (o .:? "operations" .!= mempty)) instance ToJSON ListOperationsResponse where toJSON ListOperationsResponse'{..} = object (catMaybes [("nextPageToken" .=) <$> _lorNextPageToken, ("operations" .=) <$> _lorOperations]) -- | The request message for Operations.CancelOperation. -- -- /See:/ 'cancelOperationRequest' smart constructor. data CancelOperationRequest = CancelOperationRequest' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CancelOperationRequest' with the minimum fields required to make a request. -- cancelOperationRequest :: CancelOperationRequest cancelOperationRequest = CancelOperationRequest' instance FromJSON CancelOperationRequest where parseJSON = withObject "CancelOperationRequest" (\ o -> pure CancelOperationRequest') instance ToJSON CancelOperationRequest where toJSON = const emptyObject -- | This resource represents a long-running operation that is the result of -- a network API call. -- -- /See:/ 'operation' smart constructor. data Operation = Operation' { _oDone :: !(Maybe Bool) , _oError :: !(Maybe Status) , _oResponse :: !(Maybe OperationResponse) , _oName :: !(Maybe Text) , _oMetadata :: !(Maybe OperationMetadata) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Operation' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'oDone' -- -- * 'oError' -- -- * 'oResponse' -- -- * 'oName' -- -- * 'oMetadata' operation :: Operation operation = Operation' { _oDone = Nothing , _oError = Nothing , _oResponse = Nothing , _oName = Nothing , _oMetadata = Nothing } -- | If the value is \`false\`, it means the operation is still in progress. -- If \`true\`, the operation is completed, and either \`error\` or -- \`response\` is available. oDone :: Lens' Operation (Maybe Bool) oDone = lens _oDone (\ s a -> s{_oDone = a}) -- | The error result of the operation in case of failure or cancellation. oError :: Lens' Operation (Maybe Status) oError = lens _oError (\ s a -> s{_oError = a}) -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. oResponse :: Lens' Operation (Maybe OperationResponse) oResponse = lens _oResponse (\ s a -> s{_oResponse = a}) -- | The server-assigned name, which is only unique within the same service -- that originally returns it. If you use the default HTTP mapping, the -- \`name\` should be a resource name ending with -- \`operations\/{unique_id}\`. oName :: Lens' Operation (Maybe Text) oName = lens _oName (\ s a -> s{_oName = a}) -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. oMetadata :: Lens' Operation (Maybe OperationMetadata) oMetadata = lens _oMetadata (\ s a -> s{_oMetadata = a}) instance FromJSON Operation where parseJSON = withObject "Operation" (\ o -> Operation' <$> (o .:? "done") <*> (o .:? "error") <*> (o .:? "response") <*> (o .:? "name") <*> (o .:? "metadata")) instance ToJSON Operation where toJSON Operation'{..} = object (catMaybes [("done" .=) <$> _oDone, ("error" .=) <$> _oError, ("response" .=) <$> _oResponse, ("name" .=) <$> _oName, ("metadata" .=) <$> _oMetadata]) -- | A generic empty message that you can re-use to avoid defining duplicated -- empty messages in your APIs. A typical example is to use it as the -- request or the response type of an API method. For instance: service Foo -- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The -- JSON representation for \`Empty\` is empty JSON object \`{}\`. -- -- /See:/ 'empty' smart constructor. data Empty = Empty' deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'Empty' with the minimum fields required to make a request. -- empty :: Empty empty = Empty' instance FromJSON Empty where parseJSON = withObject "Empty" (\ o -> pure Empty') instance ToJSON Empty where toJSON = const emptyObject -- -- /See:/ 'statusDetailsItem' smart constructor. newtype StatusDetailsItem = StatusDetailsItem' { _sdiAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sdiAddtional' statusDetailsItem :: HashMap Text JSONValue -- ^ 'sdiAddtional' -> StatusDetailsItem statusDetailsItem pSdiAddtional_ = StatusDetailsItem' {_sdiAddtional = _Coerce # pSdiAddtional_} -- | Properties of the object. Contains field \'type with type URL. sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue) sdiAddtional = lens _sdiAddtional (\ s a -> s{_sdiAddtional = a}) . _Coerce instance FromJSON StatusDetailsItem where parseJSON = withObject "StatusDetailsItem" (\ o -> StatusDetailsItem' <$> (parseJSONObject o)) instance ToJSON StatusDetailsItem where toJSON = toJSON . _sdiAddtional -- | Service-specific metadata associated with the operation. It typically -- contains progress information and common metadata such as create time. -- Some services might not provide such metadata. Any method that returns a -- long-running operation should document the metadata type, if any. -- -- /See:/ 'operationMetadata' smart constructor. newtype OperationMetadata = OperationMetadata' { _omAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationMetadata' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'omAddtional' operationMetadata :: HashMap Text JSONValue -- ^ 'omAddtional' -> OperationMetadata operationMetadata pOmAddtional_ = OperationMetadata' {_omAddtional = _Coerce # pOmAddtional_} -- | Properties of the object. Contains field \'type with type URL. omAddtional :: Lens' OperationMetadata (HashMap Text JSONValue) omAddtional = lens _omAddtional (\ s a -> s{_omAddtional = a}) . _Coerce instance FromJSON OperationMetadata where parseJSON = withObject "OperationMetadata" (\ o -> OperationMetadata' <$> (parseJSONObject o)) instance ToJSON OperationMetadata where toJSON = toJSON . _omAddtional -- | The normal response of the operation in case of success. If the original -- method returns no data on success, such as \`Delete\`, the response is -- \`google.protobuf.Empty\`. If the original method is standard -- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource. -- For other methods, the response should have the type \`XxxResponse\`, -- where \`Xxx\` is the original method name. For example, if the original -- method name is \`TakeSnapshot()\`, the inferred response type is -- \`TakeSnapshotResponse\`. -- -- /See:/ 'operationResponse' smart constructor. newtype OperationResponse = OperationResponse' { _orAddtional :: HashMap Text JSONValue } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'OperationResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'orAddtional' operationResponse :: HashMap Text JSONValue -- ^ 'orAddtional' -> OperationResponse operationResponse pOrAddtional_ = OperationResponse' {_orAddtional = _Coerce # pOrAddtional_} -- | Properties of the object. Contains field \'type with type URL. orAddtional :: Lens' OperationResponse (HashMap Text JSONValue) orAddtional = lens _orAddtional (\ s a -> s{_orAddtional = a}) . _Coerce instance FromJSON OperationResponse where parseJSON = withObject "OperationResponse" (\ o -> OperationResponse' <$> (parseJSONObject o)) instance ToJSON OperationResponse where toJSON = toJSON . _orAddtional
brendanhay/gogol
gogol-firebasehosting/gen/Network/Google/FirebaseHosting/Types/Product.hs
mpl-2.0
13,292
0
15
2,879
2,058
1,195
863
222
1
{-# LANGUAGE TypeFamilies, GADTs, ExistentialQuantification, EmptyDataDecls, ScopedTypeVariables, FlexibleInstances #-} module HEP.Jet.FastJet.AddOn where
wavewave/HFastJet
oldsrc/HEP/Jet/FastJet/AddOn.hs
lgpl-2.1
157
0
3
14
9
7
2
2
0
addStuff :: Int -> Int addStuff = do a <- (*2) b <- (+10) return (a+b) addStuff1 = (*2) >>= \a -> (+10) >>= \b -> return (a+b) {- (*2) >>= \a -> (+10) >>= \b -> return (a+b) == \w -> (\a -> (+10) >>= \b -> return (a+b)) (w*2) w == \w -> ((+10) >>= \b -> return (w*2+b)) w == \w -> (\w' -> (\b->return (w*2+b)) (w'+10) w') w == \w -> (\w' -> (return (w*2 +(w'+10))) w') w == \w -> (\w' -> (\_ -> (w*2+(w'+10))) w') w == \w -> (\w' -> (w*2+ (w'+10)) ) w == \w -> (w*2 + (w+10)) -} {- a <- (*2) return (1+a) (*2) >>= \a -> return (1+a) == (*2) >>= \a -> (\_ -> (1+a)) == \w -> (\a -> (\_ -> (1+a))) (w*2) w == \w -> (\_ -> (1+w*2)) w == \w -> 1 + 2*w -} -- > addStuff 3 -- 19 -- > addStuff1 3 -- 19 {- h >>= f = \w -> f (h w) w f = (\a -> (+10) >>= \b -> return (a+b)) f (h w) = (+10) >>= \b -> return ((h w) +b) (\w' -> (\b->return ((h w) + b)) (h' w') ) w (\w' -> return ((h w) + (h' w')) w' ) w return ((h w) + (h' w)) w = (h w) + (h' w) -}
egaburov/funstuff
Haskell/monads/monad1.hs
apache-2.0
1,029
0
11
321
98
57
41
6
1
data List a = Nil | Cons a (List a) len xs = len' 0 xs len' acc xs = case xs of Nil -> acc Cons _ t -> len' (acc+1) t safe queen diag xs = case xs of Nil -> True Cons q t -> queen /= q && queen /= q + diag && queen /= q - diag && safe queen (diag + 1) t appendSafe k soln solns = if (k <= 0) then solns else if safe k 1 soln then appendSafe (k-1) soln (Cons (Cons k soln) solns) else appendSafe (k-1) soln solns extend n acc solns = case solns of Nil -> acc Cons soln rest -> extend n (appendSafe n soln acc) rest find_solutions n k = if k == 0 then Cons Nil Nil else extend n Nil (find_solutions n (k-1)) -- fst_solution n = head (find_solutions n n) queens n = len (find_solutions n n) main = print (queens 13)
lpeterse/koka
test/medium/nqueens.hs
apache-2.0
874
2
15
323
382
189
193
29
3
{-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE BangPatterns #-} module Haskell.Decode.Operations where import Data.Int (Int32,Int16) import qualified Prelude as P import Prelude hiding (Num(..),Ord(..)) import Data.Monoid (Monoid(..),(<>)) type family Signum d :: * class (Eq d,Monoid (Signum d)) => Operations d where signum :: d -> Signum d abs :: d -> d negate :: d -> d zero :: d (<) :: d -> d -> Bool threeFourths :: d -> d (+) :: d -> d -> d (-) :: d -> d -> d (*) :: Signum d -> d -> d min a b = if a < b then a else b type instance Signum Double = SignumDouble newtype SignumDouble = SignumDouble Double instance Monoid SignumDouble where mempty = SignumDouble 1 mappend (SignumDouble x) (SignumDouble y) = SignumDouble (x P.* y) instance Operations Double where signum d = SignumDouble (P.signum d) abs = P.abs negate = P.negate zero = 0 (<) = (P.<) threeFourths = ((3 / 4) P.*) (+) = (P.+) (-) = (P.-) SignumDouble s * d = s P.* d type instance Signum Int = SignumInt newtype SignumInt = SignumInt Int instance Monoid SignumInt where mempty = SignumInt 1 mappend (SignumInt x) (SignumInt y) = SignumInt (x P.* y) instance Operations Int where signum i = SignumInt (P.signum i) -- surprisingly: P.abs minBound == minBound !! abs i = if i == minBound then maxBound else P.abs i -- surprisingly: P.negate minBound == minBound !! negate i = if i == minBound then maxBound else P.negate i zero = 0 (<) = (P.<) threeFourths i = let !half = i `div` 2 in half P.+ (half `div` 2) -- avoids overflows x + y = if x P.> 0 && y P.> 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.< 0 && z P.>= 0 then minBound else z where z = x P.+ y -- avoids overflows x - y = if x P.> 0 && y P.< 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.> 0 && z P.>= 0 then minBound else z where z = x P.- y SignumInt s * d = s P.* d type instance Signum Int32 = SignumInt32 newtype SignumInt32 = SignumInt32 Int32 instance Monoid SignumInt32 where mempty = SignumInt32 1 mappend (SignumInt32 x) (SignumInt32 y) = SignumInt32 (x P.* y) instance Operations Int32 where signum i = SignumInt32 (P.signum i) -- surprisingly: P.abs minBound == minBound !! abs i = if i == minBound then maxBound else P.abs i -- surprisingly: P.negate minBound == minBound !! negate i = if i == minBound then maxBound else P.negate i zero = 0 (<) = (P.<) threeFourths i = let !half = i `div` 2 in half P.+ (half `div` 2) -- avoids overflows x + y = if x P.> 0 && y P.> 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.< 0 && z P.>= 0 then minBound else z where z = x P.+ y -- avoids overflows x - y = if x P.> 0 && y P.< 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.> 0 && z P.>= 0 then minBound else z where z = x P.- y SignumInt32 s * d = s P.* d type instance Signum Int16 = SignumInt16 newtype SignumInt16 = SignumInt16 Int16 instance Monoid SignumInt16 where mempty = SignumInt16 1 mappend (SignumInt16 x) (SignumInt16 y) = SignumInt16 (x P.* y) instance Operations Int16 where signum i = SignumInt16 (P.signum i) -- surprisingly: P.abs minBound == minBound !! abs i = if i == minBound then maxBound else P.abs i -- surprisingly: P.negate minBound == minBound !! negate i = if i == minBound then maxBound else P.negate i zero = 0 (<) = (P.<) threeFourths i = let !half = i `div` 2 in half P.+ (half `div` 2) -- avoids overflows x + y = if x P.> 0 && y P.> 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.< 0 && z P.>= 0 then minBound else z where z = x P.+ y -- avoids overflows x - y = if x P.> 0 && y P.< 0 && z P.<= 0 then maxBound else if x P.< 0 && y P.> 0 && z P.>= 0 then minBound else z where z = x P.- y SignumInt16 s * d = s P.* d {-# INLINE min_dagger #-} min_dagger :: Operations d => d -> d -> d min_dagger x y = (signum x <> signum y) * min (abs x) (abs y) -- INVARIANT all values in this data-structure are non-negative data MD a = ZeroMD | OneMD a | TwoMD a a -- INVARIANT all arguments non-negative minMD ZeroMD x = OneMD x minMD (OneMD a) x | x < a = TwoMD x a | otherwise = TwoMD a x minMD (TwoMD a b) x | x < a = TwoMD x a | x < b = TwoMD a x | otherwise = TwoMD a b {-# INLINE minMD #-}
ku-fpg/ldpc
src/LDPC/Decode/Operations.hs
bsd-2-clause
4,590
0
12
1,320
1,866
1,000
866
121
2
module CLasH.Utils.Pretty (prettyShow, pprString, pprStringDebug, zEncodeString) where -- Standard imports import qualified Data.Map as Map import Text.PrettyPrint.HughesPJClass import Data.Char import Numeric -- GHC API import qualified CoreSyn import Outputable ( showSDoc, showSDocDebug, ppr, Outputable, OutputableBndr) -- VHDL Imports import qualified Language.VHDL.Ppr as Ppr import qualified Language.VHDL.AST as AST import qualified Language.VHDL.AST.Ppr -- Local imports import CLasH.VHDL.VHDLTypes import CLasH.Utils.Core.CoreShow -- | A version of the default pPrintList method, which uses a custom function -- f instead of pPrint to print elements. printList :: (a -> Doc) -> [a] -> Doc printList f = brackets . fsep . punctuate comma . map f {- instance Pretty FuncData where pPrint (FuncData flatfunc entity arch) = text "Flattened: " $$ nest 15 (ppffunc flatfunc) $+$ text "Entity" $$ nest 15 (ppent entity) $+$ pparch arch where ppffunc (Just f) = pPrint f ppffunc Nothing = text "Nothing" ppent (Just e) = pPrint e ppent Nothing = text "Nothing" pparch Nothing = text "VHDL architecture not present" pparch (Just _) = text "VHDL architecture present" -} instance Pretty Entity where pPrint (Entity id args res decl) = text "Entity: " $$ nest 10 (pPrint id) $+$ text "Args: " $$ nest 10 (pPrint args) $+$ text "Result: " $$ nest 10 (pPrint res) $+$ text "Declaration not shown" instance (OutputableBndr b, Show b) => Pretty (CoreSyn.Bind b) where pPrint (CoreSyn.NonRec b expr) = text "NonRec: " $$ nest 10 (prettyBind (b, expr)) pPrint (CoreSyn.Rec binds) = text "Rec: " $$ nest 10 (vcat $ map (prettyBind) binds) instance (OutputableBndr b, Show b) => Pretty (CoreSyn.Expr b) where pPrint = text . show instance Pretty AST.VHDLId where pPrint id = Ppr.ppr id instance Pretty AST.VHDLName where pPrint name = Ppr.ppr name prettyBind :: (Show b, Show e) => (b, e) -> Doc prettyBind (b, expr) = text b' <> text " = " <> text expr' where b' = show b expr' = show expr instance (Pretty k, Pretty v) => Pretty (Map.Map k v) where pPrint = vcat . map ppentry . Map.toList where ppentry (k, v) = pPrint k <> text " : " $$ nest 15 (pPrint v) -- Convenience method for turning an Outputable into a string pprString :: (Outputable x) => x -> String pprString = showSDoc . ppr pprStringDebug :: (Outputable x) => x -> String pprStringDebug = showSDocDebug . ppr type UserString = String -- As the user typed it type EncodedString = String -- Encoded form zEncodeString :: UserString -> EncodedString zEncodeString cs = case maybe_tuple cs of Just n -> n ++ (go cs) -- Tuples go to Z2T etc Nothing -> go cs where go [] = [] go (c:cs) = encode_digit_ch c ++ go' cs go' [] = [] go' (c:cs) = encode_ch c ++ go' cs maybe_tuple :: UserString -> Maybe EncodedString maybe_tuple "(# #)" = Just("Z1H") maybe_tuple ('(' : '#' : cs) = case count_commas (0::Int) cs of (n, '#' : ')' : _) -> Just ('Z' : shows (n+1) "H") _ -> Nothing maybe_tuple "()" = Just("Z0T") maybe_tuple ('(' : cs) = case count_commas (0::Int) cs of (n, ')' : _) -> Just ('Z' : shows (n+1) "T") _ -> Nothing maybe_tuple _ = Nothing count_commas :: Int -> String -> (Int, String) count_commas n (',' : cs) = count_commas (n+1) cs count_commas n cs = (n,cs) encode_digit_ch :: Char -> EncodedString encode_digit_ch c | c >= '0' && c <= '9' = encode_as_unicode_char c encode_digit_ch c | otherwise = encode_ch c encode_ch :: Char -> EncodedString encode_ch c | unencodedChar c = [c] -- Common case first -- Constructors encode_ch '(' = "ZL" -- Needed for things like (,), and (->) encode_ch ')' = "ZR" -- For symmetry with ( encode_ch '[' = "ZM" encode_ch ']' = "ZN" encode_ch ':' = "ZC" -- Variables encode_ch '&' = "za" encode_ch '|' = "zb" encode_ch '^' = "zc" encode_ch '$' = "zd" encode_ch '=' = "ze" encode_ch '>' = "zg" encode_ch '#' = "zh" encode_ch '.' = "zi" encode_ch '<' = "zl" encode_ch '-' = "zm" encode_ch '!' = "zn" encode_ch '+' = "zp" encode_ch '\'' = "zq" encode_ch '\\' = "zr" encode_ch '/' = "zs" encode_ch '*' = "zt" encode_ch '%' = "zv" encode_ch c = encode_as_unicode_char c encode_as_unicode_char :: Char -> EncodedString encode_as_unicode_char c = 'z' : if isDigit (head hex_str) then hex_str else '0':hex_str where hex_str = showHex (ord c) "U" unencodedChar :: Char -> Bool -- True for chars that don't need encoding unencodedChar c = c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'
christiaanb/clash
clash/CLasH/Utils/Pretty.hs
bsd-3-clause
5,175
0
17
1,542
1,504
788
716
105
4
{-# LANGUAGE RankNTypes, ScopedTypeVariables, GADTs, EmptyDataDecls, PatternGuards, TypeFamilies, MultiParamTypeClasses #-} module Compiler.Hoopl.Dataflow ( DataflowLattice(..), JoinFun, OldFact(..), NewFact(..), Fact, mkFactBase , ChangeFlag(..), changeIf , FwdPass(..), FwdTransfer, mkFTransfer, mkFTransfer3, getFTransfer3 -- * Respecting Fuel -- $fuel , FwdRewrite, mkFRewrite, mkFRewrite3, getFRewrite3, noFwdRewrite , wrapFR, wrapFR2 , BwdPass(..), BwdTransfer, mkBTransfer, mkBTransfer3, getBTransfer3 , wrapBR, wrapBR2 , BwdRewrite, mkBRewrite, mkBRewrite3, getBRewrite3, noBwdRewrite , analyzeAndRewriteFwd, analyzeAndRewriteBwd ) where import Control.Monad import Data.Maybe import Compiler.Hoopl.Checkpoint import Compiler.Hoopl.Collections import Compiler.Hoopl.Fuel import Compiler.Hoopl.Graph hiding (Graph) -- hiding so we can redefine -- and include definition in paper import qualified Compiler.Hoopl.GraphUtil as U import Compiler.Hoopl.Label import Compiler.Hoopl.Util ----------------------------------------------------------------------------- -- DataflowLattice ----------------------------------------------------------------------------- data DataflowLattice a = DataflowLattice { fact_name :: String -- Documentation , fact_bot :: a -- Lattice bottom element , fact_join :: JoinFun a -- Lattice join plus change flag -- (changes iff result > old fact) } -- ^ A transfer function might want to use the logging flag -- to control debugging, as in for example, it updates just one element -- in a big finite map. We don't want Hoopl to show the whole fact, -- and only the transfer function knows exactly what changed. type JoinFun a = Label -> OldFact a -> NewFact a -> (ChangeFlag, a) -- the label argument is for debugging purposes only newtype OldFact a = OldFact a newtype NewFact a = NewFact a data ChangeFlag = NoChange | SomeChange deriving (Eq, Ord) changeIf :: Bool -> ChangeFlag changeIf changed = if changed then SomeChange else NoChange -- | 'mkFactBase' creates a 'FactBase' from a list of ('Label', fact) -- pairs. If the same label appears more than once, the relevant facts -- are joined. mkFactBase :: forall f. DataflowLattice f -> [(Label, f)] -> FactBase f mkFactBase lattice = foldl add mapEmpty where add :: FactBase f -> (Label, f) -> FactBase f add map (lbl, f) = mapInsert lbl newFact map where newFact = case mapLookup lbl map of Nothing -> f Just f' -> snd $ join lbl (OldFact f') (NewFact f) join = fact_join lattice ----------------------------------------------------------------------------- -- Analyze and rewrite forward: the interface ----------------------------------------------------------------------------- data FwdPass m n f = FwdPass { fp_lattice :: DataflowLattice f , fp_transfer :: FwdTransfer n f , fp_rewrite :: FwdRewrite m n f } newtype FwdTransfer n f = FwdTransfer3 { getFTransfer3 :: ( n C O -> f -> f , n O O -> f -> f , n O C -> f -> FactBase f ) } newtype FwdRewrite m n f -- see Note [Respects Fuel] = FwdRewrite3 { getFRewrite3 :: ( n C O -> f -> m (Maybe (Graph n C O, FwdRewrite m n f)) , n O O -> f -> m (Maybe (Graph n O O, FwdRewrite m n f)) , n O C -> f -> m (Maybe (Graph n O C, FwdRewrite m n f)) ) } wrapFR :: (forall e x. (n e x -> f -> m (Maybe (Graph n e x, FwdRewrite m n f ))) -> (n' e x -> f' -> m' (Maybe (Graph n' e x, FwdRewrite m' n' f'))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> FwdRewrite m n f -> FwdRewrite m' n' f' -- see Note [Respects Fuel] wrapFR wrap (FwdRewrite3 (f, m, l)) = FwdRewrite3 (wrap f, wrap m, wrap l) wrapFR2 :: (forall e x . (n1 e x -> f1 -> m1 (Maybe (Graph n1 e x, FwdRewrite m1 n1 f1))) -> (n2 e x -> f2 -> m2 (Maybe (Graph n2 e x, FwdRewrite m2 n2 f2))) -> (n3 e x -> f3 -> m3 (Maybe (Graph n3 e x, FwdRewrite m3 n3 f3))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> FwdRewrite m1 n1 f1 -> FwdRewrite m2 n2 f2 -> FwdRewrite m3 n3 f3 -- see Note [Respects Fuel] wrapFR2 wrap2 (FwdRewrite3 (f1, m1, l1)) (FwdRewrite3 (f2, m2, l2)) = FwdRewrite3 (wrap2 f1 f2, wrap2 m1 m2, wrap2 l1 l2) mkFTransfer3 :: (n C O -> f -> f) -> (n O O -> f -> f) -> (n O C -> f -> FactBase f) -> FwdTransfer n f mkFTransfer3 f m l = FwdTransfer3 (f, m, l) mkFTransfer :: (forall e x . n e x -> f -> Fact x f) -> FwdTransfer n f mkFTransfer f = FwdTransfer3 (f, f, f) -- | Functions passed to 'mkFRewrite3' should not be aware of the fuel supply. -- The result returned by 'mkFRewrite3' respects fuel. mkFRewrite3 :: forall m n f. FuelMonad m => (n C O -> f -> m (Maybe (Graph n C O))) -> (n O O -> f -> m (Maybe (Graph n O O))) -> (n O C -> f -> m (Maybe (Graph n O C))) -> FwdRewrite m n f mkFRewrite3 f m l = FwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> m (Maybe a)) -> t -> t1 -> m (Maybe (a, FwdRewrite m n f)) lift rw node fact = liftM (liftM asRew) (withFuel =<< rw node fact) asRew :: forall t. t -> (t, FwdRewrite m n f) asRew g = (g, noFwdRewrite) noFwdRewrite :: Monad m => FwdRewrite m n f noFwdRewrite = FwdRewrite3 (noRewrite, noRewrite, noRewrite) noRewrite :: Monad m => a -> b -> m (Maybe c) noRewrite _ _ = return Nothing -- | Functions passed to 'mkFRewrite' should not be aware of the fuel supply. -- The result returned by 'mkFRewrite' respects fuel. mkFRewrite :: FuelMonad m => (forall e x . n e x -> f -> m (Maybe (Graph n e x))) -> FwdRewrite m n f mkFRewrite f = mkFRewrite3 f f f type family Fact x f :: * type instance Fact C f = FactBase f type instance Fact O f = f -- | if the graph being analyzed is open at the entry, there must -- be no other entry point, or all goes horribly wrong... analyzeAndRewriteFwd :: forall m n f e x entries. (CheckpointMonad m, NonLocal n, LabelsPtr entries) => FwdPass m n f -> MaybeC e entries -> Graph n e x -> Fact e f -> m (Graph n e x, FactBase f, MaybeO x f) analyzeAndRewriteFwd pass entries g f = do (rg, fout) <- arfGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedExitFact g' fout) distinguishedExitFact :: forall n e x f . Graph n e x -> Fact x f -> MaybeO x f distinguishedExitFact g f = maybe g where maybe :: Graph n e x -> MaybeO x f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany _ _ x) = case x of NothingO -> NothingO JustO _ -> JustO f ---------------------------------------------------------------- -- Forward Implementation ---------------------------------------------------------------- type Entries e = MaybeC e [Label] arfGraph :: forall m n f e x . (NonLocal n, CheckpointMonad m) => FwdPass m n f -> Entries e -> Graph n e x -> Fact e f -> m (DG f n e x, Fact x f) arfGraph pass entries = graph where {- nested type synonyms would be so lovely here type ARF thing = forall e x . thing e x -> f -> m (DG f n e x, Fact x f) type ARFX thing = forall e x . thing e x -> Fact e f -> m (DG f n e x, Fact x f) -} graph :: Graph n e x -> Fact e f -> m (DG f n e x, Fact x f) -- @ start block.tex -2 block :: forall e x . Block n e x -> f -> m (DG f n e x, Fact x f) -- @ end block.tex -- @ start node.tex -4 node :: forall e x . (ShapeLifter e x) => n e x -> f -> m (DG f n e x, Fact x f) -- @ end node.tex -- @ start bodyfun.tex body :: [Label] -> LabelMap (Block n C C) -> Fact C f -> m (DG f n C C, Fact C f) -- @ end bodyfun.tex -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' -- @ start cat.tex -2 cat :: forall e a x f1 f2 f3. (f1 -> m (DG f n e a, f2)) -> (f2 -> m (DG f n a x, f3)) -> (f1 -> m (DG f n e x, f3)) -- @ end cat.tex graph GNil = \f -> return (dgnil, f) graph (GUnit blk) = block blk graph (GMany e bdy x) = (e `ebcat` bdy) `cat` exit x where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact e f -> m (DG f n e C, Fact C f) exit :: MaybeO x (Block n C O) -> Fact C f -> m (DG f n C x, Fact x f) exit (JustO blk) = arfx block blk exit NothingO = \fb -> return (dgnilC, fb) ebcat entry bdy = c entries entry where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact e f -> m (DG f n e C, Fact C f) c NothingC (JustO entry) = block entry `cat` body (successors entry) bdy c (JustC entries) NothingO = body entries bdy c _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks -- @ start block.tex -2 block (BFirst n) = node n block (BMiddle n) = node n block (BLast n) = node n block (BCat b1 b2) = block b1 `cat` block b2 -- @ end block.tex block (BHead h n) = block h `cat` node n block (BTail n t) = node n `cat` block t block (BClosed h t)= block h `cat` block t -- @ start node.tex -4 node n f = do { grw <- frewrite pass n f ; case grw of Nothing -> return ( singletonDG f n , ftransfer pass n f ) Just (g, rw) -> let pass' = pass { fp_rewrite = rw } f' = fwdEntryFact n f in arfGraph pass' (fwdEntryLabel n) g f' } -- @ end node.tex -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} -- @ start cat.tex -2 cat ft1 ft2 f = do { (g1,f1) <- ft1 f ; (g2,f2) <- ft2 f1 ; return (g1 `dgSplice` g2, f2) } -- @ end cat.tex arfx :: forall thing x . NonLocal thing => (thing C x -> f -> m (DG f n C x, Fact x f)) -> (thing C x -> Fact C f -> m (DG f n C x, Fact x f)) arfx arf thing fb = arf thing $ fromJust $ lookupFact (entryLabel thing) $ joinInFacts lattice fb where lattice = fp_lattice pass -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' -- @ start bodyfun.tex body entries blockmap init_fbase = fixpoint Fwd lattice do_block blocks init_fbase where blocks = forwardBlockList entries blockmap lattice = fp_lattice pass do_block :: forall x. Block n C x -> FactBase f -> m (DG f n C x, Fact x f) do_block b fb = block b entryFact where entryFact = getFact lattice (entryLabel b) fb -- @ end bodyfun.tex -- Join all the incoming facts with bottom. -- We know the results _shouldn't change_, but the transfer -- functions might, for example, generate some debugging traces. joinInFacts :: DataflowLattice f -> FactBase f -> FactBase f joinInFacts (lattice @ DataflowLattice {fact_bot = bot, fact_join = fj}) fb = mkFactBase lattice $ map botJoin $ mapToList fb where botJoin (l, f) = (l, snd $ fj l (OldFact bot) (NewFact f)) forwardBlockList :: (NonLocal n, LabelsPtr entry) => entry -> Body n -> [Block n C C] -- This produces a list of blocks in order suitable for forward analysis, -- along with the list of Labels it may depend on for facts. forwardBlockList entries blks = postorder_dfs_from blks entries ----------------------------------------------------------------------------- -- Backward analysis and rewriting: the interface ----------------------------------------------------------------------------- data BwdPass m n f = BwdPass { bp_lattice :: DataflowLattice f , bp_transfer :: BwdTransfer n f , bp_rewrite :: BwdRewrite m n f } newtype BwdTransfer n f = BwdTransfer3 { getBTransfer3 :: ( n C O -> f -> f , n O O -> f -> f , n O C -> FactBase f -> f ) } newtype BwdRewrite m n f = BwdRewrite3 { getBRewrite3 :: ( n C O -> f -> m (Maybe (Graph n C O, BwdRewrite m n f)) , n O O -> f -> m (Maybe (Graph n O O, BwdRewrite m n f)) , n O C -> FactBase f -> m (Maybe (Graph n O C, BwdRewrite m n f)) ) } wrapBR :: (forall e x . Shape x -> (n e x -> Fact x f -> m (Maybe (Graph n e x, BwdRewrite m n f ))) -> (n' e x -> Fact x f' -> m' (Maybe (Graph n' e x, BwdRewrite m' n' f'))) ) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> BwdRewrite m n f -> BwdRewrite m' n' f' -- see Note [Respects Fuel] wrapBR wrap (BwdRewrite3 (f, m, l)) = BwdRewrite3 (wrap Open f, wrap Open m, wrap Closed l) wrapBR2 :: (forall e x . Shape x -> (n1 e x -> Fact x f1 -> m1 (Maybe (Graph n1 e x, BwdRewrite m1 n1 f1))) -> (n2 e x -> Fact x f2 -> m2 (Maybe (Graph n2 e x, BwdRewrite m2 n2 f2))) -> (n3 e x -> Fact x f3 -> m3 (Maybe (Graph n3 e x, BwdRewrite m3 n3 f3)))) -- ^ This argument may assume that any function passed to it -- respects fuel, and it must return a result that respects fuel. -> BwdRewrite m1 n1 f1 -> BwdRewrite m2 n2 f2 -> BwdRewrite m3 n3 f3 -- see Note [Respects Fuel] wrapBR2 wrap2 (BwdRewrite3 (f1, m1, l1)) (BwdRewrite3 (f2, m2, l2)) = BwdRewrite3 (wrap2 Open f1 f2, wrap2 Open m1 m2, wrap2 Closed l1 l2) mkBTransfer3 :: (n C O -> f -> f) -> (n O O -> f -> f) -> (n O C -> FactBase f -> f) -> BwdTransfer n f mkBTransfer3 f m l = BwdTransfer3 (f, m, l) mkBTransfer :: (forall e x . n e x -> Fact x f -> f) -> BwdTransfer n f mkBTransfer f = BwdTransfer3 (f, f, f) -- | Functions passed to 'mkBRewrite3' should not be aware of the fuel supply. -- The result returned by 'mkBRewrite3' respects fuel. mkBRewrite3 :: forall m n f. FuelMonad m => (n C O -> f -> m (Maybe (Graph n C O))) -> (n O O -> f -> m (Maybe (Graph n O O))) -> (n O C -> FactBase f -> m (Maybe (Graph n O C))) -> BwdRewrite m n f mkBRewrite3 f m l = BwdRewrite3 (lift f, lift m, lift l) where lift :: forall t t1 a. (t -> t1 -> m (Maybe a)) -> t -> t1 -> m (Maybe (a, BwdRewrite m n f)) lift rw node fact = liftM (liftM asRew) (withFuel =<< rw node fact) asRew :: t -> (t, BwdRewrite m n f) asRew g = (g, noBwdRewrite) noBwdRewrite :: Monad m => BwdRewrite m n f noBwdRewrite = BwdRewrite3 (noRewrite, noRewrite, noRewrite) -- | Functions passed to 'mkBRewrite' should not be aware of the fuel supply. -- The result returned by 'mkBRewrite' respects fuel. mkBRewrite :: FuelMonad m => (forall e x . n e x -> Fact x f -> m (Maybe (Graph n e x))) -> BwdRewrite m n f mkBRewrite f = mkBRewrite3 f f f ----------------------------------------------------------------------------- -- Backward implementation ----------------------------------------------------------------------------- arbGraph :: forall m n f e x . (NonLocal n, CheckpointMonad m) => BwdPass m n f -> Entries e -> Graph n e x -> Fact x f -> m (DG f n e x, Fact e f) arbGraph pass entries = graph where {- nested type synonyms would be so lovely here type ARB thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, f) type ARBX thing = forall e x . thing e x -> Fact x f -> m (DG f n e x, Fact e f) -} graph :: Graph n e x -> Fact x f -> m (DG f n e x, Fact e f) block :: forall e x . Block n e x -> Fact x f -> m (DG f n e x, f) node :: forall e x . (ShapeLifter e x) => n e x -> Fact x f -> m (DG f n e x, f) body :: [Label] -> Body n -> Fact C f -> m (DG f n C C, Fact C f) cat :: forall e a x info info' info''. (info' -> m (DG f n e a, info'')) -> (info -> m (DG f n a x, info')) -> (info -> m (DG f n e x, info'')) graph GNil = \f -> return (dgnil, f) graph (GUnit blk) = block blk graph (GMany e bdy x) = (e `ebcat` bdy) `cat` exit x where ebcat :: MaybeO e (Block n O C) -> Body n -> Fact C f -> m (DG f n e C, Fact e f) exit :: MaybeO x (Block n C O) -> Fact x f -> m (DG f n C x, Fact C f) exit (JustO blk) = arbx block blk exit NothingO = \fb -> return (dgnilC, fb) ebcat entry bdy = c entries entry where c :: MaybeC e [Label] -> MaybeO e (Block n O C) -> Fact C f -> m (DG f n e C, Fact e f) c NothingC (JustO entry) = block entry `cat` body (successors entry) bdy c (JustC entries) NothingO = body entries bdy c _ _ = error "bogus GADT pattern match failure" -- Lift from nodes to blocks block (BFirst n) = node n block (BMiddle n) = node n block (BLast n) = node n block (BCat b1 b2) = block b1 `cat` block b2 block (BHead h n) = block h `cat` node n block (BTail n t) = node n `cat` block t block (BClosed h t)= block h `cat` block t node n f = do { bwdres <- brewrite pass n f ; case bwdres of Nothing -> return (singletonDG entry_f n, entry_f) where entry_f = btransfer pass n f Just (g, rw) -> do { let pass' = pass { bp_rewrite = rw } ; (g, f) <- arbGraph pass' (fwdEntryLabel n) g f ; return (g, bwdEntryFact (bp_lattice pass) n f)} } -- | Compose fact transformers and concatenate the resulting -- rewritten graphs. {-# INLINE cat #-} cat ft1 ft2 f = do { (g2,f2) <- ft2 f ; (g1,f1) <- ft1 f2 ; return (g1 `dgSplice` g2, f1) } arbx :: forall thing x . NonLocal thing => (thing C x -> Fact x f -> m (DG f n C x, f)) -> (thing C x -> Fact x f -> m (DG f n C x, Fact C f)) arbx arb thing f = do { (rg, f) <- arb thing f ; let fb = joinInFacts (bp_lattice pass) $ mapSingleton (entryLabel thing) f ; return (rg, fb) } -- joinInFacts adds debugging information -- Outgoing factbase is restricted to Labels *not* in -- in the Body; the facts for Labels *in* -- the Body are in the 'DG f n C C' body entries blockmap init_fbase = fixpoint Bwd (bp_lattice pass) do_block blocks init_fbase where blocks = backwardBlockList entries blockmap do_block :: forall x. Block n C x -> Fact x f -> m (DG f n C x, LabelMap f) do_block b f = do (g, f) <- block b f return (g, mapSingleton (entryLabel b) f) backwardBlockList :: (LabelsPtr entries, NonLocal n) => entries -> Body n -> [Block n C C] -- This produces a list of blocks in order suitable for backward analysis, -- along with the list of Labels it may depend on for facts. backwardBlockList entries body = reverse $ forwardBlockList entries body {- The forward and backward cases are not dual. In the forward case, the entry points are known, and one simply traverses the body blocks from those points. In the backward case, something is known about the exit points, but this information is essentially useless, because we don't actually have a dual graph (that is, one with edges reversed) to compute with. (Even if we did have a dual graph, it would not avail us---a backward analysis must include reachable blocks that don't reach the exit, as in a procedure that loops forever and has side effects.) -} -- | if the graph being analyzed is open at the exit, I don't -- quite understand the implications of possible other exits analyzeAndRewriteBwd :: (CheckpointMonad m, NonLocal n, LabelsPtr entries) => BwdPass m n f -> MaybeC e entries -> Graph n e x -> Fact x f -> m (Graph n e x, FactBase f, MaybeO e f) analyzeAndRewriteBwd pass entries g f = do (rg, fout) <- arbGraph pass (fmap targetLabels entries) g f let (g', fb) = normalizeGraph rg return (g', fb, distinguishedEntryFact g' fout) distinguishedEntryFact :: forall n e x f . Graph n e x -> Fact e f -> MaybeO e f distinguishedEntryFact g f = maybe g where maybe :: Graph n e x -> MaybeO e f maybe GNil = JustO f maybe (GUnit {}) = JustO f maybe (GMany e _ _) = case e of NothingO -> NothingO JustO _ -> JustO f ----------------------------------------------------------------------------- -- fixpoint: finding fixed points ----------------------------------------------------------------------------- -- @ start txfb.tex data TxFactBase n f = TxFB { tfb_fbase :: FactBase (ChangeFlag, f) -- We could technically use DG f n C C to handle this, but -- using a LabelMap makes it a bit clearer. , tfb_rg :: LabelMap (DG f n C C) , tfb_cha :: ChangeFlag , tfb_lbls :: LabelSet } -- @ end txfb.tex -- See Note [TxFactBase invariants] -- @ start update.tex -- Fold function, which folds over new facts and integrates them with an -- existing FactBase, keeping track of whether or not another sweep is -- necessary. updateFact :: DataflowLattice f -> LabelSet -- labels that have already been processed -> Label -- label fact is associated with -> f -- new fact to merge in -- fst is global change flag -> (ChangeFlag, FactBase (ChangeFlag, f)) -> (ChangeFlag, FactBase (ChangeFlag, f)) -- See Note [TxFactBase change flag] updateFact lat lbls lbl new_fact (cha, fbase) -- No change to fact | NoChange <- local_change = (cha, fbase) -- Change to fact, and it's for a block we've already processed. | lbl `setMember` lbls = (SomeChange, new_fbase) -- Change to fact, but it's for a block pending processing. | otherwise = (cha, new_fbase) where (init_change, old_fact) = fromMaybe (SomeChange, fact_bot lat) (lookupFact lbl fbase) (join_change, res_fact) = fact_join lat lbl (OldFact old_fact) (NewFact new_fact) -- If we've never seen this block before, it needs to be processed. -- Otherwise, it only needs to be reprocessed if its fact changed. local_change | SomeChange <- init_change = SomeChange | otherwise = join_change new_fbase = mapInsert lbl (local_change, res_fact) fbase -- @ end update.tex {- -- this doesn't work because it can't be implemented class Monad m => FixpointMonad m where observeChangedFactBase :: m (Maybe (FactBase f)) -> Maybe (FactBase f) -} -- @ start fptype.tex data Direction = Fwd | Bwd fixpoint :: forall m n f. (CheckpointMonad m, NonLocal n) => Direction -> DataflowLattice f -> (Block n C C -> Fact C f -> m (DG f n C C, Fact C f)) -> [Block n C C] -- topologically sorted list of blocks to process -> (Fact C f -> m (DG f n C C, Fact C f)) -- @ end fptype.tex -- @ start fpimp.tex fixpoint direction lat do_block blocks init_fbase = do { -- Always begin by sweeping all blocks let init_fbase_with_flags = mapMap (\x -> (SomeChange, x)) init_fbase ; tx_fb <- loop init_fbase_with_flags mapEmpty ; return (mapFold dgSplice dgnilC (tfb_rg tx_fb), map (fst . fst) tagged_blocks `mapDeleteList` mapMap snd (tfb_fbase tx_fb) ) } -- The successors of the Graph are the the Labels -- for which we have facts and which are *not* in -- the blocks of the graph where tagged_blocks = map tag blocks is_fwd = case direction of { Fwd -> True; Bwd -> False } tag :: NonLocal t => t C C -> ((Label, t C C), [Label]) tag b = ((entryLabel b, b), if is_fwd then [entryLabel b] else successors b) -- 'tag' adds the in-labels of the block; -- see Note [TxFactBase invariants] -- A list of tagged blocks: -- [(block label, block), [entry or successor block labels]] tx_blocks :: [((Label, Block n C C), [Label])] -> TxFactBase n f -> m (TxFactBase n f) tx_blocks [] tx_fb = return tx_fb tx_blocks (((lbl,blk), in_lbls):bs) tx_fb = tx_block lbl blk in_lbls tx_fb >>= tx_blocks bs -- "in_lbls" == Labels the block may -- _depend_ upon for facts tx_block :: Label -> Block n C C -> [Label] -> TxFactBase n f -> m (TxFactBase n f) tx_block lbl blk in_lbls tx_fb@(TxFB { tfb_fbase = fbase, tfb_lbls = lbls , tfb_rg = blkMap , tfb_cha = cha }) | is_fwd && not (lbl `mapMember` fbase) = return (tx_fb {tfb_lbls = lbls'}) -- Note [Unreachable blocks] -- Don't bother processing a node if nothing affecting -- it has changed. | Just (NoChange, _) <- lookupFact lbl fbase = {-# SCC "fixpoint-shortcut" #-} return (tx_fb {tfb_lbls = lbls'}) | otherwise = {-# SCC "fixpoint-tx_block" #-} do { (rg, out_facts) <- do_block blk (mapMap snd fbase) -- XXX ugh, allocation -- Update rg for current node ; let blkMap' = mapInsert lbl rg blkMap -- Update fbase for current node ; let fbase' = case mapLookup lbl fbase of Nothing -> fbase Just (_, f) -> mapInsert lbl (NoChange, f) fbase -- Merge out_facts with fbase, and determine if -- another sweep is required. ; let (cha', fbase'') = mapFoldWithKey (updateFact lat lbls') -- combining function (cha, fbase') -- fold base out_facts -- map to fold over ; return $ TxFB { tfb_lbls = lbls' , tfb_fbase = fbase'' , tfb_rg = blkMap' , tfb_cha = cha' } } where lbls' = lbls `setUnion` setFromList in_lbls loop :: FactBase (ChangeFlag, f) -> LabelMap (DG f n C C) -> m (TxFactBase n f) loop fbase rgbase = {-# SCC "fixpoint-loop" #-} do { s <- checkpoint ; let init_tx :: TxFactBase n f init_tx = TxFB { tfb_fbase = fbase , tfb_cha = NoChange , tfb_rg = rgbase , tfb_lbls = setEmpty } ; tx_fb <- tx_blocks tagged_blocks init_tx ; case tfb_cha tx_fb of NoChange -> return tx_fb SomeChange -> do { restart s ; loop (tfb_fbase tx_fb) (tfb_rg tx_fb) } } -- @ end fpimp.tex {- Note [TxFactBase invariants] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The TxFactBase is used only during a fixpoint iteration (or "sweep"), and accumulates facts (and the transformed code) during the fixpoint iteration. * tfb_fbase increases monotonically, across all sweeps * At the beginning of each sweep tfb_cha = NoChange tfb_lbls = {} * During each sweep we process each block in turn. Processing a block is done thus: 1. Read from tfb_fbase the facts for its entry label (forward) or successors labels (backward) 2. Transform those facts into new facts for its successors (forward) or entry label (backward) 3. Augment tfb_fbase with that info We call the labels read in step (1) the "in-labels" of the sweep * The field tfb_lbls is the set of in-labels of all blocks that have been processed so far this sweep, including the block that is currently being processed. tfb_lbls is initialised to {}. It is a subset of the Labels of the *original* (not transformed) blocks. * The tfb_cha field is set to SomeChange iff we decide we need to perform another iteration of the fixpoint loop. It is initialsed to NoChange. Specifically, we set tfb_cha to SomeChange in step (3) iff (a) The fact in tfb_fbase for a block L changes (b) L is in tfb_lbls Reason: until a label enters the in-labels its accumuated fact in tfb_fbase has not been read, hence cannot affect the outcome Note [Unreachable blocks] ~~~~~~~~~~~~~~~~~~~~~~~~~ A block that is not in the domain of tfb_fbase is "currently unreachable". A currently-unreachable block is not even analyzed. Reason: consider constant prop and this graph, with entry point L1: L1: x:=3; goto L4 L2: x:=4; goto L4 L4: if x>3 goto L2 else goto L5 Here L2 is actually unreachable, but if we process it with bottom input fact, we'll propagate (x=4) to L4, and nuke the otherwise-good rewriting of L4. * If a currently-unreachable block is not analyzed, then its rewritten graph will not be accumulated in tfb_rg. And that is good: unreachable blocks simply do not appear in the output. * Note that clients must be careful to provide a fact (even if bottom) for each entry point. Otherwise useful blocks may be garbage collected. * Note that updateFact must set the change-flag if a label goes from not-in-fbase to in-fbase, even if its fact is bottom. In effect the real fact lattice is UNR bottom the points above bottom * Even if the fact is going from UNR to bottom, we still call the client's fact_join function because it might give the client some useful debugging information. * All of this only applies for *forward* fixpoints. For the backward case we must treat every block as reachable; it might finish with a 'return', and therefore have no successors, for example. -} ----------------------------------------------------------------------------- -- DG: an internal data type for 'decorated graphs' -- TOTALLY internal to Hoopl; each block is decorated with a fact ----------------------------------------------------------------------------- -- @ start dg.tex type Graph = Graph' Block type DG f = Graph' (DBlock f) data DBlock f n e x = DBlock f (Block n e x) -- ^ block decorated with fact -- @ end dg.tex instance NonLocal n => NonLocal (DBlock f n) where entryLabel (DBlock _ b) = entryLabel b successors (DBlock _ b) = successors b --- constructors dgnil :: DG f n O O dgnilC :: DG f n C C dgSplice :: NonLocal n => DG f n e a -> DG f n a x -> DG f n e x ---- observers type GraphWithFacts n f e x = (Graph n e x, FactBase f) -- A Graph together with the facts for that graph -- The domains of the two maps should be identical normalizeGraph :: forall n f e x . NonLocal n => DG f n e x -> GraphWithFacts n f e x normalizeGraph g = (graphMapBlocks dropFact g, facts g) where dropFact :: DBlock t t1 t2 t3 -> Block t1 t2 t3 dropFact (DBlock _ b) = b facts :: DG f n e x -> FactBase f facts GNil = noFacts facts (GUnit _) = noFacts facts (GMany _ body exit) = bodyFacts body `mapUnion` exitFacts exit exitFacts :: MaybeO x (DBlock f n C O) -> FactBase f exitFacts NothingO = noFacts exitFacts (JustO (DBlock f b)) = mapSingleton (entryLabel b) f bodyFacts :: LabelMap (DBlock f n C C) -> FactBase f bodyFacts body = mapFold f noFacts body where f :: forall t a x. (NonLocal t) => DBlock a t C x -> LabelMap a -> LabelMap a f (DBlock f b) fb = mapInsert (entryLabel b) f fb --- implementation of the constructors (boring) dgnil = GNil dgnilC = GMany NothingO emptyBody NothingO dgSplice = U.splice fzCat where fzCat :: DBlock f n e O -> DBlock t n O x -> DBlock f n e x fzCat (DBlock f b1) (DBlock _ b2) = DBlock f (b1 `U.cat` b2) ---------------------------------------------------------------- -- Utilities ---------------------------------------------------------------- -- Lifting based on shape: -- - from nodes to blocks -- - from facts to fact-like things -- Lowering back: -- - from fact-like things to facts -- Note that the latter two functions depend only on the entry shape. -- @ start node.tex class ShapeLifter e x where singletonDG :: f -> n e x -> DG f n e x fwdEntryFact :: NonLocal n => n e x -> f -> Fact e f fwdEntryLabel :: NonLocal n => n e x -> MaybeC e [Label] ftransfer :: FwdPass m n f -> n e x -> f -> Fact x f frewrite :: FwdPass m n f -> n e x -> f -> m (Maybe (Graph n e x, FwdRewrite m n f)) -- @ end node.tex bwdEntryFact :: NonLocal n => DataflowLattice f -> n e x -> Fact e f -> f btransfer :: BwdPass m n f -> n e x -> Fact x f -> f brewrite :: BwdPass m n f -> n e x -> Fact x f -> m (Maybe (Graph n e x, BwdRewrite m n f)) instance ShapeLifter C O where singletonDG f = gUnitCO . DBlock f . BFirst fwdEntryFact n f = mapSingleton (entryLabel n) f bwdEntryFact lat n fb = getFact lat (entryLabel n) fb ftransfer (FwdPass {fp_transfer = FwdTransfer3 (ft, _, _)}) n f = ft n f btransfer (BwdPass {bp_transfer = BwdTransfer3 (bt, _, _)}) n f = bt n f frewrite (FwdPass {fp_rewrite = FwdRewrite3 (fr, _, _)}) n f = fr n f brewrite (BwdPass {bp_rewrite = BwdRewrite3 (br, _, _)}) n f = br n f fwdEntryLabel n = JustC [entryLabel n] instance ShapeLifter O O where singletonDG f = gUnitOO . DBlock f . BMiddle fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdPass {fp_transfer = FwdTransfer3 (_, ft, _)}) n f = ft n f btransfer (BwdPass {bp_transfer = BwdTransfer3 (_, bt, _)}) n f = bt n f frewrite (FwdPass {fp_rewrite = FwdRewrite3 (_, fr, _)}) n f = fr n f brewrite (BwdPass {bp_rewrite = BwdRewrite3 (_, br, _)}) n f = br n f fwdEntryLabel _ = NothingC instance ShapeLifter O C where singletonDG f = gUnitOC . DBlock f . BLast fwdEntryFact _ f = f bwdEntryFact _ _ f = f ftransfer (FwdPass {fp_transfer = FwdTransfer3 (_, _, ft)}) n f = ft n f btransfer (BwdPass {bp_transfer = BwdTransfer3 (_, _, bt)}) n f = bt n f frewrite (FwdPass {fp_rewrite = FwdRewrite3 (_, _, fr)}) n f = fr n f brewrite (BwdPass {bp_rewrite = BwdRewrite3 (_, _, br)}) n f = br n f fwdEntryLabel _ = NothingC -- Fact lookup: the fact `orelse` bottom getFact :: DataflowLattice f -> Label -> FactBase f -> f getFact lat l fb = case lookupFact l fb of Just f -> f Nothing -> fact_bot lat {- Note [Respects fuel] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -} -- $fuel -- A value of type 'FwdRewrite' or 'BwdRewrite' /respects fuel/ if -- any function contained within the value satisfies the following properties: -- -- * When fuel is exhausted, it always returns 'Nothing'. -- -- * When it returns @Just g rw@, it consumes /exactly/ one unit -- of fuel, and new rewrite 'rw' also respects fuel. -- -- Provided that functions passed to 'mkFRewrite', 'mkFRewrite3', -- 'mkBRewrite', and 'mkBRewrite3' are not aware of the fuel supply, -- the results respect fuel. -- -- It is an /unchecked/ run-time error for the argument passed to 'wrapFR', -- 'wrapFR2', 'wrapBR', or 'warpBR2' to return a function that does not respect fuel.
ezyang/hoopl
src/Compiler/Hoopl/Dataflow.hs
bsd-3-clause
36,430
137
35
11,096
10,193
5,347
4,846
471
13
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE OverloadedStrings #-} module Duckling.Distance.FR.Corpus ( corpus ) where import Prelude import Data.String import Duckling.Distance.Types import Duckling.Locale import Duckling.Resolve import Duckling.Testing.Types corpus :: Corpus corpus = (testContext {locale = makeLocale FR Nothing}, testOptions, allExamples) allExamples :: [Example] allExamples = concat [ examples (simple Kilometre 3) [ "3 kilomètres" , "3 kilometres" , "3 km" , "3km" , "3k" ] , examples (simple Kilometre 3.0) [ "3,0 km" ] , examples (simple Mile 8) [ "8 miles" ] , examples (simple Metre 9) [ "9 metres" , "9m" ] , examples (simple Centimetre 2) [ "2cm" , "2 centimetres" ] ]
facebookincubator/duckling
Duckling/Distance/FR/Corpus.hs
bsd-3-clause
1,102
0
9
365
210
124
86
29
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NoRebindableSyntax #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} module Duckling.Volume.Types where import Control.DeepSeq import Data.Aeson import Data.Hashable import Data.Text (Text) import qualified Data.Text as Text import GHC.Generics import Prelude import Duckling.Resolve (Resolve (..)) data Unit = Gallon | Hectolitre | Litre | Millilitre deriving (Eq, Generic, Hashable, Ord, Show, NFData) instance ToJSON Unit where toJSON = String . Text.toLower . Text.pack . show data VolumeData = VolumeData { unit :: Maybe Unit , value :: Double } deriving (Eq, Generic, Hashable, Ord, Show, NFData) instance Resolve VolumeData where type ResolvedValue VolumeData = VolumeValue resolve _ VolumeData {unit = Nothing} = Nothing resolve _ VolumeData {unit = Just unit, value} = Just VolumeValue {vValue = value, vUnit = unit} data VolumeValue = VolumeValue { vUnit :: Unit , vValue :: Double } deriving (Eq, Ord, Show) instance ToJSON VolumeValue where toJSON (VolumeValue unit value) = object [ "type" .= ("value" :: Text) , "value" .= value , "unit" .= unit ]
rfranek/duckling
Duckling/Volume/Types.hs
bsd-3-clause
1,557
0
10
296
365
211
154
41
0
module Lib ( paletteThem ) where import Codec.Picture import System.Directory import Control.Monad import Data.List import qualified Data.ByteString.Lazy as B import System.Info dirSep :: String dirSep = if os == "linux" then "/" else "\\" isImage :: FilePath -> Bool isImage p = any (`isSuffixOf` p) formats where formats = [".jpg", ".jpeg", ".png", ".gif"] paletteThem :: FilePath -> FilePath -> IO () paletteThem paletteFile imgDir = do dynimg <- readImage paletteFile let palette = fmap convertRGB8 dynimg files <- getDirectoryContents imgDir let imgs = filter isImage files either putStrLn (\x -> mapM_ (paletteIt imgDir x) imgs) palette mkPalOpt :: Palette -> PaletteOptions mkPalOpt p = PaletteOptions { paletteCreationMethod = MedianMeanCut, enableImageDithering = True, paletteColorCount = imageWidth p } reorderPalette :: Palette -> Palette -> Palette reorderPalette p p' = let pl = [pixelAt p x 0 | x <- [0.. imageWidth p - 1]] pl' = [pixelAt p' x 0 | x <- [0.. imageWidth p - 1]] perm = bestPerm pl' pl in generateImage (\x _ -> perm !! x) (imageWidth p) (imageHeight p) bestPerm :: [PixelRGB8] -> [PixelRGB8] -> [PixelRGB8] bestPerm _ [] = [] bestPerm [] _ = [] bestPerm (x:xs) l = let best = minimumBy (comparePerm x) l comparePerm x p1 p2 = compare (distance x p1) (distance x p2) l' = filter (/= best) l in best : bestPerm xs l distance :: PixelRGB8 -> PixelRGB8 -> Int distance (PixelRGB8 r1 g1 b1) (PixelRGB8 r2 g2 b2) = abs $ (fromIntegral r2 - fromIntegral r1) * (fromIntegral g2 - fromIntegral g1) * (fromIntegral b2 - fromIntegral b1) paletteIt :: FilePath -> Palette -> FilePath -> IO () paletteIt dir pal file = do dynimg <- readImage $ dir ++ dirSep ++ file putStrLn $ "treating : " ++ file createDirectoryIfMissing True (dir ++ dirSep ++ "res") let img = paletteItAnnexe pal =<< dynimg either putStrLn (writePng (dir ++ dirSep ++ "res" ++ dirSep ++ file ++ ".png")) img putStrLn "done" paletteItAnnexe :: Palette -> DynamicImage -> Either String (Image PixelRGBA8) paletteItAnnexe p img = let img' = convertRGBA8 img appendAlpha a = generateImage (\x y -> let (PixelRGB8 r g b) = pixelAt a x y (PixelRGBA8 _ _ _ alp) = pixelAt img' x y in PixelRGBA8 r g b alp) (imageWidth a) (imageHeight a) palOpt = mkPalOpt p (pImg, p2) = palettize palOpt (pixelMap (\(PixelRGBA8 r g b _ ) -> PixelRGB8 r g b) img') p3 = reorderPalette p p2 in do gifByte <- encodeGifImageWithPalette pImg p3 gif <- decodeImage $ B.toStrict gifByte let rgb = convertRGB8 gif return $ appendAlpha rgb
CharlesHD/Palettize
src/Lib.hs
bsd-3-clause
3,099
0
17
1,034
1,052
529
523
61
2
{-# LANGUAGE DeriveFunctor, DeriveFoldable, DeriveTraversable #-} module Distribution.Solver.Modular.Tree ( FailReason(..) , POption(..) , Tree(..) , TreeF(..) , Weight , ana , cata , dchoices , inn , innM , para , trav , zeroOrOneChoices ) where import Control.Monad hiding (mapM, sequence) import Data.Foldable import Data.Traversable import Prelude hiding (foldr, mapM, sequence) import Distribution.Solver.Modular.Degree import Distribution.Solver.Modular.Dependency import Distribution.Solver.Modular.Flag import Distribution.Solver.Modular.Package import Distribution.Solver.Modular.PSQ (PSQ) import Distribution.Solver.Modular.Version import Distribution.Solver.Modular.WeightedPSQ (WeightedPSQ) import qualified Distribution.Solver.Modular.WeightedPSQ as W import Distribution.Solver.Types.ConstraintSource import Distribution.Solver.Types.PackagePath type Weight = Double -- | Type of the search tree. Inlining the choice nodes for now. Weights on -- package, flag, and stanza choices control the traversal order. -- TODO: The weight type should be changed from [Double] to Double to avoid -- giving too much weight to preferences that are applied later. data Tree a = -- | Choose a version for a package (or choose to link) PChoice QPN a (WeightedPSQ [Weight] POption (Tree a)) -- | Choose a value for a flag -- -- The Bool indicates whether it's manual. | FChoice QFN a WeakOrTrivial Bool (WeightedPSQ [Weight] Bool (Tree a)) -- | Choose whether or not to enable a stanza | SChoice QSN a WeakOrTrivial (WeightedPSQ [Weight] Bool (Tree a)) -- | Choose which choice to make next -- -- Invariants: -- -- * PSQ should never be empty -- * For each choice we additionally record the 'QGoalReason' why we are -- introducing that goal into tree. Note that most of the time we are -- working with @Tree QGoalReason@; in that case, we must have the -- invariant that the 'QGoalReason' cached in the 'PChoice', 'FChoice' -- or 'SChoice' directly below a 'GoalChoice' node must equal the reason -- recorded on that 'GoalChoice' node. | GoalChoice (PSQ (Goal QPN) (Tree a)) -- | We're done -- we found a solution! | Done RevDepMap -- | We failed to find a solution in this path through the tree | Fail (ConflictSet QPN) FailReason deriving (Eq, Show, Functor) -- | A package option is a package instance with an optional linking annotation -- -- The modular solver has a number of package goals to solve for, and can only -- pick a single package version for a single goal. In order to allow to -- install multiple versions of the same package as part of a single solution -- the solver uses qualified goals. For example, @0.P@ and @1.P@ might both -- be qualified goals for @P@, allowing to pick a difference version of package -- @P@ for @0.P@ and @1.P@. -- -- Linking is an essential part of this story. In addition to picking a specific -- version for @1.P@, the solver can also decide to link @1.P@ to @0.P@ (or -- vice versa). It means that @1.P@ and @0.P@ really must be the very same package -- (and hence must have the same build time configuration, and their -- dependencies must also be the exact same). -- -- See <http://www.well-typed.com/blog/2015/03/qualified-goals/> for details. data POption = POption I (Maybe PackagePath) deriving (Eq, Show) data FailReason = InconsistentInitialConstraints | Conflicting [Dep QPN] | CannotInstall | CannotReinstall | Shadowed | Broken | GlobalConstraintVersion VR ConstraintSource | GlobalConstraintInstalled ConstraintSource | GlobalConstraintSource ConstraintSource | GlobalConstraintFlag ConstraintSource | ManualFlag | MalformedFlagChoice QFN | MalformedStanzaChoice QSN | EmptyGoalChoice | Backjump | MultipleInstances | DependenciesNotLinked String | CyclicDependencies deriving (Eq, Show) -- | Functor for the tree type. data TreeF a b = PChoiceF QPN a (WeightedPSQ [Weight] POption b) | FChoiceF QFN a WeakOrTrivial Bool (WeightedPSQ [Weight] Bool b) | SChoiceF QSN a WeakOrTrivial (WeightedPSQ [Weight] Bool b) | GoalChoiceF (PSQ (Goal QPN) b) | DoneF RevDepMap | FailF (ConflictSet QPN) FailReason deriving (Functor, Foldable, Traversable) out :: Tree a -> TreeF a (Tree a) out (PChoice p i ts) = PChoiceF p i ts out (FChoice p i b m ts) = FChoiceF p i b m ts out (SChoice p i b ts) = SChoiceF p i b ts out (GoalChoice ts) = GoalChoiceF ts out (Done x ) = DoneF x out (Fail c x ) = FailF c x inn :: TreeF a (Tree a) -> Tree a inn (PChoiceF p i ts) = PChoice p i ts inn (FChoiceF p i b m ts) = FChoice p i b m ts inn (SChoiceF p i b ts) = SChoice p i b ts inn (GoalChoiceF ts) = GoalChoice ts inn (DoneF x ) = Done x inn (FailF c x ) = Fail c x innM :: Monad m => TreeF a (m (Tree a)) -> m (Tree a) innM (PChoiceF p i ts) = liftM (PChoice p i ) (sequence ts) innM (FChoiceF p i b m ts) = liftM (FChoice p i b m) (sequence ts) innM (SChoiceF p i b ts) = liftM (SChoice p i b ) (sequence ts) innM (GoalChoiceF ts) = liftM (GoalChoice ) (sequence ts) innM (DoneF x ) = return $ Done x innM (FailF c x ) = return $ Fail c x -- | Determines whether a tree is active, i.e., isn't a failure node. active :: Tree a -> Bool active (Fail _ _) = False active _ = True -- | Approximates the number of active choices that are available in a node. -- Note that we count goal choices as having one choice, always. dchoices :: Tree a -> Degree dchoices (PChoice _ _ ts) = W.degree (W.filter active ts) dchoices (FChoice _ _ _ _ ts) = W.degree (W.filter active ts) dchoices (SChoice _ _ _ ts) = W.degree (W.filter active ts) dchoices (GoalChoice _ ) = ZeroOrOne dchoices (Done _ ) = ZeroOrOne dchoices (Fail _ _ ) = ZeroOrOne -- | Variant of 'dchoices' that traverses fewer children. zeroOrOneChoices :: Tree a -> Bool zeroOrOneChoices (PChoice _ _ ts) = W.isZeroOrOne (W.filter active ts) zeroOrOneChoices (FChoice _ _ _ _ ts) = W.isZeroOrOne (W.filter active ts) zeroOrOneChoices (SChoice _ _ _ ts) = W.isZeroOrOne (W.filter active ts) zeroOrOneChoices (GoalChoice _ ) = True zeroOrOneChoices (Done _ ) = True zeroOrOneChoices (Fail _ _ ) = True -- | Catamorphism on trees. cata :: (TreeF a b -> b) -> Tree a -> b cata phi x = (phi . fmap (cata phi) . out) x trav :: (TreeF a (Tree b) -> TreeF b (Tree b)) -> Tree a -> Tree b trav psi x = cata (inn . psi) x -- | Paramorphism on trees. para :: (TreeF a (b, Tree a) -> b) -> Tree a -> b para phi = phi . fmap (\ x -> (para phi x, x)) . out -- | Anamorphism on trees. ana :: (b -> TreeF a b) -> b -> Tree a ana psi = inn . fmap (ana psi) . psi
sopvop/cabal
cabal-install/Distribution/Solver/Modular/Tree.hs
bsd-3-clause
7,333
0
11
2,025
1,830
983
847
113
1
{-# LANGUAGE RecordWildCards #-} module Main where import Control.Monad import Pipes import Pipes.Serial import Data.Serialize import qualified Data.ByteString.Char8 as B import qualified HXStream.Native as HX import qualified Pipes.Prelude as P import LDrive.Types.Adc import LDrive.Types.Encoder import LDrive.Types.Svm import LDrive.Types.CurrentControl import LDrive.Client.Pipes -- lp import MVC import qualified MVC.Prelude as MVC import Graphics.Liveplot msgDes :: Serialize a => B.ByteString -> IO (Maybe a) msgDes msg = do case runGetState get msg 0 of Left e -> putStrLn ("deserialize error: " ++ e) >> return (Nothing) Right (r, _) -> do return (Just r) des :: Proxy () (HX.Tag, B.ByteString) () (SensorReading GLfloat) IO b des = forever $ do (tag, msg) <- await case tag of 69 -> do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> mapM_ yield $ fromEncoder x 65 -> do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> mapM_ yield $ fromAdc x 83 -> do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> mapM_ yield $ fromSVM x 67 -> do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> do liftIO $ print x mapM_ yield $ fromCC x _ -> return () des' :: (Eq a, Serialize t1, Foldable t, Foldable t2) => t2 (a, t1 -> t y) -> Proxy () (a, B.ByteString) () y IO b des' mappings = forever $ do (tag, msg) <- await mapM_ (handle tag msg) mappings where handle tag msg (tag', handler) | tag == tag' = do me <- lift $ msgDes msg case me of Nothing -> return () Just x -> mapM_ yield (handler x) handle _ _ _ = return () --data HXDes a = HXDes a Int --des'' = des' [(69, fromEncoder), (65, fromAdc)] --des'' = des' [ -- (69, toReading :: Encoder -> [SensorReading GLfloat]) -- (65, toReading :: Adc -> [SensorReading GLfloat]) -- ] scaleRange :: Fractional a => (a, a) -> (a, a) -> a -> a scaleRange (fromLow, fromHigh) (toLow, toHigh) x = (x - fromLow) * (toHigh - toLow) / (fromHigh - fromLow) + toLow normRange :: Fractional a => (a, a) -> a -> a normRange from = scaleRange from (-1, 1) graphRange :: Fractional a => (a, a) -> a -> a graphRange from = scaleRange from (0, 1) -- utility pipes for liveplot normalize :: (Fractional b, Monad m) => (b, b) -> Pipe b b m r normalize from = P.map (graphRange from) dbg :: (Show a) => Pipe a a IO () dbg = P.tee (P.map (show) >-> P.stdoutLn) main :: IO () main = do let port = "/dev/ttyUSB0" s <- openSerial port defaultSerialSettings { commSpeed = CS115200 } runLiveplot $ myplot (hxserial s >-> des >-> dbg) myplot :: Producer a IO () -> Managed (View (Either (SensorReading GLfloat) GLApp), Controller (Either a Event)) myplot pipe = do let sc = (9, 2) inits = [ lineGraph "pll_pos" sc (0, 0) , lineGraph "pll_vel" sc (1, 0) , lineGraph "phase" sc (2, 0) , lineGraph "vbus" sc (3, 0) , lineGraph "phase_b" sc (4, 0) , lineGraph "phase_c" sc (5, 0) , lineGraph "svm_a" sc (6, 0) , lineGraph "svm_b" sc (7, 0) , lineGraph "svm_c" sc (8, 0) , lineGraph "alpha" sc (0, 1) , lineGraph "beta" sc (1, 1) , lineGraph "d" sc (2, 1) , lineGraph "q" sc (3, 1) , lineGraph "q_in" sc (4, 1) , lineGraph "q_err" sc (5, 1) , lineGraph "mod_d" sc (6, 1) , lineGraph "mod_q" sc (7, 1) , lineGraph "current_i_q" sc (8, 1) ] (v, c) <- ogl inits dat <- MVC.producer (bounded 1) (pipe) return (v, fmap Left (dat) <> fmap Right c) fromEncoder :: Encoder -> [SensorReading GLfloat] fromEncoder Encoder{..} = [ Reading "pll_vel" $ gr' 2000000 pll_vel , Reading "pll_pos" $ gr' 100000 pll_pos , Reading "phase" $ gr' 10 phase ] fromAdc :: Adc -> [SensorReading GLfloat] fromAdc Adc{..} = [ Reading "vbus" $ gr' 25 vbus , Reading "phase_b" $ gr' 0.15 (phase_b) , Reading "phase_c" $ gr' 0.15 (phase_c) ] fromSVM :: Svm -> [SensorReading GLfloat] fromSVM Svm{..} = [ Reading "svm_a" $ gr' 1 svm_a , Reading "svm_b" $ gr' 1 (svm_b) , Reading "svm_c" $ gr' 1 (svm_c) ] fromCC :: CurrentControl -> [SensorReading GLfloat] fromCC CurrentControl{..} = [ Reading "alpha" $ gr' 1 alpha , Reading "beta" $ gr' 1 beta , Reading "d" $ gr' 1 d , Reading "q" $ gr' 1 q , Reading "d_in" $ gr' 1 d_in , Reading "q_in" $ gr' 1 q_in , Reading "d_err" $ gr' 1 d_err , Reading "q_err" $ gr' 1 q_err , Reading "v_d" $ gr' 1 v_d , Reading "v_q" $ gr' 1 v_q , Reading "mod_d" $ gr' 1 mod_d , Reading "mod_q" $ gr' 1 mod_q , Reading "current_i_q" $ gr' 10 current_i_q ] gr' :: GLfloat -> Float -> GLfloat gr' x = (graphRange (-x, x) :: Float -> GLfloat) gR :: (GLfloat, GLfloat) -> Float -> GLfloat gR (x1, x2) = (graphRange (x1, x2) :: Float -> GLfloat) class ToReading a where toReading :: a -> [SensorReading GLfloat] instance ToReading Encoder where toReading = fromEncoder instance ToReading Adc where toReading = fromAdc
sorki/odrive
client/app/Main.hs
bsd-3-clause
5,189
0
19
1,383
2,147
1,103
1,044
142
9
triple x = tripleItYo x where tripleItYo :: Integer -> Integer tripleItYo y = y * 3
dhaneshkk/haskell-programming
localType.hs
bsd-3-clause
94
2
5
27
36
17
19
3
1
{-# LANGUAGE OverloadedStrings #-} module Filesystem ( isXmlFile , isDotFile , isDirectory , isRegularFile , isSymbolicLink , isBlockDevice , isCharacterDevice , isNamedPipe , isSocket , isValidFile , getAllFilesInDir , getAllFilesOfType , chdir ) where import Data.ByteString.Char8 (ByteString, pack, unpack) import HPath import HPath.IO import System.Posix.ByteString.FilePath import System.Posix.Directory.ByteString import System.Posix.Directory.Traversals import System.Posix.FilePath --import System.Posix.Files hiding (isSymbolicLink, isRegularFile) import qualified System.Posix.Files as F chdir :: RawFilePath -> IO () chdir = changeWorkingDirectory cmpFileType :: RawFilePath -> FileType -> IO Bool cmpFileType fp ft = do f <- parseAbs fp fmap (ft ==) (getFileType f) isXmlFile :: RawFilePath -> Bool isXmlFile fp = hasExtension fp && takeExtension fp == extension where extension = pack ".xml" isDotFile :: RawFilePath -> IO Bool isDotFile fp = return $ hiddenFile fp isDirectory :: RawFilePath -> IO Bool isDirectory fp = cmpFileType fp Directory isRegularFile :: RawFilePath -> IO Bool isRegularFile fp = cmpFileType fp RegularFile isSymbolicLink :: RawFilePath -> IO Bool isSymbolicLink fp = cmpFileType fp SymbolicLink isBlockDevice :: RawFilePath -> IO Bool isBlockDevice fp = cmpFileType fp BlockDevice isCharacterDevice :: RawFilePath -> IO Bool isCharacterDevice fp = cmpFileType fp CharacterDevice isNamedPipe :: RawFilePath -> IO Bool isNamedPipe fp = cmpFileType fp NamedPipe isSocket :: RawFilePath -> IO Bool isSocket fp = cmpFileType fp Socket isValidFile :: RawFilePath -> Bool -> IO Bool isValidFile fp allowSymLink = do fileStatus <- F.getFileStatus (unpack fp) let regularFile = F.isRegularFile fileStatus let symbolicLink = F.isSymbolicLink fileStatus return (regularFile || (symbolicLink && allowSymLink)) getAllFilesInDir :: RawFilePath -> Bool -> IO [RawFilePath] getAllFilesInDir fp followLinks = traverseDirectory flt [] fp where flt acc f = do valid <- isValidFile f followLinks if valid then return (f:acc) else return (acc) getAllFilesOfType :: RawFilePath -> ByteString -> Bool -> IO [RawFilePath] getAllFilesOfType fp typ followLinks = traverseDirectory flt [] fp where flt acc f = do valid <- isValidFile f followLinks let validType = hasExtension f && takeExtension f == typ if valid && validType then return (f:acc) else return (acc)
dxtr/hagento
src/Filesystem.hs
bsd-3-clause
2,695
0
14
646
727
373
354
66
2
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE NoMonoPatBinds #-} import Types import Data.Iso import Language.JsonGrammar import Prelude hiding (id, (.), head, either) import Control.Category import Data.Aeson (Object) import Test.Framework (Test, defaultMain) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertEqual) person = $(deriveIsos ''Person) (male, female) = $(deriveIsos ''Gender) coords = $(deriveIsos ''Coords) instance Json Person where grammar = person . object ( prop "naam" . prop "geslacht" . prop "leeftijd" . coordsProps ) instance Json Gender where grammar = male . litJson "man" <> female . litJson "vrouw" coordsProps :: Iso (Object :- t) (Object :- Coords :- t) coordsProps = duck coords . prop "lat" . prop "lng" anna :: Person anna = Person "Anna" Female 36 (Coords 53.0163038 5.1993053) main :: IO () main = defaultMain [personTest] personTest :: Test personTest = testCase "Person" (assertEqual "" anna anna') where Just anna' = fromJson annaJson Just annaJson = toJson anna
MedeaMelana/JsonGrammar
tests/Tests.hs
bsd-3-clause
1,130
0
12
226
361
191
170
-1
-1
{-# LANGUAGE BangPatterns , RankNTypes, GADTs, DataKinds #-} module Numerical.HBLAS.BLAS.Internal.Level1( AsumFun ,AxpyFun ,CopyFun ,NoScalarDotFun ,ScalarDotFun ,ComplexDotFun ,Nrm2Fun ,RotFun ,RotgFun ,RotmFun ,RotmgFun ,ScalFun ,SwapFun ,IamaxFun --,IaminFun ,asumAbstraction ,axpyAbstraction ,copyAbstraction ,noScalarDotAbstraction ,scalarDotAbstraction ,complexDotAbstraction ,norm2Abstraction ,rotAbstraction ,rotgAbstraction ,rotmAbstraction ,rotmgAbstraction ,scalAbstraction ,swapAbstraction ,iamaxAbstraction --,iaminAbstraction ) where import Numerical.HBLAS.Constants import Numerical.HBLAS.UtilsFFI import Numerical.HBLAS.BLAS.FFI.Level1 import Numerical.HBLAS.BLAS.Internal.Utility import Numerical.HBLAS.MatrixTypes import Control.Monad.Primitive import qualified Data.Vector.Storable.Mutable as SM import Foreign.C.Types import Foreign.Ptr type AsumFun el s m res = Int -> MDenseVector s Direct el -> m res type AxpyFun el s m = Int -> el -> MDenseVector s Direct el -> MDenseVector s Direct el -> m() type CopyFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> m() type NoScalarDotFun el s m res = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> m res type ScalarDotFun el s m res = Int -> el -> MDenseVector s Direct el -> MDenseVector s Direct el -> m res type ComplexDotFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> MValue (PrimState m) el -> m() type Nrm2Fun el s m res = Int -> MDenseVector s Direct el -> m res type RotFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> el -> el -> m() type RotgFun el s m = MValue (PrimState m) el -> MValue (PrimState m) el -> MValue (PrimState m) el -> MValue (PrimState m) el -> m() type RotmFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> MDenseVector s Direct el -> m() type RotmgFun el s m = MValue (PrimState m) el -> MValue (PrimState m) el -> MValue (PrimState m) el -> el -> MDenseVector s Direct el -> m() type ScalFun scale el s m = Int -> scale -> MDenseVector s Direct el -> m() type SwapFun el s m = Int -> MDenseVector s Direct el -> MDenseVector s Direct el -> m() type IamaxFun el s m = Int -> MDenseVector s Direct el -> m Int --type IaminFun el s m = Int -> MDenseVector s Direct el -> Int -> m Int {-# NOINLINE asumAbstraction #-} asumAbstraction:: (SM.Storable el, PrimMonad m) => String -> AsumFunFFI el res -> AsumFunFFI el res -> AsumFun el (PrimState m) m res asumAbstraction asumName asumSafeFFI asumUnsafeFFI = asum where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= 2 * (fromIntegral n) -- for complex vector, 2n additions are needed asum n (MutableDenseVector _ dim stride buff) | isVectorBadWithNIncrement dim n stride = error $! vectorBadInfo asumName "source matrix" dim n stride | otherwise = unsafeWithPrim buff $ \ptr -> do unsafePrimToPrim $! (if shouldCallFast n then asumUnsafeFFI else asumSafeFFI) (fromIntegral n) ptr (fromIntegral stride) {-# NOINLINE axpyAbstraction #-} axpyAbstraction :: (SM.Storable el, PrimMonad m) => String -> AxpyFunFFI scale el -> AxpyFunFFI scale el -> (el -> (scale -> m()) -> m()) -> AxpyFun el (PrimState m) m axpyAbstraction axpyName axpySafeFFI axpyUnsafeFFI constHandler = axpy where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= 2 * (fromIntegral n) -- n for a*x, and n for +y axpy n alpha (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo axpyName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo axpyName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> constHandler alpha $ \alphaPtr -> do unsafePrimToPrim $! (if shouldCallFast n then axpyUnsafeFFI else axpySafeFFI) (fromIntegral n) alphaPtr ap (fromIntegral astride) bp (fromIntegral bstride) {-# NOINLINE copyAbstraction #-} copyAbstraction :: (SM.Storable el, PrimMonad m) => String -> CopyFunFFI el -> CopyFunFFI el -> CopyFun el (PrimState m) m copyAbstraction copyName copySafeFFI copyUnsafeFFI = copy where shouldCallFast :: Bool shouldCallFast = True -- TODO:(yjj) to confirm no flops are needed in copy copy n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo copyName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo copyName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> do unsafePrimToPrim $! (if shouldCallFast then copyUnsafeFFI else copySafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) {-# NOINLINE noScalarDotAbstraction #-} noScalarDotAbstraction :: (SM.Storable el, PrimMonad m) => String -> NoScalarDotFunFFI el res -> NoScalarDotFunFFI el res -> NoScalarDotFun el (PrimState m) m res noScalarDotAbstraction dotName dotSafeFFI dotUnsafeFFI = dot where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n dot n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo dotName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo dotName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> do unsafePrimToPrim $! (if shouldCallFast n then dotUnsafeFFI else dotSafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) {-# NOINLINE scalarDotAbstraction #-} scalarDotAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> SdsdotFortranFunFFI el res -> SdsdotFortranFunFFI el res -> (CInt -> (Ptr CInt -> m res) -> m res) -> (el -> (Ptr el -> m res) -> m res) -> ScalarDotFun el (PrimState m) m res scalarDotAbstraction dotName dotSafeFFI dotUnsafeFFI intConstHandler scaleConstHandler = dot where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n dot n sb (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo dotName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo dotName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> intConstHandler (fromIntegral n) $ \nPtr -> intConstHandler (fromIntegral astride) $ \incaPtr -> intConstHandler (fromIntegral bstride) $ \incbPtr -> scaleConstHandler sb $ \sbPtr -> do unsafePrimToPrim $! (if shouldCallFast n then dotUnsafeFFI else dotSafeFFI) nPtr sbPtr ap incaPtr bp incbPtr {-# NOINLINE complexDotAbstraction #-} complexDotAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> ComplexDotFunFFI el -> ComplexDotFunFFI el -> ComplexDotFun el (PrimState m) m complexDotAbstraction dotName dotSafeFFI dotUnsafeFFI = dot where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n dot n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) (MutableValue resbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo dotName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo dotName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> unsafeWithPrim resbuff $ \resPtr -> do unsafePrimToPrim $! (if shouldCallFast n then dotUnsafeFFI else dotSafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) resPtr {-# NOINLINE norm2Abstraction #-} norm2Abstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> Nrm2FunFFI el res -> Nrm2FunFFI el res -> Nrm2Fun el (PrimState m) m res norm2Abstraction norm2Name norm2SafeFFI norm2UnsafeFFI = norm2 where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n -- not sure, maybe for complex is 2n norm2 n (MutableDenseVector _ dim stride buff) | isVectorBadWithNIncrement dim n stride = error $! vectorBadInfo norm2Name "input matrix" dim n stride | otherwise = unsafeWithPrim buff $ \p -> do unsafePrimToPrim $! (if shouldCallFast n then norm2UnsafeFFI else norm2SafeFFI) (fromIntegral n) p (fromIntegral stride) {-# NOINLINE rotAbstraction #-} rotAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> RotFunFFI el -> RotFunFFI el -> RotFun el (PrimState m) m rotAbstraction rotName rotSafeFFI rotUnsafeFFI = rot where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n rot n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) c s | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo rotName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo rotName "second matrix" bdim n bstride | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> do unsafePrimToPrim $! (if shouldCallFast n then rotUnsafeFFI else rotSafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) c s {-# NOINLINE rotgAbstraction #-} rotgAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> RotgFunFFI el -> RotgFunFFI el -> RotgFun el (PrimState m) m rotgAbstraction rotgName rotgSafeFFI rotgUnsafeFFI = rotg where shouldCallFast :: Bool shouldCallFast = True -- not sure, seems O(1) rotg (MutableValue aptr) (MutableValue bptr) (MutableValue cptr) (MutableValue sptr) = unsafeWithPrim aptr $ \ap -> unsafeWithPrim bptr $ \bp -> unsafeWithPrim cptr $ \cp -> unsafeWithPrim sptr $ \sp -> do unsafePrimToPrim $! (if shouldCallFast then rotgUnsafeFFI else rotgSafeFFI) ap bp cp sp {-# NOINLINE rotmAbstraction #-} rotmAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> RotmFunFFI el -> RotmFunFFI el -> RotmFun el (PrimState m) m rotmAbstraction rotmName rotmSafeFFI rotmUnsafeFFI = rotm where shouldCallFast :: Bool shouldCallFast = True -- O(1) rotm n (MutableDenseVector _ adim astride abuff) (MutableDenseVector _ bdim bstride bbuff) (MutableDenseVector _ pdim _ pbuff) | isVectorBadWithNIncrement adim n astride = error $! vectorBadInfo rotmName "first matrix" adim n astride | isVectorBadWithNIncrement bdim n bstride = error $! vectorBadInfo rotmName "second matrix" bdim n bstride | pdim /= 5 = error $! rotmName ++ " param dimension is not 5" | otherwise = unsafeWithPrim abuff $ \ap -> unsafeWithPrim bbuff $ \bp -> unsafeWithPrim pbuff $ \pp -> do unsafePrimToPrim $! (if shouldCallFast then rotmUnsafeFFI else rotmSafeFFI) (fromIntegral n) ap (fromIntegral astride) bp (fromIntegral bstride) pp {-# NOINLINE rotmgAbstraction #-} rotmgAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> RotmgFunFFI el -> RotmgFunFFI el -> RotmgFun el (PrimState m) m rotmgAbstraction rotmgName rotmgSafeFFI rotmgUnsafeFFI = rotmg where shouldCallFast :: Bool shouldCallFast = True -- O(1) rotmg (MutableValue d1) (MutableValue d2) (MutableValue x1) y1 (MutableDenseVector _ pdim _ pbuff) | pdim /= 5 = error $! rotmgName ++ " param dimension is not 5" | otherwise = unsafeWithPrim d1 $ \d1p -> unsafeWithPrim d2 $ \d2p -> unsafeWithPrim x1 $ \x1p -> unsafeWithPrim pbuff $ \pp -> do unsafePrimToPrim $! (if shouldCallFast then rotmgUnsafeFFI else rotmgSafeFFI) d1p d2p x1p y1 pp {-# NOINLINE scalAbstraction #-} scalAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> ScalFunFFI scale el -> ScalFunFFI scale el -> (scaleplain -> (scale -> m()) -> m()) -> ScalFun scaleplain el (PrimState m) m scalAbstraction scalName scalSafeFFI scalUnsafeFFI constHandler = scal where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n scal n alpha (MutableDenseVector _ xdim stride xbuff) | isVectorBadWithNIncrement xdim n stride = error $! vectorBadInfo scalName "vector" xdim n stride | otherwise = unsafeWithPrim xbuff $ \xptr -> constHandler alpha $ \alphaPtr -> do unsafePrimToPrim $! (if shouldCallFast n then scalUnsafeFFI else scalSafeFFI) (fromIntegral n) alphaPtr xptr (fromIntegral stride) {-# NOINLINE swapAbstraction #-} swapAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> SwapFunFFI el -> SwapFunFFI el -> SwapFun el (PrimState m) m swapAbstraction swapName swapSafeFFI swapUnsafeFFI = swap where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n -- no computation? only n times memory access? swap n (MutableDenseVector _ xdim xstride xbuff) (MutableDenseVector _ ydim ystride ybuff) | isVectorBadWithNIncrement xdim n xstride = error $! vectorBadInfo swapName "vector x" xdim n xstride | isVectorBadWithNIncrement ydim n ystride = error $! vectorBadInfo swapName "vector y" ydim n ystride | otherwise = unsafeWithPrim xbuff $ \xptr -> unsafeWithPrim ybuff $ \yptr -> do unsafePrimToPrim $! (if shouldCallFast n then swapUnsafeFFI else swapSafeFFI) (fromIntegral n) xptr (fromIntegral xstride) yptr (fromIntegral ystride) {-# NOINLINE iamaxAbstraction #-} iamaxAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> IamaxFunFFI el -> IamaxFunFFI el -> IamaxFun el (PrimState m) m iamaxAbstraction iamaxName iamaxSafeFFI iamaxUnsafeFFI = iamax where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n -- n times comparison iamax n (MutableDenseVector _ xdim xstride xbuff) | isVectorBadWithNIncrement xdim n xstride = error $! vectorBadInfo iamaxName "target vector" xdim n xstride | otherwise = unsafeWithPrim xbuff $ \xptr -> do unsafePrimToPrim $! (if shouldCallFast n then iamaxUnsafeFFI else iamaxSafeFFI) (fromIntegral n) xptr (fromIntegral xstride) {- {-# NOINLINE iaminAbstraction #-} iaminAbstraction :: (SM.Storable el, PrimMonad m, Show el) => String -> IaminFunFFI el -> IaminFunFFI el -> IaminFun el (PrimState m) m iaminAbstraction iaminName iaminSafeFFI iaminUnsafeFFI = iamin where shouldCallFast :: Int -> Bool shouldCallFast n = flopsThreshold >= fromIntegral n -- n times comparison iamin n (MutableDenseVector _ xdim _ xbuff) xincx | isVectorBadWithNIncrement xdim n xincx = error $! vectorBadInfo iaminName "target vector" xdim n xincx | otherwise = unsafeWithPrim xbuff $ \xptr -> do unsafePrimToPrim $! (if shouldCallFast n then iaminUnsafeFFI else iaminSafeFFI) (fromIntegral n) xptr (fromIntegral xincx) -}
yangjueji/hblas
src/Numerical/HBLAS/BLAS/Internal/Level1.hs
bsd-3-clause
15,741
0
26
3,383
4,557
2,292
2,265
271
2
import Data.ByteString (ByteString) import Control.Monad (replicateM) import Data.List (unfoldr) -- From the 'entropy' package - for non-determinstic random bits. -- These values come from -- - RDRAND (when on an x86-64 system with said instruction and using new enough compilers) -- - /dev/urandom (when on a nix system) -- - Windows crypt-api (obvious) import System.Entropy -- From the DRBG package -- The CtrDRBG will use NIST SP800-90 + AES-CTR + a seed you provide to -- produce cryptographically strong random values. import Crypto.Random.DRBG -- To throw exceptions instead of get 'Either' results. import Crypto.Classes.Exceptions as X -- Obtain N blocks of 1MB random values based on the given seed -- (Seed must be 32 bytes or larger) pseudoRandom :: ByteString -> Int -> [ByteString] pseudoRandom seed n = let g = X.newGen seed :: CtrDRBG in unfoldr (\(gen,cnt) -> if cnt == 0 then Nothing else let (rand,newGen) = X.genBytes (2^20) gen in Just (rand, (newGen,cnt-1))) (g,n) realRandom :: Int -> IO [ByteString] realRandom n = replicateM n (getEntropy (2^20))
GaloisInc/hacrypto
src/Haskell/rand.hs
bsd-3-clause
1,219
0
17
317
235
135
100
16
2
-------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.ARB.TextureStorageMultisample -- Copyright : (c) Sven Panne 2019 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.ARB.TextureStorageMultisample ( -- * Extension Support glGetARBTextureStorageMultisample, gl_ARB_texture_storage_multisample, -- * Functions glTexStorage2DMultisample, glTexStorage3DMultisample ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Functions
haskell-opengl/OpenGLRaw
src/Graphics/GL/ARB/TextureStorageMultisample.hs
bsd-3-clause
700
0
4
89
47
36
11
7
0
module ErrMsg ( LogReader , setLogger , handleErrMsg ) where import Bag import Control.Applicative import Data.IORef import Data.Maybe import DynFlags import ErrUtils import GHC import qualified Gap import HscTypes import Outputable ---------------------------------------------------------------- type LogReader = IO [String] ---------------------------------------------------------------- setLogger :: Bool -> DynFlags -> IO (DynFlags, LogReader) setLogger False df = return (newdf, undefined) where newdf = df { log_action = \_ _ _ _ -> return () } setLogger True df = do ref <- newIORef [] :: IO (IORef [String]) let newdf = df { log_action = appendLog ref } return (newdf, reverse <$> readIORef ref) where appendLog ref _ src stl msg = modifyIORef ref (\ls -> ppMsg src msg stl : ls) ---------------------------------------------------------------- handleErrMsg :: SourceError -> Ghc [String] handleErrMsg = return . errBagToStrList . srcErrorMessages errBagToStrList :: Bag ErrMsg -> [String] errBagToStrList = map ppErrMsg . reverse . bagToList ---------------------------------------------------------------- ppErrMsg :: ErrMsg -> String ppErrMsg err = ppMsg spn msg defaultUserStyle ++ ext where spn = head (errMsgSpans err) msg = errMsgShortDoc err ext = showMsg (errMsgExtraInfo err) defaultUserStyle ppMsg :: SrcSpan -> Message -> PprStyle -> String ppMsg spn msg stl = fromMaybe def $ do (line,col,_,_) <- Gap.getSrcSpan spn file <- Gap.getSrcFile spn return $ file ++ ":" ++ show line ++ ":" ++ show col ++ ":" ++ cts ++ "\0" where def = "ghc-mod:0:0:Probably mutual module import occurred\0" cts = showMsg msg stl ---------------------------------------------------------------- showMsg :: SDoc -> PprStyle -> String showMsg d stl = map toNull $ Gap.renderMsg d stl where toNull '\n' = '\0' toNull x = x
johntyree/ghc-mod
ErrMsg.hs
bsd-3-clause
1,919
0
15
359
571
299
272
43
2
{- EEL -- Extensible Experimental Language by Lukáš Kuklínek, 2013 -} module Main.REPL(repl) where import Parser.Parser import Parser.State import Parser.Dump import Parser.Core import Sema.Term import Sema.Infer import Backend.Emit import System.IO import Control.Applicative import Text.Parsec import Data.Char import qualified Data.Map as M -- | REPL + welcome message repl ste = do hSetBuffering stdout NoBuffering putStrLn "Welcome to the EEL interactive interpreter!" putStrLn "Type :? for help" prompt 1 repl' 1 ste -- | Read-Eval-Print Loop: quick, dirty, and ugly repl' n ste = do let quit = return (Right ste) let continue ste' = prompt (succ n) >> repl' (succ n) ste' let continue' = continue ste end <- hIsEOF stdin if end then quit else do lineIn <- getLine case reverse . dropWhile isSpace . reverse $ lineIn of "" -> continue' ":q" -> quit ":quit" -> quit ":exit" -> quit ":?" -> help >> continue' ":h" -> help >> continue' ":help" -> help >> continue' ':':'t':' ':str -> do withParse n ste pinfer str $ \term -> do case termType term of Left err -> printErr err Right ty -> putStrLn (show term ++ ": " ++ show ty) continue' ':':'g':' ':str -> withParse n ste pinfer str (putStrLn . genTerm) >> continue' ':':'d':' ':str -> do withParse n ste pinfer str $ \term -> putStrLn (dumpTerm term) continue' ':':'i':' ':str -> do case M.lookup (Symbol str) (pSymTable ste) of Nothing -> printErrStr ("Could not find symbol: '" ++ str ++ "'") Just fd -> case fd of FDUser term -> putStrLn (dumpTerm term) FDBuiltIn _ -> putStrLn "<builtin>" continue' ":x" -> continue (ste { pStack = initStack}) ":ls" -> printFuncs ste >> continue' ":l" -> printFuncs ste >> continue' ":s" -> stackDump ste >> continue' ':':str -> printErrStr ("Unknown command: " ++ show str) >> continue' line -> do ste'' <- case runParser (onLine n >> coreTopParser) ste "<interactive>" line of Left err -> printErr err >> return ste Right ste' -> case semaCheck Nothing ste' of Right _ -> (putStrLn $ show $ pStack ste') >> return ste' Left errs -> (putStrLn $ show errs) >> return ste continue ste'' -- print stack contents stackDump ste = let stk = pStack ste in putStrLn (show stk) >> putStrLn ("Type: " ++ show (stackInfer stk)) prompt n = putStr (zeroPad 3 (show (n :: Int)) ++ "> ") zeroPad n = reverse . take n . (++ repeat '0') . reverse pinfer = infer <$> coreTermParser printErr s = printErrStr (show s) printErrStr s = hPutStrLn stderr ("ERROR: " ++ s) withParse n ste parser str action = case runParser (onLine n >> coreSkipParser >> parser) ste "<interactive>" str of Left err -> printErr err Right term -> action term onLine n = fmap (flip setSourceLine n) getPosition >>= setPosition help = putStr helpMsg helpMsg = unlines [ " Available commands:", " :? show this help message", " :q quit", " :t EXPR print type of an expression", " :d EXPR dump AST of an expression", " :g EXPR generate LLVM code for EXPR", " :i NAME dump AST of an user-defined function", " :x clear the stack", " :s show current stack", " :l list of defined functions" ]
iljakuklic/eel-proto
src/Main/REPL.hs
bsd-3-clause
3,935
0
26
1,431
1,118
542
576
87
23
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeApplications #-} module RoundTripSpec (spec) where import Test.Hspec import Bound import Data.Aeson import Data.Default import Data.Map.Strict (fromList) import qualified Data.HashSet as HS import qualified Data.Vector as V import Pact.Types.RowData import Pact.Types.Runtime import Pact.Types.PactValue spec :: Spec spec = do describe "JSONRoundtrips" $ do describe "testJSONPersist" testJSONPersist describe "testJSONColumns "testJSONColumns describe "testJSONModules" testJSONModules describe "testUnification" testUnification rt :: (FromJSON a,ToJSON a,Show a,Eq a) => String -> a -> Spec rt n p = it ("roundtrips " ++ n) $ do decode (encode p) `shouldBe` Just p testJSONPersist :: Spec testJSONPersist = do rt "integer" (PLiteral (LInteger 123)) rt "decimal" (PLiteral (LDecimal 123.34857)) rt "bool" (PLiteral (LBool False)) rt "string" (PLiteral (LString "hello")) rt "time" (PLiteral (LTime (read "2016-09-17 22:47:31.904733 UTC"))) rt "keyset" (PGuard (GKeySet $ mkKeySet [PublicKey "askjh",PublicKey "dfgh"] "predfun")) rt "modref" (PModRef (ModRef "foo.bar" (Just ["baz", "bof.quux"]) def)) rt "list" (PList (V.fromList [PLiteral (LInteger 123), PLiteral (LBool False), PLiteral (LTime (read "2016-09-17 22:47:31.904733 UTC"))])) rt "object" (PObject (ObjectMap (fromList [("A",PLiteral (LInteger 123)), ("B",PLiteral (LBool False))]))) testJSONColumns :: Spec testJSONColumns = do rt "object" obj it "roundtrips as rowdata" $ do decode @RowData (encode obj) `shouldBe` Just (RowData RDV0 (pactValueToRowData <$> obj)) where uguard = GUser $ UserGuard (Name (BareName "a" def)) [PLiteral (LInteger 123)] pguard = GPact $ PactGuard (PactId "123") "456" ksguard = GKeySet $ mkKeySet [PublicKey "askjh",PublicKey "dfgh"] "predfun" ksrguard = GKeySetRef $ KeySetName "beepboop" mguard = GModule $ ModuleGuard (ModuleName "beep" Nothing) "boop" obj = ObjectMap $ fromList [("A", PLiteral (LInteger 123)) ,("B", PLiteral (LBool False)) ,("C", PLiteral (LString "hello")) ,("D", PLiteral (LTime (read "2016-09-17 22:47:31.904733 UTC"))) ,("E", PGuard uguard) ,("F", PModRef (ModRef "foo.bar" (Just ["baz", "bof.quux"]) def)) ,("G", PObject (ObjectMap (fromList [("A",PLiteral (LInteger 123))]))) ,("H", PList (V.fromList [PLiteral (LInteger 123), PLiteral (LBool False), PLiteral (LTime (read "2016-09-17 22:47:31.904733 UTC"))])) ,("I", PGuard pguard) ,("J", PGuard ksguard) ,("K", PGuard ksrguard) ,("L", PGuard mguard)] testJSONModules :: Spec testJSONModules = rt "module" tmod where tmod = TModule (MDModule (Module "foo" (Governance (Right (tStr "hi"))) def "" (ModuleHash pactInitialHash) HS.empty [] [])) (abstract (const (Just ())) (toTList TyAny def [tlet1])) def tlet1 = TBinding [] (abstract (\b -> if b == na then Just 0 else Nothing) (toTList TyAny def [(TVar na def),tlet2])) -- bound var + let BindLet def tlet2 = TBinding [] (abstract (\b -> if b == nb then Just 0 else Nothing) (toTList TyAny def [(TVar na def),(TVar nb def)])) -- free var + bound var BindLet def na = Name $ BareName "a" def nb = Name $ BareName "b" def testUnification :: Spec testUnification = do it "mod spec unifies with a module with greater coverage" $ (modRef [ifaceA], modRef [ifaceA,ifaceB]) `shouldSatisfy` (uncurry canUnifyWith) it "mod spec unifies with a module with same coverage" $ (modRef [ifaceA,ifaceB], modRef [ifaceA,ifaceB]) `shouldSatisfy` (uncurry canUnifyWith) it "mod spec does not unify with a module with less coverage" $ (modRef [ifaceA,ifaceB], modRef [ifaceA]) `shouldSatisfy` (not . uncurry canUnifyWith) it "mod spec does not unify with a module with different coverage" $ (modRef [ifaceB], modRef [ifaceA]) `shouldSatisfy` (not . uncurry canUnifyWith) -- TODO: add other cases, TyList and TySchema being important candidates where ifaceA = "ifaceA" ifaceB = "ifaceB" modRef :: [ModuleName] -> Type (Term ()) modRef is = modRefTy (ModRef "a" (Just is) def)
kadena-io/pact
tests/RoundTripSpec.hs
bsd-3-clause
4,328
0
20
937
1,558
812
746
96
3
main = putStrLn "Dummy fixpoint.native"
gridaphobe/liquid-fixpoint
src/Ocaml.hs
bsd-3-clause
40
0
5
5
9
4
5
1
1
module Main where import Trombone.Server main :: IO () main = runWithArgs
johanneshilden/principle
Main.hs
bsd-3-clause
77
0
6
15
24
14
10
4
1
module Foundation where import Prelude import Yesod import Yesod.Static import Yesod.Auth import Yesod.Auth.BrowserId import Yesod.Default.Config import Yesod.Default.Util (addStaticContentExternal) import Network.HTTP.Client.Conduit (Manager, HasHttpManager (getHttpManager)) import qualified Settings import Settings.Development (development) import qualified Database.Persist import Database.Persist.Sql (SqlPersistT) import Settings.StaticFiles import Settings (widgetFile, Extra (..)) import Model import Text.Jasmine (minifym) import Text.Hamlet (hamletFile) import Yesod.Core.Types (Logger) -- | The site argument for your application. This can be a good place to -- keep settings and values requiring initialization before your application -- starts running, such as database connections. Every handler will have -- access to the data present here. data App = App { settings :: AppConfig DefaultEnv Extra , getStatic :: Static -- ^ Settings for static file serving. , connPool :: Database.Persist.PersistConfigPool Settings.PersistConf -- ^ Database connection pool. , httpManager :: Manager , persistConfig :: Settings.PersistConf , appLogger :: Logger } instance HasHttpManager App where getHttpManager = httpManager -- Set up i18n messages. See the message folder. mkMessage "App" "messages" "en" -- This is where we define all of the routes in our application. For a full -- explanation of the syntax, please see: -- http://www.yesodweb.com/book/routing-and-handlers -- -- Note that this is really half the story; in Application.hs, mkYesodDispatch -- generates the rest of the code. Please see the linked documentation for an -- explanation for this split. mkYesodData "App" $(parseRoutesFile "config/routes") type Form x = Html -> MForm (HandlerT App IO) (FormResult x, Widget) -- Please see the documentation for the Yesod typeclass. There are a number -- of settings which can be configured by overriding methods here. instance Yesod App where approot = ApprootMaster $ appRoot . settings -- Store session data on the client in encrypted cookies, -- default session idle timeout is 120 minutes makeSessionBackend _ = fmap Just $ defaultClientSessionBackend 120 -- timeout in minutes "config/client_session_key.aes" defaultLayout widget = do master <- getYesod mmsg <- getMessage -- We break up the default layout into two components: -- default-layout is the contents of the body tag, and -- default-layout-wrapper is the entire page. Since the final -- value passed to hamletToRepHtml cannot be a widget, this allows -- you to use normal widget features in default-layout. pc <- widgetToPageContent $ do $(combineStylesheets 'StaticR [ css_normalize_css , css_bootstrap_css ]) $(widgetFile "default-layout") giveUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet") -- This is done to provide an optimization for serving static files from -- a separate domain. Please see the staticRoot setting in Settings.hs urlRenderOverride y (StaticR s) = Just $ uncurry (joinPath y (Settings.staticRoot $ settings y)) $ renderRoute s urlRenderOverride _ _ = Nothing -- The page to be redirected to when authentication is required. authRoute _ = Just $ AuthR LoginR -- Routes not requiring authenitcation. isAuthorized (AuthR _) _ = return Authorized isAuthorized FaviconR _ = return Authorized isAuthorized RobotsR _ = return Authorized -- Default to Authorized for now. isAuthorized _ _ = 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 = addStaticContentExternal minifym genFileName Settings.staticDir (StaticR . flip StaticRoute []) where -- Generate a unique filename based on the content itself genFileName lbs | development = "autogen-" ++ base64md5 lbs | otherwise = base64md5 lbs -- Place Javascript at bottom of the body tag so the rest of the page loads first jsLoader _ = BottomOfBody -- What messages should be logged. The following includes all messages when -- in development, and warnings and errors in production. shouldLog _ _source level = development || level == LevelWarn || level == LevelError makeLogger = return . appLogger -- How to run database actions. instance YesodPersist App where type YesodPersistBackend App = SqlPersistT runDB = defaultRunDB persistConfig connPool instance YesodPersistRunner App where getDBRunner = defaultGetDBRunner connPool instance YesodAuth App where type AuthId App = UserId -- Where to send a user after successful login loginDest _ = HomeR -- Where to send a user after logout logoutDest _ = HomeR getAuthId creds = runDB $ do x <- getBy $ UniqueUser $ credsIdent creds case x of Just (Entity uid _) -> return $ Just uid Nothing -> do fmap Just $ insert User { userIdent = credsIdent creds , userPassword = Nothing } -- You can add other plugins like BrowserID, email or OAuth here authPlugins _ = [authBrowserId def] authHttpManager = httpManager -- This instance is required to use forms. You can modify renderMessage to -- achieve customized and internationalized form validation messages. instance RenderMessage App FormMessage where renderMessage _ _ = defaultFormMessage -- | Get the 'Extra' value, used to hold data from the settings.yml file. getExtra :: Handler Extra getExtra = fmap (appExtra . settings) getYesod -- Note: previous versions of the scaffolding included a deliver function to -- send emails. Unfortunately, there are too many different options for us to -- give a reasonable default. Instead, the information is available on the -- wiki: -- -- https://github.com/yesodweb/yesod/wiki/Sending-email
Laquendi/memopad
Foundation.hs
mit
6,292
0
18
1,413
924
504
420
-1
-1
{-# LANGUAGE TemplateHaskell #-} module Number.Base.Data where import Autolib.ToDoc import Autolib.Reporter import Autolib.Reader import Data.Typeable import Number.Wert import Data.Char data Ziffer = Ziffer Int deriving ( Eq, Ord, Typeable ) zehn :: Int zehn = 10 instance ToDoc Ziffer where toDoc (Ziffer z) = if (0 <= z) && (z < zehn) then toDoc z else if z - zehn <= fromEnum 'Z' - fromEnum 'A' then Autolib.ToDoc.char $ toEnum $ fromEnum 'A' + (z - zehn) else error $ "cannot convert digit to character: " ++ show z instance Reader Ziffer where reader = do d <- satisfy isDigit my_whiteSpace return $ Ziffer $ fromEnum d - fromEnum '0' <|> do d <- satisfy isLower my_whiteSpace return $ Ziffer $ fromEnum d - fromEnum 'a' + zehn <|> do d <- satisfy isUpper my_whiteSpace return $ Ziffer $ fromEnum d - fromEnum 'A' + zehn data Zahl = Zahl { basis :: Int , ziffern :: [ Ziffer ] } deriving ( Eq, Ord, Typeable ) $(derives [makeReader, makeToDoc] [''Zahl]) instance Wert_at [ Ziffer ] Integer where wert_at b zs = foldl ( \ x (Ziffer y) -> fromIntegral b * x + fromIntegral y ) 0 zs instance Wert Zahl Integer where wert z = wert_at (basis z) (ziffern z) -------------------------------------------------------------------------- class Range a where range :: Int -> a -> Reporter () instance Range [ Ziffer ] where range b zs = silent $ do inform $ fsep [ text "teste Ziffern", toDoc zs , text "bezüglich der Basis", toDoc b ] nested 4 $ sequence_ $ do z <- zs return $ when ( not ( ( Ziffer 0 <= z ) && ( z < Ziffer b ) ) ) $ reject $ fsep [ text "die Ziffer", toDoc z , text "liegt nicht im erlaubten Bereich." ] -- local variables: -- mode: haskell -- end;
florianpilz/autotool
src/Number/Base/Data.hs
gpl-2.0
2,067
0
22
712
656
330
326
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeSynonymInstances #-} module GrLang.CompilerSpec where import Control.Arrow ((&&&)) import Control.Monad import Control.Monad.Except (ExceptT) import Control.Monad.Trans import Data.Functor.Identity import Data.Map (Map) import qualified Data.Map as Map import Data.String import Data.Text (Text) import Data.Text.Prettyprint.Doc (Pretty (..)) import System.FilePath import Test.Hspec import Test.HUnit import Test.QuickCheck import Test.QuickCheck.Monadic import Abstract.Category import Abstract.Category.FindMorphism import Base.Annotation (Annotated (..), Located) import qualified Base.Annotation as Ann import Base.Isomorphic import Base.Valid import Category.TypedGraph () import qualified Data.DList as DList import qualified Data.Graphs as TypeGraph import Data.TypedGraph import qualified Data.TypedGraph.Morphism as TGraph import GrLang.AST import GrLang.Compiler import GrLang.Monad hiding (GrLangState (..)) import qualified GrLang.Monad as GrLang import GrLang.TestUtils import GrLang.Value import Rewriting.DPO.TypedGraph import qualified Util.Map as Map loc :: a -> Located a loc = A Nothing instance IsString a => IsString (Located a) where fromString = loc . fromString instance IsString a => IsString (Maybe a) where fromString = Just . fromString instance IsString Metadata where fromString s = Metadata (fromString s) Nothing compileSuccess :: FilePath -> IO (TypeGraph, Map Text (Located Value)) compileSuccess = runSuccess . ioCompile compileFailure :: FilePath -> IO Error compileFailure = runFailure . ioCompile shouldProduceNumberOfErrors :: FilePath -> Int -> Expectation shouldProduceNumberOfErrors path expected = do errors <- compileFailure path let obtained = length (DList.toList errors) unless (obtained == expected) . assertFailure $ "Expected " ++ show expected ++ " errors but got only " ++ show obtained ++ ":\n" ++ show (prettyError errors) ioCompile :: MonadIO m => FilePath -> ExceptT Error (GrLangT m) (TypeGraph, Map Text (Located Value)) ioCompile path = do compileFile $ "tests/GrLang/CompilerSpec" </> path (,) <$> getTypeGraph <*> getValueContext spec :: Spec spec = do let vcsTypes = makeTypeGraph ["Revision", "Deps"] [("MDeps", "Revision", "Deps"), ("Dep", "Deps", "Revision")] describe "normalizeTypeGraph" $ do let tgraphs = [ vcsTypes , TypeGraph.fromNodesAndEdges [ Node 0 "N", Node 1 "N" ] [ Edge 0 0 1 "E", Edge 1 0 1 "E" ] ] let ensureNotRepeated :: Show a => Map (Maybe Text) [a] -> Expectation ensureNotRepeated namesToIds | Prelude.null repeatedNames = return () | otherwise = expectationFailure $ "Repeated names: " ++ show repeatedNames where repeatedNames = filter ((>1) . length . snd) namesToIds' namesToIds' = [ (name, ids) | (Just name, ids) <- Map.toList namesToIds ] it "produces output equivalent to input" . forM_ tgraphs $ \tg -> normalizeTypeGraph tg `shouldBe` tg it "produces output without repeated names" . forM_ tgraphs $ \tg -> do let tg' = normalizeTypeGraph tg let nodeIdToName = map (nodeId &&& nodeExactName) (TypeGraph.nodes tg') ensureNotRepeated (Map.inverse nodeIdToName) let edgeIdToName = map (edgeId &&& edgeExactName) (TypeGraph.edges tg') ensureNotRepeated (Map.inverse edgeIdToName) it "doesn't change already normalized values" . forM_ tgraphs $ \tg -> do let tg' = normalizeTypeGraph tg let tg'' = normalizeTypeGraph tg' map nodeExactName (TypeGraph.nodes tg'') `shouldBe` map nodeExactName (TypeGraph.nodes tg') map edgeExactName (TypeGraph.edges tg'') `shouldBe` map edgeExactName (TypeGraph.edges tg') it "compiles a type graph" $ do (compiledTGraph, _) <- compileSuccess "vcs-types.grl" compiledTGraph `shouldBe` vcsTypes describe "compileGraph" $ do it "always compiles the result of generation" . property . monadic runIdentity $ do let tgraph = makeTypeGraph ["Revision", "Deps"] [ ("MDeps", "Revision", "Deps") , ("Dep", "Deps", "Revision") , ("Foo", "Revision", "Revision") ] -- TODO: replace explicit test cases with pseudo-random generation let testCases = map normalizeGraph [ fromNodesAndEdges tgraph [ (Node 0 "r1", 1), (Node 1 "r2", 1) , (Node 2 "d1", 2), (Node 3 "d2", 2) , (Node 4 "r3", 1) ] [ (Edge 0 0 2 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 1 3 . Just $ Metadata Nothing Nothing, 1) , (Edge 2 2 1 "d12", 2) , (Edge 3 3 4 . Just $ Metadata Nothing Nothing, 2) , (Edge 4 0 0 "f1", 3) , (Edge 5 0 0 "f2", 3) , (Edge 6 0 0 "f3", 3) ] , fromNodesAndEdges tgraph [ (Node 0 "n1", 1) , (Node 1 "n2", 2) ] [ (Edge 0 0 1 "e1", 1) , (Edge 1 1 0 "e2", 2) ] , fromNodesAndEdges tgraph [ (Node 0 "n", 1) , (Node 1 "n", 2) ] [ (Edge 0 0 1 "e", 1) , (Edge 1 0 1 "e", 1)] ] graph <- pick (elements testCases) testRoundTrip generateGraph compileGraph validate typeGraph tgraph graph it "compiles a graph" $ do (tgraph, values) <- compileSuccess "case1.grl" Map.keys values `shouldBe` ["g"] let VGraph g = Ann.drop (values Map.! "g") g `shouldBe` fromNodesAndEdges tgraph [ (Node 0 "r1", 1), (Node 1 "r2", 1) , (Node 2 "d1", 2), (Node 3 "d2", 2) , (Node 4 "r3", 1) ] [ (Edge 0 0 2 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 1 3 . Just $ Metadata Nothing Nothing, 1) , (Edge 2 2 1 "d12", 2) , (Edge 3 3 4 . Just $ Metadata Nothing Nothing, 2) , (Edge 4 0 0 "f1", 3) , (Edge 5 0 0 "f2", 3) , (Edge 6 0 0 "f3", 3) ] it "allows declaration of new types after graphs" $ do (tgraph, values) <- compileSuccess "case2.grl" Map.keys values `shouldBe` ["g"] let VGraph g = Ann.drop $ values Map.! "g" typeGraph g `shouldBe` tgraph validate g `shouldBe` IsValid it "has access to elements of transitive imports" $ do (tgraph, values) <- compileSuccess "case3/main.grl" Map.keys values `shouldBe` ["g"] let VGraph g = Ann.drop $ values Map.! "g" g `shouldBe` fromNodesAndEdges tgraph [ (Node 0 "n1", 1) , (Node 1 "n2", 1) ] [ (Edge 0 0 1 "e1", 1) , (Edge 1 0 1 "e2", 1) ] it "resolves imported modules relative to the current module's parent" $ do (tgraph, values) <- compileSuccess "case4/main.grl" Map.keys values `shouldBe` ["g"] let VGraph g = Ann.drop $ values Map.! "g" g `shouldBe` fromNodesAndEdges tgraph [ (Node 0 "n1", 1) , (Node 1 "n2", 1) ] [ (Edge 0 0 1 "e1", 1) , (Edge 1 0 1 "e2", 1) ] it "imports each module only once" $ do (tgraph, values) <- compileSuccess "case5/main.grl" Map.keys values `shouldBe` ["g"] let VGraph g = Ann.drop $ values Map.! "g" g `shouldBe` fromNodesAndEdges tgraph [ (Node 0 "n1", 1) , (Node 1 "n2", 1) ] [ (Edge 0 0 1 "e1", 1) , (Edge 1 0 1 "e2", 1) ] it "hides elements that weren't explicitly imported by the current module" $ do _ <- compileFailure "case6/main.grl" return () it "fails when source or target of edges have invalid types" $ "case7.grl" `shouldProduceNumberOfErrors` 2 describe "compileMorphism" $ do it "always compiles the result of generation" . property . monadic runIdentity $ do let tgraph = makeTypeGraph ["M", "N"] [("MM", "M", "M"), ("MN", "M", "N")] -- TODO: replace explicit test cases with pseudo-random generation let g1 = parseGraph tgraph " m1 m2 : M; n1 n2: N \ \ m1 -m12:MM-> m2; m2 -m22:MM-> m2 \ \ m1 -n11:MN-> n1; m2 -n22:MN-> n2 " let g2 = parseGraph tgraph " m1 m2 m3 m4 : M \ \ n1 n2 n3 n4 : N \ \ m1 -m11:MM-> m1; m1 -m12:MM-> m2; m1 -m13:MM-> m3; m1 -n11:MN-> n1 \ \ m2 -m22:MM-> m2; m2 -m23:MM-> m3; m2 -n22:MN-> n2; m2 -n12:MN-> n3 \ \ m3 -m33:MM-> m3; m3 -m34:MM-> m4; m3 -n34:MN-> n4 \ \ m4 -m44:MM-> m4; m4 -m41:MM-> m1; m4 -n44:MN-> n4" let testCases = findAllMorphisms g1 g2 :: [GrMorphism] -- This should generate around 14 morphisms morph <- pick (elements testCases) testRoundTrip generateMorphism (compileMorphism Nothing g1 g2) validate (typeGraph . domain) tgraph morph it "compiles a morphism" $ do (_, values) <- compileSuccess "case25.grl" Map.keys values `shouldBe` ["f", "g", "h"] let VMorph f = Ann.drop $ values Map.! "f" VGraph g = Ann.drop $ values Map.! "g" VGraph h = Ann.drop $ values Map.! "h" validate f `shouldBe` IsValid domain f `shouldBe` g codomain f `shouldBe` h TGraph.applyNodeId f 0 `shouldBe` Just 0 TGraph.applyNodeId f 1 `shouldBe` Just 1 TGraph.applyEdgeId f 0 `shouldBe` Just 0 TGraph.applyEdgeId f 1 `shouldBe` Just 0 it "fails when the named domain or codomain is unknown" $ "case27.grl" `shouldProduceNumberOfErrors` 2 it "fails when a domain or codomain is missing" $ "case28.grl" `shouldProduceNumberOfErrors` 2 it "fails when the mapping doesn't preserve types" $ "case30.grl" `shouldProduceNumberOfErrors` 4 it "fails when the mapping doesn't preserve incidence" $ "case32.grl" `shouldProduceNumberOfErrors` 3 it "fails when the mapping involves unknown elements" $ "case31.grl" `shouldProduceNumberOfErrors` 4 it "fails when the mapping isn't total" $ "case33.grl" `shouldProduceNumberOfErrors` 2 describe "compileRule" $ do it "always compiles the result of generation" . property . monadic runIdentity $ do let tgraph = makeTypeGraph ["N"] [("E","N","N")] -- TODO: replace explicit test cases with pseudo-random generation let testCases = [ [ DeclMatch [DeclNodes ["n1"] "N"] , DeclMatch [DeclEdges "n1" [(AnonymousEdge, "E")] "n1"] , DeclMatch [DeclNodes ["n2"] "N", DeclEdges "n1" [(AnonymousEdge, "E")] "n2"] ] , [ DeclMatch [DeclNodes ["n1"] "N"] , DeclForbid Nothing [DeclNodes ["n3"] "N"] , DeclForbid "nodeAndEdge" [DeclNodes ["n2"] "N", DeclEdges "n1" [(AnonymousEdge, "E")] "n2"] ] , [ DeclCreate [DeclNodes ["n1"] "N"] , DeclCreate [DeclEdges "n1" [(AnonymousEdge, "E")] "n1"] , DeclCreate [DeclNodes ["n2"] "N", DeclEdges "n1" [(AnonymousEdge, "E")] "n2"] ] , [ DeclMatch [DeclNodes ["n1"] "N"] , DeclMatch [DeclEdges "n1" [(AnonymousEdge, "E")] "n1"] , DeclMatch [DeclNodes ["n2", "n3"] "N", DeclEdges "n1" [(AnonymousEdge, "E")] "n2"] , DeclDelete ["n1", "n3"] WithMatchedEdges , DeclDelete ["n2"] Isolated ] , [ DeclMatch [DeclNodes ["n1"] "N"] , DeclMatch [DeclEdges "n1" [(AnonymousEdge, "E")] "n1"] , DeclMatch [DeclNodes ["n2"] "N", DeclEdges "n1" [(AnonymousEdge, "E")] "n2"] , DeclClone "n1" ["n1'"] , DeclClone "n2" ["n3", "n4", "n5"] ] , [ DeclMatch [DeclNodes ["n1"] "N"] , DeclClone "n1" ["n1'"] ] , [ DeclMatch [DeclNodes ["n1","n2","n3","n4","n5"] "N"] , DeclJoin ["n1", "n2"] "n" , DeclJoin ["n3", "n4", "n5"] Nothing ] ] decls <- pick (elements testCases) let Right rule = evalGrLang (initState tgraph) (compileRule decls) testRoundTrip generateRule compileRule validateRule (typeGraph . leftObject) tgraph rule it "compiles a no-op rule" $ do (tgraph, values) <- compileSuccess "case8.grl" Map.keys values `shouldBe` ["r"] let VRule r = Ann.drop $ values Map.! "r" assertValidRule r assertEqual "LHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 2 "d1", 2) , (Node 3 "d2", 2) ] [ (Edge 0 0 2 "r1", 1) , (Edge 1 1 3 "r2", 1) ]) (leftObject r) assertBool "lhs morphism is iso" (isIsomorphism $ leftMorphism r) assertBool "rhs morphism is iso" (isIsomorphism $ rightMorphism r) assertEqual "NACs" [] (nacs r) it "compiles a rule with deletion" $ do (tgraph, values) <- compileSuccess "case9.grl" Map.keys values `shouldBe` ["r"] let VRule r = Ann.drop $ values Map.! "r" assertValidRule r assertEqual "LHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 2 "d1", 2) , (Node 3 "d2", 2) ] [ (Edge 0 0 2 "r1", 1) , (Edge 1 1 3 "r2", 1) ]) (leftObject r) assertEqual "RHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 3 "d2", 2) ] [ ]) (rightObject r) assertBool "lhs morphism is mono" (isMonic $ leftMorphism r) assertBool "lhs morphism is not iso" (not . isIsomorphism $ leftMorphism r) assertBool "rhs morphism is iso" (isIsomorphism $ rightMorphism r) assertEqual "NACs" [] (nacs r) it "compiles a rule with creation" $ do (tgraph, values) <- compileSuccess "case10.grl" Map.keys values `shouldBe` ["commit"] let VRule r = Ann.drop $ values Map.! "commit" assertValidRule r assertEqual "LHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "d1", 2) ] [ (Edge 0 0 1 . Just $ Metadata Nothing Nothing, 1) ]) (leftObject r) assertEqual "RHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "d1", 2) , (Node 2 "r2", 1) , (Node 3 "d2", 2) ] [ (Edge 0 0 1 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 2 3 . Just $ Metadata Nothing Nothing, 1) , (Edge 2 3 0 . Just $ Metadata Nothing Nothing, 2) ]) (rightObject r) assertBool "lhs morphism is iso" (isIsomorphism $ leftMorphism r) assertBool "rhs morphism is monic" (isMonic $ rightMorphism r) assertBool "rhs morphism is not iso" (not . isIsomorphism $ rightMorphism r) assertEqual "NACs" [] (nacs r) it "compiles a rule with creation and cloning" $ do (tgraph, values) <- compileSuccess "case11.grl" Map.keys values `shouldBe` ["commit"] let VRule r = Ann.drop $ values Map.! "commit" assertValidRule r assertEqual "LHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "d1", 2) ] [ (Edge 0 0 1 . Just $ Metadata Nothing Nothing, 1) ]) (leftObject r) assertEqual "RHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "d1", 2) , (Node 3 "r2", 1) , (Node 2 "d2", 2) ] [ (Edge 0 0 1 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 3 2 . Just $ Metadata Nothing Nothing, 1) , (Edge 2 2 0 . Just $ Metadata Nothing Nothing, 2) ]) (rightObject r) assertEqual "LHS morphism applied to d2" (Just 1) (TGraph.applyNodeId (leftMorphism r) 2) assertBool "lhs morphism is epic" (isEpic $ leftMorphism r) assertBool "lhs morphism is not monic" (not . isMonic $ leftMorphism r) assertBool "rhs morphism is monic" (isMonic $ rightMorphism r) assertBool "rhs morphism is not iso" (not . isIsomorphism $ rightMorphism r) assertEqual "NACs" [] (nacs r) it "compiles a rule with joining" $ do (tgraph, values) <- compileSuccess "case19.grl" Map.keys values `shouldBe` ["merge"] let VRule r = Ann.drop $ values Map.! "merge" assertValidRule r assertEqual "LHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 2 "d1", 2) , (Node 3 "d2", 2) ] [ (Edge 0 0 2 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 1 3 . Just $ Metadata Nothing Nothing, 1) ]) (leftObject r) assertEqual "interface" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 2 "d1", 2) , (Node 3 "d2", 2) , (Node 4 "d1'", 2) , (Node 5 "d2'", 2)] [ (Edge 0 0 2 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 1 3 . Just $ Metadata Nothing Nothing, 1) ]) (interfaceObject r) assertEqual "RHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 2 "d1", 2) , (Node 3 "d2", 2) , (Node 6 "d3", 2) , (Node 7 "r3", 1)] [ (Edge 0 0 2 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 1 3 . Just $ Metadata Nothing Nothing, 1) , (Edge 2 7 6 . Just $ Metadata Nothing Nothing, 1) , (Edge 3 6 0 . Just $ Metadata Nothing Nothing, 2) , (Edge 4 6 1 . Just $ Metadata Nothing Nothing, 2) ]) (rightObject r) assertEqual "LHS morphism applied to d1'" (Just 2) (TGraph.applyNodeId (leftMorphism r) 4) assertEqual "LHS morphism applied to d2'" (Just 3) (TGraph.applyNodeId (leftMorphism r) 5) assertEqual "RHS morphism applied to d1'" (Just 6) (TGraph.applyNodeId (rightMorphism r) 4) assertEqual "RHS morphism applied to d2'" (Just 6) (TGraph.applyNodeId (rightMorphism r) 5) assertBool "lhs morphism is not monic" (not . isMonic $ leftMorphism r) assertBool "lhs morphism is epic" (isEpic $ leftMorphism r) assertBool "rhs morphism is not monic" (not . isMonic $ rightMorphism r) assertBool "rhs morphism is not epic" (not . isEpic $ rightMorphism r) it "compiles a no-op rule with NACs" $ do (tgraph, values) <- compileSuccess "case12.grl" Map.keys values `shouldBe` ["rebaseStart"] let VRule r = Ann.drop $ values Map.! "rebaseStart" assertValidRule r assertEqual "LHS" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 2 "rRoot", 1) , (Node 3 "d1", 2) , (Node 4 "d2", 2) , (Node 5 "dRoot", 2) ] [ (Edge 0 0 3 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 1 4 . Just $ Metadata Nothing Nothing, 1) , (Edge 2 2 5 . Just $ Metadata Nothing Nothing, 1) , (Edge 3 3 2 . Just $ Metadata Nothing Nothing, 2) , (Edge 4 4 2 . Just $ Metadata Nothing Nothing, 2) ]) (leftObject r) assertBool "lhs morphism is iso" (isIsomorphism $ leftMorphism r) assertBool "rhs morphism is iso" (isIsomorphism $ rightMorphism r) assertEqual "number of NACs" 2 (length $ nacs r) let [n1, n2] = nacs r assertEqual "NAC 1" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 2 "rRoot", 1) , (Node 3 "d1", 2) , (Node 4 "d2", 2) , (Node 5 "dRoot", 2) , (Node 6 "rRoot'", 1) , (Node 7 "dRoot'", 2) ] [ (Edge 0 0 3 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 1 4 . Just $ Metadata Nothing Nothing, 1) , (Edge 2 2 5 . Just $ Metadata Nothing Nothing, 1) , (Edge 3 3 2 . Just $ Metadata Nothing Nothing, 2) , (Edge 4 4 2 . Just $ Metadata Nothing Nothing, 2) , (Edge 5 6 7 . Just $ Metadata Nothing Nothing, 1) , (Edge 6 3 6 . Just $ Metadata Nothing Nothing, 2) , (Edge 7 4 6 . Just $ Metadata Nothing Nothing, 2) , (Edge 8 7 2 . Just $ Metadata Nothing Nothing, 2) ]) (codomain n1) assertEqual "NAC 2" (fromNodesAndEdges tgraph [ (Node 0 "r1", 1) , (Node 1 "r2", 1) , (Node 2 "rRoot", 1) , (Node 3 "d1", 2) , (Node 4 "d2", 2) , (Node 5 "dRoot", 2) , (Node 6 "d3", 2) ] [ (Edge 0 0 3 . Just $ Metadata Nothing Nothing, 1) , (Edge 1 1 4 . Just $ Metadata Nothing Nothing, 1) , (Edge 2 2 5 . Just $ Metadata Nothing Nothing, 1) , (Edge 3 3 2 . Just $ Metadata Nothing Nothing, 2) , (Edge 4 4 2 . Just $ Metadata Nothing Nothing, 2) , (Edge 5 6 0 . Just $ Metadata Nothing Nothing, 2) ]) (codomain n2) it "fails when deleting unknown elements" $ "case13.grl" `shouldProduceNumberOfErrors` 1 it "fails when cloning unknown elements" $ "case14.grl" `shouldProduceNumberOfErrors` 1 it "fails when joining unknown elements" $ "case23.grl" `shouldProduceNumberOfErrors` 1 it "fails when create has a name clash" $ "case15.grl" `shouldProduceNumberOfErrors` 3 it "fails when clone has a name clash" $ "case16.grl" `shouldProduceNumberOfErrors` 3 it "fails when join has a name clash" $ "case24.grl" `shouldProduceNumberOfErrors` 1 it "fails when deleting leaves dangling edges" $ "case17.grl" `shouldProduceNumberOfErrors` 2 it "fails when source or target of created edge have invalid type" $ "case18.grl" `shouldProduceNumberOfErrors` 2 it "fails when joining nodes of different types" $ "case20.grl" `shouldProduceNumberOfErrors` 1 it "fails when joining edges of different types, sources or targets" $ "case21.grl" `shouldProduceNumberOfErrors` 3 it "fails when joining a node with an edge" $ "case22.grl" `shouldProduceNumberOfErrors` 1 testRoundTrip :: (Iso val, Valid val, Show val, Pretty ast, Show ast, Monad m) => (val -> ast) -> (ast -> ExceptT Error (GrLangT Identity) val) -> (val -> ValidationResult) -> (val -> TypeGraph) -> TypeGraph -> val -> PropertyM m () testRoundTrip generate compile validateValue getTypeGraph tgraph value = do let generated = generate value monitor (counterexample . show . pretty $ generated) monitor (counterexample . show $ value) case validateValue value of IsInvalid errors -> stop . counterexample "Invalid value!" $ counterexample (show errors) False IsValid -> return () let recompiled = evalGrLang (initState tgraph) (lift (GrLang.unsafeMakeVisible "<test>") >> compile generated) case recompiled of Left error -> stop . counterexample "Cannot compile generated value!" $ counterexample (show . prettyError $ error) False Right result -> do when (getTypeGraph result /= tgraph) . stop . counterexample "Invalid parsed type graph!" $ counterexample (show (getTypeGraph result, tgraph)) False stop $ case validateValue result of IsInvalid errors -> counterexample "Compilation created invalid value!" $ counterexample (show errors) False IsValid -> --counterexample (show . pretty $ generate result) . counterexample (show value) . counterexample "Result not isomorphic to value!" $ result ~= value -- TODO: make a proper SqPO.Production type with its own validation validateRule :: (Eq (Obj morph), Category morph, Valid morph) => Production morph -> ValidationResult validateRule (Production l r nacs) = mconcat $ [ withContext "left morphism" (validate l) , withContext "right morphism" (validate r) , ensure (domain l == domain r) "The domains of the left and right morphisms aren't the same" ] ++ zipWith validateNac nacs ([1..] :: [Int]) where validateNac nac index = mconcat [ withContext ("NAC #" ++ show index) (validate nac) , ensure (codomain l == domain nac) ("The domain of NAC #" ++ show index ++ " is not the left side of the production") ] assertValidRule :: (Category mor, Valid mor, Valid (Obj mor), Eq (Obj mor)) => Production mor -> IO () assertValidRule rule = assertEqual "rule validation" IsValid (validateRule rule)
rodrigo-machado/verigraph
tests/GrLang/CompilerSpec.hs
gpl-3.0
25,305
59
29
8,090
7,977
4,142
3,835
515
4
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} -- Derived from AWS service descriptions, licensed under Apache 2.0. -- | -- Module : Network.AWS.RDS.AddSourceIdentifierToSubscription -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Adds a source identifier to an existing RDS event notification -- subscription. -- -- /See:/ <http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_AddSourceIdentifierToSubscription.html AWS API Reference> for AddSourceIdentifierToSubscription. module Network.AWS.RDS.AddSourceIdentifierToSubscription ( -- * Creating a Request addSourceIdentifierToSubscription , AddSourceIdentifierToSubscription -- * Request Lenses , asitsSubscriptionName , asitsSourceIdentifier -- * Destructuring the Response , addSourceIdentifierToSubscriptionResponse , AddSourceIdentifierToSubscriptionResponse -- * Response Lenses , asitsrsEventSubscription , asitsrsResponseStatus ) where import Network.AWS.Prelude import Network.AWS.RDS.Types import Network.AWS.RDS.Types.Product import Network.AWS.Request import Network.AWS.Response -- | -- -- /See:/ 'addSourceIdentifierToSubscription' smart constructor. data AddSourceIdentifierToSubscription = AddSourceIdentifierToSubscription' { _asitsSubscriptionName :: !Text , _asitsSourceIdentifier :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AddSourceIdentifierToSubscription' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asitsSubscriptionName' -- -- * 'asitsSourceIdentifier' addSourceIdentifierToSubscription :: Text -- ^ 'asitsSubscriptionName' -> Text -- ^ 'asitsSourceIdentifier' -> AddSourceIdentifierToSubscription addSourceIdentifierToSubscription pSubscriptionName_ pSourceIdentifier_ = AddSourceIdentifierToSubscription' { _asitsSubscriptionName = pSubscriptionName_ , _asitsSourceIdentifier = pSourceIdentifier_ } -- | The name of the RDS event notification subscription you want to add a -- source identifier to. asitsSubscriptionName :: Lens' AddSourceIdentifierToSubscription Text asitsSubscriptionName = lens _asitsSubscriptionName (\ s a -> s{_asitsSubscriptionName = a}); -- | The identifier of the event source to be added. An identifier must begin -- with a letter and must contain only ASCII letters, digits, and hyphens; -- it cannot end with a hyphen or contain two consecutive hyphens. -- -- Constraints: -- -- - If the source type is a DB instance, then a 'DBInstanceIdentifier' -- must be supplied. -- - If the source type is a DB security group, a 'DBSecurityGroupName' -- must be supplied. -- - If the source type is a DB parameter group, a 'DBParameterGroupName' -- must be supplied. -- - If the source type is a DB snapshot, a 'DBSnapshotIdentifier' must -- be supplied. asitsSourceIdentifier :: Lens' AddSourceIdentifierToSubscription Text asitsSourceIdentifier = lens _asitsSourceIdentifier (\ s a -> s{_asitsSourceIdentifier = a}); instance AWSRequest AddSourceIdentifierToSubscription where type Rs AddSourceIdentifierToSubscription = AddSourceIdentifierToSubscriptionResponse request = postQuery rDS response = receiveXMLWrapper "AddSourceIdentifierToSubscriptionResult" (\ s h x -> AddSourceIdentifierToSubscriptionResponse' <$> (x .@? "EventSubscription") <*> (pure (fromEnum s))) instance ToHeaders AddSourceIdentifierToSubscription where toHeaders = const mempty instance ToPath AddSourceIdentifierToSubscription where toPath = const "/" instance ToQuery AddSourceIdentifierToSubscription where toQuery AddSourceIdentifierToSubscription'{..} = mconcat ["Action" =: ("AddSourceIdentifierToSubscription" :: ByteString), "Version" =: ("2014-10-31" :: ByteString), "SubscriptionName" =: _asitsSubscriptionName, "SourceIdentifier" =: _asitsSourceIdentifier] -- | /See:/ 'addSourceIdentifierToSubscriptionResponse' smart constructor. data AddSourceIdentifierToSubscriptionResponse = AddSourceIdentifierToSubscriptionResponse' { _asitsrsEventSubscription :: !(Maybe EventSubscription) , _asitsrsResponseStatus :: !Int } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'AddSourceIdentifierToSubscriptionResponse' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'asitsrsEventSubscription' -- -- * 'asitsrsResponseStatus' addSourceIdentifierToSubscriptionResponse :: Int -- ^ 'asitsrsResponseStatus' -> AddSourceIdentifierToSubscriptionResponse addSourceIdentifierToSubscriptionResponse pResponseStatus_ = AddSourceIdentifierToSubscriptionResponse' { _asitsrsEventSubscription = Nothing , _asitsrsResponseStatus = pResponseStatus_ } -- | Undocumented member. asitsrsEventSubscription :: Lens' AddSourceIdentifierToSubscriptionResponse (Maybe EventSubscription) asitsrsEventSubscription = lens _asitsrsEventSubscription (\ s a -> s{_asitsrsEventSubscription = a}); -- | The response status code. asitsrsResponseStatus :: Lens' AddSourceIdentifierToSubscriptionResponse Int asitsrsResponseStatus = lens _asitsrsResponseStatus (\ s a -> s{_asitsrsResponseStatus = a});
fmapfmapfmap/amazonka
amazonka-rds/gen/Network/AWS/RDS/AddSourceIdentifierToSubscription.hs
mpl-2.0
6,032
0
13
1,111
638
388
250
84
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift -- -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- module Module2_Types where import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..), Eq, Show, Ord, concat, error, fromIntegral, fromEnum, length, map, maybe, not, null, otherwise, return, show, toEnum, enumFromTo, Bounded, minBound, maxBound, seq, (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>)) import qualified Control.Applicative as Applicative (ZipList(..)) import Control.Applicative ( (<*>) ) import qualified Control.DeepSeq as DeepSeq import qualified Control.Exception as Exception import qualified Control.Monad as Monad ( liftM, ap, when ) import qualified Data.ByteString.Lazy as BS import Data.Functor ( (<$>) ) import qualified Data.Hashable as Hashable import qualified Data.Int as Int import qualified Data.Maybe as Maybe (catMaybes) import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as LT import qualified Data.Typeable as Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) ) import qualified Test.QuickCheck as QuickCheck ( elements ) import qualified Thrift import qualified Thrift.Types as Types import qualified Thrift.Serializable as Serializable import qualified Thrift.Arbitraries as Arbitraries import qualified Module0_Types as Module0_Types import qualified Module1_Types as Module1_Types data Struct = Struct { struct_first :: Module0_Types.Struct , struct_second :: Module1_Types.Struct } deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable Struct where encode = encode_Struct decode = decode_Struct instance Hashable.Hashable Struct where hashWithSalt salt record = salt `Hashable.hashWithSalt` struct_first record `Hashable.hashWithSalt` struct_second record instance DeepSeq.NFData Struct where rnf _record0 = DeepSeq.rnf (struct_first _record0) `seq` DeepSeq.rnf (struct_second _record0) `seq` () instance Arbitrary.Arbitrary Struct where arbitrary = Monad.liftM Struct (Arbitrary.arbitrary) `Monad.ap`(Arbitrary.arbitrary) shrink obj | obj == default_Struct = [] | otherwise = Maybe.catMaybes [ if obj == default_Struct{struct_first = struct_first obj} then Nothing else Just $ default_Struct{struct_first = struct_first obj} , if obj == default_Struct{struct_second = struct_second obj} then Nothing else Just $ default_Struct{struct_second = struct_second obj} ] from_Struct :: Struct -> Types.ThriftVal from_Struct record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [ (\_v3 -> Just (1, ("first",Module0_Types.from_Struct _v3))) $ struct_first record , (\_v3 -> Just (2, ("second",Module1_Types.from_Struct _v3))) $ struct_second record ] write_Struct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Struct -> IO () write_Struct oprot record = Thrift.writeVal oprot $ from_Struct record encode_Struct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> Struct -> BS.ByteString encode_Struct oprot record = Thrift.serializeVal oprot $ from_Struct record to_Struct :: Types.ThriftVal -> Struct to_Struct (Types.TStruct fields) = Struct{ struct_first = maybe (struct_first default_Struct) (\(_,_val5) -> (case _val5 of {Types.TStruct _val6 -> (Module0_Types.to_Struct (Types.TStruct _val6)); _ -> error "wrong type"})) (Map.lookup (1) fields), struct_second = maybe (struct_second default_Struct) (\(_,_val5) -> (case _val5 of {Types.TStruct _val7 -> (Module1_Types.to_Struct (Types.TStruct _val7)); _ -> error "wrong type"})) (Map.lookup (2) fields) } to_Struct _ = error "not a struct" read_Struct :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO Struct read_Struct iprot = to_Struct <$> Thrift.readVal iprot (Types.T_STRUCT typemap_Struct) decode_Struct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> Struct decode_Struct iprot bs = to_Struct $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_Struct) bs typemap_Struct :: Types.TypeMap typemap_Struct = Map.fromList [("first",(1,(Types.T_STRUCT Module0_Types.typemap_Struct))),("second",(2,(Types.T_STRUCT Module1_Types.typemap_Struct)))] default_Struct :: Struct default_Struct = Struct{ struct_first = Module0_Types.default_Struct, struct_second = Module1_Types.default_Struct} data BigStruct = BigStruct { bigStruct_s :: Module2_Types.Struct , bigStruct_id :: Int.Int32 } deriving (Show,Eq,Typeable.Typeable) instance Serializable.ThriftSerializable BigStruct where encode = encode_BigStruct decode = decode_BigStruct instance Hashable.Hashable BigStruct where hashWithSalt salt record = salt `Hashable.hashWithSalt` bigStruct_s record `Hashable.hashWithSalt` bigStruct_id record instance DeepSeq.NFData BigStruct where rnf _record8 = DeepSeq.rnf (bigStruct_s _record8) `seq` DeepSeq.rnf (bigStruct_id _record8) `seq` () instance Arbitrary.Arbitrary BigStruct where arbitrary = Monad.liftM BigStruct (Arbitrary.arbitrary) `Monad.ap`(Arbitrary.arbitrary) shrink obj | obj == default_BigStruct = [] | otherwise = Maybe.catMaybes [ if obj == default_BigStruct{bigStruct_s = bigStruct_s obj} then Nothing else Just $ default_BigStruct{bigStruct_s = bigStruct_s obj} , if obj == default_BigStruct{bigStruct_id = bigStruct_id obj} then Nothing else Just $ default_BigStruct{bigStruct_id = bigStruct_id obj} ] from_BigStruct :: BigStruct -> Types.ThriftVal from_BigStruct record = Types.TStruct $ Map.fromList $ Maybe.catMaybes [ (\_v11 -> Just (1, ("s",Module2_Types.from_Struct _v11))) $ bigStruct_s record , (\_v11 -> Just (2, ("id",Types.TI32 _v11))) $ bigStruct_id record ] write_BigStruct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BigStruct -> IO () write_BigStruct oprot record = Thrift.writeVal oprot $ from_BigStruct record encode_BigStruct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BigStruct -> BS.ByteString encode_BigStruct oprot record = Thrift.serializeVal oprot $ from_BigStruct record to_BigStruct :: Types.ThriftVal -> BigStruct to_BigStruct (Types.TStruct fields) = BigStruct{ bigStruct_s = maybe (bigStruct_s default_BigStruct) (\(_,_val13) -> (case _val13 of {Types.TStruct _val14 -> (Module2_Types.to_Struct (Types.TStruct _val14)); _ -> error "wrong type"})) (Map.lookup (1) fields), bigStruct_id = maybe (bigStruct_id default_BigStruct) (\(_,_val13) -> (case _val13 of {Types.TI32 _val15 -> _val15; _ -> error "wrong type"})) (Map.lookup (2) fields) } to_BigStruct _ = error "not a struct" read_BigStruct :: (Thrift.Transport t, Thrift.Protocol p) => p t -> IO BigStruct read_BigStruct iprot = to_BigStruct <$> Thrift.readVal iprot (Types.T_STRUCT typemap_BigStruct) decode_BigStruct :: (Thrift.Protocol p, Thrift.Transport t) => p t -> BS.ByteString -> BigStruct decode_BigStruct iprot bs = to_BigStruct $ Thrift.deserializeVal iprot (Types.T_STRUCT typemap_BigStruct) bs typemap_BigStruct :: Types.TypeMap typemap_BigStruct = Map.fromList [("s",(1,(Types.T_STRUCT Module2_Types.typemap_Struct))),("id",(2,Types.T_I32))] default_BigStruct :: BigStruct default_BigStruct = BigStruct{ bigStruct_s = Module2_Types.default_Struct, bigStruct_id = 0}
sinjar666/fbthrift
thrift/compiler/test/fixtures/qualified/gen-hs/Module2_Types.hs
apache-2.0
7,963
0
18
1,208
2,373
1,340
1,033
126
3
{-# LANGUAGE TemplateHaskell, RankNTypes, FlexibleContexts #-} {-| Pure functions for manipulating reservations of temporary objects NOTE: Reservations aren't released specifically, they're just all released at the end of a job. This could be improved in the future. -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.WConfd.TempRes ( TempRes , mkTempRes , TempResState(..) , emptyTempResState , NodeUUID , InstanceUUID , DiskUUID , NetworkUUID , DRBDMinor , DRBDMap , trsDRBDL , computeDRBDMap , computeDRBDMap' , allocateDRBDMinor , releaseDRBDMinors , MAC , generateMAC , reserveMAC , generateDRBDSecret , reserveLV , IPv4ResAction(..) , IPv4Reservation(..) , reserveIp , releaseIp , generateIp , commitReleaseIp , commitReservedIps , listReservedIps , dropAllReservations , isReserved , reserve , dropReservationsFor , reserved ) where import Control.Lens.At import Control.Monad.Error import Control.Monad.State import Control.Monad.Trans.Maybe import qualified Data.ByteString as BS import qualified Data.ByteString.UTF8 as UTF8 import qualified Data.Foldable as F import Data.Maybe import Data.Map (Map) import qualified Data.Map as M import Data.Monoid import qualified Data.Semigroup as Sem import qualified Data.Set as S import System.Random import qualified Text.JSON as J import Ganeti.BasicTypes import Ganeti.Config import qualified Ganeti.Constants as C import Ganeti.Errors import qualified Ganeti.JSON as J import Ganeti.Lens import qualified Ganeti.Network as N import Ganeti.Locking.Locks (ClientId) import Ganeti.Logging import Ganeti.Objects import Ganeti.THH import Ganeti.Objects.Lens (configNetworksL) import Ganeti.Utils import Ganeti.Utils.Monad import Ganeti.Utils.Random import qualified Ganeti.Utils.MultiMap as MM -- * The main reservation state -- ** Aliases to make types more meaningful: type NodeUUID = BS.ByteString type InstanceUUID = BS.ByteString type DiskUUID = BS.ByteString type NetworkUUID = BS.ByteString type DRBDMinor = Int -- | A map of the usage of DRBD minors type DRBDMap = Map NodeUUID (Map DRBDMinor DiskUUID) -- | A map of the usage of DRBD minors with possible duplicates type DRBDMap' = Map NodeUUID (Map DRBDMinor [DiskUUID]) -- * The state data structure -- | Types of IPv4 reservation actions. data IPv4ResAction = IPv4Reserve | IPv4Release deriving (Eq, Ord, Show, Bounded, Enum) instance J.JSON IPv4ResAction where showJSON IPv4Reserve = J.JSString . J.toJSString $ C.reserveAction showJSON IPv4Release = J.JSString . J.toJSString $ C.releaseAction readJSON = J.readEitherString >=> \s -> case () of _ | s == C.reserveAction -> return IPv4Reserve | s == C.releaseAction -> return IPv4Release | otherwise -> fail $ "Invalid IP reservation action: " ++ s -- | The values stored in the IPv4 reservation table. data IPv4Reservation = IPv4Res { ipv4ResAction :: IPv4ResAction , ipv4ResNetwork :: NetworkUUID , ipv4ResAddr :: Ip4Address } deriving (Eq, Ord, Show) instance J.JSON IPv4Reservation where -- Notice that addr and net are in a different order, to be compatible -- with the original Python representation (while it's used). showJSON (IPv4Res a net addr) = J.showJSON (a, addr, net) readJSON = fmap (\(a, addr, net) -> IPv4Res a net addr) . J.readJSON -- | A polymorphic data structure for managing temporary resources assigned -- to jobs. newtype TempRes j a = TempRes { getTempRes :: MM.MultiMap j a } deriving (Eq, Ord, Show) instance (Ord j, Ord a) => Sem.Semigroup (TempRes j a) where (TempRes x) <> (TempRes y) = TempRes $ x <> y instance (Ord j, Ord a) => Monoid (TempRes j a) where mempty = TempRes mempty mappend = (Sem.<>) instance (J.JSON j, Ord j, J.JSON a, Ord a) => J.JSON (TempRes j a) where showJSON = J.showJSON . getTempRes readJSON = liftM TempRes . J.readJSON -- | Create a temporary reservations from a given multi-map. mkTempRes :: MM.MultiMap j a -> TempRes j a mkTempRes = TempRes -- | The state of the temporary reservations $(buildObject "TempResState" "trs" [ simpleField "dRBD" [t| DRBDMap |] , simpleField "mACs" [t| TempRes ClientId MAC |] , simpleField "dRBDSecrets" [t| TempRes ClientId DRBDSecret |] , simpleField "lVs" [t| TempRes ClientId LogicalVolume |] , simpleField "iPv4s" [t| TempRes ClientId IPv4Reservation |] ]) emptyTempResState :: TempResState emptyTempResState = TempResState M.empty mempty mempty mempty mempty $(makeCustomLenses ''TempResState) -- ** Utility functions -- | Issues a reservation error. resError :: (MonadError GanetiException m) => String -> m a resError = throwError . ReservationError -- | Converts 'GenericError' into a 'ReservationError'. toResError :: (MonadError GanetiException m) => m a -> m a toResError = flip catchError (throwError . f) where f (GenericError msg) = ReservationError msg f e = e -- | Filter values from the nested map and remove any nested maps -- that become empty. filterNested :: (Ord a, Ord b) => (c -> Bool) -> Map a (Map b c) -> Map a (Map b c) filterNested p = M.filter (not . M.null) . fmap (M.filter p) -- | Converts a lens that works on maybe values into a lens that works -- on regular ones. A missing value on the input is replaced by -- 'mempty'. -- The output is is @Just something@ iff @something /= mempty@. maybeLens :: (Monoid a, Monoid b, Eq b) => Lens s t (Maybe a) (Maybe b) -> Lens s t a b maybeLens l f = l (fmap (mfilter (/= mempty) . Just) . f . fromMaybe mempty) -- * DRBD functions -- | Compute the map of used DRBD minor/nodes, including possible -- duplicates. -- An error is returned if the configuration isn't consistent -- (for example if a referenced disk is missing etc.). computeDRBDMap' :: (MonadError GanetiException m) => ConfigData -> TempResState -> m DRBDMap' computeDRBDMap' cfg trs = flip execStateT (fmap (fmap (: [])) (trsDRBD trs)) $ F.forM_ (configDisks cfg) addMinors where -- | Creates a lens for modifying the list of instances nodeMinor :: NodeUUID -> DRBDMinor -> Lens' DRBDMap' [DiskUUID] nodeMinor node minor = maybeLens (at node) . maybeLens (at minor) -- | Adds minors of a disk within the state monad addMinors disk = do let minors = getDrbdMinorsForDisk disk forM_ minors $ \(minor, node) -> nodeMinor (UTF8.fromString node) minor %= (UTF8.fromString (uuidOf disk) :) -- | Compute the map of used DRBD minor/nodes. -- Report any duplicate entries as an error. -- -- Unlike 'computeDRBDMap'', includes entries for all nodes, even if empty. computeDRBDMap :: (MonadError GanetiException m) => ConfigData -> TempResState -> m DRBDMap computeDRBDMap cfg trs = do m <- computeDRBDMap' cfg trs let dups = filterNested ((>= 2) . length) m unless (M.null dups) . resError $ "Duplicate DRBD ports detected: " ++ show (M.toList $ fmap M.toList dups) return $ fmap (fmap head . M.filter ((== 1) . length)) m `M.union` (fmap (const mempty) . J.fromContainer . configNodes $ cfg) -- Allocate a drbd minor. -- -- The free minor will be automatically computed from the existing devices. -- A node can not be given multiple times. -- The result is the list of minors, in the same order as the passed nodes. allocateDRBDMinor :: (MonadError GanetiException m, MonadState TempResState m) => ConfigData -> DiskUUID -> [NodeUUID] -> m [DRBDMinor] allocateDRBDMinor cfg disk nodes = do unless (nodes == ordNub nodes) . resError $ "Duplicate nodes detected in list '" ++ show nodes ++ "'" dMap <- computeDRBDMap' cfg =<< get let usedMap = fmap M.keysSet dMap let alloc :: S.Set DRBDMinor -> Map DRBDMinor DiskUUID -> (DRBDMinor, Map DRBDMinor DiskUUID) alloc used m = let k = findFirst 0 (M.keysSet m `S.union` used) in (k, M.insert k disk m) forM nodes $ \node -> trsDRBDL . maybeLens (at node) %%= alloc (M.findWithDefault mempty node usedMap) -- Release temporary drbd minors allocated for a given disk using -- 'allocateDRBDMinor'. releaseDRBDMinors :: (MonadState TempResState m) => DiskUUID -> m () releaseDRBDMinors disk = trsDRBDL %= filterNested (/= disk) -- * Other temporary resources -- | Tests if a given value is reserved for a given job. isReserved :: (Ord a, Ord j) => a -> TempRes j a -> Bool isReserved x = MM.elem x . getTempRes -- | Tries to reserve a given value for a given job. reserve :: (MonadError GanetiException m, Show a, Ord a, Ord j) => j -> a -> TempRes j a -> m (TempRes j a) reserve jobid x tr = do when (isReserved x tr) . resError $ "Duplicate reservation for resource '" ++ show x ++ "'" return . TempRes . MM.insert jobid x $ getTempRes tr dropReservationsFor :: (Ord a, Ord j) => j -> TempRes j a -> TempRes j a dropReservationsFor jobid = TempRes . MM.deleteAll jobid . getTempRes reservedFor :: (Ord a, Ord j) => j -> TempRes j a -> S.Set a reservedFor jobid = MM.lookup jobid . getTempRes reserved :: (Ord a, Ord j) => TempRes j a -> S.Set a reserved = MM.values . getTempRes -- | Computes the set of all reserved resources and passes it to -- the given function. -- This allows it to avoid resources that are already in use. withReserved :: (MonadError GanetiException m, Show a, Ord a, Ord j) => j -> (S.Set a -> m a) -> TempRes j a -> m (a, TempRes j a) withReserved jobid genfn tr = do x <- genfn (reserved tr) (,) x `liftM` reserve jobid x tr -- | Repeatedly tries to run a given monadic function until it succeeds -- and the returned value is free to reserve. -- If such a value is found, it's reserved and returned. -- Otherwise fails with an error. generate :: (MonadError GanetiException m, Show a, Ord a, Ord j) => j -> S.Set a -> m (Maybe a) -> TempRes j a -> m (a, TempRes j a) generate jobid existing genfn = withReserved jobid f where retries = 64 :: Int f res = do let vals = res `S.union` existing xOpt <- retryMaybeN retries (\_ -> mfilter (`S.notMember` vals) (MaybeT genfn)) maybe (resError "Not able generate new resource") -- TODO: (last tried: " ++ %s)" % new_resource return xOpt -- | A variant of 'generate' for randomized computations. generateRand :: (MonadError GanetiException m, Show a, Ord a, Ord j, RandomGen g) => g -> j -> S.Set a -> (g -> (Maybe a, g)) -> TempRes j a -> m (a, TempRes j a) generateRand rgen jobid existing genfn tr = evalStateT (generate jobid existing (state genfn) tr) rgen -- | Embeds a stateful computation in a stateful monad. stateM :: (MonadState s m) => (s -> m (a, s)) -> m a stateM f = get >>= f >>= \(x, s) -> liftM (const x) (put s) -- | Embeds a state-modifying computation in a stateful monad. modifyM :: (MonadState s m) => (s -> m s) -> m () modifyM f = get >>= f >>= put -- ** Functions common to all reservations -- | Removes all resources reserved by a given job. -- -- If a new reservation resource type is added, it must be added here as well. dropAllReservations :: ClientId -> State TempResState () dropAllReservations jobId = modify $ (trsMACsL %~ dropReservationsFor jobId) . (trsDRBDSecretsL %~ dropReservationsFor jobId) . (trsLVsL %~ dropReservationsFor jobId) . (trsIPv4sL %~ dropReservationsFor jobId) -- | Looks up a network by its UUID. lookupNetwork :: (MonadError GanetiException m) => ConfigData -> NetworkUUID -> m Network lookupNetwork cd netId = J.lookupContainer (resError $ "Network '" ++ show netId ++ "' not found") netId (configNetworks cd) -- ** IDs -- ** MAC addresses -- Randomly generate a MAC for an instance. -- Checks that the generated MAC isn't used by another instance. -- -- Note that we only consume, but not return the state of a random number -- generator. This is because the whole operation needs to be pure (for atomic -- 'IORef' updates) and therefore we can't use 'getStdRandom'. Therefore the -- approach we take is to instead use 'newStdGen' and discard the split -- generator afterwards. generateMAC :: (RandomGen g, MonadError GanetiException m, Functor m) => g -> ClientId -> Maybe NetworkUUID -> ConfigData -> StateT TempResState m MAC generateMAC rgen jobId netId cd = do net <- case netId of Just n -> Just <$> lookupNetwork cd n Nothing -> return Nothing let prefix = fromMaybe (clusterMacPrefix . configCluster $ cd) (networkMacPrefix =<< net) let existing = S.fromList $ getAllMACs cd StateT $ traverseOf2 trsMACsL (generateRand rgen jobId existing (over _1 Just . generateOneMAC prefix)) -- Reserves a MAC for an instance in the list of temporary reservations. reserveMAC :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> MAC -> ConfigData -> m () reserveMAC jobId mac cd = do let existing = S.fromList $ getAllMACs cd when (S.member mac existing) $ resError "MAC already in use" modifyM $ traverseOf trsMACsL (reserve jobId mac) -- ** DRBD secrets generateDRBDSecret :: (RandomGen g, MonadError GanetiException m, Functor m) => g -> ClientId -> ConfigData -> StateT TempResState m DRBDSecret generateDRBDSecret rgen jobId cd = do let existing = S.fromList $ getAllDrbdSecrets cd StateT $ traverseOf2 trsDRBDSecretsL (generateRand rgen jobId existing (over _1 Just . generateSecret C.drbdSecretLength)) -- ** LVs reserveLV :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> LogicalVolume -> ConfigData -> m () reserveLV jobId lv cd = do existing <- toError $ getAllLVs cd when (S.member lv existing) $ resError "MAC already in use" modifyM $ traverseOf trsLVsL (reserve jobId lv) -- ** IPv4 addresses -- | Lists all IPv4 addresses reserved for a given network. usedIPv4Addrs :: NetworkUUID -> S.Set IPv4Reservation -> S.Set Ip4Address usedIPv4Addrs netuuid = S.map ipv4ResAddr . S.filter ((== netuuid) . ipv4ResNetwork) -- | Reserve a given IPv4 address for use by an instance. reserveIp :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> NetworkUUID -> Ip4Address -> Bool -- ^ whether to check externally reserved IPs -> ConfigData -> m () reserveIp jobId netuuid addr checkExt cd = toResError $ do net <- lookupNetwork cd netuuid isres <- N.isReserved N.PoolInstances addr net when isres . resError $ "IP address already in use" when checkExt $ do isextres <- N.isReserved N.PoolExt addr net when isextres . resError $ "IP is externally reserved" let action = IPv4Res IPv4Reserve netuuid addr modifyM $ traverseOf trsIPv4sL (reserve jobId action) -- | Give a specific IP address back to an IP pool. -- The IP address is returned to the IP pool designated by network id -- and marked as reserved. releaseIp :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> NetworkUUID -> Ip4Address -> m () releaseIp jobId netuuid addr = let action = IPv4Res { ipv4ResAction = IPv4Release , ipv4ResNetwork = netuuid , ipv4ResAddr = addr } in modifyM $ traverseOf trsIPv4sL (reserve jobId action) -- Find a free IPv4 address for an instance and reserve it. generateIp :: (MonadError GanetiException m, MonadState TempResState m, Functor m) => ClientId -> NetworkUUID -> ConfigData -> m Ip4Address generateIp jobId netuuid cd = toResError $ do net <- lookupNetwork cd netuuid let f res = do let ips = usedIPv4Addrs netuuid res addr <- N.findFree (`S.notMember` ips) net maybe (resError "Cannot generate IP. Network is full") (return . IPv4Res IPv4Reserve netuuid) addr liftM ipv4ResAddr . stateM $ traverseOf2 trsIPv4sL (withReserved jobId f) -- | Commit a reserved/released IP address to an IP pool. -- The IP address is taken from the network's IP pool and marked as -- reserved/free for instances. commitIp :: (MonadError GanetiException m, Functor m) => IPv4Reservation -> ConfigData -> m ConfigData commitIp (IPv4Res actType netuuid addr) cd = toResError $ do let call = case actType of IPv4Reserve -> N.reserve IPv4Release -> N.release f Nothing = resError $ "Network '" ++ show netuuid ++ "' not found" f (Just net) = Just `liftM` call N.PoolInstances addr net traverseOf (configNetworksL . J.alterContainerL netuuid) f cd -- | Immediately release an IP address, without using the reservations pool. commitReleaseIp :: (MonadError GanetiException m, Functor m) => NetworkUUID -> Ip4Address -> ConfigData -> m ConfigData commitReleaseIp netuuid addr = commitIp (IPv4Res IPv4Release netuuid addr) -- | Commit all reserved/released IP address to an IP pool. -- The IP addresses are taken from the network's IP pool and marked as -- reserved/free for instances. -- -- Note that the reservations are kept, they are supposed to be cleaned -- when a job finishes. commitReservedIps :: (MonadError GanetiException m, Functor m, MonadLog m) => ClientId -> TempResState -> ConfigData -> m ConfigData commitReservedIps jobId tr cd = do let res = reservedFor jobId (trsIPv4s tr) logDebug $ "Commiting reservations: " ++ show res F.foldrM commitIp cd res listReservedIps :: ClientId -> TempResState -> S.Set IPv4Reservation listReservedIps jobid = reservedFor jobid . trsIPv4s
mbakke/ganeti
src/Ganeti/WConfd/TempRes.hs
bsd-2-clause
19,053
112
15
4,135
4,556
2,440
2,116
-1
-1
{-# LANGUAGE BangPatterns #-} -------------------------------------------------------------------------------- -- | -- Module : Foreign.CUDA.Analysis.Occupancy -- Copyright : [2009..2014] Trevor L. McDonell -- License : BSD -- -- Occupancy calculations for CUDA kernels -- -- <http://developer.download.nvidia.com/compute/cuda/3_0/sdk/docs/CUDA_Occupancy_calculator.xls> -- -- /Determining Registers Per Thread and Shared Memory Per Block/ -- -- To determine the number of registers used per thread in your kernel, simply -- compile the kernel code using the option -- -- > --ptxas-options=-v -- -- to nvcc. This will output information about register, local memory, shared -- memory, and constant memory usage for each kernel in the @.cu@ file. -- Alternatively, you can compile with the @-cubin@ option to nvcc. This will -- generate a @.cubin@ file, which you can open in a text editor. Look for the -- @code@ section with your kernel's name. Within the curly braces (@{ ... }@) -- for that code block, you will see a line with @reg = X@, where @x@ is the -- number of registers used by your kernel. You can also see the amount of -- shared memory used as @smem = Y@. However, if your kernel declares any -- external shared memory that is allocated dynamically, you will need to add -- the number in the @.cubin@ file to the amount you dynamically allocate at run -- time to get the correct shared memory usage. -- -- /Notes About Occupancy/ -- -- Higher occupancy does not necessarily mean higher performance. If a kernel -- is not bandwidth bound, then increasing occupancy will not necessarily -- increase performance. If a kernel invocation is already running at least one -- thread block per multiprocessor in the GPU, and it is bottlenecked by -- computation and not by global memory accesses, then increasing occupancy may -- have no effect. In fact, making changes just to increase occupancy can have -- other effects, such as additional instructions, spills to local memory (which -- is off chip), divergent branches, etc. As with any optimization, you should -- experiment to see how changes affect the *wall clock time* of the kernel -- execution. For bandwidth bound applications, on the other hand, increasing -- occupancy can help better hide the latency of memory accesses, and therefore -- improve performance. -- -------------------------------------------------------------------------------- module Foreign.CUDA.Analysis.Occupancy ( Occupancy(..), occupancy, optimalBlockSize, optimalBlockSizeBy, maxResidentBlocks, incPow2, incWarp, decPow2, decWarp ) where import Data.Ord import Data.List import Foreign.CUDA.Analysis.Device -- GPU Occupancy per multiprocessor -- data Occupancy = Occupancy { activeThreads :: !Int, -- ^ Active threads per multiprocessor activeThreadBlocks :: !Int, -- ^ Active thread blocks per multiprocessor activeWarps :: !Int, -- ^ Active warps per multiprocessor occupancy100 :: !Double -- ^ Occupancy of each multiprocessor (percent) } deriving (Eq, Ord, Show) -- | -- Calculate occupancy data for a given GPU and kernel resource usage -- {-# INLINEABLE occupancy #-} occupancy :: DeviceProperties -- ^ Properties of the card in question -> Int -- ^ Threads per block -> Int -- ^ Registers per thread -> Int -- ^ Shared memory per block (bytes) -> Occupancy occupancy !dev !thds !regs !smem = Occupancy at ab aw oc where at = ab * thds aw = ab * warps ab = minimum [limitWarpBlock, limitRegMP, limitSMemMP] oc = 100 * fromIntegral aw / fromIntegral (warpsPerMP gpu) regs' = 1 `max` regs smem' = 1 `max` smem floor' = floor :: Double -> Int ceiling' = ceiling :: Double -> Int ceilingBy x s = s * ceiling' (fromIntegral x / fromIntegral s) -- Physical resources -- gpu = deviceResources dev -- Allocation per thread block -- warps = ceiling' (fromIntegral thds / fromIntegral (threadsPerWarp gpu)) sharedMem = ceilingBy smem' (sharedMemAllocUnit gpu) registers = case allocation gpu of Block -> (warps `ceilingBy` regAllocWarp gpu * regs' * threadsPerWarp gpu) `ceilingBy` regAllocUnit gpu Warp -> warps * ceilingBy (regs' * threadsPerWarp gpu) (regAllocUnit gpu) -- Maximum thread blocks per multiprocessor -- limitWarpBlock = threadBlocksPerMP gpu `min` floor' (fromIntegral (warpsPerMP gpu) / fromIntegral warps) limitRegMP = threadBlocksPerMP gpu `min` floor' (fromIntegral (regFileSize gpu) / fromIntegral registers) limitSMemMP = threadBlocksPerMP gpu `min` floor' (fromIntegral (sharedMemPerMP gpu) / fromIntegral sharedMem) -- | -- Optimise multiprocessor occupancy as a function of thread block size and -- resource usage. This returns the smallest satisfying block size in increments -- of a single warp. -- {-# INLINEABLE optimalBlockSize #-} optimalBlockSize :: DeviceProperties -- ^ Architecture to optimise for -> (Int -> Int) -- ^ Register count as a function of thread block size -> (Int -> Int) -- ^ Shared memory usage (bytes) as a function of thread block size -> (Int, Occupancy) optimalBlockSize = flip optimalBlockSizeBy decWarp -- | -- As 'optimalBlockSize', but with a generator that produces the specific thread -- block sizes that should be tested. The generated list can produce values in -- any order, but the last satisfying block size will be returned. Hence, values -- should be monotonically decreasing to return the smallest block size yielding -- maximum occupancy, and vice-versa. -- {-# INLINEABLE optimalBlockSizeBy #-} optimalBlockSizeBy :: DeviceProperties -> (DeviceProperties -> [Int]) -> (Int -> Int) -> (Int -> Int) -> (Int, Occupancy) optimalBlockSizeBy !dev !fblk !freg !fsmem = maximumBy (comparing (occupancy100 . snd)) $ zip threads residency where residency = map (\t -> occupancy dev t (freg t) (fsmem t)) threads threads = fblk dev -- | Increments in powers-of-two, over the range of supported thread block sizes -- for the given device. -- {-# INLINEABLE incPow2 #-} incPow2 :: DeviceProperties -> [Int] incPow2 !dev = map ((2::Int)^) [lb, lb+1 .. ub] where round' = round :: Double -> Int lb = round' . logBase 2 . fromIntegral $ warpSize dev ub = round' . logBase 2 . fromIntegral $ maxThreadsPerBlock dev -- | Decrements in powers-of-two, over the range of supported thread block sizes -- for the given device. -- {-# INLINEABLE decPow2 #-} decPow2 :: DeviceProperties -> [Int] decPow2 !dev = map ((2::Int)^) [ub, ub-1 .. lb] where round' = round :: Double -> Int lb = round' . logBase 2 . fromIntegral $ warpSize dev ub = round' . logBase 2 . fromIntegral $ maxThreadsPerBlock dev -- | Decrements in the warp size of the device, over the range of supported -- thread block sizes. -- {-# INLINEABLE decWarp #-} decWarp :: DeviceProperties -> [Int] decWarp !dev = [block, block-warp .. warp] where !warp = warpSize dev !block = maxThreadsPerBlock dev -- | Increments in the warp size of the device, over the range of supported -- thread block sizes. -- {-# INLINEABLE incWarp #-} incWarp :: DeviceProperties -> [Int] incWarp !dev = [warp, 2*warp .. block] where warp = warpSize dev block = maxThreadsPerBlock dev -- | -- Determine the maximum number of CTAs that can be run simultaneously for a -- given kernel / device combination. -- {-# INLINEABLE maxResidentBlocks #-} maxResidentBlocks :: DeviceProperties -- ^ Properties of the card in question -> Int -- ^ Threads per block -> Int -- ^ Registers per thread -> Int -- ^ Shared memory per block (bytes) -> Int -- ^ Maximum number of resident blocks maxResidentBlocks !dev !thds !regs !smem = multiProcessorCount dev * activeThreadBlocks (occupancy dev thds regs smem)
mwu-tow/cuda
Foreign/CUDA/Analysis/Occupancy.hs
bsd-3-clause
8,068
0
15
1,730
1,222
693
529
90
2
{- (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[RnBinds]{Renaming and dependency analysis of bindings} This module does renaming and dependency analysis on value bindings in the abstract syntax. It does {\em not} do cycle-checks on class or type-synonym declarations; those cannot be done at this stage because they may be affected by renaming (which isn't fully worked out yet). -} module ETA.Rename.RnBinds ( -- Renaming top-level bindings rnTopBindsLHS, rnTopBindsRHS, rnValBindsRHS, -- Renaming local bindings rnLocalBindsAndThen, rnLocalValBindsLHS, rnLocalValBindsRHS, -- Other bindings rnMethodBinds, renameSigs, mkSigTvFn, rnMatchGroup, rnGRHSs, rnGRHS, makeMiniFixityEnv, MiniFixityEnv, HsSigCtxt(..) ) where import {-# SOURCE #-} ETA.Rename.RnExpr( rnLExpr, rnStmts ) import ETA.HsSyn.HsSyn import ETA.TypeCheck.TcRnMonad import ETA.TypeCheck.TcEvidence ( emptyTcEvBinds ) import ETA.Rename.RnTypes import ETA.Rename.RnPat import ETA.Rename.RnNames import ETA.Rename.RnEnv import ETA.Main.DynFlags import ETA.BasicTypes.Avail import ETA.BasicTypes.Module import ETA.BasicTypes.Name import ETA.BasicTypes.NameEnv import ETA.BasicTypes.NameSet import ETA.BasicTypes.RdrName ( RdrName, rdrNameOcc ) import ETA.BasicTypes.SrcLoc import ETA.Utils.ListSetOps ( findDupsEq ) import ETA.BasicTypes.BasicTypes ( RecFlag(..) ) import ETA.Utils.Digraph ( SCC(..) ) import ETA.Utils.Bag import ETA.Utils.Outputable import ETA.Utils.FastString import Data.List ( partition, sort ) import ETA.Utils.Maybes ( orElse ) import Control.Monad -- TODO:#if __GLASGOW_HASKELL__ < 709 -- import Data.Traversable ( traverse ) -- #endif {- -- ToDo: Put the annotations into the monad, so that they arrive in the proper -- place and can be used when complaining. The code tree received by the function @rnBinds@ contains definitions in where-clauses which are all apparently mutually recursive, but which may not really depend upon each other. For example, in the top level program \begin{verbatim} f x = y where a = x y = x \end{verbatim} the definitions of @a@ and @y@ do not depend on each other at all. Unfortunately, the typechecker cannot always check such definitions. \footnote{Mycroft, A. 1984. Polymorphic type schemes and recursive definitions. In Proceedings of the International Symposium on Programming, Toulouse, pp. 217-39. LNCS 167. Springer Verlag.} However, the typechecker usually can check definitions in which only the strongly connected components have been collected into recursive bindings. This is precisely what the function @rnBinds@ does. ToDo: deal with case where a single monobinds binds the same variable twice. The vertag tag is a unique @Int@; the tags only need to be unique within one @MonoBinds@, so that unique-Int plumbing is done explicitly (heavy monad machinery not needed). ************************************************************************ * * * naming conventions * * * ************************************************************************ \subsection[name-conventions]{Name conventions} The basic algorithm involves walking over the tree and returning a tuple containing the new tree plus its free variables. Some functions, such as those walking polymorphic bindings (HsBinds) and qualifier lists in list comprehensions (@Quals@), return the variables bound in local environments. These are then used to calculate the free variables of the expression evaluated in these environments. Conventions for variable names are as follows: \begin{itemize} \item new code is given a prime to distinguish it from the old. \item a set of variables defined in @Exp@ is written @dvExp@ \item a set of variables free in @Exp@ is written @fvExp@ \end{itemize} ************************************************************************ * * * analysing polymorphic bindings (HsBindGroup, HsBind) * * ************************************************************************ \subsubsection[dep-HsBinds]{Polymorphic bindings} Non-recursive expressions are reconstructed without any changes at top level, although their component expressions may have to be altered. However, non-recursive expressions are currently not expected as \Haskell{} programs, and this code should not be executed. Monomorphic bindings contain information that is returned in a tuple (a @FlatMonoBinds@) containing: \begin{enumerate} \item a unique @Int@ that serves as the ``vertex tag'' for this binding. \item the name of a function or the names in a pattern. These are a set referred to as @dvLhs@, the defined variables of the left hand side. \item the free variables of the body. These are referred to as @fvBody@. \item the definition's actual code. This is referred to as just @code@. \end{enumerate} The function @nonRecDvFv@ returns two sets of variables. The first is the set of variables defined in the set of monomorphic bindings, while the second is the set of free variables in those bindings. The set of variables defined in a non-recursive binding is just the union of all of them, as @union@ removes duplicates. However, the free variables in each successive set of cumulative bindings is the union of those in the previous set plus those of the newest binding after the defined variables of the previous set have been removed. @rnMethodBinds@ deals only with the declarations in class and instance declarations. It expects only to see @FunMonoBind@s, and it expects the global environment to contain bindings for the binders (which are all class operations). ************************************************************************ * * \subsubsection{ Top-level bindings} * * ************************************************************************ -} -- for top-level bindings, we need to make top-level names, -- so we have a different entry point than for local bindings rnTopBindsLHS :: MiniFixityEnv -> HsValBinds RdrName -> RnM (HsValBindsLR Name RdrName) rnTopBindsLHS fix_env binds = do binds' <- rnValBindsLHS (topRecNameMaker fix_env) binds checkSimilarNames binds' return binds' isPatSynBind :: HsBindLR l r -> Bool isPatSynBind (PatSynBind _) = True isPatSynBind _ = False checkSimilarNames :: HsValBindsLR Name RdrName -> RnM () checkSimilarNames (ValBindsIn mbinds _) = do { let { (patSyns, others) = partitionBag (isPatSynBind . unLoc) mbinds } ; checkBinds patSyns ; checkBinds others } where checkBinds binds = do { let { bndrs = collectHsBindsBinders binds ; val_avails = map Avail bndrs ; similar_names = (findSames val_avails) } ; when (not (null similar_names)) (addSimDeclErrors similar_names) } checkSimilarNames b = pprPanic "checkSimilarNames" (ppr b) rnTopBindsRHS :: NameSet -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnTopBindsRHS bound_names binds = do { is_boot <- tcIsHsBootOrSig ; if is_boot then rnTopBindsBoot binds else rnValBindsRHS (TopSigCtxt bound_names False) binds } rnTopBindsBoot :: HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) -- A hs-boot file has no bindings. -- Return a single HsBindGroup with empty binds and renamed signatures rnTopBindsBoot (ValBindsIn mbinds sigs) = do { checkErr (isEmptyLHsBinds mbinds) (bindsInHsBootFile mbinds) ; (sigs', fvs) <- renameSigs HsBootCtxt sigs ; return (ValBindsOut [] sigs', usesOnly fvs) } rnTopBindsBoot b = pprPanic "rnTopBindsBoot" (ppr b) {- ********************************************************* * * HsLocalBinds * * ********************************************************* -} rnLocalBindsAndThen :: HsLocalBinds RdrName -> (HsLocalBinds Name -> RnM (result, FreeVars)) -> RnM (result, FreeVars) -- This version (a) assumes that the binding vars are *not* already in scope -- (b) removes the binders from the free vars of the thing inside -- The parser doesn't produce ThenBinds rnLocalBindsAndThen EmptyLocalBinds thing_inside = thing_inside EmptyLocalBinds rnLocalBindsAndThen (HsValBinds val_binds) thing_inside = rnLocalValBindsAndThen val_binds $ \ val_binds' -> thing_inside (HsValBinds val_binds') rnLocalBindsAndThen (HsIPBinds binds) thing_inside = do (binds',fv_binds) <- rnIPBinds binds (thing, fvs_thing) <- thing_inside (HsIPBinds binds') return (thing, fvs_thing `plusFV` fv_binds) rnIPBinds :: HsIPBinds RdrName -> RnM (HsIPBinds Name, FreeVars) rnIPBinds (IPBinds ip_binds _no_dict_binds) = do (ip_binds', fvs_s) <- mapAndUnzipM (wrapLocFstM rnIPBind) ip_binds return (IPBinds ip_binds' emptyTcEvBinds, plusFVs fvs_s) rnIPBind :: IPBind RdrName -> RnM (IPBind Name, FreeVars) rnIPBind (IPBind ~(Left n) expr) = do (expr',fvExpr) <- rnLExpr expr return (IPBind (Left n) expr', fvExpr) {- ************************************************************************ * * ValBinds * * ************************************************************************ -} -- Renaming local binding groups -- Does duplicate/shadow check rnLocalValBindsLHS :: MiniFixityEnv -> HsValBinds RdrName -> RnM ([Name], HsValBindsLR Name RdrName) rnLocalValBindsLHS fix_env binds = do { binds' <- rnValBindsLHS (localRecNameMaker fix_env) binds -- Check for duplicates and shadowing -- Must do this *after* renaming the patterns -- See Note [Collect binders only after renaming] in HsUtils -- We need to check for dups here because we -- don't don't bind all of the variables from the ValBinds at once -- with bindLocatedLocals any more. -- -- Note that we don't want to do this at the top level, since -- sorting out duplicates and shadowing there happens elsewhere. -- The behavior is even different. For example, -- import A(f) -- f = ... -- should not produce a shadowing warning (but it will produce -- an ambiguity warning if you use f), but -- import A(f) -- g = let f = ... in f -- should. ; let bound_names = collectHsValBinders binds' -- There should be only Ids, but if there are any bogus -- pattern synonyms, we'll collect them anyway, so that -- we don't generate subsequent out-of-scope messages ; envs <- getRdrEnvs ; checkDupAndShadowedNames envs bound_names ; return (bound_names, binds') } -- renames the left-hand sides -- generic version used both at the top level and for local binds -- does some error checking, but not what gets done elsewhere at the top level rnValBindsLHS :: NameMaker -> HsValBinds RdrName -> RnM (HsValBindsLR Name RdrName) rnValBindsLHS topP (ValBindsIn mbinds sigs) = do { mbinds' <- mapBagM (wrapLocM (rnBindLHS topP doc)) mbinds ; return $ ValBindsIn mbinds' sigs } where bndrs = collectHsBindsBinders mbinds doc = text "In the binding group for:" <+> pprWithCommas ppr bndrs rnValBindsLHS _ b = pprPanic "rnValBindsLHSFromDoc" (ppr b) -- General version used both from the top-level and for local things -- Assumes the LHS vars are in scope -- -- Does not bind the local fixity declarations rnValBindsRHS :: HsSigCtxt -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnValBindsRHS ctxt (ValBindsIn mbinds sigs) = do { (sigs', sig_fvs) <- renameSigs ctxt sigs ; binds_w_dus <- mapBagM (rnLBind (mkSigTvFn sigs')) mbinds ; case depAnalBinds binds_w_dus of (anal_binds, anal_dus) -> return (valbind', valbind'_dus) where valbind' = ValBindsOut anal_binds sigs' valbind'_dus = anal_dus `plusDU` usesOnly sig_fvs -- Put the sig uses *after* the bindings -- so that the binders are removed from -- the uses in the sigs } rnValBindsRHS _ b = pprPanic "rnValBindsRHS" (ppr b) -- Wrapper for local binds -- -- The *client* of this function is responsible for checking for unused binders; -- it doesn't (and can't: we don't have the thing inside the binds) happen here -- -- The client is also responsible for bringing the fixities into scope rnLocalValBindsRHS :: NameSet -- names bound by the LHSes -> HsValBindsLR Name RdrName -> RnM (HsValBinds Name, DefUses) rnLocalValBindsRHS bound_names binds = rnValBindsRHS (LocalBindCtxt bound_names) binds -- for local binds -- wrapper that does both the left- and right-hand sides -- -- here there are no local fixity decls passed in; -- the local fixity decls come from the ValBinds sigs rnLocalValBindsAndThen :: HsValBinds RdrName -> (HsValBinds Name -> RnM (result, FreeVars)) -> RnM (result, FreeVars) rnLocalValBindsAndThen binds@(ValBindsIn _ sigs) thing_inside = do { -- (A) Create the local fixity environment new_fixities <- makeMiniFixityEnv [L loc sig | L loc (FixSig sig) <- sigs] -- (B) Rename the LHSes ; (bound_names, new_lhs) <- rnLocalValBindsLHS new_fixities binds -- ...and bring them (and their fixities) into scope ; bindLocalNamesFV bound_names $ addLocalFixities new_fixities bound_names $ do { -- (C) Do the RHS and thing inside (binds', dus) <- rnLocalValBindsRHS (mkNameSet bound_names) new_lhs ; (result, result_fvs) <- thing_inside binds' -- Report unused bindings based on the (accurate) -- findUses. E.g. -- let x = x in 3 -- should report 'x' unused ; let real_uses = findUses dus result_fvs -- Insert fake uses for variables introduced implicitly by -- wildcards (#4404) implicit_uses = hsValBindsImplicits binds' ; warnUnusedLocalBinds bound_names (real_uses `unionNameSet` implicit_uses) ; let -- The variables "used" in the val binds are: -- (1) the uses of the binds (allUses) -- (2) the FVs of the thing-inside all_uses = allUses dus `plusFV` result_fvs -- Note [Unused binding hack] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Note that *in contrast* to the above reporting of -- unused bindings, (1) above uses duUses to return *all* -- the uses, even if the binding is unused. Otherwise consider: -- x = 3 -- y = let p = x in 'x' -- NB: p not used -- If we don't "see" the dependency of 'y' on 'x', we may put the -- bindings in the wrong order, and the type checker will complain -- that x isn't in scope -- -- But note that this means we won't report 'x' as unused, -- whereas we would if we had { x = 3; p = x; y = 'x' } ; return (result, all_uses) }} -- The bound names are pruned out of all_uses -- by the bindLocalNamesFV call above rnLocalValBindsAndThen bs _ = pprPanic "rnLocalValBindsAndThen" (ppr bs) -- Process the fixity declarations, making a FastString -> (Located Fixity) map -- (We keep the location around for reporting duplicate fixity declarations.) -- -- Checks for duplicates, but not that only locally defined things are fixed. -- Note: for local fixity declarations, duplicates would also be checked in -- check_sigs below. But we also use this function at the top level. makeMiniFixityEnv :: [LFixitySig RdrName] -> RnM MiniFixityEnv makeMiniFixityEnv decls = foldlM add_one_sig emptyFsEnv decls where add_one_sig env (L loc (FixitySig names fixity)) = foldlM add_one env [ (loc,name_loc,name,fixity) | L name_loc name <- names ] add_one env (loc, name_loc, name,fixity) = do { -- this fixity decl is a duplicate iff -- the ReaderName's OccName's FastString is already in the env -- (we only need to check the local fix_env because -- definitions of non-local will be caught elsewhere) let { fs = occNameFS (rdrNameOcc name) ; fix_item = L loc fixity }; case lookupFsEnv env fs of Nothing -> return $ extendFsEnv env fs fix_item Just (L loc' _) -> do { setSrcSpan loc $ addErrAt name_loc (dupFixityDecl loc' name) ; return env} } dupFixityDecl :: SrcSpan -> RdrName -> SDoc dupFixityDecl loc rdr_name = vcat [ptext (sLit "Multiple fixity declarations for") <+> quotes (ppr rdr_name), ptext (sLit "also at ") <+> ppr loc] --------------------- -- renaming a single bind rnBindLHS :: NameMaker -> SDoc -> HsBind RdrName -- returns the renamed left-hand side, -- and the FreeVars *of the LHS* -- (i.e., any free variables of the pattern) -> RnM (HsBindLR Name RdrName) rnBindLHS name_maker _ bind@(PatBind { pat_lhs = pat }) = do -- we don't actually use the FV processing of rnPatsAndThen here (pat',pat'_fvs) <- rnBindPat name_maker pat return (bind { pat_lhs = pat', bind_fvs = pat'_fvs }) -- We temporarily store the pat's FVs in bind_fvs; -- gets updated to the FVs of the whole bind -- when doing the RHS below rnBindLHS name_maker _ bind@(FunBind { fun_id = rdr_name }) = do { name <- applyNameMaker name_maker rdr_name ; return (bind { fun_id = name , bind_fvs = placeHolderNamesTc }) } rnBindLHS name_maker _ (PatSynBind psb@PSB{ psb_id = rdrname }) | isTopRecNameMaker name_maker = do { addLocM checkConName rdrname ; name <- lookupLocatedTopBndrRn rdrname -- Should be bound at top level already ; return (PatSynBind psb{ psb_id = name }) } | otherwise -- Pattern synonym, not at top level = do { addErr localPatternSynonymErr -- Complain, but make up a fake -- name so that we can carry on ; name <- applyNameMaker name_maker rdrname ; return (PatSynBind psb{ psb_id = name }) } where localPatternSynonymErr :: SDoc localPatternSynonymErr = hang (ptext (sLit "Illegal pattern synonym declaration for") <+> quotes (ppr rdrname)) 2 (ptext (sLit "Pattern synonym declarations are only valid at top level")) rnBindLHS _ _ b = pprPanic "rnBindHS" (ppr b) rnLBind :: (Name -> [Name]) -- Signature tyvar function -> LHsBindLR Name RdrName -> RnM (LHsBind Name, [Name], Uses) rnLBind sig_fn (L loc bind) = setSrcSpan loc $ do { (bind', bndrs, dus) <- rnBind sig_fn bind ; return (L loc bind', bndrs, dus) } -- assumes the left-hands-side vars are in scope rnBind :: (Name -> [Name]) -- Signature tyvar function -> HsBindLR Name RdrName -> RnM (HsBind Name, [Name], Uses) rnBind _ bind@(PatBind { pat_lhs = pat , pat_rhs = grhss -- pat fvs were stored in bind_fvs -- after processing the LHS , bind_fvs = pat_fvs }) = do { mod <- getModule ; (grhss', rhs_fvs) <- rnGRHSs PatBindRhs rnLExpr grhss -- No scoped type variables for pattern bindings ; let all_fvs = pat_fvs `plusFV` rhs_fvs fvs' = filterNameSet (nameIsLocalOrFrom mod) all_fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan bndrs = collectPatBinders pat bind' = bind { pat_rhs = grhss', pat_rhs_ty = placeHolderType, bind_fvs = fvs' } is_wild_pat = case pat of L _ (WildPat {}) -> True L _ (BangPat (L _ (WildPat {}))) -> True -- #9127 _ -> False -- Warn if the pattern binds no variables, except for the -- entirely-explicit idiom _ = rhs -- which (a) is not that different from _v = rhs -- (b) is sometimes used to give a type sig for, -- or an occurrence of, a variable on the RHS ; whenWOptM Opt_WarnUnusedBinds $ when (null bndrs && not is_wild_pat) $ addWarn $ unusedPatBindWarn bind' ; fvs' `seq` -- See Note [Free-variable space leak] return (bind', bndrs, all_fvs) } rnBind sig_fn bind@(FunBind { fun_id = name , fun_infix = is_infix , fun_matches = matches }) -- invariant: no free vars here when it's a FunBind = do { let plain_name = unLoc name ; (matches', rhs_fvs) <- bindSigTyVarsFV (sig_fn plain_name) $ -- bindSigTyVars tests for Opt_ScopedTyVars rnMatchGroup (FunRhs plain_name is_infix) rnLExpr matches ; when is_infix $ checkPrecMatch plain_name matches' ; mod <- getModule ; let fvs' = filterNameSet (nameIsLocalOrFrom mod) rhs_fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan ; fvs' `seq` -- See Note [Free-variable space leak] return (bind { fun_matches = matches' , bind_fvs = fvs' }, [plain_name], rhs_fvs) } rnBind sig_fn (PatSynBind bind) = do { (bind', name, fvs) <- rnPatSynBind sig_fn bind ; return (PatSynBind bind', name, fvs) } rnBind _ b = pprPanic "rnBind" (ppr b) {- Note [Free-variable space leak] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We have fvs' = trim fvs and we seq fvs' before turning it as part of a record. The reason is that trim is sometimes something like \xs -> intersectNameSet (mkNameSet bound_names) xs and we don't want to retain the list bound_names. This showed up in trac ticket #1136. -} rnPatSynBind :: (Name -> [Name]) -- Signature tyvar function -> PatSynBind Name RdrName -> RnM (PatSynBind Name Name, [Name], Uses) rnPatSynBind _sig_fn bind@(PSB { psb_id = L _ name , psb_args = details , psb_def = pat , psb_dir = dir }) -- invariant: no free vars here when it's a FunBind = do { pattern_synonym_ok <- xoptM Opt_PatternSynonyms ; unless pattern_synonym_ok (addErr patternSynonymErr) ; ((pat', details'), fvs1) <- rnPat PatSyn pat $ \pat' -> do -- We check the 'RdrName's instead of the 'Name's -- so that the binding locations are reported -- from the left-hand side { (details', fvs) <- case details of PrefixPatSyn vars -> do { checkDupRdrNames vars ; names <- mapM lookupVar vars ; return (PrefixPatSyn names, mkFVs (map unLoc names)) } InfixPatSyn var1 var2 -> do { checkDupRdrNames [var1, var2] ; name1 <- lookupVar var1 ; name2 <- lookupVar var2 -- ; checkPrecMatch -- TODO ; return (InfixPatSyn name1 name2, mkFVs (map unLoc [name1, name2])) } ; return ((pat', details'), fvs) } ; (dir', fvs2) <- case dir of Unidirectional -> return (Unidirectional, emptyFVs) ImplicitBidirectional -> return (ImplicitBidirectional, emptyFVs) ExplicitBidirectional mg -> do { (mg', fvs) <- rnMatchGroup PatSyn rnLExpr mg ; return (ExplicitBidirectional mg', fvs) } ; mod <- getModule ; let fvs = fvs1 `plusFV` fvs2 fvs' = filterNameSet (nameIsLocalOrFrom mod) fvs -- Keep locally-defined Names -- As well as dependency analysis, we need these for the -- MonoLocalBinds test in TcBinds.decideGeneralisationPlan ; let bind' = bind{ psb_args = details' , psb_def = pat' , psb_dir = dir' , psb_fvs = fvs' } ; fvs' `seq` -- See Note [Free-variable space leak] return (bind', [name], fvs1) -- See Note [Pattern synonym wrappers don't yield dependencies] } where lookupVar = wrapLocM lookupOccRn patternSynonymErr :: SDoc patternSynonymErr = hang (ptext (sLit "Illegal pattern synonym declaration")) 2 (ptext (sLit "Use -XPatternSynonyms to enable this extension")) {- Note [Pattern synonym wrappers don't yield dependencies] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When renaming a pattern synonym that has an explicit wrapper, references in the wrapper definition should not be used when calculating dependencies. For example, consider the following pattern synonym definition: pattern P x <- C1 x where P x = f (C1 x) f (P x) = C2 x In this case, 'P' needs to be typechecked in two passes: 1. Typecheck the pattern definition of 'P', which fully determines the type of 'P'. This step doesn't require knowing anything about 'f', since the wrapper definition is not looked at. 2. Typecheck the wrapper definition, which needs the typechecked definition of 'f' to be in scope. This behaviour is implemented in 'tcValBinds', but it crucially depends on 'P' not being put in a recursive group with 'f' (which would make it look like a recursive pattern synonym a la 'pattern P = P' which is unsound and rejected). -} --------------------- depAnalBinds :: Bag (LHsBind Name, [Name], Uses) -> ([(RecFlag, LHsBinds Name)], DefUses) -- Dependency analysis; this is important so that -- unused-binding reporting is accurate depAnalBinds binds_w_dus = (map get_binds sccs, map get_du sccs) where sccs = depAnal (\(_, defs, _) -> defs) (\(_, _, uses) -> nameSetElems uses) (bagToList binds_w_dus) get_binds (AcyclicSCC (bind, _, _)) = (NonRecursive, unitBag bind) get_binds (CyclicSCC binds_w_dus) = (Recursive, listToBag [b | (b,_,_) <- binds_w_dus]) get_du (AcyclicSCC (_, bndrs, uses)) = (Just (mkNameSet bndrs), uses) get_du (CyclicSCC binds_w_dus) = (Just defs, uses) where defs = mkNameSet [b | (_,bs,_) <- binds_w_dus, b <- bs] uses = unionNameSets [u | (_,_,u) <- binds_w_dus] --------------------- -- Bind the top-level forall'd type variables in the sigs. -- E.g f :: a -> a -- f = rhs -- The 'a' scopes over the rhs -- -- NB: there'll usually be just one (for a function binding) -- but if there are many, one may shadow the rest; too bad! -- e.g x :: [a] -> [a] -- y :: [(a,a)] -> a -- (x,y) = e -- In e, 'a' will be in scope, and it'll be the one from 'y'! mkSigTvFn :: [LSig Name] -> (Name -> [Name]) -- Return a lookup function that maps an Id Name to the names -- of the type variables that should scope over its body.. mkSigTvFn sigs = \n -> lookupNameEnv env n `orElse` [] where extractScopedTyVars :: LHsType Name -> [Name] extractScopedTyVars (L _ (HsForAllTy Explicit _ ltvs _ _)) = hsLKiTyVarNames ltvs extractScopedTyVars _ = [] env :: NameEnv [Name] env = mkNameEnv [ (name, nwcs ++ extractScopedTyVars ty) -- Kind variables and type variables | L _ (TypeSig names ty nwcs) <- sigs , L _ name <- names] -- Note the pattern-match on "Explicit"; we only bind -- type variables from signatures with an explicit top-level for-all {- @rnMethodBinds@ is used for the method bindings of a class and an instance declaration. Like @rnBinds@ but without dependency analysis. NOTA BENE: we record each {\em binder} of a method-bind group as a free variable. That's crucial when dealing with an instance decl: \begin{verbatim} instance Foo (T a) where op x = ... \end{verbatim} This might be the {\em sole} occurrence of @op@ for an imported class @Foo@, and unless @op@ occurs we won't treat the type signature of @op@ in the class decl for @Foo@ as a source of instance-decl gates. But we should! Indeed, in many ways the @op@ in an instance decl is just like an occurrence, not a binder. -} rnMethodBinds :: Name -- Class name -> (Name -> [Name]) -- Signature tyvar function -> LHsBinds RdrName -> RnM (LHsBinds Name, FreeVars) rnMethodBinds cls sig_fn binds = do { checkDupRdrNames meth_names -- Check that the same method is not given twice in the -- same instance decl instance C T where -- f x = ... -- g y = ... -- f x = ... -- We must use checkDupRdrNames because the Name of the -- method is the Name of the class selector, whose SrcSpan -- points to the class declaration; and we use rnMethodBinds -- for instance decls too ; foldlM do_one (emptyBag, emptyFVs) (bagToList binds) } where meth_names = collectMethodBinders binds do_one (binds,fvs) bind = do { (bind', fvs_bind) <- rnMethodBind cls sig_fn bind ; return (binds `unionBags` bind', fvs_bind `plusFV` fvs) } rnMethodBind :: Name -> (Name -> [Name]) -> LHsBindLR RdrName RdrName -> RnM (Bag (LHsBindLR Name Name), FreeVars) rnMethodBind cls sig_fn (L loc bind@(FunBind { fun_id = name, fun_infix = is_infix , fun_matches = MG { mg_alts = matches , mg_origin = origin } })) = setSrcSpan loc $ do sel_name <- wrapLocM (lookupInstDeclBndr cls (ptext (sLit "method"))) name let plain_name = unLoc sel_name -- We use the selector name as the binder (new_matches, fvs) <- bindSigTyVarsFV (sig_fn plain_name) $ mapFvRn (rnMatch (FunRhs plain_name is_infix) rnLExpr) matches let new_group = mkMatchGroupName origin new_matches when is_infix $ checkPrecMatch plain_name new_group return (unitBag (L loc (bind { fun_id = sel_name , fun_matches = new_group , bind_fvs = fvs })), fvs `addOneFV` plain_name) -- The 'fvs' field isn't used for method binds -- Can't handle method pattern-bindings which bind multiple methods. rnMethodBind _ _ (L loc bind@(PatBind {})) = do addErrAt loc (methodBindErr bind) return (emptyBag, emptyFVs) -- Associated pattern synonyms are not implemented yet rnMethodBind _ _ (L loc bind@(PatSynBind {})) = do addErrAt loc $ methodPatSynErr bind return (emptyBag, emptyFVs) rnMethodBind _ _ b = pprPanic "rnMethodBind" (ppr b) {- ************************************************************************ * * \subsubsection[dep-Sigs]{Signatures (and user-pragmas for values)} * * ************************************************************************ @renameSigs@ checks for: \begin{enumerate} \item more than one sig for one thing; \item signatures given for things not bound here; \end{enumerate} At the moment we don't gather free-var info from the types in signatures. We'd only need this if we wanted to report unused tyvars. -} renameSigs :: HsSigCtxt -> [LSig RdrName] -> RnM ([LSig Name], FreeVars) -- Renames the signatures and performs error checks renameSigs ctxt sigs = do { mapM_ dupSigDeclErr (findDupSigs sigs) ; checkDupMinimalSigs sigs ; (sigs', sig_fvs) <- mapFvRn (wrapLocFstM (renameSig ctxt)) sigs ; let (good_sigs, bad_sigs) = partition (okHsSig ctxt) sigs' ; mapM_ misplacedSigErr bad_sigs -- Misplaced ; return (good_sigs, sig_fvs) } ---------------------- -- We use lookupSigOccRn in the signatures, which is a little bit unsatisfactory -- because this won't work for: -- instance Foo T where -- {-# INLINE op #-} -- Baz.op = ... -- We'll just rename the INLINE prag to refer to whatever other 'op' -- is in scope. (I'm assuming that Baz.op isn't in scope unqualified.) -- Doesn't seem worth much trouble to sort this. renameSig :: HsSigCtxt -> Sig RdrName -> RnM (Sig Name, FreeVars) -- FixitySig is renamed elsewhere. renameSig _ (IdSig x) = return (IdSig x, emptyFVs) -- Actually this never occurs renameSig ctxt sig@(TypeSig vs ty _) = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs -- (named and anonymous) wildcards are bound here. ; (wcs, ty') <- extractWildcards ty ; bindLocatedLocalsFV wcs $ \wcs_new -> do { (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty' ; return (TypeSig new_vs new_ty wcs_new, fvs) } } renameSig ctxt sig@(GenericSig vs ty) = do { defaultSigs_on <- xoptM Opt_DefaultSignatures ; unless defaultSigs_on (addErr (defaultSigErr sig)) ; new_v <- mapM (lookupSigOccRn ctxt sig) vs ; (new_ty, fvs) <- rnHsSigType (ppr_sig_bndrs vs) ty ; return (GenericSig new_v new_ty, fvs) } renameSig _ (SpecInstSig src ty) = do { (new_ty, fvs) <- rnLHsType SpecInstSigCtx ty ; return (SpecInstSig src new_ty,fvs) } -- {-# SPECIALISE #-} pragmas can refer to imported Ids -- so, in the top-level case (when mb_names is Nothing) -- we use lookupOccRn. If there's both an imported and a local 'f' -- then the SPECIALISE pragma is ambiguous, unlike all other signatures renameSig ctxt sig@(SpecSig v tys inl) = do { new_v <- case ctxt of TopSigCtxt {} -> lookupLocatedOccRn v _ -> lookupSigOccRn ctxt sig v -- ; (new_ty, fvs) <- rnHsSigType (quotes (ppr v)) ty ; (new_ty, fvs) <- foldM do_one ([],emptyFVs) tys ; return (SpecSig new_v new_ty inl, fvs) } where do_one (tys,fvs) ty = do { (new_ty, fvs_ty) <- rnHsSigType (quotes (ppr v)) ty ; return ( new_ty:tys, fvs_ty `plusFV` fvs) } renameSig ctxt sig@(InlineSig v s) = do { new_v <- lookupSigOccRn ctxt sig v ; return (InlineSig new_v s, emptyFVs) } renameSig ctxt sig@(FixSig (FixitySig vs f)) = do { new_vs <- mapM (lookupSigOccRn ctxt sig) vs ; return (FixSig (FixitySig new_vs f), emptyFVs) } renameSig ctxt sig@(MinimalSig s bf) = do new_bf <- traverse (lookupSigOccRn ctxt sig) bf return (MinimalSig s new_bf, emptyFVs) renameSig ctxt sig@(PatSynSig v (flag, qtvs) prov req ty) = do { v' <- lookupSigOccRn ctxt sig v ; let doc = TypeSigCtx $ quotes (ppr v) ; loc <- getSrcSpanM ; let (tv_kvs, mentioned) = extractHsTysRdrTyVars (ty:unLoc prov ++ unLoc req) ; tv_bndrs <- case flag of Implicit -> return $ mkHsQTvs . userHsTyVarBndrs loc $ mentioned Explicit -> do { let heading = ptext (sLit "In the pattern synonym type signature") <+> quotes (ppr sig) ; warnUnusedForAlls (heading $$ docOfHsDocContext doc) qtvs mentioned ; return qtvs } Qualified -> panic "renameSig: Qualified" ; bindHsTyVars doc Nothing tv_kvs tv_bndrs $ \ tyvars -> do { (prov', fvs1) <- rnContext doc prov ; (req', fvs2) <- rnContext doc req ; (ty', fvs3) <- rnLHsType doc ty ; let fvs = plusFVs [fvs1, fvs2, fvs3] ; return (PatSynSig v' (flag, tyvars) prov' req' ty', fvs) }} ppr_sig_bndrs :: [Located RdrName] -> SDoc ppr_sig_bndrs bs = quotes (pprWithCommas ppr bs) okHsSig :: HsSigCtxt -> LSig a -> Bool okHsSig ctxt (L _ sig) = case (sig, ctxt) of (GenericSig {}, ClsDeclCtxt {}) -> True (GenericSig {}, _) -> False (TypeSig {}, _) -> True (PatSynSig {}, TopSigCtxt{}) -> True (PatSynSig {}, _) -> False (FixSig {}, InstDeclCtxt {}) -> False (FixSig {}, _) -> True (IdSig {}, TopSigCtxt {}) -> True (IdSig {}, InstDeclCtxt {}) -> True (IdSig {}, _) -> False (InlineSig {}, HsBootCtxt) -> False (InlineSig {}, _) -> True (SpecSig {}, TopSigCtxt {}) -> True (SpecSig {}, LocalBindCtxt {}) -> True (SpecSig {}, InstDeclCtxt {}) -> True (SpecSig {}, _) -> False (SpecInstSig {}, InstDeclCtxt {}) -> True (SpecInstSig {}, _) -> False (MinimalSig {}, ClsDeclCtxt {}) -> True (MinimalSig {}, _) -> False ------------------- findDupSigs :: [LSig RdrName] -> [[(Located RdrName, Sig RdrName)]] -- Check for duplicates on RdrName version, -- because renamed version has unboundName for -- not-in-scope binders, which gives bogus dup-sig errors -- NB: in a class decl, a 'generic' sig is not considered -- equal to an ordinary sig, so we allow, say -- class C a where -- op :: a -> a -- default op :: Eq a => a -> a findDupSigs sigs = findDupsEq matching_sig (concatMap (expand_sig . unLoc) sigs) where expand_sig sig@(FixSig (FixitySig ns _)) = zip ns (repeat sig) expand_sig sig@(InlineSig n _) = [(n,sig)] expand_sig sig@(TypeSig ns _ _) = [(n,sig) | n <- ns] expand_sig sig@(GenericSig ns _) = [(n,sig) | n <- ns] expand_sig _ = [] matching_sig (L _ n1,sig1) (L _ n2,sig2) = n1 == n2 && mtch sig1 sig2 mtch (FixSig {}) (FixSig {}) = True mtch (InlineSig {}) (InlineSig {}) = True mtch (TypeSig {}) (TypeSig {}) = True mtch (GenericSig {}) (GenericSig {}) = True mtch _ _ = False -- Warn about multiple MINIMAL signatures checkDupMinimalSigs :: [LSig RdrName] -> RnM () checkDupMinimalSigs sigs = case filter isMinimalLSig sigs of minSigs@(_:_:_) -> dupMinimalSigErr minSigs _ -> return () {- ************************************************************************ * * \subsection{Match} * * ************************************************************************ -} rnMatchGroup :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> MatchGroup RdrName (Located (body RdrName)) -> RnM (MatchGroup Name (Located (body Name)), FreeVars) rnMatchGroup ctxt rnBody (MG { mg_alts = ms, mg_origin = origin }) = do { empty_case_ok <- xoptM Opt_EmptyCase ; when (null ms && not empty_case_ok) (addErr (emptyCaseErr ctxt)) ; (new_ms, ms_fvs) <- mapFvRn (rnMatch ctxt rnBody) ms ; return (mkMatchGroupName origin new_ms, ms_fvs) } rnMatch :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> LMatch RdrName (Located (body RdrName)) -> RnM (LMatch Name (Located (body Name)), FreeVars) rnMatch ctxt rnBody = wrapLocFstM (rnMatch' ctxt rnBody) rnMatch' :: Outputable (body RdrName) => HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> Match RdrName (Located (body RdrName)) -> RnM (Match Name (Located (body Name)), FreeVars) rnMatch' ctxt rnBody match@(Match { m_fun_id_infix = mf, m_pats = pats , m_type = maybe_rhs_sig, m_grhss = grhss }) = do { -- Result type signatures are no longer supported case maybe_rhs_sig of Nothing -> return () Just (L loc ty) -> addErrAt loc (resSigErr ctxt match ty) -- Now the main event -- note that there are no local ficity decls for matches ; rnPats ctxt pats $ \ pats' -> do { (grhss', grhss_fvs) <- rnGRHSs ctxt rnBody grhss ; let mf' = case (ctxt,mf) of (FunRhs funid isinfix,Just (L lf _,_)) -> Just (L lf funid,isinfix) _ -> Nothing ; return (Match { m_fun_id_infix = mf', m_pats = pats' , m_type = Nothing, m_grhss = grhss'}, grhss_fvs ) }} emptyCaseErr :: HsMatchContext Name -> SDoc emptyCaseErr ctxt = hang (ptext (sLit "Empty list of alternatives in") <+> pp_ctxt) 2 (ptext (sLit "Use EmptyCase to allow this")) where pp_ctxt = case ctxt of CaseAlt -> ptext (sLit "case expression") LambdaExpr -> ptext (sLit "\\case expression") _ -> ptext (sLit "(unexpected)") <+> pprMatchContextNoun ctxt resSigErr :: Outputable body => HsMatchContext Name -> Match RdrName body -> HsType RdrName -> SDoc resSigErr ctxt match ty = vcat [ ptext (sLit "Illegal result type signature") <+> quotes (ppr ty) , nest 2 $ ptext (sLit "Result signatures are no longer supported in pattern matches") , pprMatchInCtxt ctxt match ] {- ************************************************************************ * * \subsubsection{Guarded right-hand sides (GRHSs)} * * ************************************************************************ -} rnGRHSs :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> GRHSs RdrName (Located (body RdrName)) -> RnM (GRHSs Name (Located (body Name)), FreeVars) rnGRHSs ctxt rnBody (GRHSs grhss binds) = rnLocalBindsAndThen binds $ \ binds' -> do (grhss', fvGRHSs) <- mapFvRn (rnGRHS ctxt rnBody) grhss return (GRHSs grhss' binds', fvGRHSs) rnGRHS :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> LGRHS RdrName (Located (body RdrName)) -> RnM (LGRHS Name (Located (body Name)), FreeVars) rnGRHS ctxt rnBody = wrapLocFstM (rnGRHS' ctxt rnBody) rnGRHS' :: HsMatchContext Name -> (Located (body RdrName) -> RnM (Located (body Name), FreeVars)) -> GRHS RdrName (Located (body RdrName)) -> RnM (GRHS Name (Located (body Name)), FreeVars) rnGRHS' ctxt rnBody (GRHS guards rhs) = do { pattern_guards_allowed <- xoptM Opt_PatternGuards ; ((guards', rhs'), fvs) <- rnStmts (PatGuard ctxt) rnLExpr guards $ \ _ -> rnBody rhs ; unless (pattern_guards_allowed || is_standard_guard guards') (addWarn (nonStdGuardErr guards')) ; return (GRHS guards' rhs', fvs) } where -- Standard Haskell 1.4 guards are just a single boolean -- expression, rather than a list of qualifiers as in the -- Glasgow extension is_standard_guard [] = True is_standard_guard [L _ (BodyStmt _ _ _ _)] = True is_standard_guard _ = False {- ************************************************************************ * * \subsection{Error messages} * * ************************************************************************ -} dupSigDeclErr :: [(Located RdrName, Sig RdrName)] -> RnM () dupSigDeclErr pairs@((L loc name, sig) : _) = addErrAt loc $ vcat [ ptext (sLit "Duplicate") <+> what_it_is <> ptext (sLit "s for") <+> quotes (ppr name) , ptext (sLit "at") <+> vcat (map ppr $ sort $ map (getLoc . fst) pairs) ] where what_it_is = hsSigDoc sig dupSigDeclErr [] = panic "dupSigDeclErr" misplacedSigErr :: LSig Name -> RnM () misplacedSigErr (L loc sig) = addErrAt loc $ sep [ptext (sLit "Misplaced") <+> hsSigDoc sig <> colon, ppr sig] defaultSigErr :: Sig RdrName -> SDoc defaultSigErr sig = vcat [ hang (ptext (sLit "Unexpected default signature:")) 2 (ppr sig) , ptext (sLit "Use DefaultSignatures to enable default signatures") ] methodBindErr :: HsBindLR RdrName RdrName -> SDoc methodBindErr mbind = hang (ptext (sLit "Pattern bindings (except simple variables) not allowed in instance declarations")) 2 (ppr mbind) methodPatSynErr :: HsBindLR RdrName RdrName -> SDoc methodPatSynErr mbind = hang (ptext (sLit "Pattern synonyms not allowed in class/instance declarations")) 2 (ppr mbind) bindsInHsBootFile :: LHsBindsLR Name RdrName -> SDoc bindsInHsBootFile mbinds = hang (ptext (sLit "Bindings in hs-boot files are not allowed")) 2 (ppr mbinds) nonStdGuardErr :: Outputable body => [LStmtLR Name Name body] -> SDoc nonStdGuardErr guards = hang (ptext (sLit "accepting non-standard pattern guards (use PatternGuards to suppress this message)")) 4 (interpp'SP guards) unusedPatBindWarn :: HsBind Name -> SDoc unusedPatBindWarn bind = hang (ptext (sLit "This pattern-binding binds no variables:")) 2 (ppr bind) dupMinimalSigErr :: [LSig RdrName] -> RnM () dupMinimalSigErr sigs@(L loc _ : _) = addErrAt loc $ vcat [ ptext (sLit "Multiple minimal complete definitions") , ptext (sLit "at") <+> vcat (map ppr $ sort $ map getLoc sigs) , ptext (sLit "Combine alternative minimal complete definitions with `|'") ] dupMinimalSigErr [] = panic "dupMinimalSigErr"
pparkkin/eta
compiler/ETA/Rename/RnBinds.hs
bsd-3-clause
47,418
0
23
14,084
9,358
4,949
4,409
562
20
----------------------------------------------------------------------------- -- | -- Module : Plugins.Monitors.Disk -- Copyright : (c) 2010, 2011, 2012 Jose A Ortega Ruiz -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A Ortega Ruiz <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Disk usage and throughput monitors for Xmobar -- ----------------------------------------------------------------------------- module Plugins.Monitors.Disk (diskUConfig, runDiskU, startDiskIO) where import Plugins.Monitors.Common import StatFS import Data.IORef (IORef, newIORef, readIORef, writeIORef) import Control.Exception (SomeException, handle) import Control.Monad (zipWithM) import qualified Data.ByteString.Lazy.Char8 as B import Data.List (isPrefixOf, find) import System.Directory (canonicalizePath) diskIOConfig :: IO MConfig diskIOConfig = mkMConfig "" ["total", "read", "write", "totalbar", "readbar", "writebar"] diskUConfig :: IO MConfig diskUConfig = mkMConfig "" ["size", "free", "used", "freep", "usedp", "freebar", "usedbar"] type DevName = String type Path = String type DevDataRef = IORef [(DevName, [Float])] mountedDevices :: [String] -> IO [(DevName, Path)] mountedDevices req = do s <- B.readFile "/etc/mtab" parse `fmap` mapM canon (devs s) where canon (d, p) = do {d' <- canonicalizePath d; return (d', p)} devs = filter isDev . map (firstTwo . B.words) . B.lines parse = map undev . filter isReq firstTwo (a:b:_) = (B.unpack a, B.unpack b) firstTwo _ = ("", "") isDev (d, _) = "/dev/" `isPrefixOf` d isReq (d, p) = p `elem` req || drop 5 d `elem` req undev (d, f) = (drop 5 d, f) diskDevices :: [String] -> IO [(DevName, Path)] diskDevices req = do s <- B.readFile "/proc/diskstats" parse `fmap` mapM canon (devs s) where canon (d, p) = do {d' <- canonicalizePath (d); return (d', p)} devs = map (third . B.words) . B.lines parse = map undev . filter isReq third (_:_:c:_) = ("/dev/" ++ (B.unpack c), B.unpack c) third _ = ("", "") isReq (d, p) = p `elem` req || drop 5 d `elem` req undev (d, f) = (drop 5 d, f) mountedOrDiskDevices :: [String] -> IO [(DevName, Path)] mountedOrDiskDevices req = do mnt <- mountedDevices req case mnt of [] -> diskDevices req other -> return other diskData :: IO [(DevName, [Float])] diskData = do s <- B.readFile "/proc/diskstats" let extract ws = (head ws, map read (tail ws)) return $ map (extract . map B.unpack . drop 2 . B.words) (B.lines s) mountedData :: DevDataRef -> [DevName] -> IO [(DevName, [Float])] mountedData dref devs = do dt <- readIORef dref dt' <- diskData writeIORef dref dt' return $ map (parseDev (zipWith diff dt' dt)) devs where diff (dev, xs) (_, ys) = (dev, zipWith (-) xs ys) parseDev :: [(DevName, [Float])] -> DevName -> (DevName, [Float]) parseDev dat dev = case find ((==dev) . fst) dat of Nothing -> (dev, [0, 0, 0]) Just (_, xs) -> let rSp = speed (xs !! 2) (xs !! 3) wSp = speed (xs !! 6) (xs !! 7) sp = speed (xs !! 2 + xs !! 6) (xs !! 3 + xs !! 7) speed x t = if t == 0 then 0 else 500 * x / t dat' = if length xs > 6 then [sp, rSp, wSp] else [0, 0, 0] in (dev, dat') speedToStr :: Float -> String speedToStr = showWithUnits 2 1 sizeToStr :: Integer -> String sizeToStr = showWithUnits 3 0 . fromIntegral findTempl :: DevName -> Path -> [(String, String)] -> String findTempl dev path disks = case find devOrPath disks of Just (_, t) -> t Nothing -> "" where devOrPath (d, _) = d == dev || d == path devTemplates :: [(String, String)] -> [(DevName, Path)] -> [(DevName, [Float])] -> [(String, [Float])] devTemplates disks mounted dat = map (\(d, p) -> (findTempl d p disks, findData d)) mounted where findData dev = case find ((==dev) . fst) dat of Nothing -> [0, 0, 0] Just (_, xs) -> xs runDiskIO' :: (String, [Float]) -> Monitor String runDiskIO' (tmp, xs) = do s <- mapM (showWithColors speedToStr) xs b <- mapM (showLogBar 0.8) xs setConfigValue tmp template parseTemplate $ s ++ b runDiskIO :: DevDataRef -> [(String, String)] -> [String] -> Monitor String runDiskIO dref disks _ = do dev <- io $ mountedOrDiskDevices (map fst disks) dat <- io $ mountedData dref (map fst dev) strs <- mapM runDiskIO' $ devTemplates disks dev dat return $ unwords strs startDiskIO :: [(String, String)] -> [String] -> Int -> (String -> IO ()) -> IO () startDiskIO disks args rate cb = do dev <- mountedOrDiskDevices (map fst disks) dref <- newIORef (map (\d -> (fst d, repeat 0)) dev) _ <- mountedData dref (map fst dev) runM args diskIOConfig (runDiskIO dref disks) rate cb fsStats :: String -> IO [Integer] fsStats path = do stats <- getFileSystemStats path case stats of Nothing -> return [0, 0, 0] Just f -> let tot = fsStatByteCount f free = fsStatBytesAvailable f used = fsStatBytesUsed f in return [tot, free, used] runDiskU' :: String -> String -> Monitor String runDiskU' tmp path = do setConfigValue tmp template [total, free, diff] <- io (handle ign $ fsStats path) let strs = map sizeToStr [total, free, diff] freep = if total > 0 then free * 100 `div` total else 0 fr = fromIntegral freep / 100 s <- zipWithM showWithColors' strs [100, freep, 100 - freep] sp <- showPercentsWithColors [fr, 1 - fr] fb <- showPercentBar (fromIntegral freep) fr ub <- showPercentBar (fromIntegral $ 100 - freep) (1 - fr) parseTemplate $ s ++ sp ++ [fb, ub] where ign = const (return [0, 0, 0]) :: SomeException -> IO [Integer] runDiskU :: [(String, String)] -> [String] -> Monitor String runDiskU disks _ = do devs <- io $ mountedDevices (map fst disks) strs <- mapM (\(d, p) -> runDiskU' (findTempl d p disks) p) devs return $ unwords strs
tsiliakis/xmobar
src/Plugins/Monitors/Disk.hs
bsd-3-clause
6,056
0
16
1,463
2,531
1,349
1,182
135
4
module Shift.Period where import Shift.Type import Shift.Computer import Shift.Repeater import Data.List ( group, inits, tails ) import Control.Monad ( guard ) ps k = [ 2*k, 3*k, 5*k+1, 7*k+1 ] lift :: [ Int ] -> [ Bool ] lift [] = [] lift ( neg : pos : rest ) = replicate neg False ++ replicate pos True ++ lift rest -- Beispiel: show $ lift [5,24,1,7] -- = "-----++++++++++++++++++++++++-+++++++" period k = do l <- [ 0 .. k-1 ] ( if l == 0 then [ 2*k, 3*k, 1, 4*k, k, 1, k-1, 2*k ] else [ l, k-l, k, l, k-l, 2*k ] ) ++ do m <- [ 1 .. l ] do d <- [ 0 .. 1 ] [ m , k-m, m+d, 3*k, l-m+1-d, k-l+m ] ++ if m < l then [ k-m, l , k-l, 2*k ] else [ k-m, l+d, k-l-d, 2*k ] ++ do m <- [ l+1 .. k-1 ] do d <- [ 0 .. 1 ] [ l+1, k-l-1, m+d, k+l-m+1-d, m-l , 3*k , k-m, m+d, k-m-d, 2*k ] count :: Eq a => [a] -> [Int] count = map length . group xs = count . folge . ps diffs xs ys = do t @ (k, x, y) <- zip3 [0..] xs ys guard $ x /= y return t
Erdwolf/autotool-bonn
src/Shift/Period.hs
gpl-2.0
1,063
3
15
358
674
369
305
32
3
{-------------------------------------------------------------------------------- Copyright (c) Daan Leijen 2004 wxWindows License. Demonstration of making a custom color box control in wxHaskell that behaves just like any other widget. --------------------------------------------------------------------------------} module Main where import Graphics.UI.WX import Graphics.UI.WXCore -- main gui. main = start $ do f <- frame [text := "Custom color box controls"] c <- colorBox f [boxcolor := red] set f [layout := floatCenter $ widget c ,clientSize := sz 280 100] -- Define a new custom "ColorBox" as a subclass of "Window". type ColorBox a = Window (CColorBox a) data CColorBox a = CColorBox -- Create our new ColorBox control. -- Unfortunately, casting is involved here as we want to allow -- all normal window attributes; this means that one has to define -- the type signature of "colorBox" carefully. colorBox :: Window a -> [Prop (ColorBox ())] -> IO (ColorBox ()) colorBox parent props = do let defaults = [clientSize := sz 20 20, border := BorderStatic] cboxprops = castProps cast props -- cast properties to colorbox properties w <- window parent (defaults ++ cboxprops) let cbox = cast w -- cast to our new color box type set cbox [on click := selectColor cbox] return cbox where -- select a new color for the colorbox control. selectColor cbox pt = do c <- get cbox boxcolor mbc <- colorDialog cbox c case mbc of Just c -> set cbox [boxcolor := c] Nothing -> return () -- our casting operator: type signature is necessary! cast :: Window a -> ColorBox () cast = objectCast -- Define a custom attribute -- This is easy as we map to the background color. For more complicated -- things, one should define a ColorBox data type instead of a simple -- type synonym. boxcolor :: Attr (ColorBox a) Color boxcolor = newAttr "boxcolor" getter setter where getter cbox = get cbox bgcolor setter cbox clr = do set cbox [bgcolor := clr] refresh cbox
ekmett/wxHaskell
samples/wx/CustomControl.hs
lgpl-2.1
2,219
0
14
589
452
227
225
33
2
module Core.Prelude where import Core.Data import Core.Syntax import Utilities lam :: Var -> Term -> Term lam = lambda int :: Integer -> Term int = literal . Int char :: Char -> Term char = literal . Char add :: Term -> Term -> Term add e1 e2 = primOp Add [e1, e2] nilDataCon, consDataCon :: DataCon nilDataCon = "[]" consDataCon = "(:)" nil :: Term nil = data_ nilDataCon [] cons :: Var -> Var -> Term cons x xs = data_ consDataCon [x, xs] trueDataCon, falseDataCon :: DataCon trueDataCon = "True" falseDataCon = "False" true, false :: Term true = data_ trueDataCon [] false = data_ falseDataCon [] if_ :: Term -> Term -> Term -> Term if_ e et ef = case_ e [(DataAlt trueDataCon [], et), (DataAlt falseDataCon [], ef)] bool :: Bool -> Term bool x = if x then true else false nothingDataCon, justDataCon :: DataCon nothingDataCon = "Nothing" justDataCon = "Just" nothing :: Term nothing = data_ nothingDataCon [] just :: Var -> Term just x = data_ justDataCon [x] jDataCon, sDataCon :: DataCon jDataCon = "J#" sDataCon = "S#" j_, s_ :: Var -> Term j_ x = data_ jDataCon [x] s_ x = data_ sDataCon [x] tupleDataCon :: Int -> Maybe DataCon tupleDataCon 1 = Nothing tupleDataCon n = Just $ '(' : replicate (n - 1) ',' ++ ")" unitDataCon, pairDataCon :: DataCon unitDataCon = fromJust $ tupleDataCon 0 pairDataCon = fromJust $ tupleDataCon 2 unit :: Term unit = tuple [] tuple :: [Var] -> Term tuple xs = case tupleDataCon (length xs) of Nothing -> var (expectHead "tuple" xs); Just dc -> data_ dc xs
batterseapower/chsc
Core/Prelude.hs
bsd-3-clause
1,525
0
10
307
596
325
271
52
2
{-# language TypeInType, ScopedTypeVariables #-} module Silly where import Type.Reflection (Typeable, typeRep, TypeRep) import Type.Reflection.Unsafe (mkTrApp) import GHC.Exts (TYPE, RuntimeRep (..)) import Data.Kind (Type) mkTrFun :: forall (r1 :: RuntimeRep) (r2 :: RuntimeRep) (a :: TYPE r1) (b :: TYPE r2). TypeRep a -> TypeRep b -> TypeRep ((a -> b) :: Type) mkTrFun a b = typeRep `mkTrApp` a `mkTrApp` b -- originally reported that there was no (Typeable LiftedRep) instance, -- presumably to overeager RuntimeRep defaulting
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T16627.hs
bsd-3-clause
562
1
12
109
158
95
63
-1
-1
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE FlexibleContexts #-} module OpenCog.Lojban.Syntax.Util where import Prelude hiding (id,(.),(<*>),(<$>),(*>),(<*),foldl) import Data.List.Split (splitOn) import Data.List (intercalate,find,delete) import Data.Char (chr,isLetter,isDigit) import Data.Maybe import Data.Map (findWithDefault) import Control.Category import Control.Arrow import Control.Applicative hiding (many,some,optional) import Control.Monad import Control.Monad.RWS.Class import Control.Monad.Trans.Class import System.Random import Iso import Syntax hiding (SynIso,Syntax) import OpenCog.AtomSpace (Atom(..)) import OpenCog.Lojban.Syntax.Types import qualified Data.Map as M import qualified Data.ListTrie.Patricia.Set.Ord as TS ------------------------------------------------------------------------------- --Iso Util ------------------------------------------------------------------------------- mapIso :: Traversable t => SynIso a b -> SynIso (t a) (t b) mapIso iso = Iso f g where f = traverse (apply iso) g = traverse (unapply iso) --Try all SynIsos in the list and return result of the first one that works choice :: [SynIso a b] -> SynIso a b choice lst = Iso f g where f i = foldl1 mplus $ map (`apply` i) lst g i = foldl1 mplus $ map (`unapply` i) lst infix 8 |^| --Reverse of ||| (|^|) :: SynIso gamma alpha -> SynIso gamma beta -> SynIso gamma (Either alpha beta) (|^|) i j = inverse (inverse i ||| inverse j) showReadIso :: (Read a, Show a) => SynIso a String showReadIso = mkIso show read isoIntercalate :: String -> SynIso [String] String isoIntercalate x = mkIso (intercalate x) (splitOn x) isoPrepend :: String -> SynIso String String isoPrepend s1 = mkIso f g where f s2 = s1++s2 g s = drop (length s1) s isoAppend :: String -> SynIso String String isoAppend s1 = mkIso f g where f s2 = s2++s1 g s = take (length s - length s1) s --Try SynIso on failure keep original value try :: SynIso a a -> SynIso a a try iso = Iso f g where f a = apply iso a <|> pure a g a = unapply iso a <|> pure a --For dealing with maybes from/for Optional in the first or second position ifJustA :: SynIso (Maybe a,b) (Either (a,b) b) ifJustA = mkIso f g where f (Just a,b) = Left (a,b) f (Nothing,b) = Right b g (Left (a,b))= (Just a,b) g (Right b) = (Nothing,b) ifJustB :: SynIso (a,Maybe b) (Either (a,b) a) ifJustB = mkIso f g where f (a,Just b) = Left (a,b) f (a,Nothing) = Right a g (Left (a,b))= (a,Just b) g (Right a) = (a,Nothing) --Parser ID that fails when printing --Use to force a path in (maybe . pid &&& something) pid :: SynIso a a pid = Iso f g where f a = pure a g _ = lift $ Left "Only succeds when parsing." --Sep Isos consume input but have () as result --using the default we would get [()] --The count of Units is often not usefull so this just returns () --While consuming many sepIsos manySep :: Syntax () -> Syntax () manySep iso = (manySep iso <+> id) . iso <+> insert () ------------------------------------------------------------------------------- --State Helpers ------------------------------------------------------------------------------- --JAI setJai :: SynMonad t State => JJCTTS -> (t ME) () setJai a = modify (\s -> s {sJAI = Just a}) rmJai :: SynMonad t State => (t ME) () rmJai = modify (\s -> s {sJAI = Nothing}) --XU addXU :: SynMonad t State => Atom -> (t ME) () addXU a = modify (\s -> s {sXU = a:(sXU s)}) rmXU :: SynMonad t State => Atom -> (t ME) () rmXU a = modify (\s -> s {sXU = delete a (sXU s)}) addXUIso :: SynIso Atom Atom addXUIso = Iso f g where f a = addXU a >> pure a g a = rmXU a >> pure a --CTX setCtx :: SynMonad t State => [Atom] -> (t ME) () setCtx a = modify (\s -> s {sCtx = a}) setNow :: SynMonad t State => Atom -> (t ME) () setNow a = modify (\s -> s {sNow = a}) setPrimaryCtx :: SynMonad t State => Atom -> (t ME) () setPrimaryCtx a = modify (\s -> s {sCtx = a : sCtx s}) addCtx :: SynMonad t State => Atom -> (t ME) () addCtx a = modify (\s -> s {sCtx = (sCtx s) ++ [a]}) --Atoms setAtoms :: SynMonad t State => [Atom] -> (t ME) () setAtoms a = modify (\s -> s {sAtoms = a}) getAtoms :: SynMonad t State => (t ME) [Atom] getAtoms = gets sAtoms gsAtoms :: SynIso () [Atom] gsAtoms = Iso f g where f _ = do as <- getAtoms setAtoms [] pure as g a = setAtoms a rmAtom :: SynMonad t State => Atom -> (t ME) () rmAtom a = modify (\s -> s {sAtoms = delete a (sAtoms s)}) pushAtom :: SynMonad t State => Atom -> (t ME) () pushAtom a = modify (\s -> s {sAtoms = a : sAtoms s}) pushAtoms :: SynMonad t State => [Atom] -> (t ME) () pushAtoms a = modify (\s -> s {sAtoms = a ++ sAtoms s}) popAtom :: SynMonad t State => (t ME) Atom popAtom = do atoms <- gets sAtoms let ([a],as) = splitAt 1 atoms setAtoms as pure a popAtoms :: SynMonad t State => Int -> (t ME) [Atom] popAtoms i = do atoms <- gets sAtoms let (a,as) = splitAt i atoms setAtoms as pure a consAtoms :: SynIso Atom [Atom] consAtoms = Iso f g where f a = do atoms <- gets sAtoms pure (a:atoms) g (a:atoms) = do setAtoms atoms pure a appendAtoms :: Int -> SynIso [Atom] [Atom] appendAtoms i = Iso f g where f as = do atoms <- gets sAtoms pure (as++atoms) g atoms = do let (a,as) = splitAt i atoms setAtoms as pure a --Add a fixed number of Atoms to the State toState :: Int -> SynIso [Atom] () toState i = Iso f g where f as = if length as == i then pushAtoms as else lift $ Left "List has wrong lenght, is this intended?" g () = popAtoms i fstToState :: Int -> SynIso ([Atom],a) a fstToState i = iunit . commute . first (toState i) sndToState :: Int -> SynIso (a,[Atom]) a sndToState i = iunit . second (toState i) --TypedVariableLinks pushTVLs :: SynMonad t State => [Atom] -> (t ME) () pushTVLs a = modify (\s -> s {sTVLs = a ++ sTVLs s}) setTVLs :: SynMonad t State => [Atom] -> (t ME) () setTVLs a = modify (\s -> s {sTVLs = a}) --Clean State withCleanState :: Syntax a -> Syntax a withCleanState syn = Iso f g where f () = do state <- get put (cleanState state) res <- apply syn () state2 <-get put (mergeState state state2) pure res g a = unapply syn a cleanState :: State -> State cleanState s = State {sFlags = M.empty ,sAtoms = [] ,sTVLs = [] ,sText = sText s ,sSeed = sSeed s ,sNow = sNow s ,sCtx = sCtx s ,sJAI = Nothing ,sDA = sDA s ,sDaM = sDaM s ,sXU = []} mergeState :: State -> State -> State mergeState s1 s2 = State {sFlags = sFlags s1 ,sAtoms = sAtoms s1 ,sTVLs = sTVLs s2 ,sText = sText s2 ,sSeed = sSeed s2 ,sNow = sNow s1 ,sCtx = sCtx s1 ,sJAI = sJAI s1 ,sDA = sDA s2 ,sDaM = sDaM s2 ,sXU = sXU s1} withEmptyState :: SynIso a b -> SynIso a b withEmptyState iso = Iso f g where f a = do atoms <- gets sAtoms setAtoms [] b <- apply iso a pushAtoms atoms pure b g = unapply iso --Seed setSeed :: SynMonad t State => Int -> (t ME) () setSeed i = modify (\s -> s {sSeed = i}) -- DA Function setDAF :: SynMonad t State => (Atom -> Atom) -> (t ME) () setDAF f = modify (\s -> s {sDA = f}) --DA instantiations setDa :: SynMonad t State => String -> Atom -> (t ME) () setDa da a = modify (\s -> s {sDaM = M.insert da a (sDaM s)}) unsetDA :: SynMonad t State => String -> (t ME) () unsetDA da = modify (\s -> s {sDaM = M.delete da (sDaM s)}) getDA :: SynMonad t State => String -> (t ME) (Maybe Atom) getDA da = do das <- gets sDaM pure $ M.lookup da das --Flags setFlag :: SynMonad t State => Flag -> (t ME) () setFlag f = modify (\s -> s {sFlags = M.insert f "" (sFlags s) }) setFlagValue :: SynMonad t State => Flag -> String -> (t ME) () setFlagValue f v = modify (\s -> s {sFlags = M.insert f v (sFlags s) }) getFlagValue :: SynMonad t State => Flag -> (t ME) String getFlagValue f = do flags <- gets sFlags case M.lookup f flags of Just a -> pure a Nothing -> lift $ Left $ "Flag: " ++ f ++ " doesn't exist." getFlagValueIso :: Flag -> SynIso () String getFlagValueIso flag = Iso f g where f () = getFlagValue flag g s = setFlagValue flag s --Set or Read the Flag Value setFlagValueIso :: Flag -> SynIso String () setFlagValueIso flag = inverse (getFlagValueIso flag) rmFlag :: SynMonad t State => Flag -> (t ME) () rmFlag f = modify (\s -> s {sFlags = M.delete f (sFlags s)}) --Set or Delete the Flag Value setFlagValueIso2 :: Flag -> String -> SynIso a a setFlagValueIso2 flag val = Iso f g where f a = setFlagValue flag val >> pure a g a = rmFlag flag >> pure a --Set or Delete the Flat with no Value setFlagIso :: Flag -> SynIso a a setFlagIso flag = Iso f g where f a = setFlag flag >> pure a g a = rmFlag flag >> pure a rmFlagIso :: Flag -> SynIso a a rmFlagIso flag = inverse $ setFlagIso flag --Run SynIso with Flag set and remove the Flag afterwards withFlag :: Flag -> SynIso a b -> SynIso a b withFlag flag syn = rmFlagIso flag . syn . setFlagIso flag --Run SynIso with Flag and Value set and remove the Flag afterwards withFlagValue :: Flag -> String -> SynIso a b -> SynIso a b withFlagValue flag val syn = inverse (setFlagValueIso2 flag val) . syn . setFlagValueIso2 flag val toggleFlag :: Flag -> SynIso a a toggleFlag f = setFlagIso f . ifNotFlag f <+> rmFlagIso f . ifFlag f --Iso that fails if flag is not Set ifFlag :: Flag -> SynIso a a ifFlag flag = Iso f f where f a = do flags <- gets sFlags if flag `M.member` flags then pure a else lift $ Left $ "Flag: " ++ flag ++ " is not set." --Iso that fails if flag doesn't have Value ifFlagVlaue :: Flag -> String -> SynIso a a ifFlagVlaue flag val = Iso f f where f a = do value <- getFlagValue flag if value == val then pure a else lift $ Left $ "Flag: " ++ flag ++ " doesn't have value" ++ val --Iso that fails if flag is set ifNotFlag :: Flag -> SynIso a a ifNotFlag flag = Iso f f where f a = do flags <- gets sFlags if flag `M.member` flags then lift $ Left $ "Flag: " ++ flag ++ " is set." else pure a --Left if Flag else Right switchOnFlag :: Flag -> SynIso a (Either a a) switchOnFlag flag = Iso f g where f a = do flags <- gets sFlags if flag `M.member` flags then pure (Left a) else pure (Right a) g (Left a) = setFlag flag >> pure a g (Right a) = pure a --Left if a has Value else Right switchOnValue :: Eq a => a -> SynIso a (Either a a) switchOnValue val = mkIso f g where f a = if a == val then Left a else Right a g (Left a) = a g (Right a) = a --Left if Flag has Value else Right switchOnFlagValue :: Eq a => Flag -> String -> SynIso a (Either a a) switchOnFlagValue flag val = Iso f g where f a = do flagval <- getFlagValue flag if flagval == val then pure (Left a) else pure (Right a) g (Left a) = setFlagValue flag val >> pure a g (Right a) = pure a
ngeiswei/opencog
opencog/nlp/lojban/HaskellLib/src/OpenCog/Lojban/Syntax/Util.hs
agpl-3.0
11,755
0
14
3,418
4,814
2,446
2,368
-1
-1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ko-KR"> <title>FuzzDB Files</title> <maps> <homeID>fuzzdb</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/fuzzdb/src/main/javahelp/help_ko_KR/helpset_ko_KR.hs
apache-2.0
960
77
66
156
407
206
201
-1
-1
-- Check that the record selector for maskMB unfolds in the body of f -- At one stage it didn't because the implicit unfolding looked too big -- #2581 module ShouldCompile where import Data.Array.Base data MBloom s a = MB { shiftMB :: {-# UNPACK #-} !Int , maskMB :: {-# UNPACK #-} !Int , bitArrayMB :: {-# UNPACK #-} !(STUArray s Int Int) } f a b c = case maskMB (MB a b c) of 3 -> True _ -> False
sdiehl/ghc
testsuite/tests/eyeball/record1.hs
bsd-3-clause
444
0
11
128
99
57
42
9
2
{-# LANGUAGE BangPatterns, GeneralizedNewtypeDeriving #-} module Distribution.Server.Features.Search.TermBag ( TermId, TermBag, size, fromList, elems, termCount, ) where import Distribution.Server.Framework.MemSize import qualified Data.Vector.Unboxed as Vec import qualified Data.Map as Map import Data.Word (Word32) import Data.Bits newtype TermId = TermId Word32 deriving (Eq, Ord, Show, Enum, MemSize) instance Bounded TermId where minBound = TermId 0 maxBound = TermId 0x00FFFFFF data TermBag = TermBag !Int !(Vec.Vector TermIdAndCount) deriving Show -- We sneakily stuff both the TermId and the bag count into one 32bit word type TermIdAndCount = Word32 -- Bottom 24 bits is the TermId, top 8 bits is the bag count termIdAndCount :: TermId -> Int -> TermIdAndCount termIdAndCount (TermId termid) freq = (min (fromIntegral freq) 255 `shiftL` 24) .|. (termid .&. 0x00FFFFFF) getTermId :: TermIdAndCount -> TermId getTermId word = TermId (word .&. 0x00FFFFFF) getTermCount :: TermIdAndCount -> Int getTermCount word = fromIntegral (word `shiftR` 24) size :: TermBag -> Int size (TermBag sz _) = sz elems :: TermBag -> [TermId] elems (TermBag _ vec) = map getTermId (Vec.toList vec) termCount :: TermBag -> TermId -> Int termCount (TermBag _ vec) = binarySearch 0 (Vec.length vec - 1) where binarySearch :: Int -> Int -> TermId -> Int binarySearch !a !b !key | a > b = 0 | otherwise = let mid = (a + b) `div` 2 tidAndCount = vec Vec.! mid in case compare key (getTermId tidAndCount) of LT -> binarySearch a (mid-1) key EQ -> getTermCount tidAndCount GT -> binarySearch (mid+1) b key fromList :: [TermId] -> TermBag fromList termids = let bag = Map.fromListWith (+) [ (t, 1) | t <- termids ] sz = Map.foldl' (+) 0 bag vec = Vec.fromListN (Map.size bag) [ termIdAndCount termid freq | (termid, freq) <- Map.toAscList bag ] in TermBag sz vec instance MemSize TermBag where memSize (TermBag _ vec) = 2 + memSizeUVector 2 vec
mpickering/hackage-server
Distribution/Server/Features/Search/TermBag.hs
bsd-3-clause
2,174
0
15
558
695
371
324
60
3
{-# LANGUAGE GADTs #-} {-# LANGUAGE ConstraintKinds #-} -- | Facilities for changing the lore of some fragment, with no context. module Futhark.Analysis.Rephrase ( rephraseProg , rephraseFunDef , rephraseExp , rephraseBody , rephraseStm , rephraseLambda , rephraseExtLambda , rephrasePattern , rephrasePatElem , Rephraser (..) , castStm ) where import Control.Applicative import Prelude import Futhark.Representation.AST data Rephraser m from to = Rephraser { rephraseExpLore :: ExpAttr from -> m (ExpAttr to) , rephraseLetBoundLore :: LetAttr from -> m (LetAttr to) , rephraseFParamLore :: FParamAttr from -> m (FParamAttr to) , rephraseLParamLore :: LParamAttr from -> m (LParamAttr to) , rephraseBodyLore :: BodyAttr from -> m (BodyAttr to) , rephraseRetType :: RetType from -> m (RetType to) , rephraseBranchType :: BranchType from -> m (BranchType to) , rephraseOp :: Op from -> m (Op to) } rephraseProg :: Monad m => Rephraser m from to -> Prog from -> m (Prog to) rephraseProg rephraser = fmap Prog . mapM (rephraseFunDef rephraser) . progFunctions rephraseFunDef :: Monad m => Rephraser m from to -> FunDef from -> m (FunDef to) rephraseFunDef rephraser fundec = do body' <- rephraseBody rephraser $ funDefBody fundec params' <- mapM (rephraseParam $ rephraseFParamLore rephraser) $ funDefParams fundec rettype' <- mapM (rephraseRetType rephraser) $ funDefRetType fundec return fundec { funDefBody = body', funDefParams = params', funDefRetType = rettype' } rephraseExp :: Monad m => Rephraser m from to -> Exp from -> m (Exp to) rephraseExp = mapExpM . mapper rephraseStm :: Monad m => Rephraser m from to -> Stm from -> m (Stm to) rephraseStm rephraser (Let pat (StmAux cs attr) e) = Let <$> rephrasePattern (rephraseLetBoundLore rephraser) pat <*> (StmAux cs <$> rephraseExpLore rephraser attr) <*> rephraseExp rephraser e rephrasePattern :: Monad m => (from -> m to) -> PatternT from -> m (PatternT to) rephrasePattern f (Pattern context values) = Pattern <$> rephrase context <*> rephrase values where rephrase = mapM $ rephrasePatElem f rephrasePatElem :: Monad m => (from -> m to) -> PatElemT from -> m (PatElemT to) rephrasePatElem rephraser (PatElem ident BindVar from) = PatElem ident BindVar <$> rephraser from rephrasePatElem rephraser (PatElem ident (BindInPlace src is) from) = PatElem ident (BindInPlace src is) <$> rephraser from rephraseParam :: Monad m => (from -> m to) -> ParamT from -> m (ParamT to) rephraseParam rephraser (Param name from) = Param name <$> rephraser from rephraseBody :: Monad m => Rephraser m from to -> Body from -> m (Body to) rephraseBody rephraser (Body lore bnds res) = Body <$> rephraseBodyLore rephraser lore <*> mapM (rephraseStm rephraser) bnds <*> pure res rephraseLambda :: Monad m => Rephraser m from to -> Lambda from -> m (Lambda to) rephraseLambda rephraser lam = do body' <- rephraseBody rephraser $ lambdaBody lam params' <- mapM (rephraseParam $ rephraseLParamLore rephraser) $ lambdaParams lam return lam { lambdaBody = body', lambdaParams = params' } rephraseExtLambda :: Monad m => Rephraser m from to -> ExtLambda from -> m (ExtLambda to) rephraseExtLambda rephraser lam = do body' <- rephraseBody rephraser $ extLambdaBody lam params' <- mapM (rephraseParam $ rephraseLParamLore rephraser) $ extLambdaParams lam return lam { extLambdaBody = body', extLambdaParams = params' } mapper :: Monad m => Rephraser m from to -> Mapper from to m mapper rephraser = identityMapper { mapOnBody = const $ rephraseBody rephraser , mapOnRetType = rephraseRetType rephraser , mapOnBranchType = rephraseBranchType rephraser , mapOnFParam = rephraseParam (rephraseFParamLore rephraser) , mapOnLParam = rephraseParam (rephraseLParamLore rephraser) , mapOnOp = rephraseOp rephraser } -- | Convert a binding from one lore to another, if possible. castStm :: (SameScope from to, ExpAttr from ~ ExpAttr to, BodyAttr from ~ BodyAttr to, RetType from ~ RetType to, BranchType from ~ BranchType to) => Stm from -> Maybe (Stm to) castStm = rephraseStm caster where caster = Rephraser { rephraseExpLore = Just , rephraseBodyLore = Just , rephraseLetBoundLore = Just , rephraseFParamLore = Just , rephraseLParamLore = Just , rephraseOp = const Nothing , rephraseRetType = Just , rephraseBranchType = Just }
ihc/futhark
src/Futhark/Analysis/Rephrase.hs
isc
4,856
0
12
1,268
1,481
733
748
96
1
class Foo a where foo :: Int -> a data Emp = Emp String Int deriving (Eq, Show) data Tmp = Tmp String Int deriving (Eq, Show) instance Foo Emp where foo x = Emp "Permanent" x instance Foo Tmp where foo x = Tmp "Temporary" x test x y = if x == y then True else False x = 42 plus = (20.5+) hola :: (Num a) => a -> String hola 1 = "OK" hola _ = "Not OK" --a = ((1::Num a => a) == (1::Num a => a)) z = 2
gitrookie/functionalcode
code/Haskell/retpoly.hs
mit
472
0
7
168
181
96
85
19
2
{-# OPTIONS -Wall #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} import qualified Data.List as List import qualified Data.Map.Strict as Map import qualified Data.Maybe as Maybe import Data.Text (Text) import Helpers.Graph (Graph) import qualified Helpers.Graph as Graph import Helpers.Parse import Text.Parsec type Polymer = String main :: IO () main = do (template, rules) <- parseTextIO parser let steps = iterate (insertBetweenPairs rules) template let step = steps !! 10 let counts :: [Int] = List.sort $ Map.elems $ Map.fromListWith (+) $ map (,1) step let answer = last counts - head counts print answer insertBetweenPairs :: Graph Polymer -> Polymer -> Polymer insertBetweenPairs rules template = let pairs = zip template (tail template) in head template : concatMap (\(a, b) -> Maybe.fromJust (Graph.lookupOnly [a, b] rules) ++ [b]) pairs parser :: Parsec Text () (Polymer, Graph Polymer) parser = do template <- polymer <* string "\n\n" rules <- Graph.directedGraph <$> rule `endBy` string "\n" return (template, rules) where polymer = many1 letter rule = do start <- polymer _ <- string " -> " end <- polymer return (start, end)
SamirTalwar/advent-of-code
2021/AOC_14_1.hs
mit
1,226
0
15
244
440
230
210
35
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} module ProducerExample where import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar) import Control.Exception (bracket) import Control.Monad (forM_) import Control.Monad.IO.Class (MonadIO(..)) import Data.ByteString (ByteString) import Data.ByteString.Char8 (pack) import Kafka.Consumer (Offset) import Kafka.Producer import Data.Text (Text) -- Global producer properties producerProps :: ProducerProperties producerProps = brokersList ["localhost:9092"] <> sendTimeout (Timeout 10000) <> setCallback (deliveryCallback print) <> logLevel KafkaLogDebug -- Topic to send messages to targetTopic :: TopicName targetTopic = "kafka-client-example-topic" mkMessage :: Maybe ByteString -> Maybe ByteString -> ProducerRecord mkMessage k v = ProducerRecord { prTopic = targetTopic , prPartition = UnassignedPartition , prKey = k , prValue = v } -- Run an example runProducerExample :: IO () runProducerExample = bracket mkProducer clProducer runHandler >>= print where mkProducer = newProducer producerProps clProducer (Left _) = return () clProducer (Right prod) = closeProducer prod runHandler (Left err) = return $ Left err runHandler (Right prod) = sendMessages prod sendMessages :: KafkaProducer -> IO (Either KafkaError ()) sendMessages prod = do putStrLn "Producer is ready, send your messages!" msg1 <- getLine err1 <- produceMessage prod (mkMessage Nothing (Just $ pack msg1)) forM_ err1 print putStrLn "One more time!" msg2 <- getLine err2 <- produceMessage prod (mkMessage (Just "key") (Just $ pack msg2)) forM_ err2 print putStrLn "And the last one..." msg3 <- getLine err3 <- produceMessage prod (mkMessage (Just "key3") (Just $ pack msg3)) -- errs <- produceMessageBatch prod -- [ mkMessage (Just "b-1") (Just "batch-1") -- , mkMessage (Just "b-2") (Just "batch-2") -- , mkMessage Nothing (Just "batch-3") -- ] -- forM_ errs (print . snd) putStrLn "Thank you." return $ Right () -- | An example for sending messages synchronously using the 'produceMessage'' -- function -- sendMessageSync :: MonadIO m => KafkaProducer -> ProducerRecord -> m (Either KafkaError Offset) sendMessageSync producer record = liftIO $ do -- Create an empty MVar: var <- newEmptyMVar -- Produce the message and use the callback to put the delivery report in the -- MVar: res <- produceMessage' producer record (putMVar var) case res of Left (ImmediateError err) -> pure (Left err) Right () -> do -- Flush producer queue to make sure you don't get stuck waiting for the -- message to send: flushProducer producer -- Wait for the message's delivery report and map accordingly: takeMVar var >>= return . \case DeliverySuccess _ offset -> Right offset DeliveryFailure _ err -> Left err NoMessageError err -> Left err
haskell-works/kafka-client
example/ProducerExample.hs
mit
3,229
0
17
862
728
369
359
64
4
module Main where import Test.QuickCheck import Test.QuickCheck.Gen (oneof) -- Trivial data Trivial = Trivial deriving (Eq, Show) trivialGen :: Gen Trivial trivialGen = return Trivial instance Arbitrary Trivial where arbitrary = trivialGen -- Identity data Identity a = Identity a deriving (Eq, Show) instance Arbitrary a => Arbitrary (Identity a) where arbitrary = identityGen identityGen :: Arbitrary a => Gen (Identity a) identityGen = do a <- arbitrary return (Identity a) identityGenInt :: Gen (Identity Int) identityGenInt = identityGen data Pair a b = Pair a b deriving (Eq, Show) pairGen :: (Arbitrary a, Arbitrary b) => Gen (Pair a b) pairGen = do a <- arbitrary b <- arbitrary return (Pair a b) instance (Arbitrary a, Arbitrary b) => Arbitrary (Pair a b) where arbitrary = pairGen pairGenIntString :: Gen (Pair Int String) pairGenIntString = pairGen data Sum a b = First a | Second b deriving (Eq,Show) sumGenEqual :: (Arbitrary a, Arbitrary b) => Gen (Sum a b) sumGenEqual = do a <- arbitrary b <- arbitrary oneof [return $ First a, return $ Second b] sumGenCharInt :: Gen (Sum Char Int) sumGenCharInt = sumGenEqual -- Let's leave it for now -- instance (Arbitrary a, -- Arbitrary b) => -- Gen (Sum a b) -- arbitrary = sumGenEqual -- Here we use the same idea as in Bounded class. sumGenFirstPls :: (Arbitrary a, Arbitrary b) => Gen (Sum a b) sumGenFirstPls = do a <- arbitrary b <- arbitrary frequency [(10, return $ First a), (1, return $ Second b)] sumGenCharIntFirst :: Gen (Sum Char Int) sumGenCharIntFirst = sumGenFirstPls main :: IO () main = do sample trivialGen
raventid/coursera_learning
haskell/chapter14/kicking-around-quickcheck/app/Main.hs
mit
1,802
0
11
490
585
307
278
64
1
{- Inductive program synthesis : Agent training Author: Abdul Rahim Nizamani, ITIT, Gothenburg University, Sweden Started: 2013-09-29 Updated: 2013-09-29 -} {-# LANGUAGE DataKinds #-} module Main where import System.Environment (getArgs, getProgName) import Niz import Parsing import Data.Char import Instances import Interpreter import Data.List import Data.Word import Data.Maybe import Language.Haskell.Syntax import Language.Haskell.Parser import qualified Language.Haskell.Pretty as P import System.IO import Haskell import Data.Maybe (isNothing) import Control.Monad (foldM) import Control.Parallel.Strategies import Debug.Trace type Delta = [Axiom] noSrc = SrcLoc "" 0 0 ansatz :: Language -> [HsExp] ansatz "List" = [HsApp (HsVar (UnQual (HsIdent "rev"))) (HsVar (UnQual (HsIdent "x"))), HsApp (HsVar (UnQual (HsIdent "rev"))) (HsList [] )] ansatz "Math" = [--HsApp (HsVar (UnQual (HsIdent "f"))) (HsVar (UnQual (HsIdent "x"))), --HsApp (HsVar (UnQual (HsIdent "f"))) (HsLit (HsInt 0)), --HsApp (HsVar (UnQual (HsIdent "f"))) (HsInfixApp (HsVar (UnQual (HsIdent "x"))) (HsQVarOp (UnQual (HsSymbol "+"))) (HsLit (HsInt 1))) HsInfixApp (HsVar (UnQual (HsIdent "x"))) (HsQVarOp (UnQual (HsIdent "g"))) (HsLit (HsInt 0)), HsInfixApp (HsVar (UnQual (HsIdent "x"))) (HsQVarOp (UnQual (HsIdent "g"))) (HsVar (UnQual (HsIdent "y"))), HsInfixApp (HsVar (UnQual (HsIdent "x"))) (HsQVarOp (UnQual (HsIdent "g"))) (HsInfixApp (HsVar (UnQual (HsIdent "y"))) (HsQVarOp (UnQual (HsSymbol "+"))) (HsLit (HsInt 1))) ] ansatz "Analogy2" = [HsApp (HsVar (UnQual (HsIdent "f"))) (HsVar (UnQual (HsIdent "x")))] ansatz _ = [] langUnits :: Language -> Int -> [HsExp] langUnits "Stream" 1 = [HsVar (UnQual (HsIdent x)) | x <- ["Alice","Plays","Bob","Crawls"]] langUnits "Math" 1 = [HsLit (HsInt x) | x <- [0..9]] --langUnits "Math" 2 = [HsLit (HsInt x) | x <- [10..99]] langUnits "Analogy2" 1 = [HsVar (UnQual (HsIdent "Palm")), HsVar (UnQual (HsIdent "Feet")), HsVar (UnQual (HsIdent "Sole"))] langUnits "List" 1 = [HsList []] langUnits "Clause" 1 = [HsCon (UnQual (HsIdent x)) | x <- ["A","B","C"]] langUnits _ _ = [] langOps :: Language -> Int -> [HsExp] langOps "List" 1 = [HsVar (UnQual (HsIdent "rev"))] langOps "List" 2 = [HsVar (UnQual (HsSymbol "++"))] langOps "Math" 2 = [HsVar (UnQual (HsSymbol "+"))] -- ,HsVar (UnQual (HsIdent "g")) ] -- ,HsVar (UnQual (HsSymbol "*"))] langOps "Analogy2" 1 = [HsVar (UnQual (HsIdent "under")),HsVar (UnQual (HsIdent "f2"))] langOps "Clause" 1 = [HsVar (UnQual (HsIdent x)) | x <- ["raven","black"]] langOps _ _ = [] printMessage = do p <- getProgName putStrLn $ "Usage: " ++ p ++ " agent.hs" putStrLn $ " where: agent.hs contains the agent description and memory" -- | Save an agent in a file saveAgent :: Agent -> FilePath -> IO () saveAgent (Agent comments (width,depth,sol) lang file axioms) filename = do writeFile filename comments appendFile filename $ "-}\n" appendFile filename $ unlines $ map showAxiom axioms appendFile filename $ "\n" main :: IO () main = do args <- getArgs if length args < 1 then printMessage else do let [agentfile] = take 1 args agent' <- parseAgent agentfile if isNothing agent' then do putStrLn $ "Error reading agent." return () else do let (Just agent@(Agent c (width,depth,sol) lang file _)) = agent' (pos,neg) <- parseTrainingFile file expnew <- findDelta 0 agent neg pos --expnew <- trainAgent agent if null (fst expnew) then do --putStrLn $ "All examples solved. Nothing to learn." return () else do putStrLn $ "\nLearned this rule: " putStrLn . unlines . map showAxiom $ fst expnew putStrLn . show $ snd expnew putStrLn $ "Do you want the agent to remember it? (Y/n) " c <- getChar if c == 'n' || c == 'N' then do return () else do let (Agent c (width,depth,sol) lang file axioms) = agent let newltm = union axioms (fst expnew) let newagent = Agent c (width,depth,sol) lang file newltm saveAgent newagent agentfile putStrLn $ "Stored in memory." findDelta :: Int -> Agent -> [IP] -> [IP] -> IO ([Axiom],Int) findDelta len ag _ _ | len < 0 = return ([],0) findDelta len agent neg posex = do let (Agent c (width,depth,sol) lang file ltm) = agent let pos = [x | x@(IP p e v) <- posex, e /= HsVar (UnQual (HsIdent "x"))] let ded = [x | x@(IP p (HsVar (UnQual (HsIdent "x"))) v) <- posex] let posAxioms = [p :->> e | IP p e v <- pos] let optimum = sum ([v | IP p e v <- pos, v > 0] ++ [v | IP p e v <- ded, v > 0]) if optimum < 1 then return ([],0) else do if len > sum (map size pos) then do putStrLn $ "Size exceeded from " ++ show (sum (map size pos)) return (posAxioms,sum [v | (IP _ _ v) <- pos, v > 0]) else do if len > fromIntegral sol then do putStrLn $ "Maximum size reached: " ++ show sol return ([],0) else do if len < 1 then do ans <- mapM (findAnswerDecl ltm width depth) pos if and ans && not (null ans) then do newans <- mapM (findSolDecl ltm width depth) pos putStrLn $ "Computations1: " putStrLn $ unlines $ map (\x -> unlines $ map showState x) newans putStrLn $ "All examples solved. Nothing to learn.\n" return ([],0) else do newans <- mapM (findSolDecl ltm width depth) ded let lefts = [x | x@(Left _) <- (map fst (map head newans))] if null lefts && (not . null) ded then do putStrLn $ "Computations2: " putStrLn $ unlines $ map (\x -> unlines $ map showState x) newans putStrLn $ "All examples solved. Nothing to learn.\n" return ([],0) else findDelta 1 agent neg pos else do putStrLn $ "Searching at length: " ++ show len let funcs = [ (i, filter isPure (generateFuncsAll lang i pos)) | i <- [1..len] ] let delta2 = concat $ [ [[g1,g2],[g2,g1]] | i <- [1..(len `div` 2)], g1 <- fromJust (lookup i funcs), g2 <- fromJust (lookup (len-i) funcs), --isPure g1, --isPure g2, not (numberChange g1), not (numberChange g2), if i == (len-i) then g1 /= g2 else True, not (lhsNotSame g1 g2) ] let delta1 = [ [g] | g <- fromJust (lookup len funcs), not (numberChange g) --isPure g ] putStrLn $ " generated functions: " ++ show (length delta1 + length delta2) --appendFile "temp.txt" -- $ unlines $ map (\x -> concat . intersperse ", " $ map showAxiom x) delta let func delta = do result <- sequence $ parMap rpar (performance width depth sol ltm neg pos ded) delta let result' = [(x,y) | (Just x,y) <- result] let optimal = [(x,y) | (x,y) <- result', y == optimum] let best = maximum $ map snd result' let optimal' = [(x,y) | (x,y) <- result', y == best] if (not . null) optimal then do putStrLn $ "Optimal performance: " ++ show optimum putStrLn $ show (length optimal) ++ " optimal deltas found." let delta = chooseBestDelta optimal return $ Just delta else do if len == fromIntegral sol && (not . null) optimal' then do putStrLn $ "Best performance: " ++ show optimum putStrLn $ show (length optimal) ++ " best deltas found." let delta = chooseBestDelta optimal' return $ Just delta else return Nothing result2 <- func delta2 if result2 /= Nothing then return $ fromJust result2 else do result1 <- func delta1 if result1 /= Nothing then return $ fromJust result1 else findDelta (len+1) agent neg pos numberChange (HsLit (HsInt _) :->> _) = True numberChange (HsLit (HsInt _) :-> _) = True numberChange _ = False isPure (p :->> q) = let pvar = nub [HsVar e |(HsVar e) <- getSubExp p] qvar = nub [HsVar e |(HsVar e) <- getSubExp q] in null (qvar \\ pvar) isPure (p :-> q) = let pvar = nub [HsVar e |(HsVar e) <- getSubExp p] qvar = nub [HsVar e |(HsVar e) <- getSubExp q] in null (qvar \\ pvar) lhsNotSame ((HsVar _) :->> y) ((HsVar _) :->> q) = True lhsNotSame ((HsVar _) :->> y) ((HsVar _) :-> q) = True lhsNotSame ((HsVar _) :-> y) ((HsVar _) :-> q) = True lhsNotSame ((HsVar _) :-> y) ((HsVar _) :->> q) = True lhsNotSame (x :->> y) (p :->> q) = x == p lhsNotSame (x :-> y) (p :-> q) = x == p lhsNotSame _ _ = False ----------------------- chooseBestDelta :: [([Axiom],Int)] -> ([Axiom],Int) chooseBestDelta [] = ([],0) chooseBestDelta [x] = x chooseBestDelta deltas = let deltas' = [(ax,perf,length [p | p@(_ :->> _) <- ax]) | (ax,perf) <- deltas] maxArrowCount = maximum [arrows | (ax,perf,arrows) <- deltas'] deltas1 = [(ax,perf) | x@(ax,perf,arrows) <- deltas', arrows == maxArrowCount] in if length deltas1 == 1 then head deltas1 else let deltas2 = [(ax,perf,sum (map countVars ax)) | (ax,perf) <- deltas1] maxVarCount = maximum [varCount | (ax,perf,varCount) <- deltas2] deltas3 = [(ax,perf) | x@(ax,perf,vars) <- deltas2, vars == maxVarCount] in if length deltas3 == 1 then head deltas3 else head deltas3 countVars :: Axiom -> Int countVars (p :->> q) = countVars' p + countVars' q countVars (p :-> q) = countVars' p + countVars' q countVars' exp = length [HsVar e |(HsVar e) <- getSubExp exp] --learning :: Int -> Word -> Word -> HsModule -> [HsMatch] -> HsMatch -> IO (Maybe HsMatch) --learning len _ _ _ _ _ | len < 0 = return Nothing --learning 0 width depth ltm negex m@(HsMatch _ name pats (HsUnGuardedRhs rhs) _) = do -- let exp = foldl (\exp p -> HsApp exp (patToExp p)) (HsVar (UnQual name)) pats -- ans <- solveAnswer (fromIntegral width) (fromIntegral depth) ltm (Right exp, []) -- if ans == (Just rhs) -- then return Nothing -- else learning 1 width depth ltm negex m performance :: Int -> Int -> Int -> [Axiom] -> [IP] -> [IP] -> [IP] -> Delta -> IO (Maybe Delta,Int) performance width depth sol ltm negex pos ded func = do --putStrLn $ unlines $ map showAxiom func let ltm' = ltm ++ func ansPos <- mapM (\x@(IP _ _ y) -> do result <- findAnswerDecl ltm' width depth x return (result,y)) pos ansDed <- mapM (\x@(IP _ _ y) -> do result <- findSolDecl ltm' width depth x return (result,y)) ded ansNeg <- mapM (\x@(IP _ _ y) -> do result <- findAnswerDecl ltm' width depth x return (result,y)) negex let posUtil = sum [y | (True,y) <- ansPos] let dedUtil = sum [y | (sol,y) <- ansDed, (Right _,_) <- [head sol]] let negUtil = sum [y | (True,y) <- ansNeg] let util = posUtil + dedUtil - negUtil if or (map fst ansNeg) then return (Nothing,util) else do if and (map fst ansPos) then do if null [x | (x@(Left _),_) <- (map head (map fst ansDed))] then return (Just func,util) else return (Nothing,util) else return (Nothing,util) generateFuncsAll :: Language -> Int -> [IP] -> Delta generateFuncsAll _ len _ | len < 2 = [] generateFuncsAll lang len pos = let parts = [lhs | (IP lhs _ _) <- pos] ++ [rhs | (IP _ rhs _) <- pos] units = nub $ [x | x <- (concatMap getSubExp parts), size x == 1] ++ [HsVar (UnQual (HsIdent [c])) | c <- "x"] ++ langUnits lang 1 ++ ansatz lang unary = langOps lang 1 ++ [HsVar x | (HsApp (HsVar x) _) <- parts] binary = langOps lang 2 ++ [HsVar x | (HsInfixApp _ (HsQVarOp x) _) <- parts] funcs = [ (i, generateExps i units unary binary) | i <- [1..(len-1)] ] result = concat [ [p :->> q, q :->> p] | i <- [1 .. (len `div` 2)], p <- fromJust (lookup i funcs), q <- fromJust (lookup (len - i) funcs), if i == (len-i) then p /= q else True ] {- pats = nub [p' | i <- [1 .. (len-1)], p' <- generateLhs i units lhs, matchExpExp p' lhs] exps = [(HsApp (HsVar f) p) :->> exp | p <- pats, f <- [x | (HsApp (HsVar x) _) <- [lhs]], exp <- generateExps (len - (size p + 1)) units unary binary] ansatzExps = [p :->> rhs | -- p@(HsApp (HsVar (UnQual f)) ps) <- ansatz lang, p <- ansatz lang, rhs <- generateExps (len - 1) units unary binary] exps1 = [p :->> exp | p <- pats, exp <- generateExps (len - size p) units unary binary, matchExpExp exp rhs] exps2 = [p :->> rhs | p <- pats, size rhs == len - size p] result = (exps ++ exps1 ++ exps2 ++ ansatzExps) -- ++ expsexps) -} in result -- ++ [x :-> y | (x :->> y) <- result] -- generate patterns for expressions, given a list of patterns for element types -- for example, -- 5 -> _, x, 5 -- 5*3 -> x, 5*x, x*3, 5*3, x*y -- 1+2 -> x, 1+x, x+2, 1+2, x+y generateLhs :: Int -> [HsExp] -> HsExp -> [HsExp] generateLhs len _ _ | len < 1 = [] --generateLhs 1 units e@(HsInfixApp p qn q) -- only to generate (_ * _) -- = [HsInfixApp x qn y | x <- generateLhs 0 units p, -- y <- generateLhs 0 units q] -- ++ [u | u <- units, matchExpExp e u] generateLhs 1 units p = [u | u <- units] generateLhs len l (HsNegApp p) = (HsNegApp p) : (map HsNegApp $ generateLhs (len-1) l p) generateLhs len l (HsParen p) = (HsParen p) : (map HsParen $ generateLhs (len-1) l p) generateLhs len l (HsInfixApp p1 qn p2) = concat $ [ [HsInfixApp p1' qn p2' | p1' <- generateLhs i l p1, p2' <- generateLhs (len' - i) l p2] | i <- [0 .. len'] ] where len' = len - 1 generateLhs len l (HsApp qn p) = [HsApp qn x | x <- generateLhs (len-1) l p, matchExpExp p x] generateLhs len xs p@(HsList ps) = let pats = generateListPats len [] in pats ++ [HsInfixApp x (HsQConOp (Special HsCons)) y | x <- xs, y <- generateListPats (len - 1) (xs \\ [x])] generateLhs len xs p = [] generateExps :: Int -> [HsExp] -> [HsExp] -> [HsExp] -> [HsExp] generateExps len _ _ _ | len < 1 = [] generateExps 1 units _ _ = units generateExps 2 units funcs1 _ = [HsApp x y | x <- funcs1, y <- units] generateExps len units funcs1 funcs2 = let exps2 = generateExps (len-2) units funcs1 funcs2 exps1 = generateExps (len-1) units funcs1 funcs2 in [HsInfixApp x (HsQVarOp op) y | x <- exps2, y <- exps2, (HsVar op) <- funcs2] ++ [HsApp op arg | op <- funcs1, arg <- exps1] {- generateExps len units funcs1 funcs2 (HsInfixApp x (HsQConOp (Special HsCons)) y) = let exps = generateExps (len-1) units funcs1 funcs2 y lists = exps ++ [HsList [x]] ++ [HsInfixApp x (HsQConOp (Special HsCons)) l | l <- exps] in lists ++ [HsApp f l | l <- lists, f <- funcs1] ++ [HsInfixApp l1 (HsQVarOp f) l2 | l1 <- lists, l2 <- lists, (HsVar f) <- funcs2, (size l1 + size l2) < len ] generateExps len units funcs1 funcs2 p@(HsInfixApp x qn y) = result ++ [HsApp f r | f <- funcs1, r <- result, size r < len] where result = [HsInfixApp x qn y | x <- generateExps (len-2) units funcs1 funcs2 p, y <- generateExps (len-2) units funcs1 funcs2 p] -} -- generate patterns for list type, given a list of patterns for element types -- for example, given [1,x], it generates -- _, xs, [], (x:_), (x:[]), (x:xs), (1:_), (1:[]), (1:xs), (x:1:_), (1:x:_), ... generateListPats :: Int -> [HsExp] -> [HsExp] generateListPats len _ | len < 1 = [] generateListPats _ [] = [HsList [],HsVar (UnQual (HsIdent "l"))] generateListPats len xs = let listpats = generateListPats len [] in listpats ++ [HsInfixApp x (HsQConOp (Special HsCons)) y | x <- xs, y <- generateListPats (len - 1) (xs \\ [x])] -- generate a list of list expressions for each pattern -- the second argument is a list of functions of type :: [a] -> [a] -- the third argument is a list of functions of type :: [a] -> [a] -> [a] generateListExps :: Int -> [HsExp] -> [HsExp] -> HsExp -> [HsExp] generateListExps len _ _ _ | len < 1 = [HsList []] generateListExps _ _ _ HsWildCard = [HsList []] generateListExps _ _ _ (HsList []) = [HsList []] generateListExps len funcs1 funcs2 (HsVar x) = [HsVar x] ++ [HsApp f (HsVar x) | f <- funcs1] generateListExps len funcs1 funcs2 (HsInfixApp x (HsQConOp (Special HsCons)) y) = let exps = generateListExps (len-1) funcs1 funcs2 y lists = exps ++ [HsList [x]] ++ [HsInfixApp x (HsQConOp (Special HsCons)) l | l <- exps] in lists ++ [HsApp f l | l <- lists, f <- funcs1] ++ [HsInfixApp l1 (HsQVarOp f) l2 | l1 <- lists, l2 <- lists, (HsVar f) <- funcs2, (size l1 + size l2) < len] generateListExps _ _ _ _ = [HsList []] ------------------------------------------------------------------------------- -- HELPER FUNCTIONS ------------------------------------------------------------------------------- getInt :: Maybe HsExp -> Integer getInt (Just (HsLit (HsInt i))) = i getInt _ = 0 getString :: Maybe HsExp -> String getString (Just (HsLit (HsString s))) = s getString _ = "" -- check if the answer is the same as given, using Astar search findAnswerDecl :: [Axiom] -> Int -> Int -> IP -> IO Bool findAnswerDecl ltm width depth (IP exp rhs _) = do ans <- solveAnswer (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) (Just rhs) return (isJust ans && equalExp (fromJust ans,rhs)) --findAnswerDecl ltm width depth (HsFunBind [HsMatch loc name pats (HsUnGuardedRhs rhs) _]) = do -- let exp = foldl (\exp p -> HsApp exp (patToExp p)) (HsVar (UnQual name)) pats -- ans <- solveAnswer (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) (Just rhs) -- return (isJust ans && equalExp (fromJust ans,rhs)) -- find the solution (all proof steps) using the Astar search findSolDecl :: [Axiom] -> Int -> Int -> IP -> IO [StateD] -- if rhs is x, then search for any answer findSolDecl ltm width depth (IP exp (HsVar (UnQual (HsIdent "x"))) _) = do ans <- solve (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) Nothing if ans /= Nothing then return $ (Right (exp,Nothing), []) : fromJust ans else return $ [(Left "No solution found", [])] -- else search for the given answer findSolDecl ltm width depth (IP exp rhs _) = do ans <- solve (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) (Just rhs) if ans /= Nothing then return $ (Right (exp,Nothing), []) : fromJust ans else return $ [(Left "No solution found", [])] {- findSolDecl ltm width depth (HsFunBind [HsMatch loc name pats (HsUnGuardedRhs rhs) _]) = do let exp = foldl (\exp p -> HsApp exp (patToExp p)) (HsVar (UnQual name)) pats ans <- solve (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) (Just rhs) if ans /= Nothing then return $ (Right (exp,Nothing), []) : fromJust ans else return $ [(Left "No solution found", [])] findSolDecl ltm width depth (HsFunBind [HsMatch loc name pats (HsUnGuardedRhs (HsVar (UnQual (HsIdent "x")))) _]) = do let exp = foldl (\exp p -> HsApp exp (patToExp p)) (HsVar (UnQual name)) pats ans <- solve (fromIntegral width) (fromIntegral depth) ltm (Right (exp,Nothing), []) Nothing if ans /= Nothing then return $ (Right (exp,Nothing), []) : fromJust ans else return $ [(Left "No solution found", [])] -} ------------------------------------------------------------------------------- -- UNUSED CODE ------------------------------------------------------------------------------- -- | Generate all functions of the given length generateFuncs :: HsMatch -> Int -> [HsMatch] generateFuncs m len | len < 1 = [] generateFuncs (HsMatch loc name pats (HsUnGuardedRhs rhs) x) 1 = [] -- | size rhs == 1 -- = [HsMatch loc name [HsPWildCard] (HsUnGuardedRhs rhs) x] generateFuncs m@(HsMatch loc name pats (HsUnGuardedRhs rhs) x) 2 = [HsMatch loc name [HsPVar (HsIdent "x")] (HsUnGuardedRhs (HsVar (UnQual (HsIdent "x")))) x] ++ if size m == 2 then [m] else [] generateFuncs m@(HsMatch loc name pats (HsUnGuardedRhs rhs) x) len = if size m == len then [m] else []
arnizamani/occam
occam.hs
mit
22,531
27
23
7,345
6,981
3,591
3,390
-1
-1
{-# LANGUAGE TypeFamilies, GADTs, CPP #-} module Database.Selda.Selectors ( Assignment ((:=)), Selector, Coalesce , (!), (?), with, ($=) , selectorIndex, unsafeSelector ) where import Database.Selda.SqlRow (SqlRow) import Database.Selda.SqlType import Database.Selda.Column import Data.List (foldl') import Unsafe.Coerce -- | Coalesce nested nullable column into a single level of nesting. type family Coalesce a where Coalesce (Maybe (Maybe a)) = Coalesce (Maybe a) Coalesce a = a -- | A selector indicating the nth (zero-based) column of a table. -- -- Will cause errors in queries during compilation, execution, or both, -- unless handled with extreme care. You really shouldn't use it at all. unsafeSelector :: (SqlRow a, SqlType b) => Int -> Selector a b unsafeSelector = Selector -- | Extract the given column from the given row. (!) :: SqlType a => Row s t -> Selector t a -> Col s a (Many xs) ! (Selector i) = case xs !! i of Untyped x -> One (unsafeCoerce x) infixl 9 ! -- | Extract the given column from the given nullable row. -- Nullable rows usually result from left joins. -- If a nullable column is extracted from a nullable row, the resulting -- nested @Maybe@s will be squashed into a single level of nesting. (?) :: SqlType a => Row s (Maybe t) -> Selector t a -> Col s (Coalesce (Maybe a)) (Many xs) ? (Selector i) = case xs !! i of Untyped x -> One (unsafeCoerce x) infixl 9 ? upd :: Row s a -> Assignment s a -> Row s a upd (Many xs) (Selector i := (One x')) = case splitAt i xs of (left, _:right) -> Many (left ++ Untyped x' : right) _ -> error "BUG: too few columns in row!" upd (Many xs) (Modify (Selector i) f) = case splitAt i xs of (left, Untyped x:right) -> Many (left ++ f' (unsafeCoerce x) : right) _ -> error "BUG: too few columns in row!" where f' x = case f (One x) of One y -> Untyped y -- | A selector-value assignment pair. data Assignment s a where -- | Set the given column to the given value. (:=) :: Selector t a -> Col s a -> Assignment s t -- | Modify the given column by the given function. Modify :: Selector t a -> (Col s a -> Col s a) -> Assignment s t infixl 2 := -- | Apply the given function to the given column. ($=) :: Selector t a -> (Col s a -> Col s a) -> Assignment s t ($=) = Modify infixl 2 $= -- | For each selector-value pair in the given list, on the given tuple, -- update the field pointed out by the selector with the corresponding value. with :: Row s a -> [Assignment s a] -> Row s a with = foldl' upd -- | A column selector. Column selectors can be used together with the '!' and -- 'with' functions to get and set values on rows, or to specify -- foreign keys. newtype Selector t a = Selector {selectorIndex :: Int}
valderman/selda
selda/src/Database/Selda/Selectors.hs
mit
2,813
0
14
650
808
432
376
45
3
{-# LANGUAGE DeriveDataTypeable, CPP #-} import GetURL import TimeIt import Data.Either import Control.Monad import System.IO import Control.Concurrent hiding(forkFinally) import Control.Exception import Text.Printf import qualified Data.ByteString as B import Data.Typeable import Prelude hiding (catch) data Async a = Async ThreadId (MVar (Either SomeException a)) forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action fun = mask $ \restore -> forkIO (do r <- try (restore action); fun r) async :: IO a -> IO (Async a) async action = do m <- newEmptyMVar t <- forkFinally action (putMVar m) return (Async t m) waitCatch :: Async a -> IO (Either SomeException a) waitCatch (Async _ var) = readMVar var wait :: Async a -> IO a wait m = do r <- waitCatch m case r of Left e -> throwIO e Right a -> return a cancel :: Async a -> IO () cancel (Async t var) = throwTo t ThreadKilled sites = ["http://forec.cn", "https://cn.bing.com", "https://www.baidu.com", "https://ipv6.google.com"] timeDownload :: String -> IO () timeDownload url = do (page, time) <- timeit $ getURL url printf "downloaded: %s (%d bytes, %.2fs)\n" url (B.length page) time main = do as <- mapM (async . timeDownload) sites forkIO $ do hSetBuffering stdin NoBuffering forever $ do c <- getChar when (c == 'q') $ mapM_ cancel as rs <- mapM waitCatch as printf "%d/%d succeeded\n" (length (rights rs)) (length rs)
Forec/learn
2017.3/Parallel Haskell/ch10/geturlscancel2.hs
mit
1,569
0
16
387
582
286
296
49
2
module Glucose.Lexer.Location where import Data.Char import Glucose.Lexer.Char data Location = Location { codePoint, line, column :: Int } deriving (Eq, Ord) instance Show Location where show (Location cp line col) = show line ++ ":" ++ show col ++ "@" ++ show cp instance Read Location where readsPrec d s0 = [ (Location cp line col, s5) | (line, s1) <- readsPrec (d+1) s0 , (":", s2) <- lex s1 , (col, s3) <- readsPrec (d+1) s2 , ("@", s4) <- lex s3 , (cp, s5) <- readsPrec (d+1) s4] beginning :: Location beginning = Location 0 1 1 updateLocation :: Char -> Location -> Location updateLocation c (Location char line _) | isNewline c = Location (char+1) (line+1) 1 updateLocation c (Location char line col) | isControl c = Location (char+1) line col updateLocation _ (Location char line col) = Location (char+1) line (col+1) codePointsBetween :: Location -> Location -> Int codePointsBetween (Location start _ _) (Location end _ _) = end - start advance :: Location -> Int -> Location advance (Location cp line col) n = Location (cp + n) line (col + n) rewind :: Location -> Location rewind (Location _ _ 1) = error "Can't rewind a Location past a newline!" rewind (Location cp line col) = Location (cp-1) line (col-1)
sardonicpresence/glucose
src/Glucose/Lexer/Location.hs
mit
1,364
0
11
359
579
301
278
26
1
module PayPal.Identity ( createIdentity , getIdentity ) where createIdentity = undefined getIdentity = undefined
AndrewRademacher/hs-paypal-rest
src/PayPal/Identity.hs
mit
127
0
4
28
24
15
9
5
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE RecordWildCards #-} module Widgets.Tabs.Reviews ( panelReviews ) where import Control.Monad (join) import Commons import qualified Data.Text as T import Data.List (sortOn) import Data.Time.Format import QuaTypes.Review import Reflex.Dom import Widgets.Commons import Widgets.Generation panelReviews :: Reflex t => Dynamic t (Either JSError ReviewSettings) -> QuaWidget t x () panelReviews reviewSettingsD = do void $ dyn $ renderPanelReviews <$> reviewSettingsD renderPanelReviews :: Reflex t => Either JSError ReviewSettings -> QuaWidget t x () renderPanelReviews (Left _) = blank renderPanelReviews (Right reviewSettings) = do expertRespE <- renderWriteExpertReview reviewSettings respE <- renderWriteReview reviewSettings let revs = reverse . sortOn reviewTimestamp $ reviews reviewSettings reviewsE <- accum (flip ($)) revs $ leftmost [accumRevs <$> respE, onlyOneExpRev <$> expertRespE] let renderRevs = mapM_ $ renderReview $ criterions reviewSettings void $ widgetHold (renderRevs revs) (renderRevs <$> reviewsE) where accumRevs (Right newRev) revs = newRev:revs accumRevs (Left _) revs = revs onlyOneExpRev :: Either JSError Review -> [Review] -> [Review] onlyOneExpRev (Right newRev) revs = newRev : (filter (not . isMyExpertReview) revs) onlyOneExpRev (Left _) revs = revs -- draws the write-review-text-entry component if ReviewSettings contains `Just reviewsUrl`. -- Returns event of posted review, or error on unsuccessful post. renderWriteReview :: Reflex t => ReviewSettings -> QuaWidget t x (Event t (Either JSError Review)) renderWriteReview (ReviewSettings crits _ (Just revsUrl) _) = elAttr "div" ( "class" =: "card" <> "style" =: "padding: 0px; margin: 10px 0px 10px 0px" ) $ elClass "div" (T.unwords ["card-main", spaces2px, writeReviewClass]) $ mdo textD <- elClass "div" (T.unwords ["card-inner", spaces2px]) $ elClass "div" "form-group form-group-label" $ do tD <- renderTextArea resetTextE "Write a review" void $ dyn $ renderTxt <$> thumbD <*> critD return tD (critD, thumbD, clickE) <- elClass "div" (T.unwords ["card-action", spaces2px]) $ do cD <- renderCriterions crits tD <- renderThumbs cE <- buttonFlatDyn (hideState <$> critD <*> thumbD) "Send" mempty return (cD, tD, cE) let postDataOnClickE = (\th te c -> ReviewPost (criterionId c) th te) <$> current thumbD <*> current textD <@> fmapMaybe id (current critD <@ clickE) responseE <- httpPost $ (,) revsUrl <$> postDataOnClickE let reset (Right _) = Just "" reset _ = Nothing let resetTextE = fmapMaybe reset responseE renderError responseE return responseE where WidgetCSSClasses {..} = widgetCSS renderTxt _ Nothing = blank renderTxt None _ = blank renderTxt thumb (Just crit) = text $ toTxt thumb <> (textFromJSString $ criterionName crit) <> " " where toTxt ThumbUp = "Upvote " toTxt ThumbDown = "Downvote " toTxt None = "" renderWriteReview _ = return never renderReview :: Reflex t => [Criterion] -> Review -> QuaWidget t x () renderReview crits r = elClass "div" (T.unwords ["card", cardSpaces]) $ do case reviewRating r of ExpertRating _ -> pure () UserRating critId thumb -> elAttr "aside" ( "class" =: "card-side pull-left" <> "style" =: "background-color: #ffffff; width: 24px; margin: 2px; padding: 0px" ) $ do elClass "span" (T.unwords ["icon", icon24px, "text-brand-accent"]) $ text $ showThumb thumb renderCrit critId elClass "div" (T.unwords ["card-main", spaces0px]) $ elClass "div" (T.unwords ["card-inner", spaces2px]) $ do elClass "p" (T.unwords ["text-brand-accent", smallP]) $ do text $ T.pack $ ' ' : formatTime defaultTimeLocale "%F, %R - " (reviewTimestamp r) text $ textFromJSString $ reviewUserName r case reviewRating r of ExpertRating grade -> renderStars grade UserRating _ _ -> pure () elClass "p" smallP $ text $ textFromJSString $ reviewComment r where WidgetCSSClasses {..} = widgetCSS renderCrit critId = void $ for [ c | c <- crits, critId == criterionId c] $ \c -> do (spanEl, ()) <- elAttr' "span" ("style" =: "position: relative; top: 5px;") blank setInnerHTML spanEl $ criterionIcon c renderStars grade = let star t = elClass "span" "icon icon-lg" $ text t in sequence_ $ (Prelude.replicate grade $ star "star") ++ Prelude.replicate (5 - grade) (star "star_border") -- draws the write-expert-review-text-entry component -- if ReviewSettings contains `Just expertReviewsUrl`. -- Returns event of posted review, or error on unsuccessful post. renderWriteExpertReview :: Reflex t => ReviewSettings -> QuaWidget t x (Event t (Either JSError Review)) renderWriteExpertReview (ReviewSettings _ revs _ (Just revsUrl)) = elAttr "div" ( "class" =: "card" <> "style" =: "padding: 0px; margin: 10px 0px 10px 0px" ) $ elClass "div" (T.unwords ["card-main", spaces2px, writeReviewClass]) $ mdo textD <- elClass "div" (T.unwords ["card-inner", spaces2px]) $ elClass "div" "form-group form-group-label" $ join <$> widgetHold (renderTextArea resetTextE initLabel) (renderTextArea resetTextE <$> (updateReviewTxt <$ resetTextE)) (gradeD, clickE) <- elClass "div" (T.unwords ["card-action", spaces2px]) $ do gD <- renderGrade 0 cE <- buttonFlatDyn (hideZeroState <$> gradeD) "Grade" mempty return (gD, cE) let postDataOnClickE = (\txt grade -> ExpertReviewPost grade txt) <$> current textD <@> ffilter (> 0) (current gradeD <@ clickE) responseE <- httpPost $ (,) revsUrl <$> postDataOnClickE let reset (Right _) = Just "" reset _ = Nothing let resetTextE = fmapMaybe reset responseE renderError responseE return responseE where updateReviewTxt = "Update your expert review" writeReviewTxt = "Write an expert review" initLabel = if any isMyExpertReview revs then updateReviewTxt else writeReviewTxt WidgetCSSClasses {..} = widgetCSS renderWriteExpertReview _ = return never writeReviewClass :: Text writeReviewClass = $(do reviewCls <- newVar qcss [cassius| .#{reviewCls} .card-inner .form-group margin: 8px 0 0 0 width: 100% textarea resize: vertical .card-action min-height: 32px .btn-flat padding: 0 line-height: 14px |] returnVars [reviewCls] ) -- renders the `JSError` or blank renderError :: Reflex t => Event t (Either JSError a) -> QuaWidget t x () renderError event = do performEvent_ $ liftIO . print <$> (fst $ fanEither event) void $ widgetHold blank (renderErr <$> event) where renderErr (Left err) = el "div" $ text $ textFromJSString $ getJSError err renderErr (Right _) = blank -- render bootstrapified textarea and return dynamic of text it contains renderTextArea :: Reflex t => Event t Text -> Text -> QuaWidget t x (Dynamic t JSString) renderTextArea setValE label = do elAttr "label" ("class" =: "floating-label") $ text label let config = TextAreaConfig "" setValE $ constDyn ("class" =: "form-control") t <- textArea config return $ textToJSString <$> _textArea_value t -- | Render supplied criterios and return dynamic with criterionId of selected one renderCriterions :: Reflex t => [Criterion] -> QuaWidget t x (Dynamic t (Maybe Criterion)) renderCriterions crits = elClass "span" critsClass $ mdo let critE = leftmost critEs critEs <- for crits $ \c -> do let cTitle = "title" =: textFromJSString (criterionName c) activeStyle' = activeStyle <> cTitle inactiveStyle' = inactiveStyle <> cTitle chooseStyle mc _ | Just c' <- mc, criterionId c' == criterionId c = activeStyle' | otherwise = inactiveStyle' critAttrD <- foldDyn chooseStyle inactiveStyle' critE (spanEl, ()) <- elDynAttr' "span" critAttrD $ return () setInnerHTML spanEl $ criterionIcon c return $ Just c <$ domEvent Click spanEl holdDyn Nothing critE where critsClass = $(do critsCls <- newVar qcss [cassius| .#{critsCls} position: relative top: 5px margin-right: 15px span cursor: pointer &:hover opacity: 1 !important |] returnVars [critsCls] ) -- render grading stars and return dynamic of their state (0 is unselected) renderGrade :: Reflex t => Int -> QuaWidget t x (Dynamic t Int) renderGrade nrStartStars = mdo nrStarsD <- holdDyn nrStartStars nrStarsE nrStarsEE <- dyn (renderStars <$> nrStarsD) nrStarsE <- switchPromptly never nrStarsEE return nrStarsD where renderStars nr = do els <- sequence $ (Prelude.replicate nr $ renderStar "star") ++ (Prelude.replicate (5 - nr) $ renderStar "star_border") return $ leftmost $ (\(i, elm) -> i <$ domEvent Click elm) <$> Prelude.zip [1..] els renderStar t = fmap fst $ elClass' "span" (T.unwords ["icon","icon-lg", starsClass]) $ text t starsClass = $(do starsCls <- newVar qcss [cassius| .#{starsCls} cursor: pointer &:hover color: #ff6f00 |] returnVars [starsCls] ) -- render thumb-up and -down buttons and return dynamic of their state renderThumbs :: Reflex t => QuaWidget t x (Dynamic t ThumbState) renderThumbs = elClass "span" thumbsClass $ mdo let thumbE = leftmost [ ThumbUp <$ domEvent Click upEl , ThumbDown <$ domEvent Click dnEl ] let makeThumb upOrDown = do let chooseStyle th _ | th == upOrDown = activeStyle | otherwise = inactiveStyle thumbAttrD <- foldDyn chooseStyle inactiveStyle thumbE fst <$> elDynAttr' "span" (fmap (<> "class" =: "icon") thumbAttrD) (text $ showThumb upOrDown) upEl <- makeThumb ThumbUp dnEl <- makeThumb ThumbDown holdDyn None thumbE where thumbsClass = $(do thumbsCls <- newVar qcss [cassius| .#{thumbsCls} margin-right: 10px >span margin-right: 5px cursor: pointer &:hover opacity: 1 !important |] returnVars [thumbsCls] ) showThumb :: ThumbState -> Text showThumb ThumbUp = "thumb_up" showThumb ThumbDown = "thumb_down" showThumb None = "none" hideState :: Maybe a -> ThumbState -> ComponentState s hideState (Just _) ThumbUp = Active hideState (Just _) ThumbDown = Active hideState _ _ = Inactive hideZeroState :: Int -> ComponentState s hideZeroState 0 = Inactive hideZeroState _ = Active inactiveStyle :: Map Text Text inactiveStyle = "style" =: "opacity: 0.3" activeStyle :: Map Text Text activeStyle = "style" =: "opacity: 1" isMyExpertReview :: Review -> Bool isMyExpertReview rev = reviewIsMine rev && isExpertRating (reviewRating rev) where isExpertRating (ExpertRating _) = True isExpertRating _ = False
achirkin/qua-view
src/Widgets/Tabs/Reviews.hs
mit
12,801
10
23
4,106
3,247
1,590
1,657
252
6
{-# LANGUAGE OverloadedStrings #-} module IRTS.CodegenGo (codegenGo) where import Control.Monad.Trans.State.Strict (State, evalState, gets) import Data.Char (isAlphaNum, ord) import Data.Int (Int64) import qualified Data.Map.Strict as M import Data.Maybe (fromMaybe, mapMaybe) import qualified Data.Set as S import qualified Data.Text as T import qualified Data.Text.IO as TIO import Formatting (int, sformat, stext, string, (%)) import System.IO (IOMode (..), withFile) import System.Process (CreateProcess (..), StdStream (..), createProcess, proc, waitForProcess) import Idris.Core.TT hiding (V, arity) import IRTS.CodegenCommon import IRTS.Lang (FDesc (..), FType (..), LVar (..), PrimFn (..)) import IRTS.Simplified data Line = Line (Maybe Var) [Var] T.Text deriving (Show) data Var = RVal | V Int deriving (Show, Eq, Ord) newtype CGState = CGState { requiresTrampoline :: Name -> Bool } type CG a = State CGState a createCgState :: (Name -> Bool) -> CGState createCgState trampolineLookup = CGState { requiresTrampoline = trampolineLookup } goPreamble :: [T.Text] -> T.Text goPreamble imports = T.unlines $ [ "// THIS FILE IS AUTOGENERATED! DO NOT EDIT" , "" , "package main" , "" , "import (" , " \"flag\"" , " \"log\"" , " \"math/big\"" , " \"os\"" , " \"strconv\"" , " \"unicode/utf8\"" , " \"unsafe\"" , " \"runtime\"" , " \"runtime/pprof\"" , ")" , "" ] ++ map ("import " `T.append`) imports ++ [ "" , "func BigIntFromString(s string) *big.Int {" , " value, _ := big.NewInt(0).SetString(s, 10)" , " return value" , "}" , "" , "type Con0 struct {" , " tag int" , "}" , "" , "type Con1 struct {" , " tag int" , " _0 unsafe.Pointer" , "}" , "" , "type Con2 struct {" , " tag int" , " _0, _1 unsafe.Pointer" , "}" , "" , "type Con3 struct {" , " tag int" , " _0, _1, _2 unsafe.Pointer" , "}" , "" , "type Con4 struct {" , " tag int" , " _0, _1, _2, _3 unsafe.Pointer" , "}" , "" , "type Con5 struct {" , " tag int" , " _0, _1, _2, _3, _4 unsafe.Pointer" , "}" , "" , "type Con6 struct {" , " tag int" , " _0, _1, _2, _3, _4, _5 unsafe.Pointer" , "}" , "" , "var nullCons [256]Con0" , "" , "func GetTag(con unsafe.Pointer) int {" , " return (*Con0)(con).tag" , "}" , "" , "func MkCon0(tag int) unsafe.Pointer {" , " return unsafe.Pointer(&Con0{tag})" , "}" , "" , "func MkCon1(tag int, _0 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con1{tag, _0})" , "}" , "" , "func MkCon2(tag int, _0, _1 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con2{tag, _0, _1})" , "}" , "" , "func MkCon3(tag int, _0, _1, _2 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con3{tag, _0, _1, _2})" , "}" , "" , "func MkCon4(tag int, _0, _1, _2, _3 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con4{tag, _0, _1, _2, _3})" , "}" , "" , "func MkCon5(tag int, _0, _1, _2, _3, _4 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con5{tag, _0, _1, _2, _3, _4})" , "}" , "" , "func MkCon6(tag int, _0, _1, _2, _3, _4, _5 unsafe.Pointer) unsafe.Pointer {" , " return unsafe.Pointer(&Con6{tag, _0, _1, _2, _3, _4, _5})" , "}" , "" , "func MkIntFromBool(value bool) unsafe.Pointer {" , " if value {" , " return intOne" , " } else {" , " return intZero" , " }" , "}" , "" , "func MkInt(value int64) unsafe.Pointer {" , " var retVal *int64 = new(int64)" , " *retVal = value" , " return unsafe.Pointer(retVal)" , "}" , "" , "func MkRune(value rune) unsafe.Pointer {" , " var retVal *rune = new(rune)" , " *retVal = value" , " return unsafe.Pointer(retVal)" , "}" , "" , "func MkString(value string) unsafe.Pointer {" , " var retVal *string = new(string)" , " *retVal = value" , " return unsafe.Pointer(retVal)" , "}" , "" , "func RuneAtIndex(s string, index int) rune {" , " if index == 0 {" , " chr, _ := utf8.DecodeRuneInString(s)" , " return chr" , " } else {" , " i := 0" , " for _, chr := range s {" , " if i == index {" , " return chr" , " }" , " i++" , " }" , " }" , "panic(\"Illegal index: \" + string(index))" , "}" , "" , "func StrTail(s string) string {" , " _, offset := utf8.DecodeRuneInString(s)" , " return s[offset:]" , "}" , "" , "func WriteStr(str unsafe.Pointer) unsafe.Pointer {" , " _, err := os.Stdout.WriteString(*(*string)(str))" , " if (err != nil) {" , " return intZero" , " } else {" , " return intMinusOne" , " }" , "}" , "" , "func Go(action unsafe.Pointer) {" , " var th Thunk" , " go Trampoline(MkThunk2(&th, APPLY0, action, nil))" , "}" , "" , "func MkMaybe(value unsafe.Pointer, present bool) unsafe.Pointer {" , " if present {" , " return MkCon1(1, value)" , " } else {" , " return unsafe.Pointer(&nullCons[0])" , " }" , "}" , "" , "type Thunk0 func(*Thunk) unsafe.Pointer" , "type Thunk1 func(*Thunk, unsafe.Pointer) unsafe.Pointer" , "type Thunk2 func(*Thunk, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk3 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk4 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk5 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk6 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "type Thunk7 func(*Thunk, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer, unsafe.Pointer) unsafe.Pointer" , "" , "type Thunk struct {" , " arity int8" , " f0 Thunk0" , " f1 Thunk1" , " f2 Thunk2" , " f3 Thunk3" , " f4 Thunk4" , " f5 Thunk5" , " f6 Thunk6" , " f7 Thunk7" , " _0, _1, _2, _3, _4, _5, _6 unsafe.Pointer" , "}" , "" , "func (t *Thunk) Run() unsafe.Pointer {" , " switch t.arity {" , " case 0:" , " return t.f0(t)" , " case 1:" , " return t.f1(t, t._0)" , " case 2:" , " return t.f2(t, t._0, t._1)" , " case 3:" , " return t.f3(t, t._0, t._1, t._2)" , " case 4:" , " return t.f4(t, t._0, t._1, t._2, t._3)" , " case 5:" , " return t.f5(t, t._0, t._1, t._2, t._3, t._4,)" , " case 6:" , " return t.f6(t, t._0, t._1, t._2, t._3, t._4, t._5)" , " case 7:" , " return t.f7(t, t._0, t._1, t._2, t._3, t._4, t._5, t._6)" , " }" , " panic(\"Invalid arity: \" + string(t.arity))" , "}" , "" , "func MkThunk0(th *Thunk, f Thunk0) *Thunk {" , " th.arity = 0" , " th.f0 = f" , " return th" , "}" , "" , "func MkThunk1(th *Thunk, f Thunk1, _0 unsafe.Pointer) *Thunk {" , " th.arity = 1" , " th.f1 = f" , " th._0 = _0" , " return th" , "}" , "" , "func MkThunk2(th *Thunk, f Thunk2, _0, _1 unsafe.Pointer) *Thunk {" , " th.arity = 2" , " th.f2 = f" , " th._0 = _0" , " th._1 = _1" , " return th" , "}" , "" , "func MkThunk3(th *Thunk, f Thunk3, _0, _1, _2 unsafe.Pointer) *Thunk {" , " th.arity = 3" , " th.f3 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " return th" , "}" , "" , "func MkThunk4(th *Thunk, f Thunk4, _0, _1, _2, _3 unsafe.Pointer) *Thunk {" , " th.arity = 4" , " th.f4 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " th._3 = _3" , " return th" , "}" , "" , "func MkThunk5(th *Thunk, f Thunk5, _0, _1, _2, _3, _4 unsafe.Pointer) *Thunk {" , " th.arity = 5" , " th.f5 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " th._3 = _3" , " th._4 = _4" , " return th" , "}" , "" , "func MkThunk6(th *Thunk, f Thunk6, _0, _1, _2, _3, _4, _5 unsafe.Pointer) *Thunk {" , " th.arity = 6" , " th.f6 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " th._3 = _3" , " th._4 = _4" , " th._5 = _5" , " return th" , "}" , "" , "func MkThunk7(th *Thunk, f Thunk7, _0, _1, _2, _3, _4, _5, _6 unsafe.Pointer) *Thunk {" , " th.arity = 7" , " th.f7 = f" , " th._0 = _0" , " th._1 = _1" , " th._2 = _2" , " th._3 = _3" , " th._4 = _4" , " th._5 = _5" , " th._6 = _6" , " return th" , "}" , "" , "func Trampoline(th *Thunk) unsafe.Pointer {" , " var result unsafe.Pointer" , " for th.arity >= 0 {" , " result = th.Run()" , " }" , " return result" , "}" , "" , "func initNullCons() {" , " for i := 0; i < 256; i++ {" , " nullCons[i] = Con0{i}" , " }" , "}" , "" , "var bigZero *big.Int = big.NewInt(0)" , "var bigOne *big.Int = big.NewInt(1)" , "var intMinusOne unsafe.Pointer = MkInt(-1)" , "var intZero unsafe.Pointer = MkInt(0)" , "var intOne unsafe.Pointer = MkInt(1)" , "" -- This solely exists so the strconv import is used even if the program -- doesn't use the LIntStr primitive. , "func __useStrconvImport() string {" , " return strconv.Itoa(-42)" , "}" , "" ] mangleName :: Name -> T.Text mangleName name = T.concat $ map mangleChar (showCG name) where mangleChar x | isAlphaNum x = T.singleton x | otherwise = sformat ("_" % int % "_") (ord x) nameToGo :: Name -> T.Text nameToGo (MN i n) | T.all (\x -> isAlphaNum x || x == '_') n = n `T.append` T.pack (show i) nameToGo n = mangleName n lVarToGo :: LVar -> T.Text lVarToGo (Loc i) = sformat ("_" % int) i lVarToGo (Glob n) = nameToGo n lVarToVar :: LVar -> Var lVarToVar (Loc i) = V i lVarToVar v = error $ "LVar not convertible to var: " ++ show v varToGo :: Var -> T.Text varToGo RVal = "__rval" varToGo (V i) = sformat ("_" % int) i assign :: Var -> T.Text -> T.Text assign RVal x = "__thunk.arity = -1; " `T.append` varToGo RVal `T.append` " = " `T.append` x assign var x = varToGo var `T.append` " = " `T.append` x exprToGo :: Name -> Var -> SExp -> CG [Line] exprToGo f var SNothing = return . return $ Line (Just var) [] (assign var "nil") exprToGo _ var (SConst i@BI{}) | i == BI 0 = return [ Line (Just var) [] (assign var "unsafe.Pointer(bigZero)") ] | i == BI 1 = return [ Line (Just var) [] (assign var "unsafe.Pointer(bigOne)") ] | otherwise = return [ Line (Just var) [] (assign var (sformat ("unsafe.Pointer(" % stext % ")") (constToGo i))) ] exprToGo f var (SConst c@Ch{}) = return . return $ mkVal var c (sformat ("MkRune(" % stext % ")")) exprToGo _ var (SConst i@I{}) | i == I (-1) = return . return $ Line (Just var) [] (assign var "intMinusOne") | i == I 0 = return . return $ Line (Just var) [] (assign var "intZero") | i == I 1 = return . return $ Line (Just var) [] (assign var "intOne") | otherwise = return . return $ mkVal var i (sformat ("MkInt(" % stext % ")")) exprToGo f var (SConst s@Str{}) = return . return $ mkVal var s (sformat ("MkString(" % stext % ")")) exprToGo _ (V i) (SV (Loc j)) | i == j = return [] exprToGo _ var (SV (Loc i)) = return [ Line (Just var) [V i] (assign var (lVarToGo (Loc i))) ] exprToGo f var (SLet (Loc i) e sc) = do a <- exprToGo f (V i) e b <- exprToGo f var sc return $ a ++ b exprToGo f var (SApp True name vs) -- self call, simply goto to the entry again | f == name = return $ [ Line (Just (V i)) [ V a ] (sformat ("_" % int % " = _" % int) i a) | (i, Loc a) <- zip [0..] vs, i /= a ] ++ [ Line Nothing [ ] "goto entry" ] exprToGo f RVal (SApp True name vs) = do trampolined <- fmap ($ name) (gets requiresTrampoline) let args = T.intercalate ", " ("__thunk" : map lVarToGo vs) code = if trampolined then mkThunk name vs else assign RVal (nameToGo name `T.append` "(" `T.append` args `T.append` ")") return [ Line (Just RVal) [ V i | (Loc i) <- vs ] code ] exprToGo _ var (SApp True _ _) = error $ "Tail-recursive call, but should be assigned to " ++ show var exprToGo _ var (SApp False name vs) = do -- Not a tail call, but we might call a function that needs to be trampolined trampolined <- fmap ($ name) (gets requiresTrampoline) let code = if trampolined then assign var (sformat ("Trampoline(" % stext % ")") (mkThunk name vs)) else assign var (sformat (stext % "(" % stext % ")") (nameToGo name) args) return [ Line (Just var) [ V i | (Loc i) <- vs ] code ] where args = T.intercalate ", " ("__thunk" : map lVarToGo vs) exprToGo f var (SCase up (Loc l) alts) | isBigIntConst alts = constBigIntCase f var (V l) (dedupDefaults alts) | isConst alts = constCase f var (V l) alts | otherwise = conCase f var (V l) alts where isBigIntConst (SConstCase (BI _) _ : _) = True isBigIntConst _ = False isConst [] = False isConst (SConstCase _ _ : _) = True isConst (SConCase{} : _) = False isConst (_ : _) = False dedupDefaults (d@SDefaultCase{} : [SDefaultCase{}]) = [d] dedupDefaults (x : xs) = x : dedupDefaults xs dedupDefaults [] = [] exprToGo f var (SChkCase (Loc l) alts) = conCase f var (V l) alts exprToGo f var (SCon _ tag name args) = return . return $ Line (Just var) [ V i | (Loc i) <- args] (comment `T.append` assign var mkCon) where comment = "// " `T.append` (T.pack . show) name `T.append` "\n" mkCon | tag < 256 && null args = sformat ("unsafe.Pointer(&nullCons[" % int % "])") tag | otherwise = let argsCode = case args of [] -> T.empty _ -> ", " `T.append` T.intercalate ", " (map lVarToGo args) in sformat ("MkCon" % int % "(" % int % stext % ")") (length args) tag argsCode exprToGo f var (SOp prim args) = return . return $ primToGo var prim args exprToGo f var (SForeign ty (FApp callType callTypeArgs) args) = let call = toCall callType callTypeArgs in return . return $ Line Nothing [] (retVal (fDescToGoType ty) call) where convertedArgs = [ toArg (fDescToGoType t) (lVarToGo l) | (t, l) <- args] toCall ct [ FStr fname ] | ct == sUN "Function" = T.pack fname `T.append` "(" `T.append` T.intercalate ", " convertedArgs `T.append` ")" toCall ct [ FStr _, _, FStr methodName ] | ct == sUN "Method" = let obj : args = convertedArgs in sformat (stext % "." % string % "(" % stext % ")") obj methodName (T.intercalate ", " args) toCall ct a = error $ show ct ++ " " ++ show a toArg (GoInterface name) x = sformat ("(*(*" % string % ")(" % stext % "))") name x toArg GoByte x = "byte(*(*rune)(" `T.append` x `T.append` "))" toArg GoString x = "*(*string)(" `T.append` x `T.append` ")" toArg GoAny x = x toArg f _ = error $ "Not implemented yet: toArg " ++ show f ptrFromRef x = "unsafe.Pointer(&" `T.append` x `T.append` ")" toPtr (GoInterface _) x = ptrFromRef x toPtr GoInt x = ptrFromRef x toPtr GoString x = ptrFromRef x toPtr (GoNilable valueType) x = sformat ("MkMaybe(" % stext % ", " % stext % " != nil)" ) (toPtr valueType x) x retRef ty x = sformat ("{ __tmp := " % stext % "\n " % stext % " = " % stext % " }") x (varToGo var) (toPtr ty "__tmp") retVal GoUnit x = x retVal GoString x = retRef GoString x retVal (i@GoInterface{}) x = retRef i x retVal (n@GoNilable{}) x = retRef n x retVal (GoMultiVal varTypes) x = -- XXX assumes exactly two vars sformat ("{ " % stext % " := " % stext % "\n " % stext % " = MkCon" % int % "(0, " % stext % ") }") (T.intercalate ", " [ sformat ("__tmp" % int) i | i <- [1..length varTypes]]) x (varToGo var) (length varTypes) (T.intercalate ", " [ toPtr varTy (sformat ("__tmp" % int) i) | (i, varTy) <- zip [1 :: Int ..] varTypes ]) retVal (GoPtr _) x = sformat (stext % " = unsafe.Pointer(" % stext % ")") (varToGo var) x retVal t _ = error $ "Not implemented yet: retVal " ++ show t exprToGo _ _ expr = error $ "Not implemented yet: " ++ show expr data GoType = GoByte | GoInt | GoString | GoNilable GoType | GoInterface String | GoUnit | GoMultiVal [GoType] | GoPtr GoType | GoAny deriving (Show) fDescToGoType :: FDesc -> GoType fDescToGoType (FCon c) | c == sUN "Go_Byte" = GoByte | c == sUN "Go_Int" = GoInt | c == sUN "Go_Str" = GoString | c == sUN "Go_Unit" = GoUnit fDescToGoType (FApp c [ FStr name ]) | c == sUN "Go_Interface" = GoInterface name fDescToGoType (FApp c [ _ ]) | c == sUN "Go_Any" = GoAny fDescToGoType (FApp c [ _, ty ]) | c == sUN "Go_Nilable" = GoNilable (fDescToGoType ty) fDescToGoType (FApp c [ _, _, FApp c2 [ _, _, a, b ] ]) | c == sUN "Go_MultiVal" && c2 == sUN "MkPair" = GoMultiVal [ fDescToGoType a, fDescToGoType b ] fDescToGoType (FApp c [ _, ty ]) | c == sUN "Go_Ptr" = GoPtr (fDescToGoType ty) fDescToGoType f = error $ "Not implemented yet: fDescToGoType " ++ show f toFunType :: FDesc -> FType toFunType (FApp c [ _, _ ]) | c == sUN "Go_FnBase" = FFunction | c == sUN "Go_FnIO" = FFunctionIO toFunType desc = error $ "Not implemented yet: toFunType " ++ show desc mkThunk :: Name -> [LVar] -> T.Text mkThunk f [] = sformat ("MkThunk0(__thunk, " % stext % ")") (nameToGo f) mkThunk f args = sformat ("MkThunk" % int % "(__thunk, " % stext % ", " % stext % ")") (length args) (nameToGo f) (T.intercalate "," (map lVarToGo args)) mkVal :: Var -> Const -> (T.Text -> T.Text) -> Line mkVal var c factory = Line (Just var) [] (assign var (factory (constToGo c))) constToGo :: Const -> T.Text constToGo (BI i) | i == 0 = "bigZero" | i == 1 = "bigOne" | i < toInteger (maxBound :: Int64) && i > toInteger (minBound :: Int64) = "big.NewInt(" `T.append` T.pack (show i) `T.append` ")" | otherwise = "BigIntFromString(\"" `T.append` T.pack (show i) `T.append` "\")" constToGo (Ch '\DEL') = "'\\x7F'" constToGo (Ch '\SO') = "'\\x0e'" constToGo (Str s) = T.pack (show s) constToGo constVal = T.pack (show constVal) -- Special case for big.Ints, as we need to compare with Cmp there constBigIntCase :: Name -> Var -> Var -> [SAlt] -> CG [Line] constBigIntCase f var v alts = do cases <- traverse case_ alts return $ [ Line Nothing [] "switch {" ] ++ concat cases ++ [ Line Nothing [] "}" ] where valueCmp other = sformat ("(*big.Int)(" % stext % ").Cmp(" % stext % ") == 0") (varToGo v) (constToGo other) case_ (SConstCase constVal expr) = do code <- exprToGo f var expr return $ Line Nothing [v] (sformat ("case " % stext % ":") (valueCmp constVal)) : code case_ (SDefaultCase expr) = do code <- exprToGo f var expr return $ Line Nothing [] "default:" : code case_ c = error $ "Unexpected big int case: " ++ show c constCase :: Name -> Var -> Var -> [SAlt] -> CG [Line] constCase f var v alts = do cases <- traverse case_ alts return $ [ Line Nothing [v] (T.concat [ "switch " , castValue alts , " {" ]) ] ++ concat cases ++ [ Line Nothing [] "}" ] where castValue (SConstCase (Ch _) _ : _) = "*(*rune)(" `T.append` varToGo v `T.append` ")" castValue (SConstCase (I _) _ : _) = "*(*int64)(" `T.append` varToGo v `T.append` ")" castValue (SConstCase constVal _ : _) = error $ "Not implemented: cast for " ++ show constVal castValue _ = error "First alt not a SConstCase!" case_ (SDefaultCase expr) = do code <- exprToGo f var expr return $ Line Nothing [] "default:" : code case_ (SConstCase constVal expr) = do code <- exprToGo f var expr return $ Line Nothing [] (T.concat [ "case " , constToGo constVal , ":" ]) : code case_ c = error $ "Unexpected const case: " ++ show c conCase :: Name -> Var -> Var -> [SAlt] -> CG [Line] conCase f var v [ SDefaultCase expr ] = exprToGo f var expr conCase f var v alts = do cases <- traverse case_ alts return $ [ Line Nothing [v] (T.concat [ "switch GetTag(" , varToGo v , ") {" ]) ] ++ concat cases ++ [ Line Nothing [] "}" ] where project left i = Line (Just left) [v] (assign left (sformat ("(*Con" % int % ")(" % stext % ")._" % int) (i+1) (varToGo v) i)) case_ (SConCase base tag name args expr) = do let locals = [base .. base + length args - 1] projections = [ project (V i) (i - base) | i <- locals ] code <- exprToGo f var expr return $ [ Line Nothing [] (sformat ("case " % int % ":\n // Projection of " % stext) tag (nameToGo name)) ] ++ projections ++ code case_ (SDefaultCase expr) = do code <- exprToGo f var expr return $ Line Nothing [] "default:" : code case_ c = error $ "Unexpected con case: " ++ show c primToGo :: Var -> PrimFn -> [LVar] -> Line primToGo var (LChInt ITNative) [ch] = let code = "MkInt(int64(*(*rune)(" `T.append` lVarToGo ch `T.append` ")))" in Line (Just var) [ lVarToVar ch ] (assign var code) primToGo var (LEq (ATInt ITChar)) [left, right] = let code = T.concat [ "MkIntFromBool(*(*rune)(" , lVarToGo left , ") == *(*rune)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LEq (ATInt ITNative)) [left, right] = let code = T.concat [ "MkIntFromBool(*(*int64)(" , lVarToGo left , ") == *(*int64)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LEq (ATInt ITBig)) [left, right] = let code = T.concat [ "MkIntFromBool((*big.Int)(" , lVarToGo left , ").Cmp((*big.Int)(" , lVarToGo right , ")) == 0)" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LSLt (ATInt ITChar)) [left, right] = let code = T.concat [ "MkIntFromBool(*(*rune)(" , lVarToGo left , ") < *(*rune)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LSLt (ATInt ITNative)) [left, right] = let code = T.concat [ varToGo var , " = MkIntFromBool(*(*int64)(" , lVarToGo left , ") < *(*int64)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] code primToGo var (LSLt (ATInt ITBig)) [left, right] = let code = T.concat [ "MkIntFromBool((*big.Int)(" , lVarToGo left , ").Cmp((*big.Int)(" , lVarToGo right , ")) < 0)" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var (LMinus (ATInt ITNative)) [left, right] = nativeIntBinOp var left right "-" primToGo var (LMinus (ATInt ITBig)) [left, right] = bigIntBigOp var left right "Sub" primToGo var (LPlus (ATInt ITNative)) [left, right] = nativeIntBinOp var left right "+" primToGo var (LPlus (ATInt ITBig)) [left, right] = bigIntBigOp var left right "Add" primToGo var (LSExt ITNative ITBig) [i] = let code = "unsafe.Pointer(big.NewInt(*(*int64)(" `T.append` lVarToGo i `T.append` ")))" in Line (Just var) [ lVarToVar i ] (assign var code) primToGo var (LIntStr ITBig) [i] = let code = "MkString((*big.Int)(" `T.append` lVarToGo i `T.append` ").String())" in Line (Just var) [ lVarToVar i ] (assign var code) primToGo var (LIntStr ITNative) [i] = let code = "MkString(strconv.FormatInt(*(*int64)(" `T.append` lVarToGo i `T.append` "), 10))" in Line (Just var) [ lVarToVar i ] (assign var code) primToGo var LStrEq [left, right] = let code = T.concat [ "MkIntFromBool(*(*string)(" , lVarToGo left , ") == *(*string)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var LStrCons [c, s] = let code = T.concat [ "MkString(string(*(*rune)(" , lVarToGo c , ")) + *(*string)(" , lVarToGo s , "))" ] in Line (Just var) [ lVarToVar c, lVarToVar s ] (assign var code) primToGo var LStrHead [s] = let code = "MkRune(RuneAtIndex(*(*string)(" `T.append` lVarToGo s `T.append` "), 0))" in Line (Just var) [ lVarToVar s ] (assign var code) primToGo var LStrTail [s] = let code = "MkString(StrTail(*(*string)(" `T.append` lVarToGo s `T.append` ")))" in Line (Just var) [ lVarToVar s ] (assign var code) primToGo var LStrConcat [left, right] = let code = T.concat [ "MkString(*(*string)(" , lVarToGo left , ") + *(*string)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) primToGo var LWriteStr [world, s] = let code = "WriteStr(" `T.append` lVarToGo s `T.append` ")" in Line (Just var) [ lVarToVar world, lVarToVar s ] (assign var code) primToGo var (LTimes (ATInt ITNative)) [left, right] = nativeIntBinOp var left right "*" primToGo var (LTimes (ATInt ITBig)) [left, right] = bigIntBigOp var left right "Mul" primToGo _ fn _ = Line Nothing [] (sformat ("panic(\"Unimplemented PrimFn: " % string % "\")") (show fn)) bigIntBigOp :: Var -> LVar -> LVar -> T.Text -> Line bigIntBigOp var left right op = let code = T.concat [ "unsafe.Pointer(new(big.Int)." , op , "((*big.Int)(" , lVarToGo left , "), (*big.Int)(" , lVarToGo right , ")))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) nativeIntBinOp :: Var -> LVar -> LVar -> T.Text -> Line nativeIntBinOp var left right op = let code = T.concat [ "MkInt(*(*int64)(" , lVarToGo left , ") " , op , " *(*int64)(" , lVarToGo right , "))" ] in Line (Just var) [ lVarToVar left, lVarToVar right ] (assign var code) data TailCall = Self | Other deriving (Eq, Show) containsTailCall :: Name -> SExp -> [TailCall] containsTailCall self (SApp True n _) = if self == n then [ Self ] else [ Other ] containsTailCall self (SLet _ a b) = containsTailCall self a ++ containsTailCall self b containsTailCall self (SUpdate _ e) = containsTailCall self e containsTailCall self (SCase _ _ alts) = concatMap (altContainsTailCall self) alts containsTailCall self (SChkCase _ alts) = concatMap (altContainsTailCall self) alts containsTailCall _ _ = [] altContainsTailCall :: Name -> SAlt -> [TailCall] altContainsTailCall self (SConCase _ _ _ _ e) = containsTailCall self e altContainsTailCall self (SConstCase _ e) = containsTailCall self e altContainsTailCall self (SDefaultCase e) = containsTailCall self e extractUsedVars :: [Line] -> S.Set Var extractUsedVars lines = S.fromList (concat [used | Line _ used _ <- lines]) filterUnusedLines :: [Line] -> [Line] filterUnusedLines lines = let usedVars = extractUsedVars lines requiredLines = mapMaybe (required usedVars) lines in if length lines /= length requiredLines -- the filtered lines might have made some other lines obsolete, filter again then filterUnusedLines requiredLines else lines where required _ l@(Line Nothing _ _) = Just l required _ l@(Line (Just RVal) _ _) = Just l required usedVars l@(Line (Just v) _ _) = if S.member v usedVars then Just l else Nothing funToGo :: (Name, SDecl, [TailCall]) -> CG T.Text funToGo (name, SFun _ args locs expr, tailCalls) = do bodyLines <- filterUnusedLines <$> exprToGo name RVal expr let usedVars = extractUsedVars bodyLines pure . T.concat $ [ "// " , T.pack $ show name , "\nfunc " , nameToGo name , "(" , "__thunk *Thunk" `T.append` if (not . null) args then ", " else T.empty , T.intercalate ", " [ sformat ("_" % int % " unsafe.Pointer") i | i <- [0..length args-1]] , ") unsafe.Pointer {\n var __rval unsafe.Pointer\n" , reserve usedVars locs , tailCallEntry , T.unlines [ line | Line _ _ line <- bodyLines ] , "return __rval\n}\n\n" ] where tailCallEntry = if Self `elem` tailCalls then "entry:" else T.empty loc usedVars i = let i' = length args + i in if S.member (V i') usedVars then Just $ sformat ("_" % int) i' else Nothing reserve usedVars locs = case mapMaybe (loc usedVars) [0..locs] of [] -> T.empty usedLocs -> " var " `T.append` T.intercalate ", " usedLocs `T.append` " unsafe.Pointer\n" genMain :: T.Text genMain = T.unlines [ "var cpuprofile = flag.String(\"cpuprofile\", \"\", \"write cpu profile `file`\")" , "var memprofile = flag.String(\"memprofile\", \"\", \"write memory profile to `file`\")" , "" , "func main() {" , " flag.Parse()" , " initNullCons()" , " if *cpuprofile != \"\" {" , " f, err := os.Create(*cpuprofile)" , " if err != nil {" , " log.Fatal(\"Could not create CPU profile: \", err)" , " }" , " if err := pprof.StartCPUProfile(f); err != nil {" , " log.Fatal(\"Could not start CPU profile: \", err)" , " }" , " defer pprof.StopCPUProfile()" , " }" , " var thunk Thunk" , " runMain0(&thunk)" , " if *memprofile != \"\" {" , " f, err := os.Create(*memprofile)" , " if err != nil {" , " log.Fatal(\"Could not create memory profile: \", err)" , " }" , " runtime.GC()" , " if err := pprof.WriteHeapProfile(f); err != nil {" , " log.Fatal(\"Could not write memory profile: \", err)" , " }" , " f.Close()" , " }" , "}" ] codegenGo :: CodeGenerator codegenGo ci = do let funs = [ (name, fun, containsTailCall name expr) | (name, fun@(SFun _ _ _ expr)) <- simpleDecls ci ] needsTrampolineByName = M.fromList [ (name, Other `elem` tailCalls) | (name, _, tailCalls) <- funs ] trampolineLookup = fromMaybe False . (`M.lookup` needsTrampolineByName) funCodes = evalState (traverse funToGo funs) (createCgState trampolineLookup) code = T.concat [ goPreamble (map (T.pack . show) (includes ci)) , T.concat funCodes , genMain ] withFile (outputFile ci) WriteMode $ \hOut -> do (Just hIn, _, _, p) <- createProcess (proc "gofmt" [ "-s" ]){ std_in = CreatePipe, std_out = UseHandle hOut } TIO.hPutStr hIn code _ <- waitForProcess p return ()
Trundle/idris-go
src/IRTS/CodegenGo.hs
mit
32,179
0
19
9,664
9,873
5,186
4,687
786
25
-- The solution of exercise 1.23 -- The `smallest-divisor` procedure shown at the start of this section does -- lots of needless testing: After it checks to see if the number is -- divisible by 2 there is no point in checking to see if it is divisible -- by any larger even numbers. This suggests that the values used for -- `test-divisor` should not be 2, 3, 4, 5, 6, ..., but rather 2, 3, 5, 7, -- 9,... . To implement this change, define a procedure `next` that returns -- 3 if its input is equal to 2 and otherwise returns its input plus 2. -- Modify the `smallest-divisor` procedure to use (next test-divisor) -- instead of (+ test-divisor 1). With `timed-prime-test` incorporating -- this modified version of `smallest-divisor`, run the test for each of -- the 12 primes found in exercise 1.22. Since this modification halves the -- number of test steps, you should expect it to run about twice as fast. -- Is this expectation confirmed? If not, what is the observed ratio of the -- speeds of the two algorithms, and how do you explain the fact that it is -- different from 2? -- -- -------- (above from SICP) -- import Data.Time -- Run 'cabal install vector' first! import qualified Data.Vector as V -- Find the smallest divisor of an integer smallestDivisor :: (Integral a) => a -> a smallestDivisor n = if n < 0 then smallestDivisor (-n) else let next n | n == 2 = 3 | n > 2 = n + 2 findDivisor m td | td * td > m = m | mod m td == 0 = td | otherwise = findDivisor m (next td) in findDivisor n 2 -- Test a number is a prime or not isPrime n | n < 0 = isPrime (-n) | n == 0 = False | n == 1 = False | otherwise = smallestDivisor n == n -- Find the smallest prime that is larger than n nextPrime :: (Integral a) => a -> a nextPrime n = let findPrime counter = if isPrime counter then counter else findPrime (counter + 1) in findPrime (n + 1) -- Find the smallest m primes that are larger than n nextPrimes :: (Integral a, Show a) => a -> a -> IO () nextPrimes n m = let searchPrimeCount init counter maxCount = if counter < maxCount then do let newPrime = nextPrime init putStrLn ("prime[" ++ show counter ++ "] " ++ show newPrime) searchPrimeCount newPrime (counter + 1) maxCount else return () in searchPrimeCount n 0 m -- Find the m th primes that are larger than n nextPrimesNum :: (Integral a) => a -> a -> a nextPrimesNum n m = let searchPrimeCount init counter maxCount = if counter < maxCount then let newPrime = nextPrime init in searchPrimeCount newPrime (counter + 1) maxCount else init in searchPrimeCount n 0 m -- -- Find the smallest m primes that are bigger than n and store all of them -- in a vector. Test an example: find the next 100 odd primes of 19999. -- -- *Main> nextPrimesVec 19999 100 -- [20011,20021,20023,20029,20047,20051,20063,20071,20089,20101,20107, -- 20113,20117,20123,20129,20143,20147,20149,20161,20173,20177,20183, -- 20201,20219,20231,20233,20249,20261,20269,20287,20297,20323,20327, -- 20333,20341,20347,20353,20357,20359,20369,20389,20393,20399,20407, -- 20411,20431,20441,20443,20477,20479,20483,20507,20509,20521,20533, -- 20543,20549,20551,20563,20593,20599,20611,20627,20639,20641,20663, -- 20681,20693,20707,20717,20719,20731,20743,20747,20749,20753,20759, -- 20771,20773,20789,20807,20809,20849,20857,20873,20879,20887,20897, -- 20899,20903,20921,20929,20939,20947,20959,20963,20981,20983,21001, -- 21011] -- nextPrimesVec :: (Integral a) => a -> a -> V.Vector a nextPrimesVec n m = let searchPrimeCount init counter maxCount vector = if counter < maxCount then let newPrime = nextPrime init in searchPrimeCount newPrime (counter + 1) maxCount (V.snoc vector newPrime) else vector v0 = V.fromList [] in searchPrimeCount n 0 m v0 -- Compute the runtime of `nextPrimesNum` computeRuntime n m = do start <- getCurrentTime print $ nextPrimesNum n m stop <- getCurrentTime print $ diffUTCTime stop start -- -- *Main> computeRuntime 100000000000 3 -- 100000000057 -- 0.978514s -- *Main> computeRuntime 1000000000000 3 -- 1000000000063 -- 2.987301s -- *Main> computeRuntime 10000000000000 3 -- 10000000000099 -- 11.742541s --
perryleo/sicp
ch1/sicpc1e23.hs
mit
4,498
0
17
1,090
776
402
374
61
2
{-# LANGUAGE NoImplicitPrelude #-} module Compiler.IO (unsafeInterleaveIO, unsafePerformIO) where import Compiler.Base -- for seq, IO = IOActionX, LazyIO, IOAndPass, MFIX, IOReturn import Data.Tuple -- for snd -- See Control.Monad.State -- drat -- my implementation of IO assumes that the state is FIRST, but should be SECOND. unsafeInterleaveIO x = LazyIO x unsafePerformIO (IOAction f) = snd (f 0) unsafePerformIO (LazyIO f) = unsafePerformIO f unsafePerformIO (IOAndPass (LazyIO f) g) = let x = unsafePerformIO f in unsafePerformIO (g x) unsafePerformIO (IOAndPass f g) = let x = unsafePerformIO f in x `seq` unsafePerformIO (g x) unsafePerformIO (MFix f) = let x = unsafePerformIO (f x) in x unsafePerformIO (IOReturn x) = x
bredelings/BAli-Phy
haskell/Compiler/IO.hs
gpl-2.0
761
0
11
144
218
110
108
12
1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE OverloadedStrings #-} module Main where import Data.Char (isSpace) import Control.DeepSeq import Criterion.Main import qualified Criterion.Main as C import Data.Text (unlines, Text, replicate) import Prelude hiding (unlines) import qualified Yi.Rope as F longText :: Text longText = force . Data.Text.unlines $ Prelude.replicate 1000 "Lorem Спасибопожалусто dolor 中文測試 amet" {-# NOINLINE longText #-} longTextTree :: F.YiString longTextTree = force . F.fromText . Data.Text.unlines $ Prelude.replicate 1000 "Lorem Спасибопожалусто dolor 中文測試 amet" {-# NOINLINE longTextTree #-} longFRope :: F.YiString longFRope = force (F.fromText longText) {-# NOINLINE longFRope #-} wideText :: Text wideText = force . unlines $ Prelude.replicate 10 $ Data.Text.replicate 100 "Lorem Спасибопожалусто dolor 中文測試 amet " {-# NOINLINE wideText #-} shortText :: Text shortText = force . unlines $ Prelude.replicate 3 "Lorem Спасибопожалусто dolor 中文測試 amet" {-# NOINLINE shortText #-} tinyText :: Text tinyText = force $ "Lorem Спасибопожалусто dolor 中文測試 amet" {-# NOINLINE tinyText #-} wideFRope :: F.YiString wideFRope = force (F.fromText wideText) {-# NOINLINE wideFRope #-} benchOnText :: NFData b => a -> String -> (a -> b) -> Benchmark benchOnText text name f = C.bench name $ C.nf f text benchSplitAt :: NFData a => a -> String -> (Int -> a -> (a, a)) -> C.Benchmark benchSplitAt text name f = C.bench name $ C.nf (\x -> Prelude.foldr ((fst .) . f) x [1000, 999 .. 1]) text benchTakeDrop :: NFData a => a -> String -> (Int -> a -> a) -> C.Benchmark benchTakeDrop text name f = C.bench name $ C.nf (\x -> foldr f x [1000, 999 .. 1]) text -- | Chunk sizes to test with. chunkSizes :: [Int] chunkSizes = [1200] wideTexts :: (Int -> String, [(Int, F.YiString)]) wideTexts = (\x -> "wide " ++ show x, mkTextSample wideText) longTexts :: (Int -> String, [(Int, F.YiString)]) longTexts = (\x -> "long " ++ show x, mkTextSample longText) shortTexts :: (Int -> [Char], [(Int, F.YiString)]) shortTexts = (\x -> "short " ++ show x, mkTextSample shortText) tinyTexts :: (Int -> String, [(Int, F.YiString)]) tinyTexts = (\x -> "tiny " ++ show x, mkTextSample tinyText) mkTextSample :: Text -> [(Int, F.YiString)] mkTextSample s = force $ zipWith mkTexts chunkSizes (Prelude.repeat s) where mkTexts :: Int -> Text -> (Int, F.YiString) mkTexts x t = (x, F.fromText' x t) allTexts :: [(Int -> String, [(Int, F.YiString)])] allTexts = [longTexts {-, wideTexts, shortTexts, tinyTexts -}] allChars :: [(Int -> String, [(Int, Char)])] allChars = map mkChar "λa" where mkChar c = (\x -> unwords [ "char", [c], show x ], [(1, c)]) -- | Sample usage: -- -- > mkGroup "drop" F.drop allTexts benchOnText mkGroup :: String -- ^ Group name -> f -- ^ Function being benchmarked -> [(chsize -> String, [(chsize, input)])] -> (input -> String -> f -> Benchmark) -> Benchmark mkGroup n f subs r = bgroup n tests where mkTest s (l, t) = r t (s l) f tests = Prelude.concat $ map (\(s, t) -> map (mkTest s) t) subs onTextGroup :: NFData a => String -> (F.YiString -> a) -> Benchmark onTextGroup n f = mkGroup n f allTexts benchOnText onCharGroup :: NFData a => String -> (Char -> a) -> Benchmark onCharGroup n f = mkGroup n f allChars benchOnText onIntGroup :: String -> (Int -> F.YiString -> F.YiString) -> Benchmark onIntGroup n f = mkGroup n f allTexts benchTakeDrop onSplitGroup :: String -> (Int -> F.YiString -> (F.YiString, F.YiString)) -> Benchmark onSplitGroup n f = mkGroup n f allTexts benchSplitAt splitBench :: [Benchmark] splitBench = [ onTextGroup "split none" (F.split (== '×')) , onTextGroup "split lots" (F.split (\x -> x == 'a' || x == 'o')) , onTextGroup "split all" (F.split (const True)) ] wordsBench :: [Benchmark] wordsBench = -- The replicate here inflates the benchmark like mad, should be -- moved out. [ onTextGroup "unwords" (\x -> F.unwords (Prelude.replicate 100 x)) , onTextGroup "words" F.words ] spanBreakBench :: [Benchmark] spanBreakBench = [ onTextGroup "spanTrue" $ F.span (const True) , onTextGroup "spanFalse" $ F.span (const False) , onTextGroup "spanSpace" $ F.span isSpace , onTextGroup "breakTrue" $ F.break (const True) , onTextGroup "breakFalse" $ F.break (const False) , onTextGroup "breakSpace" $ F.break isSpace ] foldBench :: [Benchmark] foldBench = [ onTextGroup "foldCount" $ F.foldl' (\x _ -> x + 1) (0 :: Integer) , onTextGroup "foldId" $ F.foldl' F.snoc F.empty , onTextGroup "foldReverse" $ F.foldl' (\x y -> F.cons y x) F.empty ] main :: IO () main = defaultMain $ [ onIntGroup "drop" F.drop , onIntGroup "take" F.take , onTextGroup "cons" (F.cons 'λ') , onTextGroup "snoc" (`F.snoc` 'λ') , onCharGroup "singleton" F.singleton , onTextGroup "countNewLines" F.countNewLines , onTextGroup "lines" F.lines , onSplitGroup "splitAt" F.splitAt , onSplitGroup "splitAtLine" F.splitAtLine , onTextGroup "toReverseString" F.toReverseString , onTextGroup "toReverseText" F.toReverseText , onTextGroup "toText" F.toText , onTextGroup "length" F.length , onTextGroup "reverse" F.reverse , onTextGroup "null" F.null , onTextGroup "empty" $ const F.empty , onTextGroup "append" (\x -> F.append x x) , onTextGroup "concat x100" $ F.concat . Prelude.replicate 100 , onTextGroup "any OK, (== '中')" $ F.any (== '中') , onTextGroup "any bad, (== '×')" $ F.any (== '×') , onTextGroup "all OK (/= '×')" $ F.all (== '×') , onTextGroup "all bad, (== '中')" $ F.all (== '中') , onTextGroup "init" F.init , onTextGroup "tail" F.tail , onTextGroup "replicate 50" (F.replicate 50) ] ++ splitBench ++ wordsBench ++ spanBreakBench ++ foldBench
siddhanathan/yi-rope
bench/MainBenchmarkSuite.hs
gpl-2.0
6,077
0
15
1,254
2,057
1,110
947
140
1
-- Parse module -- By Gregory W. Schwartz -- Collects all functions pertaining to the parsing of strings to data -- structures {-# LANGUAGE OverloadedStrings #-} module Parse where -- | Built-in import Data.List import Data.Maybe -- | Cabal import qualified Data.Text.Lazy as T -- | Local import Types -- | Parse a string to a list of fasta sequences parseCSV :: Bool -> Bool -> Bool -> [T.Text] -> [Int] -> T.Text -> Int -> T.Text -> Int -> T.Text -> Int -> T.Text -> T.Text -> [FastaSequence] parseCSV noHeader includeGermline includeClone headers headerCols seqs seqCol germ germCol clone cloneCol sep contents = map lineToSeq . zip ([1..] :: [Int]) . map (T.splitOn sep) . filterShortLines . body noHeader $ contents where lineToSeq = convertToFastaSeq headerList convertToFastaSeq [-1] (x, xs) = FastaSequence { fastaInfo = showText x , fastaSeq = xs !! mainSeq , germline = getGerm includeGermline xs , cloneID = getClone includeClone xs } convertToFastaSeq _ (_, xs) = FastaSequence { fastaInfo = T.intercalate "|" . map (getHeader xs) $ headerList , fastaSeq = xs !! mainSeq , germline = getGerm includeGermline xs , cloneID = getClone includeClone xs } getHeader xs x = xs !! x filterShortLines = filter ( \x -> length (T.splitOn sep x) >= maxField ) maxField = maximum (headerList ++ [mainSeq, mainGerm, mainClone]) body True = T.lines body False = tail . T.lines header = T.splitOn sep . head . T.lines $ contents getGerm True xs = Just (xs !! mainGerm) getGerm False _ = Nothing getClone True xs = Just (xs !! mainClone) getClone False _ = Nothing headerList | null headers = map (flip (-) 1) headerCols | otherwise = mapMaybe (`elemIndex` header) headers mainSeq | T.null seqs = seqCol - 1 | otherwise = fromMaybe (error "Sequence column not found") . elemIndex seqs $ header mainGerm | T.null germ = germCol - 1 | otherwise = fromMaybe (error "Germline column not found") . elemIndex germ $ header mainClone | T.null clone = cloneCol - 1 | otherwise = fromMaybe (error "Clone column not found") . elemIndex clone $ header -- | Counts the number of times a substring appears in a string count :: (Eq a) => a -> [a] -> Int count x = foldl' (\acc y -> if y == x then acc + 1 else acc) 0
GregorySchwartz/csv-to-fasta
src/Parse.hs
gpl-2.0
4,119
0
18
2,312
789
412
377
90
5
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-} module Lamdu.GUI.ExpressionEdit.NomEdit ( makeFromNom, makeToNom ) where import Prelude.Compat import Control.Lens.Operators import Control.Lens.Tuple import Control.MonadA (MonadA) import Data.Store.Transaction (Transaction) import Data.Vector.Vector2 (Vector2(..)) import qualified Graphics.UI.Bottle.EventMap as E import qualified Graphics.UI.Bottle.Widget as Widget import qualified Lamdu.Config as Config import Lamdu.GUI.ExpressionGui (ExpressionGui) import qualified Lamdu.GUI.ExpressionGui as ExpressionGui import Lamdu.GUI.ExpressionGui.Monad (ExprGuiM) import qualified Lamdu.GUI.ExpressionGui.Monad as ExprGuiM import qualified Lamdu.GUI.ExpressionGui.Types as ExprGuiT import Lamdu.Sugar.Names.Types (Name(..)) import qualified Lamdu.Sugar.Types as Sugar import qualified Lamdu.GUI.WidgetIds as WidgetIds makeToNom :: MonadA m => Sugar.Nominal (Name m) m (ExprGuiT.SugarExpr m) -> Sugar.Payload m ExprGuiT.Payload -> ExprGuiM m (ExpressionGui m) makeToNom nom@(Sugar.Nominal _ val _) pl = ExpressionGui.stdWrapParentExpr pl $ \myId -> do valEdit <- ExprGuiM.makeSubexpression 0 val <&> ExpressionGui.egAlignment . _1 .~ 0.5 let valWidth = valEdit ^. ExpressionGui.egWidget . Widget.width nameEdit <- nameGui "Wrapper" nom nameId <&> ExpressionGui.egWidget %~ Widget.padToSizeAlign (Vector2 valWidth 0) 0.5 >>= ExpressionGui.addValFrame nameId ExpressionGui.vboxTopFocalSpaced [valEdit, nameEdit] & ExprGuiM.assignCursor myId nameId where nameId = Widget.joinId (WidgetIds.fromEntityId (pl ^. Sugar.plEntityId)) ["name"] makeFromNom :: MonadA m => Sugar.Nominal (Name m) m (ExprGuiT.SugarExpr m) -> Sugar.Payload m ExprGuiT.Payload -> ExprGuiM m (ExpressionGui m) makeFromNom nom@(Sugar.Nominal _ val _) pl = ExpressionGui.stdWrapParentExpr pl $ \myId -> do nameEdit <- nameGui "Unwrapper" nom nameId valEdit <- ExprGuiM.makeSubexpression 11 val symLabel <- ExpressionGui.grammarLabel "⇈" (Widget.toAnimId myId) ExpressionGui.hboxSpaced [nameEdit, symLabel, valEdit] & ExprGuiM.assignCursor myId nameId where nameId = Widget.joinId (WidgetIds.fromEntityId (pl ^. Sugar.plEntityId)) ["name"] nameGui :: MonadA m => String -> Sugar.Nominal (Name m) m a -> Widget.Id -> ExprGuiM m (ExpressionGui m) nameGui docName (Sugar.Nominal tidg _val mDel) nameId = do delEventMap <- mkDelEventMap docName mDel ExpressionGui.makeNameEdit (tidg ^. Sugar.tidgName) nameId <&> Widget.weakerEvents delEventMap <&> ExpressionGui.fromValueWidget mkDelEventMap :: MonadA m => String -> Maybe (Transaction m Sugar.EntityId) -> ExprGuiM m (Widget.EventHandlers (Transaction m)) mkDelEventMap docName mDel = do config <- ExprGuiM.readConfig mDel <&> fmap WidgetIds.fromEntityId & maybe mempty (Widget.keysEventMapMovesCursor (Config.delKeys config) doc) & return where doc = E.Doc ["Edit", "Delete", docName]
rvion/lamdu
Lamdu/GUI/ExpressionEdit/NomEdit.hs
gpl-3.0
3,316
0
15
780
913
484
429
-1
-1
module Mapgen.CampusArgs where -- todo: It's gonna be fun splitting stuff up once I actually decide to add another mapgen... data CampusArgs = CampusArgs { numOutsidePaths :: Int, numCrossingCorridors :: Int, numCorridors :: Int, randomConnectionChance :: Double, randomOutsideConnectionChance :: Double }
arirahikkala/straylight-divergence
src/Mapgen/CampusArgs.hs
gpl-3.0
338
0
8
73
46
30
16
7
0
module Chapter15_monoids where import Test.QuickCheck hiding (Failure, Success) import Data.Monoid import qualified Data.Semigroup as S import Data.Semigroup (Semigroup) data Optional a = Nada | Only a deriving (Eq, Show) instance Monoid a => Monoid (Optional a) where mempty = Nada mappend Nada o@(Only a) = o mappend o@(Only a) Nada = o mappend Nada Nada = Nada mappend (Only a) (Only b) = Only $ mappend a b newtype First' a = First' { getFirst' :: Optional a } deriving (Eq, Show) firstGen :: Arbitrary a => Gen (First' a) firstGen = do a <- arbitrary elements [First' (Only a), First' Nada] instance Arbitrary a => Arbitrary (First' a) where arbitrary = firstGen instance Monoid (First' a) where mempty = First' Nada mappend o@(First' (Only a)) _ = o mappend (First' Nada) o@(First' (Only a)) = o mappend (First' Nada) n@(First' Nada) = n firstMappend :: First' a -> First' a -> First' a firstMappend = mappend type FirstMappend = First' String -> First' String -> First' String -> Bool type FstId = First' String -> Bool -- monoid laws monoidAssoc :: (Eq m, Monoid m) => m -> m -> m -> Bool monoidAssoc a b c = (a <> (b <> c)) == ((a <> b) <> c) monoidLeftIdentity :: (Eq m, Monoid m) => m -> Bool monoidLeftIdentity a = (mempty <> a) == a monoidRightIdentity :: (Eq m, Monoid m) => m -> Bool monoidRightIdentity a = (a <> mempty) == a -- semigroups semigroupAssoc :: (Eq m, Semigroup m) => m -> m -> m -> Bool semigroupAssoc a b c = (a S.<> (b S.<> c)) == ((a S.<> b) S.<> c) -- 1 data Trivial = Trivial deriving (Eq, Show) instance Semigroup Trivial where _ <> _ = Trivial instance Arbitrary Trivial where arbitrary = return Trivial type TrivialAssoc = Trivial -> Trivial -> Trivial -> Bool -- 2 newtype Identity a = Identity a deriving (Eq, Show) instance Semigroup a => Semigroup (Identity a) where (Identity a) <> (Identity b) = Identity $ a S.<> b instance Arbitrary a => Arbitrary (Identity a) where arbitrary = do a <- arbitrary return (Identity a) -- instance Arbitrary a => Arbitrary (Sum a) where -- arbitrary = do -- i <- arbitrary -- return (Sum i) type IdentityAssoc = Identity (Sum Int) -> Identity (Sum Int) -> Identity (Sum Int) -> Bool -- 3 data Two a b = Two a b deriving (Eq, Show) instance (Semigroup a, Semigroup b) => Semigroup (Two a b) where (Two a b) <> (Two c d) = Two (a S.<> c) (b S.<> d ) instance (Arbitrary a, Arbitrary b) => Arbitrary (Two a b) where arbitrary = do a <- arbitrary b <- arbitrary return (Two a b) type TwoAssoc = Two String String -> Two String String -> Two String String -> Bool -- 4 data Three a b c = Three a b c deriving (Eq, Show) instance (Semigroup a, Semigroup b, Semigroup c) => Semigroup (Three a b c) where (Three a b c) <> (Three d e f) = Three (a S.<> d) (b S.<> e) (c S.<> f) instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (Three a b c) where arbitrary = do a <- arbitrary b <- arbitrary c <- arbitrary return (Three a b c) type ThreeAssoc = Three String String String -> Three String String String -> Three String String String -> Bool -- 5 data Four a b c d = Four a b c d deriving (Eq, Show) instance (Semigroup a, Semigroup b, Semigroup c, Semigroup d) => Semigroup (Four a b c d) where (Four a1 b1 c1 d1) <> (Four a2 b2 c2 d2) = Four (a1 S.<> a2) (b1 S.<> b2) (c1 S.<> c2) (d1 S.<> d2) instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Arbitrary (Four a b c d) where arbitrary = do a <- arbitrary b <- arbitrary c <- arbitrary d <- arbitrary return (Four a b c d) type FourAssoc = Four String String String String -> Four String String String String -> Four String String String String -> Bool -- 6 newtype BoolConj = BoolConj Bool deriving (Eq, Show) instance Semigroup BoolConj where (BoolConj a) <> (BoolConj b) = BoolConj (a && b) instance Arbitrary BoolConj where arbitrary = elements [BoolConj True, BoolConj False] type BoolConjAssoc = BoolConj -> BoolConj -> BoolConj -> Bool -- 7 newtype BoolDisj = BoolDisj Bool deriving (Eq, Show) instance Semigroup BoolDisj where (BoolDisj a) <> (BoolDisj b) = BoolDisj (a || b) instance Arbitrary BoolDisj where arbitrary = elements [BoolDisj True, BoolDisj False] type BoolDisjAssoc = BoolDisj -> BoolDisj -> BoolDisj -> Bool -- 8 data Or a b = Fst a | Snd b deriving (Eq, Show) instance Semigroup (Or a b) where f@(Snd a) <> _ = f (Fst _) <> f@(Snd a) = f (Fst _) <> f@(Fst a) = f orGen :: (Arbitrary a, Arbitrary b) => Gen (Or a b) orGen = do a <- arbitrary b <- arbitrary elements [Fst a, Snd b] instance (Arbitrary a, Arbitrary b) => Arbitrary (Or a b) where arbitrary = orGen type OrAssoc = Or String Int -> Or String Int -> Or String Int -> Bool -- 9 newtype Combine a b = Combine { unCombine :: a -> b } instance Semigroup b => Semigroup (Combine a b) where (Combine f1) <> (Combine f2) = Combine (\a -> f1 a S.<> f2 a) -- 10 newtype Comp a = Comp { unComp :: a -> a } instance Semigroup a => Semigroup (Comp a) where (Comp f1) <> (Comp f2) = Comp (\a -> f1 a S.<> f2 a) -- 11 data Validation a b = Failure a | Success b deriving (Eq, Show) instance Semigroup a => Semigroup (Validation a b) where (Failure a1) <> (Failure a2) = Failure $ a1 S.<> a2 f@(Failure b) <> (Success a) = f (Success a) <> f@(Failure b) = f (Success a) <> s@(Success b) = s validationGen :: (Arbitrary a, Arbitrary b) => Gen (Validation a b) validationGen = do a <- arbitrary b <- arbitrary elements [Failure a, Success b] instance (Arbitrary a, Arbitrary b) => Arbitrary (Validation a b) where arbitrary = validationGen type ValidationAssoc = Validation String Int -> Validation String Int -> Validation String Int -> Bool -- 12 newtype AccumulateRight a b = AccumulateRight (Validation a b) deriving (Eq, Show) instance Semigroup b => Semigroup (AccumulateRight a b) where AccumulateRight (Success a1) <> AccumulateRight (Success a2) = AccumulateRight (Success $ a1 S.<> a2) AccumulateRight (Failure b) <> r@(AccumulateRight (Success a)) = r s@(AccumulateRight (Success a)) <> AccumulateRight (Failure b) = s AccumulateRight (Failure a) <> r@(AccumulateRight (Failure b)) = r accumulateRightGen :: (Arbitrary a, Arbitrary b) => Gen (AccumulateRight a b) accumulateRightGen = do a <- arbitrary b <- arbitrary elements [AccumulateRight (Failure a), AccumulateRight (Success b)] instance (Arbitrary a, Arbitrary b) => Arbitrary (AccumulateRight a b) where arbitrary = accumulateRightGen type AccumulateRightAssoc = AccumulateRight String String -> AccumulateRight String String -> AccumulateRight String String -> Bool -- 13 newtype AccumulateBoth a b = AccumulateBoth (Validation a b) deriving (Eq, Show) instance (Semigroup a, Semigroup b) => Semigroup (AccumulateBoth a b) where AccumulateBoth (Success a) <> AccumulateBoth (Success b) = AccumulateBoth (Success $ a S.<> b) f@(AccumulateBoth (Failure a)) <> AccumulateBoth (Success b) = f AccumulateBoth (Success a) <> f@(AccumulateBoth (Failure b)) = f AccumulateBoth (Failure a) <> AccumulateBoth (Failure b) = AccumulateBoth (Failure $ a S.<> b) accumulateBothGen :: (Arbitrary a, Arbitrary b) => Gen (AccumulateBoth a b) accumulateBothGen = do a <- arbitrary b <- arbitrary elements [AccumulateBoth (Failure a), AccumulateBoth (Success b)] instance (Arbitrary a, Arbitrary b) => Arbitrary (AccumulateBoth a b) where arbitrary = accumulateBothGen type AccumulateBothAssoc = AccumulateBoth String String -> AccumulateBoth String String -> AccumulateBoth String String -> Bool
maruks/haskell-book
src/Chapter15_monoids.hs
gpl-3.0
7,799
0
11
1,750
3,359
1,722
1,637
170
1
module Lexer where -- -- the lexer for my new language -- import ApplicativeParsec import qualified Text.ParserCombinators.Parsec.Token as P import Types languageDef = P.LanguageDef { P.commentStart = "{-" , P.commentEnd = "-}" , P.commentLine = "--" , P.nestedComments = True , P.identStart = lower , P.identLetter = alphaNum <|> char '_' , P.opStart = oneOf ":!#$%&*+./<=>?\\^|-~" , P.opLetter = oneOf ":!#$%&*+./<=>?\\^|-~" , P.reservedOpNames= ["::","..","=","\\","|","<-","->","~"] , P.reservedNames = ["let","in","case","of" ,"if","then","else" ,"data","type" ,"class","default","deriving" ,"infix","infixl","infixr" ,"instance","do" ,"newtype" ,"primitive", "module","import", "export", "compile", "where", "when", "private", "public" ] , P.caseSensitive = True } lexer = P.makeTokenParser languageDef whiteSpace = P.whiteSpace lexer lexeme = P.lexeme lexer symbol = P.symbol lexer natural = P.natural lexer parens = P.parens lexer semi = P.semi lexer semiSep = P.semiSep lexer identifier = P.identifier lexer operator = P.operator lexer reserved = P.reserved lexer reservedOp = P.reservedOp lexer braces = P.braces lexer squares = P.squares lexer colon = P.colon lexer commaSep = P.commaSep lexer commaSep1 = P.commaSep1 lexer stringLiteral = P.stringLiteral lexer charLiteral = P.charLiteral lexer integer = P.integer lexer float = P.float lexer lowerId = P.identifier lexer upperId :: GenParser Char st [Char] upperId = (:) <$> upper <*> ((many $ alphaNum <|> char '_') <* whiteSpace) upperId2 = (:) <$> upper <*> (many $ alphaNum <|> char '_') boolId = ((reserved "true") >> return "true") <|> ((reserved "false") >> return "false") wildcard = symbol "_" <?> "wildcard" funcId = lowerId <?> "function" atomId = (:) <$> char '@' <*> (lowerId <?> "atom") moduleId = upperId <?> "module" varId = upperId <?> "variable" moduleOp = "::" modSep x = sepBy1 x (reservedOp moduleOp) colonSep p = sepBy p colon infixFun = between (char '`') (char '`') funcId <?> "function" prefixOperator = parens operator <?> "operator" concatWith [] sep = [] concatWith ws sep = foldr1 (\w s -> w ++ sep ++ s) ws
Jem777/deepthought
src/Lexer.hs
gpl-3.0
2,563
0
10
766
767
425
342
66
1
module LevelSpec(main, spec) where import Test.Hspec import Level import Renderable import TestHelper main :: IO () main = hspec spec spec :: Spec spec = describe "A Level" $ do let levelString = unlines [ "###" , " ##" , "m #" ] level = createLevel levelString at' c = head $ at (from2d c) level it "can be accessed via coordinates" $ do render (at' (1,1)) `shouldBe` '#' render (at' (0,2)) `shouldBe` 'm' render (at' (2,0)) `shouldBe` '#' render (at' (0,1)) `shouldBe` ' ' render (at' (1,2)) `shouldBe` ' ' it "can be rendered to a string" $ do show level `shouldBe` levelString
svenkeidel/gnome-citadel
test/LevelSpec.hs
gpl-3.0
662
0
15
185
265
140
125
23
1
{-# LANGUAGE OverloadedStrings #-} module Greg.Commands.Default (defaultCommands, success, failure) where import System.Random (randomRIO) import System.Process (createProcess, proc, CreateProcess (std_out), StdStream (..)) import Control.Concurrent (readMVar, modifyMVar_) import qualified Data.Text.IO as T import qualified Data.Text as T import Data.Text.Read (decimal) import qualified Data.Map as M import qualified Data.Sequence as S import Greg.Types import Greg.Bot defaultCommands :: [Command] defaultCommands = [echo, help, dementia, quoteview, rq, quote_, visudo, offend, permit, remember, level, fortune_, quotesinfo, quoteinfo] echo, help, dementia, quoteview, rq, quote_, visudo, offend, permit, remember, level, fortune_, quoteinfo, quotesinfo :: Command echo = Com { alias = "echo", desc = "echo something!", reqp = Mod, run = \m _ -> success $ msg m } help = Com { alias = "help", desc = "get help bro :(", reqp = Normal, run = \m b -> case lookupByAlias (msg m) (commands b) of Just cmd -> success $ desc cmd _ -> failure "command not found" } dementia = Com { alias = "dementia", desc = "forget all of a person's quotes", reqp = Mod, run = \m b -> do modifyMVar_ (quotes b) (return . M.delete (msg m)) success "OK." } quoteinfo = Com { alias = "quote-info", desc = "learn about a person in the quote db", reqp = Normal, run = \m b -> do qs <- readMVar (quotes b) let quoteTotal = T.pack $ show $ case M.lookup (msg m) qs of Just iqs -> S.length iqs _ -> 0 success $ sender m `T.append` ": " `T.append` quoteTotal `T.append` " quotes from this person in the db." } quotesinfo = Com { alias = "quotes-info", desc = "learn about quotes", reqp = Normal, run = \m b -> do qs <- readMVar (quotes b) let totalDudes = T.pack $ show $ M.size qs totalQuotes = T.pack $ show $ sum $ map (S.length . snd) (M.toList qs) success $ sender m `T.append` ": " `T.append` totalDudes `T.append` " people in the db, " `T.append` totalQuotes `T.append` " quotes in total." } quoteview = Com { alias = "quote-view", desc = "get the nth quote from someone, eg ~quote-view guy 345", reqp = Normal, run = \m b -> do qs <- readMVar (quotes b) let ws = T.words (msg m) if length ws == 2 then case M.lookup (head ws) qs of Just iqs -> case decimal (ws !! 1) of -- decimal (T.unpack (ws !! 1)) :: [(Int, String)] of Right (i, "") | i <= S.length iqs -> success $ sender m `T.append` ": " `T.append` S.index iqs i _ -> failure "not found" _ -> failure "this person has no quotes" else failure "bad arguments" } rq = quote_ { alias = "rq" } -- an awesome hack quote_ = Com { alias = "quote", desc = "get a quote!", reqp = Normal, run = \m b -> if T.null (msg m) then do qs <- readMVar (quotes b) if M.null qs then failure "No quotes available!" else do senderIndex <- randomRIO (0, M.size qs - 1) let (nick, quoteSeq) = M.elemAt senderIndex qs quoteIndex <- randomRIO (0, S.length quoteSeq - 1) let quote = quoteSeq `S.index` quoteIndex success $ "<" `T.append` nick `T.append` "> " `T.append` quote else do qs <- readMVar (quotes b) case M.lookup (msg m) qs of Just quoteSeq -> do quoteIndex <- randomRIO (0, S.length quoteSeq - 1) let quote = quoteSeq `S.index` quoteIndex success $ "<" `T.append` msg m `T.append` "> " `T.append` quote _ -> failure "YOU LOSE!" } visudo = Com { alias = "visudo", desc = "grant any permission", reqp = Admin, run = \(Msg _ _ m) bot -> case T.words m of [dude, newPermit] -> case decimal newPermit of Right (p, "") | p < 4 -> do addToPermissions bot dude (toEnum p) success "OK." _ -> failure "sorry dave!" _ -> failure "bad arguments dave!" } fortune_ = Com { alias = "fortune", desc = "sporadically-daily fortunes", reqp = Normal, run = \_ _ -> do (_, Just fortuneHandle, _, _) <- createProcess (proc "fortune" ["-s"]) { std_out = CreatePipe } fortune <- T.hGetContents fortuneHandle success fortune } offend = Com { alias = "offend", desc = "too many friends? offend someone!", reqp = Normal, run = \(Msg _ _ target) _ -> do (_, Just fortuneHandle, _, _) <- createProcess (proc "fortune" ["-os"]) { std_out = CreatePipe } fortune <- T.hGetContents fortuneHandle success $ (if T.null target then "" else target `T.append` ": ") `T.append` fortune } permit = Com { alias = "permit", desc = "get a permit", reqp = Mod, run = \(Msg _ _ m) bot -> case T.words m of [dude, newPermit] -> case decimal newPermit of Right (p, "") | p < 4 -> do addToPermissions bot dude (toEnum p) success "OK" _ -> failure "sorry dave" _ -> failure "sorry dave" } remember = Com { alias = "remember", desc = "remember a quote", reqp = Mod, run = \(Msg _ _ m) bot -> case T.breakOn " " m of ("", _) -> failure "can't do that" (_, "") -> failure "can't do that" (dude, quote) -> do addToQuotes bot (Msg dude undefined (T.tail quote)) success "OK" } level = Com { alias = "level", desc = "get your level!", reqp = Normal, run = \mg bot -> do ps <- readMVar (permissions bot) maybe (success "Normal") (success . T.pack . show) (M.lookup (if T.null (msg mg) then sender mg else msg mg) ps) } {-# INLINE success #-} success :: a -> IO (Either b a) success = return . Right {-# INLINE failure #-} failure :: a -> IO (Either a b) failure = return . Left
mikeplus64/Greg
src/Greg/Commands/Default.hs
gpl-3.0
6,443
0
22
2,240
2,137
1,168
969
156
4
{-# LANGUAGE OverloadedStrings #-} -- Type : module -- Crée le: 17 Fév. 2013 à 16h46 -- Auteur : Sarfraz Kapasi -- License: GPLv3 module MSendT ( Provider (..) , Auth (..) , Cred (..) , emptyAuth , emptyCred , gmail , mimeMsg , emailT ) where import Network import Network.TLS import Network.TLS.Extra import System.Cmd (rawSystem) import System.Random import System.IO import System.FilePath import Text.Printf import Control.Applicative ( (<$>) ) import Control.Monad (unless) import Data.Monoid ( (<>) ) import Data.List (isPrefixOf) import qualified Crypto.Random.AESCtr as RNG (makeSystem) import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Lazy.UTF8 as BLU (fromString,toString) import qualified Data.ByteString.Base64.Lazy as BE (encode) import qualified Data.Text as T import qualified Data.Text.IO as T --- Data Part --- data Provider = Provider {server :: T.Text, port :: Int} data Auth = Auth {user :: T.Text, pass :: T.Text} data Cred = Cred {name :: T.Text, mail :: T.Text, company :: T.Text} emptyAuth :: Auth emptyAuth = Auth { user = "" , pass = "" } emptyCred :: Cred emptyCred = Cred { name = "" , mail = "" , company = "" } gmail :: Provider gmail = Provider {server = "smtp.gmail.com", port = 587} --- MIME Part --- mimeMsgT :: RandomGen a => a -> Cred -> Cred -> T.Text -> T.Text -> (T.Text,T.Text) mimeMsgT g from to subject body = ("From: " <> name from <> " <" <> mail from <> ">" <> "\n" <> "To: " <> name to <> " <" <> mail to <> ">" <> "\n" <> "Subject: " <> subject <> "\n" <> "MIME-Version: 1.0" <> "\n" <> "Content-Type: multipart/mixed; boundary=" <> boundary <> "\n\n" <> "--" <> boundary <> "\n" <> "Content-Type: text/plain; charset=utf-8" <> "\n" <> "Content-Transfer-Encoding: 8bit" <> "\n\n" <> body <> "\n\n", boundary) where boundary = T.pack $ take 20 $ randomRs ('a','z') g mimeMsgA :: T.Text -> [(T.Text,FilePath)] -> IO T.Text mimeMsgA boundary attachments = if null attachments then return "" else T.concat <$> mapM (mimeA boundary) attachments mimeA :: T.Text -> (T.Text,FilePath) -> IO T.Text mimeA boundary attachment = BL.readFile (snd attachment) >>= (\x -> return $ "--" <> boundary <> "\n" <> "Content-Type: " <> fst attachment <> "\n" <> "Content-Disposition: attachment; filename=\"" <> T.pack (takeFileName $ snd attachment) <> "\"" <> "\n" <> "Content-Transfer-Encoding: base64" <> "\n\n" <> T.pack (BLU.toString $ BE.encode x) <> "\n\n") mimeMsgC :: T.Text -> T.Text mimeMsgC boundary = "--" <> boundary <> "--" mimeMsg :: RandomGen a => a -> Cred -> Cred -> T.Text -> T.Text -> [(T.Text,FilePath)] -> IO T.Text mimeMsg g from to subject body attachments = do msgA <- mimeMsgA (snd msgT) attachments return $ fst msgT <> msgA <> mimeMsgC (snd msgT) where msgT = mimeMsgT g from to subject body --- Mail Part ---- cWrite :: Handle -> String -> IO () cWrite h s = do hPrintf h "%s\r\n" s printf "> %s\n" s cWaitFor :: Handle -> String -> IO () cWaitFor h str = do ln <- hGetLine h putStrLn ln unless (str `isPrefixOf` ln) (cWaitFor h str) tWrite :: Context -> BL.ByteString -> IO () tWrite ctx bts = do sendData ctx $ bts <> "\r\n" BL.putStrLn ("> " <> bts) tWaitFor :: Context -> BC.ByteString -> IO () tWaitFor ctx bts = do dat <- recvData ctx BC.putStrLn dat unless (bts `BC.isPrefixOf` dat) (tWaitFor ctx bts) emailT :: Provider -> Auth -> Cred -> Cred -> T.Text -> T.Text -> [(T.Text,FilePath)] -> IO () emailT provider auth from to subject email attachments = do let ciphers = [cipher_AES128_SHA1,cipher_AES256_SHA1,cipher_RC4_128_MD5,cipher_RC4_128_SHA1] params = defaultParamsClient{pCiphers = ciphers} g <- RNG.makeSystem mimeMail <- mimeMsg g from to subject email attachments h <- connectTo (T.unpack $ server provider) (PortNumber (fromIntegral (port provider))) hSetBuffering h LineBuffering cWrite h "EHLO" cWaitFor h "250-STARTTLS" cWrite h "STARTTLS" cWaitFor h "220" con <- contextNewOnHandle h params g handshake con tWrite con "EHLO" tWaitFor con "250" tWrite con "AUTH LOGIN" tWaitFor con "334" tWrite con $ BE.encode $ BLU.fromString $ T.unpack $ user auth tWaitFor con "334" tWrite con $ BE.encode $ BLU.fromString $ T.unpack $ pass auth tWaitFor con "235" tWrite con $ BLU.fromString $ T.unpack ("MAIL FROM:<"<> mail from <>">") tWaitFor con "250" tWrite con $ BLU.fromString $ T.unpack ("RCPT TO:<"<> mail to <>">") tWaitFor con "250" tWrite con "DATA" tWaitFor con "354" tWrite con $ BLU.fromString $ T.unpack mimeMail tWrite con "\r\n." tWaitFor con "250" tWrite con "QUIT" tWaitFor con "221" bye con --EOF
neliel/MSendT
MsendT.hs
gpl-3.0
5,002
0
34
1,185
1,753
905
848
128
2
-- This file is part of seismic_acc_no_up. -- -- seismic_acc_no_up 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. -- -- seismic_acc_no_up 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 seismic_acc_no_up. If not, see <http://www.gnu.org/licenses/>. {-# LANGUAGE FlexibleContexts, BangPatterns, ScopedTypeVariables#-} {-# OPTIONS -Wall -fno-warn-missing-signatures -fno-warn-incomplete-patterns #-} import Seismic import System.Environment import Data.Time(getCurrentTime, diffUTCTime) import Data.Array.Accelerate.CUDA as CUDA main :: IO () main = do args <- getArgs case args of [t, x, y] -> go (read t::Int) (read x::Int) (read y::Int) _ -> print usage go !t !x !y = do let ppf = genPPF x y let apf = genAPF x y let vel = genVEL x y let pulse = genSeismicPulseVector t start <- getCurrentTime let !res = CUDA.run $ doNTimes ppf apf vel pulse t 0 x y end <- getCurrentTime print $ diffUTCTime end start return () usage :: String usage = "Usage: seismic_acc_no_up timeSteps xDim yDim"
agremm/Seismic
accelerate/imaginary_gpu_update/Main.hs
gpl-3.0
1,528
0
12
319
281
145
136
24
2
#!/usr/bin/env stack {- stack runghc --verbosity info --package aeson --package bytestring --package conduit --package http-conduit --package resourcet --package text -} {- gist.hs - a command-line client for gist.github.com that works. (c) 2012-2017 Simon Michael <[email protected]> -} {-# LANGUAGE OverloadedStrings, RecordWildCards, FlexibleContexts #-} import Control.Applicative ((<$>), empty) import Control.Monad.Trans.Resource import Data.Aeson import qualified Data.ByteString.Lazy.Char8 as BL import Data.Conduit import qualified Data.Text as T import Network.HTTP.Conduit import System.IO import System.Environment version = "0.1.98" data Paste = Paste { pasteDescription :: T.Text, pastePublic :: Bool, pasteFiles :: Value } instance ToJSON Paste where toJSON Paste{..} = object [ "description" .= pasteDescription ,"public" .= pastePublic ,"files" .= pasteFiles ] data PasteResponse = PasteResponse { pasteResponseUrl :: String } instance FromJSON PasteResponse where parseJSON (Object v) = PasteResponse <$> v .: "html_url" parseJSON _ = empty main = do args <- getArgs hasstdin <- hReady stdin case (args, hasstdin) of ([f],_) -> readFile f >>= paste "" (T.pack f) >>= report ([],True) -> getContents >>= paste "" "" >>= report _ -> usage usage = putStr $ unlines ["gist "++version ,"Usage: gist FILE or cat FILE | gist to make a public paste at gist.github.com" ] paste description filename content = do let paste = Paste description True $ object [filename .= object ["content" .= content]] req <- parseUrl "https://api.github.com/gists" runResourceT $ do withManager $ \mgr -> do httpLbs req{method = "POST", requestBody = RequestBodyLBS $ encode paste} mgr report rsp = do putStrLn $ show $ responseStatus rsp let body = responseBody rsp mresponse = decode body putStrLn $ maybe ("Unknown response:\n" ++ (BL.unpack body)) pasteResponseUrl mresponse
simonmichael/gist
gist.hs
gpl-3.0
2,094
0
18
488
512
273
239
47
3
{-# LANGUAGE RankNTypes #-} module Diaspec.Backend.PrintDiaspec where {- - This module is intended to handle pretty printing of - Diaspec code. Using the compiler using this backend - should be like a linter. -} -- Copyright 2015 © Paul van der Walt <[email protected]> import UU.Pretty hiding (pp) import Diaspec.Backend.AG import Diaspec.Sort () import Data.List (sort) -- TODO directly call all functions on Specification -- it's a nonterminal now too!! -- give this a name for exporting. prettyDia :: Specification -> PP_Doc prettyDia (S pn s) = text "" >-< text "-- Auto generated specification" >-< text "" >-< format (sort s) where format = formatWith (\d -> ppDia_Syn_Declaration (wrap_Declaration (sem_Declaration d) (inhDeclaration pn))) inhDeclaration :: String -> Inh_Declaration inhDeclaration pn = Inh_Declaration { pkg_Inh_Declaration = Nothing , tyEnv_Inh_Declaration = [] } formatWith :: forall a b. (PP b) => (a->b) -> [a] -> PP_Doc formatWith f = foldr (\d doc -> f d >-< text "" >-< doc) empty prettyRacket :: Specification -> PP_Doc prettyRacket (S pn s) = text "" >-< text ";; Auto generated specification" >-< text "#lang s-exp \"diaspec.rkt\"" >-< text "" >-< format (sort s) where format = formatWith (\d -> ppRacket_Syn_Declaration (wrap_Declaration (sem_Declaration d) (inhDeclaration pn)))
toothbrush/diaspec
src/Diaspec/Backend/PrintDiaspec.hs
gpl-3.0
1,538
0
14
413
354
188
166
22
1
{-# LANGUAGE OverloadedStrings #-} module Web.Crew.Templates.Helpers where import Text.Blaze.Html5 as H import Text.Blaze.Html5.Attributes as A headWithTitle :: H.Markup -> Html headWithTitle t = H.head $ do meta ! charset "utf-8" meta ! name "viewport" ! content "width=device-width, initial-scale=1.0" meta ! name "description" ! content "" meta ! name "author" ! content "Schell Scivally" H.title t -- Bootstrap core CSS link ! href "http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" ! rel "stylesheet" link ! href "http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" ! rel "stylesheet" -- Add custom CSS here H.style "body {margin-top: 60px;}"
schell/scottys-crew
Web/Crew/Templates/Helpers.hs
gpl-3.0
738
0
10
128
164
80
84
14
1
module QFeldspar.ErrorMonad(ErrM(..),frmRgt) where import Prelude (Monad(..),String,Eq,Show,Functor,error) import Control.Applicative (Applicative(..)) import Data.Foldable (Foldable) import Data.Traversable (Traversable) data ErrM t = Rgt t | Lft String deriving instance Eq t => Eq (ErrM t) deriving instance Show t => Show (ErrM t) deriving instance Functor ErrM deriving instance Foldable ErrM deriving instance Traversable ErrM instance Applicative ErrM where pure = return e1 <*> e2 = do v1 <- e1 v2 <- e2 return (v1 v2) instance Monad ErrM where return = Rgt Lft l >>= _ = Lft l Rgt r >>= k = k r fail x = Lft x frmRgt :: ErrM a -> a frmRgt (Rgt x) = x frmRgt (Lft s) = error s
shayan-najd/QFeldspar
QFeldspar/ErrorMonad.hs
gpl-3.0
774
0
10
205
311
162
149
-1
-1
{-# LANGUAGE FlexibleContexts #-} -------------------------------------------------------------------------------- -- | -- Module : Web.Model -- Copyright : (C) 2014 Yorick Laupa -- License : (see the file LICENSE) -- -- Maintainer : Yorick Laupa <[email protected]> -- Stability : provisional -- Portability : non-portable -- -------------------------------------------------------------------------------- module Web.Model where -------------------------------------------------------------------------------- import Control.Monad.State import Data.List import System.Locale (defaultTimeLocale) -------------------------------------------------------------------------------- import Data.Time -------------------------------------------------------------------------------- import Web.Pandoc import Web.Type -------------------------------------------------------------------------------- model :: MonadState AppState m => Input -> m Output model (Index names) = modelIndex names model (GetArticle name c) = modelGetArticle name c -------------------------------------------------------------------------------- modelIndex :: MonadState AppState m => [String] -> m Output modelIndex = return . ArticleList . sortArticles . fmap parseArticle -------------------------------------------------------------------------------- modelGetArticle :: MonadState AppState m => String -> String -> m Output modelGetArticle name content = return $ ArticleView title date doc where (date, titleStr) = splitAt 10 name title = replace '_' ' ' $ drop 1 titleStr doc = readGithubMarkdown content -------------------------------------------------------------------------------- parseArticle :: String -> Article parseArticle name = Article name date title where (dateStr, titleStr) = splitAt 10 name date = readTime defaultTimeLocale "%Y-%m-%d" dateStr title = replace '_' ' ' $ drop 1 titleStr -------------------------------------------------------------------------------- replace :: Eq a => a -> a -> [a] -> [a] replace trg val = map (\c -> if c == trg then val else c) -------------------------------------------------------------------------------- sortArticles :: [Article] -> [Article] sortArticles = reverse . sortBy go where go a b = compare (articleDate a) (articleDate b)
YoEight/personal-site
Web/Model.hs
gpl-3.0
2,346
0
9
315
451
242
209
32
2
import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes import ListApplicative import Validation import ChapterExercises main :: IO() main = do quickBatch $ functor (undefined :: List (String, Char, Integer)) quickBatch $ applicative (undefined :: List (String, Char, Integer)) quickBatch $ functor (undefined :: ZipList (String, Char, Integer)) quickBatch $ applicative (undefined :: ZipList (String, Char, Integer)) quickBatch $ functor (undefined :: Validation Int (String, Char, Int)) quickBatch $ applicative (undefined :: Validation String (String, Char, Int)) quickBatch $ functor (undefined :: Pair (String, Char, Int)) quickBatch $ applicative (undefined :: Pair (String, Char, Int)) quickBatch $ functor (undefined :: Two String (String, Char, Int)) quickBatch $ applicative (undefined :: Two String (String, Char, Int)) quickBatch $ functor (undefined :: Three String String (String, Char, Int)) quickBatch $ applicative (undefined :: Three String String (String, Char, Int)) quickBatch $ functor (undefined :: Three' String (String, Char, Int)) quickBatch $ applicative (undefined :: Three' String (String, Char, Int))
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
Applicative/test/Spec.hs
gpl-3.0
1,218
0
11
211
454
245
209
22
1
-- Martelli and Montanari 1976 unification Algorithm A -- I call it Unification Transform because it transforms -- a first order term equations set (FOTEset) into its solved form -- 23 Jun 2015 V 1 module MMAlgoA ( unificationTransform, eliminatableVariablesExist, isInSolvedForm, isUnsolvable, step_a, step_b, termReduction, variableElimination ) where import FOTEset (FOTE, FOTEset, varOccurAtLeastOnceInRestof, varOccurMoreThanOnceIn) import ReadPrintTerms (Term(..), isVariable, occursAt) import Substitution (applySubs) import Data.Tuple (swap) import Data.Maybe (fromJust) import Data.List (find, delete) isInSolvedForm :: FOTEset -> Bool -- Pre-requisite: -- None isInSolvedForm eSet | eSet == [] = True | (not . all foteHasGoodForm) eSet = False | occurMoreThanOnce eSet eSet = False | otherwise = True occurMoreThanOnce :: FOTEset -> FOTEset -> Bool -- pre-requisite: -- In first argument, all FOTEs in good form -- argument specifiaction: -- first and second argument are equal in value -- functionality: -- check if left member (variables) of good form FOTEs occur more than once occurMoreThanOnce [] _ = False occurMoreThanOnce (equ:restEqu) eSet = equ `varOccurMoreThanOnceIn` eSet || occurMoreThanOnce restEqu eSet -------------------------------------------------------------------------------- isUnsolvable :: FOTEset -> Bool -- Pre-requisite: -- isInSolvedForm returns False isUnsolvable eSet | termReduceFail eSet = True | variableEliminationFail eSet = True | otherwise = False -------------------------------------------------------------------------------- unificationTransform :: FOTEset -> Maybe FOTEset unificationTransform eSet | isInSolvedForm eSet = Just eSet | isUnsolvable eSet = Nothing | (not . all foteHasGoodForm) eSet = unificationTransform $ step_b $ step_a $ termReduction $ step_b $ step_a eSet | eliminatableVariablesExist eSet eSet = unificationTransform $ step_b $ step_a $ variableElimination $ step_b $ step_a eSet --step a) any t = x -> x = t where x is a vriable and t is not variable --------------------------------------------------------------------------------- swapConditionMet :: FOTE -> Bool swapConditionMet (left, right) = (isVariable right) && ((not . isVariable) left) swapIf :: ((a, a)-> Bool) -> (a, a) -> (a, a) swapIf condi tup | condi tup = swap tup | otherwise = tup step_a :: FOTEset -> FOTEset -- Pre-requisite: -- None step_a [] = [] step_a eSet@(_:_) = map (swapIf swapConditionMet) eSet -- step b) select any equation of the form x =x , where x is variable, erase it step_b :: FOTEset -> FOTEset -- Pre-requisite: -- None step_b = filter (not . erasable) erasable :: FOTE -> Bool erasable (Variable a, Variable b) | a == b = True | otherwise = False erasable _ = False --step c) select any equation of form t = t' where t and t' are not variables --if t and t' have different root function symbol return fail otherwiseapply term reduction singleFail :: FOTE -> Bool -- tell whether term reduction shall return failure on an equation singleFail ((Constant a), (Constant c)) | a /= c = True | otherwise = False singleFail ((Function f a ts), (Constant c)) | f /= c || a /= 0 || ((not . null) ts) = True | otherwise = False singleFail ((Constant c), (Function f a ts)) | f /= c || a /= 0 || ((not . null) ts) = True | otherwise = False singleFail ((Function g b ts1), (Function f a ts2)) | f /= g || a /= b || ((length ts1) /= (length ts2)) = True | otherwise = False singleFail _ = False -------------------------------------------------------------------------------- termReduceFail :: FOTEset -> Bool -- check-of-fail for term reduction; point-free definition of function -- True case: -- there is any FOTE makes singleFail return True -- False case: -- no FOTE makes singleFail return True termReduceFail = any singleFail -------------------------------------------------------------------------------- reduceFOTE :: FOTE -> FOTEset --applies to any FOTE in the FOTE set when the set doesn't make term reduction fail reduceFOTE ((Constant _), (Constant _)) = [] reduceFOTE ((Function _ _ _), (Constant _)) = [] reduceFOTE ((Constant _), (Function _ _ _)) = [] reduceFOTE ((Function _ _ ts1), (Function _ _ ts2)) = zip ts1 ts2 reduceFOTE fote = [fote] --------------------------------------------------------------------------------- termReduction :: FOTEset -> FOTEset --operates when check-of-fail shows not fail for term reduction termReduction = concat . map reduceFOTE -- step d) variable elimination: choose any equation of the form x = t where x is -- a variable that occurs somewhere else in the set; t /= x; if x occurs in t return -- fail othwise perform variable elimination -------------------------------------------------------------------------------- foteHasGoodForm :: FOTE -> Bool -- tell whether a FOTE has the form x = t where x is a variable and t is not x -- i.e. tell whether a FOTE is good form FOTE foteHasGoodForm (Variable l, Variable r) | l /= r = True | otherwise = False foteHasGoodForm (Variable _ , _ ) = True foteHasGoodForm _ = False --------------------------------------------------------------------------------- goodFormFOTEPassesOccursCheck :: FOTE -> Bool -- Argument specification: -- FOTE must has good form (x = t) -- Functionality: -- see whether x occurs in t goodFormFOTEPassesOccursCheck (_ , Variable _) = True goodFormFOTEPassesOccursCheck (_ , Constant _) = True goodFormFOTEPassesOccursCheck (x , t) | x `occursAt` t = False | otherwise = True --------------------------------------------------------------------------------- variableEliminationFail :: FOTEset -> Bool variableEliminationFail = not . all goodFormFOTEPassesOccursCheck . filter foteHasGoodForm -- False cases: -- No good form FOTE, or -- there is good form FOTE(s) and all good form FOTEs pass occurs check -- True case: -- there is good form FOTE(s) and any of them doesn't pass occurs check --------------------------------------------------------------------------------- eliminatableVariablesExist :: FOTEset -> FOTEset -> Bool -- Pre-requisite: -- variableEliminationFail False cases -- Arguments specification: -- First argument is the set of good form FOTEs (maybe empty) -- Second argument is a superset of the first argument -- Functionality: -- this funnction tells are there any FOTE in the first argument whose variable (left member) occurs -- more than once in the second argumennt. -- True case: -- First argument not empty, and -- at least one FOTE from first argument has left member, which is a variable, occurs more than once in the second argument -- False cases: -- No good form FOTE, or -- there is good form FOTE and none of them has a left member, which is a variable, occurs more than once in the second argument eliminatableVariablesExist [] _ = False eliminatableVariablesExist (fote:fotes) eSet = (fote `varOccurMoreThanOnceIn` eSet) || eliminatableVariablesExist fotes eSet --Alternatively: --(fote `varOccurAtLeastOnceInRestof` eSet) || eliminatableVariablesExist fotes eSet -------------------------------------------------------------------------------- isFoteThatContainsEliminatableVarialeIn :: FOTEset -> FOTE -> Bool -- Pre-requisite: -- eliminatableVariablesExist True Case -- Functionality: -- Tell whether the FOTE whose left member which is a variable, can be -- eliminated from the FOTEset isFoteThatContainsEliminatableVarialeIn eSet fote = fote ` varOccurMoreThanOnceIn` eSet -- Alternatively: -- fote ` varOccurMoreThanOnceIn` eSet --------------------------------------------------------------------------------- variableElimination :: FOTEset -> FOTEset -- Pre-requisite : -- eliminatableVariablesExist True Case -- The procedure: -- find the first good form FOTE ft that contains eliminatable variable from all good form FOTES -- remove ft from the FOTE set but keep a copy of ft elsewhere; yielding a new FOTE set fts from where one occurance of ft has been removed -- regard ft as substitution s_ft (swap); -- unzip fts to get ([Term],[Term]) -- apply s_ft to both lists of terms -- zip the resulting two lists where there is no occurance of the variable to be eliminated, yielding FOTE set fts' -- add ft back to fts' variableElimination eSet = eSet' where goodFormFOTEs = filter foteHasGoodForm eSet goodFormFOTE = find (isFoteThatContainsEliminatableVarialeIn eSet) goodFormFOTEs ft = fromJust goodFormFOTE fts = delete ft eSet s_ft = swap ft : [] (ts1, ts2) = unzip fts ts1' = applySubs s_ft ts1 ts2' = applySubs s_ft ts2 fts' = zip ts1' ts2' eSet' = ft : fts'
YueLiPicasso/unification
MMAlgoA.hs
gpl-3.0
9,961
0
12
2,717
1,626
879
747
105
1
{-# LANGUAGE CPP #-} {-| Print some statistics for the journal. -} module Hledger.Cli.Stats where import Data.List import Data.Maybe import Data.Ord import Data.Time.Calendar import Text.Printf import qualified Data.Map as Map import Hledger.Cli.Options import Hledger.Data import Prelude hiding (putStr) import Hledger.Utils.UTF8 (putStr) -- like Register.summarisePostings -- | Print various statistics for the journal. stats :: [Opt] -> [String] -> Journal -> IO () stats opts args j = do d <- getCurrentDay let filterspec = optsToFilterSpec opts args d l = journalToLedger filterspec j reportspan = (ledgerDateSpan l) `orDatesFrom` (datespan filterspec) intervalspans = splitSpan (intervalFromOpts opts) reportspan showstats = showLedgerStats opts args l d s = intercalate "\n" $ map showstats intervalspans putStr s showLedgerStats :: [Opt] -> [String] -> Ledger -> Day -> DateSpan -> String showLedgerStats _ _ l today span = unlines (map (uncurry (printf fmt)) stats) where fmt = "%-" ++ show w1 ++ "s: %-" ++ show w2 ++ "s" w1 = maximum $ map (length . fst) stats w2 = maximum $ map (length . show . snd) stats stats = [ ("Journal file", journalFilePath $ journal l) ,("Transactions span", printf "%s to %s (%d days)" (start span) (end span) days) ,("Last transaction", maybe "none" show lastdate ++ showelapsed lastelapsed) ,("Transactions", printf "%d (%0.1f per day)" tnum txnrate) ,("Transactions last 30 days", printf "%d (%0.1f per day)" tnum30 txnrate30) ,("Transactions last 7 days", printf "%d (%0.1f per day)" tnum7 txnrate7) ,("Payees/descriptions", show $ length $ nub $ map tdescription ts) ,("Accounts", printf "%d (depth %d)" acctnum acctdepth) ,("Commodities", printf "%s (%s)" (show $ length cs) (intercalate ", " cs)) -- Transactions this month : %(monthtxns)s (last month in the same period: %(lastmonthtxns)s) -- Uncleared transactions : %(uncleared)s -- Days since reconciliation : %(reconcileelapsed)s -- Days since last transaction : %(recentelapsed)s ] where ts = sortBy (comparing tdate) $ filter (spanContainsDate span . tdate) $ jtxns $ journal l as = nub $ map paccount $ concatMap tpostings ts cs = Map.keys $ canonicaliseCommodities $ nub $ map commodity $ concatMap amounts $ map pamount $ concatMap tpostings ts lastdate | null ts = Nothing | otherwise = Just $ tdate $ last ts lastelapsed = maybe Nothing (Just . diffDays today) lastdate showelapsed Nothing = "" showelapsed (Just days) = printf " (%d %s)" days' direction where days' = abs days direction | days >= 0 = "days ago" | otherwise = "days from now" tnum = length ts start (DateSpan (Just d) _) = show d start _ = "" end (DateSpan _ (Just d)) = show d end _ = "" days = fromMaybe 0 $ daysInSpan span txnrate | days==0 = 0 | otherwise = fromIntegral tnum / fromIntegral days :: Double tnum30 = length $ filter withinlast30 ts withinlast30 t = d >= addDays (-30) today && (d<=today) where d = tdate t txnrate30 = fromIntegral tnum30 / 30 :: Double tnum7 = length $ filter withinlast7 ts withinlast7 t = d >= addDays (-7) today && (d<=today) where d = tdate t txnrate7 = fromIntegral tnum7 / 7 :: Double acctnum = length as acctdepth | null as = 0 | otherwise = maximum $ map accountNameLevel as
trygvis/hledger
hledger/Hledger/Cli/Stats.hs
gpl-3.0
3,888
0
15
1,221
1,111
571
540
66
4
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.AppEngine.Apps.Firewall.IngressRules.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Gets the specified firewall rule. -- -- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ App Engine Admin API Reference> for @appengine.apps.firewall.ingressRules.get@. module Network.Google.Resource.AppEngine.Apps.Firewall.IngressRules.Get ( -- * REST Resource AppsFirewallIngressRulesGetResource -- * Creating a Request , appsFirewallIngressRulesGet , AppsFirewallIngressRulesGet -- * Request Lenses , afirgXgafv , afirgUploadProtocol , afirgAccessToken , afirgUploadType , afirgIngressRulesId , afirgAppsId , afirgCallback ) where import Network.Google.AppEngine.Types import Network.Google.Prelude -- | A resource alias for @appengine.apps.firewall.ingressRules.get@ method which the -- 'AppsFirewallIngressRulesGet' request conforms to. type AppsFirewallIngressRulesGetResource = "v1" :> "apps" :> Capture "appsId" Text :> "firewall" :> "ingressRules" :> Capture "ingressRulesId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] FirewallRule -- | Gets the specified firewall rule. -- -- /See:/ 'appsFirewallIngressRulesGet' smart constructor. data AppsFirewallIngressRulesGet = AppsFirewallIngressRulesGet' { _afirgXgafv :: !(Maybe Xgafv) , _afirgUploadProtocol :: !(Maybe Text) , _afirgAccessToken :: !(Maybe Text) , _afirgUploadType :: !(Maybe Text) , _afirgIngressRulesId :: !Text , _afirgAppsId :: !Text , _afirgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AppsFirewallIngressRulesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'afirgXgafv' -- -- * 'afirgUploadProtocol' -- -- * 'afirgAccessToken' -- -- * 'afirgUploadType' -- -- * 'afirgIngressRulesId' -- -- * 'afirgAppsId' -- -- * 'afirgCallback' appsFirewallIngressRulesGet :: Text -- ^ 'afirgIngressRulesId' -> Text -- ^ 'afirgAppsId' -> AppsFirewallIngressRulesGet appsFirewallIngressRulesGet pAfirgIngressRulesId_ pAfirgAppsId_ = AppsFirewallIngressRulesGet' { _afirgXgafv = Nothing , _afirgUploadProtocol = Nothing , _afirgAccessToken = Nothing , _afirgUploadType = Nothing , _afirgIngressRulesId = pAfirgIngressRulesId_ , _afirgAppsId = pAfirgAppsId_ , _afirgCallback = Nothing } -- | V1 error format. afirgXgafv :: Lens' AppsFirewallIngressRulesGet (Maybe Xgafv) afirgXgafv = lens _afirgXgafv (\ s a -> s{_afirgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). afirgUploadProtocol :: Lens' AppsFirewallIngressRulesGet (Maybe Text) afirgUploadProtocol = lens _afirgUploadProtocol (\ s a -> s{_afirgUploadProtocol = a}) -- | OAuth access token. afirgAccessToken :: Lens' AppsFirewallIngressRulesGet (Maybe Text) afirgAccessToken = lens _afirgAccessToken (\ s a -> s{_afirgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). afirgUploadType :: Lens' AppsFirewallIngressRulesGet (Maybe Text) afirgUploadType = lens _afirgUploadType (\ s a -> s{_afirgUploadType = a}) -- | Part of \`name\`. See documentation of \`appsId\`. afirgIngressRulesId :: Lens' AppsFirewallIngressRulesGet Text afirgIngressRulesId = lens _afirgIngressRulesId (\ s a -> s{_afirgIngressRulesId = a}) -- | Part of \`name\`. Name of the Firewall resource to retrieve. Example: -- apps\/myapp\/firewall\/ingressRules\/100. afirgAppsId :: Lens' AppsFirewallIngressRulesGet Text afirgAppsId = lens _afirgAppsId (\ s a -> s{_afirgAppsId = a}) -- | JSONP afirgCallback :: Lens' AppsFirewallIngressRulesGet (Maybe Text) afirgCallback = lens _afirgCallback (\ s a -> s{_afirgCallback = a}) instance GoogleRequest AppsFirewallIngressRulesGet where type Rs AppsFirewallIngressRulesGet = FirewallRule type Scopes AppsFirewallIngressRulesGet = '["https://www.googleapis.com/auth/appengine.admin", "https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/cloud-platform.read-only"] requestClient AppsFirewallIngressRulesGet'{..} = go _afirgAppsId _afirgIngressRulesId _afirgXgafv _afirgUploadProtocol _afirgAccessToken _afirgUploadType _afirgCallback (Just AltJSON) appEngineService where go = buildClient (Proxy :: Proxy AppsFirewallIngressRulesGetResource) mempty
brendanhay/gogol
gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/Firewall/IngressRules/Get.hs
mpl-2.0
5,719
0
19
1,272
790
461
329
120
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.ImageStreamImage where import GHC.Generics import Data.Text import Kubernetes.V1.ObjectMeta import Openshift.V1.Image import qualified Data.Aeson -- | data ImageStreamImage = ImageStreamImage { kind :: Maybe Text -- ^ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds , apiVersion :: Maybe Text -- ^ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources , metadata :: Maybe ObjectMeta -- ^ , image :: Image -- ^ the image associated with the ImageStream and image name } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON ImageStreamImage instance Data.Aeson.ToJSON ImageStreamImage
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/ImageStreamImage.hs
apache-2.0
1,233
0
9
178
122
75
47
19
0
{- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE RecordWildCards #-} {- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE ViewPatterns #-} -- | -- This module encapsulates the logics behind the prediction code in the -- multi-player setup. module CodeWorld.Prediction ( Timestamp, AnimationRate, StepFun, Future, initFuture, currentTimePasses, currentState, addEvent, currentStateDirect, eqFuture, printInternalState, ) where import Data.Bifunctor (second) import qualified Data.IntMap as IM import Data.List (foldl', intercalate) import qualified Data.MultiMap as M import Text.Printf type PlayerId = Int type Timestamp = Double -- in seconds, relative to some arbitrary starting point type AnimationRate = Double -- in seconds, e.g. 0.1 -- All we do with events is to apply them to the state. So let's just store the -- function that does that. type Event s = s -> s -- A state and an event only make sense together with a time. type TState s = (Timestamp, s) type TEvent s = (Timestamp, Event s) type StepFun s = Double -> s -> s type EventQueue s = M.MultiMap (Timestamp, PlayerId) (Event s) -- | Invariants about the time stamps in this data type: -- * committed <= pending <= current < future -- * The time is advanced with strictly ascending timestamps -- * For each player, events come in with strictly ascending timestamps -- * For each player, all events in pending or future are before the -- corresponding lastEvents entry. data Future s = Future { committed :: TState s, lastQuery :: Timestamp, lastEvents :: IM.IntMap Timestamp, pending :: EventQueue s, future :: EventQueue s, current :: TState s } initFuture :: s -> Int -> Future s initFuture s numPlayers = Future { committed = (0, s), lastQuery = 0, lastEvents = IM.fromList [(n, 0) | n <- [0 .. numPlayers - 1]], pending = M.empty, future = M.empty, current = (0, s) } -- Time handling. -- -- Move state forward in fixed animation rate steps, and get -- the timestamp as close to the given target as possible (but possibly stop short) timePassesBigStep :: StepFun s -> AnimationRate -> Timestamp -> TState s -> TState s timePassesBigStep step rate target (now, s) | now + rate <= target = timePassesBigStep step rate target (stepBy step rate (now, s)) | otherwise = (now, s) -- Move state forward in fixed animation rate steps, and get -- the timestamp as close to the given target as possible, and then do a final small step timePasses :: StepFun s -> AnimationRate -> Timestamp -> TState s -> TState s timePasses step rate target = stepTo step target . timePassesBigStep step rate target stepBy :: StepFun s -> Double -> TState s -> TState s stepBy step diff (now, s) = (now + diff, step diff s) stepTo :: StepFun s -> Timestamp -> TState s -> TState s stepTo step target (now, s) = (target, step (target - now) s) handleNextEvent :: StepFun s -> AnimationRate -> TEvent s -> TState s -> TState s handleNextEvent step rate (target, event) = second event . timePasses step rate target handleNextEvents :: StepFun s -> AnimationRate -> EventQueue s -> TState s -> TState s handleNextEvents step rate eq ts = foldl' (flip (handleNextEvent step rate)) ts $ map (\((t, _p), h) -> (t, h)) $ M.toList eq -- | This should be called shortly following 'currentTimePasses' currentState :: StepFun s -> AnimationRate -> Timestamp -> Future s -> s currentState step rate target f = snd $ timePasses step rate target (current f) -- | This should be called regularly, to keep the current state up to date, -- and to incorporate future events in it. currentTimePasses :: StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s currentTimePasses step rate target = advanceCurrentTime step rate target . advanceFuture step rate target -- | Take a new event into account, local or remote. -- Invariant: -- * The timestamp of the event is larger than the timestamp -- of any event added for this player (which is the timestamp for the player -- in `lastEvents`) addEvent :: StepFun s -> AnimationRate -> PlayerId -> Timestamp -> Maybe (Event s) -> Future s -> Future s -- A future event. addEvent step rate player now mbEvent f | now > lastQuery f = recordActivity step rate player now $ f {future = maybe id (M.insertR (now, player)) mbEvent $ future f} -- A past event, goes to pending events. Pending events need to be replayed. addEvent step rate player now mbEvent f = replayPending step rate $ recordActivity step rate player now $ f {pending = maybe id (M.insertR (now, player)) mbEvent $ pending f} -- | Updates the 'lastEvents' field, and possibly updates the commmitted state recordActivity :: StepFun s -> AnimationRate -> PlayerId -> Timestamp -> Future s -> Future s recordActivity step rate player now f = advanceCommitted step rate $ f {lastEvents = IM.insert player now $ lastEvents f} -- | Commits events from the pending queue that are past the commitTime advanceCommitted :: StepFun s -> AnimationRate -> Future s -> Future s advanceCommitted step rate f | M.null eventsToCommit = f -- do not bother | otherwise = f {committed = committed', pending = uncommited'} where commitTime' = minimum $ IM.elems $ lastEvents f canCommit t = t < commitTime' (eventsToCommit, uncommited') = M.spanAntitone (canCommit . fst) (pending f) committed' = handleNextEvents step rate eventsToCommit $ committed f -- | Throws away the current state, and recreates it from -- pending events. To be used when inserting a pending event. replayPending :: StepFun s -> AnimationRate -> Future s -> Future s replayPending step rate f = f {current = current'} where current' = timePassesBigStep step rate (lastQuery f) $ handleNextEvents step rate (pending f) $ committed f -- | Takes into account all future event that happen before the given 'Timestamp' -- Does not have to call 'replayPending', as we only append to the 'pending' queue. -- But does have to call 'advanceCommitted', as the newly added events might -- go directly to the committed state. advanceFuture :: StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s advanceFuture step rate target f | M.null toPerform = f | otherwise = advanceCommitted step rate $ f {current = current', pending = pending', future = future'} where hasHappened t = t <= target (toPerform, future') = M.spanAntitone (hasHappened . fst) (future f) pending' = pending f `M.union` toPerform current' = handleNextEvents step rate toPerform $ current f -- | Advances the current time (by big steps) advanceCurrentTime :: StepFun s -> AnimationRate -> Timestamp -> Future s -> Future s advanceCurrentTime step rate target f = f { current = timePassesBigStep step rate target $ current f, lastQuery = target } -- | Only for testing. currentStateDirect :: Future s -> (Timestamp, s) currentStateDirect = current -- | Only for testing. eqFuture :: Eq s => Future s -> Future s -> Bool eqFuture f1 f2 = ( current f1, lastEvents f1, M.keys (pending f1), M.keys (future f1), committed f1 ) == ( current f2, lastEvents f2, M.keys (pending f2), M.keys (future f2), committed f2 ) -- | Only for testing. printInternalState :: (s -> String) -> Future s -> IO () printInternalState showState f = do printf " Current: (%6.3f) %s\n" (fst (current f)) $ showState (snd (current f)) printf " Latest: %s\n" $ intercalate " " [printf "%d:%.3f" p t | (p, t) <- IM.toList (lastEvents f)] printf " Committed: (%6.3f) %s\n" (fst (committed f)) $ showState (snd (committed f))
google/codeworld
codeworld-prediction/src/CodeWorld/Prediction.hs
apache-2.0
8,940
0
14
1,922
2,079
1,092
987
152
1
import Data.Char import Data.List import qualified Data.Vector.Unboxed as U insert_word :: [[Char]] -> [Char] -> [[Char]] insert_word (a:tail) word | a==word = [(a)] ++ tail | otherwise = [(a)] ++ insert_word tail word insert_word _ w = [(w)] find_word :: [[Char]] -> [Char] -> Bool find_word (a:tail) word | a==word = True | otherwise = find_word tail word find_word [] word = False word_counter :: [[Char]] -> [Char] -> Integer word_counter list word = find_word_counter list word 0 find_word_counter :: [[Char]] -> [Char] -> Integer -> Integer find_word_counter (a:tail) word counter | a==word = find_word_counter tail word counter+1 | otherwise = find_word_counter tail word counter find_word_counter [] word counter = counter --count words from words table, ignore case with map count_words ((a):tail) dictionary = let dict = (insert_word dictionary (map toLower a)) in count_words tail dict count_words [] dictionary = dictionary --TRIM -- check if letter is in "special charater" group special_char letter | letter `elem` [',', '.', ':', '!', '?', ';'] = True | otherwise = False --trim from word special characters defined above trim_special word | special_char (last word) == True = trim_special (init word) | otherwise = word --trim special characters from words table trim_every_special ((a):tail) = [(trim_special a)] ++ trim_every_special tail trim_every_special [] = [] --word_to_lower :: [Char] -> [Char] word_to_lower word@(a:tail) = map toLower word -- converts "trim words from string" to ["trim", "words", "from", string"] --trim_words b = trim_every_special (words b) trim_words b = map word_to_lower (map trim_special (words b)) -- /TRIM dictionary_sum (word:tail) dict = if (find_word dict word)==False then [word] ++ dictionary_sum tail (dict++[word]) else dictionary_sum tail dict dictionary_sum [] dict = [] algebraic_string_sum string1 string2 = sort (dictionary_sum (trim_words string1 ++ trim_words string2) []) -- FIXIT -> Fractional elements string_vector (a:tail) string = [word_counter string a] ++ (string_vector tail string) string_vector [] string = [] -- absolute sum of vector elements get_vector_abs_sum (a:tail) = (abs a) + get_vector_abs_sum tail get_vector_abs_sum [] = 0 -- module of vector -> (sum of elements module) / vector length get_vector_module vector = (fromIntegral (get_vector_abs_sum vector)) / (fromIntegral (length vector)) -- curse of floating numbers isInt x = x == fromInteger (round x) --vector1 - vector2 vector_minus (a:tail) (b:tail2) = [a-b] ++ (vector_minus tail tail2) vector_minus [] [] = [] -- Vector * Scalar vector_times_scalar (a:tail) scalar = [ a * scalar ] ++ (vector_times_scalar tail scalar) vector_times_scalar [] scalar = [] --get_multipier_vector :: (Integral a, Fractional b) => [a] -> [a] -> [b] get_multipier_vector (a:tail) (b:tail2) = if (b/=0) then [ ceiling (fromIntegral a / fromIntegral b)] ++ get_multipier_vector tail tail2 else (get_multipier_vector tail tail2) get_multipier_vector [] [] = [0] -- returns (vector1 - x*vector2) linear_combination vector1 vector2 x = vector_minus vector1 (vector_times_scalar vector2 x) -- FOR get_x_factor FUNCTION --get_x :: Integral a => [a] -> [a] -> [a] -> a -> a get_x vector1@(v1:t1) vector2@(v2:t2) mul_vec@(a:tail) minimum | get_vector_module (linear_combination vector1 vector2 a)< get_vector_module (linear_combination vector1 vector2 minimum) = get_x vector1 vector2 tail a | otherwise = get_x vector1 vector2 tail minimum get_x (v1:t1) (v2:t2) [] minimum = minimum --get_x_factor :: (Fractional a, Integral a) => [a] -> [a] -> a get_x_factor [] [] = 0 get_x_factor vector1 vector2 = get_x vector1 vector2 mul_vec min where mul_vec = (get_multipier_vector vector1 vector2) min = mul_vec !! 0 --(vector_minus vector1 (vector_times_scalar vector2 (mul_vec !! 0))) --recipe -- get two strings: str1 str2 -- trim words from strings: trim_words -- create strings sum : algebraic_string_sum str1 str2 -- create string vector for str1 and str2: v1 = string_vector dict (trim_words str1) -- get_x_factor from v1 v2 : x = get_x_factor v1 v2 -- Podobienstwo = 1 - f(x)/f(0) podobienstwo string1 string2 = 1.0 - (get_vector_module (linear_combination v1 v2 x)) / (get_vector_module v1) where suma = (algebraic_string_sum string1 string2) -- longer-shorter for security reasons (for Integral x's) longer = if length string1>length string2 then string1 else string2 shorter = if length string1>length string2 then string2 else string1 v1 = string_vector suma (trim_words longer) v2 = string_vector suma (trim_words shorter) x = get_x_factor v1 v2 main :: IO() main = do putStrLn (show "Podaj dwa teksty") string1 <- getLine string2 <- getLine --readLn reads any type you want let suma = (algebraic_string_sum string1 string2) v1 = string_vector suma (trim_words string1) v2 = string_vector suma (trim_words string2) x = get_x_factor v1 v2 putStrLn (show "Requested data: ") putStrLn (show ("Algebraic, sorted sum of strings: " ++ show suma)) putStrLn (show (string1 ++ " <-- vector " ++ show v1)) putStrLn (show (string2 ++ " <-- vector " ++ show v2)) putStrLn (show ("Determined x factor : " ++ show x)) putStrLn (show ("For known value of x linear combination equals = " ++ show (linear_combination v1 v2 x))) putStrLn (show ("Calculated similarity : " ++ show ((podobienstwo string1 string2) * 100.0) ++ show "%"))
rybycy/HaskellStringSimilarity
projekt_extended.hs
apache-2.0
5,465
56
17
918
1,780
915
865
96
3
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Web.Twitter.Conduit.Request.Internal where import Control.Lens import Data.ByteString (ByteString) import qualified Data.ByteString.Char8 as S8 import Data.Proxy import Data.Text (Text) import qualified Data.Text.Encoding as T import Data.Time.Calendar (Day) import GHC.OverloadedLabels import GHC.TypeLits import qualified Network.HTTP.Types as HT data Param label t = label := t type EmptyParams = ('[] :: [Param Symbol *]) type HasParam (label :: Symbol) (paramType :: *) (params :: [Param Symbol *]) = ParamType label params ~ paramType type family ParamType (label :: Symbol) (params :: [Param Symbol *]) :: * where ParamType label ((label ':= paramType) ': ks) = paramType ParamType label ((label' ':= paramType') ': ks) = ParamType label ks type APIQuery = [APIQueryItem] type APIQueryItem = (ByteString, PV) data PV = PVInteger { unPVInteger :: Integer } | PVBool { unPVBool :: Bool } | PVString { unPVString :: Text } | PVIntegerArray { unPVIntegerArray :: [Integer] } | PVStringArray { unPVStringArray :: [Text] } | PVDay { unPVDay :: Day } deriving (Show, Eq) class Parameters req where type SupportParameters req :: [Param Symbol *] params :: Lens' req APIQuery class ParameterValue a where wrap :: a -> PV unwrap :: PV -> a instance ParameterValue Integer where wrap = PVInteger unwrap = unPVInteger instance ParameterValue Bool where wrap = PVBool unwrap = unPVBool instance ParameterValue Text where wrap = PVString unwrap = unPVString instance ParameterValue [Integer] where wrap = PVIntegerArray unwrap = unPVIntegerArray instance ParameterValue [Text] where wrap = PVStringArray unwrap = unPVStringArray instance ParameterValue Day where wrap = PVDay unwrap = unPVDay makeSimpleQuery :: APIQuery -> HT.SimpleQuery makeSimpleQuery = traversed . _2 %~ paramValueBS paramValueBS :: PV -> ByteString paramValueBS (PVInteger i) = S8.pack . show $ i paramValueBS (PVBool True) = "true" paramValueBS (PVBool False) = "false" paramValueBS (PVString txt) = T.encodeUtf8 txt paramValueBS (PVIntegerArray iarr) = S8.intercalate "," $ map (S8.pack . show) iarr paramValueBS (PVStringArray iarr) = S8.intercalate "," $ map T.encodeUtf8 iarr paramValueBS (PVDay day) = S8.pack . show $ day rawParam :: (Parameters p, ParameterValue a) => ByteString -- ^ key -> Lens' p (Maybe a) rawParam key = lens getter setter where getter = preview $ params . to (lookup key) . _Just . to unwrap setter = flip (over params . replace key) replace k (Just v) = ((k, wrap v):) . dropAssoc k replace k Nothing = dropAssoc k dropAssoc k = filter ((/= k) . fst) instance ( Parameters req , ParameterValue a , KnownSymbol label , HasParam label a (SupportParameters req) , Functor f , lens ~ ((Maybe a -> f (Maybe a)) -> req -> f req)) => IsLabel label lens where #if MIN_VERSION_base(4, 10, 0) fromLabel = rawParam key #else fromLabel _ = rawParam key #endif where key = S8.pack (symbolVal (Proxy :: Proxy label))
Javran/twitter-conduit
Web/Twitter/Conduit/Request/Internal.hs
bsd-2-clause
3,530
1
14
735
1,060
590
470
-1
-1
{-# LANGUAGE DeriveGeneric, DeriveDataTypeable, GeneralizedNewtypeDeriving #-} -- | Handling project configuration, types. -- module Distribution.Client.ProjectConfig.Types ( -- * Types for project config ProjectConfig(..), ProjectConfigBuildOnly(..), ProjectConfigShared(..), PackageConfig(..), -- * Resolving configuration SolverSettings(..), BuildTimeSettings(..), -- * Extra useful Monoids MapLast(..), MapMappend(..), ) where import Distribution.Client.Types ( RemoteRepo ) import Distribution.Client.Dependency.Types ( PreSolver ) import Distribution.Client.Targets ( UserConstraint ) import Distribution.Client.BuildReports.Types ( ReportLevel(..) ) import Distribution.Solver.Types.Settings import Distribution.Solver.Types.ConstraintSource import Distribution.Package ( PackageName, PackageId, UnitId, Dependency ) import Distribution.Version ( Version ) import Distribution.System ( Platform ) import Distribution.PackageDescription ( FlagAssignment, SourceRepo(..) ) import Distribution.Simple.Compiler ( Compiler, CompilerFlavor , OptimisationLevel(..), ProfDetailLevel, DebugInfoLevel(..) ) import Distribution.Simple.Setup ( Flag, AllowNewer(..), AllowOlder(..) ) import Distribution.Simple.InstallDirs ( PathTemplate ) import Distribution.Utils.NubList ( NubList ) import Distribution.Verbosity ( Verbosity ) import Data.Map (Map) import qualified Data.Map as Map import Distribution.Compat.Binary (Binary) import Distribution.Compat.Semigroup import GHC.Generics (Generic) ------------------------------- -- Project config types -- -- | This type corresponds directly to what can be written in the -- @cabal.project@ file. Other sources of configuration can also be injected -- into this type, such as the user-wide @~/.cabal/config@ file and the -- command line of @cabal configure@ or @cabal build@. -- -- Since it corresponds to the external project file it is an instance of -- 'Monoid' and all the fields can be empty. This also means there has to -- be a step where we resolve configuration. At a minimum resolving means -- applying defaults but it can also mean merging information from multiple -- sources. For example for package-specific configuration the project file -- can specify configuration that applies to all local packages, and then -- additional configuration for a specific package. -- -- Future directions: multiple profiles, conditionals. If we add these -- features then the gap between configuration as written in the config file -- and resolved settings we actually use will become even bigger. -- data ProjectConfig = ProjectConfig { -- | Packages in this project, including local dirs, local .cabal files -- local and remote tarballs. When these are file globs, they must -- match at least one package. projectPackages :: [String], -- | Like 'projectConfigPackageGlobs' but /optional/ in the sense that -- file globs are allowed to match nothing. The primary use case for -- this is to be able to say @optional-packages: */@ to automagically -- pick up deps that we unpack locally without erroring when -- there aren't any. projectPackagesOptional :: [String], -- | Packages in this project from remote source repositories. projectPackagesRepo :: [SourceRepo], -- | Packages in this project from hackage repositories. projectPackagesNamed :: [Dependency], -- See respective types for an explanation of what these -- values are about: projectConfigBuildOnly :: ProjectConfigBuildOnly, projectConfigShared :: ProjectConfigShared, -- | Configuration to be applied to *local* packages; i.e., -- any packages which are explicitly named in `cabal.project`. projectConfigLocalPackages :: PackageConfig, projectConfigSpecificPackage :: MapMappend PackageName PackageConfig } deriving (Eq, Show, Generic) -- | That part of the project configuration that only affects /how/ we build -- and not the /value/ of the things we build. This means this information -- does not need to be tracked for changes since it does not affect the -- outcome. -- data ProjectConfigBuildOnly = ProjectConfigBuildOnly { projectConfigVerbosity :: Flag Verbosity, projectConfigDryRun :: Flag Bool, projectConfigOnlyDeps :: Flag Bool, projectConfigSummaryFile :: NubList PathTemplate, projectConfigLogFile :: Flag PathTemplate, projectConfigBuildReports :: Flag ReportLevel, projectConfigReportPlanningFailure :: Flag Bool, projectConfigSymlinkBinDir :: Flag FilePath, projectConfigOneShot :: Flag Bool, projectConfigNumJobs :: Flag (Maybe Int), projectConfigKeepGoing :: Flag Bool, projectConfigOfflineMode :: Flag Bool, projectConfigKeepTempFiles :: Flag Bool, projectConfigHttpTransport :: Flag String, projectConfigIgnoreExpiry :: Flag Bool, projectConfigCacheDir :: Flag FilePath, projectConfigLogsDir :: Flag FilePath } deriving (Eq, Show, Generic) -- | Project configuration that is shared between all packages in the project. -- In particular this includes configuration that affects the solver. -- data ProjectConfigShared = ProjectConfigShared { projectConfigHcFlavor :: Flag CompilerFlavor, projectConfigHcPath :: Flag FilePath, projectConfigHcPkg :: Flag FilePath, projectConfigHaddockIndex :: Flag PathTemplate, -- Things that only make sense for manual mode, not --local mode -- too much control! --projectConfigUserInstall :: Flag Bool, --projectConfigInstallDirs :: InstallDirs (Flag PathTemplate), --TODO: [required eventually] decide what to do with InstallDirs -- currently we don't allow it to be specified in the config file --projectConfigPackageDBs :: [Maybe PackageDB], -- configuration used both by the solver and other phases projectConfigRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers. projectConfigLocalRepos :: NubList FilePath, -- solver configuration projectConfigConstraints :: [(UserConstraint, ConstraintSource)], projectConfigPreferences :: [Dependency], projectConfigCabalVersion :: Flag Version, --TODO: [required eventually] unused projectConfigSolver :: Flag PreSolver, projectConfigAllowOlder :: Maybe AllowOlder, projectConfigAllowNewer :: Maybe AllowNewer, projectConfigMaxBackjumps :: Flag Int, projectConfigReorderGoals :: Flag ReorderGoals, projectConfigCountConflicts :: Flag CountConflicts, projectConfigStrongFlags :: Flag StrongFlags -- More things that only make sense for manual mode, not --local mode -- too much control! --projectConfigIndependentGoals :: Flag Bool, --projectConfigShadowPkgs :: Flag Bool, --projectConfigReinstall :: Flag Bool, --projectConfigAvoidReinstalls :: Flag Bool, --projectConfigOverrideReinstall :: Flag Bool, --projectConfigUpgradeDeps :: Flag Bool } deriving (Eq, Show, Generic) -- | Project configuration that is specific to each package, that is where we -- can in principle have different values for different packages in the same -- project. -- data PackageConfig = PackageConfig { packageConfigProgramPaths :: MapLast String FilePath, packageConfigProgramArgs :: MapMappend String [String], packageConfigProgramPathExtra :: NubList FilePath, packageConfigFlagAssignment :: FlagAssignment, packageConfigVanillaLib :: Flag Bool, packageConfigSharedLib :: Flag Bool, packageConfigDynExe :: Flag Bool, packageConfigProf :: Flag Bool, --TODO: [code cleanup] sort out packageConfigProfLib :: Flag Bool, -- this duplication packageConfigProfExe :: Flag Bool, -- and consistency packageConfigProfDetail :: Flag ProfDetailLevel, packageConfigProfLibDetail :: Flag ProfDetailLevel, packageConfigConfigureArgs :: [String], packageConfigOptimization :: Flag OptimisationLevel, packageConfigProgPrefix :: Flag PathTemplate, packageConfigProgSuffix :: Flag PathTemplate, packageConfigExtraLibDirs :: [FilePath], packageConfigExtraFrameworkDirs :: [FilePath], packageConfigExtraIncludeDirs :: [FilePath], packageConfigGHCiLib :: Flag Bool, packageConfigSplitObjs :: Flag Bool, packageConfigStripExes :: Flag Bool, packageConfigStripLibs :: Flag Bool, packageConfigTests :: Flag Bool, packageConfigBenchmarks :: Flag Bool, packageConfigCoverage :: Flag Bool, packageConfigRelocatable :: Flag Bool, packageConfigDebugInfo :: Flag DebugInfoLevel, packageConfigRunTests :: Flag Bool, --TODO: [required eventually] use this packageConfigDocumentation :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockHoogle :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockHtml :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockHtmlLocation :: Flag String, --TODO: [required eventually] use this packageConfigHaddockExecutables :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockTestSuites :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockBenchmarks :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockInternal :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockCss :: Flag FilePath, --TODO: [required eventually] use this packageConfigHaddockHscolour :: Flag Bool, --TODO: [required eventually] use this packageConfigHaddockHscolourCss :: Flag FilePath, --TODO: [required eventually] use this packageConfigHaddockContents :: Flag PathTemplate --TODO: [required eventually] use this } deriving (Eq, Show, Generic) instance Binary ProjectConfig instance Binary ProjectConfigBuildOnly instance Binary ProjectConfigShared instance Binary PackageConfig -- | Newtype wrapper for 'Map' that provides a 'Monoid' instance that takes -- the last value rather than the first value for overlapping keys. newtype MapLast k v = MapLast { getMapLast :: Map k v } deriving (Eq, Show, Functor, Generic, Binary) instance Ord k => Monoid (MapLast k v) where mempty = MapLast Map.empty mappend = (<>) instance Ord k => Semigroup (MapLast k v) where MapLast a <> MapLast b = MapLast (flip Map.union a b) -- rather than Map.union which is the normal Map monoid instance -- | Newtype wrapper for 'Map' that provides a 'Monoid' instance that -- 'mappend's values of overlapping keys rather than taking the first. newtype MapMappend k v = MapMappend { getMapMappend :: Map k v } deriving (Eq, Show, Functor, Generic, Binary) instance (Semigroup v, Ord k) => Monoid (MapMappend k v) where mempty = MapMappend Map.empty mappend = (<>) instance (Semigroup v, Ord k) => Semigroup (MapMappend k v) where MapMappend a <> MapMappend b = MapMappend (Map.unionWith (<>) a b) -- rather than Map.union which is the normal Map monoid instance instance Monoid ProjectConfig where mempty = gmempty mappend = (<>) instance Semigroup ProjectConfig where (<>) = gmappend instance Monoid ProjectConfigBuildOnly where mempty = gmempty mappend = (<>) instance Semigroup ProjectConfigBuildOnly where (<>) = gmappend instance Monoid ProjectConfigShared where mempty = gmempty mappend = (<>) instance Semigroup ProjectConfigShared where (<>) = gmappend instance Monoid PackageConfig where mempty = gmempty mappend = (<>) instance Semigroup PackageConfig where (<>) = gmappend ---------------------------------------- -- Resolving configuration to settings -- -- | Resolved configuration for the solver. The idea is that this is easier to -- use than the raw configuration because in the raw configuration everything -- is optional (monoidial). In the 'BuildTimeSettings' every field is filled -- in, if only with the defaults. -- -- Use 'resolveSolverSettings' to make one from the project config (by -- applying defaults etc). -- data SolverSettings = SolverSettings { solverSettingRemoteRepos :: [RemoteRepo], -- ^ Available Hackage servers. solverSettingLocalRepos :: [FilePath], solverSettingConstraints :: [(UserConstraint, ConstraintSource)], solverSettingPreferences :: [Dependency], solverSettingFlagAssignment :: FlagAssignment, -- ^ For all local packages solverSettingFlagAssignments :: Map PackageName FlagAssignment, solverSettingCabalVersion :: Maybe Version, --TODO: [required eventually] unused solverSettingSolver :: PreSolver, solverSettingAllowOlder :: AllowOlder, solverSettingAllowNewer :: AllowNewer, solverSettingMaxBackjumps :: Maybe Int, solverSettingReorderGoals :: ReorderGoals, solverSettingCountConflicts :: CountConflicts, solverSettingStrongFlags :: StrongFlags -- Things that only make sense for manual mode, not --local mode -- too much control! --solverSettingIndependentGoals :: Bool, --solverSettingShadowPkgs :: Bool, --solverSettingReinstall :: Bool, --solverSettingAvoidReinstalls :: Bool, --solverSettingOverrideReinstall :: Bool, --solverSettingUpgradeDeps :: Bool } deriving (Eq, Show, Generic) instance Binary SolverSettings -- | Resolved configuration for things that affect how we build and not the -- value of the things we build. The idea is that this is easier to use than -- the raw configuration because in the raw configuration everything is -- optional (monoidial). In the 'BuildTimeSettings' every field is filled in, -- if only with the defaults. -- -- Use 'resolveBuildTimeSettings' to make one from the project config (by -- applying defaults etc). -- data BuildTimeSettings = BuildTimeSettings { buildSettingDryRun :: Bool, buildSettingOnlyDeps :: Bool, buildSettingSummaryFile :: [PathTemplate], buildSettingLogFile :: Maybe (Compiler -> Platform -> PackageId -> UnitId -> FilePath), buildSettingLogVerbosity :: Verbosity, buildSettingBuildReports :: ReportLevel, buildSettingReportPlanningFailure :: Bool, buildSettingSymlinkBinDir :: [FilePath], buildSettingOneShot :: Bool, buildSettingNumJobs :: Int, buildSettingKeepGoing :: Bool, buildSettingOfflineMode :: Bool, buildSettingKeepTempFiles :: Bool, buildSettingRemoteRepos :: [RemoteRepo], buildSettingLocalRepos :: [FilePath], buildSettingCacheDir :: FilePath, buildSettingHttpTransport :: Maybe String, buildSettingIgnoreExpiry :: Bool }
sopvop/cabal
cabal-install/Distribution/Client/ProjectConfig/Types.hs
bsd-3-clause
16,126
0
14
4,155
2,047
1,252
795
216
0