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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
main = print hello
-- test that layout has not been screwed up
hello = "こんにちは 世界"
|
urbanslug/ghc
|
testsuite/tests/parser/unicode/T1744.hs
|
bsd-3-clause
| 102
| 0
| 5
| 20
| 15
| 8
| 7
| 2
| 1
|
module Network.JSONApi.ErrorSpec where
import qualified Data.Aeson as AE
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Default (def)
import Data.Maybe
import Network.JSONApi
import Prelude hiding (id)
import TestHelpers (prettyEncode)
import Test.Hspec
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "Defaults" $ do
it "provides defaults" $
let expectedDefault = Error
{ id = Nothing
, links = Nothing
, status = Nothing
, code = Nothing
, title = Nothing
, detail = Nothing
, source = Nothing
, meta = Nothing
}
in (def::Error Int) `shouldBe` expectedDefault
describe "JSON serialization" $
it "provides ToJSON/FromJSON instances" $ do
let testError = (def::Error Int)
let encJson = BS.unpack . prettyEncode $ testError
let decJson = AE.decode (BS.pack encJson) :: Maybe (Error Int)
isJust decJson `shouldBe` True
{- putStrLn encJson -}
{- putStrLn $ show . fromJust $ decJson -}
|
toddmohney/json-api
|
test/Network/JSONApi/ErrorSpec.hs
|
mit
| 1,096
| 0
| 16
| 325
| 293
| 164
| 129
| 31
| 1
|
{-
This is my xmonad configuration file.
There are many like it, but this one is mine.
If you want to customize this file, the easiest workflow goes
something like this:
1. Make a small change.
2. Hit "super-q", which recompiles and restarts xmonad
3. If there is an error, undo your change and hit "super-q" again to
get to a stable place again.
4. Repeat
Author: David Brewer
Repository: https://github.com/davidbrewer/xmonad-ubuntu-conf
-}
import XMonad
import XMonad.Hooks.SetWMName
import XMonad.Layout.Grid
import XMonad.Layout.ResizableTile
import XMonad.Layout.IM
import XMonad.Layout.ThreeColumns
import XMonad.Layout.NoBorders
import XMonad.Layout.Circle
import XMonad.Layout.PerWorkspace (onWorkspace)
import XMonad.Layout.Fullscreen
import XMonad.Util.EZConfig
import XMonad.Util.Run
import XMonad.Hooks.DynamicLog
import XMonad.Actions.Plane
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.UrgencyHook
import qualified XMonad.StackSet as W
import qualified Data.Map as M
import Data.Ratio ((%))
{-
Xmonad configuration variables. These settings control some of the
simpler parts of xmonad's behavior and are straightforward to tweak.
-}
myModMask = mod4Mask -- changes the mod key to "super"
myFocusedBorderColor = "#ff0000" -- color of focused border
myNormalBorderColor = "#cccccc" -- color of inactive border
myBorderWidth = 3 -- width of border around windows
myTerminal = "terminator" -- which terminal software to use
myIMRosterTitle = "Contact List" -- title of roster on IM workspace
{-
Xmobar configuration variables. These settings control the appearance
of text which xmonad is sending to xmobar via the DynamicLog hook.
-}
myTitleColor = "#eeeeee" -- color of window title
myTitleLength = 80 -- truncate window title to this length
myCurrentWSColor = "#e6744c" -- color of active workspace
myVisibleWSColor = "#c185a7" -- color of inactive workspace
myUrgentWSColor = "#cc0000" -- color of workspace with 'urgent' window
myCurrentWSLeft = "[" -- wrap active workspace with these
myCurrentWSRight = "]"
myVisibleWSLeft = "(" -- wrap inactive workspace with these
myVisibleWSRight = ")"
myUrgentWSLeft = "{" -- wrap urgent workspace with these
myUrgentWSRight = "}"
{-
Workspace configuration. Here you can change the names of your
workspaces. Note that they are organized in a grid corresponding
to the layout of the number pad.
I would recommend sticking with relatively brief workspace names
because they are displayed in the xmobar status bar, where space
can get tight. Also, the workspace labels are referred to elsewhere
in the configuration file, so when you change a label you will have
to find places which refer to it and make a change there as well.
This central organizational concept of this configuration is that
the workspaces correspond to keys on the number pad, and that they
are organized in a grid which also matches the layout of the number pad.
So, I don't recommend changing the number of workspaces unless you are
prepared to delve into the workspace navigation keybindings section
as well.
-}
myWorkspaces =
[
"7:Chat", "8:Dbg", "9:Pix",
"4:Docs", "5:Dev", "6:Web",
"1:Term", "2:Hub", "3:Mail",
"0:VM", "Extr1", "Extr2"
]
startupWorkspace = "5:Dev" -- which workspace do you want to be on after launch?
{-
Layout configuration. In this section we identify which xmonad
layouts we want to use. I have defined a list of default
layouts which are applied on every workspace, as well as
special layouts which get applied to specific workspaces.
Note that all layouts are wrapped within "avoidStruts". What this does
is make the layouts avoid the status bar area at the top of the screen.
Without this, they would overlap the bar. You can toggle this behavior
by hitting "super-b" (bound to ToggleStruts in the keyboard bindings
in the next section).
-}
-- Define group of default layouts used on most screens, in the
-- order they will appear.
-- "smartBorders" modifier makes it so the borders on windows only
-- appear if there is more than one visible window.
-- "avoidStruts" modifier makes it so that the layout provides
-- space for the status bar at the top of the screen.
defaultLayouts = smartBorders(avoidStruts(
-- ResizableTall layout has a large master window on the left,
-- and remaining windows tile on the right. By default each area
-- takes up half the screen, but you can resize using "super-h" and
-- "super-l".
ResizableTall 1 (3/100) (1/2) []
-- Mirrored variation of ResizableTall. In this layout, the large
-- master window is at the top, and remaining windows tile at the
-- bottom of the screen. Can be resized as described above.
||| Mirror (ResizableTall 1 (3/100) (1/2) [])
-- Full layout makes every window full screen. When you toggle the
-- active window, it will bring the active window to the front.
||| noBorders Full
-- Grid layout tries to equally distribute windows in the available
-- space, increasing the number of columns and rows as necessary.
-- Master window is at top left.
||| Grid
-- ThreeColMid layout puts the large master window in the center
-- of the screen. As configured below, by default it takes of 3/4 of
-- the available space. Remaining windows tile to both the left and
-- right of the master window. You can resize using "super-h" and
-- "super-l".
||| ThreeColMid 1 (3/100) (3/4)
-- Circle layout places the master window in the center of the screen.
-- Remaining windows appear in a circle around it
||| Circle))
-- Here we define some layouts which will be assigned to specific
-- workspaces based on the functionality of that workspace.
-- The chat layout uses the "IM" layout. We have a roster which takes
-- up 1/8 of the screen vertically, and the remaining space contains
-- chat windows which are tiled using the grid layout. The roster is
-- identified using the myIMRosterTitle variable, and by default is
-- configured for Empathy, so if you're using something else you
-- will want to modify that variable.
chatLayout = avoidStruts(withIM (1%7) (Title myIMRosterTitle) Grid)
-- The GIMP layout uses the ThreeColMid layout. The traditional GIMP
-- floating panels approach is a bit of a challenge to handle with xmonad;
-- I find the best solution is to make the image you are working on the
-- master area, and then use this ThreeColMid layout to make the panels
-- tile to the left and right of the image. If you use GIMP 2.8, you
-- can use single-window mode and avoid this issue.
gimpLayout = smartBorders(avoidStruts(ThreeColMid 1 (3/100) (3/4)))
-- Here we combine our default layouts with our specific, workspace-locked
-- layouts.
myLayouts =
onWorkspace "7:Chat" chatLayout
$ onWorkspace "9:Pix" gimpLayout
$ defaultLayouts
{-
Custom keybindings. In this section we define a list of relatively
straightforward keybindings. This would be the clearest place to
add your own keybindings, or change the keys we have defined
for certain functions.
It can be difficult to find a good list of keycodes for use
in xmonad. I have found this page useful -- just look
for entries beginning with "xK":
http://xmonad.org/xmonad-docs/xmonad/doc-index-X.html
Note that in the example below, the last three entries refer
to nonstandard keys which do not have names assigned by
xmonad. That's because they are the volume and mute keys
on my laptop, a Lenovo W520.
If you have special keys on your keyboard which you
want to bind to specific actions, you can use the "xev"
command-line tool to determine the code for a specific key.
Launch the command, then type the key in question and watch
the output.
-}
myKeyBindings =
[
((myModMask, xK_b), sendMessage ToggleStruts)
, ((myModMask, xK_a), sendMessage MirrorShrink)
, ((myModMask, xK_z), sendMessage MirrorExpand)
, ((myModMask, xK_p), spawn "synapse")
, ((myModMask, xK_u), focusUrgent)
, ((0, 0x1008FF12), spawn "amixer -q set Master toggle")
, ((0, 0x1008FF11), spawn "amixer -q set Master 10%-")
, ((0, 0x1008FF13), spawn "amixer -q set Master 10%+")
]
{-
Management hooks. You can use management hooks to enforce certain
behaviors when specific programs or windows are launched. This is
useful if you want certain windows to not be managed by xmonad,
or sent to a specific workspace, or otherwise handled in a special
way.
Each entry within the list of hooks defines a way to identify a
window (before the arrow), and then how that window should be treated
(after the arrow).
To figure out to identify your window, you will need to use a
command-line tool called "xprop". When you run xprop, your cursor
will temporarily change to crosshairs; click on the window you
want to identify. In the output that is printed in your terminal,
look for a couple of things:
- WM_CLASS(STRING): values in this list of strings can be compared
to "className" to match windows.
- WM_NAME(STRING): this value can be compared to "resource" to match
windows.
The className values tend to be generic, and might match any window or
dialog owned by a particular program. The resource values tend to be
more specific, and will be different for every dialog. Sometimes you
might want to compare both className and resource, to make sure you
are matching only a particular window which belongs to a specific
program.
Once you've pinpointed the window you want to manipulate, here are
a few examples of things you might do with that window:
- doIgnore: this tells xmonad to completely ignore the window. It will
not be tiled or floated. Useful for things like launchers and
trays.
- doFloat: this tells xmonad to float the window rather than tiling
it. Handy for things that pop up, take some input, and then go away,
such as dialogs, calculators, and so on.
- doF (W.shift "Workspace"): this tells xmonad that when this program
is launched it should be sent to a specific workspace. Useful
for keeping specific tasks on specific workspaces. In the example
below I have specific workspaces for chat, development, and
editing images.
-}
myManagementHooks :: [ManageHook]
myManagementHooks = [
resource =? "synapse" --> doIgnore
, resource =? "stalonetray" --> doIgnore
, className =? "rdesktop" --> doFloat
, (className =? "Komodo IDE") --> doF (W.shift "5:Dev")
, (className =? "Komodo IDE" <&&> resource =? "Komodo_find2") --> doFloat
, (className =? "Komodo IDE" <&&> resource =? "Komodo_gotofile") --> doFloat
, (className =? "Komodo IDE" <&&> resource =? "Toplevel") --> doFloat
, (className =? "Empathy") --> doF (W.shift "7:Chat")
, (className =? "Pidgin") --> doF (W.shift "7:Chat")
, (className =? "Gimp-2.8") --> doF (W.shift "9:Pix")
]
{-
Workspace navigation keybindings. This is probably the part of the
configuration I have spent the most time messing with, but understand
the least. Be very careful if messing with this section.
-}
-- We define two lists of keycodes for use in the rest of the
-- keyboard configuration. The first is the list of numpad keys,
-- in the order they occur on the keyboard (left to right and
-- top to bottom). The second is the list of number keys, in an
-- order corresponding to the numpad. We will use these to
-- make workspace navigation commands work the same whether you
-- use the numpad or the top-row number keys. And, we also
-- use them to figure out where to go when the user
-- uses the arrow keys.
numPadKeys =
[
xK_KP_Home, xK_KP_Up, xK_KP_Page_Up
, xK_KP_Left, xK_KP_Begin,xK_KP_Right
, xK_KP_End, xK_KP_Down, xK_KP_Page_Down
, xK_KP_Insert, xK_KP_Delete, xK_KP_Enter
]
numKeys =
[
xK_7, xK_8, xK_9
, xK_4, xK_5, xK_6
, xK_1, xK_2, xK_3
, xK_0, xK_minus, xK_equal
]
-- Here, some magic occurs that I once grokked but has since
-- fallen out of my head. Essentially what is happening is
-- that we are telling xmonad how to navigate workspaces,
-- how to send windows to different workspaces,
-- and what keys to use to change which monitor is focused.
myKeys = myKeyBindings ++
[
((m .|. myModMask, k), windows $ f i)
| (i, k) <- zip myWorkspaces numPadKeys
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]
] ++
[
((m .|. myModMask, k), windows $ f i)
| (i, k) <- zip myWorkspaces numKeys
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]
] ++
M.toList (planeKeys myModMask (Lines 4) Finite) ++
[
((m .|. myModMask, key), screenWorkspace sc
>>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [1,0,2]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]
]
{-
Here we actually stitch together all the configuration settings
and run xmonad. We also spawn an instance of xmobar and pipe
content into it via the logHook..
-}
main = do
xmproc <- spawnPipe "xmobar ~/.xmonad/xmobarrc"
xmonad $ withUrgencyHook NoUrgencyHook $ defaultConfig {
focusedBorderColor = myFocusedBorderColor
, normalBorderColor = myNormalBorderColor
, terminal = myTerminal
, borderWidth = myBorderWidth
, layoutHook = myLayouts
, workspaces = myWorkspaces
, modMask = myModMask
, handleEventHook = fullscreenEventHook
, startupHook = do
setWMName "LG3D"
windows $ W.greedyView startupWorkspace
spawn "~/.xmonad/startup-hook"
, manageHook = manageHook defaultConfig
<+> composeAll myManagementHooks
<+> manageDocks
, logHook = dynamicLogWithPP $ xmobarPP {
ppOutput = hPutStrLn xmproc
, ppTitle = xmobarColor myTitleColor "" . shorten myTitleLength
, ppCurrent = xmobarColor myCurrentWSColor ""
. wrap myCurrentWSLeft myCurrentWSRight
, ppVisible = xmobarColor myVisibleWSColor ""
. wrap myVisibleWSLeft myVisibleWSRight
, ppUrgent = xmobarColor myUrgentWSColor ""
. wrap myUrgentWSLeft myUrgentWSRight
}
}
`additionalKeys` myKeys
|
status203/.xmonad
|
xmonad.hs
|
mit
| 14,229
| 0
| 18
| 2,945
| 1,535
| 914
| 621
| 135
| 1
|
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE OverloadedStrings #-}
module Bond.Util
( sepBy
, sepEndBy
, sepBeginBy
, optional
, angles
, brackets
, braces
, parens
, between
) where
import Data.Monoid
import Data.String (IsString)
import Prelude
sepEndBy :: (Monoid a, Eq a)
=> a -> (t -> a) -> [t] -> a
sepEndBy _ _ [] = mempty
sepEndBy s f (x:xs)
| next == mempty = rest
| otherwise = next <> s <> rest
where
next = f x
rest = sepEndBy s f xs
sepBeginBy :: (Monoid a, Eq a)
=> a -> (t -> a) -> [t] -> a
sepBeginBy _ _ [] = mempty
sepBeginBy s f (x:xs)
| next == mempty = rest
| otherwise = s <> next <> rest
where
next = f x
rest = sepBeginBy s f xs
sepBy :: (Monoid a, Eq a)
=> a -> (t -> a) -> [t] -> a
sepBy _ _ [] = mempty
sepBy s f (x:xs)
| null xs = next
| next == mempty = rest
| otherwise = next <> sepBeginBy s f xs
where
next = f x
rest = sepBy s f xs
optional :: (Monoid m) => (a -> m) -> Maybe a -> m
optional = maybe mempty
between :: (Monoid a, Eq a) => a -> a -> a -> a
between l r m
| m == mempty = mempty
| otherwise = l <> m <> r
angles, brackets, braces, parens
:: (Monoid a, IsString a, Eq a)
=> a -> a
angles m = between "<" ">" m
brackets m = between "[" "]" m
braces m = between "{" "}" m
parens m = between "(" ")" m
|
innovimax/bond
|
compiler/Bond/Util.hs
|
mit
| 1,570
| 0
| 9
| 515
| 650
| 338
| 312
| 52
| 1
|
-- | Events for Caramia.
--
-- At the moment, this is just a thin layer of abstraction over the SDL2
-- library.
--
{-# LANGUAGE LambdaCase #-}
module Caramia.Events
(
-- * Getting events.
getEvents
, SDL.Event(..) )
where
import Caramia.Context
import Caramia.Internal.Error
import Graphics.UI.SDL
import qualified Graphics.UI.SDL as SDL
import Graphics.Rendering.OpenGL.Raw.Core32
import Foreign.Marshal.Array
import Data.Monoid
import Data.Foldable
import Control.Applicative
import Control.Monad
-- | Gets all the events that have happened since the last time it was called
-- or after the initialization of SDL2.
getEvents :: IO [SDL.Event]
getEvents = do
_ <- currentContextID
pumpEvents
(events', num_events) <- allocaArray 200 $ \event_ptr -> do
result <- fromIntegral <$>
peepEvents event_ptr 200
SDL.eventActionGetEvent
SDL.eventTypeFirstEvent
SDL.eventTypeLastEvent
when (result == -1) throwSDLError
(,) <$> peekArray result event_ptr <*> return result
events <- handleOurEvents events'
if num_events == 200
then do more_events <- getEvents
return $ events <> more_events
else return events
-- | Handle some events ourselves that we don't expect the user to handle.
--
-- Right now the result is always the same as input though; we only want to
-- know if some special events happen.
handleOurEvents :: [SDL.Event] -> IO [SDL.Event]
handleOurEvents events = return events <* (for_ events $ \case
WindowEvent { windowEventEvent = wevent
, windowEventData1 = w
, windowEventData2 = h } |
wevent == windowEventResized ->
glViewport 0 0 (fromIntegral w) (fromIntegral h)
_ -> return ())
|
Noeda/caramia-sdl2
|
src/Caramia/Events.hs
|
mit
| 1,858
| 0
| 15
| 498
| 377
| 205
| 172
| 40
| 2
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE DeriveGeneric #-}
module Models.FeaturedComic (FeaturedComic(..)) where
import BasicPrelude
import Data.Aeson (FromJSON(..), ToJSON(..))
import GHC.Generics (Generic)
import Models.Ids (ComicId)
import Models.Image (Image)
data FeaturedComic = FeaturedComic
{ id :: ComicId
, name :: Text
, thumbnail :: Image
} deriving (Show, Generic)
instance FromJSON FeaturedComic
instance ToJSON FeaturedComic
|
nicolashery/example-marvel-haskell
|
Models/FeaturedComic.hs
|
mit
| 461
| 0
| 8
| 67
| 123
| 75
| 48
| 15
| 0
|
module Roogle where
import Roogle.Types
import Roogle.Scope
import Roogle.Document
import System.Environment
import Control.Monad.IO.Class
import Data.Char
import Text.Regex
--- should have Scope -> Doc instead of [Code] -> Doc
--- desireable: [Code] -> Scope -> Doc, Code -> Scope -> Doc
extractTypeSignature :: String -> String -> Maybe String
extractTypeSignature ptn str = case typeSignatureMatch ptn str of
Just v -> Just $ toDoc v
Nothing -> Nothing
typeSignatureMatch :: String -> Code -> Maybe String
typeSignatureMatch ptn str = case matchRegexAll (mkRegex ptn) str of
Just (_, _, v, _) -> Just v
Nothing -> Nothing
compactMaybe :: [Maybe a] -> [a]
compactMaybe [] = []
compactMaybe (x:xs) = case x of
Just v -> [v] ++ compactMaybe xs
Nothing -> compactMaybe xs
extractTypeSignatures :: String -> [Code] -> Doc
extractTypeSignatures ptn strs = compactMaybe (map (\x -> (extractTypeSignature ptn x)) strs)
extractTypeSignatureWithSpecifiedPattern :: String -> (String -> Maybe String)
extractTypeSignatureWithSpecifiedPattern = extractTypeSignature
typeSignaturePattern1 :: String
typeSignaturePattern1 = "typesig "
|
Azabuhs/Roogle
|
src/Roogle.hs
|
mit
| 1,235
| 0
| 11
| 271
| 335
| 177
| 158
| 27
| 2
|
-----------------------------------------------------------------------------
--
-- Module : PSCi
-- Copyright : (c) 2013-15 Phil Freeman, (c) 2014-15 Gary Burgess
-- License : MIT (http://opensource.org/licenses/MIT)
--
-- Maintainer : Phil Freeman <paf31@cantab.net>
-- Stability : experimental
-- Portability :
--
-- |
-- PureScript Compiler Interactive.
--
-----------------------------------------------------------------------------
{-# LANGUAGE DoAndIfThenElse #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
module PSCi where
import Prelude ()
import Prelude.Compat
import Data.Foldable (traverse_)
import Data.List (intercalate, nub, sort)
import Data.Tuple (swap)
import Data.Version (showVersion)
import qualified Data.Map as M
import Control.Arrow (first)
import Control.Monad
import Control.Monad.Error.Class (MonadError(..))
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except (ExceptT(), runExceptT)
import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT)
import Control.Monad.Trans.State.Strict
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Writer.Strict (Writer(), runWriter)
import Options.Applicative as Opts
import System.Console.Haskeline
import System.Directory (doesFileExist, findExecutable, getHomeDirectory, getCurrentDirectory)
import System.Exit
import System.FilePath (pathSeparator, (</>), isPathSeparator)
import System.FilePath.Glob (glob)
import System.Process (readProcessWithExitCode)
import System.IO.Error (tryIOError)
import qualified Language.PureScript as P
import qualified Language.PureScript.Names as N
import qualified Paths_purescript as Paths
import qualified Directive as D
import Completion (completion)
import IO (mkdirp)
import Parser (parseCommand)
import Types
-- | The name of the PSCI support module
supportModuleName :: P.ModuleName
supportModuleName = P.ModuleName [P.ProperName "$PSCI", P.ProperName "Support"]
-- | Support module, contains code to evaluate terms
supportModule :: P.Module
supportModule =
case P.parseModulesFromFiles id [("", code)] of
Right [(_, P.Module ss cs _ ds exps)] -> P.Module ss cs supportModuleName ds exps
_ -> P.internalError "Support module could not be parsed"
where
code :: String
code = unlines
[ "module S where"
, ""
, "import Prelude"
, "import Control.Monad.Eff"
, "import Control.Monad.Eff.Console"
, "import Control.Monad.Eff.Unsafe"
, ""
, "class Eval a where"
, " eval :: a -> Eff (console :: CONSOLE) Unit"
, ""
, "instance evalShow :: (Show a) => Eval a where"
, " eval = print"
, ""
, "instance evalEff :: (Eval a) => Eval (Eff eff a) where"
, " eval x = unsafeInterleaveEff x >>= eval"
]
-- File helpers
onFirstFileMatching :: Monad m => (b -> m (Maybe a)) -> [b] -> m (Maybe a)
onFirstFileMatching f pathVariants = runMaybeT . msum $ map (MaybeT . f) pathVariants
-- |
-- Locates the node executable.
-- Checks for either @nodejs@ or @node@.
--
findNodeProcess :: IO (Maybe String)
findNodeProcess = onFirstFileMatching findExecutable names
where names = ["nodejs", "node"]
-- |
-- Grabs the filename where the history is stored.
--
getHistoryFilename :: IO FilePath
getHistoryFilename = do
home <- getHomeDirectory
let filename = home </> ".purescript" </> "psci_history"
mkdirp filename
return filename
-- |
-- Loads a file for use with imports.
--
loadModule :: FilePath -> IO (Either String [P.Module])
loadModule filename = do
content <- readFile filename
return $ either (Left . P.prettyPrintMultipleErrors False) (Right . map snd) $ P.parseModulesFromFiles id [(filename, content)]
-- |
-- Load all modules.
--
loadAllModules :: [FilePath] -> IO (Either P.MultipleErrors [(Either P.RebuildPolicy FilePath, P.Module)])
loadAllModules files = do
filesAndContent <- forM files $ \filename -> do
content <- readFile filename
return (Right filename, content)
return $ P.parseModulesFromFiles (either (const "") id) filesAndContent
-- |
-- Load all modules, updating the application state
--
loadAllImportedModules :: PSCI ()
loadAllImportedModules = do
files <- PSCI . lift $ fmap psciImportedFilenames get
modulesOrFirstError <- psciIO $ loadAllModules files
case modulesOrFirstError of
Left errs -> printErrors errs
Right modules -> PSCI . lift . modify $ \st -> st { psciLoadedModules = modules }
-- |
-- Expands tilde in path.
--
expandTilde :: FilePath -> IO FilePath
expandTilde ('~':p:rest) | isPathSeparator p = (</> rest) <$> getHomeDirectory
expandTilde p = return p
-- Messages
-- |
-- The help message.
--
helpMessage :: String
helpMessage = "The following commands are available:\n\n " ++
intercalate "\n " (map line D.help) ++
"\n\n" ++ extraHelp
where
line :: (Directive, String, String) -> String
line (dir, arg, desc) =
let cmd = ':' : D.stringFor dir
in unwords [ cmd
, replicate (11 - length cmd) ' '
, arg
, replicate (11 - length arg) ' '
, desc
]
extraHelp =
"Further information is available on the PureScript wiki:\n" ++
" --> https://github.com/purescript/purescript/wiki/psci"
-- |
-- The welcome prologue.
--
prologueMessage :: String
prologueMessage = intercalate "\n"
[ " ____ ____ _ _ "
, "| _ \\ _ _ _ __ ___/ ___| ___ _ __(_)_ __ | |_ "
, "| |_) | | | | '__/ _ \\___ \\ / __| '__| | '_ \\| __|"
, "| __/| |_| | | | __/___) | (__| | | | |_) | |_ "
, "|_| \\__,_|_| \\___|____/ \\___|_| |_| .__/ \\__|"
, " |_| "
, ""
, ":? shows help"
]
-- |
-- The quit message.
--
quitMessage :: String
quitMessage = "See ya!"
-- |
-- PSCI monad
--
newtype PSCI a = PSCI { runPSCI :: InputT (StateT PSCiState IO) a } deriving (Functor, Applicative, Monad)
psciIO :: IO a -> PSCI a
psciIO io = PSCI . lift $ lift io
-- |
-- Makes a volatile module to execute the current expression.
--
createTemporaryModule :: Bool -> PSCiState -> P.Expr -> P.Module
createTemporaryModule exec PSCiState{psciImportedModules = imports, psciLetBindings = lets} val =
let
moduleName = P.ModuleName [P.ProperName "$PSCI"]
trace = P.Var (P.Qualified (Just supportModuleName) (P.Ident "eval"))
mainValue = P.App trace (P.Var (P.Qualified Nothing (P.Ident "it")))
itDecl = P.ValueDeclaration (P.Ident "it") P.Public [] $ Right val
mainDecl = P.ValueDeclaration (P.Ident "main") P.Public [] $ Right mainValue
decls = if exec then [itDecl, mainDecl] else [itDecl]
in
P.Module (P.internalModuleSourceSpan "<internal>") [] moduleName ((importDecl `map` imports) ++ lets ++ decls) Nothing
-- |
-- Makes a volatile module to hold a non-qualified type synonym for a fully-qualified data type declaration.
--
createTemporaryModuleForKind :: PSCiState -> P.Type -> P.Module
createTemporaryModuleForKind PSCiState{psciImportedModules = imports, psciLetBindings = lets} typ =
let
moduleName = P.ModuleName [P.ProperName "$PSCI"]
itDecl = P.TypeSynonymDeclaration (P.ProperName "IT") [] typ
in
P.Module (P.internalModuleSourceSpan "<internal>") [] moduleName ((importDecl `map` imports) ++ lets ++ [itDecl]) Nothing
-- |
-- Makes a volatile module to execute the current imports.
--
createTemporaryModuleForImports :: PSCiState -> P.Module
createTemporaryModuleForImports PSCiState{psciImportedModules = imports} =
let
moduleName = P.ModuleName [P.ProperName "$PSCI"]
in
P.Module (P.internalModuleSourceSpan "<internal>") [] moduleName (importDecl `map` imports) Nothing
importDecl :: ImportedModule -> P.Declaration
importDecl (mn, declType, asQ) = P.ImportDeclaration mn declType asQ
indexFile :: FilePath
indexFile = ".psci_modules" ++ pathSeparator : "index.js"
modulesDir :: FilePath
modulesDir = ".psci_modules" ++ pathSeparator : "node_modules"
-- | This is different than the runMake in 'Language.PureScript.Make' in that it specifies the
-- options and ignores the warning messages.
runMake :: P.Make a -> IO (Either P.MultipleErrors a)
runMake mk = fst <$> P.runMake P.defaultOptions mk
makeIO :: (IOError -> P.ErrorMessage) -> IO a -> P.Make a
makeIO f io = do
e <- liftIO $ tryIOError io
either (throwError . P.singleError . f) return e
make :: PSCiState -> [(Either P.RebuildPolicy FilePath, P.Module)] -> P.Make P.Environment
make PSCiState{..} ms = P.make actions' (map snd (psciLoadedModules ++ ms))
where
filePathMap = M.fromList $ (first P.getModuleName . swap) `map` (psciLoadedModules ++ ms)
actions = P.buildMakeActions modulesDir filePathMap psciForeignFiles False
actions' = actions { P.progress = const (return ()) }
-- |
-- Takes a value declaration and evaluates it with the current state.
--
handleDeclaration :: P.Expr -> PSCI ()
handleDeclaration val = do
st <- PSCI $ lift get
let m = createTemporaryModule True st val
let nodeArgs = psciNodeFlags st ++ [indexFile]
e <- psciIO . runMake $ make st [(Left P.RebuildAlways, supportModule), (Left P.RebuildAlways, m)]
case e of
Left errs -> printErrors errs
Right _ -> do
psciIO $ writeFile indexFile "require('$PSCI').main();"
process <- psciIO findNodeProcess
result <- psciIO $ traverse (\node -> readProcessWithExitCode node nodeArgs "") process
case result of
Just (ExitSuccess, out, _) -> PSCI $ outputStrLn out
Just (ExitFailure _, _, err) -> PSCI $ outputStrLn err
Nothing -> PSCI $ outputStrLn "Couldn't find node.js"
-- |
-- Takes a list of declarations and updates the environment, then run a make. If the declaration fails,
-- restore the original environment.
--
handleDecls :: [P.Declaration] -> PSCI ()
handleDecls ds = do
st <- PSCI $ lift get
let st' = updateLets ds st
let m = createTemporaryModule False st' (P.ObjectLiteral [])
e <- psciIO . runMake $ make st' [(Left P.RebuildAlways, m)]
case e of
Left err -> printErrors err
Right _ -> PSCI $ lift (put st')
-- |
-- Show actual loaded modules in psci.
--
handleShowLoadedModules :: PSCI ()
handleShowLoadedModules = do
PSCiState { psciLoadedModules = loadedModules } <- PSCI $ lift get
psciIO $ readModules loadedModules >>= putStrLn
return ()
where readModules = return . unlines . sort . nub . map toModuleName
toModuleName = N.runModuleName . (\ (P.Module _ _ mdName _ _) -> mdName) . snd
-- |
-- Show the imported modules in psci.
--
handleShowImportedModules :: PSCI ()
handleShowImportedModules = do
PSCiState { psciImportedModules = importedModules } <- PSCI $ lift get
psciIO $ showModules importedModules >>= putStrLn
return ()
where
showModules = return . unlines . sort . map showModule
showModule (mn, declType, asQ) =
"import " ++ case asQ of
Just mn' -> "qualified " ++ N.runModuleName mn ++ " as " ++ N.runModuleName mn'
Nothing -> N.runModuleName mn ++ " " ++ showDeclType declType
showDeclType P.Implicit = ""
showDeclType (P.Explicit refs) = refsList refs
showDeclType (P.Hiding refs) = "hiding " ++ refsList refs
refsList refs = "(" ++ commaList (map showRef refs) ++ ")"
showRef :: P.DeclarationRef -> String
showRef (P.TypeRef pn dctors) = show pn ++ "(" ++ maybe ".." (commaList . map N.runProperName) dctors ++ ")"
showRef (P.ValueRef ident) = show ident
showRef (P.TypeClassRef pn) = show pn
showRef (P.TypeInstanceRef ident) = show ident
showRef (P.ModuleRef name) = "module " ++ show name
showRef (P.PositionedDeclarationRef _ _ ref) = showRef ref
commaList :: [String] -> String
commaList = intercalate ", "
-- |
-- Imports a module, preserving the initial state on failure.
--
handleImport :: ImportedModule -> PSCI ()
handleImport im = do
st <- updateImportedModules im <$> PSCI (lift get)
let m = createTemporaryModuleForImports st
e <- psciIO . runMake $ make st [(Left P.RebuildAlways, m)]
case e of
Left errs -> printErrors errs
Right _ -> do
PSCI $ lift $ put st
return ()
-- |
-- Takes a value and prints its type
--
handleTypeOf :: P.Expr -> PSCI ()
handleTypeOf val = do
st <- PSCI $ lift get
let m = createTemporaryModule False st val
e <- psciIO . runMake $ make st [(Left P.RebuildAlways, m)]
case e of
Left errs -> printErrors errs
Right env' ->
case M.lookup (P.ModuleName [P.ProperName "$PSCI"], P.Ident "it") (P.names env') of
Just (ty, _, _) -> PSCI . outputStrLn . P.prettyPrintType $ ty
Nothing -> PSCI $ outputStrLn "Could not find type"
-- |
-- Pretty print a module's signatures
--
printModuleSignatures :: P.ModuleName -> P.Environment -> PSCI ()
printModuleSignatures moduleName env =
PSCI $ let namesEnv = P.names env
moduleNamesIdent = (filter ((== moduleName) . fst) . M.keys) namesEnv
in case moduleNamesIdent of
[] -> outputStrLn $ "This module '"++ P.runModuleName moduleName ++"' does not export functions."
_ -> ( outputStrLn
. unlines
. sort
. map (showType . findType namesEnv)) moduleNamesIdent
where findType :: M.Map (P.ModuleName, P.Ident) (P.Type, P.NameKind, P.NameVisibility) -> (P.ModuleName, P.Ident) -> (P.Ident, Maybe (P.Type, P.NameKind, P.NameVisibility))
findType envNames m@(_, mIdent) = (mIdent, M.lookup m envNames)
showType :: (P.Ident, Maybe (P.Type, P.NameKind, P.NameVisibility)) -> String
showType (mIdent, Just (mType, _, _)) = show mIdent ++ " :: " ++ P.prettyPrintType mType
showType _ = P.internalError "The impossible happened in printModuleSignatures."
-- |
-- Browse a module and displays its signature (if module exists).
--
handleBrowse :: P.ModuleName -> PSCI ()
handleBrowse moduleName = do
st <- PSCI $ lift get
env <- psciIO . runMake $ make st []
case env of
Left errs -> printErrors errs
Right env' ->
if moduleName `notElem` (nub . map ((\ (P.Module _ _ modName _ _ ) -> modName) . snd)) (psciLoadedModules st)
then PSCI $ outputStrLn $ "Module '" ++ N.runModuleName moduleName ++ "' is not valid."
else printModuleSignatures moduleName env'
-- | Pretty-print errors
printErrors :: P.MultipleErrors -> PSCI ()
printErrors = PSCI . outputStrLn . P.prettyPrintMultipleErrors False
-- |
-- Takes a value and prints its kind
--
handleKindOf :: P.Type -> PSCI ()
handleKindOf typ = do
st <- PSCI $ lift get
let m = createTemporaryModuleForKind st typ
mName = P.ModuleName [P.ProperName "$PSCI"]
e <- psciIO . runMake $ make st [(Left P.RebuildAlways, m)]
case e of
Left errs -> printErrors errs
Right env' ->
case M.lookup (P.Qualified (Just mName) $ P.ProperName "IT") (P.typeSynonyms env') of
Just (_, typ') -> do
let chk = (P.emptyCheckState env') { P.checkCurrentModule = Just mName }
k = check (P.kindOf typ') chk
check :: StateT P.CheckState (ExceptT P.MultipleErrors (Writer P.MultipleErrors)) a -> P.CheckState -> Either P.MultipleErrors (a, P.CheckState)
check sew cs = fst . runWriter . runExceptT . runStateT sew $ cs
case k of
Left errStack -> PSCI . outputStrLn . P.prettyPrintMultipleErrors False $ errStack
Right (kind, _) -> PSCI . outputStrLn . P.prettyPrintKind $ kind
Nothing -> PSCI $ outputStrLn "Could not find kind"
-- Commands
-- |
-- Parses the input and returns either a Metacommand, or an error as a string.
--
getCommand :: Bool -> InputT (StateT PSCiState IO) (Either String (Maybe Command))
getCommand singleLineMode = handleInterrupt (return (Right Nothing)) $ do
firstLine <- withInterrupt $ getInputLine "> "
case firstLine of
Nothing -> return (Right (Just QuitPSCi)) -- Ctrl-D when input is empty
Just "" -> return (Right Nothing)
Just s | singleLineMode || head s == ':' -> return .fmap Just $ parseCommand s
Just s -> fmap Just . parseCommand <$> go [s]
where
go :: [String] -> InputT (StateT PSCiState IO) String
go ls = maybe (return . unlines $ reverse ls) (go . (:ls)) =<< getInputLine " "
-- |
-- Performs an action for each meta-command given, and also for expressions.
--
handleCommand :: Command -> PSCI ()
handleCommand (Expression val) = handleDeclaration val
handleCommand ShowHelp = PSCI $ outputStrLn helpMessage
handleCommand (Import im) = handleImport im
handleCommand (Decls l) = handleDecls l
handleCommand (LoadFile filePath) = whenFileExists filePath $ \absPath -> do
PSCI . lift $ modify (updateImportedFiles absPath)
m <- psciIO $ loadModule absPath
case m of
Left err -> PSCI $ outputStrLn err
Right mods -> PSCI . lift $ modify (updateModules (map ((,) (Right absPath)) mods))
handleCommand (LoadForeign filePath) = whenFileExists filePath $ \absPath -> do
foreignsOrError <- psciIO . runMake $ do
foreignFile <- makeIO (const (P.ErrorMessage [] $ P.CannotReadFile absPath)) (readFile absPath)
P.parseForeignModulesFromFiles [(absPath, foreignFile)]
case foreignsOrError of
Left err -> PSCI $ outputStrLn $ P.prettyPrintMultipleErrors False err
Right foreigns -> PSCI . lift $ modify (updateForeignFiles foreigns)
handleCommand ResetState = do
files <- psciImportedFilenames <$> PSCI (lift get)
PSCI . lift . modify $ \st -> st
{ psciImportedFilenames = files
, psciImportedModules = []
, psciLetBindings = []
}
loadAllImportedModules
handleCommand (TypeOf val) = handleTypeOf val
handleCommand (KindOf typ) = handleKindOf typ
handleCommand (BrowseModule moduleName) = handleBrowse moduleName
handleCommand (ShowInfo QueryLoaded) = handleShowLoadedModules
handleCommand (ShowInfo QueryImport) = handleShowImportedModules
handleCommand QuitPSCi = P.internalError "`handleCommand QuitPSCi` was called. This is a bug."
whenFileExists :: FilePath -> (FilePath -> PSCI ()) -> PSCI ()
whenFileExists filePath f = do
absPath <- psciIO $ expandTilde filePath
exists <- psciIO $ doesFileExist absPath
if exists
then f absPath
else PSCI . outputStrLn $ "Couldn't locate: " ++ filePath
-- |
-- Attempts to read initial commands from '.psci' in the present working
-- directory then the user's home
--
loadUserConfig :: IO (Maybe [Command])
loadUserConfig = onFirstFileMatching readCommands pathGetters
where
pathGetters = [getCurrentDirectory, getHomeDirectory]
readCommands :: IO FilePath -> IO (Maybe [Command])
readCommands path = do
configFile <- (</> ".psci") <$> path
exists <- doesFileExist configFile
if exists
then do
ls <- lines <$> readFile configFile
case traverse parseCommand ls of
Left err -> print err >> exitFailure
Right cs -> return $ Just cs
else
return Nothing
-- | Checks if the Console module is defined
consoleIsDefined :: [P.Module] -> Bool
consoleIsDefined = any ((== P.ModuleName (map P.ProperName [ "Control", "Monad", "Eff", "Console" ])) . P.getModuleName)
-- |
-- The PSCI main loop.
--
loop :: PSCiOptions -> IO ()
loop PSCiOptions{..} = do
config <- loadUserConfig
inputFiles <- concat <$> traverse glob psciInputFile
foreignFiles <- concat <$> traverse glob psciForeignInputFiles
modulesOrFirstError <- loadAllModules inputFiles
case modulesOrFirstError of
Left errs -> putStrLn (P.prettyPrintMultipleErrors False errs) >> exitFailure
Right modules -> do
historyFilename <- getHistoryFilename
let settings = defaultSettings { historyFile = Just historyFilename }
foreignsOrError <- runMake $ do
foreignFilesContent <- forM foreignFiles (\inFile -> (inFile,) <$> makeIO (const (P.ErrorMessage [] $ P.CannotReadFile inFile)) (readFile inFile))
P.parseForeignModulesFromFiles foreignFilesContent
case foreignsOrError of
Left errs -> putStrLn (P.prettyPrintMultipleErrors False errs) >> exitFailure
Right foreigns ->
flip evalStateT (PSCiState inputFiles [] modules foreigns [] psciInputNodeFlags) . runInputT (setComplete completion settings) $ do
outputStrLn prologueMessage
traverse_ (traverse_ (runPSCI . handleCommand)) config
modules' <- lift $ gets psciLoadedModules
unless (consoleIsDefined (map snd modules')) . outputStrLn $ unlines
[ "PSCi requires the purescript-console module to be installed."
, "For help getting started, visit http://wiki.purescript.org/PSCi"
]
go
where
go :: InputT (StateT PSCiState IO) ()
go = do
c <- getCommand (not psciMultiLineMode)
case c of
Left err -> outputStrLn err >> go
Right Nothing -> go
Right (Just QuitPSCi) -> outputStrLn quitMessage
Right (Just c') -> do
handleInterrupt (outputStrLn "Interrupted.")
(withInterrupt (runPSCI (loadAllImportedModules >> handleCommand c')))
go
multiLineMode :: Parser Bool
multiLineMode = switch $
long "multi-line-mode"
<> short 'm'
<> Opts.help "Run in multi-line mode (use ^D to terminate commands)"
inputFile :: Parser FilePath
inputFile = strArgument $
metavar "FILE"
<> Opts.help "Optional .purs files to load on start"
inputForeignFile :: Parser FilePath
inputForeignFile = strOption $
short 'f'
<> long "ffi"
<> help "The input .js file(s) providing foreign import implementations"
nodeFlagsFlag :: Parser [String]
nodeFlagsFlag = option parser $
long "node-opts"
<> metavar "NODE_OPTS"
<> value []
<> Opts.help "Flags to pass to node, separated by spaces"
where
parser = words <$> str
psciOptions :: Parser PSCiOptions
psciOptions = PSCiOptions <$> multiLineMode
<*> many inputFile
<*> many inputForeignFile
<*> nodeFlagsFlag
runPSCi :: IO ()
runPSCi = execParser opts >>= loop
where
opts = info (version <*> helper <*> psciOptions) infoModList
infoModList = fullDesc <> headerInfo <> footerInfo
headerInfo = header "psci - Interactive mode for PureScript"
footerInfo = footer $ "psci " ++ showVersion Paths.version
version :: Parser (a -> a)
version = abortOption (InfoMsg (showVersion Paths.version)) $ long "version" <> Opts.help "Show the version number" <> hidden
|
michaelficarra/purescript
|
psci/PSCi.hs
|
mit
| 22,518
| 1
| 27
| 4,842
| 6,577
| 3,359
| 3,218
| 416
| 9
|
module Main where
import Types
import Scheduler
import Simulator
import qualified Data.Heap as H
import System.Random
import Text.Show.Pretty (pPrint)
main :: IO ()
main = do
g <- newStdGen
let
randJobs = take 1000 (randomRs (Job 1 0 1 1, Job 8 1 1000 100) g :: [Job])
farmState = FarmState { currentTime = 0
, machineSchedules = [MachineSchedule (ResourceBundle 32 4 10000) i [] | i <- [1..1]]
, stats = mempty
}
endState = simulate firstFitScheduler randJobs (H.singleton 0) farmState
{-
schedulers = [firstFitScheduler,
bestRAMFit, bestGPUFit, bestCoresFit, bestAllFit,
worstRAMFit, worstGPUFit, worstCoresFit, worstAllFit]
results = map (\s -> currentTime $ simulate s randJobs (H.singleton 0) farmState) schedulers
-}
pPrint endState
|
mohsen3/haskell-tutorials
|
src/job-scheduling/src/Main.hs
|
mit
| 886
| 0
| 15
| 258
| 200
| 110
| 90
| 17
| 1
|
module HappySchedulerSpec (spec) where
import Test.Hspec
import Prelude
import Data.Time.Calendar (Day, fromGregorian)
import Data.Time.Clock (getCurrentTime, utctDay)
import Database.Persist.Sql (Entity(..), toSqlKey)
import Model
import HappyScheduler
aTask :: Task
aTask = Task { taskName = "a task"
, taskStartDate = Nothing
, taskDone = False
, taskDeadline = Nothing
, taskHappy = True
, taskTime = 0
, taskUserId = toSqlKey 0
}
sadTask :: Entity Task
sadTask = Entity (toSqlKey 1) aTask {taskHappy = False}
happyTask :: Entity Task
happyTask = Entity (toSqlKey 1) aTask {taskHappy = True}
today :: IO Day
today = fmap utctDay getCurrentTime
spec :: Spec
spec =
describe "scheduleTasks" $ do
context "when the list of tasks is empty" $
it "should return an empty list" $ do
today' <- today
scheduleTasks today' [] `shouldBe` ([] :: [Entity Task])
it "if everything equal,should put happy tasks first" $ do
let [Entity _ st1, Entity _ st2] = scheduleTasks (fromGregorian 2017 7 29) [sadTask, happyTask]
taskHappy st1 `shouldBe` True
taskHappy st2 `shouldBe` False
it "should give a 'start date'" $ do
today' <- today
let [Entity _ schTask] = scheduleTasks today' [sadTask {
entityVal = (entityVal sadTask) {taskTime = 1}
}]
taskStartDate schTask `shouldBe` Just today'
it "should start happy tasks as early as possible" $ do
today' <- today
let [Entity _ schTask] = scheduleTasks today' [happyTask]
taskStartDate schTask `shouldBe` Just today'
context "when happy tasks schedule superpose" $
it "should change the less urgent task to start after the more urgent" $ do
let today' = fromGregorian 2017 8 18
t1 = Entity (toSqlKey 1) aTask {
taskHappy = True,
taskTime = 2,
taskDeadline = Just (fromGregorian 2017 8 31)
}
t2 = Entity (toSqlKey 2) aTask {
taskHappy = True,
taskTime = 3,
taskDeadline = Just (fromGregorian 2017 9 1)
}
[Entity _ st1, Entity _ st2] = scheduleTasks today' [t1, t2]
taskStartDate st1 `shouldBe` Just today'
taskStartDate st2 `shouldBe` Just (fromGregorian 2017 8 20)
context "when sad tasks schedule superpose" $
it "should change the more urgent task to start before the less urgent" $ do
let t1 = Entity (toSqlKey 3) aTask {
taskHappy = False,
taskTime = 2,
taskDeadline = Just (fromGregorian 2017 8 31)
}
t2 = Entity (toSqlKey 5) aTask {
taskHappy = False,
taskTime = 3,
taskDeadline = Just (fromGregorian 2017 9 1)
}
[Entity _ st1, Entity _ st2] = scheduleTasks (fromGregorian 2017 7 26) [t1, t2]
taskStartDate st1 `shouldBe` Just (fromGregorian 2017 8 26)
taskStartDate st2 `shouldBe` Just (fromGregorian 2017 8 29)
context "when happy and sad tasks schedule superpose" $
it "should change the sad task to start after the happy task" $ do
let t1 = Entity (toSqlKey 7) aTask {
taskHappy = True,
taskTime = 7,
taskDeadline = Just (fromGregorian 2017 8 31)
}
t2 = Entity (toSqlKey 11) aTask {
taskHappy = False,
taskTime = 7,
taskDeadline = Just (fromGregorian 2017 8 31)
}
[Entity _ st1, Entity _ st2] = scheduleTasks (fromGregorian 2017 8 20) [t1, t2]
taskStartDate st1 `shouldBe` Just (fromGregorian 2017 8 20)
taskStartDate st2 `shouldBe` Just (fromGregorian 2017 8 27)
it "should sort properly" $ do
let t1 = Entity (toSqlKey 1) aTask {
taskHappy = True,
taskTime = 3,
taskDeadline = Just (fromGregorian 2017 8 13)
}
t2 = Entity (toSqlKey 2) aTask {
taskHappy = True,
taskTime = 5,
taskDeadline = Just (fromGregorian 2017 8 13)
}
t3 = Entity (toSqlKey 3) aTask {
taskHappy = False,
taskTime = 2,
taskDeadline = Just (fromGregorian 2017 8 7)
}
[st1, st2, st3] = scheduleTasks (fromGregorian 2017 8 1) [t1, t2, t3]
st1 `shouldBe` t1 { entityVal =
(entityVal t1) {taskStartDate = Just (fromGregorian 2017 8 1)}
}
st2 `shouldBe` t3 { entityVal =
(entityVal t3) {taskStartDate = Just (fromGregorian 2017 8 5)}
}
st3 `shouldBe` t2 { entityVal =
(entityVal t2) {taskStartDate = Just (fromGregorian 2017 8 7)}
}
context "when a task don't have a deadline" $
it "should start after the last task" $ do
let taskWithDeadline = Entity (toSqlKey 4) aTask {
taskDeadline = Just (fromGregorian 2017 8 23),
taskTime = 1,
taskHappy = False
}
taskWithoutDeadline = Entity (toSqlKey 5) aTask {
taskDeadline = Nothing,
taskHappy = False
}
[_, st2] = scheduleTasks (fromGregorian 2017 8 18) [taskWithDeadline, taskWithoutDeadline]
schStartDate st2 `shouldBe` Just (fromGregorian 2017 8 23)
|
frt/happyscheduler
|
test/HappySchedulerSpec.hs
|
mit
| 6,337
| 0
| 20
| 2,745
| 1,616
| 845
| 771
| 113
| 1
|
data RomanNumeral = I | V | X | L | C | D | M
deriving (Show, Eq, Ord)
convertThousands :: Int -> [RomanNumeral]
convertThousands n = replicate n M
convertHundreds :: Int -> [RomanNumeral]
convertHundreds n
| n < 4 = replicate n C
| n == 4 = [C, D]
| n == 5 = [D]
| n < 9 = D : replicate (n - 5) C
| n == 9 = [C, M]
convertTens :: Int -> [RomanNumeral]
convertTens n
| n < 4 = replicate n X
| n == 4 = [X, L]
| n == 5 = [L]
| n < 9 = L : replicate (n - 5) X
| n == 9 = [X, C]
convertOnes :: Int -> [RomanNumeral]
convertOnes n
| n < 4 = replicate n I
| n == 4 = [I, V]
| n == 5 = [V]
| n < 9 = V : replicate (n - 5) I
| n == 9 = [I, X]
intToRoman :: Int -> [RomanNumeral]
intToRoman n =
convertThousands (n `div` 1000) ++
convertHundreds ((n `mod` 1000) `div` 100) ++
convertTens ((n `mod` 100) `div` 10) ++
convertOnes (n `mod` 10)
singleRomanToInt :: RomanNumeral -> Int
singleRomanToInt M = 1000
singleRomanToInt D = 500
singleRomanToInt C = 100
singleRomanToInt L = 50
singleRomanToInt X = 10
singleRomanToInt V = 5
singleRomanToInt I = 1
romanToInt :: [RomanNumeral] -> Int
romanToInt [] = 0
romanToInt (x:y:xs) =
if x < y
then singleRomanToInt y - singleRomanToInt x + romanToInt xs
else singleRomanToInt x + romanToInt (y:xs)
romanToInt (x:xs) =
singleRomanToInt x + romanToInt xs
showNumerals :: [RomanNumeral] -> String
showNumerals numerals = concat $ map show numerals
parseNumeral :: Char -> RomanNumeral
parseNumeral 'M' = M
parseNumeral 'D' = D
parseNumeral 'C' = C
parseNumeral 'L' = L
parseNumeral 'X' = X
parseNumeral 'V' = V
parseNumeral 'I' = I
parseNumerals :: String -> [RomanNumeral]
parseNumerals = map parseNumeral
file = "p089_roman.txt"
readNumerals :: IO [[RomanNumeral]]
readNumerals = do
contents <- readFile file
return $ map parseNumerals $ words contents
charsSaved :: [RomanNumeral] -> Int
charsSaved numerals = length numerals - length optimisedNumerals
where optimisedNumerals = intToRoman $ romanToInt numerals
euler89 = do
numerals <- readNumerals
print $ sum $ map charsSaved numerals
|
RossMeikleham/Project-Euler-Haskell
|
89.hs
|
mit
| 2,183
| 0
| 12
| 544
| 932
| 479
| 453
| 70
| 2
|
-- You are given the following information, but you may prefer to do
-- some research for yourself.
-- 1 Jan 1900 was a Monday.
-- Thirty days has September,
-- April, June and November.
-- All the rest have thirty-one,
-- Saving February alone,
-- Which has twenty-eight, rain or shine.
-- And on leap years, twenty-nine.
-- A leap year occurs on any year evenly divisible by 4, but not on
-- a century unless it is divisible by 400.
-- How many Sundays fell on the first of the month during the
-- twentieth century (1 Jan 1901 to 31 Dec 2000)?
module Euler.Problem019
( solution
, modifiedJulian
, isSunday
) where
import Data.Ix (range)
type Day = (Integer, Int, Int)
solution :: Day -> Day -> Int
solution s e = length . filter isSunday $ firstsBetween s e
firstsBetween :: Day -> Day -> [Day]
firstsBetween (sy, sm, sd) (ey, em, _) = do
y <- range (sy, ey)
let sm' = if sd == 1 then sm else sm + 1
m <- range (sm', em)
return (y, m, 1)
isSunday :: Day -> Bool
isSunday = (== 0) . (`mod` 7) . (`subtract` firstSunday) . modifiedJulian
where firstSunday = -678933
-- Stolen from http://alcor.concordia.ca/~gpkatch/gdate-algorithm.html
modifiedJulian :: Day -> Integer
modifiedJulian (y, m, d) =
let m' = toInteger ((m + 9) `mod` 12)
y' = y - (m' `div` 10)
d' = toInteger d
epoch = 678881
in 365 * y'
+ y' `div` 4
- y' `div` 100
+ y' `div` 400
+ (m' * 306 + 5) `div` 10
+ d' - 1 - epoch
|
whittle/euler
|
src/Euler/Problem019.hs
|
mit
| 1,513
| 0
| 18
| 397
| 416
| 242
| 174
| 29
| 2
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module QTuple where
import Quipper
-- |The 'Tuple' class creates a tuple out of a list.
class QTuple a where
tupleSize :: a -> Int
tupleFromList :: [Qubit] -> a
instance QTuple Qubit where
tupleSize _ = 1
tupleFromList (q1:_) = q1
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 1 or more, got" ++ show (length l)
instance QTuple (Qubit, Qubit) where
tupleSize _ = 2
tupleFromList (q1:q2:_) = (q1, q2)
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 2 or more, got" ++ show (length l)
instance QTuple (Qubit, Qubit, Qubit) where
tupleSize _ = 3
tupleFromList (q1:q2:q3:_) = (q1, q2, q3)
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 3 or more, got" ++ show (length l)
instance QTuple (Qubit, Qubit, Qubit, Qubit) where
tupleSize _ = 4
tupleFromList (q1:q2:q3:q4:_) = (q1, q2, q3, q4)
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 4 or more, got" ++ show (length l)
instance QTuple (Qubit, Qubit, Qubit, Qubit, Qubit) where
tupleSize _ = 5
tupleFromList (q1:q2:q3:q4:q5:_) = (q1, q2, q3, q4,q5)
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 5 or more, got" ++ show (length l)
instance QTuple (Qubit, Qubit, Qubit, Qubit, Qubit, Qubit) where
tupleSize _ = 6
tupleFromList (q1:q2:q3:q4:q5:q6:_) = (q1, q2, q3, q4, q5, q6)
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 6 or more, got" ++ show (length l)
instance QTuple (Qubit, Qubit, Qubit, Qubit, Qubit, Qubit, Qubit) where
tupleSize _ = 7
tupleFromList (q1:q2:q3:q4:q5:q6:q7:_) = (q1, q2, q3, q4, q5, q6, q7)
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 7 or more, got" ++ show (length l)
instance QTuple (Qubit, Qubit, Qubit, Qubit, Qubit, Qubit, Qubit, Qubit) where
tupleSize _ = 8
tupleFromList (q1:q2:q3:q4:q5:q6:q7:q8:_) = (q1, q2, q3, q4, q5, q6, q7, q8)
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 8 or more, got" ++ show (length l)
instance QTuple (Qubit, Qubit, Qubit, Qubit, Qubit, Qubit, Qubit, Qubit, Qubit) where
tupleSize _ = 9
tupleFromList (q1:q2:q3:q4:q5:q6:q7:q8:q9:_) = (q1, q2, q3, q4, q5, q6, q7, q8, q9)
tupleFromList l = error $ "Not enough elements passed to tupleFromList, expected 9 or more, got" ++ show (length l)
|
miniBill/entangle
|
src/lib/QTuple.hs
|
mit
| 2,586
| 0
| 16
| 539
| 952
| 524
| 428
| 43
| 0
|
-- Danger! Danger! I haven't finished converting this file to the new system!
-- type errors abound!! jcp
----------------------------------------------------------------
-- Stream Processors
--
-- Choice of symbols is inspired by John Hughes' Arrow combinators
----------------------------------------------------------------
module SPtalk
( module SPtalk
) where
import XVTypes
import Geometry
import Draw
import SP hiding(composite2,Tracker)
-- import Pipe
--import SSD hiding(interactive_init,Delta,ssd)
import Matrix
import Image
import Video
import Window
import SSD
import Init
import IOExts
import Monad
import Maybe
import XVUtilities
import List( transpose )
import Array
import CStream
import XVision(clrproject)
import FranCore(scanlE)
import FVision(createMPEGSourceDisplay)
-- Basic types used:
-- type Delta a = (a -> a)
--type AugmentedDelta st = WithError (Delta st)
type AugmentedState st = WithError st
type AugmentedDelta st = WithError st
-->>-->> IP: Commented Delta type does not work with what I have written.
type Pos = Transform2 -- Defines a transformation onto the sampling area
type Src clk st = SP clk st ImageInt
type Stepper clk st = SP clk ImageInt (AugmentedDelta st)
type Tracker clk st = SP clk st (AugmentedState st)
c = unsafePerformIO (openConsole True True)
--newWindow nm = createnamedWindow c nm
newWindow nm = createWindow c
--newsrc :: Video -> Size -> Int -> Src clk Pos
--newsrc vidsrc sz res =
-- (newsrcC vidsrc sz res) >>> (sp1 colorToBWImage)
newsrcC vidsrc sz res =
spIO1 (\pos -> acquireImage NoOptions vidsrc sz
(iscale2 res `compose2` pos))
-->>-->> IP: is using scanlE right here ?????
scanCStream f a (CStream as)= CStream $ scanlE f a as
withErrorP (a,err) = WithError a err
-->>-->> IP: This does not work since Transform2 is not instance of Num.
{-
integralS :: Num a => a -> CStream clk a -> CStream clk a
integralS = scanCStream (+)
-- stateIntegral:: Num st => st -> SP clk (st,err) (st,err)
stateIntegral:: Num st => st -> SP clk (AugmentedDelta st) (AugmentedState st)
stateIntegral start =
\x -> joinWithE (integralS start ((lift1S fst') x), (lift1S snd') x)
where
fst' (WithError a err) = a
snd' (WithError a err) = err
joinWithE = sp1 withErrorP . join2
basicTracker:: Num a => Stepper clk a -> Src clk a -> a -> Tracker clk a
basicTracker step src start =
src >>> step >>> (stateIntegral start)
-- instance Num Transform2 where
-- (+) = compose2
-- ssd :: ImageInt -> Src clk Transform2 -> Transform2 -> Tracker clk Transform2
ssd im src pos = basicTracker
( (lift1S (ssdStep im)) >>> (sp1 withErrorP) )
src pos
-}
type Plus a = a -> a -> a
integralS :: Plus a -> a -> CStream clk a -> CStream clk a
integralS f = scanCStream f
stateIntegral:: Plus st -> st -> SP clk (AugmentedDelta st) (AugmentedState st)
stateIntegral f start =
\x -> joinWithE (integralS f start ((lift1S fst') x), (lift1S snd') x)
where
fst' (WithError a err) = a
snd' (WithError a err) = err
joinWithE = sp1 withErrorP . join2
basicTracker:: Plus a -> Stepper clk a -> Src clk a -> a -> Tracker clk a
basicTracker f step src start =
src >>> step >>> (stateIntegral f start)
ssd :: ImageInt -> Src clk Transform2 -> Transform2 -> Tracker clk Transform2
ssd im src pos = basicTracker
compose2
( (lift1S (ssdStep im)) >>> (sp1 withErrorP) )
src pos
pointsToTr2 :: Point2 -> Point2 -> Transform2
pointsToTr2 p1 p2 = translate2 (p2v (p2-p1))
masked th rgb im = threshBWImageInt th 1 (clrproject rgb (bwToColorImage im))
colorStepper:: RGBtriple -> Integer -> Stepper clk Transform2
colorStepper rgb th imS =(sp1 findTr2) imS
where
p1 im=centroidBWImageInt (masked th rgb im)
p2 im= let (x,y)=sizeOf im
in (x/2,y/2)
findTr2 im = pointsToTr2 (p1 im) (p2 im)
type Src2 clk st = SP clk (ImageRGB,st) ImageInt
type Tracker2 clk st = SP clk (ImageRGB,st) (AugmentedState st)
colorTracker:: RGBtriple -> Integer -> Src2 clk Transform2
-> Tracker2 clk Transform2
colorTracker rgb th src start=
(src >>> (colorStepper rgb th) >>> (stateIntegral compose2 start))
runColorTracker th src= do
{ c <- openConsole True True
; (v,_) <- openVideo "MPEG"
; (p,size) <- interactiveInitRect c v "Rectangle"
; print ("point : " ++ show p ++ " size : " ++ show size)
; (im,start) <- acquireImage NoOptions v (toSize size) (translate2 (p2v p))
; closeVideo v
; let rgb = avgColorImageRGB im
; s <- createMPEGSourceDisplay "mpeg_file.mpg"
; (_,img,_) <- (fst s)
; print ("rgb : "++ show rgb)
; let ct = colorTracker rgb th src start
--; let loop imrgb=loop (
; runVisionSP s
( (loopCS start id ct)
(lift1S iPointToPoint2) >>> (nulltestCS)
)
}
|
jatinshah/autonomous_systems
|
project/fvision.hugs/sptalkcode2.hs
|
mit
| 5,065
| 14
| 12
| 1,270
| 1,337
| 702
| 635
| -1
| -1
|
module Self where
class C a where
f1 :: a -> a
f2 :: a -> a
data T = K
-- Not actually recursive, just one function defined in terms of the others
instance C T where
f1 = \x -> x
f2 = f1
|
antalsz/hs-to-coq
|
examples/tests/Self.hs
|
mit
| 202
| 0
| 7
| 61
| 62
| 35
| 27
| 8
| 0
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.UIRequestEvent (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.UIRequestEvent
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.UIRequestEvent
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/UIRequestEvent.hs
|
mit
| 355
| 0
| 5
| 33
| 33
| 26
| 7
| 4
| 0
|
-- -------------------------------------------------------------------------------------
-- Author: Sourabh S Joshi (cbrghostrider); Copyright - All rights reserved.
-- For email, run on linux (perl v5.8.5):
-- perl -e 'print pack "H*","736f75726162682e732e6a6f73686940676d61696c2e636f6d0a"'
-- -------------------------------------------------------------------------------------
-- this code currently times out on the biggest inputs
-- the problem is that I am increasing f by 1 at each step.
-- I need to binary search the space instead
import Data.List
-- computes the fewest mangoes consumed when number of friends in the party are fixed to f
mangoesConsumed :: [Int] -> [Int] -> Int -> Int
mangoesConsumed as hs f = sum . take f . sort . map (\(a, h) -> a + (f-1)*h) $ zip as hs
-- try picking # of friends from 0, 1, 2, ... until constraint is broken
solveProblem :: [Int] -> [Int] -> [Int] -> Int
solveProblem [n, m] as hs = fst . last . takeWhile ((<=m) . snd) . zip [0..] . map (mangoesConsumed as hs) $ [0..(length as)]
main :: IO ()
main = do
nmstr <- getLine
asstr <- getLine
hsstr <- getLine
putStrLn $ show $ solveProblem (map read . words $ nmstr) (map read . words $ asstr) (map read . words $ hsstr)
|
cbrghostrider/Hacking
|
HackerRank/FunctionalProgramming/AdHoc/mangoes_v1.hs
|
mit
| 1,264
| 0
| 13
| 246
| 309
| 164
| 145
| 11
| 1
|
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module GigSpider.Places where
import GigSpider.URL
import qualified GigSpider.Search as S
import qualified GigSpider.Geocoding as G
import Control.Applicative
import Control.Monad.Trans.Either
import Data.Aeson
import GHC.Generics
import Network.HTTP.Conduit (simpleHttp)
data Point = Point { lat :: Float
, long :: Float }
deriving (Generic)
instance FromJSON Point
instance Show Point where
show point = show (lat point) ++ "," ++ show (long point)
convert :: G.Point -> Point
convert gp = Point (G.lat gp) (G.lng gp)
data Geometry = Geometry { location :: Point }
deriving (Show, Generic)
instance FromJSON Geometry
data Place = Place { name :: String
, reference :: String }
deriving (Show, Generic)
instance FromJSON Place
data PlacesResponse = PlacesResponse { results :: [Place] }
deriving (Show, Generic)
instance FromJSON PlacesResponse
placesApiBase :: String
placesApiBase = "https://maps.googleapis.com/maps/api/place/nearbysearch/json"
defaultRadius :: Int
defaultRadius = 10000
defaultTypes :: String
defaultTypes = "bar|cafe|night_club|restaurant"
placesApiUrl :: Point -> String -> String
placesApiUrl point key =
urlWithParams placesApiBase [loc, radius, types, k]
where loc = ("location", show point)
radius = ("radius", show defaultRadius)
types = ("types", defaultTypes)
k = ("key", key)
toVenue :: Place -> S.Venue
toVenue place = S.Venue (name place) [] Nothing
toVenues :: PlacesResponse -> [S.Venue]
toVenues = map toVenue . results
findVenuesNearArea :: S.Area -> String -> EitherT String IO [S.Venue]
findVenuesNearArea area key = do
point <- G.find area key
let url = placesApiUrl (convert point) key
found <- eitherDecode <$> simpleHttp url
hoistEither $ toVenues <$> found
data GoogleBackend = GoogleBackend { apiKey :: String }
instance S.Backend GoogleBackend where
search (GoogleBackend key) area = runEitherT $ findVenuesNearArea area key
|
owickstrom/GigSpider
|
src/GigSpider/Places.hs
|
mit
| 2,136
| 0
| 12
| 480
| 616
| 335
| 281
| 54
| 1
|
{- |
Module : $Header$
Description : Provers for propositional logic
Copyright : (c) Till Mossakowski, Uni Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : till@informatik.uni-bremen.de
Stability : experimental
Portability : portable
A truth table prover for propositional logic.
Inefficient, but useful for learning purposes.
-}
module Propositional.ProveWithTruthTable
( ttProver
, ttConsistencyChecker
, ttConservativityChecker
, allModels
) where
import Common.Lib.Tabular
import Propositional.AS_BASIC_Propositional
import Propositional.Sign
import qualified Propositional.Morphism as PMorphism
import qualified Propositional.ProverState as PState
import qualified Propositional.Sign as Sig
import Propositional.Sublogic (PropSL, top)
import qualified Logic.Prover as LP
import qualified Interfaces.GenericATPState as ATPState
import GUI.GenericATP
import GUI.Utils (infoDialog, createTextSaveDisplay)
import Common.ProofTree
import qualified Common.AS_Annotation as AS_Anno
import qualified Common.Id as Id
import qualified Data.Set as Set
import qualified Common.OrderedMap as OMap
import Common.Consistency
import qualified Common.Result as Result
import Data.Time (midnight)
-- * Prover implementation
-- | the name of the prover
ttS :: String
ttS = "truth tables"
-- maximal size of the signature
maxSigSize :: Int
maxSigSize = 17
-- display error message when signature is too large
sigTooLarge :: Int -> String
sigTooLarge sigSize = unlines
[ "Signature is too large."
, "It should contain < " ++ show maxSigSize ++ " symbols,"
, "but it contains " ++ show sigSize ++ " symbols." ]
ttHelpText :: String
ttHelpText = "An implementation of the truth table method.\n"
++ "Very inefficient, but useful for learning and teaching\n"
++ "Works well for signatures with less than " ++ show maxSigSize
++ " symbols."
{- |
Models and evaluation of sentences
-}
type Model = Set.Set Id.Id -- a model specifies which propositions are true
-- | show Bools in truth table
showBool :: Bool -> String
showBool True = "T"
showBool False = "F"
-- | evaluation of sentences in a model
eval :: Model -> FORMULA -> Bool
eval m (Negation phi _) = not $ eval m phi
eval m (Conjunction phis _) = all (eval m) phis
eval m (Disjunction phis _) = any (eval m) phis
eval m (Implication phi1 phi2 _) = not (eval m phi1) || eval m phi2
eval m (Equivalence phi1 phi2 _) = eval m phi1 == eval m phi2
eval _ (True_atom _) = True
eval _ (False_atom _) = False
eval m (Predication ident) = Id.simpleIdToId ident `Set.member` m
evalNamed :: Model -> AS_Anno.Named FORMULA -> Bool
evalNamed m = eval m . AS_Anno.sentence
{- |
Evaluation of (co)freeness constraints
-}
-- | amalgamation of models
amalg :: Model -> Model -> Model
amalg = Set.union
data FormulaOrFree =
Formula FORMULA
| FreeConstraint (LP.FreeDefMorphism FORMULA PMorphism.Morphism)
evalNamedFormulaOrFree :: Model -> AS_Anno.Named FormulaOrFree -> Bool
evalNamedFormulaOrFree m = evalFormulaOrFree m . AS_Anno.sentence
evalFormulaOrFree :: Model -> FormulaOrFree -> Bool
evalFormulaOrFree m (Formula phi) = eval m phi
evalFormulaOrFree m (FreeConstraint freedef) = evalFree m freedef
reduceModel :: Sig.Sign -> Model -> Model
reduceModel sig m = Set.intersection m (items sig)
leq :: Model -> Model -> Bool
leq = Set.isSubsetOf
isMin :: Bool -> Model -> [Model] -> Bool
isMin isCo m = all (\m' -> if isCo then leq m' m else leq m m')
evalFree :: Model
-> LP.FreeDefMorphism FORMULA PMorphism.Morphism
-> Bool
evalFree m freedef =
let diffsig = Sign (items freetar `Set.difference` items freesrc)
mred = reduceModel freesrc m
modelsOverMred = map (mred `amalg`) (allModels diffsig)
modelClass = foldr (filter . flip eval) modelsOverMred freeth
in all (eval m) freeth -- the model satisfies the axioms ...
&& isMin isCo m modelClass -- ... and is the minimal one that does so
where freemor = LP.freeDefMorphism freedef
freesrc = PMorphism.source freemor
freetar = PMorphism.target freemor
freeth = map AS_Anno.sentence $ LP.freeTheory freedef
isCo = LP.isCofree freedef
-- | generate all models for a signature
allModels :: Sign -> [Model]
allModels sig = allModels1 $ Set.toList $ items sig
where allModels1 [] = [Set.empty]
allModels1 (p:rest) =
let models = allModels1 rest
in models ++ map (Set.insert p) models
data TTExtRow =
TTExtRow { rextprops, rextaxioms :: [Bool]
, rextIsModel :: Bool
}
data TTRow =
TTRow { rprops, raxioms :: [Bool]
, rgoal :: Maybe Bool
, rextrows :: [TTExtRow]
, rIsModel :: Bool
, rIsOK :: Bool
}
data TTHead =
TTHead { hprops, haxioms, hextprops, hextaxioms :: [String]
, hgoal :: Maybe String
}
data TruthTable =
TruthTable { thead :: TTHead
, trows :: [TTRow]
}
renderTT :: TruthTable -> Table String String String
renderTT tt = Table rowHeaders header table
where
hextpropsTT = hextprops (thead tt)
hextaxiomsTT = hextaxioms (thead tt)
rowsTT = trows tt
header = Group DoubleLine
( [ Group SingleLine (map Header (hprops (thead tt)))
, Group SingleLine (map Header (haxioms (thead tt)))]
++ (if null hextpropsTT && null hextaxiomsTT then []
else [ Header ""
, Group SingleLine (map Header hextpropsTT)
, Group SingleLine (map Header hextaxiomsTT)])
++ case hgoal (thead tt) of
Nothing -> []
Just g -> [Group DoubleLine [Header g]])
rowtype r = (if rIsModel r then "M" else " ")
++(if rIsOK r then (if rIsModel r then "+" else "o")
else "-")
rowHeader r = Group NoLine
$ Header (rowtype r) : map (const (Header "")) [2..length (rextrows r)]
rowHeaders = if all (null . rextrows) rowsTT
then Group NoLine (map (Header . rowtype) rowsTT)
else Group SingleLine (map rowHeader rowsTT)
makeExtRow e = (if rextIsModel e then "M" else "") :
map showBool (rextprops e) ++ map showBool (rextaxioms e)
makeRow r =
let common = map showBool (rprops r) ++ map showBool (raxioms r) ++
case (rgoal r) of
Nothing -> []
Just g -> [showBool g]
emptyPrefix = map (const "") [1..length common]
in case map makeExtRow (rextrows r) of
[] -> [common]
e : extrows -> (common ++ e) : map (emptyPrefix ++) extrows
table = concatMap makeRow rowsTT
{- |
The Prover implementation.
Implemented are: a prover GUI.
-}
ttProver :: LP.Prover Sig.Sign FORMULA PMorphism.Morphism PropSL ProofTree
ttProver = LP.mkProverTemplate ttS top ttProveGUI
{- |
The Consistency Cheker.
-}
ttConsistencyChecker :: LP.ConsChecker Sig.Sign FORMULA PropSL
PMorphism.Morphism ProofTree
ttConsistencyChecker = LP.mkConsChecker ttS top consCheck
consCheck :: String -> LP.TacticScript
-> LP.TheoryMorphism Sig.Sign FORMULA PMorphism.Morphism ProofTree
-> [LP.FreeDefMorphism FORMULA PMorphism.Morphism]
-- ^ free definitions
-> IO (LP.CCStatus ProofTree)
consCheck _ _ tm _freedefs = case LP.tTarget tm of
LP.Theory sig nSens ->
let sigSize = Set.size (items sig) in
if sigSize >= maxSigSize then
return $ LP.CCStatus (ProofTree $ sigTooLarge sigSize) midnight Nothing
else do
let axs = filter (AS_Anno.isAxiom . snd) $ OMap.toList nSens
models = allModels sig
sigList = Set.toList $ items sig
heading = TTHead { hprops = map show sigList
, haxioms = map fst axs
, hextprops = [], hextaxioms = []
, hgoal = Nothing
}
mkRow m =
let evalAx = map (eval m . AS_Anno.sentence . snd) axs
isModel = and evalAx
in TTRow { rprops = map (`Set.member` m) sigList
, raxioms = evalAx
, rextrows = []
, rgoal = Nothing
, rIsModel = isModel
, rIsOK = isModel
}
rows = map mkRow models
isOK = any rIsOK rows
table = TruthTable { thead = heading
, trows = rows
}
legend = "Legend:\nM+ = model of the axioms\n"
++ " - = not a model of the axioms\n"
body = legend ++ "\n" ++ render id id id (renderTT table)
return $ LP.CCStatus (ProofTree body) midnight $ Just isOK
-- ** prover GUI
{- |
Invokes the generic prover GUI.
-}
ttProveGUI :: String -- ^ theory name
-> LP.Theory Sig.Sign FORMULA ProofTree
-> [LP.FreeDefMorphism FORMULA PMorphism.Morphism]
-- ^ free definitions
-> IO([LP.ProofStatus ProofTree]) -- ^ proof status for each goal
ttProveGUI thName th freedefs =
genericATPgui (atpFun thName) True (LP.proverName ttProver) thName th
freedefs emptyProofTree
{- |
Record for prover specific functions. This is used by both GUI and command
line interface.
-}
atpFun :: String -- ^ Theory name
-> ATPState.ATPFunctions Sig.Sign FORMULA PMorphism.Morphism ProofTree
PState.PropProverState
atpFun thName = ATPState.ATPFunctions
{ ATPState.initialProverState = PState.propProverState
, ATPState.goalOutput = goalProblem thName
, ATPState.atpTransSenName = PState.transSenName
, ATPState.atpInsertSentence = PState.insertSentence
, ATPState.proverHelpText = ttHelpText
, ATPState.runProver = runTt
, ATPState.batchTimeEnv = ""
, ATPState.fileExtensions = ATPState.FileExtensions
{ ATPState.problemOutput = ".tt"
, ATPState.proverOutput = ".tt"
, ATPState.theoryConfiguration = ".tt"}
, ATPState.createProverOptions = createTtOptions
}
defaultProofStatus :: AS_Anno.Named FORMULA -> LP.ProofStatus ProofTree
defaultProofStatus nGoal =
LP.openProofStatus (AS_Anno.senAttr nGoal) (LP.proverName ttProver)
emptyProofTree
{- |
Runs tt.
-}
runTt :: PState.PropProverState
-- ^ logical part containing the input Sign and
-- axioms and possibly goals that have been proved
-- earlier as additional axioms
-> ATPState.GenericConfig ProofTree
-- ^ configuration to use
-> Bool
-- ^ True means save DIMACS file
-> String
-- ^ Name of the theory
-> AS_Anno.Named FORMULA
-- ^ Goal to prove
-> IO (ATPState.ATPRetval, ATPState.GenericConfig ProofTree)
-- ^ (retval, configuration with proof status and complete output)
runTt pState cfg _ _thName nGoal =
let sig = PState.initialSignature pState
sigSize = Set.size $ items sig
in if sigSize >= maxSigSize then do
infoDialog "Signature too large" $ sigTooLarge sigSize
return (ATPState.ATPTLimitExceeded,
cfg { ATPState.proofStatus = defaultProofStatus nGoal })
else do
let axs = PState.initialAxioms pState
freedefs = PState.freeDefs pState
nameFree fd =
AS_Anno.makeNamed (if LP.isCofree fd then "cofree" else "free")
(FreeConstraint fd)
sens = map (AS_Anno.mapNamed Formula) axs ++ map nameFree freedefs
models = allModels sig
sigList = Set.toList $ items sig
heading =
TTHead { hprops = map show sigList
, haxioms = map AS_Anno.senAttr sens
, hextprops = [], hextaxioms = []
, hgoal = Just $ AS_Anno.senAttr nGoal
}
mkRow m =
let evalAx = map (evalNamedFormulaOrFree m) sens
evalGoal = evalNamed m nGoal
isModel = and evalAx
in TTRow { rprops = map (`Set.member` m) sigList
, raxioms = evalAx
, rextrows = []
, rgoal = Just evalGoal
, rIsModel = isModel
, rIsOK = not isModel || evalGoal
}
rows = map mkRow models
isOK = all rIsOK rows
consistent = any rIsModel rows
table = TruthTable { thead = heading
, trows = rows
}
legend = "Legend:\nM = model of the premises\n"++
"+ = OK, model fulfills conclusion\n"++
"- = not OK, counterexample for logical consequence\n"++
"o = OK, premises are not fulfilled, hence conclusion is "
++ "irrelevant\n"
body = legend++"\n"++render id id id (renderTT table)
let status = (defaultProofStatus nGoal)
{ LP.goalStatus = if isOK then LP.Proved consistent
else LP.Disproved
,LP.usedAxioms = map AS_Anno.senAttr sens
}
return (ATPState.ATPSuccess,
cfg { ATPState.proofStatus = status
, ATPState.resultOutput = [body] })
{- |
Creates a list of all options the truth table prover runs with.
Only Option is the timelimit
-}
createTtOptions :: ATPState.GenericConfig ProofTree -> [String]
createTtOptions _cfg = [] -- [(show $ configTimeLimit cfg)]
goalProblem :: String -- ^ name of the theory
-> PState.PropProverState -- ^ initial Prover state
-> AS_Anno.Named FORMULA -- ^ goal to prove
-> [String] -- ^ Options (ignored)
-> IO String
goalProblem _ _ _ _ = return ""
{- |
Conservativity check
-}
-- | Conservativity Check via truth table
-- TODO: check for injectivity!
ttConservativityChecker ::
(Sign, [AS_Anno.Named FORMULA]) -- ^ Initial sign and formulas
-> PMorphism.Morphism -- ^ morhpism between specs
-> [AS_Anno.Named FORMULA] -- ^ Formulas of extended spec
-> IO (Result.Result (Maybe (Conservativity, [FORMULA])))
ttConservativityChecker (_, srcSens) mor tarSens =
let srcAxs = filter AS_Anno.isAxiom srcSens
tarAxs = filter AS_Anno.isAxiom tarSens
srcSig = items $ PMorphism.source mor
imageSig = Set.map (PMorphism.applyMorphism mor) srcSig
imageSigList = Set.toList imageSig
tarSig = items $ PMorphism.target mor
newSig = Set.difference tarSig imageSig
sigSize = Set.size tarSig
in if sigSize >= maxSigSize then return $ return Nothing
else do
let imageAxs = map (AS_Anno.mapNamed (PMorphism.mapSentenceH mor)) srcAxs
models = allModels (Sign imageSig)
newSigList = Set.toList newSig
heading =
TTHead { hprops = map show imageSigList,
haxioms = map AS_Anno.senAttr srcAxs,
hextprops = map show newSigList,
hextaxioms = map AS_Anno.senAttr tarAxs,
hgoal = Nothing
}
mkRow m =
let evalAx = map (evalNamed m) imageAxs
isModel = and evalAx
extmodels = allModels (Sign newSig)
extrow m' =
let evalExtAx = map (evalNamed (m `amalg` m')) tarAxs
isExtModel = and evalExtAx
in TTExtRow { rextprops = map (`Set.member` m') newSigList,
rextaxioms = evalExtAx,
rextIsModel = isExtModel
}
extrows = map extrow extmodels
in TTRow { rprops = map (`Set.member` m) imageSigList,
raxioms = evalAx,
rgoal = Nothing,
rextrows = if isModel then extrows else [],
rIsModel = isModel,
rIsOK = not isModel || any rextIsModel extrows
}
rows = map mkRow models
isOK = all rIsOK rows
table = TruthTable { thead = heading,
trows = rows
}
title = "The extension is "++ (if isOK then "" else "not ")
++ "conservative"
legend = "Legend:\n"
++ "M = model of the axioms\n"
++ "+ = OK, has expansion\n"
++ "- = not OK, has no expansion, hence conservativity fails\n"
++ "o = OK, not a model of the axioms, hence no expansion needed\n"
body = legend++"\n"++render id id id (renderTT table)
res = if isOK then Cons else Inconsistent
createTextSaveDisplay title "unnamed" body
return $ return $ Just (res, [])
|
nevrenato/Hets_Fork
|
Propositional/ProveWithTruthTable.hs
|
gpl-2.0
| 17,262
| 0
| 25
| 5,635
| 4,176
| 2,222
| 1,954
| 326
| 10
|
--------------------------------------------------------------------------------
-- /////////////////////////////////////////////////////////////////////////////
--------------------------------------------------------------------------------
module P_Shuffle where
--------------------------------------------------------------------------------
{-
From posting-system@google.com Mon Sep 3 14:05:52 2001
Date: Mon, 3 Sep 2001 13:59:46 -0700
From: oleg@pobox.com
Newsgroups: comp.lang.functional
Subject: _Provably_ perfect shuffle algorithms [Was: Shuffle]
This article will give two pure functional programs that _perfectly_
shuffle a sequence of arbitrary elements. We prove that the algorithms
are correct. The algorithms are implemented in Haskell and can
trivially be re-written into other (functional) languages. We also
discuss why a commonly used sort-based shuffle algorithm falls short
of perfect shuffling.
* What is the perfect shuffle
* An imperative implementation: swapping
* A sort-based algorithm and its critique
* A pure-functional perfect-shuffle algorithm
* Naive -- lucid but inefficient -- implementation
* Efficient implementation based on complete binary trees
* A note on repeats in a sequence of random numbers
* What is the perfect shuffle
Let's consider a sequence of n elements: (e1, e2, ...en). Intuitively, the perfect
random shuffle will be a permutation chosen uniformly at random from the set of
all possible n! permutations.
Let (b1, b2, ... bn) be such a random permutation.
Of all n! permutations, (n-1)! of them will have e1 at the first position, (n-1)!
more will have element e2 at the first position, etc.
Therefore, in the perfect shuffle (b1, b2, ... bn) b1 is uniformly randomly chosen
among {e1, ... en}. The second element b2 of the shuffled sequence is uniformly
randomly chosen among {e1, ... en} - {b1}. The third element of the
shuffle b3 is uniformly randomly chosen among {e1, ... en} - {b1, b2},
etc.
Therefore, to perform a perfect shuffle, we need a sequence of
numbers (r1, r2, ... rn) where r1 is a sample of a random
quantity uniformly distributed within [0..n-1]. r2 is an independent
sample of a random quantity uniformly distributed within
[0..n-2]. Finally, rn is 0. It easy to see that the joint probability
of (r1, r2, ... rn) is 1/n * 1/(n-1) * ... 1 = 1/n! -- which is to be
expected.
* An imperative implementation: swapping
The imperative implementation of the algorithm is well known. Let's
arrange the input sequence (e1, e2, ...en) into an array 'a' so that
initially a[i] = ei, i=1..n.
At step 1, we choose a random number r1 uniformly from [0..n-1].
Thus a[1+r1] will be the first element of the
permuted sample, b1. We swap a[1+r1] and a[1]. Thus a[1] will contain
b1. At step 2, we choose a random number r2 uniformly from
[0..n-2]. a[2+r2] will be a uniform sample from {e1..en} - {b1}. After
we swap a[2] and a[2+r2], a[2] will be b2, and a[3..n] will contain
the remaining elements of the original sequence, {e1..en} -
{b1,b2}. After n-1 steps, we're done. The imperative algorithm in
OCaml has been already posted on this thread.
* A sort-based algorithm and its critique
A commonly used shuffle algorithm attaches random tags to elements
of a sequence and then sorts the sequence by the tags. Although this
algorithm performs well in practice, it does not achieve the perfect
shuffling.
Let us consider the simplest example (which happens to be the worst
case): a sequence of two elements, [a b]. According to the
shuffle-by-random-keys algorithm, we pick two binary random numbers,
and associate the first number with the 'a' element, and the second
number with the 'b' element. The two numbers are the tags (keys) for
the elements of the sequence. We then sort the keyed sequence in the
ascending order of the keys. We assume a stable sort algorithm. There
are only 4 possible combinations of two binary random
numbers. Therefore, there are only four possible tagged sequences:
[(0,a) (0,b)]
[(0,a) (1,b)]
[(1,a) (0,b)]
[(1,a) (1,b)]
After the sorting, the sequences become:
[(0,a) (0,b)]
[(0,a) (1,b)]
[(0,b) (1,a)]
[(1,a) (1,b)]
As we can see, after the sorting, the sequence [a, b] is three times
more likely than the sequence [b, a]. That can't be a perfect shuffle.
If we use the algorithm described in the previous two sections, we
choose one binary random number. If it is 0, we leave the sequence
[a, b] as it is. If the number is 1, we swap the elements. Both
alternatives are equally likely.
Furthermore, if we have a sequence of N elements and associate with
each element a key -- a random number uniformly distributed within [0,
M-1] (where N!>M>=N), we have the configurational space of size M^N
(i.e., M^N ways to key the sequence). There are N! possible
permutations of the sequence. Alas, for N>2 and M<N!, M^N is not
evenly divisible by N!. Therefore, certain permutations are bound to
be a bit more likely than the others.
* A pure-functional perfect-shuffle algorithm
Let's consider a functional implementation. The code will take as its
input a sequence (r1, r2, ... rn) where ri is an independent sample of
a random quantity uniformly distributed within [0..n-i]. We can obtain
r[i] as rng[i] mod (n-i), i<n; r[n] is 0. Here, rng is a sequence of
samples independently drawn from a uniform random distribution
[0..M-1]. We can obtain rng from radioactive decay measurements or
from published tables of random numbers. We can compute rng by
applying a digest function (e.g., md5) to a big collection of events
considered random (keystroke presses, Ethernet packet arriving times,
checksums in TCP packets from several IP addresses, etc). Some
systems have a /dev/random, which is a source of cryptographically
strong random numbers. Finally, rng can be a suitable pseudo-random
number generator (PRNG). Note, PRNG are specifically tested that (rng
mod k) is uniformly distributed. The latter phrase does not mean that
the histogram of (rng mod k) is perfectly flat. Even the "real" random
numbers generally don't have the perfectly flat histogram, for any
finite number of samples. It is important that the histogram is
"statistically" flat, in the sense of chi-squared or
Kolmogorov-Smirnov criteria. A volume of Knuth discusses PRNG tests in
great detail.
-}
-- /////////////////////////////////////////////////////////////////////////////
-- ** Naive -- lucid but inefficient -- implementation
-- First, a naive functional shuffle. We note that in the sequence
-- (r1,...rn), rn is always zero. Therefore, we pass to the function
-- 'shuffle' a sequence of n-1 random numbers.
extract:: Integer -> [a] -> (a,[a])
-- given a list l, extract the n-th element and return the element and
-- the remaining list. We won't worry about the order of the list
-- of the remaining elements. n>=0. n==0 corresponds to the first element.
extract 0 (h:t) = (h,t)
extract n l = loop n l []
where
loop 0 (h:t) accum = (h,accum ++ t)
loop n (h:t) accum = loop (n-1) t (h:accum)
-- given a sequence (e1,...en) to shuffle, and a sequence
-- (r1,...r[n-1]) of numbers such that r[i] is an independent sample
-- from a uniform random distribution [0..n-i], compute the
-- corresponding permutation of the input sequence.
shuffle:: [b] -> [Integer] -> [b]
shuffle [e] [] = [e]
shuffle elements (r:r_others) = let (b,rest) = extract r elements
in b:(shuffle rest r_others)
-- Obviously the running time of "extract n l" is
-- O(length(l)). Therefore, the running time of shuffle is O(n^2).
-- ** Efficient implementation based on complete binary trees
-- The following is a more sophisticated algorithm
-- A complete binary tree, of leaves and internal nodes.
-- Internal node: Node card l r
-- where card is the number of leaves under the node.
-- Invariant: card >=2. All internal tree nodes are always full.
data Tree a = Leaf a | Node Integer (Tree a) (Tree a) deriving Show
fix f = g where g = f g -- The fixed point combinator
-- Convert a sequence (e1...en) to a complete binary tree
build_tree = (fix grow_level) . (map Leaf)
where
grow_level self [node] = node
grow_level self l = self $ inner l
inner [] = []
inner [e] = [e]
inner (e1:e2:rest) = (join e1 e2) : inner rest
join l@(Leaf _) r@(Leaf _) = Node 2 l r
join l@(Node ct _ _) r@(Leaf _) = Node (ct+1) l r
join l@(Leaf _) r@(Node ct _ _) = Node (ct+1) l r
join l@(Node ctl _ _) r@(Node ctr _ _) = Node (ctl+ctr) l r
-- example:
-- Main> build_tree ['a','b','c','d','e']
-- Node 5 (Node 4 (Node 2 (Leaf 'a') (Leaf 'b'))
-- (Node 2 (Leaf 'c') (Leaf 'd')))
-- (Leaf 'e')
-- given a sequence (e1,...en) to shuffle, and a sequence
-- (r1,...r[n-1]) of numbers such that r[i] is an independent sample
-- from a uniform random distribution [0..n-i], compute the
-- corresponding permutation of the input sequence.
shuffle1 elements rseq = shuffle1' (build_tree elements) rseq
where
shuffle1' (Leaf e) [] = [e]
shuffle1' tree (r:r_others) =
let (b,rest) = extract_tree r tree
in b:(shuffle1' rest r_others)
-- extract_tree n tree
-- extracts the n-th element from the tree and returns
-- that element, paired with a tree with the element
-- deleted.
-- The function maintains the invariant of the completeness
-- of the tree: all internal nodes are always full.
-- The collection of patterns below is deliberately not complete.
-- All the missing cases may not occur (and if they do,
-- that's an error.
extract_tree 0 (Node _ (Leaf e) r) = (e,r)
extract_tree 1 (Node 2 (Leaf l) (Leaf r)) = (r,Leaf l)
extract_tree n (Node c (Leaf l) r) =
let (e,new_r) = extract_tree (n-1) r
in (e,Node (c-1) (Leaf l) new_r)
extract_tree n (Node n1 l (Leaf e))
| n+1 == n1 = (e,l)
extract_tree n (Node c l@(Node cl _ _) r)
| n < cl = let (e,new_l) = extract_tree n l
in (e,Node (c-1) new_l r)
| otherwise = let (e,new_r) = extract_tree (n-cl) r
in (e,Node (c-1) l new_r)
-- /////////////////////////////////////////////////////////////////////////////
-- examples
{-
Main> shuffle1 ['a','b','c','d','e'] [0,0,0,0]
"abcde"
Note, that rseq of all zeros leaves the sequence unperturbed.
Main> shuffle1 ['a','b','c','d','e'] [4,3,2,1]
"edcba"
The rseq of (n-i | i<-[1..n-1]) reverses the original sequence of elements
Main> shuffle1 ['a','b','c','d','e'] [2,1,2,0]
"cbead"
Just some random shuffle.
The function build_tree builds a complete binary tree, of depth
ceil(log2(n)). The function 'extract_tree' traverses the tree and
rebuilds a truncated branch. This requires as many steps as the length
of the rebuilt branch, which is at most ceil(log2(n)). To be more
precise, the complexity of 'extract_tree' is ceil(log2(size(tree))),
because extract_tree keeps the tree complete. The function shuffle1'
invokes 'extract_tree' (n-1) times. Thus the overall complexity is
O(n*logn).
* A note on repeats in a sequence of random numbers
> > ...though you need to make sure that the randoms are all distinct,
> Linear congruential generators have that property. Since they are of
> the form x' <- (ax + b) mod m, you get a repeat only when the prng
> loops. So a long-period will generate numbers without repeats.
I'm afraid this is not true. Indeed, a linear congruential generator
repeats _completely_ after a period: that is sample[i] ==
sample[i+period] for _all_ i. That does not mean that a particular
sample cannot repeat within a period. Suppose we have a sequence of
random numbers uniformly distributed within [0..M-1]. If the i-th
sample has the value of x, the (i+1)-th sample may be x as well. The
probability of this event is the same as the probability of the
(i+1)-th sample being x+1 or any other given number within
[0..M-1]. Each sample in a sequence is chosen independently. The
sample of random numbers may contain subsequences (0,0,0,0) -- which
are just as likely as (1,2,3,4) or (3,1,4,1) or any other given
sequence of four values. In fact, this is one of the PRNG tests --
making sure that all the tuples (r1,r2) or (r1,r2,r3) appear equally
likely. The infamous rand() generator fails the triples test -- and
the generator was much maligned in the G.Forsythe, M.Malcolm, C.Moler
book. BTW, given a sequence of random numbers, the probability that
two consecutive numbers in the sequence are the same is 1/M. If we're
to shuffle a sequence of 1600 elements, we are interested in random
numbers distributed within [0..1599]. We need to draw at least 1599
elements to shuffle the sequence, i.e, 1598 pairs of consecutive
drawings. Given that the probability of two consecutive samples being
the same is 1/1600, we should rather expect to see one such pair. To
be precise, the probability of occurrence of such a pair is, by
binomial distribution, 1598*(1/1600)*(1599/1600)^1597, or approx
0.368.
-}
-- /////////////////////////////////////////////////////////////////////////////
|
gennady-em/haskel
|
src/P_Shuffle.hs
|
gpl-2.0
| 13,141
| 19
| 14
| 2,493
| 1,070
| 583
| 487
| 39
| 7
|
module Data.AtFieldTH (make) where
import qualified Data.Char as Char
import qualified Data.List as List
import Language.Haskell.TH.Syntax
make :: Name -> Q [Dec]
make typeName = do
TyConI typeCons <- reify typeName
(makeAtName, typeVars, ctor) <-
case typeCons of
DataD _ _ typeVars constructors _ ->
case constructors of
[ctor] -> return (makeAtNameForDataField, typeVars, ctor)
_ -> fail "one constructor expected for Data.AtFieldTH.make"
NewtypeD _ _ typeVars ctor _ -> return (makeAtNameForNewtype typeName, typeVars, ctor)
_ -> error $ show typeCons ++ " is not supported!"
return $ constructorAtFuncs makeAtName typeName typeVars ctor
constructorAtFuncs :: (Name -> Name) -> Name -> [TyVarBndr] -> Con -> [Dec]
constructorAtFuncs makeAtName typeName typeVars constructor =
concatMap (uncurry (fieldAtFunc makeAtName typeName typeVars isFreeVar)) fields
where
fields = constructorFields constructor
constructorVars = concatMap (List.nub . varsOfType . snd) fields
isFreeVar v = 1 == countElemRepetitions v constructorVars
constructorFields :: Con -> [(Name, Type)]
constructorFields (NormalC name [(_, t)]) = [(name, t)]
constructorFields (RecC _ fields) =
map f fields
where
f (name, _, t) = (name, t)
constructorFields _ = error "unsupported constructor for type supplied to Data.AtFieldTH.make"
countElemRepetitions :: Eq a => a -> [a] -> Int
countElemRepetitions x = length . filter (== x)
makeAtNameForNewtype :: Name -> Name -> Name
makeAtNameForNewtype newTypeName _ = mkName $ "at" ++ nameBase newTypeName
makeAtNameForDataField :: Name -> Name
makeAtNameForDataField fieldName =
mkName $ "at" ++ (Char.toUpper fieldNameHead : fieldNameTail)
where
fieldNameHead : fieldNameTail = nameBase fieldName
fieldAtFunc :: (Name -> Name) -> Name -> [TyVarBndr] -> (Name -> Bool) -> Name -> Type -> [Dec]
fieldAtFunc makeAtName typeName typeVars isFreeVar fieldName fieldType =
[ SigD resName . ForallT resultTypeVars [] $ foldr1 arrow
[ arrow (sideType fieldType "Src") (sideType fieldType "Dst")
, input
, output
]
, FunD resName [ Clause [VarP funcName, VarP valName] clause [] ]
]
where
arrow = AppT . AppT ArrowT
funcName = mkName "func"
valName = mkName "val"
resName = makeAtName fieldName
clause = NormalB $ RecUpdE (VarE valName) [(fieldName, applyExp)]
applyExp = AppE (VarE funcName) . AppE (VarE fieldName) $ VarE valName
valType = foldl AppT (ConT typeName) $ map (VarT . tyVarBndrName) typeVars
sideType t suffix = mapTypeVarNames (sideTypeVar suffix) t
fieldVars = List.nub (varsOfType fieldType)
sideTypeVar suffix name =
if isFreeVar name && elem name fieldVars
then mkName (nameBase name ++ suffix) else name
input = sideType valType "Src"
output = sideType valType "Dst"
resultTypeVars = map PlainTV . List.nub $ concatMap varsOfType [input, output]
tyVarBndrName :: TyVarBndr -> Name
tyVarBndrName (PlainTV name) = name
tyVarBndrName (KindedTV name _) = name
-- TODO [BP]: can boilerplate be reduced with SYB/uniplate ?
varsOfType :: Type -> [Name]
varsOfType (ForallT _ _ t) = varsOfType t -- TODO: dwa need todo something wrt the predicates?
varsOfType (VarT x) = [x]
varsOfType (ConT _) = []
varsOfType (TupleT _) = []
varsOfType ArrowT = []
varsOfType ListT = []
varsOfType (AppT x y) = varsOfType x ++ varsOfType y
varsOfType (SigT x _) = varsOfType x
-- TODO BP
mapTypeVarNames :: (Name -> Name) -> Type -> Type
mapTypeVarNames func (ForallT vars cxt t) =
ForallT vars (map (mapPredVarNames func) cxt) (mapTypeVarNames func t)
mapTypeVarNames func (VarT x) = VarT (func x)
mapTypeVarNames _ (ConT x) = ConT x
mapTypeVarNames _ (TupleT x) = TupleT x
mapTypeVarNames _ ArrowT = ArrowT
mapTypeVarNames _ ListT = ListT
mapTypeVarNames func (AppT x y) = AppT (mapTypeVarNames func x) (mapTypeVarNames func y)
mapTypeVarNames func (SigT t kind) = SigT (mapTypeVarNames func t) kind
-- TODO BP
mapPredVarNames :: (Name -> Name) -> Pred -> Pred
mapPredVarNames func (ClassP name types) = ClassP name $ map (mapTypeVarNames func) types
mapPredVarNames func (EqualP x y) = EqualP (mapTypeVarNames func x) (mapTypeVarNames func y)
|
alonho/bottle
|
src/Data/AtFieldTH.hs
|
gpl-3.0
| 4,418
| 0
| 15
| 986
| 1,488
| 761
| 727
| 83
| 4
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeApplication
, getApplicationDev
, makeFoundation
) where
import Import
import Settings
import Yesod.Auth
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Network.Wai.Middleware.RequestLogger
import qualified Database.Persist
import Database.Persist.Sql (runMigration)
import Network.HTTP.Conduit (newManager, def)
import Control.Monad.Logger (runLoggingT)
import System.IO (stdout)
import System.Log.FastLogger (mkLogger)
-- non scaffoled imports below
import System.Directory (getDirectoryContents)
import Data.Text (unpack, dropWhileEnd)
import Data.Text.Encoding (decodeUtf8)
import Data.IORef (newIORef)
import Data.List (isSuffixOf, head)
import System.FilePath (pathSeparator)
import qualified Data.Map as M
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base64.URL as B64
import Data.List.Split (chunksOf)
import Numeric (readHex)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Home
import Handler.RefString
import Handler.GithubWebHook
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeApplication :: AppConfig DefaultEnv Extra -> IO Application
makeApplication conf = do
foundation <- makeFoundation conf
-- Initialize the logging middleware
logWare <- mkRequestLogger def
{ outputFormat =
if development
then Detailed True
else Apache FromSocket
, destination = Logger $ appLogger foundation
}
-- Create the WAI application and apply middlewares
app <- toWaiAppPlain foundation
return $ logWare app
-- | Loads up any necessary settings, creates your foundation datatype, and
-- performs some initialization.
makeFoundation :: AppConfig DefaultEnv Extra -> IO App
makeFoundation conf = do
let qdfPath = unpack $ extraQdfPath (appExtra conf)
manager <- newManager def
static <- staticSite
fns <- getDirectoryContents qdfPath
qtfMap <- localFilesToMap readQtfFiles qdfPath ".qtf" fns >>= newIORef
qpfMap <- localFilesToMap readQpfFiles qdfPath ".qpf" fns >>= newIORef
dbCnf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf)
Database.Persist.loadConfig >>=
Database.Persist.applyEnv
poolCnf <- Database.Persist.createPoolConfig (dbCnf :: Settings.PersistConf)
logger <- mkLogger True stdout
let foundation = App manager logger conf static qtfMap qpfMap dbCnf poolCnf
-- Perform database migration using our application's logging settings.
runLoggingT
(Database.Persist.runPool dbCnf (runMigration migrateAll) poolCnf)
(messageLoggerSource foundation logger)
return foundation
where
localFilesToMap :: ([FilePath] -> IO [QLines a]) -> FilePath -> String -> [FilePath] -> IO (M.Map Text (QLines a))
localFilesToMap filesReader qdfPath ext fns =
let sfns = filter (isSuffixOf ext) fns in
let toPaths = map ((++) $ qdfPath ++ [pathSeparator]) in
let fileNameToID = (dropWhileEnd (== '=')) . decodeUtf8 . B64.encode . BS.pack .
(map (fst . head . readHex)) . (chunksOf 2 . take 16) in
{- let fileNameToID = decodeUtf8 . B64.encode . toLazyByteString . -- might work from bytestring-0.10.x -}
{- (foldr (<>) mempty) . (map (word8 . fromIntegral . digitToInt)) . (take 16) in-}
filesReader (toPaths sfns) >>= return . M.fromList . (zip (map fileNameToID sfns))
-- for yesod devel
getApplicationDev :: IO (Int, Application)
getApplicationDev =
defaultDevelApp loader makeApplication
where
loader = Yesod.Default.Config.loadConfig (configSettings Development)
{ csParseExtra = parseExtra
}
|
oqc/oqs
|
Application.hs
|
gpl-3.0
| 4,301
| 0
| 22
| 885
| 906
| 489
| 417
| -1
| -1
|
mu . bimap id mu . alpha = mu . bimap mu id
|
hmemcpy/milewski-ctfp-pdf
|
src/content/3.6/code/haskell/snippet12.hs
|
gpl-3.0
| 43
| 1
| 8
| 12
| 31
| 13
| 18
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
import Control.Lens
import Control.Monad
import Control.Monad.Trans (liftIO)
import Control.Monad.Trans.Either (EitherT(..))
import Control.Monad.Trans.Maybe
-- import Data.Attoparsec.Lazy
import qualified Data.Aeson.Generic as G
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Foldable (foldrM)
import Data.Maybe
import System.Environment
import System.IO
--
import HEP.Storage.WebDAV.CURL
import HEP.Storage.WebDAV.Type
-- import HEP.Storage.WebDAV.Util
import HEP.Util.Either
--
import HEP.Physics.Analysis.ATLAS.Common
import HEP.Physics.Analysis.ATLAS.SUSY.SUSY_0L2to6JMET_8TeV
import HEP.Physics.Analysis.Common.XSecNTotNum
import HEP.Util.Work
--
import Util
import Debug.Trace
import HROOT
data AnalysisType = MET | MEFF | RatioMET_MEFF | FirstLepPT | FirstJetPT deriving (Show)
-- |
getAnalysis :: AnalysisType -> WebDAVConfig -> WebDAVRemoteDir -> String
-> EitherT String IO [(Double, (Bool,Bool,Bool,Bool,Bool))]
getAnalysis MET = atlas_getMissingET
getAnalysis MEFF = atlas_getMeff
getAnalysis RatioMET_MEFF = atlas_getRatioMET_Meff
getAnalysis FirstLepPT = atlas_get1stLepPT
getAnalysis FirstJetPT = atlas_get1stJetPT
-- |
getAnalysisMinMaxX :: AnalysisType -> (Double,Double)
getAnalysisMinMaxX MET = (0,1000)
getAnalysisMinMaxX MEFF = (0,3000)
getAnalysisMinMaxX RatioMET_MEFF = (0,0.7)
getAnalysisMinMaxX FirstLepPT = (-10,500)
getAnalysisMinMaxX FirstJetPT = (0,1000)
-- |
luminosity :: Double
luminosity = 20300
-- data DataSet a where
-- Triple (Double,Double,Double) | Doublet (Double,Double)
createRdirBName_xqld procname (mg,mq,mn) =
let rdir = "montecarlo/admproject/XQLDdegen/8TeV/neutLOSP/scan_" ++ procname
basename = "ADMXQLD111degenMG"++ show mg++ "MQ" ++ show mq ++ "ML50000.0MN" ++ show mn ++ "_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set"
in (rdir,basename)
createRdirBName_xqldnoneut procname (mg,mq,mn) =
let rdir = "montecarlo/admproject/XQLDdegen/8TeV/scan_" ++ procname
basename = "ADMXQLD111degenMG"++ show mg++ "MQ" ++ show mq ++ "ML50000.0MN50000.0_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set"
in (rdir,basename)
createRdirBName_xudd procname (mg,mq,mn) =
let rdir = "montecarlo/admproject/XUDDdegen/8TeV/neutLOSP/scan_" ++ procname
basename = "ADMXUDD112degenMG"++ show mg++ "MQ" ++ show mq ++ "ML50000.0MN" ++ show mn ++ "_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set"
in (rdir,basename)
createRdirBName_xuddnoneut procname (mg,mq,mn) =
let rdir = "montecarlo/admproject/XUDDdegen/8TeV/scan_" ++ procname
basename = "ADMXUDD112degenMG"++ show mg++ "MQ" ++ show mq ++ "ML50000.0MN50000.0_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set"
in (rdir,basename)
createRdirBName_simplifiedsusy procname (mg,mq,mn) =
let rdir = "montecarlo/admproject/SimplifiedSUSY/8TeV/scan_" ++ procname
basename = "SimplifiedSUSYMN"++ show mn++ "MG" ++ show mg ++ "MSQ" ++ show mq ++ "_" ++ procname ++ "_LHC8ATLAS_NoMatch_NoCut_AntiKT0.4_NoTau_Set"
in (rdir,basename)
dirset_xqld = [ "2sg_2l8j2x"
, "sqsg_2l7j2x"
, "2sq_2l6j2x" ]
dirset_xqldnoneut = [ "2sg_2l4j2x"
, "2sq_oo_2l2j2x"
, "2sq_no_2l2j2x"
, "2sq_nn_2l2j2x"
, "sqsg_o_2l3j2x"
, "sqsg_n_2l3j2x"
]
dirset_xudd = [ "2sg_10j2x"
, "sqsg_9j2x"
, "2sq_8j2x"
]
dirset_xuddnoneut = [ "2sg_6j2x"
, "2sq_nn_4j2x"
, "2sq_no_4j2x"
, "2sq_oo_4j2x"
, "sqsg_n_5j2x"
, "sqsg_o_5j2x" ]
dirset_simplifiedsusy = [ "2sg_4j2n"
, "2sq_2j2n"
, "sqsg_3j2n" ]
getResult f (rdir,basename) = do
let nlst = [1]
fileWork f "config1.txt" rdir basename nlst
main = do
let -- set = [ (1000.0,1000.0, mn) | mn <- [100.0,300.0,500.0] ]
-- set' = [ (1500.0,1000.0,100.0) ]
-- set'' = [ (1500.0,1000.0,100.0), (1500.0,1000.0,300.0), (1500.0,1000.0,500.0) ]
-- set_xudd_sq = [ (2500.0,1500.0,50000.0) ]
-- set_smpl_sq = [ (2500.0,1500.0, mn) | mn <- [100.0,300.0,500.0] ]
set_xudd_neut = [ (1000.0,1000.0,mn) | mn <- [100.0, 300.0, 500.0] ]
set_smpl_neut = [ (1000.0,1000.0, mn) | mn <- [100.0,300.0,500.0] ]
-- mapM_ (mainAnalysis FirstLepPT createRdirBName_xqld dirset_xqld) set -- set'
-- mapM_ (mainAnalysis FirstLepPT createRdirBName_simplifiedsusy dirset_simplifiedsusy) set -- set''
-- mapM_ (mainAnalysis MET createRdirBName_xuddnoneut dirset_xuddnoneut) set_xudd_sq
-- mapM_ (mainAnalysis MET createRdirBName_simplifiedsusy dirset_simplifiedsusy) set_smpl_sq
-- mapM_ (mainAnalysis MET createRdirBName_xudd dirset_xudd) set_xudd_neut
-- mapM_ (mainAnalysis MET createRdirBName_simplifiedsusy dirset_simplifiedsusy) set_smpl_neut
-- mapM_ (mainAnalysis MEFF createRdirBName_xuddnoneut dirset_xuddnoneut) set_xudd_sq
-- mapM_ (mainAnalysis MEFF createRdirBName_simplifiedsusy dirset_simplifiedsusy) set_smpl_sq
-- mapM_ (mainAnalysis MEFF createRdirBName_xudd dirset_xudd) set_xudd_neut
-- mapM_ (mainAnalysis MEFF createRdirBName_simplifiedsusy dirset_simplifiedsusy) set_smpl_neut
-- mapM_ (mainAnalysis RatioMET_MEFF createRdirBName_xuddnoneut dirset_xuddnoneut) set_xudd_sq
-- mapM_ (mainAnalysis RatioMET_MEFF createRdirBName_simplifiedsusy dirset_simplifiedsusy) set_smpl_sq
mapM_ (mainAnalysis RatioMET_MEFF createRdirBName_xudd dirset_xudd) set_xudd_neut
mapM_ (mainAnalysis RatioMET_MEFF createRdirBName_simplifiedsusy dirset_simplifiedsusy) set_smpl_neut
-- mainAnalysis MET createRdirBName_xqldnoneut dirset_xqldnoneut (mg,mq,mn)
-- mapM_ (mainAnalysis MET createRdirBName_simplifiedsusy dirset_simplifiedsusy) set -- (mg,mq,mn)
-- mapM_ (mainAnalysis MET createRdirBName_xuddnoneut dirset_xuddnoneut) set'
-- mapM_ (mainAnalysis MET createRdirBName_xqld dirset_xqld) set
-- mapM_ (mainAnalysis MEFF createRdirBName_xuddnoneut dirset_xuddnoneut) set'
mapM_ (mainAnalysis RatioMET_MEFF createRdirBName_xuddnoneut dirset_xuddnoneut) set'
-- mapM_ (mainAnalysis RatioMET_MEFF createRdirBName_simplifiedsusy dirset_simplifiedsusy) set
-- mainAnalysis FirstLepPT createRdirBName_xqld dirset_xqld (mg,mq,mn)
-- mainAnalysis FirstJetPT createRdirBName_xudd dirset_xudd (mg,mq,mn)
-- mainAnalysis FirstJetPT createRdirBName_simplifiedsusy dirset_simplifiedsusy (mg,mq,mn)
-- mapM_ (mainAnalysisNJet createRdirBName_xuddnoneut dirset_xuddnoneut) set_xudd_sq
-- mapM_ (mainAnalysisNJet createRdirBName_simplifiedsusy dirset_simplifiedsusy) set_smpl_sq
-- mapM_ (mainAnalysisNJet createRdirBName_xudd dirset_xudd) set_xudd_neut
-- mapM_ (mainAnalysisNJet createRdirBName_simplifiedsusy dirset_simplifiedsusy) set_smpl_neut
-- mapM_ (mainAnalysisNJet createRdirBName_simplifiedsusy dirset_simplifiedsusy) set
-- mapM_ (mainAnalysisNJet createRdirBName_xuddnoneut dirset_xuddnoneut) set'
-- |
mainAnalysis :: AnalysisType
-> (String -> (Double,Double,Double) -> (String,String))
-> [String]
-> (Double,Double,Double)
-> IO ()
mainAnalysis analtype rdirbnamefunc dirset (mg,mq,mn) = do
let (minx,maxx) = getAnalysisMinMaxX analtype; nchan = 51
(_,bname') = rdirbnamefunc "total" (mg,mq,mn)
tfile <- newTFile (bname' ++ "_" ++ show analtype ++ ".root") "NEW" "" 1
ha <- newTH1F "2jet" "2jet" nchan minx maxx
hb <- newTH1F "3jet" "3jet" nchan minx maxx
hc <- newTH1F "4jet" "4jet" nchan minx maxx
hd <- newTH1F "5jet" "5jet" nchan minx maxx
he <- newTH1F "6jet" "6jet" nchan minx maxx
r <- runEitherT $ mapM_ (\x -> countEvent analtype rdirbnamefunc (mg,mq,mn) x (ha,hb,hc,hd,he)) dirset
mapM_ (\x->write x "" 0 0) [ha,hb,hc,hd,he]
close tfile ""
case r of
Left err -> putStrLn err
Right _ -> return ()
mainAnalysisNJet :: (String -> (Double,Double,Double) -> (String,String))
-> [String]
-> (Double,Double,Double)
-> IO ()
mainAnalysisNJet rdirbnamefunc dirset (mg,mq,mn) = do
let minx = -0.5; maxx = 9.5; nchan = 10
(_,bname') = rdirbnamefunc "total" (mg,mq,mn)
tfile <- newTFile (bname' ++ "_NJet.root") "NEW" "" 1
hist <- newTH1F "NJet" "NJet" nchan minx maxx
r <- runEitherT $ mapM_ (\x -> countNJetEvent rdirbnamefunc (mg,mq,mn) x hist) dirset
write hist "" 0 0
close tfile ""
case r of
Left err -> putStrLn err
Right _ -> return ()
getXsec :: WebDAVConfig -> WebDAVRemoteDir -> String -> EitherT String IO CrossSectionAndCount
getXsec wdavcfg wdavrdir bname = do
let fp2 = bname ++ "_total_count.json"
guardEitherM (show wdavrdir ++ "/" ++ fp2 ++ " not exist!") (doesFileExistInDAV wdavcfg wdavrdir fp2)
(_,mr2) <- liftIO (downloadFile True wdavcfg wdavrdir fp2)
r2 <- (liftM LB.pack . EitherT . return . maybeToEither (fp2 ++ " is not downloaded ")) mr2
(xsec :: CrossSectionAndCount) <- (EitherT . return . maybeToEither (fp2 ++ " JSON cannot be decoded") . G.decode) r2
return xsec
countEvent :: AnalysisType
-> (String -> (Double,Double,Double) -> (String,String))
-> (Double,Double,Double)
-> String
-> (TH1F, TH1F, TH1F, TH1F, TH1F)
-> EitherT String IO ()
countEvent analtype rdirbnamefunc (mg,mq,mn) str (ha,hb,hc,hd,he) = do
let (rdir,bname) = rdirbnamefunc str (mg,mq,mn)
xsec <- singleWork getXsec "config1.txt" rdir bname 1
let weight = crossSectionInPb xsec * luminosity / fromIntegral (numberOfEvent xsec)
--
let fillfunc :: Double -> (Double,(Bool,Bool,Bool,Bool,Bool)) -> IO ()
fillfunc w (x,sr) = do
when (view _1 sr) (fill1w ha x w >> return ())
when (view _2 sr) (fill1w hb x w >> return ())
when (view _3 sr) (fill1w hc x w >> return ())
when (view _4 sr) (fill1w hd x w >> return ())
when (view _5 sr) (fill1w he x w >> return ())
r <- getCount analtype (rdir,bname)
-- liftIO $ print r
liftIO ( mapM_ (fillfunc weight) r )
-- liftIO $ (mapM_ print r )
countNJetEvent :: (String -> (Double,Double,Double) -> (String,String))
-> (Double,Double,Double)
-> String
-> TH1F
-> EitherT String IO ()
countNJetEvent rdirbnamefunc (mg,mq,mn) str hist = do
let (rdir,bname) = rdirbnamefunc str (mg,mq,mn)
xsec <- singleWork getXsec "config1.txt" rdir bname 1
let weight = crossSectionInPb xsec * luminosity / fromIntegral (numberOfEvent xsec)
r <- getNJetCount (rdir,bname)
-- liftIO $ print r
liftIO ( mapM_ (\x->fill1w hist (fromIntegral x) weight) r )
-- liftIO $ (mapM_ print r )
getCount :: AnalysisType -> (String,String) -> EitherT String IO [(Double,(Bool,Bool,Bool,Bool,Bool))]
getCount analtype (rdir,basename) = do
let nlst = [1]
rs <- fileWork (getAnalysis analtype) "config1.txt" rdir basename nlst
liftIO $ print (length (head rs))
return (concat rs)
getNJetCount :: (String,String) -> EitherT String IO [Int]
getNJetCount (rdir,basename) = do
let nlst = [1]
rs <- fileWork atlas_getNJet "config1.txt" rdir basename nlst
liftIO $ print (length (head rs))
return (concat rs)
|
wavewave/lhc-analysis-collection
|
analysis/histograms_ATLAS0L2to6JMET_8TeV.hs
|
gpl-3.0
| 11,615
| 0
| 17
| 2,400
| 2,886
| 1,552
| 1,334
| 177
| 2
|
--
-- Environment is formed via evaluation of definitions. This module
-- describes minimal MIDA environment in form of monad transformer.
--
-- Copyright © 2014–2017 Mark Karpov
--
-- MIDA 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.
--
-- MIDA is distributed in the hope that it will be useful, but WITHOUT ANY
-- WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
-- details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Mida.Language.Environment
( MidaEnv
, HasEnv (..)
, runMidaEnv
, addDef
, remDef
, clearDefs
, getPrin
, getSrc
, fullSrc
, getRefs
, purgeEnv
, checkRecur )
where
import Control.Applicative (empty)
import Control.Arrow ((***), (>>>))
import Control.Monad.Catch (MonadThrow, MonadCatch, MonadMask)
import Control.Monad.Reader
import Control.Monad.State.Class
import Control.Monad.State.Strict
import Data.Map (Map)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import Data.Text.Lazy (Text)
import Mida.Language.SyntaxTree
import Mida.Representation.Base (noteAlias, modifiers)
import Mida.Representation.Show (showDefinition)
import Numeric.Natural
import System.Console.Haskeline.MonadException
import System.Random (split)
import System.Random.TF (TFGen, mkTFGen)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as M
-- | MIDA environment state. Basically this amounts to collection of
-- definitions and random number generator.
data MidaEnvSt = MidaEnvSt
{ meDefs :: Defs -- ^ Collection of definitions
, meRandGen :: TFGen -- ^ Random generator
} deriving Show
-- | Type synonym for collection of definitions, where a definition is a
-- pair of variable name and corresponding AST.
type Defs = Map String SyntaxTree
-- | Monad that implements MIDA environment.
newtype MidaEnv m a = MidaEnv
{ unMidaEnv :: StateT MidaEnvSt m a }
deriving ( Functor
, Applicative
, Monad
, MonadIO
, MonadState MidaEnvSt
, MonadException
, MonadThrow
, MonadCatch
, MonadMask )
-- | Type class for things that can be considered MIDA environment.
class Monad m => HasEnv m where
-- | Get collection of all definitions.
getDefs :: m Defs
-- | Update definitions with given ones.
setDefs :: Defs -> m ()
-- | Set random generator seed.
setRandGen :: Natural -> m ()
-- | Split current random generator, update it, and return new one.
newRandGen :: m TFGen
instance Monad m => HasEnv (MidaEnv m) where
getDefs = gets meDefs
setDefs defs = modify $ \env -> env { meDefs = defs }
setRandGen gen = modify $ \e -> e { meRandGen = mkTFGen (fromIntegral gen) }
newRandGen = do
(g, g') <- split <$> gets meRandGen
modify $ \e -> e { meRandGen = g' }
return g
instance HasEnv m => HasEnv (StateT e m) where
getDefs = lift getDefs
setDefs = lift . setDefs
setRandGen = lift . setRandGen
newRandGen = lift newRandGen
instance HasEnv m => HasEnv (ReaderT e m) where
getDefs = lift getDefs
setDefs = lift . setDefs
setRandGen = lift . setRandGen
newRandGen = lift newRandGen
-- | Run state monad with MIDA environment.
runMidaEnv :: Monad m => MidaEnv m a -> m a
runMidaEnv m = evalStateT (unMidaEnv m) MidaEnvSt
{ meDefs = defaultDefs
, meRandGen = mkTFGen 0 }
-- | Default definitions in MIDA environment.
defaultDefs :: Defs
defaultDefs = M.fromList $
zip noteAlias (f <$> [0..]) <>
zip modifiers (f <$> [128,256..])
where f = pure . Value
-- | Add a new definition to the environment.
addDef :: HasEnv m
=> String -- ^ Reference name
-> SyntaxTree -- ^ AST of its principle
-> m ()
addDef name tree = getDefs >>= setDefs . M.insert name tree
-- | Remove definition given its name.
remDef :: HasEnv m
=> String -- ^ Reference name
-> m ()
remDef name = getDefs >>= setDefs . M.delete name
-- | Remove all definitions, restoring default state of environment.
clearDefs :: HasEnv m => m ()
clearDefs = setDefs defaultDefs
-- | Get principle corresponding to given variable name.
getPrin :: HasEnv m
=> String -- ^ Reference name
-> m SyntaxTree -- ^ Syntax tree
getPrin name = (fromMaybe [] . M.lookup name) <$> getDefs
-- | Get source code of definition given its name.
getSrc :: HasEnv m
=> String -- ^ Reference name
-> m Text -- ^ Textual representation of source code
getSrc name = showDefinition name <$> getPrin name
-- | Reconstruct source code for all existing definitions.
fullSrc :: HasEnv m => m Text
fullSrc = (M.foldMapWithKey showDefinition . (M.\\ defaultDefs)) <$> getDefs
-- | Get all reference names defined at the moment.
getRefs :: HasEnv m => m [String]
getRefs = M.keys <$> getDefs
-- | This performs “definition traversal” and returns collection of
-- definition names that given reference name depends on.
tDefs
:: String -- ^ Reference name
-> Defs -- ^ Definitions
-> [String] -- ^ Collection of definition names
tDefs name defs = maybe empty cm (name `M.lookup` defs)
where cm = (>>= f)
f (Value _) = mempty
f (Section x) = cm x
f (Multi x) = cm x
f (CMulti x) = NE.toList x >>= (cm *** cm >>> uncurry (<>))
f (Reference x) = return x <> tDefs x defs
f (Range _ _) = mempty
f (Product x y) = f x <> f y
f (Division x y) = f x <> f y
f (Sum x y) = f x <> f y
f (Diff x y) = f x <> f y
f (Loop x y) = f x <> f y
f (Rotation x y) = f x <> f y
f (Reverse x) = f x
-- | Purge environment removing definitions that are not used in
-- construction of “top-level” definitions.
purgeEnv :: HasEnv m
=> [String] -- ^ Top-level definitions
-> m ()
purgeEnv tops = getDefs >>= setDefs . f
where f defs = M.intersection defs (M.unions [ts, ms defs, defaultDefs])
ms = M.unions . fmap toDefs . zipWith tDefs tops . repeat
ts = toDefs tops
-- | Check if definition with given name is depends on itself.
checkRecur :: HasEnv m
=> String -- ^ Reference name
-> SyntaxTree -- ^ Its syntax tree
-> m Bool
checkRecur name tree = check <$> getDefs
where check = elem name . tDefs name . M.insert name tree
-- | Turn collection of definition names into collection of empty
-- definitions.
toDefs :: [String] -> Defs
toDefs = M.fromList . fmap (, [])
|
mrkkrp/mida
|
src/Mida/Language/Environment.hs
|
gpl-3.0
| 6,930
| 0
| 12
| 1,706
| 1,675
| 912
| 763
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.TPU.Projects.Locations.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists information about the supported locations for this service.
--
-- /See:/ <https://cloud.google.com/tpu/ Cloud TPU API Reference> for @tpu.projects.locations.list@.
module Network.Google.Resource.TPU.Projects.Locations.List
(
-- * REST Resource
ProjectsLocationsListResource
-- * Creating a Request
, projectsLocationsList
, ProjectsLocationsList
-- * Request Lenses
, pllXgafv
, pllUploadProtocol
, pllAccessToken
, pllUploadType
, pllName
, pllFilter
, pllPageToken
, pllPageSize
, pllCallback
) where
import Network.Google.Prelude
import Network.Google.TPU.Types
-- | A resource alias for @tpu.projects.locations.list@ method which the
-- 'ProjectsLocationsList' request conforms to.
type ProjectsLocationsListResource =
"v1" :>
Capture "name" Text :>
"locations" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListLocationsResponse
-- | Lists information about the supported locations for this service.
--
-- /See:/ 'projectsLocationsList' smart constructor.
data ProjectsLocationsList =
ProjectsLocationsList'
{ _pllXgafv :: !(Maybe Xgafv)
, _pllUploadProtocol :: !(Maybe Text)
, _pllAccessToken :: !(Maybe Text)
, _pllUploadType :: !(Maybe Text)
, _pllName :: !Text
, _pllFilter :: !(Maybe Text)
, _pllPageToken :: !(Maybe Text)
, _pllPageSize :: !(Maybe (Textual Int32))
, _pllCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pllXgafv'
--
-- * 'pllUploadProtocol'
--
-- * 'pllAccessToken'
--
-- * 'pllUploadType'
--
-- * 'pllName'
--
-- * 'pllFilter'
--
-- * 'pllPageToken'
--
-- * 'pllPageSize'
--
-- * 'pllCallback'
projectsLocationsList
:: Text -- ^ 'pllName'
-> ProjectsLocationsList
projectsLocationsList pPllName_ =
ProjectsLocationsList'
{ _pllXgafv = Nothing
, _pllUploadProtocol = Nothing
, _pllAccessToken = Nothing
, _pllUploadType = Nothing
, _pllName = pPllName_
, _pllFilter = Nothing
, _pllPageToken = Nothing
, _pllPageSize = Nothing
, _pllCallback = Nothing
}
-- | V1 error format.
pllXgafv :: Lens' ProjectsLocationsList (Maybe Xgafv)
pllXgafv = lens _pllXgafv (\ s a -> s{_pllXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pllUploadProtocol :: Lens' ProjectsLocationsList (Maybe Text)
pllUploadProtocol
= lens _pllUploadProtocol
(\ s a -> s{_pllUploadProtocol = a})
-- | OAuth access token.
pllAccessToken :: Lens' ProjectsLocationsList (Maybe Text)
pllAccessToken
= lens _pllAccessToken
(\ s a -> s{_pllAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pllUploadType :: Lens' ProjectsLocationsList (Maybe Text)
pllUploadType
= lens _pllUploadType
(\ s a -> s{_pllUploadType = a})
-- | The resource that owns the locations collection, if applicable.
pllName :: Lens' ProjectsLocationsList Text
pllName = lens _pllName (\ s a -> s{_pllName = a})
-- | A filter to narrow down results to a preferred subset. The filtering
-- language accepts strings like \"displayName=tokyo\", and is documented
-- in more detail in [AIP-160](https:\/\/google.aip.dev\/160).
pllFilter :: Lens' ProjectsLocationsList (Maybe Text)
pllFilter
= lens _pllFilter (\ s a -> s{_pllFilter = a})
-- | A page token received from the \`next_page_token\` field in the
-- response. Send that page token to receive the subsequent page.
pllPageToken :: Lens' ProjectsLocationsList (Maybe Text)
pllPageToken
= lens _pllPageToken (\ s a -> s{_pllPageToken = a})
-- | The maximum number of results to return. If not set, the service selects
-- a default.
pllPageSize :: Lens' ProjectsLocationsList (Maybe Int32)
pllPageSize
= lens _pllPageSize (\ s a -> s{_pllPageSize = a}) .
mapping _Coerce
-- | JSONP
pllCallback :: Lens' ProjectsLocationsList (Maybe Text)
pllCallback
= lens _pllCallback (\ s a -> s{_pllCallback = a})
instance GoogleRequest ProjectsLocationsList where
type Rs ProjectsLocationsList = ListLocationsResponse
type Scopes ProjectsLocationsList =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsLocationsList'{..}
= go _pllName _pllXgafv _pllUploadProtocol
_pllAccessToken
_pllUploadType
_pllFilter
_pllPageToken
_pllPageSize
_pllCallback
(Just AltJSON)
tPUService
where go
= buildClient
(Proxy :: Proxy ProjectsLocationsListResource)
mempty
|
brendanhay/gogol
|
gogol-tpu/gen/Network/Google/Resource/TPU/Projects/Locations/List.hs
|
mpl-2.0
| 6,057
| 0
| 19
| 1,439
| 962
| 556
| 406
| 133
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.GamesConfiguration.LeaderboardConfigurations.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves the metadata of the leaderboard configuration with the given
-- ID.
--
-- /See:/ <https://developers.google.com/games/services Google Play Game Services Publishing API Reference> for @gamesConfiguration.leaderboardConfigurations.get@.
module Network.Google.Resource.GamesConfiguration.LeaderboardConfigurations.Get
(
-- * REST Resource
LeaderboardConfigurationsGetResource
-- * Creating a Request
, leaderboardConfigurationsGet
, LeaderboardConfigurationsGet
-- * Request Lenses
, lcgLeaderboardId
) where
import Network.Google.GamesConfiguration.Types
import Network.Google.Prelude
-- | A resource alias for @gamesConfiguration.leaderboardConfigurations.get@ method which the
-- 'LeaderboardConfigurationsGet' request conforms to.
type LeaderboardConfigurationsGetResource =
"games" :>
"v1configuration" :>
"leaderboards" :>
Capture "leaderboardId" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] LeaderboardConfiguration
-- | Retrieves the metadata of the leaderboard configuration with the given
-- ID.
--
-- /See:/ 'leaderboardConfigurationsGet' smart constructor.
newtype LeaderboardConfigurationsGet = LeaderboardConfigurationsGet'
{ _lcgLeaderboardId :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'LeaderboardConfigurationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcgLeaderboardId'
leaderboardConfigurationsGet
:: Text -- ^ 'lcgLeaderboardId'
-> LeaderboardConfigurationsGet
leaderboardConfigurationsGet pLcgLeaderboardId_ =
LeaderboardConfigurationsGet'
{ _lcgLeaderboardId = pLcgLeaderboardId_
}
-- | The ID of the leaderboard.
lcgLeaderboardId :: Lens' LeaderboardConfigurationsGet Text
lcgLeaderboardId
= lens _lcgLeaderboardId
(\ s a -> s{_lcgLeaderboardId = a})
instance GoogleRequest LeaderboardConfigurationsGet
where
type Rs LeaderboardConfigurationsGet =
LeaderboardConfiguration
type Scopes LeaderboardConfigurationsGet =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient LeaderboardConfigurationsGet'{..}
= go _lcgLeaderboardId (Just AltJSON)
gamesConfigurationService
where go
= buildClient
(Proxy :: Proxy LeaderboardConfigurationsGetResource)
mempty
|
rueshyna/gogol
|
gogol-games-configuration/gen/Network/Google/Resource/GamesConfiguration/LeaderboardConfigurations/Get.hs
|
mpl-2.0
| 3,341
| 0
| 12
| 684
| 301
| 186
| 115
| 52
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AppEngine.Apps.DomainMAppings.Patch
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Updates the specified domain mapping. To map an SSL certificate to a
-- domain mapping, update certificate_id to point to an
-- AuthorizedCertificate resource. A user must be authorized to administer
-- the associated domain in order to update a DomainMapping resource.
--
-- /See:/ <https://cloud.google.com/appengine/docs/admin-api/ App Engine Admin API Reference> for @appengine.apps.domainMappings.patch@.
module Network.Google.Resource.AppEngine.Apps.DomainMAppings.Patch
(
-- * REST Resource
AppsDomainMAppingsPatchResource
-- * Creating a Request
, appsDomainMAppingsPatch
, AppsDomainMAppingsPatch
-- * Request Lenses
, admapXgafv
, admapUploadProtocol
, admapUpdateMask
, admapAccessToken
, admapUploadType
, admapPayload
, admapAppsId
, admapDomainMAppingsId
, admapCallback
) where
import Network.Google.AppEngine.Types
import Network.Google.Prelude
-- | A resource alias for @appengine.apps.domainMappings.patch@ method which the
-- 'AppsDomainMAppingsPatch' request conforms to.
type AppsDomainMAppingsPatchResource =
"v1" :>
"apps" :>
Capture "appsId" Text :>
"domainMappings" :>
Capture "domainMappingsId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "updateMask" GFieldMask :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] DomainMApping :>
Patch '[JSON] Operation
-- | Updates the specified domain mapping. To map an SSL certificate to a
-- domain mapping, update certificate_id to point to an
-- AuthorizedCertificate resource. A user must be authorized to administer
-- the associated domain in order to update a DomainMapping resource.
--
-- /See:/ 'appsDomainMAppingsPatch' smart constructor.
data AppsDomainMAppingsPatch =
AppsDomainMAppingsPatch'
{ _admapXgafv :: !(Maybe Xgafv)
, _admapUploadProtocol :: !(Maybe Text)
, _admapUpdateMask :: !(Maybe GFieldMask)
, _admapAccessToken :: !(Maybe Text)
, _admapUploadType :: !(Maybe Text)
, _admapPayload :: !DomainMApping
, _admapAppsId :: !Text
, _admapDomainMAppingsId :: !Text
, _admapCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AppsDomainMAppingsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'admapXgafv'
--
-- * 'admapUploadProtocol'
--
-- * 'admapUpdateMask'
--
-- * 'admapAccessToken'
--
-- * 'admapUploadType'
--
-- * 'admapPayload'
--
-- * 'admapAppsId'
--
-- * 'admapDomainMAppingsId'
--
-- * 'admapCallback'
appsDomainMAppingsPatch
:: DomainMApping -- ^ 'admapPayload'
-> Text -- ^ 'admapAppsId'
-> Text -- ^ 'admapDomainMAppingsId'
-> AppsDomainMAppingsPatch
appsDomainMAppingsPatch pAdmapPayload_ pAdmapAppsId_ pAdmapDomainMAppingsId_ =
AppsDomainMAppingsPatch'
{ _admapXgafv = Nothing
, _admapUploadProtocol = Nothing
, _admapUpdateMask = Nothing
, _admapAccessToken = Nothing
, _admapUploadType = Nothing
, _admapPayload = pAdmapPayload_
, _admapAppsId = pAdmapAppsId_
, _admapDomainMAppingsId = pAdmapDomainMAppingsId_
, _admapCallback = Nothing
}
-- | V1 error format.
admapXgafv :: Lens' AppsDomainMAppingsPatch (Maybe Xgafv)
admapXgafv
= lens _admapXgafv (\ s a -> s{_admapXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
admapUploadProtocol :: Lens' AppsDomainMAppingsPatch (Maybe Text)
admapUploadProtocol
= lens _admapUploadProtocol
(\ s a -> s{_admapUploadProtocol = a})
-- | Required. Standard field mask for the set of fields to be updated.
admapUpdateMask :: Lens' AppsDomainMAppingsPatch (Maybe GFieldMask)
admapUpdateMask
= lens _admapUpdateMask
(\ s a -> s{_admapUpdateMask = a})
-- | OAuth access token.
admapAccessToken :: Lens' AppsDomainMAppingsPatch (Maybe Text)
admapAccessToken
= lens _admapAccessToken
(\ s a -> s{_admapAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
admapUploadType :: Lens' AppsDomainMAppingsPatch (Maybe Text)
admapUploadType
= lens _admapUploadType
(\ s a -> s{_admapUploadType = a})
-- | Multipart request metadata.
admapPayload :: Lens' AppsDomainMAppingsPatch DomainMApping
admapPayload
= lens _admapPayload (\ s a -> s{_admapPayload = a})
-- | Part of \`name\`. Name of the resource to update. Example:
-- apps\/myapp\/domainMappings\/example.com.
admapAppsId :: Lens' AppsDomainMAppingsPatch Text
admapAppsId
= lens _admapAppsId (\ s a -> s{_admapAppsId = a})
-- | Part of \`name\`. See documentation of \`appsId\`.
admapDomainMAppingsId :: Lens' AppsDomainMAppingsPatch Text
admapDomainMAppingsId
= lens _admapDomainMAppingsId
(\ s a -> s{_admapDomainMAppingsId = a})
-- | JSONP
admapCallback :: Lens' AppsDomainMAppingsPatch (Maybe Text)
admapCallback
= lens _admapCallback
(\ s a -> s{_admapCallback = a})
instance GoogleRequest AppsDomainMAppingsPatch where
type Rs AppsDomainMAppingsPatch = Operation
type Scopes AppsDomainMAppingsPatch =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient AppsDomainMAppingsPatch'{..}
= go _admapAppsId _admapDomainMAppingsId _admapXgafv
_admapUploadProtocol
_admapUpdateMask
_admapAccessToken
_admapUploadType
_admapCallback
(Just AltJSON)
_admapPayload
appEngineService
where go
= buildClient
(Proxy :: Proxy AppsDomainMAppingsPatchResource)
mempty
|
brendanhay/gogol
|
gogol-appengine/gen/Network/Google/Resource/AppEngine/Apps/DomainMAppings/Patch.hs
|
mpl-2.0
| 6,796
| 0
| 20
| 1,527
| 945
| 551
| 394
| 140
| 1
|
import Char
resource = plugin {
stringProcessor = map toUpper
}
|
Changaco/haskell-plugins
|
testsuite/shell/simple/Plugin.hs
|
lgpl-2.1
| 73
| 0
| 7
| 20
| 20
| 11
| 9
| 3
| 1
|
import Chain
import Control.Concurrent.STM
main :: IO ()
main = do
chain <- newTVarIO ([] :: [String])
atomically $ addTransaction chain "My transaction"
atomically $ chain `addTransaction` "My transaction1"
atomically $ addTransaction chain "My transaction2"
transactions <- atomically $ readTVar chain
print transactions
chain' <- atomically makeChain
atomically $ addTransaction chain' "My transaction"
atomically $ addTransaction chain' "My transaction1"
transactions' <- atomically $ getTransactions chain
print transactions'
|
mreluzeon/block-monad
|
examples/chain_example.hs
|
lgpl-3.0
| 555
| 0
| 10
| 91
| 157
| 72
| 85
| 15
| 1
|
-- |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 800
{-# LANGUAGE UndecidableSuperClasses #-}
{-# LANGUAGE FlexibleInstances #-}
#endif
module WebApi.Docs
( WebApiDocs (..)
, ApiDocs (..)
, Docs
, FName
, Rec(..), nil
, ResourceDoc (..)
, DocField
, (:-)
, bodyDocs
, docs
, field
, nested
, (-:)
, docSummary
, nestedSummary
, nestedDocs
, f
) where
import WebApi.Contract
import Data.Proxy
import GHC.Generics
import GHC.TypeLits
import GHC.Exts
#if __GLASGOW_HASKELL__ >= 800
import GHC.OverloadedLabels
#endif
import Data.Text
import Data.String
import Language.Haskell.TH.Quote
import Language.Haskell.TH
class (WebApi p) => WebApiDocs (p :: *) where
type DocumentedApis p :: [*]
data ResourceDoc m r = ResourceDoc
deriving (Generic)
class ApiContract p m r => ApiDocs (p :: *) (m :: *) (r :: *) where
apiDocs :: Proxy p -> Proxy (Request m r) -> Docs (ResourceDoc m r)
default apiDocs :: Generic (ResourceDoc m r) => Proxy p -> Proxy (Request m r) -> Docs (ResourceDoc m r)
apiDocs _ _ = docs "" nil
queryParamDocs :: Generic (QueryParam m r) => Proxy p -> Proxy (Request m r) -> Docs (QueryParam m r)
default queryParamDocs :: Generic (QueryParam m r) => Proxy p -> Proxy (Request m r) -> Docs (QueryParam m r)
queryParamDocs _ _ = docs "" nil
formParamDocs :: Generic (FormParam m r) => Proxy p -> Proxy (Request m r) -> Docs (FormParam m r)
default formParamDocs :: Generic (FormParam m r) => Proxy p -> Proxy (Request m r) -> Docs (FormParam m r)
formParamDocs _ _ = docs "" nil
fileParamDocs :: Generic (FileParam m r) => Proxy p -> Proxy (Request m r) -> Docs (FileParam m r)
default fileParamDocs :: Generic (FileParam m r) => Proxy p -> Proxy (Request m r) -> Docs (FileParam m r)
fileParamDocs _ _ = docs "" nil
headerInDocs :: Generic (HeaderIn m r) => Proxy p -> Proxy (Request m r) -> Docs (HeaderIn m r)
default headerInDocs :: Generic (HeaderIn m r) => Proxy p -> Proxy (Request m r) -> Docs (HeaderIn m r)
headerInDocs _ _ = docs "" nil
cookieInDocs :: Generic (CookieIn m r) => Proxy p -> Proxy (Request m r) -> Docs (CookieIn m r)
default cookieInDocs :: Generic (CookieIn m r) => Proxy p -> Proxy (Request m r) -> Docs (CookieIn m r)
cookieInDocs _ _ = docs "" nil
apiOutDocs :: Generic (ApiOut m r) => Proxy p -> Proxy (Request m r) -> Docs (ApiOut m r)
default apiOutDocs :: Generic (ApiOut m r) => Proxy p -> Proxy (Request m r) -> Docs (ApiOut m r)
apiOutDocs _ _ = docs "" nil
apiErrDocs :: Generic (ApiErr m r) => Proxy p -> Proxy (Request m r) -> Docs (ApiErr m r)
default apiErrDocs :: Generic (ApiErr m r) => Proxy p -> Proxy (Request m r) -> Docs (ApiErr m r)
apiErrDocs _ _ = docs "" nil
headerOutDocs :: Generic (HeaderOut m r) => Proxy p -> Proxy (Request m r) -> Docs (HeaderOut m r)
default headerOutDocs :: Generic (HeaderOut m r) => Proxy p -> Proxy (Request m r) -> Docs (HeaderOut m r)
headerOutDocs _ _ = docs "" nil
cookieOutDocs :: Generic (CookieOut m r) => Proxy p -> Proxy (Request m r) -> Docs (CookieOut m r)
default cookieOutDocs :: Generic (CookieOut m r) => Proxy p -> Proxy (Request m r) -> Docs (CookieOut m r)
cookieOutDocs _ _ = docs "" nil
reqBodyDocs :: All1 Generic (RequestBody m r) => Proxy p -> Proxy (Request m r) -> ReqBodyDoc (RequestBody m r)
default reqBodyDocs :: ( EmptyReqBodyDoc (RequestBody m r)
, All1 Generic (RequestBody m r)
) => Proxy p -> Proxy (Request m r) -> ReqBodyDoc (RequestBody m r)
reqBodyDocs _ _ = emptyBodyDoc Proxy
type family All1 (c :: * -> Constraint) (xs :: [*]) :: Constraint where
All1 c (x ': xs) = (c x, All1 c xs)
All1 c '[] = ()
data ReqBodyDoc (bodies :: [*]) = ReqBodyDoc (Rec Docs bodies)
bodyDocs :: Rec (DocField body) xs -> ReqBodyDoc '[body]
bodyDocs bdocs = ReqBodyDoc (docs "" bdocs :& nil)
class EmptyReqBodyDoc (bodies :: [*]) where
emptyBodyDoc :: Proxy bodies -> ReqBodyDoc bodies
instance EmptyReqBodyDoc bodies => EmptyReqBodyDoc (bdy ': bodies) where
emptyBodyDoc _ = case emptyBodyDoc Proxy of
ReqBodyDoc docss -> ReqBodyDoc (docs "" nil :& docss)
instance EmptyReqBodyDoc '[] where
emptyBodyDoc _ = ReqBodyDoc nil
data ((fn :: Symbol) :- (a :: *)) = Field
data Docs t = forall xs.Docs Text (Rec (DocField t) xs)
docSummary :: Docs t -> Text
docSummary (Docs summ _) = summ
data DocField s (fld :: *) where
DocField :: FName fn -> Doc t -> DocField s (fn :- t)
data Doc t = Doc Text
| Nested (NestedDoc t)
data NestedDoc t = NestedDoc
{ nsummary :: Text
, ndocs :: Docs t
}
nestedDocs :: Doc t -> Maybe (Docs t)
nestedDocs (Nested ndoc) = Just $ ndocs ndoc
nestedDocs (Doc _) = Nothing
nestedSummary :: Doc t -> Maybe Text
nestedSummary (Nested ndoc) = Just $ nsummary ndoc
nestedSummary _ = Nothing
instance IsString (Doc t) where
fromString = Doc . pack
data Rec :: (k -> *) -> [k] -> * where
Nil :: Rec f '[]
(:&) :: f x -> Rec f xs -> Rec f (x ': xs)
infixr 7 :&
data FName (fn :: Symbol) = FN
field :: forall fn.FName fn
field = FN
(-:) :: FName fn -> Doc t -> DocField s (fn :- t)
(-:) fn doc = DocField fn doc
docs :: Text -> Rec (DocField t) xs -> Docs t
docs = Docs
nested :: Text -> Docs t -> Doc t
nested summary = Nested . NestedDoc summary
nil :: Rec f '[]
nil = Nil
f :: QuasiQuoter
f = QuasiQuoter
{ quoteExp = quoteFieldExp
, quotePat = error "Field QuasiQuote cannot be used in pattern"
, quoteDec = error "Field QuasiQuote cannot be used in declaration"
, quoteType = error "Field QuasiQuote cannot be used in type"
}
quoteFieldExp :: String -> Q Exp
quoteFieldExp fld = do
let ty = litT $ strTyLit fld
[|field :: FName $(ty) |]
#if __GLASGOW_HASKELL__ >= 800
instance fn ~ fn' => IsLabel (fn :: Symbol) (FName fn') where
{-# INLINE fromLabel #-}
#endif
#if MIN_VERSION_base(4,10,1)
fromLabel = FN
#elif MIN_VERSION_base(4,9,1)
fromLabel _ = FN
#endif
|
byteally/webapi
|
webapi-docs/src/WebApi/Docs.hs
|
bsd-3-clause
| 6,723
| 0
| 13
| 1,733
| 2,551
| 1,310
| 1,241
| 138
| 1
|
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : ForSyDe.MoC.SDF.Lib
-- Copyright : (c) George Ungureanu, KTH/ICT/ESY 2015-2017
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : ugeorge@kth.se
-- Stability : experimental
-- Portability : portable
--
-- The @SDF@ library implements a DSL of atoms operating according to the synchronous
-- dataflow model of computation, along with helpers and associated patterns.
--
-- This module provides a set of helpers for properly instantiating
-- process network patterns as process constructors.
--
-----------------------------------------------------------------------------
module ForSyDe.Atom.MoC.SDF.SDF where
import qualified ForSyDe.Atom.MoC as MoC
import ForSyDe.Atom.MoC.SDF.Core
import ForSyDe.Atom.Utility.Tuple
------- DOCTEST SETUP -------
-- $setup
-- >>> import ForSyDe.Atom.MoC.Stream (takeS)
------- DELAY -------
-- | The @delay@ process "delays" a signal with initial events built
-- from a list. It is an instantiation of the 'ForSyDe.Atom.MoC.delay'
-- constructor.
--
-- >>> let s = signal [1,2,3,4,5]
-- >>> delay [0,0,0] s
-- {0,0,0,1,2,3,4,5}
--
-- <<fig/moc-sdf-pattern-delay.png>>
delay :: [a] -- ^ list of initial values
-> Signal a -- ^ input signal
-> Signal a -- ^ output signal
delay i = MoC.delay (signal i)
-- | Similar to the previous, but this is the raw instantiation of the
-- 'ForSyDe.Atom.MoC.delay' pattern. It appends the contents of one
-- signal at the head of another signal.
--
-- >>> let s1 = signal [0,0,0]
-- >>> let s2 = signal [1,2,3,4,5]
-- >>> delay' s1 s2
-- {0,0,0,1,2,3,4,5}
--
-- <<fig/moc-sdf-pattern-delayp.png>>
delay' :: Signal a -- ^ signal containing the initial tokens
-> Signal a -- ^ input signal
-> Signal a -- ^ output signal
delay' = MoC.delay
------- COMB -------
-- | @actor@ processes map combnational functions on signals and take
-- care of synchronization between input signals. It instantiates the
-- @comb@ atom pattern (see 'ForSyDe.Atom.MoC.comb22').
--
-- Constructors: @actor[1-4][1-4]@.
--
-- >>> let s1 = signal [1..]
-- >>> let s2 = signal [1,1,1,1,1,1,1]
-- >>> let f [a,b,c] [d,e] = [a+d, c+e]
-- >>> actor21 ((3,2),2,f) s1 s2
-- {2,4,5,7,8,10}
--
-- Incorrect usage (not covered by @doctest@):
--
-- > λ> actor21 ((3,2),3,f) s1 s2
-- > *** Exception: [MoC.SDF] Wrong production
--
-- <<fig/moc-sdf-pattern-comb.png>>
actor22 :: ((Cons,Cons), (Prod,Prod),
[a1] -> [a2] -> ([b1], [b2]))
-- ^ function on lists of values, tupled with consumption /
-- production rates
-> Signal a1 -- ^ first input signal
-> Signal a2 -- ^ second input signal
-> (Signal b1, Signal b2) -- ^ two output signals
actor11 :: (Cons, Prod,
[a1] -> [b1])
-> Signal a1
-> Signal b1
actor21 :: ((Cons,Cons), Prod,
[a1] -> [a2] -> [b1])
-> Signal a1 -> Signal a2
-> Signal b1
actor31 :: ((Cons,Cons,Cons), Prod,
[a1] -> [a2] -> [a3] -> [b1])
-> Signal a1 -> Signal a2 -> Signal a3
-> Signal b1
actor41 :: ((Cons,Cons,Cons,Cons), Prod,
[a1] -> [a2] -> [a3] -> [a4] -> [b1])
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> Signal b1
actor12 :: (Cons, (Prod,Prod),
[a1] -> ([b1], [b2]))
-> Signal a1
-> (Signal b1, Signal b2)
actor32 :: ((Cons,Cons,Cons), (Prod,Prod),
[a1] -> [a2] -> [a3] -> ([b1], [b2]))
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2)
actor42 :: ((Cons,Cons,Cons,Cons), (Prod,Prod),
[a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2]))
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2)
actor13 :: (Cons, (Prod,Prod,Prod),
[a1] -> ([b1], [b2], [b3]))
-> Signal a1
-> (Signal b1, Signal b2, Signal b3)
actor23 :: ((Cons,Cons), (Prod,Prod,Prod),
[a1] -> [a2] -> ([b1], [b2], [b3]))
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3)
actor33 :: ((Cons,Cons,Cons), (Prod,Prod,Prod),
[a1] -> [a2] -> [a3] -> ([b1], [b2], [b3]))
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3)
actor43 :: ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2], [b3]))
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3)
actor14 :: (Cons, (Prod,Prod,Prod,Prod),
[a1] -> ([b1], [b2], [b3], [b4]))
-> Signal a1 -> (Signal b1, Signal b2, Signal b3, Signal b4)
actor24 :: ((Cons,Cons), (Prod,Prod,Prod,Prod),
[a1] -> [a2] -> ([b1], [b2], [b3], [b4]))
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3, Signal b4)
actor34 :: ((Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[a1] -> [a2] -> [a3] -> ([b1], [b2], [b3], [b4]))
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3, Signal b4)
actor44 :: ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2], [b3], [b4]))
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3, Signal b4)
actor11 cpf s1 = MoC.comb11 (scen11 cpf) s1
actor21 cpf s1 s2 = MoC.comb21 (scen21 cpf) s1 s2
actor31 cpf s1 s2 s3 = MoC.comb31 (scen31 cpf) s1 s2 s3
actor41 cpf s1 s2 s3 s4 = MoC.comb41 (scen41 cpf) s1 s2 s3 s4
actor12 cpf s1 = MoC.comb12 (scen12 cpf) s1
actor22 cpf s1 s2 = MoC.comb22 (scen22 cpf) s1 s2
actor32 cpf s1 s2 s3 = MoC.comb32 (scen32 cpf) s1 s2 s3
actor42 cpf s1 s2 s3 s4 = MoC.comb42 (scen42 cpf) s1 s2 s3 s4
actor13 cpf s1 = MoC.comb13 (scen13 cpf) s1
actor23 cpf s1 s2 = MoC.comb23 (scen23 cpf) s1 s2
actor33 cpf s1 s2 s3 = MoC.comb33 (scen33 cpf) s1 s2 s3
actor43 cpf s1 s2 s3 s4 = MoC.comb43 (scen43 cpf) s1 s2 s3 s4
actor14 cpf s1 = MoC.comb14 (scen14 cpf) s1
actor24 cpf s1 s2 = MoC.comb24 (scen24 cpf) s1 s2
actor34 cpf s1 s2 s3 = MoC.comb34 (scen34 cpf) s1 s2 s3
actor44 cpf s1 s2 s3 s4 = MoC.comb44 (scen44 cpf) s1 s2 s3 s4
------- RECONFIG -------
-- | @reconfig@ creates an SDF adaptive process where the first signal
-- carries functions and the other carry the arguments. It
-- instantiates the @reconfig@ atom pattern (see
-- 'ForSyDe.Atom.MoC.reconfig22'). According to our SDF definition,
-- the production and consumption rates need to be fixed, so they are
-- passed as parameters to the constructor, whereas the first signal
-- carries adaptive functions only. For the adaptive signal it only
-- makes sense that the consumption rate is always 1.
--
-- Constructors: @reconfig[1-4][1-4]@.
--
-- >>> let f1 a = [sum a]
-- >>> let f2 a = [maximum a]
-- >>> let sf = signal [f1,f2,f1,f2,f1,f2,f1]
-- >>> let s1 = signal [1..]
-- >>> reconfig11 (4,1) sf s1
-- {10,8,42,16,74,24,106}
--
-- <<fig/moc-sdf-pattern-reconfig.png>>
reconfig22 :: ((Cons,Cons), (Prod,Prod))
-> Signal ([a1] -> [a2] -> ([b1], [b2]))
-- ^ function on lists of values, tupled with consumption /
-- production rates
-> Signal a1 -- ^ first input signal
-> Signal a2 -- ^ second input signal
-> (Signal b1, Signal b2) -- ^ two output signals
reconfig11 :: (Cons, Prod)
-> Signal ([a1] -> [b1])
-> Signal a1
-> Signal b1
reconfig21 :: ((Cons,Cons), Prod)
-> Signal ( [a1] -> [a2] -> [b1])
-> Signal a1 -> Signal a2
-> Signal b1
reconfig31 :: ((Cons,Cons,Cons), Prod)
-> Signal ([a1] -> [a2] -> [a3] -> [b1])
-> Signal a1 -> Signal a2 -> Signal a3
-> Signal b1
reconfig41 :: ((Cons,Cons,Cons,Cons), Prod)
-> Signal ([a1] -> [a2] -> [a3] -> [a4] -> [b1])
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> Signal b1
reconfig12 :: (Cons, (Prod,Prod))
-> Signal ([a1] -> ([b1], [b2]))
-> Signal a1
-> (Signal b1, Signal b2)
reconfig32 :: ((Cons,Cons,Cons), (Prod,Prod))
-> Signal ([a1] -> [a2] -> [a3] -> ([b1], [b2]))
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2)
reconfig42 :: ((Cons,Cons,Cons,Cons), (Prod,Prod))
-> Signal ([a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2]))
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2)
reconfig13 :: (Cons, (Prod,Prod,Prod))
-> Signal ([a1] -> ([b1], [b2], [b3]))
-> Signal a1
-> (Signal b1, Signal b2, Signal b3)
reconfig23 :: ((Cons,Cons), (Prod,Prod,Prod))
-> Signal ([a1] -> [a2] -> ([b1], [b2], [b3]))
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3)
reconfig33 :: ((Cons,Cons,Cons), (Prod,Prod,Prod))
-> Signal ([a1] -> [a2] -> [a3] -> ([b1], [b2], [b3]))
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3)
reconfig43 :: ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod))
-> Signal ([a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2], [b3]))
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3)
reconfig14 :: (Cons, (Prod,Prod,Prod,Prod))
-> Signal ([a1] -> ([b1], [b2], [b3], [b4]))
-> Signal a1
-> (Signal b1, Signal b2, Signal b3, Signal b4)
reconfig24 :: ((Cons,Cons), (Prod,Prod,Prod,Prod))
-> Signal ([a1] -> [a2] -> ([b1], [b2], [b3], [b4]))
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3, Signal b4)
reconfig34 :: ((Cons,Cons,Cons), (Prod,Prod,Prod,Prod))
-> Signal ([a1] -> [a2] -> [a3] -> ([b1], [b2], [b3], [b4]))
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3, Signal b4)
reconfig44 :: ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod))
-> Signal ([a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2], [b3], [b4]))
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3, Signal b4)
wrap ctxt c p sf = (fmap . fmap) (\f->ctxt (c,p,f)) sf
reconfig11 (c,p) sf = MoC.reconfig11 (wrap scen11 c p sf)
reconfig12 (c,p) sf = MoC.reconfig12 (wrap scen12 c p sf)
reconfig13 (c,p) sf = MoC.reconfig13 (wrap scen13 c p sf)
reconfig14 (c,p) sf = MoC.reconfig14 (wrap scen14 c p sf)
reconfig21 (c,p) sf = MoC.reconfig21 (wrap scen21 c p sf)
reconfig22 (c,p) sf = MoC.reconfig22 (wrap scen22 c p sf)
reconfig23 (c,p) sf = MoC.reconfig23 (wrap scen23 c p sf)
reconfig24 (c,p) sf = MoC.reconfig24 (wrap scen24 c p sf)
reconfig31 (c,p) sf = MoC.reconfig31 (wrap scen31 c p sf)
reconfig32 (c,p) sf = MoC.reconfig32 (wrap scen32 c p sf)
reconfig33 (c,p) sf = MoC.reconfig33 (wrap scen33 c p sf)
reconfig34 (c,p) sf = MoC.reconfig34 (wrap scen34 c p sf)
reconfig41 (c,p) sf = MoC.reconfig41 (wrap scen41 c p sf)
reconfig42 (c,p) sf = MoC.reconfig42 (wrap scen42 c p sf)
reconfig43 (c,p) sf = MoC.reconfig43 (wrap scen43 c p sf)
reconfig44 (c,p) sf = MoC.reconfig44 (wrap scen44 c p sf)
------- CONSTANT -------
-- | A signal generator which repeats the initial tokens
-- indefinitely. It is actually an instantiation of the @stated0X@
-- constructor (check 'ForSyDe.Atom.MoC.stated22').
--
-- Constructors: @constant[1-4]@.
--
-- >>> let (s1, s2) = constant2 ([1,2,3],[2,1])
-- >>> takeS 7 s1
-- {1,2,3,1,2,3,1}
-- >>> takeS 5 s2
-- {2,1,2,1,2}
--
-- <<fig/moc-sdf-pattern-constant.png>>
constant2 :: ([b1], [b2]) -- ^ values to be repeated
-> (Signal b1, Signal b2) -- ^ generated signals
constant1 :: ([b1])
-> (Signal b1)
constant3 :: ([b1], [b2], [b3])
-> (Signal b1, Signal b2, Signal b3)
constant4 :: ([b1], [b2], [b3], [b4])
-> (Signal b1, Signal b2, Signal b3, Signal b4)
constant1 i = MoC.stated01 (MoC.ctxt11 1 1 id) (signal i)
constant2 i = MoC.stated02 (MoC.ctxt22 (1,1) (1,1) (,)) (signal2 i)
constant3 i = MoC.stated03 (MoC.ctxt33 (1,1,1) (1,1,1) (,,)) (signal3 i)
constant4 i = MoC.stated04 (MoC.ctxt44 (1,1,1,1) (1,1,1,1) (,,,)) (signal4 i)
------- GENERATE -------
-- | A signal generator based on a function and a kernel value. It
-- is actually an instantiation of the @stated0X@ constructor
-- (check 'ForSyDe.Atom.MoC.stated22').
--
-- Constructors: @generate[1-4]@.
--
-- >>> let f a b = ([sum a, sum a],[sum b, sum b, sum b])
-- >>> let (s1,s2) = generate2 ((2,3),(2,3),f) ([1,1],[2,2,2])
-- >>> takeS 7 s1
-- {1,1,2,2,4,4,8}
-- >>> takeS 8 s2
-- {2,2,2,6,6,6,18,18}
--
-- <<fig/moc-sdf-pattern-generate.png>>
generate2 :: ((Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> ([b1], [b2]))
-- ^ function to generate next value, tupled with
-- consumption / production rates
-> ([b1], [b2])
-- ^ values of initial tokens
-> (Signal b1, Signal b2)
-- ^ generated signals
generate1 :: (Cons, Prod,
[b1] -> [b1])
-> [b1]
-> Signal b1
generate3 :: ((Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> (Signal b1, Signal b2, Signal b3)
generate4 :: ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> (Signal b1, Signal b2, Signal b3, Signal b4)
generate1 cpf i = MoC.stated01 (scen11 cpf) (signal i)
generate2 cpf i = MoC.stated02 (scen22 cpf) (signal2 i)
generate3 cpf i = MoC.stated03 (scen33 cpf) (signal3 i)
generate4 cpf i = MoC.stated04 (scen44 cpf) (signal4 i)
------- STATED -------
-- | @stated@ is a state machine without an output decoder. It is an
-- instantiation of the @state@ MoC constructor (see
-- 'ForSyDe.Atom.MoC.stated22').
--
-- Constructors: @stated[1-4][1-4]@.
--
-- >>> let f [a] [b,c] = [a+b+c]
-- >>> let s = signal [1,2,3,4,5,6,7]
-- >>> stated11 ((1,2),1,f) [1] s
-- {1,4,11,22}
--
-- <<fig/moc-sdf-pattern-stated.png>>
stated22 :: ((Cons,Cons,Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> [a1] -> [a2] -> ([b1], [b2]))
-- ^ next state function, tupled with
-- consumption / production rates
-> ([b1], [b2])
-- ^ initial state partitions of values
-> Signal a1
-- ^ first input signal
-> Signal a2
-- ^ second input signal
-> (Signal b1, Signal b2)
-- ^ output signals
stated11 :: ((Cons,Cons), Prod,
[b1] -> [a1] -> [b1])
-> [b1]
-> Signal a1
-> Signal b1
stated12 :: ((Cons,Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> [a1] -> ([b1], [b2]))
-> ([b1], [b2])
-> Signal a1
-> (Signal b1, Signal b2)
stated13 :: ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [a1] -> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> Signal a1
-> (Signal b1, Signal b2, Signal b3)
stated14 :: ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> [a1]
-> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> Signal a1
-> (Signal b1, Signal b2, Signal b3, Signal b4)
stated21 :: ((Cons,Cons,Cons), Prod,
[b1] -> [a1] -> [a2] -> [b1])
-> [b1]
-> Signal a1 -> Signal a2
-> Signal b1
stated23 :: ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [a1] -> [a2] -> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3)
stated24 :: ((Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> [a1] -> [a2]
-> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3, Signal b4)
stated31 :: ((Cons,Cons,Cons,Cons), Prod,
[b1] -> [a1] -> [a2] -> [a3] -> [b1])
-> [b1]
-> Signal a1 -> Signal a2 -> Signal a3
-> Signal b1
stated32 :: ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> [a1] -> [a2] -> [a3] -> ([b1], [b2]))
-> ([b1], [b2])
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2)
stated33 :: ((Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [a1] -> [a2] -> [a3]
-> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3)
stated34 :: ((Cons,Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> [a1] -> [a2] -> [a3]
-> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3, Signal b4)
stated41 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[b1] -> [a1] -> [a2] -> [a3] -> [a4] -> [b1])
-> [b1]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> Signal b1
stated42 :: ((Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> [a1] -> [a2] -> [a3] -> [a4]
-> ([b1], [b2]))
-> ([b1], [b2])
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2)
stated43 :: ((Cons,Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [a1] -> [a2] -> [a3] -> [a4]
-> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3)
stated44 :: ((Cons,Cons,Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> [a1] -> [a2] -> [a3]
-> [a4] -> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3, Signal b4)
stated11 ns i = MoC.stated11 (scen21 ns) (signal i)
stated12 ns i = MoC.stated12 (scen32 ns) (signal2 i)
stated13 ns i = MoC.stated13 (scen43 ns) (signal3 i)
stated14 ns i = MoC.stated14 (scen54 ns) (signal4 i)
stated21 ns i = MoC.stated21 (scen31 ns) (signal i)
stated22 ns i = MoC.stated22 (scen42 ns) (signal2 i)
stated23 ns i = MoC.stated23 (scen53 ns) (signal3 i)
stated24 ns i = MoC.stated24 (scen64 ns) (signal4 i)
stated31 ns i = MoC.stated31 (scen41 ns) (signal i)
stated32 ns i = MoC.stated32 (scen52 ns) (signal2 i)
stated33 ns i = MoC.stated33 (scen63 ns) (signal3 i)
stated34 ns i = MoC.stated34 (scen74 ns) (signal4 i)
stated41 ns i = MoC.stated41 (scen51 ns) (signal i)
stated42 ns i = MoC.stated42 (scen62 ns) (signal2 i)
stated43 ns i = MoC.stated43 (scen73 ns) (signal3 i)
stated44 ns i = MoC.stated44 (scen84 ns) (signal4 i)
------- STATE -------
-- | @state@ is a state machine without an output decoder. It is an
-- instantiation of the @stated@ MoC constructor (see
-- 'ForSyDe.Atom.MoC.state22').
--
-- Constructors: @state[1-4][1-4]@.
--
-- >>> let f [a] [b,c] = [a+b+c]
-- >>> let s = signal [1,2,3,4,5,6,7]
-- >>> state11 ((1,2),1,f) [1] s
-- {4,11,22}
--
-- <<fig/moc-sdf-pattern-state.png>>
state22 :: ((Cons,Cons,Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> [a1] -> [a2] -> ([b1], [b2]))
-- ^ next state function, tupled with consumption /
-- production rates
-> ([b1], [b2])
-- ^ initial partitions of values
-> Signal a1
-- ^ first input signal
-> Signal a2
-- ^ second input signal
-> (Signal b1, Signal b2)
-- ^ output signals
state11 :: ((Cons,Cons), Prod,
[b1] -> [a1] -> [b1])
-> [b1]
-> Signal a1
-> Signal b1
state12 :: ((Cons,Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> [a1] -> ([b1], [b2]))
-> ([b1], [b2])
-> Signal a1
-> (Signal b1, Signal b2)
state13 :: ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [a1] -> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> Signal a1
-> (Signal b1, Signal b2, Signal b3)
state14 :: ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> [a1] -> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> Signal a1
-> (Signal b1, Signal b2, Signal b3, Signal b4)
state21 :: ((Cons,Cons,Cons), Prod,
[b1] -> [a1] -> [a2] -> [b1])
-> [b1]
-> Signal a1 -> Signal a2
-> Signal b1
state23 :: ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [a1] -> [a2] -> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3)
state24 :: ((Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> [a1] -> [a2] -> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3, Signal b4)
state31 :: ((Cons,Cons,Cons,Cons), Prod,
[b1] -> [a1] -> [a2] -> [a3] -> [b1])
-> [b1]
-> Signal a1 -> Signal a2 -> Signal a3
-> Signal b1
state32 :: ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> [a1] -> [a2] -> [a3] -> ([b1], [b2]))
-> ([b1], [b2])
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2)
state33 :: ((Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [a1] -> [a2] -> [a3] -> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3)
state34 :: ((Cons,Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> [a1] -> [a2] -> [a3] -> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3, Signal b4)
state41 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[b1] -> [a1] -> [a2] -> [a3] -> [a4] -> [b1])
-> [b1]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> Signal b1
state42 :: ((Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod),
[b1] -> [b2] -> [a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2]))
-> ([b1], [b2])
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2)
state43 :: ((Cons,Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2], [b3]))
-> ([b1], [b2], [b3])
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3)
state44 :: ((Cons,Cons,Cons,Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[b1] -> [b2] -> [b3] -> [b4] -> [a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2], [b3], [b4]))
-> ([b1], [b2], [b3], [b4])
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3, Signal b4)
state11 ns i = MoC.state11 (scen21 ns) (signal i)
state12 ns i = MoC.state12 (scen32 ns) (signal2 i)
state13 ns i = MoC.state13 (scen43 ns) (signal3 i)
state14 ns i = MoC.state14 (scen54 ns) (signal4 i)
state21 ns i = MoC.state21 (scen31 ns) (signal i)
state22 ns i = MoC.state22 (scen42 ns) (signal2 i)
state23 ns i = MoC.state23 (scen53 ns) (signal3 i)
state24 ns i = MoC.state24 (scen64 ns) (signal4 i)
state31 ns i = MoC.state31 (scen41 ns) (signal i)
state32 ns i = MoC.state32 (scen52 ns) (signal2 i)
state33 ns i = MoC.state33 (scen63 ns) (signal3 i)
state34 ns i = MoC.state34 (scen74 ns) (signal4 i)
state41 ns i = MoC.state41 (scen51 ns) (signal i)
state42 ns i = MoC.state42 (scen62 ns) (signal2 i)
state43 ns i = MoC.state43 (scen73 ns) (signal3 i)
state44 ns i = MoC.state44 (scen84 ns) (signal4 i)
------- MOORE -------
-- | @moore@ processes model Moore state machines. It is an
-- instantiation of the @moore@ MoC constructor (see
-- 'ForSyDe.Atom.MoC.moore22').
--
-- Constructors: @moore[1-4][1-4]@.
--
-- >>> let ns [a] [b,c] = [a+b+c]
-- >>> let od [a] = [a+1,a*2]
-- >>> let s = signal [1,2,3,4,5,6,7]
-- >>> moore11 ((1,2),1,ns) (1,2,od) [1] s
-- {2,2,5,8,12,22,23,44}
--
-- <<fig/moc-sdf-pattern-moore.png>>
moore22 :: ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [st])
-- ^ next state function, tupled with consumption / production
-- rates
-> (Cons, (Prod,Prod), [st] -> ([b1], [b2]))
-- ^ output decoder, tupled with consumption / production
-- rates
-> [st]
-- ^ initial state values
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2)
moore11 :: ((Cons,Cons), Prod, [st] -> [a1] -> [st])
-> (Cons, Prod, [st] -> [b1])
-> [st]
-> Signal a1
-> Signal b1
moore12 :: ((Cons,Cons), Prod, [st] -> [a1] -> [st])
-> (Cons, (Prod,Prod), [st] -> ([b1], [b2]))
-> [st]
-> Signal a1
-> (Signal b1, Signal b2)
moore13 :: ((Cons,Cons), Prod, [st] -> [a1] -> [st])
-> ( Cons, (Prod,Prod,Prod), [st] -> ([b1], [b2], [b3]))
-> [st]
-> Signal a1
-> (Signal b1, Signal b2, Signal b3)
moore14 :: ((Cons,Cons), Prod, [st] -> [a1] -> [st])
-> ( Cons , (Prod,Prod,Prod,Prod),
[st] -> ([b1], [b2], [b3], [b4]))
-> [st]
-> Signal a1
-> (Signal b1, Signal b2, Signal b3, Signal b4)
moore21 :: ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [st])
-> ( Cons, Prod, [st] -> [b1])
-> [st]
-> Signal a1 -> Signal a2
-> Signal b1
moore23 :: ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [st])
-> ( Cons, (Prod,Prod,Prod), [st] -> ([b1], [b2], [b3]))
-> [st]
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3)
moore24 :: ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [st])
-> (Cons, (Prod,Prod,Prod,Prod),
[st] -> ([b1], [b2], [b3], [b4]))
-> [st]
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3, Signal b4)
moore31 :: ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [st])
-> ( Cons, Prod, [st] -> [b1])
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3
-> Signal b1
moore32 :: ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [st])
-> ( Cons, (Prod,Prod), [st] -> ([b1], [b2]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2)
moore33 :: ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [st])
-> ( Cons, (Prod,Prod,Prod), [st] -> ([b1], [b2], [b3]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3)
moore34 :: ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [st])
-> ( Cons, (Prod,Prod,Prod,Prod),
[st] -> ([b1], [b2], [b3], [b4]))
-> [st] -> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3, Signal b4)
moore41 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [st])
-> ( Cons, Prod, [st] -> [b1])
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> Signal b1
moore42 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [st])
-> ( Cons, (Prod,Prod), [st] -> ([b1], [b2]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2)
moore43 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [st])
-> ( Cons, (Prod,Prod,Prod), [st] -> ([b1], [b2], [b3]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3)
moore44 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [st])
-> (Cons, (Prod,Prod,Prod,Prod),
[st] -> ([b1], [b2], [b3], [b4]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3, Signal b4)
moore11 ns od i = MoC.moore11 (scen21 ns) (scen11 od) (signal i)
moore12 ns od i = MoC.moore12 (scen21 ns) (scen12 od) (signal i)
moore13 ns od i = MoC.moore13 (scen21 ns) (scen13 od) (signal i)
moore14 ns od i = MoC.moore14 (scen21 ns) (scen14 od) (signal i)
moore21 ns od i = MoC.moore21 (scen31 ns) (scen11 od) (signal i)
moore22 ns od i = MoC.moore22 (scen31 ns) (scen12 od) (signal i)
moore23 ns od i = MoC.moore23 (scen31 ns) (scen13 od) (signal i)
moore24 ns od i = MoC.moore24 (scen31 ns) (scen14 od) (signal i)
moore31 ns od i = MoC.moore31 (scen41 ns) (scen11 od) (signal i)
moore32 ns od i = MoC.moore32 (scen41 ns) (scen12 od) (signal i)
moore33 ns od i = MoC.moore33 (scen41 ns) (scen13 od) (signal i)
moore34 ns od i = MoC.moore34 (scen41 ns) (scen14 od) (signal i)
moore41 ns od i = MoC.moore41 (scen51 ns) (scen11 od) (signal i)
moore42 ns od i = MoC.moore42 (scen51 ns) (scen12 od) (signal i)
moore43 ns od i = MoC.moore43 (scen51 ns) (scen13 od) (signal i)
moore44 ns od i = MoC.moore44 (scen51 ns) (scen14 od) (signal i)
------- MEALY -------
-- | @mealy@ processes model Mealy state machines. It is an
-- instantiation of the @mealy@ MoC constructor
-- (see 'ForSyDe.Atom.MoC.mealy22').
--
-- Constructors: @mealy[1-4][1-4]@.
--
-- >>> let ns [a] [b,c] = [a+b+c]
-- >>> let od [a] [b] = [a+b,a*b]
-- >>> let s = signal [1,2,3,4,5,6,7]
-- >>> mealy11 ((1,2),1,ns) ((1,1),2,od) [1] s
-- {2,1,6,8,14,33,26,88}
--
-- <<fig/moc-sdf-pattern-mealy.png>>
mealy22 :: ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [st])
-- ^ next state function, tupled with consumption / production
-- rates
-> ((Cons,Cons,Cons), (Prod,Prod),
[st] -> [a1] -> [a2] -> ([b1], [b2]))
-- ^ outpt decoder, tupled with consumption / production rates
-> [st]
-- ^ initial state values
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2)
mealy11 :: ((Cons,Cons), Prod, [st] -> [a1] -> [st])
-> ((Cons,Cons), Prod, [st] -> [a1] -> [b1])
-> [st]
-> Signal a1
-> Signal b1
mealy12 :: ((Cons,Cons), Prod, [st] -> [a1] -> [st])
-> ((Cons,Cons), (Prod,Prod), [st] -> [a1] -> ([b1], [b2]))
-> [st]
-> Signal a1
-> (Signal b1, Signal b2)
mealy13 :: ((Cons,Cons), Prod, [st] -> [a1] -> [st])
-> ((Cons,Cons), (Prod,Prod,Prod),
[st] -> [a1] -> ([b1], [b2], [b3]))
-> [st]
-> Signal a1
-> (Signal b1, Signal b2, Signal b3)
mealy14 :: ((Cons,Cons), Prod, [st] -> [a1] -> [st])
-> ((Cons,Cons), (Prod,Prod,Prod,Prod),
[st] -> [a1] -> ([b1], [b2], [b3], [b4]))
-> [st]
-> Signal a1
-> (Signal b1, Signal b2, Signal b3, Signal b4)
mealy21 :: ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [st])
-> ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [b1])
-> [st]
-> Signal a1 -> Signal a2
-> Signal b1
mealy23 :: ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [st])
-> ((Cons,Cons,Cons), (Prod,Prod,Prod),
[st] -> [a1] -> [a2] -> ([b1], [b2], [b3]))
-> [st]
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3)
mealy24 :: ((Cons,Cons,Cons), Prod, [st] -> [a1] -> [a2] -> [st])
-> ((Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[st] -> [a1] -> [a2] -> ([b1], [b2], [b3], [b4]))
-> [st]
-> Signal a1 -> Signal a2
-> (Signal b1, Signal b2, Signal b3, Signal b4)
mealy31 :: ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [st])
-> ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [b1])
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3
-> Signal b1
mealy32 :: ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [st])
-> ((Cons,Cons,Cons,Cons), (Prod,Prod),
[st] -> [a1] -> [a2] -> [a3] -> ([b1], [b2]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2)
mealy33 :: ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [st])
-> ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[st] -> [a1] -> [a2] -> [a3] -> ([b1], [b2], [b3]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3)
mealy34 :: ((Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [st])
-> ((Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[st] -> [a1] -> [a2] -> [a3] -> ([b1], [b2], [b3], [b4]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3
-> (Signal b1, Signal b2, Signal b3, Signal b4)
mealy41 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [st])
-> ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [b1])
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> Signal b1
mealy42 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [st])
-> ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod),
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2)
mealy43 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [st])
-> ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod),
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2], [b3]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3)
mealy44 :: ((Cons,Cons,Cons,Cons,Cons), Prod,
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> [st])
-> ((Cons,Cons,Cons,Cons,Cons), (Prod,Prod,Prod,Prod),
[st] -> [a1] -> [a2] -> [a3] -> [a4] -> ([b1], [b2], [b3], [b4]))
-> [st]
-> Signal a1 -> Signal a2 -> Signal a3 -> Signal a4
-> (Signal b1, Signal b2, Signal b3, Signal b4)
mealy11 ns od i = MoC.mealy11 (scen21 ns) (scen21 od) (signal i)
mealy12 ns od i = MoC.mealy12 (scen21 ns) (scen22 od) (signal i)
mealy13 ns od i = MoC.mealy13 (scen21 ns) (scen23 od) (signal i)
mealy14 ns od i = MoC.mealy14 (scen21 ns) (scen24 od) (signal i)
mealy21 ns od i = MoC.mealy21 (scen31 ns) (scen31 od) (signal i)
mealy22 ns od i = MoC.mealy22 (scen31 ns) (scen32 od) (signal i)
mealy23 ns od i = MoC.mealy23 (scen31 ns) (scen33 od) (signal i)
mealy24 ns od i = MoC.mealy24 (scen31 ns) (scen34 od) (signal i)
mealy31 ns od i = MoC.mealy31 (scen41 ns) (scen41 od) (signal i)
mealy32 ns od i = MoC.mealy32 (scen41 ns) (scen42 od) (signal i)
mealy33 ns od i = MoC.mealy33 (scen41 ns) (scen43 od) (signal i)
mealy34 ns od i = MoC.mealy34 (scen41 ns) (scen44 od) (signal i)
mealy41 ns od i = MoC.mealy41 (scen51 ns) (scen51 od) (signal i)
mealy42 ns od i = MoC.mealy42 (scen51 ns) (scen52 od) (signal i)
mealy43 ns od i = MoC.mealy43 (scen51 ns) (scen53 od) (signal i)
mealy44 ns od i = MoC.mealy44 (scen51 ns) (scen54 od) (signal i)
|
forsyde/forsyde-atom
|
src/ForSyDe/Atom/MoC/SDF/SDF.hs
|
bsd-3-clause
| 36,157
| 0
| 16
| 10,084
| 16,769
| 9,482
| 7,287
| 633
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-------------------------------------------------------------------------------
-- |
-- Module : Database.Bloodhound.Client
-- Copyright : (C) 2014 Chris Allen
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Chris Allen <cma@bitemyapp.com
-- Stability : provisional
-- Portability : OverloadedStrings
--
-- Client side functions for talking to Elasticsearch servers.
--
-------------------------------------------------------------------------------
module Database.Bloodhound.Client
( -- * Bloodhound client functions
-- | The examples in this module assume the following code has been run.
-- The :{ and :} will only work in GHCi. You'll only need the data types
-- and typeclass instances for the functions that make use of them.
-- $setup
withBH
, createIndex
, deleteIndex
, indexExists
, openIndex
, closeIndex
, putTemplate
, templateExists
, deleteTemplate
, putMapping
, deleteMapping
, indexDocument
, getDocument
, documentExists
, deleteDocument
, searchAll
, searchByIndex
, searchByType
, scanSearch
, refreshIndex
, mkSearch
, mkAggregateSearch
, mkHighlightSearch
, bulk
, pageSearch
, mkShardCount
, mkReplicaCount
, getStatus
, encodeBulkOperations
, encodeBulkOperation
-- * Reply-handling tools
, isVersionConflict
, isSuccess
, isCreated
)
where
import qualified Blaze.ByteString.Builder as BB
import Control.Applicative
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Aeson
import Data.ByteString.Lazy.Builder
import qualified Data.ByteString.Lazy.Char8 as L
import Data.Default.Class
import Data.Ix
import Data.Maybe (fromMaybe)
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Vector as V
import Network.HTTP.Client
import qualified Network.HTTP.Types.Method as NHTM
import qualified Network.HTTP.Types.Status as NHTS
import qualified Network.HTTP.Types.URI as NHTU
import Prelude hiding (filter, head)
import URI.ByteString hiding (Query)
import Database.Bloodhound.Types
-- $setup
-- >>> :set -XOverloadedStrings
-- >>> :set -XDeriveGeneric
-- >>> import Database.Bloodhound
-- >>> import Test.DocTest.Prop (assert)
-- >>> let testServer = (Server "http://localhost:9200")
-- >>> let runBH' = withBH defaultManagerSettings testServer
-- >>> let testIndex = IndexName "twitter"
-- >>> let testMapping = MappingName "tweet"
-- >>> let defaultIndexSettings = IndexSettings (ShardCount 1) (ReplicaCount 0)
-- >>> data TweetMapping = TweetMapping deriving (Eq, Show)
-- >>> _ <- runBH' $ deleteIndex testIndex >> deleteMapping testIndex testMapping
-- >>> import GHC.Generics
-- >>> import Data.Time.Calendar (Day (..))
-- >>> import Data.Time.Clock (UTCTime (..), secondsToDiffTime)
-- >>> :{
--instance ToJSON TweetMapping where
-- toJSON TweetMapping =
-- object ["tweet" .=
-- object ["properties" .=
-- object ["location" .=
-- object ["type" .= ("geo_point" :: Text)]]]]
--data Location = Location { lat :: Double
-- , lon :: Double } deriving (Eq, Generic, Show)
--data Tweet = Tweet { user :: Text
-- , postDate :: UTCTime
-- , message :: Text
-- , age :: Int
-- , location :: Location } deriving (Eq, Generic, Show)
--exampleTweet = Tweet { user = "bitemyapp"
-- , postDate = UTCTime
-- (ModifiedJulianDay 55000)
-- (secondsToDiffTime 10)
-- , message = "Use haskell!"
-- , age = 10000
-- , location = Location 40.12 (-71.34) }
--instance ToJSON Tweet
--instance FromJSON Tweet
--instance ToJSON Location
--instance FromJSON Location
--data BulkTest = BulkTest { name :: Text } deriving (Eq, Generic, Show)
--instance FromJSON BulkTest
--instance ToJSON BulkTest
-- :}
-- | 'mkShardCount' is a straight-forward smart constructor for 'ShardCount'
-- which rejects 'Int' values below 1 and above 1000.
--
-- >>> mkShardCount 10
-- Just (ShardCount 10)
mkShardCount :: Int -> Maybe ShardCount
mkShardCount n
| n < 1 = Nothing
| n > 1000 = Nothing
| otherwise = Just (ShardCount n)
-- | 'mkReplicaCount' is a straight-forward smart constructor for 'ReplicaCount'
-- which rejects 'Int' values below 1 and above 1000.
--
-- >>> mkReplicaCount 10
-- Just (ReplicaCount 10)
mkReplicaCount :: Int -> Maybe ReplicaCount
mkReplicaCount n
| n < 1 = Nothing
| n > 1000 = Nothing -- ...
| otherwise = Just (ReplicaCount n)
emptyBody :: L.ByteString
emptyBody = L.pack ""
dispatch :: MonadBH m => Method -> Text -> Maybe L.ByteString
-> m Reply
dispatch dMethod url body = do
initReq <- liftIO $ parseUrl' url
let reqBody = RequestBodyLBS $ fromMaybe emptyBody body
let req = initReq { method = dMethod
, requestBody = reqBody
, checkStatus = \_ _ _ -> Nothing}
mgr <- bhManager <$> getBHEnv
liftIO $ httpLbs req mgr
joinPath' :: [Text] -> Text
joinPath' = T.intercalate "/"
joinPath :: MonadBH m => [Text] -> m Text
joinPath ps = do
Server s <- bhServer <$> getBHEnv
return $ joinPath' (s:ps)
appendSearchTypeParam :: Text -> SearchType -> Text
appendSearchTypeParam originalUrl st = addQuery params originalUrl
where stText = "search_type"
params
| st == SearchTypeDfsQueryThenFetch = [(stText, Just "dfs_query_then_fetch")]
| st == SearchTypeCount = [(stText, Just "count")]
| st == SearchTypeScan = [(stText, Just "scan"), ("scroll", Just "1m")]
| st == SearchTypeQueryAndFetch = [(stText, Just "query_and_fetch")]
| st == SearchTypeDfsQueryAndFetch = [(stText, Just "dfs_query_and_fetch")]
-- used to catch 'SearchTypeQueryThenFetch', which is also the default
| otherwise = [(stText, Just "query_then_fetch")]
-- | Severely dumbed down query renderer. Assumes your data doesn't
-- need any encoding
addQuery :: [(Text, Maybe Text)] -> Text -> Text
addQuery q u = u <> rendered
where
rendered =
T.decodeUtf8 $ BB.toByteString $ NHTU.renderQueryText prependQuestionMark q
prependQuestionMark = True
bindM2 :: (Applicative m, Monad m) => (a -> b -> m c) -> m a -> m b -> m c
bindM2 f ma mb = join (f <$> ma <*> mb)
-- | Convenience function that sets up a manager and BHEnv and runs
-- the given set of bloodhound operations. Connections will be
-- pipelined automatically in accordance with the given manager
-- settings in IO. If you've got your own monad transformer stack, you
-- should use 'runBH' directly.
withBH :: ManagerSettings -> Server -> BH IO a -> IO a
withBH ms s f = do
mgr <- newManager ms
let env = BHEnv { bhServer = s
, bhManager = mgr }
runBH env f
-- Shortcut functions for HTTP methods
delete :: MonadBH m => Text -> m Reply
delete = flip (dispatch NHTM.methodDelete) Nothing
get :: MonadBH m => Text -> m Reply
get = flip (dispatch NHTM.methodGet) Nothing
head :: MonadBH m => Text -> m Reply
head = flip (dispatch NHTM.methodHead) Nothing
put :: MonadBH m => Text -> Maybe L.ByteString -> m Reply
put = dispatch NHTM.methodPut
post :: MonadBH m => Text -> Maybe L.ByteString -> m Reply
post = dispatch NHTM.methodPost
-- indexDocument s ix name doc = put (root </> s </> ix </> name </> doc) (Just encode doc)
-- http://hackage.haskell.org/package/http-client-lens-0.1.0/docs/Network-HTTP-Client-Lens.html
-- https://github.com/supki/libjenkins/blob/master/src/Jenkins/Rest/Internal.hs
-- | 'getStatus' fetches the 'Status' of a 'Server'
--
-- >>> serverStatus <- runBH' getStatus
-- >>> fmap status (serverStatus)
-- Just 200
getStatus :: MonadBH m => m (Maybe Status)
getStatus = do
url <- joinPath []
request <- liftIO $ parseUrl' url
mgr <- bhManager <$> getBHEnv
response <- liftIO $ httpLbs request mgr
return $ decode (responseBody response)
-- | 'createIndex' will create an index given a 'Server', 'IndexSettings', and an 'IndexName'.
--
-- >>> response <- runBH' $ createIndex defaultIndexSettings (IndexName "didimakeanindex")
-- >>> respIsTwoHunna response
-- True
-- >>> runBH' $ indexExists (IndexName "didimakeanindex")
-- True
createIndex :: MonadBH m => IndexSettings -> IndexName -> m Reply
createIndex indexSettings (IndexName indexName) =
bindM2 put url (return body)
where url = joinPath [indexName]
body = Just $ encode indexSettings
-- | 'deleteIndex' will delete an index given a 'Server', and an 'IndexName'.
--
-- >>> _ <- runBH' $ createIndex defaultIndexSettings (IndexName "didimakeanindex")
-- >>> response <- runBH' $ deleteIndex (IndexName "didimakeanindex")
-- >>> respIsTwoHunna response
-- True
-- >>> runBH' $ indexExists testIndex
-- False
deleteIndex :: MonadBH m => IndexName -> m Reply
deleteIndex (IndexName indexName) =
delete =<< joinPath [indexName]
statusCodeIs :: Int -> Reply -> Bool
statusCodeIs n resp = NHTS.statusCode (responseStatus resp) == n
respIsTwoHunna :: Reply -> Bool
respIsTwoHunna = statusCodeIs 200
existentialQuery :: MonadBH m => Text -> m (Reply, Bool)
existentialQuery url = do
reply <- head url
return (reply, respIsTwoHunna reply)
-- | 'indexExists' enables you to check if an index exists. Returns 'Bool'
-- in IO
--
-- >>> exists <- runBH' $ indexExists testIndex
indexExists :: MonadBH m => IndexName -> m Bool
indexExists (IndexName indexName) = do
(_, exists) <- existentialQuery =<< joinPath [indexName]
return exists
-- | 'refreshIndex' will force a refresh on an index. You must
-- do this if you want to read what you wrote.
--
-- >>> _ <- runBH' $ createIndex defaultIndexSettings testIndex
-- >>> _ <- runBH' $ refreshIndex testIndex
refreshIndex :: MonadBH m => IndexName -> m Reply
refreshIndex (IndexName indexName) =
bindM2 post url (return Nothing)
where url = joinPath [indexName, "_refresh"]
stringifyOCIndex :: OpenCloseIndex -> Text
stringifyOCIndex oci = case oci of
OpenIndex -> "_open"
CloseIndex -> "_close"
openOrCloseIndexes :: MonadBH m => OpenCloseIndex -> IndexName -> m Reply
openOrCloseIndexes oci (IndexName indexName) =
bindM2 post url (return Nothing)
where ociString = stringifyOCIndex oci
url = joinPath [indexName, ociString]
-- | 'openIndex' opens an index given a 'Server' and an 'IndexName'. Explained in further detail at
-- <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
--
-- >>> reply <- runBH' $ openIndex testIndex
openIndex :: MonadBH m => IndexName -> m Reply
openIndex = openOrCloseIndexes OpenIndex
-- | 'closeIndex' closes an index given a 'Server' and an 'IndexName'. Explained in further detail at
-- <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/indices-open-close.html>
--
-- >>> reply <- runBH' $ closeIndex testIndex
closeIndex :: MonadBH m => IndexName -> m Reply
closeIndex = openOrCloseIndexes CloseIndex
-- | 'putTemplate' creates a template given an 'IndexTemplate' and a 'TemplateName'.
-- Explained in further detail at
-- <https://www.elastic.co/guide/en/elasticsearch/reference/1.7/indices-templates.html>
--
-- >>> let idxTpl = IndexTemplate (TemplatePattern "tweet-*") (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping]
-- >>> resp <- runBH' $ putTemplate idxTpl (TemplateName "tweet-tpl")
putTemplate :: MonadBH m => IndexTemplate -> TemplateName -> m Reply
putTemplate indexTemplate (TemplateName templateName) =
bindM2 put url (return body)
where url = joinPath ["_template", templateName]
body = Just $ encode indexTemplate
-- | 'templateExists' checks to see if a template exists.
--
-- >>> exists <- runBH' $ templateExists (TemplateName "tweet-tpl")
templateExists :: MonadBH m => TemplateName -> m Bool
templateExists (TemplateName templateName) = do
(_, exists) <- existentialQuery =<< joinPath ["_template", templateName]
return exists
-- | 'deleteTemplate' is an HTTP DELETE and deletes a template.
--
-- >>> let idxTpl = IndexTemplate (TemplatePattern "tweet-*") (Just (IndexSettings (ShardCount 1) (ReplicaCount 1))) [toJSON TweetMapping]
-- >>> _ <- runBH' $ putTemplate idxTpl (TemplateName "tweet-tpl")
-- >>> resp <- runBH' $ deleteTemplate (TemplateName "tweet-tpl")
deleteTemplate :: MonadBH m => TemplateName -> m Reply
deleteTemplate (TemplateName templateName) =
delete =<< joinPath ["_template", templateName]
-- | 'putMapping' is an HTTP PUT and has upsert semantics. Mappings are schemas
-- for documents in indexes.
--
-- >>> _ <- runBH' $ createIndex defaultIndexSettings testIndex
-- >>> resp <- runBH' $ putMapping testIndex testMapping TweetMapping
-- >>> print resp
-- Response {responseStatus = Status {statusCode = 200, statusMessage = "OK"}, responseVersion = HTTP/1.1, responseHeaders = [("Content-Type","application/json; charset=UTF-8"),("Content-Length","21")], responseBody = "{\"acknowledged\":true}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose}
putMapping :: (MonadBH m, ToJSON a) => IndexName
-> MappingName -> a -> m Reply
putMapping (IndexName indexName) (MappingName mappingName) mapping =
bindM2 put url (return body)
where url = joinPath [indexName, "_mapping", mappingName]
-- "_mapping" and mappingName above were originally transposed
-- erroneously. The correct API call is: "/INDEX/_mapping/MAPPING_NAME"
body = Just $ encode mapping
-- | 'deleteMapping' is an HTTP DELETE and deletes a mapping for a given index.
-- Mappings are schemas for documents in indexes.
--
-- >>> _ <- runBH' $ createIndex defaultIndexSettings testIndex
-- >>> _ <- runBH' $ putMapping testIndex testMapping TweetMapping
-- >>> resp <- runBH' $ deleteMapping testIndex testMapping
-- >>> print resp
-- Response {responseStatus = Status {statusCode = 200, statusMessage = "OK"}, responseVersion = HTTP/1.1, responseHeaders = [("Content-Type","application/json; charset=UTF-8"),("Content-Length","21")], responseBody = "{\"acknowledged\":true}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose}
deleteMapping :: MonadBH m => IndexName -> MappingName -> m Reply
deleteMapping (IndexName indexName)
(MappingName mappingName) =
-- "_mapping" and mappingName below were originally transposed
-- erroneously. The correct API call is: "/INDEX/_mapping/MAPPING_NAME"
delete =<< joinPath [indexName, "_mapping", mappingName]
-- | 'indexDocument' is the primary way to save a single document in
-- Elasticsearch. The document itself is simply something we can
-- convert into a JSON 'Value'. The 'DocId' will function as the
-- primary key for the document.
--
-- >>> resp <- runBH' $ indexDocument testIndex testMapping defaultIndexDocumentSettings exampleTweet (DocId "1")
-- >>> print resp
-- Response {responseStatus = Status {statusCode = 201, statusMessage = "Created"}, responseVersion = HTTP/1.1, responseHeaders = [("Content-Type","application/json; charset=UTF-8"),("Content-Length","74")], responseBody = "{\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"1\",\"_version\":1,\"created\":true}", responseCookieJar = CJ {expose = []}, responseClose' = ResponseClose}
indexDocument :: (ToJSON doc, MonadBH m) => IndexName -> MappingName
-> IndexDocumentSettings -> doc -> DocId -> m Reply
indexDocument (IndexName indexName)
(MappingName mappingName) cfg document (DocId docId) =
bindM2 put url (return body)
where url = addQuery params <$> joinPath [indexName, mappingName, docId]
versionCtlParams = case idsVersionControl cfg of
NoVersionControl -> []
InternalVersion v -> versionParams v "internal"
ExternalGT (ExternalDocVersion v) -> versionParams v "external_gt"
ExternalGTE (ExternalDocVersion v) -> versionParams v "external_gte"
ForceVersion (ExternalDocVersion v) -> versionParams v "force"
vt = T.pack . show . docVersionNumber
versionParams v t = [ ("version", Just $ vt v)
, ("version_type", Just t)
]
parentParams = case idsParent cfg of
Nothing -> []
Just (DocumentParent (DocId p)) -> [ ("parent", Just p) ]
params = versionCtlParams ++ parentParams
body = Just (encode document)
-- | 'deleteDocument' is the primary way to delete a single document.
--
-- >>> _ <- runBH' $ deleteDocument testIndex testMapping (DocId "1")
deleteDocument :: MonadBH m => IndexName -> MappingName
-> DocId -> m Reply
deleteDocument (IndexName indexName)
(MappingName mappingName) (DocId docId) =
delete =<< joinPath [indexName, mappingName, docId]
-- | 'bulk' uses
-- <http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html Elasticsearch's bulk API>
-- to perform bulk operations. The 'BulkOperation' data type encodes the
-- index/update/delete/create operations. You pass a 'V.Vector' of 'BulkOperation's
-- and a 'Server' to 'bulk' in order to send those operations up to your Elasticsearch
-- server to be performed. I changed from [BulkOperation] to a Vector due to memory overhead.
--
-- >>> let stream = V.fromList [BulkIndex testIndex testMapping (DocId "2") (toJSON (BulkTest "blah"))]
-- >>> _ <- runBH' $ bulk stream
-- >>> _ <- runBH' $ refreshIndex testIndex
bulk :: MonadBH m => V.Vector BulkOperation -> m Reply
bulk bulkOps = bindM2 post url (return body)
where url = joinPath ["_bulk"]
body = Just $ encodeBulkOperations bulkOps
-- | 'encodeBulkOperations' is a convenience function for dumping a vector of 'BulkOperation'
-- into an 'L.ByteString'
--
-- >>> let bulkOps = V.fromList [BulkIndex testIndex testMapping (DocId "2") (toJSON (BulkTest "blah"))]
-- >>> encodeBulkOperations bulkOps
-- "\n{\"index\":{\"_type\":\"tweet\",\"_id\":\"2\",\"_index\":\"twitter\"}}\n{\"name\":\"blah\"}\n"
encodeBulkOperations :: V.Vector BulkOperation -> L.ByteString
encodeBulkOperations stream = collapsed where
blobs = fmap encodeBulkOperation stream
mashedTaters = mash (mempty :: Builder) blobs
collapsed = toLazyByteString $ mappend mashedTaters (byteString "\n")
mash :: Builder -> V.Vector L.ByteString -> Builder
mash = V.foldl' (\b x -> b `mappend` (byteString "\n") `mappend` (lazyByteString x))
mkBulkStreamValue :: Text -> Text -> Text -> Text -> Value
mkBulkStreamValue operation indexName mappingName docId =
object [operation .=
object [ "_index" .= indexName
, "_type" .= mappingName
, "_id" .= docId]]
-- | 'encodeBulkOperation' is a convenience function for dumping a single 'BulkOperation'
-- into an 'L.ByteString'
--
-- >>> let bulkOp = BulkIndex testIndex testMapping (DocId "2") (toJSON (BulkTest "blah"))
-- >>> encodeBulkOperation bulkOp
-- "{\"index\":{\"_type\":\"tweet\",\"_id\":\"2\",\"_index\":\"twitter\"}}\n{\"name\":\"blah\"}"
encodeBulkOperation :: BulkOperation -> L.ByteString
encodeBulkOperation (BulkIndex (IndexName indexName)
(MappingName mappingName)
(DocId docId) value) = blob
where metadata = mkBulkStreamValue "index" indexName mappingName docId
blob = encode metadata `mappend` "\n" `mappend` encode value
encodeBulkOperation (BulkCreate (IndexName indexName)
(MappingName mappingName)
(DocId docId) value) = blob
where metadata = mkBulkStreamValue "create" indexName mappingName docId
blob = encode metadata `mappend` "\n" `mappend` encode value
encodeBulkOperation (BulkDelete (IndexName indexName)
(MappingName mappingName)
(DocId docId)) = blob
where metadata = mkBulkStreamValue "delete" indexName mappingName docId
blob = encode metadata
encodeBulkOperation (BulkUpdate (IndexName indexName)
(MappingName mappingName)
(DocId docId) value) = blob
where metadata = mkBulkStreamValue "update" indexName mappingName docId
doc = object ["doc" .= value]
blob = encode metadata `mappend` "\n" `mappend` encode doc
-- | 'getDocument' is a straight-forward way to fetch a single document from
-- Elasticsearch using a 'Server', 'IndexName', 'MappingName', and a 'DocId'.
-- The 'DocId' is the primary key for your Elasticsearch document.
--
-- >>> yourDoc <- runBH' $ getDocument testIndex testMapping (DocId "1")
getDocument :: MonadBH m => IndexName -> MappingName
-> DocId -> m Reply
getDocument (IndexName indexName)
(MappingName mappingName) (DocId docId) =
get =<< joinPath [indexName, mappingName, docId]
-- | 'documentExists' enables you to check if a document exists. Returns 'Bool'
-- in IO
--
-- >>> exists <- runBH' $ documentExists testIndex testMapping (DocId "1")
documentExists :: MonadBH m => IndexName -> MappingName
-> DocId -> m Bool
documentExists (IndexName indexName)
(MappingName mappingName) (DocId docId) = do
(_, exists) <- existentialQuery =<< url
return exists
where url = joinPath [indexName, mappingName, docId]
dispatchSearch :: MonadBH m => Text -> Search -> m Reply
dispatchSearch url search = post url' (Just (encode search))
where url' = appendSearchTypeParam url (searchType search)
-- | 'searchAll', given a 'Search', will perform that search against all indexes
-- on an Elasticsearch server. Try to avoid doing this if it can be helped.
--
-- >>> let query = TermQuery (Term "user" "bitemyapp") Nothing
-- >>> let search = mkSearch (Just query) Nothing
-- >>> reply <- runBH' $ searchAll search
searchAll :: MonadBH m => Search -> m Reply
searchAll = bindM2 dispatchSearch url . return
where url = joinPath ["_search"]
-- | 'searchByIndex', given a 'Search' and an 'IndexName', will perform that search
-- against all mappings within an index on an Elasticsearch server.
--
-- >>> let query = TermQuery (Term "user" "bitemyapp") Nothing
-- >>> let search = mkSearch (Just query) Nothing
-- >>> reply <- runBH' $ searchByIndex testIndex search
searchByIndex :: MonadBH m => IndexName -> Search -> m Reply
searchByIndex (IndexName indexName) = bindM2 dispatchSearch url . return
where url = joinPath [indexName, "_search"]
-- | 'searchByType', given a 'Search', 'IndexName', and 'MappingName', will perform that
-- search against a specific mapping within an index on an Elasticsearch server.
--
-- >>> let query = TermQuery (Term "user" "bitemyapp") Nothing
-- >>> let search = mkSearch (Just query) Nothing
-- >>> reply <- runBH' $ searchByType testIndex testMapping search
searchByType :: MonadBH m => IndexName -> MappingName -> Search
-> m Reply
searchByType (IndexName indexName)
(MappingName mappingName) = bindM2 dispatchSearch url . return
where url = joinPath [indexName, mappingName, "_search"]
scanSearch' :: MonadBH m => IndexName -> MappingName -> Search -> m (Maybe ScrollId)
scanSearch' (IndexName indexName) (MappingName mappingName) search = do
let url = joinPath [indexName, mappingName, "_search"]
search' = search { searchType = SearchTypeScan }
resp' <- bindM2 dispatchSearch url (return search')
let msr = decode' $ responseBody resp' :: Maybe (SearchResult ())
msid = maybe Nothing scrollId msr
return msid
scroll' :: (FromJSON a, MonadBH m) => Maybe ScrollId -> m ([Hit a], Maybe ScrollId)
scroll' Nothing = return ([], Nothing)
scroll' (Just sid) = do
url <- joinPath ["_search/scroll?scroll=1m"]
resp' <- post url (Just . L.fromStrict $ T.encodeUtf8 sid)
let msr = decode' $ responseBody resp' :: FromJSON a => Maybe (SearchResult a)
resp = case msr of
Just sr -> (hits $ searchHits sr, scrollId sr)
_ -> ([], Nothing)
return resp
simpleAccumilator :: (FromJSON a, MonadBH m) => [Hit a] -> ([Hit a], Maybe ScrollId) -> m ([Hit a], Maybe ScrollId)
simpleAccumilator oldHits (newHits, Nothing) = return (oldHits ++ newHits, Nothing)
simpleAccumilator oldHits ([], _) = return (oldHits, Nothing)
simpleAccumilator oldHits (newHits, msid) = do
(newHits', msid') <- scroll' msid
simpleAccumilator (oldHits ++ newHits) (newHits', msid')
-- | 'scanSearch' uses the 'scan&scroll' API of elastic,
-- for a given 'IndexName' and 'MappingName',
scanSearch :: (FromJSON a, MonadBH m) => IndexName -> MappingName -> Search -> m [Hit a]
scanSearch indexName mappingName search = do
msid <- scanSearch' indexName mappingName search
(hits, msid') <- scroll' msid
(totalHits, _) <- simpleAccumilator [] (hits, msid')
return totalHits
-- | 'mkSearch' is a helper function for defaulting additional fields of a 'Search'
-- to Nothing in case you only care about your 'Query' and 'Filter'. Use record update
-- syntax if you want to add things like aggregations or highlights while still using
-- this helper function.
--
-- >>> let query = TermQuery (Term "user" "bitemyapp") Nothing
-- >>> mkSearch (Just query) Nothing
-- Search {queryBody = Just (TermQuery (Term {termField = "user", termValue = "bitemyapp"}) Nothing), filterBody = Nothing, sortBody = Nothing, aggBody = Nothing, highlight = Nothing, trackSortScores = False, from = From 0, size = Size 10, searchType = SearchTypeQueryThenFetch, fields = Nothing, source = Nothing}
mkSearch :: Maybe Query -> Maybe Filter -> Search
mkSearch query filter = Search query filter Nothing Nothing Nothing False (From 0) (Size 10) SearchTypeQueryThenFetch Nothing Nothing
-- | 'mkAggregateSearch' is a helper function that defaults everything in a 'Search' except for
-- the 'Query' and the 'Aggregation'.
--
-- >>> let terms = TermsAgg $ (mkTermsAggregation "user") { termCollectMode = Just BreadthFirst }
-- >>> terms
-- TermsAgg (TermsAggregation {term = Left "user", termInclude = Nothing, termExclude = Nothing, termOrder = Nothing, termMinDocCount = Nothing, termSize = Nothing, termShardSize = Nothing, termCollectMode = Just BreadthFirst, termExecutionHint = Nothing, termAggs = Nothing})
-- >>> let myAggregation = mkAggregateSearch Nothing $ mkAggregations "users" terms
mkAggregateSearch :: Maybe Query -> Aggregations -> Search
mkAggregateSearch query mkSearchAggs = Search query Nothing Nothing (Just mkSearchAggs) Nothing False (From 0) (Size 0) SearchTypeQueryThenFetch Nothing Nothing
-- | 'mkHighlightSearch' is a helper function that defaults everything in a 'Search' except for
-- the 'Query' and the 'Aggregation'.
--
-- >>> let query = QueryMatchQuery $ mkMatchQuery (FieldName "_all") (QueryString "haskell")
-- >>> let testHighlight = Highlights Nothing [FieldHighlight (FieldName "message") Nothing]
-- >>> let search = mkHighlightSearch (Just query) testHighlight
mkHighlightSearch :: Maybe Query -> Highlights -> Search
mkHighlightSearch query searchHighlights = Search query Nothing Nothing Nothing (Just searchHighlights) False (From 0) (Size 10) SearchTypeQueryThenFetch Nothing Nothing
-- | 'pageSearch' is a helper function that takes a search and assigns the from
-- and size fields for the search. The from parameter defines the offset
-- from the first result you want to fetch. The size parameter allows you to
-- configure the maximum amount of hits to be returned.
--
-- >>> let query = QueryMatchQuery $ mkMatchQuery (FieldName "_all") (QueryString "haskell")
-- >>> let search = mkSearch (Just query) Nothing
-- >>> search
-- Search {queryBody = Just (QueryMatchQuery (MatchQuery {matchQueryField = FieldName "_all", matchQueryQueryString = QueryString "haskell", matchQueryOperator = Or, matchQueryZeroTerms = ZeroTermsNone, matchQueryCutoffFrequency = Nothing, matchQueryMatchType = Nothing, matchQueryAnalyzer = Nothing, matchQueryMaxExpansions = Nothing, matchQueryLenient = Nothing, matchQueryBoost = Nothing})), filterBody = Nothing, sortBody = Nothing, aggBody = Nothing, highlight = Nothing, trackSortScores = False, from = From 0, size = Size 10, searchType = SearchTypeQueryThenFetch, fields = Nothing, source = Nothing}
-- >>> pageSearch (From 10) (Size 100) search
-- Search {queryBody = Just (QueryMatchQuery (MatchQuery {matchQueryField = FieldName "_all", matchQueryQueryString = QueryString "haskell", matchQueryOperator = Or, matchQueryZeroTerms = ZeroTermsNone, matchQueryCutoffFrequency = Nothing, matchQueryMatchType = Nothing, matchQueryAnalyzer = Nothing, matchQueryMaxExpansions = Nothing, matchQueryLenient = Nothing, matchQueryBoost = Nothing})), filterBody = Nothing, sortBody = Nothing, aggBody = Nothing, highlight = Nothing, trackSortScores = False, from = From 10, size = Size 100, searchType = SearchTypeQueryThenFetch, fields = Nothing, source = Nothing}
pageSearch :: From -- ^ The result offset
-> Size -- ^ The number of results to return
-> Search -- ^ The current seach
-> Search -- ^ The paged search
pageSearch resultOffset pageSize search = search { from = resultOffset, size = pageSize }
parseUrl' :: MonadThrow m => Text -> m Request
parseUrl' t =
case parseURI laxURIParserOptions (T.encodeUtf8 t) of
Right uri -> setURI def uri
Left e -> throwM $ InvalidUrlException (T.unpack t) ("Invalid URL: " ++ show e)
setURI :: MonadThrow m => Request -> URI -> m Request
setURI req URI{..} = do
Authority {..} <- maybe missingUA return uriAuthority
let req' = req { secure = isSecure
, host = hostBS authorityHost
, port = thePort
, path = uriPath
}
thePort = maybe defPort portNumber authorityPort
addAuth = maybe id addAuth' authorityUserInfo
return $ setQueryString theQueryString $ addAuth req'
where
missingUA = throwM $ InvalidUrlException "N/A" "Missing URI host/port"
addAuth' UserInfo {..} = applyBasicProxyAuth uiUsername uiPassword
defPort
| isSecure = 443
| otherwise = 80
isSecure = case uriScheme of
Scheme "https" -> True
_ -> False
theQueryString = [(k , Just v) | (k, v) <- queryPairs uriQuery]
-- | Was there an optimistic concurrency control conflict when
-- indexing a document?
isVersionConflict :: Reply -> Bool
isVersionConflict = statusCheck (== 409)
isSuccess :: Reply -> Bool
isSuccess = statusCheck (inRange (200, 299))
isCreated :: Reply -> Bool
isCreated = statusCheck (== 201)
statusCheck :: (Int -> Bool) -> Reply -> Bool
statusCheck prd = prd . NHTS.statusCode . responseStatus
|
beni55/bloodhound
|
src/Database/Bloodhound/Client.hs
|
bsd-3-clause
| 31,282
| 0
| 15
| 6,499
| 5,269
| 2,823
| 2,446
| 350
| 6
|
module Debug.IDE(RIDE,
IDEAlign(..),
IDEPanel(..),
IDEPanels(..),
panelsAppend,
panelCBNull,
ideNew,
ideWidget,
ideAddLeft,
ideAddCenter,
ideAddRight,
ideAddBottom,
ideRemove,
framePanelNew,
panedPanelsNew,
tabbedPanelsNew) where
import qualified Graphics.UI.Gtk as G
import Data.Maybe
import Data.IORef
import Control.Monad
import System.IO
data IDEAlign = AlignLeft
| AlignCenter
| AlignRight
| AlignBottom
-- IDE panel callbacks
data PanelCB = PanelCB {
cbDelete :: IO ()
}
panelCBNull :: PanelCB
panelCBNull = PanelCB {cbDelete = return ()}
-- Interface to a widget that contains an individual IDE panel
data IDEPanel = IDEPanel {
panelSetCB :: PanelCB -> IO (),
panelGetWidget :: IO G.Widget,
panelGetName :: IO String
}
-- Interface to a widget that contains a list of IDE panels
data IDEPanels = IDEPanels {
-- Insert after index (-1 to insert before the first element)
panelsInsert :: Int -> G.Widget -> String -> IO (),
panelsDelete :: Int -> IO (),
panelsGetIndex :: G.Widget -> IO (Maybe Int),
panelsGetNumChildren :: IO Int,
-- top-level widget
panelsGetWidget :: IO G.Widget,
panelsSetCB :: PanelCB -> IO ()
}
panelsDeleteWidget :: IDEPanels -> G.Widget -> IO ()
panelsDeleteWidget panels w = do
midx <- (panelsGetIndex panels) w
case midx of
Nothing -> return ()
Just idx -> (panelsDelete panels) idx
panelsAppend :: IDEPanels -> G.Widget -> String -> IO ()
panelsAppend panels w n = do
num <- panelsGetNumChildren panels
(panelsInsert panels) (num - 1) w n
panelsPrepend :: IDEPanels -> G.Widget -> String -> IO ()
panelsPrepend panels w n = (panelsInsert panels) (-1) w n
---------------------------------------------------------------
-- Implementation of IDEPanel based on GTK frame
---------------------------------------------------------------
data FramePanel = FramePanel {
fpFrame :: G.Frame,
fpName :: String,
fpPanelCB :: PanelCB,
fpDeleteCB :: IO ()
}
type RFramePanel = IORef FramePanel
framePanelNew :: G.Widget -> String -> IO () -> IO IDEPanel
framePanelNew w name deletecb = do
frame <- G.frameNew
G.widgetShow frame
G.frameSetLabel frame name
G.containerAdd frame w
ref <- newIORef $ FramePanel { fpFrame = frame
, fpName = name
, fpPanelCB = panelCBNull
, fpDeleteCB = deletecb}
return $ IDEPanel { panelSetCB = fpSetCB ref
, panelGetWidget = fpGetWidget ref
, panelGetName = fpGetName ref}
fpSetCB :: RFramePanel -> PanelCB -> IO ()
fpSetCB ref cb = do
fp <- readIORef ref
writeIORef ref $ fp {fpPanelCB = cb}
fpGetWidget :: RFramePanel -> IO G.Widget
fpGetWidget ref = do
fp <- readIORef ref
return $ G.toWidget $ fpFrame fp
fpGetName :: RFramePanel -> IO String
fpGetName ref = do
fp <- readIORef ref
return $ fpName fp
---------------------------------------------------------------
-- Implementation of IDEPanels based on Paned widgets
---------------------------------------------------------------
data PanedPanels = PanedPanels {
ppMkPaned :: IO G.Paned,
ppFrame :: G.Frame,
ppNumChildren :: Int,
ppPanes :: [G.Paned],
ppCB :: PanelCB
}
type RPanedPanels = IORef PanedPanels
panedPanelsNew :: IO G.Paned -> IO IDEPanels
panedPanelsNew f = do
frame <- G.frameNew
G.frameSetShadowType frame G.ShadowNone
--G.widgetSetSizeRequest frame ideDefaultWidth ideDefaultHeight
G.widgetShow frame
ref <- newIORef $ PanedPanels { ppMkPaned = f
, ppFrame = frame
, ppNumChildren = 0
, ppPanes = []
, ppCB = panelCBNull}
return $ IDEPanels { panelsInsert = ppInsert ref
, panelsDelete = ppDelete ref
, panelsGetIndex = ppGetIndex ref
, panelsGetNumChildren = ppGetNumChildren ref
, panelsGetWidget = ppWidget ref
, panelsSetCB = ppSetCB ref}
ppInsert :: RPanedPanels -> Int -> G.Widget -> String -> IO ()
ppInsert ref i w _ = do
pp <- readIORef ref
case (ppNumChildren pp, i) of
(0, _) -> do G.containerAdd (ppFrame pp) w
writeIORef ref $ pp {ppNumChildren = 1}
(_, -1) -> do -- create new top-level pane
pane <- ppMkPaned pp
G.widgetShow pane
G.panedAdd1 pane w
oldw <- (liftM fromJust) $ G.binGetChild $ ppFrame pp
G.containerRemove (ppFrame pp) oldw
G.panedAdd2 pane oldw
G.containerAdd (ppFrame pp) pane
writeIORef ref $ pp {ppNumChildren = ppNumChildren pp + 1, ppPanes = pane:(ppPanes pp)}
(1, _) -> do pane <- ppMkPaned pp
G.widgetShow pane
G.panedAdd2 pane w
oldw <- (liftM fromJust) $ G.binGetChild $ ppFrame pp
G.containerRemove (ppFrame pp) oldw
G.panedAdd1 pane oldw
G.containerAdd (ppFrame pp) pane
writeIORef ref $ pp {ppNumChildren = ppNumChildren pp + 1, ppPanes = [pane]}
(_,_) -> if i == ppNumChildren pp - 1
then do pane <- ppMkPaned pp
G.widgetShow pane
G.panedAdd2 pane w
oldw <- (liftM fromJust) $ G.panedGetChild2 $ last $ ppPanes pp
G.containerRemove (last $ ppPanes pp) oldw
G.panedAdd1 pane oldw
G.panedAdd2 (last $ ppPanes pp) pane
writeIORef ref $ pp {ppNumChildren = ppNumChildren pp + 1, ppPanes = (ppPanes pp)++[pane]}
else do pane <- ppMkPaned pp
G.widgetShow pane
G.panedAdd1 pane w
oldw <- (liftM fromJust) $ G.panedGetChild2 $ ppPanes pp !! i
G.containerRemove (ppPanes pp !! i) oldw
G.panedAdd2 pane oldw
G.panedAdd2 (ppPanes pp !! i) pane
writeIORef ref $ pp {ppNumChildren = ppNumChildren pp + 1, ppPanes = (take i $ ppPanes pp)++[pane]++(drop i $ ppPanes pp)}
ppDelete :: RPanedPanels -> Int -> IO ()
ppDelete ref i = do
pp <- readIORef ref
case (ppNumChildren pp, i) of
(1,_) -> do w <- (liftM fromJust) $ G.binGetChild $ ppFrame pp
G.containerRemove (ppFrame pp) w
writeIORef ref $ pp {ppNumChildren = 0}
(_,0) -> do w1 <- (liftM fromJust) $ G.panedGetChild1 (head $ ppPanes pp)
w2 <- (liftM fromJust) $ G.panedGetChild2 (head $ ppPanes pp)
G.containerRemove (head $ ppPanes pp) w1
G.containerRemove (head $ ppPanes pp) w2
G.containerRemove (ppFrame pp) (head $ ppPanes pp)
G.containerAdd (ppFrame pp) w2
writeIORef ref $ pp {ppNumChildren = ppNumChildren pp - 1, ppPanes = tail $ ppPanes pp}
(2,1) -> do w1 <- (liftM fromJust) $ G.panedGetChild1 (head $ ppPanes pp)
w2 <- (liftM fromJust) $ G.panedGetChild2 (head $ ppPanes pp)
G.containerRemove (head $ ppPanes pp) w1
G.containerRemove (head $ ppPanes pp) w2
G.containerRemove (ppFrame pp) (head $ ppPanes pp)
G.containerAdd (ppFrame pp) w1
writeIORef ref $ pp {ppNumChildren = 1, ppPanes = []}
(_,_) -> if i == ppNumChildren pp - 1
then do let pane = last $ ppPanes pp
prev = last $ init $ ppPanes pp
w1 <- (liftM fromJust) $ G.panedGetChild1 pane
w2 <- (liftM fromJust) $ G.panedGetChild2 pane
G.containerRemove pane w1
G.containerRemove pane w2
G.containerRemove prev pane
G.panedAdd2 prev w1
writeIORef ref $ pp {ppNumChildren = ppNumChildren pp - 1, ppPanes = init $ ppPanes pp}
else do let pane = ppPanes pp !! i
prev = ppPanes pp !! (i-1)
w1 <- (liftM fromJust) $ G.panedGetChild1 pane
w2 <- (liftM fromJust) $ G.panedGetChild2 pane
G.containerRemove pane w1
G.containerRemove pane w2
G.containerRemove prev pane
G.panedAdd2 prev w2
writeIORef ref $ pp {ppNumChildren = ppNumChildren pp - 1, ppPanes = (take i $ ppPanes pp)++(drop (i+1) $ ppPanes pp)}
if ppNumChildren pp == 1
then cbDelete $ ppCB pp
else return ()
ppGetIndex :: RPanedPanels -> G.Widget -> IO (Maybe Int)
ppGetIndex ref w = do
pp <- readIORef ref
if ppNumChildren pp == 1
then do w0 <- (liftM fromJust) $ G.binGetChild $ ppFrame pp
if w0 == w
then return $ Just 0
else return Nothing
else ppGetIndex' (ppPanes pp) w 0
ppGetIndex' :: [G.Paned] -> G.Widget -> Int -> IO (Maybe Int)
ppGetIndex' [] _ _ = return Nothing
ppGetIndex' [p] w i = do
w1 <- (liftM fromJust) $ G.panedGetChild1 p
w2 <- (liftM fromJust) $ G.panedGetChild2 p
if w1 == w
then return $ Just i
else if w2 == w
then return $ Just $ i + 1
else return Nothing
ppGetIndex' (p:ps) w i = do
w1 <- (liftM fromJust) $ G.panedGetChild1 p
if w1 == w
then return $ Just i
else ppGetIndex' ps w (i+1)
ppGetNumChildren :: RPanedPanels -> IO Int
ppGetNumChildren ref = do
pp <- readIORef ref
return $ ppNumChildren pp
ppWidget :: RPanedPanels -> IO G.Widget
ppWidget ref = do
pp <- readIORef ref
return $ G.toWidget $ ppFrame pp
ppSetCB :: RPanedPanels -> PanelCB -> IO ()
ppSetCB ref cb = do
pp <- readIORef ref
writeIORef ref $ pp {ppCB = cb}
---------------------------------------------------------------
-- Implementation of IDEPanels based on Notebook widget
---------------------------------------------------------------
data TabbedPanels = TabbedPanels {
tpNotebook :: G.Notebook,
tpNumChildren :: Int,
tpCB :: PanelCB
}
type RTabbedPanels = IORef TabbedPanels
tabbedPanelsNew :: IO IDEPanels
tabbedPanelsNew = do
nb <- G.notebookNew
G.notebookSetScrollable nb True
G.widgetShow nb
ref <- newIORef $ TabbedPanels { tpNotebook = nb
, tpNumChildren = 0
, tpCB = panelCBNull}
return $ IDEPanels { panelsInsert = tpInsert ref
, panelsDelete = tpDelete ref
, panelsGetIndex = tpGetIndex ref
, panelsGetNumChildren = tpGetNumChildren ref
, panelsGetWidget = tpWidget ref
, panelsSetCB = tpSetCB ref}
tpInsert :: RTabbedPanels -> Int -> G.Widget -> String -> IO ()
tpInsert ref i w n = do
tp <- readIORef ref
let i' = if i < tpNumChildren tp - 1
then i + 1
else -1
G.notebookInsertPage (tpNotebook tp) w n i'
writeIORef ref $ tp {tpNumChildren = tpNumChildren tp + 1}
tpDelete :: RTabbedPanels -> Int -> IO ()
tpDelete ref i = do
tp <- readIORef ref
G.notebookRemovePage (tpNotebook tp) i
writeIORef ref $ tp {tpNumChildren = tpNumChildren tp - 1}
if tpNumChildren tp == 1
then cbDelete $ tpCB tp
else return ()
tpGetIndex :: RTabbedPanels -> G.Widget -> IO (Maybe Int)
tpGetIndex ref w = do
tp <- readIORef ref
G.notebookPageNum (tpNotebook tp) w
tpGetNumChildren :: RTabbedPanels -> IO Int
tpGetNumChildren ref = do
tp <- readIORef ref
return $ tpNumChildren tp
tpWidget :: RTabbedPanels -> IO G.Widget
tpWidget ref = do
tp <- readIORef ref
return $ G.toWidget $ tpNotebook tp
tpSetCB :: RTabbedPanels -> PanelCB -> IO ()
tpSetCB ref cb = do
tp <- readIORef ref
writeIORef ref $ tp {tpCB = cb}
---------------------------------------------------------
-- Debugger IDE
---------------------------------------------------------
data IDE = IDE {
ideMain :: IDEPanels,
ideLeft :: Maybe IDEPanels,
ideTopBottom :: Maybe IDEPanels,
ideTop :: Maybe IDEPanels,
ideBottom :: Maybe IDEPanels,
ideCenter :: Maybe IDEPanels,
ideRight :: Maybe IDEPanels
}
type RIDE = IORef IDE
ideNew :: IO RIDE
ideNew = do
main <- panedPanelsNew ((liftM G.toPaned) G.hPanedNew)
newIORef $ IDE { ideMain = main
, ideLeft = Nothing
, ideTopBottom = Nothing
, ideTop = Nothing
, ideBottom = Nothing
, ideCenter = Nothing
, ideRight = Nothing}
ideWidget :: RIDE -> IO G.Widget
ideWidget ref = do
ide <- readIORef ref
panelsGetWidget $ ideMain ide
-- Create left panel if one does not exist
ideCreateLeft :: RIDE -> IO ()
ideCreateLeft ref = do
ide <- readIORef ref
case ideLeft ide of
Just _ -> return ()
Nothing -> do left <- panedPanelsNew ((liftM G.toPaned) G.vPanedNew)
w <- panelsGetWidget left
panelsPrepend (ideMain ide) w ""
panelsSetCB left (PanelCB $ ideDeleteLeft ref)
writeIORef ref $ ide {ideLeft = Just left}
ideDeleteLeft :: RIDE -> IO ()
ideDeleteLeft ref = do
ide <- readIORef ref
w <- panelsGetWidget $ fromJust $ ideLeft ide
writeIORef ref $ ide {ideLeft = Nothing}
panelsDeleteWidget (ideMain ide) w
ideCreateTopBottom :: RIDE -> IO ()
ideCreateTopBottom ref = do
ide <- readIORef ref
case ideTopBottom ide of
Just _ -> return ()
Nothing -> do tb <- panedPanelsNew ((liftM G.toPaned) G.vPanedNew)
w <- panelsGetWidget tb
panelsAppend (ideMain ide) w ""
panelsSetCB tb (PanelCB $ ideDeleteTopBottom ref)
writeIORef ref $ ide {ideTopBottom = Just tb}
ideDeleteTopBottom :: RIDE -> IO ()
ideDeleteTopBottom ref = do
ide <- readIORef ref
w <- panelsGetWidget $ fromJust $ ideTopBottom ide
writeIORef ref $ ide {ideTopBottom = Nothing}
panelsDeleteWidget (ideMain ide) w
ideCreateBottom :: RIDE -> IO ()
ideCreateBottom ref = do
ideCreateTopBottom ref
ide <- readIORef ref
case ideBottom ide of
Just _ -> return ()
Nothing -> do bottom <- tabbedPanelsNew
w <- panelsGetWidget bottom
panelsAppend (fromJust $ ideTopBottom ide) w ""
panelsSetCB bottom (PanelCB $ ideDeleteBottom ref)
writeIORef ref $ ide {ideBottom = Just bottom}
ideDeleteBottom :: RIDE -> IO ()
ideDeleteBottom ref = do
ide <- readIORef ref
w <- panelsGetWidget $ fromJust $ ideBottom ide
writeIORef ref $ ide {ideBottom = Nothing}
panelsDeleteWidget (fromJust $ ideTopBottom ide) w
ideCreateTop :: RIDE -> IO ()
ideCreateTop ref = do
ideCreateTopBottom ref
ide <- readIORef ref
case ideTop ide of
Just _ -> return ()
Nothing -> do top <- panedPanelsNew ((liftM G.toPaned) G.hPanedNew)
w <- panelsGetWidget top
panelsPrepend (fromJust $ ideTopBottom ide) w ""
panelsSetCB top (PanelCB $ ideDeleteTop ref)
writeIORef ref $ ide {ideTop = Just top}
ideDeleteTop :: RIDE -> IO ()
ideDeleteTop ref = do
ide <- readIORef ref
w <- panelsGetWidget $ fromJust $ ideTop ide
writeIORef ref $ ide {ideTop = Nothing}
panelsDeleteWidget (fromJust $ ideTopBottom ide) w
ideCreateCenter :: RIDE -> IO ()
ideCreateCenter ref = do
ideCreateTop ref
ide <- readIORef ref
case ideCenter ide of
Just _ -> return ()
Nothing -> do center <- panedPanelsNew ((liftM G.toPaned) G.hPanedNew)
w <- panelsGetWidget center
panelsPrepend (fromJust $ ideTop ide) w ""
panelsSetCB center (PanelCB $ ideDeleteCenter ref)
writeIORef ref $ ide {ideCenter = Just center}
ideDeleteCenter :: RIDE -> IO ()
ideDeleteCenter ref = do
ide <- readIORef ref
w <- panelsGetWidget $ fromJust $ ideCenter ide
writeIORef ref $ ide {ideCenter = Nothing}
panelsDeleteWidget (fromJust $ ideTop ide) w
ideCreateRight :: RIDE -> IO ()
ideCreateRight ref = do
ideCreateTop ref
ide <- readIORef ref
case ideRight ide of
Just _ -> return ()
Nothing -> do right <- panedPanelsNew ((liftM G.toPaned) G.vPanedNew)
w <- panelsGetWidget right
panelsAppend (fromJust $ ideTop ide) w ""
panelsSetCB right (PanelCB $ ideDeleteRight ref)
writeIORef ref $ ide {ideRight = Just right}
ideDeleteRight :: RIDE -> IO ()
ideDeleteRight ref = do
ide <- readIORef ref
w <- panelsGetWidget $ fromJust $ ideRight ide
writeIORef ref $ ide {ideRight = Nothing}
panelsDeleteWidget (fromJust $ ideTop ide) w
ideAddLeft :: RIDE -> IDEPanel -> IO ()
ideAddLeft ref panel = do
ideCreateLeft ref
ide <- readIORef ref
w <- panelGetWidget panel
n <- panelGetName panel
panelsAppend (fromJust $ ideLeft ide) w n
panelSetCB panel (PanelCB $ panelsDeleteWidget (fromJust $ ideLeft ide) w)
ideAddRight :: RIDE -> IDEPanel -> IO ()
ideAddRight ref panel = do
ideCreateRight ref
ide <- readIORef ref
w <- panelGetWidget panel
n <- panelGetName panel
panelsAppend (fromJust $ ideRight ide) w n
panelSetCB panel (PanelCB $ panelsDeleteWidget (fromJust $ ideRight ide) w)
ideAddCenter :: RIDE -> IDEPanel -> IO ()
ideAddCenter ref panel = do
ideCreateCenter ref
ide <- readIORef ref
w <- panelGetWidget panel
n <- panelGetName panel
panelsAppend (fromJust $ ideCenter ide) w n
panelSetCB panel (PanelCB $ panelsDeleteWidget (fromJust $ ideCenter ide) w)
ideAddBottom :: RIDE -> IDEPanel -> IO ()
ideAddBottom ref panel = do
ideCreateBottom ref
ide <- readIORef ref
w <- panelGetWidget panel
n <- panelGetName panel
panelsAppend (fromJust $ ideBottom ide) w n
panelSetCB panel (PanelCB $ panelsDeleteWidget (fromJust $ ideBottom ide) w)
ideRemove :: RIDE -> IDEPanel -> IO ()
ideRemove ref panel = do
ide <- readIORef ref
w <- panelGetWidget panel
case ideLeft ide of
Nothing -> return ()
Just p -> panelsDeleteWidget p w
case ideCenter ide of
Nothing -> return ()
Just p -> panelsDeleteWidget p w
case ideRight ide of
Nothing -> return ()
Just p -> panelsDeleteWidget p w
case ideBottom ide of
Nothing -> return ()
Just p -> panelsDeleteWidget p w
|
termite2/debug
|
Debug/IDE.hs
|
bsd-3-clause
| 20,149
| 0
| 21
| 7,183
| 6,190
| 2,981
| 3,209
| 447
| 6
|
module Language.Eiffel.Summary where
import qualified Data.ByteString.Char8 as B
import Data.Binary
import Language.Eiffel.Syntax
import Language.Eiffel.Parser.Class
import qualified Language.Eiffel.Parser.Lex as L
import Language.Eiffel.Parser
import Language.Eiffel.PrettyPrint
import Text.Parsec
import System.IO
summaryP :: L.Parser [ClasInterface]
summaryP = many clasInterfaceP
parseSummary :: String -> IO (Either ParseError [ClasInterface])
parseSummary fileName = lexThenParseFromFile summaryP fileName
writeSummary :: FilePath -> [ClasInterface] -> IO ()
writeSummary filePath ifaces =
withFile filePath WriteMode $ \ hdl ->
mapM_ (B.hPutStrLn hdl . B.pack . show . toInterfaceDoc) ifaces
readBinarySummary :: String -> IO [ClasInterface]
readBinarySummary = decodeFile
writeBinarySummary :: String -> [ClasInterface] -> IO ()
writeBinarySummary = encodeFile
|
scottgw/language-eiffel
|
Language/Eiffel/Summary.hs
|
bsd-3-clause
| 886
| 0
| 13
| 115
| 241
| 136
| 105
| 22
| 1
|
module MyOwnMaybe where
isJust :: Maybe a-> Bool
isJust (Just _) = True
isJust Nothing = False
isNothing = not . isJust
maybbe :: b -> (a -> b) -> Maybe a -> b
maybbe acc f Nothing = acc
maybbe acc f (Just n) = f n
fromMaybe :: a -> Maybe a -> a
fromMaybe a Nothing = a
fromMaybe a (Just a1) = a1
listToMaybe :: [a] -> Maybe a
listToMaybe [] = Nothing
listToMaybe (x:xs) = Just x
catMaybes :: [Maybe a] -> [a]
catMaybes = foldr go []
where go :: Maybe a -> [a] -> [a]
go Nothing xs = xs
go (Just x) xs = x:xs
flipMaybe :: [Maybe a] -> Maybe [a]
flipMaybe = foldr go (Just [])
where go :: Maybe a -> Maybe [a] -> Maybe [a]
go Nothing _ = Nothing
go _ Nothing = Nothing
go (Just x) (Just xs) = Just (x:xs)
|
chengzh2008/hpffp
|
src/ch12-SignalingAdversity/myOwnMaybe.hs
|
bsd-3-clause
| 755
| 0
| 10
| 206
| 397
| 203
| 194
| 25
| 3
|
module Memory where
data Memory = Memory [Int] Int [Int] deriving (Show)
peek :: Memory -> Int
peek (Memory _ c _) = c
write :: Memory -> Int -> Memory
write (Memory b _ f) i = Memory b i f
next :: Memory -> Memory
next (Memory b c []) = Memory (c:b) 0 []
next (Memory b c (f:fs)) = Memory (c:b) f fs
prev :: Memory -> Memory
prev (Memory [] c f) = Memory [] 0 (c:f)
prev (Memory (b:bs) c f) = Memory bs b (c:f)
inc :: Memory -> Memory
inc = add 1
add :: Int -> Memory -> Memory
add n (Memory b c f) = Memory b ((c + n) `mod` 255) f
dec :: Memory -> Memory
dec = sub 1
sub :: Int -> Memory -> Memory
sub n (Memory b c f) = Memory b ((c - n) `mod` 255) f
|
pdpi/brainfuck.hs
|
src/memory.hs
|
bsd-3-clause
| 671
| 0
| 9
| 171
| 411
| 216
| 195
| 20
| 1
|
module Demo where
import Control.Applicative
import Happstack.Server hiding (timeout)
import Happstack.Auth
import Text.Blaze
import Templates
-- Session timeouts
timeout :: Minutes
timeout = 5
demoResponse :: Html -- ^ Body
-> ServerPartT IO Response
demoResponse html = do
maybeSession <- getSessionData
uri <- rqUri <$> askRq
ok . toResponse $
defaultTemplate (defaultHeader Nothing)
(defaultBody maybeSession uri html)
--------------------------------------------------------------------------------
-- Response handler
demoHome :: ServerPartT IO Response
demoHome = demoResponse homeTemplate
demoRegister :: ServerPartT IO Response
demoRegister = withSession (demoResponse . loggedInTemplate) $ do
dat <- getDataFn . body $ (,) <$> look "username"
<*> look "password"
case dat of
Right (un,pw) -> do
register timeout un pw
(demoResponse $ invalidUsernameTemplate un)
(seeOther "/happstack-auth" $ toResponse "Registration OK")
_ -> demoResponse registerTemplate
demoLogin :: ServerPartT IO Response
demoLogin = withSession (demoResponse . loggedInTemplate) $
loginHandler timeout Nothing Nothing
(seeOther "/happstack-auth" $ toResponse "Login OK")
loginH
where
loginH (Just u) p = demoResponse $ loginFailTemplate u p
loginH _ _ = demoResponse loginTemplate
demoLogout :: ServerPartT IO Response
demoLogout = logoutHandler (seeOther "/happstack-auth" $ toResponse "Logout OK")
demoStats :: ServerPartT IO Response
demoStats = do
nu <- numUsers
ul <- listUsers
ns <- numSessions
demoResponse $ statsTemplate nu ul ns
|
mcmaniac/happstack-auth
|
demo/Demo.hs
|
bsd-3-clause
| 1,798
| 0
| 16
| 474
| 440
| 219
| 221
| 43
| 2
|
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.ARB.TextureGather
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.ARB.TextureGather (
-- * Extension Support
glGetARBTextureGather,
gl_ARB_texture_gather,
-- * Enums
pattern GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB,
pattern GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB,
pattern GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
|
haskell-opengl/OpenGLRaw
|
src/Graphics/GL/ARB/TextureGather.hs
|
bsd-3-clause
| 779
| 0
| 5
| 99
| 57
| 42
| 15
| 9
| 0
|
-- |
-- Module : Streamly.Network.Socket
-- Copyright : (c) 2018 Composewell Technologies
--
-- License : BSD3
-- Maintainer : streamly@composewell.com
-- Stability : experimental
-- Portability : GHC
--
-- A socket is a handle to a protocol endpoint.
--
-- This module provides APIs to read and write streams and arrays to and from
-- network sockets. Sockets may be connected or unconnected. Connected sockets
-- can only send or recv data to/from the connected endpoint, therefore, APIs
-- for connected sockets do not need to explicitly specify the remote endpoint.
-- APIs for unconnected sockets need to explicitly specify the remote endpoint.
--
-- = Programmer Notes
--
-- Read IO requests to connected stream sockets are performed in chunks of
-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize'. Unless specified
-- otherwise in the API, writes are collected into chunks of
-- 'Streamly.Internal.Memory.Array.Types.defaultChunkSize' before they are
-- written to the socket. APIs are provided to control the chunking behavior.
--
-- > import qualified Streamly.Network.Socket as SK
--
-- For additional, experimental APIs take a look at
-- "Streamly.Internal.Network.Socket" module.
-- By design, connected socket IO APIs are similar to
-- "Streamly.Memory.Array" read write APIs. They are almost identical to the
-- sequential streaming APIs in "Streamly.Internal.FileSystem.File".
--
module Streamly.Network.Socket
(
-- * Socket Specification
SockSpec(..)
-- * Accept Connections
, accept
-- * Read
, read
, readWithBufferOf
, readChunks
, readChunksWithBufferOf
-- * Write
, write
, writeWithBufferOf
, writeChunks
)
where
import Streamly.Internal.Network.Socket
import Prelude hiding (read)
|
harendra-kumar/asyncly
|
src/Streamly/Network/Socket.hs
|
bsd-3-clause
| 1,794
| 0
| 5
| 331
| 93
| 75
| 18
| 13
| 0
|
module SIGyM.Database (module X) where
import SIGyM.Database.Pool as X
import SIGyM.Database.TH as X
|
meteogrid/sigym-core
|
src/SIGyM/Database.hs
|
bsd-3-clause
| 103
| 0
| 4
| 15
| 28
| 20
| 8
| 3
| 0
|
module Language.Typo.Parser
( Language.Typo.Parser.parse -- :: FilePath -> String -> Either ParseError (Program Surface)
, program -- :: Parsec String u Program
, definition -- :: Parsec String u Definition
, surface -- :: Parsec String u Surface
, value -- :: Parsec String u Value
, operator -- :: Parsec String u Op
, operatorTable -- :: [(String, Op)]
) where
import Control.Applicative ( (<$>), (<*>), (*>) )
import qualified Language.Typo.Token as T
import Language.Typo.ASTs
import Text.Parsec
parse :: FilePath -> String -> Either ParseError (Program Surface)
parse = Text.Parsec.parse program
program :: Parsec String u (Program Surface)
program = T.whiteSpace *> (Program <$> (many definition) <*> surface)
-- N.B. `definition` cannot use the parens combinator because the `program`
-- parser needs to be able to backtrack past the left paren. If `definition`
-- did use the parens combinator, a `try` would have to wrap it. Instead,
-- the implementation uses a left paren parser and a string parser for the
-- "def" keyword, and wraps that sequence with `try`.
--
definition :: Parsec String u (Definition Surface)
definition = between start end
((T.parens $ Definition <$> T.identifier <*> (many T.identifier)) <*> surface)
where
start = try (lparen *> T.lexeme (string "define"))
end = rparen
lparen = T.lexeme (char '(')
rparen = T.lexeme (char ')')
surface :: Parsec String u Surface
surface = (T.parens nonval) <|> val
where
nonval = bop <|> (try $ _let <|> cond) <|> app
_let = do
T.lexeme (try $ string "let")
T.parens (Let <$> T.identifier <*> surface) <*> surface
cond = do
T.lexeme (try $ string "if" )
Cond <$> surface <*> surface <*> surface
bop = Bop <$> operator <*> surface <*> surface
app = App <$> T.identifier <*> (many surface)
val = Val <$> value
value :: Parsec String u Value
value = num <|> bool <|> ident
where
num = Number <$> fromIntegral <$> T.natural
bool = T.lexeme $ Boolean <$> do
char '#'
(char 't' *> return True) <|> (char 'f' *> return False)
ident = Id <$> T.identifier
operator :: Parsec String u Op
operator = do
op <- T.operator
case lookup op operatorTable of
Just op' -> return op'
Nothing -> fail $ "unrecognized operator: " ++ op
operatorTable :: [(String, Op)]
operatorTable = [
("+", Add)
, ("-", Sub)
, ("*", Mul)
, ("/", Div)
, ("%", Rem)
, ("&&", And)
, ("||", Or)
, ("->", Imp)
, ("==", Eq)
, ("<", Lt)
]
|
seliopou/typo
|
Language/Typo/Parser.hs
|
bsd-3-clause
| 2,575
| 0
| 14
| 617
| 767
| 424
| 343
| 60
| 2
|
{-# LANGUAGE FlexibleContexts #-}
-- |
-- Module: Network.Protocool.ZigBee.ZNet25.Encoder
-- Copyright: (c) 2012 David Joyner
-- License: BSD3
-- Maintainer: David Joyner <david@joynerhome.net>
-- Stability: experimental
-- Portability: portable
--
-- XBee ZNet 2.5 (ZigBee) frame encoder/decoder functions
module Network.Protocol.ZigBee.ZNet25.Encoder (
-- * Frame encoder
encode
-- * Stateful frame decoder
, DecoderState
, initDecode
, decode
) where
import Network.Protocol.ZigBee.ZNet25.Constants
import Network.Protocol.ZigBee.ZNet25.Frame
import Control.Monad
import qualified Control.Monad.State as S
import Data.Bits (xor)
import qualified Data.ByteString as B
import Data.Either.Utils (forceEither)
import qualified Data.Serialize as DS
import Data.Word
-- | Serialize a 'Frame', escape control characters, and wrap the result with
-- framing bytes. Return an array of 'B.ByteString' suitable for transmission
-- to the XBee modem.
--
-- Note that this function returns an array of 'B.ByteString'. Encoding
-- takes place in a piece-wise manner and for efficiency's sake the individual
-- bits are not concatenated to form a single 'B.ByteString'. Typically this is
-- a non-issue however if you need a single 'B.ByteString' representation of the
-- 'Frame' you can always obtain it by calling 'B.concat'.
--
-- Here's an example that illustrates 'encode' usage as well as the
-- on-the-wire frame format:
--
-- > import qualified Data.ByteString as B
-- > import Network.Protocol.ZigBee.ZNet25
-- > import Text.Printf
-- >
-- > main = hexdump $ B.concat $ encode (ATCommand 0 (commandName "ND") B.empty)
-- >
-- > hexdump = mapM_ (putStr . printf "%02x ") . B.unpack
--
-- This prints:
--
-- > 7e 00 04 08 00 4e 44 65
--
-- The leading @7e@ byte is the frame delimiter. This is followed by the 16-bit
-- frame length (4 bytes in this case), that many bytes of data (the
-- serialized 'ATCommand' frame), and the final checksum byte.
encode :: Frame -> [B.ByteString]
encode f = [ B.singleton ctrlFrameDelim, len, f_esc, cksum ]
where
f_enc = DS.encode f
f_esc = escapeBuffer f_enc
len = (escapeBuffer . DS.runPut . DS.putWord16be .
fromIntegral . B.length) f_enc
cksum = escapeBuffer $ B.singleton $ 0xff - (B.foldl (+) 0 f_enc)
data FrameState = Hunting
| GetLength
| GetData deriving Show
-- | 'decode' runs in the 'S.State' monad. @DecoderState@ tracks the
-- decoder's in/out-of frame state, current frame length, and other state
-- variables.
data DecoderState = DS
{ dsFrameState :: FrameState
, dsFrameLength :: Int
, dsEscapedChar :: Bool
, dsBuffer :: B.ByteString } deriving Show
-- | Initial state needed to run 'decode' in the 'S.State' monad.
initDecode :: DecoderState
initDecode = DS Hunting 0 False B.empty
-- | Decode a 'B.ByteString' in the 'S.State' monad, reversing the 'encode'
-- process. Once a frame delimiter byte is found, the inner frame payload is
-- unescaped, the checksum is verified, and finally a 'Frame' is deserialized.
--
-- Note that this function may produce zero or more errors or 'Frame's depending
-- on the 'DecoderState' and input byte string. Errors will be reported for
-- checksum errors and 'Frame' deserialization failures.
--
-- Here's a slightly more complex example that 'encode's two separate frames,
-- runs each array of 'B.ByteString's through @decode@ and prints the result
-- after running the 'S.State' monad:
--
-- > import Control.Monad.State
-- > import qualified Data.ByteString as B
-- > import Network.Protocol.ZigBee.ZNet25
-- >
-- > main = putStrLn $ show $ evalState (mapM decode bs) initDecode
-- > where
-- > bs = concat $ map encode [atndCommand, txRequest]
-- > atndCommand = ATCommand 1 (commandName "ND") B.empty
-- > txRequest = ZigBeeTransmitRequest 2 addr nwaddr 0 0 $ B.singleton 0x55
-- > addr = address $ B.pack [ 0xde, 0xad, 0xbe, 0xef, 0xba, 0xda, 0xba, 0xda ]
-- > nwaddr = networkAddress $ B.pack [ 0x55, 0xaa ]
--
-- This prints:
--
-- > [[],[],[],[Right (ATCommand 1 "ND" "")],[],[],[],[Right (ZigBeeTransmitRequest 2 de:ad:be:ef:ba:da:ba:da 55:aa 0 0 "U")]]
--
-- Note a few things:
--
-- * Each call to 'encode' apparently produced four separate 'B.ByteString's.
-- This is a by-product of the 'encode' implementation as described above.
--
-- * @decode@ was only able to produce a result once the final 'B.ByteString'
-- of each 'Frame' was processed. In this case the result was
-- 'Right' 'Frame'. If an error had occurred, we'd see 'Left' 'String'
-- instead.
decode :: S.MonadState DecoderState m => B.ByteString -> m [Either String Frame]
decode bs0 = do
ds <- S.get
let t = S.runState (unescapeBuffer bs0) $ dsEscapedChar ds
go ds { dsEscapedChar = snd t } $ fst t
where
-- Drop bytes until a frame delimiter is found
go ds@(DS Hunting _ _ _) bs
| B.null bs = S.put ds >> return []
| B.head bs == ctrlFrameDelim = go ds_gl $ B.tail bs
| otherwise = go ds $ B.tail bs
where
ds_gl = ds { dsFrameState = GetLength, dsBuffer = B.empty }
-- Once we have at least two bytes of unescaped data,
-- deserialize the length (add one byte for trailing checksum)
go ds@(DS GetLength _ _ buf) bs
| B.length buf' >= 2 = go ds_gd $ B.drop 2 buf'
| otherwise = S.put ds_gl >> return []
where
buf' = B.append buf bs
len' = (fromIntegral . forceEither . DS.runGet DS.getWord16be) buf' + 1
ds_gd = ds { dsFrameState = GetData
, dsFrameLength = len'
, dsBuffer = B.empty }
ds_gl = ds { dsBuffer = buf' }
-- Once we've accumulated the whole frame (including the checksum byte)
-- then we can decode and output the result
go ds@(DS GetData len _ buf) bs
| B.length buf' >= len = liftM (result:) $ go ds_h $ B.drop len buf'
| otherwise = S.put ds_gd >> return []
where
result
| cksum_ok = case DS.decode $ B.take (len - 1) buf' of
Left err -> Left $ "Decode error: " ++ err
Right f -> Right (f :: Frame)
| otherwise = Left "Checksum error"
buf' = B.append buf bs
cksum_ok = B.foldl (+) 0 (B.take len buf') == 0xff
ds_h = initDecode
ds_gd = ds { dsBuffer = buf' }
escapeBuffer :: B.ByteString -> B.ByteString
escapeBuffer = B.concat . fmap B.pack . map escapeChar . B.unpack
unescapeBuffer :: S.MonadState Bool m => B.ByteString -> m B.ByteString
unescapeBuffer = liftM (B.pack . concat) . mapM unescapeChar . B.unpack
escapeChar :: Word8 -> [Word8]
escapeChar c
| isControlChar c = [ctrlEscape, c `xor` 0x20]
| otherwise = [c]
unescapeChar :: S.MonadState Bool m => Word8 -> m [Word8]
unescapeChar c = S.get >>= unescape
where
unescape True = S.put False >> return [c `xor` 0x20]
unescape False
| c == ctrlEscape = S.put True >> return []
| otherwise = return [c]
isControlChar :: Word8 -> Bool
isControlChar c
| c == ctrlFrameDelim = True
| c == ctrlEscape = True
| c == ctrlXon = True
| c == ctrlXoff = True
| otherwise = False
|
djoyner/zigbee-znet25
|
src/Network/Protocol/ZigBee/ZNet25/Encoder.hs
|
bsd-3-clause
| 7,343
| 0
| 14
| 1,775
| 1,346
| 736
| 610
| 84
| 4
|
{- Data/Singletons/Promote.hs
(c) Richard Eisenberg 2013
eir@cis.upenn.edu
This file contains functions to promote term-level constructs to the
type level. It is an internal module to the singletons package.
-}
{-# LANGUAGE TemplateHaskell, MultiWayIf, LambdaCase, TupleSections #-}
module Data.Singletons.Promote where
import Language.Haskell.TH hiding ( Q, cxt )
import Language.Haskell.TH.Syntax ( Quasi(..) )
import Language.Haskell.TH.Desugar
import Data.Singletons.Names
import Data.Singletons.Promote.Monad
import Data.Singletons.Promote.Eq
import Data.Singletons.Promote.Defun
import Data.Singletons.Promote.Type
import Data.Singletons.Deriving.Ord
import Data.Singletons.Deriving.Bounded
import Data.Singletons.Deriving.Enum
import Data.Singletons.Partition
import Data.Singletons.Util
import Data.Singletons.Syntax
import Prelude hiding (exp)
import Control.Monad
import qualified Data.Map.Strict as Map
import Data.Map.Strict ( Map )
import Data.Maybe
-- | Generate promoted definitions from a type that is already defined.
-- This is generally only useful with classes.
genPromotions :: DsMonad q => [Name] -> q [Dec]
genPromotions names = do
checkForRep names
infos <- mapM reifyWithWarning names
dinfos <- mapM dsInfo infos
ddecs <- promoteM_ [] $ mapM_ promoteInfo dinfos
return $ decsToTH ddecs
-- | Promote every declaration given to the type level, retaining the originals.
promote :: DsMonad q => q [Dec] -> q [Dec]
promote qdec = do
decls <- qdec
ddecls <- withLocalDeclarations decls $ dsDecs decls
promDecls <- promoteM_ decls $ promoteDecs ddecls
return $ decls ++ decsToTH promDecls
-- | Promote each declaration, discarding the originals. Note that a promoted
-- datatype uses the same definition as an original datatype, so this will
-- not work with datatypes. Classes, instances, and functions are all fine.
promoteOnly :: DsMonad q => q [Dec] -> q [Dec]
promoteOnly qdec = do
decls <- qdec
ddecls <- dsDecs decls
promDecls <- promoteM_ decls $ promoteDecs ddecls
return $ decsToTH promDecls
-- | Generate defunctionalization symbols for existing type family
genDefunSymbols :: DsMonad q => [Name] -> q [Dec]
genDefunSymbols names = do
checkForRep names
infos <- mapM (dsInfo <=< reifyWithWarning) names
decs <- promoteMDecs [] $ concatMapM defunInfo infos
return $ decsToTH decs
-- | Produce instances for '(:==)' (type-level equality) from the given types
promoteEqInstances :: DsMonad q => [Name] -> q [Dec]
promoteEqInstances = concatMapM promoteEqInstance
-- | Produce instances for 'POrd' from the given types
promoteOrdInstances :: DsMonad q => [Name] -> q [Dec]
promoteOrdInstances = concatMapM promoteOrdInstance
-- | Produce an instance for 'POrd' from the given type
promoteOrdInstance :: DsMonad q => Name -> q [Dec]
promoteOrdInstance = promoteInstance mkOrdInstance "Ord"
-- | Produce instances for 'PBounded' from the given types
promoteBoundedInstances :: DsMonad q => [Name] -> q [Dec]
promoteBoundedInstances = concatMapM promoteBoundedInstance
-- | Produce an instance for 'PBounded' from the given type
promoteBoundedInstance :: DsMonad q => Name -> q [Dec]
promoteBoundedInstance = promoteInstance mkBoundedInstance "Bounded"
-- | Produce instances for 'PEnum' from the given types
promoteEnumInstances :: DsMonad q => [Name] -> q [Dec]
promoteEnumInstances = concatMapM promoteEnumInstance
-- | Produce an instance for 'PEnum' from the given type
promoteEnumInstance :: DsMonad q => Name -> q [Dec]
promoteEnumInstance = promoteInstance mkEnumInstance "Enum"
-- | Produce an instance for '(:==)' (type-level equality) from the given type
promoteEqInstance :: DsMonad q => Name -> q [Dec]
promoteEqInstance name = do
(_tvbs, cons) <- getDataD "I cannot make an instance of (:==) for it." name
cons' <- concatMapM dsCon cons
vars <- replicateM (length _tvbs) (qNewName "k")
kind <- promoteType (foldType (DConT name) (map DVarT vars))
inst_decs <- mkEqTypeInstance kind cons'
return $ decsToTH inst_decs
promoteInstance :: DsMonad q => (DType -> [DCon] -> q UInstDecl)
-> String -> Name -> q [Dec]
promoteInstance mk_inst class_name name = do
(tvbs, cons) <- getDataD ("I cannot make an instance of " ++ class_name
++ " for it.") name
cons' <- concatMapM dsCon cons
tvbs' <- mapM dsTvb tvbs
raw_inst <- mk_inst (foldType (DConT name) (map tvbToType tvbs')) cons'
decs <- promoteM_ [] $ void $ promoteInstanceDec Map.empty raw_inst
return $ decsToTH decs
promoteInfo :: DInfo -> PrM ()
promoteInfo (DTyConI dec _instances) = promoteDecs [dec]
promoteInfo (DPrimTyConI _name _numArgs _unlifted) =
fail "Promotion of primitive type constructors not supported"
promoteInfo (DVarI _name _ty _mdec) =
fail "Promotion of individual values not supported"
promoteInfo (DTyVarI _name _ty) =
fail "Promotion of individual type variables not supported"
-- Note [Promoting declarations in two stages]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- It is necessary to know the types of things when promoting. So,
-- we promote in two stages: first, we build a LetDecEnv, which allows
-- for easy lookup. Then, we go through the actual elements of the LetDecEnv,
-- performing the promotion.
--
-- Why do we need the types? For kind annotations on the type family. We also
-- need to have both the types and the actual function definition at the same
-- time, because the function definition tells us how many patterns are
-- matched. Note that an eta-contracted function needs to return a TyFun,
-- not a proper type-level function.
--
-- Consider this example:
--
-- foo :: Nat -> Bool -> Bool
-- foo Zero = id
-- foo _ = not
--
-- Here the first parameter to foo is non-uniform, because it is
-- inspected in a pattern and can be different in each defining
-- equation of foo. The second parameter to foo, specified in the type
-- signature as Bool, is a uniform parameter - it is not inspected and
-- each defining equation of foo uses it the same way. The foo
-- function will be promoted to a type familty Foo like this:
--
-- type family Foo (n :: Nat) :: TyFun Bool Bool -> * where
-- Foo Zero = Id
-- Foo a = Not
--
-- To generate type signature for Foo type family we must first learn
-- what is the actual number of patterns used in defining cequations
-- of foo. In this case there is only one so we declare Foo to take
-- one argument and have return type of Bool -> Bool.
-- Promote a list of top-level declarations.
promoteDecs :: [DDec] -> PrM ()
promoteDecs raw_decls = do
decls <- expand raw_decls -- expand type synonyms
checkForRepInDecls decls
PDecs { pd_let_decs = let_decs
, pd_class_decs = classes
, pd_instance_decs = insts
, pd_data_decs = datas } <- partitionDecs decls
-- promoteLetDecs returns LetBinds, which we don't need at top level
_ <- promoteLetDecs noPrefix let_decs
mapM_ promoteClassDec classes
let all_meth_sigs = foldMap (lde_types . cd_lde) classes
mapM_ (promoteInstanceDec all_meth_sigs) insts
promoteDataDecs datas
promoteDataDecs :: [DataDecl] -> PrM ()
promoteDataDecs data_decs = do
rec_selectors <- concatMapM extract_rec_selectors data_decs
_ <- promoteLetDecs noPrefix rec_selectors
mapM_ promoteDataDec data_decs
where
extract_rec_selectors :: DataDecl -> PrM [DLetDec]
extract_rec_selectors (DataDecl _nd data_name tvbs cons _derivings) =
let arg_ty = foldType (DConT data_name)
(map tvbToType tvbs)
in
concatMapM (getRecordSelectors arg_ty) cons
-- curious about ALetDecEnv? See the LetDecEnv module for an explanation.
promoteLetDecs :: (String, String) -- (alpha, symb) prefixes to use
-> [DLetDec] -> PrM ([LetBind], ALetDecEnv)
-- See Note [Promoting declarations in two stages]
promoteLetDecs prefixes decls = do
let_dec_env <- buildLetDecEnv decls
all_locals <- allLocals
let binds = [ (name, foldType (DConT sym) (map DVarT all_locals))
| name <- Map.keys $ lde_defns let_dec_env
, let proName = promoteValNameLhsPrefix prefixes name
sym = promoteTySym proName (length all_locals) ]
(decs, let_dec_env') <- letBind binds $ promoteLetDecEnv prefixes let_dec_env
emitDecs decs
return (binds, let_dec_env' { lde_proms = Map.fromList binds })
-- Promotion of data types to kinds is automatic (see "Ginving Haskell a
-- Promotion" paper for more details). Here we "plug into" the promotion
-- mechanism to add some extra stuff to the promotion:
--
-- * if data type derives Eq we generate a type family that implements the
-- equality test for the data type.
--
-- * for each data constructor with arity greater than 0 we generate type level
-- symbols for use with Apply type family. In this way promoted data
-- constructors and promoted functions can be used in a uniform way at the
-- type level in the same way they can be used uniformly at the type level.
--
-- * for each nullary data constructor we generate a type synonym
promoteDataDec :: DataDecl -> PrM ()
promoteDataDec (DataDecl _nd name tvbs ctors derivings) = do
-- deriving Eq instance
kvs <- replicateM (length tvbs) (qNewName "k")
kind <- promoteType (foldType (DConT name) (map DVarT kvs))
when (any (\case DConPr n -> n == eqName
_ -> False) derivings) $ do
eq_decs <- mkEqTypeInstance kind ctors
emitDecs eq_decs
ctorSyms <- buildDefunSymsDataD name tvbs ctors
emitDecs ctorSyms
-- Note [CUSKification]
-- ~~~~~~~~~~~~~~~~~~~~
-- GHC #12928 means that sometimes, this TH code will produce a declaration
-- that has a kind signature even when we want kind inference to work. There
-- seems to be no way to avoid this, so we embrace it:
--
-- * If a class type variable has no explicit kind, we make no effort to
-- guess it and default to *. This is OK because before TypeInType we were
-- limited by KProxy anyway.
--
-- * If a class type variable has an explicit kind, it is preserved.
--
-- This way, we always get proper CUSKs where we need them.
promoteClassDec :: UClassDecl
-> PrM AClassDecl
promoteClassDec decl@(ClassDecl { cd_cxt = cxt
, cd_name = cls_name
, cd_tvbs = tvbs'
, cd_fds = fundeps
, cd_lde = lde@LetDecEnv
{ lde_defns = defaults
, lde_types = meth_sigs
, lde_infix = infix_decls } }) = do
let
-- a workaround for GHC Trac #12928; see Note [CUSKification]
cuskify :: DTyVarBndr -> DTyVarBndr
cuskify (DPlainTV tvname) = DKindedTV tvname DStarT
cuskify tv = tv
tvbs = map cuskify tvbs'
let pClsName = promoteClassName cls_name
pCxt <- mapM promote_superclass_pred cxt
sig_decs <- mapM (uncurry promote_sig) (Map.toList meth_sigs)
let defaults_list = Map.toList defaults
defaults_names = map fst defaults_list
(default_decs, ann_rhss, prom_rhss)
<- mapAndUnzip3M (promoteMethod Nothing meth_sigs) defaults_list
let infix_decls' = catMaybes $ map (uncurry promoteInfixDecl) infix_decls
-- no need to do anything to the fundeps. They work as is!
emitDecs [DClassD pCxt pClsName tvbs fundeps
(sig_decs ++ default_decs ++ infix_decls')]
let defaults_list' = zip defaults_names ann_rhss
proms = zip defaults_names prom_rhss
return (decl { cd_lde = lde { lde_defns = Map.fromList defaults_list'
, lde_proms = Map.fromList proms } })
where
promote_sig :: Name -> DType -> PrM DDec
promote_sig name ty = do
let proName = promoteValNameLhs name
(argKs, resK) <- promoteUnraveled ty
args <- mapM (const $ qNewName "arg") argKs
emitDecsM $ defunctionalize proName (map Just argKs) (Just resK)
return $ DOpenTypeFamilyD (DTypeFamilyHead proName
(zipWith DKindedTV args argKs)
(DKindSig resK)
Nothing)
promote_superclass_pred :: DPred -> PrM DPred
promote_superclass_pred = go
where
go (DAppPr pr ty) = DAppPr <$> go pr <*> promoteType ty
go (DSigPr pr _k) = go pr -- just ignore the kind; it can't matter
go (DVarPr name) = fail $ "Cannot promote ConstraintKinds variables like "
++ show name
go (DConPr name) = return $ DConPr (promoteClassName name)
go DWildCardPr = return DWildCardPr
-- returns (unpromoted method name, ALetDecRHS) pairs
promoteInstanceDec :: Map Name DType -> UInstDecl -> PrM AInstDecl
promoteInstanceDec meth_sigs
decl@(InstDecl { id_name = cls_name
, id_arg_tys = inst_tys
, id_meths = meths }) = do
cls_tvb_names <- lookup_cls_tvb_names
inst_kis <- mapM promoteType inst_tys
let subst = Map.fromList $ zip cls_tvb_names inst_kis
(meths', ann_rhss, _) <- mapAndUnzip3M (promoteMethod (Just subst) meth_sigs) meths
emitDecs [DInstanceD Nothing [] (foldType (DConT pClsName)
inst_kis) meths']
return (decl { id_meths = zip (map fst meths) ann_rhss })
where
pClsName = promoteClassName cls_name
lookup_cls_tvb_names :: PrM [Name]
lookup_cls_tvb_names = do
mb_info <- dsReify pClsName
case mb_info of
Just (DTyConI (DClassD _ _ tvbs _ _) _) -> return (map extractTvbName tvbs)
_ -> do
mb_info' <- dsReify cls_name
case mb_info' of
Just (DTyConI (DClassD _ _ tvbs _ _) _) -> return (map extractTvbName tvbs)
_ -> fail $ "Cannot find class declaration annotation for " ++ show cls_name
-- promoteMethod needs to substitute in a method's kind because GHC does not do
-- enough kind checking of associated types. See GHC#9063. When that bug is fixed,
-- the substitution code can be removed.
-- Bug is fixed, but only in HEAD, naturally. When we stop supporting 7.8,
-- this can be rewritten more cleanly, I imagine.
-- UPDATE: GHC 7.10.2 didn't fully solve GHC#9063. Urgh.
promoteMethod :: Maybe (Map Name DKind)
-- ^ instantiations for class tyvars (Nothing for default decls)
-> Map Name DType -- method types
-> (Name, ULetDecRHS)
-> PrM (DDec, ALetDecRHS, DType)
-- returns (type instance, ALetDecRHS, promoted RHS)
promoteMethod m_subst sigs_map (meth_name, meth_rhs) = do
(arg_kis, res_ki) <- lookup_meth_ty
((_, _, _, eqns), _defuns, ann_rhs)
<- promoteLetDecRHS (Just (arg_kis, res_ki)) sigs_map noPrefix meth_name meth_rhs
meth_arg_tvs <- mapM (const $ qNewName "a") arg_kis
let do_subst = maybe id substKind m_subst
meth_arg_kis' = map do_subst arg_kis
meth_res_ki' = do_subst res_ki
helperNameBase = case nameBase proName of
first:_ | not (isHsLetter first) -> "TFHelper"
alpha -> alpha
family_args
-- GHC 8 requires bare tyvars to the left of a type family default
| Nothing <- m_subst
= map DVarT meth_arg_tvs
| otherwise
= zipWith (DSigT . DVarT) meth_arg_tvs meth_arg_kis'
helperName <- newUniqueName helperNameBase
emitDecs [DClosedTypeFamilyD (DTypeFamilyHead
helperName
(zipWith DKindedTV meth_arg_tvs meth_arg_kis')
(DKindSig meth_res_ki')
Nothing)
eqns]
emitDecsM (defunctionalize helperName (map Just meth_arg_kis') (Just meth_res_ki'))
return ( DTySynInstD
proName
(DTySynEqn family_args
(foldApply (promoteValRhs helperName) (map DVarT meth_arg_tvs)))
, ann_rhs
, DConT (promoteTySym helperName 0) )
where
proName = promoteValNameLhs meth_name
lookup_meth_ty :: PrM ([DKind], DKind)
lookup_meth_ty = case Map.lookup meth_name sigs_map of
Nothing -> do
mb_info <- dsReify proName
case mb_info of
Just (DTyConI (DOpenTypeFamilyD (DTypeFamilyHead _ tvbs mb_res_ki _)) _)
-> let arg_kis = map (default_to_star . extractTvbKind) tvbs
res_ki = default_to_star (resultSigToMaybeKind mb_res_ki)
in return (arg_kis, res_ki)
_ -> fail $ "Cannot find type annotation for " ++ show proName
Just ty -> promoteUnraveled ty
default_to_star Nothing = DStarT
default_to_star (Just k) = k
promoteLetDecEnv :: (String, String) -> ULetDecEnv -> PrM ([DDec], ALetDecEnv)
promoteLetDecEnv prefixes (LetDecEnv { lde_defns = value_env
, lde_types = type_env
, lde_infix = infix_decls }) = do
let infix_decls' = catMaybes $ map (uncurry promoteInfixDecl) infix_decls
-- promote all the declarations, producing annotated declarations
let (names, rhss) = unzip $ Map.toList value_env
(payloads, defun_decss, ann_rhss)
<- fmap unzip3 $ zipWithM (promoteLetDecRHS Nothing type_env prefixes) names rhss
emitDecs $ concat defun_decss
let decs = map payload_to_dec payloads ++ infix_decls'
-- build the ALetDecEnv
let let_dec_env' = LetDecEnv { lde_defns = Map.fromList $ zip names ann_rhss
, lde_types = type_env
, lde_infix = infix_decls
, lde_proms = Map.empty } -- filled in promoteLetDecs
return (decs, let_dec_env')
where
payload_to_dec (name, tvbs, m_ki, eqns) = DClosedTypeFamilyD
(DTypeFamilyHead name tvbs sig Nothing)
eqns
where
sig = maybe DNoSig DKindSig m_ki
promoteInfixDecl :: Fixity -> Name -> Maybe DDec
promoteInfixDecl fixity name
| isUpcase name = Nothing -- no need to promote the decl
| otherwise = Just $ DLetDec $ DInfixD fixity (promoteValNameLhs name)
-- This function is used both to promote class method defaults and normal
-- let bindings. Thus, it can't quite do all the work locally and returns
-- an intermediate structure. Perhaps a better design is available.
promoteLetDecRHS :: Maybe ([DKind], DKind) -- the promoted type of the RHS (if known)
-- needed to fix #136
-> Map Name DType -- local type env't
-> (String, String) -- let-binding prefixes
-> Name -- name of the thing being promoted
-> ULetDecRHS -- body of the thing
-> PrM ( (Name, [DTyVarBndr], Maybe DKind, [DTySynEqn]) -- "type family"
, [DDec] -- defunctionalization
, ALetDecRHS ) -- annotated RHS
promoteLetDecRHS m_rhs_ki type_env prefixes name (UValue exp) = do
(res_kind, num_arrows)
<- case m_rhs_ki of
Just (arg_kis, res_ki) -> return ( Just (ravelTyFun (arg_kis ++ [res_ki]))
, length arg_kis )
_ | Just ty <- Map.lookup name type_env
-> do ki <- promoteType ty
return (Just ki, countArgs ty)
| otherwise
-> return (Nothing, 0)
case num_arrows of
0 -> do
all_locals <- allLocals
(exp', ann_exp) <- promoteExp exp
let proName = promoteValNameLhsPrefix prefixes name
defuns <- defunctionalize proName (map (const Nothing) all_locals) res_kind
return ( ( proName, map DPlainTV all_locals, res_kind
, [DTySynEqn (map DVarT all_locals) exp'] )
, defuns
, AValue (foldType (DConT proName) (map DVarT all_locals))
num_arrows ann_exp )
_ -> do
names <- replicateM num_arrows (newUniqueName "a")
let pats = map DVarPa names
newArgs = map DVarE names
promoteLetDecRHS m_rhs_ki type_env prefixes name
(UFunction [DClause pats (foldExp exp newArgs)])
promoteLetDecRHS m_rhs_ki type_env prefixes name (UFunction clauses) = do
numArgs <- count_args clauses
(m_argKs, m_resK, ty_num_args) <- case m_rhs_ki of
Just (arg_kis, res_ki) -> return (map Just arg_kis, Just res_ki, length arg_kis)
_ | Just ty <- Map.lookup name type_env
-> do
-- promoteType turns arrows into TyFun. So, we unravel first to
-- avoid this behavior. Note the use of ravelTyFun in resultK
-- to make the return kind work out
(argKs, resultK) <- promoteUnraveled ty
-- invariant: countArgs ty == length argKs
return (map Just argKs, Just resultK, length argKs)
| otherwise
-> return (replicate numArgs Nothing, Nothing, numArgs)
let proName = promoteValNameLhsPrefix prefixes name
all_locals <- allLocals
defun_decs <- defunctionalize proName
(map (const Nothing) all_locals ++ m_argKs) m_resK
let local_tvbs = map DPlainTV all_locals
tyvarNames <- mapM (const $ qNewName "a") m_argKs
expClauses <- mapM (etaExpand (ty_num_args - numArgs)) clauses
(eqns, ann_clauses) <- mapAndUnzipM promoteClause expClauses
prom_fun <- lookupVarE name
let args = zipWith inferMaybeKindTV tyvarNames m_argKs
all_args = local_tvbs ++ args
return ( (proName, all_args, m_resK, eqns)
, defun_decs
, AFunction prom_fun ty_num_args ann_clauses )
where
etaExpand :: Int -> DClause -> PrM DClause
etaExpand n (DClause pats exp) = do
names <- replicateM n (newUniqueName "a")
let newPats = map DVarPa names
newArgs = map DVarE names
return $ DClause (pats ++ newPats) (foldExp exp newArgs)
count_args (DClause pats _ : _) = return $ length pats
count_args _ = fail $ "Impossible! A function without clauses."
promoteClause :: DClause -> PrM (DTySynEqn, ADClause)
promoteClause (DClause pats exp) = do
-- promoting the patterns creates variable bindings. These are passed
-- to the function promoted the RHS
((types, pats'), new_vars) <- evalForPair $ mapAndUnzipM promotePat pats
(ty, ann_exp) <- lambdaBind new_vars $ promoteExp exp
all_locals <- allLocals -- these are bound *outside* of this clause
return ( DTySynEqn (map DVarT all_locals ++ types) ty
, ADClause new_vars pats' ann_exp )
promoteMatch :: DType -> DMatch -> PrM (DTySynEqn, ADMatch)
promoteMatch prom_case (DMatch pat exp) = do
-- promoting the patterns creates variable bindings. These are passed
-- to the function promoted the RHS
((ty, pat'), new_vars) <- evalForPair $ promotePat pat
(rhs, ann_exp) <- lambdaBind new_vars $ promoteExp exp
all_locals <- allLocals
return $ ( DTySynEqn (map DVarT all_locals ++ [ty]) rhs
, ADMatch new_vars prom_case pat' ann_exp)
-- promotes a term pattern into a type pattern, accumulating bound variable names
-- See Note [No wildcards in singletons]
promotePat :: DPat -> QWithAux VarPromotions PrM (DType, DPat)
promotePat (DLitPa lit) = do
lit' <- promoteLitPat lit
return (lit', DLitPa lit)
promotePat (DVarPa name) = do
-- term vars can be symbols... type vars can't!
tyName <- mkTyName name
addElement (name, tyName)
return (DVarT tyName, DVarPa name)
promotePat (DConPa name pats) = do
(types, pats') <- mapAndUnzipM promotePat pats
let name' = unboxed_tuple_to_tuple name
return (foldType (DConT name') types, DConPa name pats')
where
unboxed_tuple_to_tuple n
| Just deg <- unboxedTupleNameDegree_maybe n = tupleDataName deg
| otherwise = n
promotePat (DTildePa pat) = do
qReportWarning "Lazy pattern converted into regular pattern in promotion"
(ty, pat') <- promotePat pat
return (ty, DTildePa pat')
promotePat (DBangPa pat) = do
qReportWarning "Strict pattern converted into regular pattern in promotion"
(ty, pat') <- promotePat pat
return (ty, DBangPa pat')
promotePat DWildPa = do
name <- newUniqueName "_z"
tyName <- mkTyName name
addElement (name, tyName)
return (DVarT tyName, DVarPa name)
promoteExp :: DExp -> PrM (DType, ADExp)
promoteExp (DVarE name) = fmap (, ADVarE name) $ lookupVarE name
promoteExp (DConE name) = return $ (promoteValRhs name, ADConE name)
promoteExp (DLitE lit) = fmap (, ADLitE lit) $ promoteLitExp lit
promoteExp (DAppE exp1 exp2) = do
(exp1', ann_exp1) <- promoteExp exp1
(exp2', ann_exp2) <- promoteExp exp2
return (apply exp1' exp2', ADAppE ann_exp1 ann_exp2)
promoteExp (DLamE names exp) = do
lambdaName <- newUniqueName "Lambda"
tyNames <- mapM mkTyName names
let var_proms = zip names tyNames
(rhs, ann_exp) <- lambdaBind var_proms $ promoteExp exp
tyFamLamTypes <- mapM (const $ qNewName "t") names
all_locals <- allLocals
let all_args = all_locals ++ tyFamLamTypes
tvbs = map DPlainTV all_args
emitDecs [DClosedTypeFamilyD (DTypeFamilyHead
lambdaName
tvbs
DNoSig
Nothing)
[DTySynEqn (map DVarT (all_locals ++ tyNames))
rhs]]
emitDecsM $ defunctionalize lambdaName (map (const Nothing) all_args) Nothing
let promLambda = foldl apply (DConT (promoteTySym lambdaName 0))
(map DVarT all_locals)
return (promLambda, ADLamE var_proms promLambda names ann_exp)
promoteExp (DCaseE exp matches) = do
caseTFName <- newUniqueName "Case"
all_locals <- allLocals
let prom_case = foldType (DConT caseTFName) (map DVarT all_locals)
(exp', ann_exp) <- promoteExp exp
(eqns, ann_matches) <- mapAndUnzipM (promoteMatch prom_case) matches
tyvarName <- qNewName "t"
let all_args = all_locals ++ [tyvarName]
tvbs = map DPlainTV all_args
emitDecs [DClosedTypeFamilyD (DTypeFamilyHead caseTFName tvbs DNoSig Nothing) eqns]
-- See Note [Annotate case return type] in Single
let applied_case = prom_case `DAppT` exp'
return ( applied_case
, ADCaseE ann_exp exp' ann_matches applied_case )
promoteExp (DLetE decs exp) = do
unique <- qNewUnique
let letPrefixes = uniquePrefixes "Let" ":<<<" unique
(binds, ann_env) <- promoteLetDecs letPrefixes decs
(exp', ann_exp) <- letBind binds $ promoteExp exp
return (exp', ADLetE ann_env ann_exp)
promoteExp (DSigE exp ty) = do
(exp', ann_exp) <- promoteExp exp
ty' <- promoteType ty
return (DSigT exp' ty', ADSigE ann_exp ty)
promoteExp e@(DStaticE _) = fail ("Static expressions cannot be promoted: " ++ show e)
promoteLitExp :: Monad m => Lit -> m DType
promoteLitExp (IntegerL n)
| n >= 0 = return $ (DConT tyFromIntegerName `DAppT` DLitT (NumTyLit n))
| otherwise = return $ (DConT tyNegateName `DAppT`
(DConT tyFromIntegerName `DAppT` DLitT (NumTyLit (-n))))
promoteLitExp (StringL str) = return $ DLitT (StrTyLit str)
promoteLitExp lit =
fail ("Only string and natural number literals can be promoted: " ++ show lit)
promoteLitPat :: Monad m => Lit -> m DType
promoteLitPat (IntegerL n)
| n >= 0 = return $ (DLitT (NumTyLit n))
| otherwise =
fail $ "Negative literal patterns are not allowed,\n" ++
"because literal patterns are promoted to natural numbers."
promoteLitPat (StringL str) = return $ DLitT (StrTyLit str)
promoteLitPat lit =
fail ("Only string and natural number literals can be promoted: " ++ show lit)
|
int-index/singletons
|
src/Data/Singletons/Promote.hs
|
bsd-3-clause
| 27,939
| 0
| 21
| 7,218
| 6,689
| 3,344
| 3,345
| 450
| 6
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
module Feldspar.Core.Constructs.Trace
( Trace (..)
) where
import Language.Syntactic
import Language.Syntactic.Constructs.Binding
import Feldspar.Core.Types
import Feldspar.Core.Interpretation
import Debug.Trace
data Trace a
where
Trace :: Type a => Trace (IntN :-> a :-> Full a)
-- TODO Seems a more suitable definition might be
--
-- Trace :: Type a => IntN -> Trace (a :-> Full a)
--
-- since the front-end function will always make a literal for the label.
instance Semantic Trace
where
semantics Trace = Sem "trace" (\i a -> trace (show i ++ ":" ++ show a) a)
instance Constrained Trace
where
type Sat Trace = Type
exprDict Trace = Dict
instance Equality Trace where equal = equalDefault; exprHash = exprHashDefault
instance Render Trace where renderArgs = renderArgsDefault
instance ToTree Trace
instance Eval Trace where evaluate = evaluateDefault
instance EvalBind Trace where evalBindSym = evalBindSymDefault
instance Sharable Trace
instance AlphaEq dom dom dom env => AlphaEq Trace Trace dom env
where
alphaEqSym = alphaEqSymDefault
instance SizeProp (Trace :|| Type)
where
sizeProp (C' Trace) (WrapFull _ :* WrapFull a :* Nil) = infoSize a
instance ( (Trace :|| Type) :<: dom
, OptimizeSuper dom)
=> Optimize (Trace :|| Type) dom
where
constructFeatUnOpt opts x@(C' _) = constructFeatUnOptDefault opts x
|
rCEx/feldspar-lang-small
|
src/Feldspar/Core/Constructs/Trace.hs
|
bsd-3-clause
| 3,222
| 0
| 13
| 632
| 416
| 239
| 177
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.Singletons.TH.Deriving.Eq
-- Copyright : (C) 2020 Ryan Scott
-- License : BSD-style (see LICENSE)
-- Maintainer : Ryan Scott
-- Stability : experimental
-- Portability : non-portable
--
-- Implements deriving of Eq instances
--
----------------------------------------------------------------------------
module Data.Singletons.TH.Deriving.Eq (mkEqInstance) where
import Control.Monad
import Data.Singletons.TH.Deriving.Infer
import Data.Singletons.TH.Deriving.Util
import Data.Singletons.TH.Names
import Data.Singletons.TH.Syntax
import Data.Singletons.TH.Util
import Language.Haskell.TH.Desugar
import Language.Haskell.TH.Syntax
mkEqInstance :: DsMonad q => DerivDesc q
mkEqInstance mb_ctxt ty (DataDecl _ _ cons) = do
let con_pairs = [ (c1, c2) | c1 <- cons, c2 <- cons ]
constraints <- inferConstraintsDef mb_ctxt (DConT eqName) ty cons
clauses <- if null cons
then pure [DClause [DWildP, DWildP] (DConE trueName)]
else traverse mkEqClause con_pairs
pure (InstDecl { id_cxt = constraints
, id_name = eqName
, id_arg_tys = [ty]
, id_sigs = mempty
, id_meths = [(equalsName, UFunction clauses)] })
mkEqClause :: Quasi q => (DCon, DCon) -> q DClause
mkEqClause (c1, c2)
| lname == rname = do
lnames <- replicateM lNumArgs (newUniqueName "a")
rnames <- replicateM lNumArgs (newUniqueName "b")
let lpats = map DVarP lnames
rpats = map DVarP rnames
lvars = map DVarE lnames
rvars = map DVarE rnames
pure $ DClause
[DConP lname [] lpats, DConP rname [] rpats]
(andExp (zipWith (\l r -> foldExp (DVarE equalsName) [l, r])
lvars rvars))
| otherwise =
pure $ DClause
[DConP lname [] (replicate lNumArgs DWildP),
DConP rname [] (replicate rNumArgs DWildP)]
(DConE falseName)
where
andExp :: [DExp] -> DExp
andExp [] = DConE trueName
andExp [one] = one
andExp (h:t) = DVarE andName `DAppE` h `DAppE` andExp t
(lname, lNumArgs) = extractNameArgs c1
(rname, rNumArgs) = extractNameArgs c2
|
goldfirere/singletons
|
singletons-th/src/Data/Singletons/TH/Deriving/Eq.hs
|
bsd-3-clause
| 2,265
| 0
| 18
| 557
| 650
| 352
| 298
| 45
| 3
|
module Test.Rogue.Suite.DummySpec
( spec
) where
import Control.Exception (evaluate)
import Test.Hspec (Spec, anyException, describe, it,
shouldBe, shouldThrow)
import Test.QuickCheck (property)
spec :: Spec
spec =
describe "Prelude.head" $ do
it "returns the first element of a list" $ do
head [23 ..] `shouldBe` (23 :: Int)
it "returns the first element of an *arbitrary* list" $
property $ \x xs -> head (x:xs) == (x :: Int)
it "throws an exception if used with an empty list" $ do
evaluate (head []) `shouldThrow` anyException
|
ChShersh/rogue-lang
|
test/Test/Rogue/Suite/DummySpec.hs
|
bsd-3-clause
| 682
| 0
| 15
| 235
| 178
| 98
| 80
| 15
| 1
|
{-|
Module : Data.Type.Lambda
Description : Type level functions.
Copyright : (c) Alexander Vieth, 2016
Licence : BSD3
Maintainer : aovieth@gmail.com
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
module Lambda where
import GHC.TypeLits
import Data.Kind
import Data.Proxy
-- | It's good to have a special kind to parameterize Lambda, so that we can
-- distinguish abstractions from fully-applied types. This way a type of kind
--
-- Lambda (LBase (s -> t -> r))
--
-- means it holds a type of kind s -> t -> r, contrasted with a type of kind
--
-- Lambda (LArrow (LBase s) (LArrow (LBase t) (LBase r)))
--
-- which is the lifted kind of the type s -> (t -> r)
data LambdaType where
LBase :: s -> LambdaType
LArrow :: LambdaType -> LambdaType -> LambdaType
type Ty = 'LBase
infixr 0 :->
type (:->) = 'LArrow
data Lambda (t :: LambdaType) where
-- Type annotation.
LAnn :: Lambda t -> Proxy t -> Lambda t
-- Type constructor (includes 0-arity type constructors like 'True).
LCon :: t -> Lambda ('LBase t)
-- Type constructor application.
LCap :: Lambda (LBase (s -> t)) -> Lambda (LBase s) -> Lambda (LBase t)
-- Named variable.
LVar :: Proxy (name :: Symbol) -> Lambda t
-- Lambda abstraction. Note the type variable @s@ which appears only in the
-- rightmost part. It can be constrained by using 'LAnn.
LAbs :: Proxy (name :: Symbol) -> Lambda t -> Lambda (LArrow s t)
-- Lambda application. Contrast with LCap, which does application within
-- the arrow kind.
LApp :: Lambda (LArrow s t) -> Lambda s -> Lambda t
-- Let bindings (recursive).
LLet :: Proxy (name :: Symbol) -> Lambda t -> Lambda u -> Lambda u
-- Embedding of type families.
-- Since type families are not types, we proxy them with actual types.
-- A saturated type family proxy must have kind Type. An unsaturated proxy
-- embedded here in Lambda may have any kind as its rightmost kind.
-- Do not use this constructor directly; instead, use @F@, which by way
-- of @LFamType@ computes the proper type parameter.
LFam :: (Lambda s -> t) -> Lambda ('LArrow s u)
-- Analyse (pattern matching).
LYse :: Patterns against body -> Lambda ('LBase against) -> Lambda body
infixl 0 :@
type x :@ y = 'LCap x y
infixl 9 :$
type x :$ y = 'LApp x y
infixr 0 :$:
type x :$: y = 'LApp x y
type x ::: y = 'LAnn x y
type L (x :: Symbol) y = 'LAbs ('Proxy :: Proxy x) y
type V (x :: Symbol) = 'LVar ('Proxy :: Proxy x)
type family LFamType (l :: Type) :: LambdaType where
LFamType (Proxy (t :: LambdaType) -> Type) = t
LFamType (Lambda t -> r) = 'LArrow t (LFamType r)
type family F (l :: Lambda s -> t) :: Lambda ('LArrow s (LFamType t)) where
F l = 'LFam l
type family EvalFamily (d :: Proxy (t :: LambdaType) -> Type) :: Lambda t
data Times (m :: Lambda (Ty Nat)) (n :: Lambda (Ty Nat)) (pl :: Proxy (Ty Nat))
type instance EvalFamily (Times lm ln) = 'LCon ((RunLambda lm) GHC.TypeLits.* (RunLambda ln))
data Plus (m :: Lambda (Ty Nat)) (n :: Lambda (Ty Nat)) (pl :: Proxy (Ty Nat))
type instance EvalFamily (Plus lm ln) = 'LCon ((RunLambda lm) GHC.TypeLits.+ (RunLambda ln))
data FmapProxy (g :: Lambda (s :-> t)) (x :: Lambda (Ty (f (Lambda s)))) (px :: Proxy (Ty (f (Lambda t))))
type instance EvalFamily (FmapProxy g x) = FmapInstance g (RunLambda x)
type f :<$> x = F FmapProxy :$ f :$ x
-- Notice that the second parameter is stripped of the outer lambda, so that the
-- family can match directly.
type family FmapInstance (g :: Lambda (s :-> t)) (x :: f (Lambda s)) :: Lambda (Ty (f (Lambda t)))
type instance FmapInstance g 'Nothing = 'LCon 'Nothing
type instance FmapInstance g ('Just x) = 'LCon ('Just (g :$ x))
type instance FmapInstance g ('Left x) = 'LCon ('Left x)
type instance FmapInstance g ('Right x) = 'LCon ('Right (g :$ x))
type instance FmapInstance g '[] = 'LCon '[]
type instance FmapInstance g (x ': xs) =
'LCon ((g :$ x) ': RunLambda (FmapInstance g xs))
data SemigroupAp (pt :: Proxy t) (l :: Lambda (Ty t)) (r :: Lambda (Ty t)) (pr :: Proxy (Ty t))
type instance EvalFamily (SemigroupAp pt l r) =
'LCon (SemigroupApInstance (RunLambda l) (RunLambda r))
type family SemigroupApInstance (l :: k) (r :: k) :: k
data And where
And :: Bool -> And
type instance SemigroupApInstance ('And 'True) ('And b) = 'And b
type instance SemigroupApInstance ('And 'False) ('And b) = 'And 'False
type Ex = F (SemigroupAp 'Proxy) :$ 'LCon ('And 'True) :$ 'LCon ('And 'True)
data FoldrProxy (f :: Lambda (Ty a :-> Ty b :-> Ty b)) (e :: Lambda (Ty b)) (xs :: Lambda (Ty [a])) (p :: Proxy (Ty b))
type instance EvalFamily (FoldrProxy f e xs) = FoldrInstance f (RunLambda e) (RunLambda xs)
type family FoldrInstance (f :: Lambda (Ty a :-> Ty b :-> Ty b)) (e :: b) (xs :: [a]) :: Lambda (Ty b)
type instance FoldrInstance f e '[] = 'LCon e
type instance FoldrInstance f e (x ': xs) = f :$ 'LCon x :$ (FoldrInstance f e xs)
type Foldr = F FoldrProxy
data ApProxy (mf :: Lambda (Ty (f (Lambda (a :-> b))))) (mx :: Lambda (Ty (f (Lambda a)))) (p :: Proxy (Ty (f (Lambda b))))
type instance EvalFamily (ApProxy mf mx) = ApInstance (RunLambda mf) (RunLambda mx)
type family ApInstance (mf :: f (Lambda (a :-> b))) (mx :: f (Lambda a)) :: Lambda (Ty (f (Lambda b)))
type instance ApInstance 'Nothing 'Nothing = 'LCon 'Nothing
type instance ApInstance ('Just f) 'Nothing = 'LCon 'Nothing
type instance ApInstance 'Nothing ('Just f) = 'LCon 'Nothing
type instance ApInstance ('Just f) ('Just x) = 'LCon ('Just (f :$ x))
type instance ApInstance ('Left x) ('Left y) = 'LCon ('Left x)
type instance ApInstance ('Left x) ('Right y) = 'LCon ('Left x)
type instance ApInstance ('Right f) ('Left y) = 'LCon ('Left y)
type instance ApInstance ('Right f) ('Right x) = 'LCon ('Right (f :$ x))
type mf :<*> mx = F ApProxy :$ mf :$ mx
-- | Evaluation of a Lambda to normal form makes use of an environment mapping
-- names (Symbols) to Lambdas.
data BoundNames where
BoundNamesNil :: BoundNames
BoundNamesCons :: Proxy (name :: Symbol) -> (BoundNames, Lambda t) -> BoundNames -> BoundNames
BoundNamesRecCons :: Proxy (name :: Symbol) -> Lambda t -> BoundNames -> BoundNames
-- | Try to resolve a name from a binding environment. If not found, give back
-- an 'LVar.
type family LookupName (name :: Symbol) (t :: LambdaType) (env :: BoundNames) :: (BoundNames, Lambda t) where
LookupName name t env = LookupNameRec env name t env
-- | Keep the original environment around. Useful for when it gets stuck, so we
-- can see the whole input.
type family LookupNameRec (origEnv :: BoundNames) (name :: Symbol) (t :: LambdaType) (env :: BoundNames) :: (BoundNames, Lambda t) where
LookupNameRec origEnv name t ('BoundNamesCons ('Proxy :: Proxy name) '(env, (x :: Lambda t)) rest) = '(env, x)
LookupNameRec origEnv name t ('BoundNamesRecCons ('Proxy :: Proxy name) (x :: Lambda t) rest) =
NormalForm ('BoundNamesRecCons ('Proxy :: Proxy name) x rest) x
LookupNameRec origEnv name t ('BoundNamesCons ('Proxy :: Proxy name') '(env, (x :: Lambda t')) rest) =
LookupNameRec origEnv name t rest
LookupNameRec origEnv name t ('BoundNamesRecCons ('Proxy :: Proxy name') (x :: Lambda t') rest) =
LookupNameRec origEnv name t rest
type family AppendBoundNames (a :: BoundNames) (b :: BoundNames) :: BoundNames where
AppendBoundNames 'BoundNamesNil b = b
AppendBoundNames ('BoundNamesCons proxy t rest) b =
'BoundNamesCons proxy t (AppendBoundNames rest b)
AppendBoundNames ('BoundNamesRecCons proxy t rest) b =
'BoundNamesRecCons proxy t (AppendBoundNames rest b)
-- | Evaluate a Lambda to normal form.
type family NormalForm (env :: BoundNames) (l :: Lambda t) :: (BoundNames, Lambda t) where
NormalForm env ('LAnn l proxy) = NormalForm env l
NormalForm env ('LCon c) = '(env, 'LCon c)
NormalForm env ('LCap left right) =
NormalFormCap env (NormalForm env left) (NormalForm env right)
NormalForm env ('LVar ('Proxy :: Proxy name) :: Lambda t) = LookupName name t env
NormalForm env ('LAbs proxyName body) = '(env, 'LAbs proxyName body)
NormalForm env ('LApp left right) =
NormalFormApp env (NormalForm env left) (NormalForm env right)
-- Let is recursive. We get the normal form of the rhs with a recursive
-- binding to itself, and give a nonrecursive binding to that when
-- computing the normal form of the body.
NormalForm env ('LLet proxyName rhs body) =
NormalForm ('BoundNamesCons proxyName (NormalForm ('BoundNamesRecCons proxyName rhs env) rhs) env) body
-- Type families are in normal form, just like lambda abstractions. Only
-- when applied to something will they be reduced.
NormalForm env ('LFam l) = '(env, 'LFam l)
NormalForm env ('LYse pats t) =
NormalFormYse env pats (NormalForm env t)
-- | The normal form of an application. Takes the normal form left-hand part
-- and the normal form right-hand part.
type family NormalFormApp (env :: BoundNames) (left :: (BoundNames, Lambda (LArrow s t))) (right :: (BoundNames, Lambda s)) :: (BoundNames, Lambda t) where
NormalFormApp env '(env', 'LAbs proxyName body) '(env'', right) =
NormalForm ('BoundNamesCons proxyName '(env'', right) (AppendBoundNames env' env)) body
NormalFormApp env '(env', 'LFam (l :: Lambda s -> Proxy t -> Type)) '(env'', right) =
NormalForm env (EvalFamily (l right))
NormalFormApp env '(env', 'LFam (l :: Lambda s -> Lambda t -> r)) '(env'', right) =
NormalForm env ('LFam (l right))
type family NormalFormCap (env :: BoundNames) (left :: (BoundNames, Lambda (LBase (s -> t)))) (right :: (BoundNames, Lambda (LBase s))) :: (BoundNames, Lambda (LBase t)) where
-- In order to apply right to con, we need to evaluate right to a
-- non-Lambda. This works only if right is an 'LCon.
NormalFormCap env '(env', 'LCon con) '(env'', right) =
NormalForm env ('LCon (con (GetLambda right)))
type family NormalFormYse (env :: BoundNames) (pats :: Patterns s t) (l :: (BoundNames, Lambda ('LBase s))) :: (BoundNames, Lambda t) where
NormalFormYse env ('Patterns ( '(clause, body) ': rest )) '(env', l) =
NormalFormYseContinue env ('Patterns rest) '(env', l) (MatchClause clause (RunLambda l)) body
type family NormalFormYseContinue (env :: BoundNames) (pats :: Patterns s t) (l :: (BoundNames, Lambda ('LBase s))) (match :: Maybe BoundNames) (body :: Lambda t) :: (BoundNames, Lambda t) where
NormalFormYseContinue env pats '(env', l) 'Nothing body =
NormalFormYse env pats '(env', l)
NormalFormYseContinue env pats '(env', l) ('Just env'') body =
NormalForm (AppendBoundNames env'' env) body
-- | A normal form Lambda can sometimes be eliminated to yield a non-Lambda
-- type.
type family GetLambda (l :: Lambda (LBase s)) :: s where
GetLambda ('LCon c) = c
type family RunLambda (l :: Lambda (LBase s)) :: s where
RunLambda l = GetLambda (DropEnv (NormalForm 'BoundNamesNil l))
type family DropEnv (t :: (BoundNames, l)) :: l where
DropEnv '(env, l) = l
type Id (pk :: Proxy k) =
(L "x" (V "x")) ::: ('Proxy :: Proxy (Ty k :-> Ty k))
-- Const is weird. We have it as Lambda (k -> l -> k) but shouldn't it be
-- Lambda (k -> Lambda (l -> k)) ???
type Const (pk :: Proxy k) (pl :: Proxy l) =
(L "x" (L "y" (V "x"))) ::: ('Proxy :: Proxy (Ty k :-> Ty l :-> Ty k))
-- |
-- == Pattern matching on types of algebraic kinds.
--
-- If we define a (generalized) algebraic datatype, of course we can pattern
-- match on terms thereof. But what about the promoted types? There is no
-- pattern matching construct at the type level, but we can hack one up.
--
--
data Patterns (against :: Type) (body :: LambdaType) where
Patterns :: [(PatternClause against, Lambda body)] -> Patterns against body
-- | This GADT is formed in such a way that a poly-kinded type constructor will
-- be specialized according to the kinds which compose a @PatternBindings@
-- type.
data PatternClause (against :: Type) where
PatternClause
:: Proxy rightmost
-> constructor
-> PatternBindings constructor rightmost
-> PatternClause rightmost
-- | Describes the arguments of a constructor. The first parameter is a
-- type with as many arrows as there are @PatternBindingsCons@'s in the
-- term, and the second parameter is the type that the first parameter will
-- have when it is saturated with arguments.
-- Each @PatternBindingsCons@ indicates the type (kind) expected and also
-- names it using a @Symbol@.
data PatternBindings (constructor :: Type) (rightmost :: Type) where
PatternBindingsNil :: PatternBindings rightmost rightmost
PatternBindingsCons
:: Symbol
-> Proxy t
-> PatternBindings l r
-> PatternBindings (t -> l) r
-- | Describes a match of a @PatternBindings@ against a type, and holds the
-- actual types that were found.
data PatternMatch (args :: [(Symbol, Type)]) (rightmost :: Type) where
PatternMatchNil :: PatternMatch '[] rightmost
PatternMatchCons
:: Proxy (name :: Symbol)
-> t
-> PatternMatch ts (t -> r)
-> PatternMatch ( '(name, t) ': ts ) r
type family PatternMatchConsMaybe (n :: Symbol) (t :: Type) (k :: t) (pm :: Maybe (PatternMatch ts (t -> r))) :: Maybe (PatternMatch ( '(n, t) ': ts) r ) where
PatternMatchConsMaybe n t k 'Nothing = 'Nothing
PatternMatchConsMaybe n t k ('Just rest) = 'Just ('PatternMatchCons 'Proxy k rest)
-- | Here's where we match: give the names and argument types in reverse
-- argument order, and then the rightmost kind and something of that kind.
-- If you get @'Just@, then the @PatternMatch@ type contains the actual
-- types found in the type called @rightmost@, and their associated names as
-- determined by the names list.
type family MatchAgainst (args :: [(Symbol, Type)]) (constructor :: k) (rightmost :: Type) (t :: rightmost) :: Maybe (PatternMatch args rightmost) where
MatchAgainst ( '(n, k) ': ks ) constructor l ((q :: k -> l) (x :: k)) =
PatternMatchConsMaybe n k x (MatchAgainst ks constructor (k -> l) q)
MatchAgainst '[] q l (q :: l) = 'Just 'PatternMatchNil
MatchAgainst a b c d = 'Nothing
-- | Convert a @PatternBindings@ into a list suitable for use as the first
-- parameter to @MatchAgainst@.
type family PatternBindingsForm (p :: PatternBindings constructor rightmost) :: [(Symbol, Type)] where
PatternBindingsForm 'PatternBindingsNil = '[]
PatternBindingsForm ('PatternBindingsCons sym ('Proxy :: Proxy t) rest) =
Snoc '(sym, t) (PatternBindingsForm rest)
type family Snoc (t :: k) (ts :: [k]) :: [k] where
Snoc t '[] = '[t]
Snoc t (s ': ss) = s ': Snoc t ss
-- | BoundNames is just a PatternMatch without type information. This family
-- shows how.
type family PatternMatchToBoundNames (pm :: PatternMatch args rightmost) :: BoundNames where
PatternMatchToBoundNames 'PatternMatchNil = 'BoundNamesNil
PatternMatchToBoundNames ('PatternMatchCons proxyName t rest) =
'BoundNamesCons proxyName '( 'BoundNamesNil, 'LCon t ) (PatternMatchToBoundNames rest)
type family PatternMatchToBoundNamesMaybe (pm :: Maybe (PatternMatch args rightmost)) :: Maybe BoundNames where
PatternMatchToBoundNamesMaybe 'Nothing = 'Nothing
PatternMatchToBoundNamesMaybe ('Just pm) = 'Just (PatternMatchToBoundNames pm)
type family MatchClause (pc :: PatternClause against) (t :: against) :: Maybe BoundNames where
MatchClause ('PatternClause (proxy :: Proxy k) constructor pbindings) t =
PatternMatchToBoundNamesMaybe (MatchAgainst (PatternBindingsForm pbindings) constructor k t)
type IsJust (p :: Proxy t) =
(L "x" (
'LYse ('Patterns '[
'( 'PatternClause ('Proxy :: Proxy (Maybe t)) 'Just ('PatternBindingsCons "x" ('Proxy :: Proxy t) 'PatternBindingsNil), 'LCon 'True)
, '( 'PatternClause ('Proxy :: Proxy (Maybe t)) 'Nothing 'PatternBindingsNil, 'LCon 'False)
])
(V "x")
))
::: ('Proxy :: Proxy (Ty (Maybe t) :-> Ty Bool))
type BoolNot =
L "x" (
'LYse ('Patterns '[
'( 'PatternClause 'Proxy 'True 'PatternBindingsNil, 'LCon 'False )
, '( 'PatternClause 'Proxy 'False 'PatternBindingsNil, 'LCon 'True )
])
(V "x")
)
:::
('Proxy :: Proxy (Ty Bool :-> Ty Bool))
type BoolAnd =
L "x" (
L "y" (
('LYse ('Patterns '[
'( 'PatternClause 'Proxy 'True 'PatternBindingsNil, V "y")
, '( 'PatternClause 'Proxy 'False 'PatternBindingsNil, 'LCon 'False )
])
(V "x")
)))
:::
('Proxy :: Proxy (Ty Bool :-> Ty Bool :-> Ty Bool))
type Dot (ps :: Proxy s) (pt :: Proxy t) (pu :: Proxy u) =
L "g" (
L "f" (
L "x" (
((V "g") ::: ('Proxy :: Proxy (t :-> u))) :$ (
((V "f") ::: ('Proxy :: Proxy (s :-> t))) :$ (
((V "x") ::: ('Proxy :: Proxy s)))))))
:::
('Proxy :: Proxy ((t :-> u) :-> (s :-> t) :-> (s :-> u)))
infixr 9 :.
type g :. f = Dot 'Proxy 'Proxy 'Proxy :$ g :$ f
data List t where
Nil :: List t
Cons :: t -> List t -> List t
-- Safe list head
-- Here it seems the kind proxying is necessary.
type SafeHead (pt :: Proxy t) =
L "xs" (
'LYse ('Patterns '[
'( 'PatternClause 'Proxy 'Nil 'PatternBindingsNil, 'LCon 'Nothing )
, '( 'PatternClause 'Proxy 'Cons ('PatternBindingsCons "x" ('Proxy :: Proxy t) ('PatternBindingsCons "xs" ('Proxy :: Proxy (List t)) 'PatternBindingsNil))
, 'LCon 'Just :@ V "x")
])
(V "xs")
)
:::
('Proxy :: Proxy (Ty (List t) :-> Ty (Maybe t)))
-- List length
type Length (pt :: Proxy t) =
'LLet ('Proxy :: Proxy "length")
((L "xs" (
'LYse ('Patterns '[
'( 'PatternClause 'Proxy 'Nil 'PatternBindingsNil, 'LCon 0 )
, '( 'PatternClause 'Proxy 'Cons ('PatternBindingsCons "x" ('Proxy :: Proxy t) ('PatternBindingsCons "xs'" ('Proxy :: Proxy (List t)) 'PatternBindingsNil))
, F Plus :$ 'LCon 1 :$ ((V "length" ::: ('Proxy :: Proxy (Ty (List t) :-> Ty Nat))) :$ (V "xs'" ::: ('Proxy :: Proxy (Ty (List t)))))
)
])
(V "xs" ::: ('Proxy :: Proxy (Ty (List t))))
))
::: ('Proxy :: Proxy (Ty (List t) :-> Ty Nat)))
(V "length" ::: ('Proxy :: Proxy (Ty (List t) :-> (Ty Nat))))
::: ('Proxy :: Proxy (Ty (List t) :-> Ty Nat))
|
avieth/type-lambda
|
Data/Type/Lambda.hs
|
bsd-3-clause
| 18,814
| 134
| 29
| 4,242
| 6,791
| 3,643
| 3,148
| -1
| -1
|
{-#LANGUAGE GADTs, StandaloneDeriving, GeneralizedNewtypeDeriving #-}
module Genome.Data.FrequencyArray where
import Data.List (sort)
import Data.Set (Set)
import Data.Sequence (Seq)
import Data.Sequence ((><), (<|), (|>))
import qualified Data.Foldable as Foldable
import Data.Map (Map, (!))
import qualified Data.Map as M
import Util.Util (invertedMap, hamdist)
{-
To implement frequency arrays, we need a lexical order on types, and there
lists. Lexicographical order requires that the type be converted into an Int,
and an Int to the type.
-}
class Show b => Lexicord b where
--cardinality :: Int, does not compile, needs b
lexord :: b -> Int
lexval :: Int -> b
listlexord :: Int -> [b] -> Int
listlexord _ [] = 0
listlexord k (x:xs) = 1 + (lexord x) + k * (listlexord k xs)
listlexval :: Int -> Int -> [b]
listlexval _ 0 = []
listlexval k x = (lexval $ mod rx k) : (listlexval k (div rx k))
where rx = x - 1
mostFrequentKmers :: Lexicord b => Int -> Int -> [b] -> (Int, [[b]])
mostFrequentKmers c k text = (n, map (listlexval c) (m ! n))
where
m = freqKmerLexicords c k text
n = (maximum . M.keys) m
freqKmerLexicords :: Lexicord b => Int -> Int -> [b] -> Map Int [Int]
freqKmerLexicords c k text = invertedMap (kmerLexicordCounts c k text)
kmerLexicordCounts :: Lexicord b => Int -> Int -> [b] -> Map Int Int
kmerLexicordCounts c k text = if (length kmer) < k
then M.empty
else M.insertWith (+) (listlexord c kmer) 1 kcounts
where
kmer = take k text
kcounts = kmerLexicordCounts c k (drop 1 text)
type Simpred b = [b] -> [b] -> Bool
mostAppxFreqKmers :: Lexicord b => Int -> Simpred b -> Int -> [b] -> (Int, [[b]])
mostAppxFreqKmers c areSimilar k text = (n, map (listlexval c) (m ! n))
where
m = invertedMap (appxKmerLexicordCounts c areSimilar k text)
n = (maximum . M.keys) m
appxKmerLexicordCounts :: Lexicord b => Int -> Simpred b -> Int -> [b] -> Map Int Int
appxKmerLexicordCounts c areSimilar k text = foldl
(\m p -> M.insert p (hcount p) m)
M.empty
(M.keys kcs)
where
kcs = kmerLexicordCounts c k text
hcount p = foldl
(\s q ->
if areSimilar (listlexval c p) (listlexval c q)
then s + (kcs ! q)
else s)
0
(M.keys kcs)
|
visood/bioalgo
|
src/lib/Genome/Data/FrequencyArray.hs
|
bsd-3-clause
| 2,515
| 0
| 13
| 770
| 901
| 485
| 416
| 50
| 2
|
{-|
Description: path matching utility
This module provides the tools you need to match the path of a request, extract data
from it, and connect matches to Respond actions.
-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Web.Respond.Path where
import Control.Applicative
import Network.Wai
import qualified Data.Text as T
import qualified Data.Sequence as S
import Safe (headMay)
import Data.Maybe (fromMaybe)
import qualified Control.Monad.State.Class as MState
import qualified Control.Monad.State as StateT
import qualified Control.Monad.Trans.Maybe as MaybeT
import Data.HList
import Web.PathPieces
import Network.HTTP.Types.Method
import Web.Respond.Types
import Web.Respond.Monad
import Web.Respond.Response
import Web.Respond.Method
import Web.Respond.HListUtils
-- * matching paths to actions
-- | the PathMatcher makes it easy to provide actions for different paths.
-- you use 'matchPath' to run it.
--
-- you can use this as a monad, but tbh you probably just want to use the
-- 'Applicative' and especially 'Alternative' instances.
newtype PathMatcher a = PathMatcher {
runPathMatcher :: PathConsumer -> Maybe a
}
instance Functor PathMatcher where
fmap f pm = PathMatcher $ fmap f . runPathMatcher pm
instance Applicative PathMatcher where
pure v = PathMatcher $ pure $ pure v
f <*> r = PathMatcher $ (<*>) <$> runPathMatcher f <*> runPathMatcher r
instance Alternative PathMatcher where
empty = PathMatcher $ const Nothing
l <|> r = PathMatcher $ (<|>) <$> runPathMatcher l <*> runPathMatcher r
instance Monad PathMatcher where
return = pure
a >>= f = PathMatcher $ (>>=) <$> runPathMatcher a <*> flip (runPathMatcher . f)
-- | run a path matcher containing a respond action against the current
-- path. uses the currently installed unmatched path handler if the match
-- fails.
--
-- see 'handleUnmatchedPath'
matchPath :: MonadRespond m => PathMatcher (m ResponseReceived) -> m ResponseReceived
matchPath pm = getPath >>= (fromMaybe handleUnmatchedPath . runPathMatcher pm)
-- ** transforming path matchers
-- | wrap the action within a path matcher with 'matchOnlyMethod'; this way
-- all paths below this can be restricted to a single method properly.
matchPathWithMethod :: MonadRespond m => StdMethod -> PathMatcher (m ResponseReceived) -> PathMatcher (m ResponseReceived)
matchPathWithMethod = fmap . matchOnlyMethod
-- | 'pathWithMethod' GET
matchPathWithGET :: MonadRespond m => PathMatcher (m ResponseReceived) -> PathMatcher (m ResponseReceived)
matchPathWithGET = matchPathWithMethod GET
-- * extracting path elements
-- | the path extractor matches the path and extracts values; it is useful
-- for building PathMatchers. it is built on both MState and Maybe - if it
-- succeeds, it can modify the state to represent the path it has consumed.
newtype PathExtractor l = PathExtractor {
runPathExtractor :: MaybeT.MaybeT (StateT.State PathConsumer) l
} deriving (Functor, Applicative, Monad, Alternative, MState.MonadState PathConsumer, MonadPlus)
-- | takes a Maybe and makes it into a path extractor
asPathExtractor :: Maybe a -> PathExtractor a
asPathExtractor = maybe empty return
-- | a path extractor that extracts nothing, just matches
type PathExtractor0 = PathExtractor HList0
-- | a path extractor that extracts a single value from the path
type PathExtractor1 a = PathExtractor (HList1 a)
-- ** using path extractors
-- | runs a 'PathExtractor' against a 'PathConsumer'.
pathExtract :: PathExtractor a -> PathConsumer -> (Maybe a, PathConsumer)
pathExtract = StateT.runState . MaybeT.runMaybeT . runPathExtractor
-- | create a 'PathMatcher' by providing a path extractor and an action that
-- consumes the extracted elements.
--
-- note that 'HListElim' is just a function from the types extracted to
-- something else
--
-- > path ((value :: PathExtractor1 String) </> seg "whatever" </> (value :: PathExtractor1 Integer)) $ \string integer -> -- some action
path :: MonadRespond m => PathExtractor (HList l) -> HListElim l (m a) -> PathMatcher (m a)
path extractor f = PathMatcher $ uncurry (useNextPathState f) . pathExtract extractor
-- | an action that runs the action (HListElim l (m a)) with the new path
-- consumer state if an extracted value is provided.
--
-- this mainly exists for the use of 'path'.
useNextPathState :: MonadRespond m => HListElim l (m a) -> Maybe (HList l) -> PathConsumer -> Maybe (m a)
useNextPathState elim maybeExtraction nextPath = (usePath nextPath . hListUncurry elim) <$> maybeExtraction
-- | a simple matcher for being at the end of the path.
--
-- > pathEndOrSlash = path endOrSlash
pathEndOrSlash :: MonadRespond m => m a -> PathMatcher (m a)
pathEndOrSlash = path endOrSlash
-- | a simple matcher for the last segment of a path
--
-- > pathLastSeg s = path (seg s </> endOrSlash)
pathLastSeg :: MonadRespond m => T.Text -> m a -> PathMatcher (m a)
pathLastSeg s = path (seg s </> endOrSlash)
-- | combine two path extractors in sequence.
(</>) :: PathExtractor (HList l) -> PathExtractor (HList r) -> PathExtractor (HList (HAppendList l r))
(</>) = liftA2 hAppendList
-- ** useful path extractors
-- | match only when the PathConsumer in the path state has no unconsumed
-- elements.
pathEnd :: PathExtractor0
pathEnd = MState.get >>= maybe (return HNil) (const empty) . pcGetNext
-- | build a path matcher that runs an extractor function on a single
-- element and then advances the path state if it matched.
singleSegExtractor :: (T.Text -> Maybe (HList a)) -> PathExtractor (HList a)
singleSegExtractor extractor = do
res <- MState.get >>= asPathExtractor . (pcGetNext >=> extractor)
MState.modify pcConsumeNext
return res
-- | build an extractor from a function that does not produce any real
-- value
unitExtractor :: (T.Text -> Maybe ()) -> PathExtractor0
unitExtractor = singleSegExtractor . (fmap (const HNil) .)
-- | convert a predicate into a 'PathExtractor0'
predicateExtractor :: (T.Text -> Bool) -> PathExtractor0
predicateExtractor = unitExtractor . (mayWhen () .)
-- | WAI represents a trailing slash by having a null text as the last
-- element in the list. this matches it. it's just
--
-- @
-- slashEnd = 'predicateExtractor' 'Data.Text.null'
-- @
slashEnd :: PathExtractor0
slashEnd = predicateExtractor T.null
-- | best way to match the path end. it's just
--
-- @
-- endOrSlash = 'pathEnd' 'Control.Applicative.<|>' 'slashEnd'
-- @
endOrSlash :: PathExtractor0
endOrSlash = pathEnd <|> slashEnd
-- | require that a segment be a certain string.
seg :: T.Text -> PathExtractor0
seg = predicateExtractor . (==)
-- | an extractor that takes a single path element and produces a single
-- value
singleItemExtractor :: (T.Text -> Maybe a) -> PathExtractor1 a
singleItemExtractor = singleSegExtractor . (fmap (hEnd . hBuild) .)
-- | if you have a 'PathPiece' instance for some type, you can extract it
-- from the path.
value :: PathPiece a => PathExtractor1 a
value = singleItemExtractor fromPathPiece
-- *** extract while matching methods
-- | path extraction matcher transformed with 'matchPath'
pathMethod :: MonadRespond m => StdMethod -> PathExtractor (HList l) -> HListElim l (m ResponseReceived) -> PathMatcher (m ResponseReceived)
pathMethod m extractor = matchPathWithMethod m . path extractor
-- | path extraction matcher with action wrapped so that it only matches
-- GET method
pathGET :: MonadRespond m => PathExtractor (HList l) -> HListElim l (m ResponseReceived) -> PathMatcher (m ResponseReceived)
pathGET = pathMethod GET
-- * utilities
-- | utility method for conditionally providing a value
mayWhen :: a -> Bool -> Maybe a
mayWhen v True = Just v
mayWhen _ False = Nothing
-- | run the inner action with a set path state.
--
-- > usePath = withPath . const
usePath :: MonadRespond m => PathConsumer -> m a -> m a
usePath = withPath . const
-- | get the part of the path that's been consumed so far.
--
-- > getConsumedPath = _pcConsumed <$> getPath
getConsumedPath :: MonadRespond m => m (S.Seq T.Text)
getConsumedPath = _pcConsumed <$> getPath
-- | get the part of the path that has yet to be consumed.
--
-- > getUnconsumedPath = _pcUnconsumed <$> getPath
getUnconsumedPath :: MonadRespond m => m [T.Text]
getUnconsumedPath = _pcUnconsumed <$> getPath
-- | get the next unconsumed path segment if there is one
--
-- > getNextSegment = headMay <$> getUnconsumedPath
getNextSegment :: MonadRespond m => m (Maybe T.Text)
getNextSegment = headMay <$> getUnconsumedPath
-- | run the inner action with the next path segment consumed.
--
-- > withNextSegmentConsumed = withPath pcConsumeNext
withNextSegmentConsumed :: MonadRespond m => m a -> m a
withNextSegmentConsumed = withPath pcConsumeNext
-- ** things you can get out of paths
-- | natural numbers starting with 1. you can get this out of a path.
newtype Natural = Natural Integer deriving (Eq, Show)
instance PathPiece Natural where
toPathPiece (Natural i) = T.pack $ show i
fromPathPiece s = fromPathPiece s >>= \i -> mayWhen (Natural i) (i >= 1)
|
raptros/respond
|
src/Web/Respond/Path.hs
|
bsd-3-clause
| 9,176
| 0
| 11
| 1,544
| 1,779
| 960
| 819
| 103
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Web.Orion.Database where
import Web.Orion
import Network.OAuth.OAuth2
import Web.Orion.OAuth.Services
import Database.HDBC
import Control.Monad.IO.Class (liftIO)
import Control.Monad
import Data.Maybe
import Database.HDBC.Sqlite3
import System.Directory
createUserDatabaseIfNeeded :: OrionM ()
createUserDatabaseIfNeeded = do
dbfp <- readCfgUserDBFilePath
dbExists <- liftIO $ doesFileExist dbfp
unless dbExists $ do
liftIO $ putStrLn "Creating users.db"
createUserDatabase
createUserDatabase :: OrionM ()
createUserDatabase = do
withUserDB createTables
withUserDB updateTables
createTables :: Connection -> IO ()
createTables conn = forM_ [schemaSQL, usersSQL, accountsSQL] (\sql -> void $ run conn sql [])
updateTables :: Connection -> IO ()
updateTables conn = void $ run conn updateSchemaSQL []
userDBFilePath :: IO FilePath
userDBFilePath = getCfg >>= getCfgUserDBFilePath
lookupAccounts :: AuthService -> UserData -> ActionOM [OrionAccount]
lookupAccounts service UserData{..} = do
accs <- withUserDB $ accountQuery service _udId
return $ catMaybes $ map sqlToOrionAccount accs
createNewUser :: AuthService -> AccessToken -> UserData -> ActionOM (Maybe OrionUser)
createNewUser service t udat = do
acl <- readCfgNewUserAclLevel
uid <- withUserDB $ \conn -> do
idset <- quickQuery' conn "SELECT id FROM users ORDER BY id DESC LIMIT 1" []
liftIO $ putStrLn $ "Last id: " ++ show idset
let uId = case idset of
[x]:_ -> (fromSql x) + 1
_ -> 1
-- If this is the first account make it the super overlord.
acl' = if uId == 1 then 0 else acl
let vars = [ toSql acl' ]
sql = "INSERT INTO users (acl_level) VALUES (?)"
void $ run conn sql vars
return uId
addAccountToUser service uid t udat
addAccountToUser :: AuthService -> Integer -> AccessToken -> UserData -> ActionOM (Maybe OrionUser)
addAccountToUser service uid t UserData{..} = do
void $ withUserDB $ \conn -> do
let vals = [ toSql uid
, toSql $ serviceToString service
, toSql _udId
, toSql _udLogin
, toSql _udName
, toSql _udEmail
, toSql t
]
sql = unwords [ "INSERT INTO accounts ("
, "user_id, service, service_id, service_login, "
, "service_name, service_email, service_token"
, ") VALUES (?,?,?,?,?,?,?)"
]
void $ run conn sql vals
lookupUser uid
lookupUserByAccount :: OrionAccount -> ActionOM (Maybe OrionUser)
lookupUserByAccount OrionAccount{..} = do
mId <- withUserDB $ \conn -> do
let sql = "SELECT user_id FROM accounts WHERE id = ?"
val = [toSql _accId]
set <- quickQuery' conn sql val
case set of
[uid]:_ -> return $ Just $ fromSql uid
_ -> return Nothing
case mId of
Nothing -> return Nothing
Just uid -> lookupUser uid
lookupUser :: Integer -> ActionOM (Maybe OrionUser)
lookupUser uid = do
let usql = "SELECT * FROM users WHERE id = ?"
uval = [toSql uid]
asql = "SELECT * FROM accounts where user_id = ?"
withUserDB $ \c -> do
uset <- quickQuery' c usql uval
case uset of
[] -> return Nothing
u:_ -> do aset <- quickQuery' c asql uval
let accs = catMaybes $ map sqlToOrionAccount aset
return $ fmap (\o -> o{_ouAccounts=accs}) (sqlToOrionUser u)
userExists :: Integer -> ActionOM Bool
userExists uid = do
mUser <- lookupUser uid
return $ case mUser of
Nothing -> False
Just _ -> True
sqlToOrionAccount :: [SqlValue] -> Maybe OrionAccount
sqlToOrionAccount [aid, _, service, sid, login, name, email, token] = do
service' <- stringToService $ fromSql service
return $ OrionAccount (fromSql aid)
service'
(fromSql sid)
(fromSql login)
(fromSql name)
(fromSql email)
(fromSql token)
sqlToOrionAccount _ = Nothing
sqlToOrionUser :: [SqlValue] -> Maybe OrionUser
sqlToOrionUser [uid, acl] = return $ OrionUser (fromSql uid)
(fromSql acl)
[]
sqlToOrionUser _ = Nothing
accountQuery :: IConnection c => AuthService -> Integer -> c -> IO [[SqlValue]]
accountQuery service sid conn =
let vars = [toSql $ serviceToString service, toSql sid]
sql = "SELECT * FROM accounts WHERE service = ? AND service_id = ?"
in quickQuery' conn sql vars
schemaSQL :: String
schemaSQL = unwords
[ "CREATE TABLE IF NOT EXISTS schema ("
, "version INTEGER NOT NULL DEFAULT (0)"
, ")"
]
updateSchemaSQL :: String
updateSchemaSQL = "INSERT INTO schema VALUES (0)"
usersSQL :: String
usersSQL = unwords
[ "CREATE TABLE IF NOT EXISTS users ("
, "id INTEGER PRIMARY KEY ASC AUTOINCREMENT,"
, "acl_level INTEGER NOT NULL DEFAULT (100)"
, ")"
]
accountsSQL :: String
accountsSQL = unwords
[ "CREATE TABLE IF NOT EXISTS accounts ("
, "id INTEGER PRIMARY KEY ASC AUTOINCREMENT,"
, "user_id INTEGER NOT NULL,"
, "service VARCHAR (32) NOT NULL,"
, "service_id INTEGER NOT NULL,"
, "service_login VARCHAR (128) NOT NULL,"
, "service_name VARCHAR (128) NOT NULL,"
, "service_email VARCHAR (256) NOT NULL,"
, "service_token VARCHAR (256)"
, ")"
]
|
schell/orion
|
src/Web/Orion/Database.hs
|
bsd-3-clause
| 5,813
| 0
| 21
| 1,810
| 1,445
| 730
| 715
| 140
| 3
|
{-# LANGUAGE DataKinds #-}
module FRP.Basket.Signals.Common where
import FRP.Basket.Signals
import Control.Applicative
import Prelude hiding (const)
import Data.HList
identity :: Signal '[] a a
identity = Signal $ \_ s a -> (a, s)
const :: c -> Signal '[] a c
const = pure
-- This should usually not be needed, but is here for completeness
time :: Signal '[] a Time
time = Signal $ \t s _ -> (t, s)
-- This returns the time difference
-- NOTE, as with all other signals this will need an initial state value provided for it (0, of course).
deltaT :: Signal '[Time] a Time
deltaT = mkSignal $ \t s _ -> (t - s, t)
-- Maybe this should move to another module
runUntil :: Time -> Signal s a b -> Signal s a (b, Bool)
runUntil t sf = Signal $ \t' s a -> let (b, s') = runSignal sf t' s a
in if t' < t then ((b, False), s') else ((b, True), s')
-- This probably won't be needed often, but it is provided for the sake of completeness
getState :: Signal s a (HList s)
getState = Signal $ \_ s _ -> (s, s)
|
jhstanton/Basket
|
src/FRP/Basket/Signals/Common.hs
|
bsd-3-clause
| 1,050
| 0
| 11
| 255
| 350
| 198
| 152
| 19
| 2
|
{-# LANGUAGE RecordWildCards #-}
module Network.Hawk.Internal.Server where
import Data.ByteString (ByteString)
import Network.Hawk.Types
import Network.Hawk.Internal.Server.Types
import Network.Hawk.Internal
serverMac :: Credentials -> HawkType -> HeaderArtifacts -> ByteString
serverMac Credentials{..} = calculateMac scAlgorithm scKey
|
rvl/hsoz
|
src/Network/Hawk/Internal/Server.hs
|
bsd-3-clause
| 341
| 0
| 7
| 35
| 75
| 45
| 30
| 8
| 1
|
{-# LINE 1 "Control.Monad.IO.Class.hs" #-}
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.IO.Class
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : R.Paterson@city.ac.uk
-- Stability : experimental
-- Portability : portable
--
-- Class of monads based on @IO@.
-----------------------------------------------------------------------------
module Control.Monad.IO.Class (
MonadIO(..)
) where
-- | Monads in which 'IO' computations may be embedded.
-- Any monad built by applying a sequence of monad transformers to the
-- 'IO' monad will be an instance of this class.
--
-- Instances should satisfy the following laws, which state that 'liftIO'
-- is a transformer of monads:
--
-- * @'liftIO' . 'return' = 'return'@
--
-- * @'liftIO' (m >>= f) = 'liftIO' m >>= ('liftIO' . f)@
class (Monad m) => MonadIO m where
-- | Lift a computation from the 'IO' monad.
liftIO :: IO a -> m a
instance MonadIO IO where
liftIO = id
|
phischu/fragnix
|
builtins/base/Control.Monad.IO.Class.hs
|
bsd-3-clause
| 1,174
| 0
| 8
| 229
| 89
| 61
| 28
| 7
| 0
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module NixLanguageTests (genTests) where
import Control.Arrow ( (&&&) )
import Control.Exception
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.ST
import Data.List ( delete
, sort
)
import Data.List.Split ( splitOn )
import Data.Map ( Map )
import qualified Data.Map as Map
import Data.Set ( Set )
import qualified Data.Set as Set
import qualified Data.Text as Text
import qualified Data.Text.IO as Text
import Data.Time
import GHC.Exts
import Nix.Lint
import Nix.Options
import Nix.Options.Parser
import Nix.Parser
import Nix.Pretty
import Nix.String
import Nix.Utils
import Nix.XML
import qualified Options.Applicative as Opts
import System.Environment
import System.FilePath
import System.FilePath.Glob ( compile
, globDir1
)
import Test.Tasty
import Test.Tasty.HUnit
import TestCommon
{-
From (git://nix)/tests/lang.sh we see that
lang/parse-fail-*.nix -> parsing should fail
lang/parse-okay-*.nix -> parsing should succeed
lang/eval-fail-*.nix -> eval should fail
lang/eval-okay-*.{nix,xml} -> eval should succeed,
xml dump should be the same as the .xml
lang/eval-okay-*.{nix,exp} -> eval should succeed,
plain text output should be the same as the .exp
lang/eval-okay-*.{nix,exp,flags} -> eval should succeed,
plain text output should be the same as the .exp,
pass the extra flags to nix-instantiate
NIX_PATH=lang/dir3:lang/dir4 should be in the environment of all
eval-okay-*.nix evaluations
TEST_VAR=foo should be in all the environments # for eval-okay-getenv.nix
-}
groupBy :: Ord k => (v -> k) -> [v] -> Map k [v]
groupBy key = Map.fromListWith (++) . map (key &&& pure)
-- | New tests, which have never yet passed. Once any of these is passing,
-- please remove it from this list. Do not add tests to this list if they have
-- previously passed.
newFailingTests :: Set String
newFailingTests = Set.fromList
[ "eval-okay-path"
, "eval-okay-fromTOML"
, "eval-okay-context-introspection"
]
genTests :: IO TestTree
genTests = do
testFiles <-
sort
-- jww (2018-05-07): Temporarily disable this test until #128 is fixed.
. filter ((`Set.notMember` newFailingTests) . takeBaseName)
. filter ((/= ".xml") . takeExtension)
<$> globDir1 (compile "*-*-*.*") "data/nix/tests/lang"
let testsByName = groupBy (takeFileName . dropExtensions) testFiles
let testsByType = groupBy testType (Map.toList testsByName)
let testGroups = map mkTestGroup (Map.toList testsByType)
return $ localOption (mkTimeout 2000000) $ testGroup
"Nix (upstream) language tests"
testGroups
where
testType (fullpath, _files) = take 2 $ splitOn "-" $ takeFileName fullpath
mkTestGroup (kind, tests) =
testGroup (unwords kind) $ map (mkTestCase kind) tests
mkTestCase kind (basename, files) = testCase (takeFileName basename) $ do
time <- liftIO getCurrentTime
let opts = defaultOptions time
case kind of
["parse", "okay"] -> assertParse opts $ the files
["parse", "fail"] -> assertParseFail opts $ the files
["eval" , "okay"] -> assertEval opts files
["eval" , "fail"] -> assertEvalFail $ the files
_ -> error $ "Unexpected: " ++ show kind
assertParse :: Options -> FilePath -> Assertion
assertParse _opts file = parseNixFileLoc file >>= \case
Success _expr -> return () -- pure $! runST $ void $ lint opts expr
Failure err ->
assertFailure $ "Failed to parse " ++ file ++ ":\n" ++ show err
assertParseFail :: Options -> FilePath -> Assertion
assertParseFail opts file = do
eres <- parseNixFileLoc file
catch
(case eres of
Success expr -> do
_ <- pure $! runST $ void $ lint opts expr
assertFailure
$ "Unexpected success parsing `"
++ file
++ ":\nParsed value: "
++ show expr
Failure _ -> return ()
)
$ \(_ :: SomeException) -> return ()
assertLangOk :: Options -> FilePath -> Assertion
assertLangOk opts file = do
actual <- printNix <$> hnixEvalFile opts (file ++ ".nix")
expected <- Text.readFile $ file ++ ".exp"
assertEqual "" expected $ Text.pack (actual ++ "\n")
assertLangOkXml :: Options -> FilePath -> Assertion
assertLangOkXml opts file = do
actual <- principledStringIgnoreContext . toXML <$> hnixEvalFile
opts
(file ++ ".nix")
expected <- Text.readFile $ file ++ ".exp.xml"
assertEqual "" expected actual
assertEval :: Options -> [FilePath] -> Assertion
assertEval _opts files = do
time <- liftIO getCurrentTime
let opts = defaultOptions time
case delete ".nix" $ sort $ map takeExtensions files of
[] -> () <$ hnixEvalFile opts (name ++ ".nix")
[".exp" ] -> assertLangOk opts name
[".exp.xml" ] -> assertLangOkXml opts name
[".exp.disabled"] -> return ()
[".exp-disabled"] -> return ()
[".exp", ".flags"] -> do
liftIO $ unsetEnv "NIX_PATH"
flags <- Text.readFile (name ++ ".flags")
let flags' | Text.last flags == '\n' = Text.init flags
| otherwise = flags
case
Opts.execParserPure
Opts.defaultPrefs
(nixOptionsInfo time)
(fixup (map Text.unpack (Text.splitOn " " flags')))
of
Opts.Failure err ->
errorWithoutStackTrace
$ "Error parsing flags from "
++ name
++ ".flags: "
++ show err
Opts.Success opts' -> assertLangOk
(opts'
{ include = include opts'
++ [ "nix=../../../../data/nix/corepkgs"
, "lang/dir4"
, "lang/dir5"
]
}
)
name
Opts.CompletionInvoked _ -> error "unused"
_ -> assertFailure $ "Unknown test type " ++ show files
where
name =
"data/nix/tests/lang/" ++ the (map (takeFileName . dropExtensions) files)
fixup ("--arg" : x : y : rest) = "--arg" : (x ++ "=" ++ y) : fixup rest
fixup ("--argstr" : x : y : rest) = "--argstr" : (x ++ "=" ++ y) : fixup rest
fixup (x : rest) = x : fixup rest
fixup [] = []
assertEvalFail :: FilePath -> Assertion
assertEvalFail file = catch ?? (\(_ :: SomeException) -> return ()) $ do
time <- liftIO getCurrentTime
evalResult <- printNix <$> hnixEvalFile (defaultOptions time) file
evalResult
`seq` assertFailure
$ file
++ " should not evaluate.\nThe evaluation result was `"
++ evalResult
++ "`."
|
jwiegley/hnix
|
tests/NixLanguageTests.hs
|
bsd-3-clause
| 7,403
| 0
| 20
| 2,433
| 1,727
| 885
| 842
| 150
| 12
|
{-| This module contains test cases for functions on source locations. -}
module SourceLocation(testSourceLocations) where
import Test.Tasty
import Test.Tasty.QuickCheck
import Test.Tasty.HUnit
import Prelude hiding (span)
import Language.Astview.Language
import Control.Exception(Exception,evaluate,try)
import Control.Monad(unless)
testSourceLocations :: TestTree
testSourceLocations =
testGroup "Source locations" [groupContains,smartConstructors]
groupContains :: TestTree
groupContains =
testGroup "ord instance for source locations implements contains"
[groupInOneline
,groupSorrounded
,groupSameBegin
,groupSameEnd
,groupEx
,groupAlgebraicProperties
]
groupAlgebraicProperties :: TestTree
groupAlgebraicProperties = testGroup "algebraic properties"
[propReflexivity
,propDuality
]
propReflexivity :: TestTree
propReflexivity = testGroup "Reflexivity" [propLEQ,propGEQ] where
propLEQ = testProperty "Reflexivity of <=" prop where
prop :: SrcSpan -> Bool
prop s = s <= s
propGEQ = testProperty "Reflexivity of >=" prop where
prop :: SrcSpan -> Bool
prop s = s >= s
propDuality:: TestTree
propDuality = testProperty "Duality of < and >" prop where
prop :: SrcSpan -> SrcSpan -> Bool
prop a b
| a < b = b > a && a /= b
| a == b = b == a
| a > b = b < a && a /= b
| otherwise = True
groupInOneline :: TestTree
groupInOneline = testGroup "Everything in one line" $ map (testCase [])
[ linear 3 1 2 > linear 3 1 2 @?= False
, linear 4 1 9 > linear 4 3 6 @?= True
, linear 4 0 6 < linear 4 1 9 @?= False
, linear 4 2 9 < linear 4 1 7 @?= False
, linear 4 1 9 > linear 4 1 9 @?= False
]
groupSorrounded :: TestTree
groupSorrounded = testGroup "Point sorrounded by span" $ map (testCase [])
[ span 4 9 7 9 > span 5 18 6 100 @?= True
, span 4 9 7 9 > span 5 1 6 1 @?= True
]
groupSameBegin :: TestTree
groupSameBegin = testGroup "Same begin line" $ map (testCase [])
[ span 4 9 7 9 > span 4 18 6 100 @?= True
, span 4 9 6 9 > span 4 18 7 100 @?= False
]
groupSameEnd :: TestTree
groupSameEnd = testGroup "Same end line" $ map (testCase [])
[ span 4 9 7 9 > span 5 18 7 5 @?= True
, span 1 9 7 9 > span 4 18 7 10 @?= False
]
groupEx :: TestTree
groupEx = testGroup "Extreme cases"
[ testCase "equal position" $ span 1 9 7 9 > span 1 9 7 9 @?= False
, testCase "same end" $ span 1 1 7 9 > span 1 2 7 9 @?= True
, testCase "same begin" $ span 1 9 7 9 > span 1 9 7 3 @?= True
]
smartConstructors :: TestTree
smartConstructors = testGroup "Smart constructors"
[ testCase "span works" $ span 1 2 3 4 @=? SrcSpan (SrcPos 1 2) (SrcPos 3 4)
, testCase "span throws exception if begin line > end line" $
assertException (SrcLocException $ spanUnsafe 2 1 1 1) (span 2 1 1 1)
, testCase "span throws exception if begin line equals end line and begin column > end column" $
assertException (SrcLocException $ spanUnsafe 1 5 1 3) (span 1 5 1 3)
, testCase "position works" $ position 3 4 @=? span 3 4 3 4
, testCase "linear works" $ linear 1 2 5 @=? span 1 2 1 5
, testCase "linear throws exception if begin row > end row" $
assertException (SrcLocException $ spanUnsafe 1 3 1 1) (linear 1 3 1)
]
-- * Util functions
-- |unsafe variant of 'span'
spanUnsafe :: Int -> Int -> Int -> Int -> SrcSpan
spanUnsafe bl bc el ec = SrcSpan (SrcPos bl bc) (SrcPos el ec)
-- |expects the exception @e@ to occur whhen trying to evaluate @t@
assertException :: (Show a,Show e,Exception e,Eq e) => e -> a -> Assertion
assertException e t =
let failure x = assertFailure $ "Expected exception ["++show e++"] but got "++show x
in do
result <- try (evaluate t)
case result of
Left exception -> unless (e == exception) $ failure exception
Right t -> failure t
|
jokusi/Astview
|
test/SourceLocation.hs
|
mit
| 3,920
| 0
| 15
| 976
| 1,337
| 671
| 666
| 85
| 2
|
{-|
Module : Graphics.Sudbury.State
Description : Wayland state tracker
Copyright : (c) Auke Booij, 2015-2017
License : MIT
Maintainer : auke@tulcod.com
Stability : experimental
Wayland is a stateful protocol. This code can track that state.
-}
module Graphics.Sudbury.State where
import Data.Word
import qualified Data.Map as M -- FIXME: Should this be Strict? or an IntMap?
import Data.List
import Graphics.Sudbury.Internal
import Graphics.Sudbury.Protocol.XML.Types
import Graphics.Sudbury.WirePackages
{-
Some fields in this file should probably be strict to avoid memory leaks.
-}
-- placeholders until I figure out what these should be
type MyObjectType = String
type MyMessageType = XMLMessage
type ProtocolSet = XMLProtocol
{-
state-related operations:
- insert new_id style object into map with version
(increase state)
< id and run-time type
+ read WireMessage and extract new_ids, insert into map
< typed message
- find Message corresponding to incoming WirePackage
< wirepackage
< protocol set
> Message?
- find interface type corresponding to sender ID (table lookup)
- find message corresponding to opcode ID (protocol lookup)
(read state)
+ interpret incoming wirepackage as typed message
< wirepackage
< protocol set
> typed message
- remove object from map on destruction
< id
- zombie?
(decrease state)
+ read (typed) message and extract destruction, remove from map
< typed message
+ read package and interpret as message, extract destruction, remove from map
< wirepackage
-}
-- | This represents (the state segment of) 'wl_client' (compositor-side) or 'wl_display' (client-side) in libwayland.
data ConnectionState = ConnectionState
{ connectionObjects :: M.Map Word32 MyObjectType
, connectionLastObjectId :: Word32
}
-- What will our analogue to 'wl_global_bind_func_t' be?
data Global = Global
{ globalInterface :: XMLInterface
, globalType :: MyObjectType
}
-- | This is known as 'wl_display' (compositor-side) in libwayland.
-- There is no client-side analogue.
-- The protocol is used to exchange this information from the compositor to the client.
data CompositorState = CompositorState
{ globalList :: M.Map Word32 Global
}
-- What do we want to say about the display object?
initialConnectionState :: ConnectionState
initialConnectionState = ConnectionState M.empty 1
-- This should probably be populated
initialCompositorState :: CompositorState
initialCompositorState = CompositorState M.empty
-- todo: do something more interesting if the key already exists
insertNewId :: Word32 -> MyObjectType -> ConnectionState -> ConnectionState
insertNewId i tp s = s { connectionObjects = M.insert i tp (connectionObjects s) }
packageFindMessage :: ServerClient -> ProtocolSet -> WirePackage -> ConnectionState -> Maybe MyMessageType
packageFindMessage sc ps pack s = do
tp <- M.lookup (wirePackageSender pack) (connectionObjects s)
iface <- find (\i -> interfaceName i == tp) (protocolInterfaces ps)
-- FIXME the following can fail!
let msg = case sc of
Server -> interfaceRequests iface !! fromIntegral (wirePackageOpcode pack)
Client -> interfaceEvents iface !! fromIntegral (wirePackageOpcode pack)
return msg
removeObject :: Word32 -> ConnectionState -> ConnectionState
removeObject i s = s { connectionObjects = M.delete i (connectionObjects s) }
|
abooij/sudbury
|
Graphics/Sudbury/State.hs
|
mit
| 3,369
| 0
| 16
| 562
| 436
| 240
| 196
| 34
| 2
|
{-
Copyright (C) 2012-2014 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
import Text.Pandoc
import Criterion.Main
import Criterion.Types (Config(..))
import Data.Maybe (mapMaybe)
import Debug.Trace (trace)
import Text.Pandoc.Error
readerBench :: Pandoc
-> (String, ReaderOptions -> String -> IO (Either PandocError Pandoc))
-> Maybe Benchmark
readerBench doc (name, reader) =
case lookup name writers of
Just (PureStringWriter writer) ->
let inp = writer def{ writerWrapText = True} doc
in return $ bench (name ++ " reader") $ nfIO $
(fmap handleError <$> reader def{ readerSmart = True }) inp
_ -> trace ("\nCould not find writer for " ++ name ++ "\n") Nothing
writerBench :: Pandoc
-> (String, WriterOptions -> Pandoc -> String)
-> Benchmark
writerBench doc (name, writer) = bench (name ++ " writer") $ nf
(writer def{ writerWrapText = True }) doc
main :: IO ()
main = do
inp <- readFile "tests/testsuite.txt"
let opts = def{ readerSmart = True }
let doc = handleError $ readMarkdown opts inp
let readers' = [(n,r) | (n, StringReader r) <- readers]
let readerBs = mapMaybe (readerBench doc)
$ filter (\(n,_) -> n /="haddock") readers'
let writers' = [(n,w) | (n, PureStringWriter w) <- writers]
let writerBs = map (writerBench doc)
$ writers'
defaultMainWith defaultConfig{ timeLimit = 6.0 }
(writerBs ++ readerBs)
|
alexvong1995/pandoc
|
benchmark/benchmark-pandoc.hs
|
gpl-2.0
| 2,146
| 0
| 16
| 484
| 522
| 272
| 250
| 34
| 2
|
{- |
Module : ./utils/itcor/GenItCorrections.hs
Copyright : (c) C. Maeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : experimental
Portability : portable
-}
module Main where
import Text.ParserCombinators.Parsec
import qualified Data.Map as Map
import System.Environment
import System.Exit
import System.Cmd
import Control.Monad
usage :: IO ()
usage = putStrLn
"Usage: it-corrections \"gen_it_characters\" \"gen_it_words\""
main :: IO ()
main = do
args <- getArgs
case args of
[] -> usage
[_] -> usage
[fp1_base, fp2_base] -> do
let fp1 = fp1_base ++ ".txt"
fp2 = fp2_base ++ ".txt"
fp1_tex = fp1_base ++ ".tex"
fp2_tex = fp2_base ++ ".tex"
fp1_pdf = fp1_base ++ ".pdf"
fp2_pdf = fp2_base ++ ".pdf"
generate_tex_files fp2_tex fp1_tex
convert_to_txt fp1_tex fp1_pdf
convert_to_txt fp2_tex fp2_pdf
str1 <- readFile fp1 -- file with table for every character
p1 <- parseItTable str1
str2 <- readFile fp2 -- file with table for combinated characters
p2 <- parseItTable str2
let itc = corrections (Map.fromList (zip allCharacters p1))
(zip combinations p2)
str <- output itc "" -- print itc
putStrLn ("\nitaliccorrection_map :: Map String Int\n" ++
"italiccorrection_map = fromList $ read " ++ post_proc str )
_ -> usage
convert_to_txt :: FilePath -> FilePath -> IO ()
convert_to_txt tex_name pdf_name = do
system ("pdflatex -interaction=batchmode " ++ tex_name ++ " >/dev/null") >>=
\ ec -> when (isFail ec) (fail "pdflatex went wrong")
rawSystem "pdftotext" ["-raw", "-q", pdf_name] >>=
\ ec -> when (isFail ec) (fail "pdftotext went wrong")
return ()
where isFail ec = case ec of
ExitFailure _ -> True
_ -> False
generate_tex_files :: String -> String -> IO ()
generate_tex_files filename1 filename2 = do
writeFile filename1 (tex_file $ writeTexTable combinations)
writeFile filename2 (tex_file $ writeTexTable [[c] | c <- allCharacters])
output :: [(String, Int)] -> String -> IO String
output [] str = return (init str)
output ((s, i) : xs) str =
output xs $ str ++ "(\"" ++ s ++ "\"," ++ show i ++ "),"
post_proc :: String -> String
post_proc str = '\"' : '[' : concatMap conv str ++ "]\""
where conv c = case c of
'\"' -> "\\\""
-- substitute umlauts with \196\214\220\223\228\246\252
'\196' -> "\\196"
'\214' -> "\\214"
'\220' -> "\\220"
'\223' -> "\\223"
'\228' -> "\\228"
'\246' -> "\\246"
'\252' -> "\\252"
_ -> [c]
-- -------- Parser for Table generated with "width-it-table.tex" ---------
parseItTable :: String -> IO [Double]
parseItTable str = case parse itParser "" str of
Left err -> do
putStr "parse error at"
print err; error ""
Right x -> return x
itParser :: Parser [Double]
itParser = do
manyTill anyChar (try (string "wl: "))
many1 tableEntry
<|> do
anyChar
itParser
tableEntry :: Parser Double
tableEntry = do
str <- parseDouble
string "pt"
spaces
try (manyTill anyChar $ try $ string "wl: ") <|> manyTill anyChar eof
return (read str)
parseDouble :: Parser String
parseDouble = many1 double
double :: Parser Char
double = digit <|> char '.'
stringHead :: Parser String
stringHead = do
c1 <- tableChar
c2 <- option "" tableChar
return (c1 ++ c2)
tableChar :: Parser String
tableChar = do
str <- try letter <|> digit
return [str]
-- ------------------------------------------------------------------------
corrections :: Map.Map Char Double -> [(String, Double)] -> [(String, Int)]
corrections fm = map (corrections' fm)
corrections' :: Map.Map Char Double -> (String, Double) -> (String, Int)
corrections' fm (str, d) = case str of
[c1, c2] ->
let d1 = Map.findWithDefault 0.0 c1 fm
d2 = Map.findWithDefault 0.0 c2 fm
dif = round (((d1 + d2) - d) * 0.351 * 1000.0)
in (str, dif)
_ -> error "corrections'"
combinations :: [String]
combinations = let z = zipIt allCharacters allCharacters
in [ c1 : [c2] | (c1, c2) <- z ]
where
zipIt :: String -> String -> [(Char, Char)]
zipIt [] _ = []
zipIt (a : as) bs = zip [a, a ..] bs ++ zipIt as bs
allCharacters :: String
allCharacters = ['a' .. 'z'] ++ ['A' .. 'Z'] ++ ['0' .. '9']
++ "\228\252\246\196\220\214\223"
writeTexTable :: [String] -> String
writeTexTable [] = []
writeTexTable strl = concat
[ "\\wordline{\\textit{" ++ str ++ "}}\n\\hline\n" | str <- f ]
++ "\\end{tabular}\n\\newpage\n\\begin{tabular}{l|l}\n\\hline\n"
++ writeTexTable r
where (f, r) = splitAt 30 strl
tex_file :: String -> String
tex_file str = unlines
[ "\\documentclass[a4paper]{article}"
, "\\usepackage{bookman}"
, "\\usepackage[latin1]{inputenc}"
, "\\usepackage{german}"
, "\\usepackage{calc}"
, "\\usepackage{longtable}"
, "\\newlength{\\widthofword}"
, "\\setlength{\\parindent}{0cm}"
, "\\newcommand{\\wordline}[1]%"
, "{#1 & wl: \\setlength{\\widthofword}{\\widthof{#1}}\\the\\widthofword\\\\}"
, "\\title{Useful Widths for Typesetting-CASL}"
, "\\author{Klaus Luettich}"
, "\\begin{document}"
, "\\maketitle"
, "\\begin{tabular}{l|l}"
, "\\hline"
, str
, "\\end{tabular}"
, "\\end{document}" ]
|
spechub/Hets
|
utils/itcor/GenItCorrections.hs
|
gpl-2.0
| 5,688
| 0
| 19
| 1,531
| 1,599
| 816
| 783
| 146
| 9
|
-- GSoC 2015 - Haskell bindings for OpenCog.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
-- | This Module defines some useful data types for proper interaction
-- with the AtomSpace C wrapper library.
-- Intended for internal use only.
module OpenCog.AtomSpace.Internal (
Handle(..)
, AtomTypeRaw(..)
, AtomRaw(..)
, toRaw
, fromRaw
, TVRaw(..)
, fromTVRaw
, toTVRaw
, TVTypeEnum(..)
, tvMAX_PARAMS
) where
import Foreign.C.Types (CULong(..))
import Data.Functor ((<$>))
import Data.Typeable (cast,Typeable)
import OpenCog.AtomSpace.Filter (Gen(..),FilterIsChild(..))
import OpenCog.AtomSpace.AtomType (AtomType(..),fromAtomTypeRaw,toAtomTypeRaw)
import OpenCog.AtomSpace.Types (Atom(..),AtomName(..),getType,TruthVal(..),
appAtomGen,AtomGen(..))
-- Data type to hold atoms's UUID.
type Handle = CULong
type AtomTypeRaw = String
-- Main general atom representation.
data AtomRaw = Link AtomTypeRaw [AtomRaw] (Maybe TVRaw)
| Node AtomTypeRaw AtomName (Maybe TVRaw)
-- Function to convert an Atom to its general representation.
toRaw :: Atom a -> AtomRaw
toRaw at = let atype = toAtomTypeRaw $ getType at
in case at of
PredicateNode n -> Node atype n Nothing
ConceptNode n tv -> Node atype n $ toTVRaw <$> tv
NumberNode d -> Node atype (show d) Nothing
SchemaNode n -> Node atype n Nothing
GroundedSchemaNode n -> Node atype n Nothing
AndLink a1 a2 tv -> Link atype [toRaw a1,toRaw a2] $ toTVRaw <$> tv
OrLink a1 a2 tv -> Link atype [toRaw a1,toRaw a2] $ toTVRaw <$> tv
ImplicationLink a1 a2 tv -> Link atype [toRaw a1,toRaw a2] $ toTVRaw <$> tv
EquivalenceLink a1 a2 tv -> Link atype [toRaw a1,toRaw a2] $ toTVRaw <$> tv
EvaluationLink a1 a2 tv -> Link atype [toRaw a1,toRaw a2] $ toTVRaw <$> tv
InheritanceLink a1 a2 tv -> Link atype [toRaw a1,toRaw a2] $ toTVRaw <$> tv
SimilarityLink a1 a2 tv -> Link atype [toRaw a1,toRaw a2] $ toTVRaw <$> tv
MemberLink a1 a2 tv -> Link atype [toRaw a1,toRaw a2] $ toTVRaw <$> tv
SatisfyingSetLink a1 -> Link atype [toRaw a1] Nothing
ExecutionLink a1 a2 a3 -> Link atype [toRaw a1,toRaw a2,toRaw a3] Nothing
ListLink list -> Link atype (map (appAtomGen toRaw) list) Nothing
_ -> undefined
-- Function to get an Atom back from its general representation (if possible).
fromRaw :: Typeable a => AtomRaw -> Atom a -> Maybe (Atom a)
fromRaw raw _ = fromRaw' raw >>= appAtomGen cast
-- Function to get an Atom back from its general representation (if possible).
fromRaw' :: AtomRaw -> Maybe (AtomGen)
fromRaw' (Node araw n tvraw) = let tv = fromTVRaw <$> tvraw in do
atype <- fromAtomTypeRaw araw
case atype of
ConceptT -> Just $ AtomGen $ ConceptNode n tv
PredicateT -> Just $ AtomGen $ PredicateNode n
SchemaT -> Just $ AtomGen $ SchemaNode n
GroundedSchemaT -> Just $ AtomGen $ GroundedSchemaNode n
NumberT -> readMaybe n >>= Just . AtomGen . NumberNode
_ -> Nothing
where
readMaybe :: (Read a) => String -> Maybe a
readMaybe s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
fromRaw' (Link araw out tvraw) = let tv = fromTVRaw <$> tvraw in do
atype <- fromAtomTypeRaw araw
case (atype,out) of
(AndT ,[ar,br]) -> do
a <- filt ar :: Maybe (Gen ConceptT)
b <- filt br :: Maybe (Gen ConceptT)
case (a,b) of
(Gen a1,Gen b1) -> Just $ AtomGen $ AndLink a1 b1 tv
(OrT ,[ar,br]) -> do
a <- filt ar :: Maybe (Gen ConceptT)
b <- filt br :: Maybe (Gen ConceptT)
case (a,b) of
(Gen a1,Gen b1) -> Just $ AtomGen $ OrLink a1 b1 tv
(ImplicationT ,[ar,br]) -> do
a <- fromRaw' ar
b <- fromRaw' br
case (a,b) of
(AtomGen a1,AtomGen b1) -> Just $ AtomGen $ ImplicationLink a1 b1 tv
(EquivalenceT ,[ar,br]) -> do
a <- fromRaw' ar
b <- fromRaw' br
case (a,b) of
(AtomGen a1,AtomGen b1) -> Just $ AtomGen $ EquivalenceLink a1 b1 tv
(EvaluationT ,[ar,br]) -> do
a <- filt ar :: Maybe (Gen PredicateT)
b <- filt br :: Maybe (Gen ListT)
case (a,b) of
(Gen a1,Gen b1) -> Just $ AtomGen $ EvaluationLink a1 b1 tv
(InheritanceT ,[ar,br]) -> do
a <- filt ar :: Maybe (Gen ConceptT)
b <- filt br :: Maybe (Gen ConceptT)
case (a,b) of
(Gen a1,Gen b1) -> Just $ AtomGen $ InheritanceLink a1 b1 tv
(SimilarityT ,[ar,br]) -> do
a <- filt ar :: Maybe (Gen ConceptT)
b <- filt br :: Maybe (Gen ConceptT)
case (a,b) of
(Gen a1,Gen b1) -> Just $ AtomGen $ SimilarityLink a1 b1 tv
(MemberT ,[ar,br]) -> do
a <- filt ar :: Maybe (Gen ConceptT)
b <- filt br :: Maybe (Gen ConceptT)
case (a,b) of
(Gen a1,Gen b1) -> Just $ AtomGen $ MemberLink a1 b1 tv
(SatisfyingSetT ,[ar]) -> do
a <- filt ar :: Maybe (Gen PredicateT)
case a of
(Gen a1) -> Just $ AtomGen $ SatisfyingSetLink a1
(ExecutionT ,[ar,br,cr]) -> do
a <- filt ar :: Maybe (Gen SchemaT)
b <- filt br :: Maybe (Gen ListT)
c <- filt br :: Maybe (Gen AtomT)
case (a,b,c) of
(Gen a1,Gen b1,Gen c1) -> Just $ AtomGen $ ExecutionLink a1 b1 c1
(ListT, _ ) -> do
lnew <- mapM fromRaw' out
Just $ AtomGen $ ListLink lnew
_ -> Nothing
filt :: FilterIsChild a => AtomRaw -> Maybe (Gen a)
filt araw = do
agen <- fromRaw' araw
case agen of
(AtomGen at) -> filtIsChild at
-- Constant with the maximum number of parameters in any type of TV.
tvMAX_PARAMS :: Int
tvMAX_PARAMS = 5
-- TV enum type to work with TruthValueTypes from
-- <opencog/atomspace/TruthValue.h> definition.
-- Note: this data type must be always similar to the definition on ../TruthValue.h.
-- The order of enum types MUST be exactly the same on both sites.
data TVTypeEnum = NULL_TRUTH_VALUE
| SIMPLE_TRUTH_VALUE
| COUNT_TRUTH_VALUE
| INDEFINITE_TRUTH_VALUE
| FUZZY_TRUTH_VALUE
| PROBABILISTIC_TRUTH_VALUE
deriving Enum
data TVRaw = TVRaw TVTypeEnum [Double]
toTVRaw :: TruthVal -> TVRaw
toTVRaw (SimpleTV a b ) = TVRaw SIMPLE_TRUTH_VALUE [a,b]
toTVRaw (CountTV a b c ) = TVRaw COUNT_TRUTH_VALUE [a,b,c]
toTVRaw (IndefTV a b c d e) = TVRaw INDEFINITE_TRUTH_VALUE [a,b,c,d,e]
toTVRaw (FuzzyTV a b ) = TVRaw FUZZY_TRUTH_VALUE [a,b]
toTVRaw (ProbTV a b c ) = TVRaw PROBABILISTIC_TRUTH_VALUE [a,b,c]
fromTVRaw :: TVRaw -> TruthVal
fromTVRaw (TVRaw SIMPLE_TRUTH_VALUE (a:b:_)) = SimpleTV a b
fromTVRaw (TVRaw COUNT_TRUTH_VALUE (a:b:c:_)) = CountTV a b c
fromTVRaw (TVRaw INDEFINITE_TRUTH_VALUE (a:b:c:d:e:_)) = IndefTV a b c d e
fromTVRaw (TVRaw FUZZY_TRUTH_VALUE (a:b:_)) = FuzzyTV a b
fromTVRaw (TVRaw PROBABILISTIC_TRUTH_VALUE (a:b:c:_)) = ProbTV a b c
|
jswiergo/atomspace
|
opencog/haskell/OpenCog/AtomSpace/Internal.hs
|
agpl-3.0
| 7,266
| 0
| 18
| 2,155
| 2,668
| 1,363
| 1,305
| 144
| 18
|
module Juno.Types.Event
( Event(..)
) where
import Juno.Types.Message
data Event = ERPC RPC
| AERs AlotOfAERs
| ElectionTimeout String
| HeartbeatTimeout String
deriving (Show)
|
buckie/juno
|
src/Juno/Types/Event.hs
|
bsd-3-clause
| 219
| 0
| 6
| 66
| 53
| 33
| 20
| 8
| 0
|
{-# LANGUAGE CPP #-}
-- | Log message formatting and debuging functions.
module Control.Super.Plugin.Log
( pprToStr, sDocToStr
, missingCaseError
, smErrMsg, smDebugMsg, smObjMsg, smWarnMsg
, formatGroupSrcSpans
, formatConstraint, formatSpan
-- * Debug Functions
, printTrace, printObjTrace, trace
-- * Debugging and priniting from within TcPluginM
, printObj, printMsg, printErr, printWarn
, pluginAssert, pluginFailSDoc
) where
import Data.List ( groupBy, intercalate )
import Debug.Trace ( trace )
import SrcLoc
( SrcSpan(..)
, srcSpanFileName_maybe
, srcSpanStartLine, srcSpanEndLine
, srcSpanStartCol, srcSpanEndCol )
import Outputable ( Outputable, SDoc )
import FastString ( unpackFS )
import TcRnTypes
( Ct(..), CtFlavour(..)--, CtLoc(..)
, ctFlavour, ctPred )
import TcPluginM ( TcPluginM, tcPluginIO, unsafeTcPluginTcM )
import IOEnv ( failWithM )
import Control.Super.Plugin.Debug ( pprToStr, sDocToStr )
import Control.Super.Plugin.Utils ( removeDup )
import Control.Super.Plugin.Constraint ( constraintSourceLocation )
-- | @prefixMsg prefix msg@ prefixes a message with the given string.
prefixMsg :: String -> String -> String
prefixMsg prefix = unlines . fmap ((pluginMsgPrefix ++ prefix) ++) . lines
-- | Message prefix of the plugin.
pluginMsgPrefix :: String
pluginMsgPrefix = "[SM]"
-- | Prefix a message with the error prefix.
smErrMsg :: String -> String
smErrMsg = prefixMsg $ " ERROR: "
-- | Prefix a message with the warning prefix.
smWarnMsg :: String -> String
smWarnMsg = prefixMsg $ " WARNING: "
-- | Prefix a message with the standard debug prefix.
smDebugMsg :: String -> String
smDebugMsg = prefixMsg $ " "
-- | Prefix a message with the debug prefix and a note that this is a
-- printed object.
smObjMsg :: String -> String
smObjMsg = prefixMsg $ "> "
-- | Used to emit an error with a message describing the missing case.
-- The string is the function that misses the case and the 'Outputable'
-- is the object being matched.
missingCaseError :: (Outputable o) => String -> Maybe o -> a
missingCaseError funName (Just val) = error $ "Missing case in '" ++ funName ++ "' for " ++ pprToStr val
missingCaseError funName Nothing = error $ "Missing case in '" ++ funName ++ "'"
-- -----------------------------------------------------------------------------
-- Formatting
-- -----------------------------------------------------------------------------
-- | Format a list of source spans by grouping spans in the same file together.
formatGroupSrcSpans :: [SrcSpan] -> String
formatGroupSrcSpans spans = unwords $ fmap formatSpanGroup groupedSpans
where
formatSpanGroup :: [SrcSpan] -> String
formatSpanGroup [] = ""
formatSpanGroup ss@(s:_) =
case srcSpanFileName_maybe s of
Nothing -> intercalate ", " $ fmap formatSpan ss
Just file -> unpackFS file ++ ": " ++ intercalate ", " (fmap formatSpan ss) ++ ";"
groupedSpans = groupBy eqFileName $ removeDup spans
eqFileName s1 s2 = srcSpanFileName_maybe s1 == srcSpanFileName_maybe s2
-- | Format a source span.
formatSpan :: SrcSpan -> String
formatSpan (UnhelpfulSpan str) = unpackFS str
formatSpan (RealSrcSpan s) =
show (srcSpanStartLine s) ++ ":" ++
show (srcSpanStartCol s) ++ "-" ++
(if srcSpanStartLine s /= srcSpanEndLine s then show (srcSpanEndLine s) ++ ":" else "") ++
show (srcSpanEndCol s)
-- | Format a constraint in a readable way, without displaying information
-- irrelevant to the plugin.
--
-- /Example:/
--
-- >>> [G] Supermonad m Identity m (129:12-131:41, CDictCan)
-- >>> [D] m_a1kdW ~ m (134:3-14, CNonCanonical)
formatConstraint :: Ct -> String
formatConstraint ct
= "[" ++ formatCtFlavour ct
++ "] " ++ formatCtType ct
++ " (" ++ formatSpan (constraintSourceLocation ct)
++ ", " ++ formatCtDataCon ct
++ ")"
where
formatCtDataCon :: Ct -> String
formatCtDataCon c = case c of
CDictCan {} -> "CDictCan"
#if MIN_VERSION_GLASGOW_HASKELL(8,4,0,0)
CIrredCan {} -> "CIrredCan"
#else
CIrredEvCan {} -> "CIrredEvCan"
#endif
CTyEqCan {} -> "CTyEqCan"
CFunEqCan {} -> "CFunEqCan"
CNonCanonical {} -> "CNonCanonical"
CHoleCan {} -> "CHoleCan"
formatCtFlavour :: Ct -> String
formatCtFlavour c = case ctFlavour c of
Given -> "G"
-- Pattern matching this way is important, because up to GHC 8.0
-- "Wanted" does not have arguments. Howeverm from GHC 8.2 onwards
-- it does have arguments.
Wanted {} -> "W"
Derived -> "D"
formatCtType :: Ct -> String
formatCtType c = pprToStr $ ctPred c
-- -----------------------------------------------------------------------------
-- Debug Functions
-- -----------------------------------------------------------------------------
-- | Print the result of calling 'show' on the given object.
printTrace :: (Show a) => a -> a
printTrace x = trace (show x) x
-- | Print the result of the 'Outputable' instance of the given object.
printObjTrace :: (Outputable o) => o -> o
printObjTrace o = trace (pprToStr o) o
-- -----------------------------------------------------------------------------
-- Debugging and printing from within TcPluginM
-- -----------------------------------------------------------------------------
-- | Internal function for printing from within the monad.
internalPrint :: String -> TcPluginM ()
internalPrint = tcPluginIO . putStr
-- | Print a message using the plugin formatting.
printMsg :: String -> TcPluginM ()
printMsg = internalPrint . smDebugMsg
-- | Print an error message using the plugin formatting.
printErr :: String -> TcPluginM ()
printErr = internalPrint . smErrMsg
-- | Print a warning message using the plugin formatting.
printWarn :: String -> TcPluginM ()
printWarn = internalPrint . smWarnMsg
-- | Print an object using the plugin formatting.
printObj :: Outputable o => o -> TcPluginM ()
printObj = internalPrint . smObjMsg . pprToStr
-- | Throw a type checker error with the given message.
pluginFailSDoc :: SDoc -> TcPluginM a
pluginFailSDoc msg = do
printMsg $ sDocToStr msg
unsafeTcPluginTcM $ failWithM (sDocToStr msg)
-- | If the given condition is false this will fail the compiler with the given error message.
pluginAssert :: Bool -> SDoc -> TcPluginM ()
pluginAssert True _ = return ()
pluginAssert False msg = pluginFailSDoc msg
|
jbracker/supermonad-plugin
|
src/Control/Super/Plugin/Log.hs
|
bsd-3-clause
| 6,401
| 0
| 14
| 1,200
| 1,278
| 700
| 578
| 102
| 8
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Web.Scotty.Action
( addHeader
, body
, bodyReader
, file
, files
, header
, headers
, html
, json
, jsonData
, next
, param
, params
, raise
, raw
, readEither
, redirect
, request
, rescue
, setHeader
, status
, stream
, text
, Param
, Parsable(..)
-- private to Scotty
, runAction
) where
import Blaze.ByteString.Builder (fromLazyByteString)
import Control.Monad.Error.Class
import Control.Monad.Reader
import qualified Control.Monad.State as MS
import Control.Monad.Trans.Except
import qualified Data.Aeson as A
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.CaseInsensitive as CI
import Data.Default.Class (def)
import Data.Int
#if !(MIN_VERSION_base(4,8,0))
import Data.Monoid (mconcat)
#endif
import qualified Data.Text as ST
import qualified Data.Text.Lazy as T
import Data.Text.Lazy.Encoding (encodeUtf8)
import Data.Word
import Network.HTTP.Types
import Network.Wai
import Numeric.Natural
import Web.Scotty.Internal.Types
import Web.Scotty.Util
-- Nothing indicates route failed (due to Next) and pattern matching should continue.
-- Just indicates a successful response.
runAction :: (ScottyError e, Monad m) => ErrorHandler e m -> ActionEnv -> ActionT e m () -> m (Maybe Response)
runAction h env action = do
(e,r) <- flip MS.runStateT def
$ flip runReaderT env
$ runExceptT
$ runAM
$ action `catchError` (defH h)
return $ either (const Nothing) (const $ Just $ mkResponse r) e
-- | Default error handler for all actions.
defH :: (ScottyError e, Monad m) => ErrorHandler e m -> ActionError e -> ActionT e m ()
defH _ (Redirect url) = do
status status302
setHeader "Location" url
defH Nothing (ActionError e) = do
status status500
html $ mconcat ["<h1>500 Internal Server Error</h1>", showError e]
defH h@(Just f) (ActionError e) = f e `catchError` (defH h) -- so handlers can throw exceptions themselves
defH _ Next = next
-- | Throw an exception, which can be caught with 'rescue'. Uncaught exceptions
-- turn into HTTP 500 responses.
raise :: (ScottyError e, Monad m) => e -> ActionT e m a
raise = throwError . ActionError
-- | Abort execution of this action and continue pattern matching routes.
-- Like an exception, any code after 'next' is not executed.
--
-- As an example, these two routes overlap. The only way the second one will
-- ever run is if the first one calls 'next'.
--
-- > get "/foo/:bar" $ do
-- > w :: Text <- param "bar"
-- > unless (w == "special") next
-- > text "You made a request to /foo/special"
-- >
-- > get "/foo/:baz" $ do
-- > w <- param "baz"
-- > text $ "You made a request to: " <> w
next :: (ScottyError e, Monad m) => ActionT e m a
next = throwError Next
-- | Catch an exception thrown by 'raise'.
--
-- > raise "just kidding" `rescue` (\msg -> text msg)
rescue :: (ScottyError e, Monad m) => ActionT e m a -> (e -> ActionT e m a) -> ActionT e m a
rescue action h = catchError action $ \e -> case e of
ActionError err -> h err -- handle errors
other -> throwError other -- rethrow internal error types
-- | Redirect to given URL. Like throwing an uncatchable exception. Any code after the call to redirect
-- will not be run.
--
-- > redirect "http://www.google.com"
--
-- OR
--
-- > redirect "/foo/bar"
redirect :: (ScottyError e, Monad m) => T.Text -> ActionT e m a
redirect = throwError . Redirect
-- | Get the 'Request' object.
request :: Monad m => ActionT e m Request
request = ActionT $ liftM getReq ask
-- | Get list of uploaded files.
files :: Monad m => ActionT e m [File]
files = ActionT $ liftM getFiles ask
-- | Get a request header. Header name is case-insensitive.
header :: (ScottyError e, Monad m) => T.Text -> ActionT e m (Maybe T.Text)
header k = do
hs <- liftM requestHeaders request
return $ fmap strictByteStringToLazyText $ lookup (CI.mk (lazyTextToStrictByteString k)) hs
-- | Get all the request headers. Header names are case-insensitive.
headers :: (ScottyError e, Monad m) => ActionT e m [(T.Text, T.Text)]
headers = do
hs <- liftM requestHeaders request
return [ ( strictByteStringToLazyText (CI.original k)
, strictByteStringToLazyText v)
| (k,v) <- hs ]
-- | Get the request body.
body :: (ScottyError e, MonadIO m) => ActionT e m BL.ByteString
body = ActionT ask >>= (liftIO . getBody)
-- | Get an IO action that reads body chunks
--
-- * This is incompatible with 'body' since 'body' consumes all chunks.
bodyReader :: Monad m => ActionT e m (IO B.ByteString)
bodyReader = ActionT $ getBodyChunk `liftM` ask
-- | Parse the request body as a JSON object and return it. Raises an exception if parse is unsuccessful.
jsonData :: (A.FromJSON a, ScottyError e, MonadIO m) => ActionT e m a
jsonData = do
b <- body
either (\e -> raise $ stringError $ "jsonData - no parse: " ++ e ++ ". Data was:" ++ BL.unpack b) return $ A.eitherDecode b
-- | Get a parameter. First looks in captures, then form data, then query parameters.
--
-- * Raises an exception which can be caught by 'rescue' if parameter is not found.
--
-- * If parameter is found, but 'read' fails to parse to the correct type, 'next' is called.
-- This means captures are somewhat typed, in that a route won't match if a correctly typed
-- capture cannot be parsed.
param :: (Parsable a, ScottyError e, Monad m) => T.Text -> ActionT e m a
param k = do
val <- ActionT $ liftM (lookup k . getParams) ask
case val of
Nothing -> raise $ stringError $ "Param: " ++ T.unpack k ++ " not found!"
Just v -> either (const next) return $ parseParam v
-- | Get all parameters from capture, form and query (in that order).
params :: Monad m => ActionT e m [Param]
params = ActionT $ liftM getParams ask
-- | Minimum implemention: 'parseParam'
class Parsable a where
-- | Take a 'T.Text' value and parse it as 'a', or fail with a message.
parseParam :: T.Text -> Either T.Text a
-- | Default implementation parses comma-delimited lists.
--
-- > parseParamList t = mapM parseParam (T.split (== ',') t)
parseParamList :: T.Text -> Either T.Text [a]
parseParamList t = mapM parseParam (T.split (== ',') t)
-- No point using 'read' for Text, ByteString, Char, and String.
instance Parsable T.Text where parseParam = Right
instance Parsable ST.Text where parseParam = Right . T.toStrict
instance Parsable B.ByteString where parseParam = Right . lazyTextToStrictByteString
instance Parsable BL.ByteString where parseParam = Right . encodeUtf8
-- | Overrides default 'parseParamList' to parse String.
instance Parsable Char where
parseParam t = case T.unpack t of
[c] -> Right c
_ -> Left "parseParam Char: no parse"
parseParamList = Right . T.unpack -- String
-- | Checks if parameter is present and is null-valued, not a literal '()'.
-- If the URI requested is: '/foo?bar=()&baz' then 'baz' will parse as (), where 'bar' will not.
instance Parsable () where
parseParam t = if T.null t then Right () else Left "parseParam Unit: no parse"
instance (Parsable a) => Parsable [a] where parseParam = parseParamList
instance Parsable Bool where
parseParam t = if t' == T.toCaseFold "true"
then Right True
else if t' == T.toCaseFold "false"
then Right False
else Left "parseParam Bool: no parse"
where t' = T.toCaseFold t
instance Parsable Double where parseParam = readEither
instance Parsable Float where parseParam = readEither
instance Parsable Int where parseParam = readEither
instance Parsable Int8 where parseParam = readEither
instance Parsable Int16 where parseParam = readEither
instance Parsable Int32 where parseParam = readEither
instance Parsable Int64 where parseParam = readEither
instance Parsable Integer where parseParam = readEither
instance Parsable Word where parseParam = readEither
instance Parsable Word8 where parseParam = readEither
instance Parsable Word16 where parseParam = readEither
instance Parsable Word32 where parseParam = readEither
instance Parsable Word64 where parseParam = readEither
instance Parsable Natural where parseParam = readEither
-- | Useful for creating 'Parsable' instances for things that already implement 'Read'. Ex:
--
-- > instance Parsable Int where parseParam = readEither
readEither :: Read a => T.Text -> Either T.Text a
readEither t = case [ x | (x,"") <- reads (T.unpack t) ] of
[x] -> Right x
[] -> Left "readEither: no parse"
_ -> Left "readEither: ambiguous parse"
-- | Set the HTTP response status. Default is 200.
status :: Monad m => Status -> ActionT e m ()
status = ActionT . MS.modify . setStatus
-- Not exported, but useful in the functions below.
changeHeader :: Monad m
=> (CI.CI B.ByteString -> B.ByteString -> [(HeaderName, B.ByteString)] -> [(HeaderName, B.ByteString)])
-> T.Text -> T.Text -> ActionT e m ()
changeHeader f k = ActionT
. MS.modify
. setHeaderWith
. f (CI.mk $ lazyTextToStrictByteString k)
. lazyTextToStrictByteString
-- | Add to the response headers. Header names are case-insensitive.
addHeader :: Monad m => T.Text -> T.Text -> ActionT e m ()
addHeader = changeHeader add
-- | Set one of the response headers. Will override any previously set value for that header.
-- Header names are case-insensitive.
setHeader :: Monad m => T.Text -> T.Text -> ActionT e m ()
setHeader = changeHeader replace
-- | Set the body of the response to the given 'T.Text' value. Also sets \"Content-Type\"
-- header to \"text/plain; charset=utf-8\" if it has not already been set.
text :: (ScottyError e, Monad m) => T.Text -> ActionT e m ()
text t = do
changeHeader addIfNotPresent "Content-Type" "text/plain; charset=utf-8"
raw $ encodeUtf8 t
-- | Set the body of the response to the given 'T.Text' value. Also sets \"Content-Type\"
-- header to \"text/html; charset=utf-8\" if it has not already been set.
html :: (ScottyError e, Monad m) => T.Text -> ActionT e m ()
html t = do
changeHeader addIfNotPresent "Content-Type" "text/html; charset=utf-8"
raw $ encodeUtf8 t
-- | Send a file as the response. Doesn't set the \"Content-Type\" header, so you probably
-- want to do that on your own with 'setHeader'.
file :: Monad m => FilePath -> ActionT e m ()
file = ActionT . MS.modify . setContent . ContentFile
-- | Set the body of the response to the JSON encoding of the given value. Also sets \"Content-Type\"
-- header to \"application/json; charset=utf-8\" if it has not already been set.
json :: (A.ToJSON a, ScottyError e, Monad m) => a -> ActionT e m ()
json v = do
changeHeader addIfNotPresent "Content-Type" "application/json; charset=utf-8"
raw $ A.encode v
-- | Set the body of the response to a Source. Doesn't set the
-- \"Content-Type\" header, so you probably want to do that on your
-- own with 'setHeader'.
stream :: Monad m => StreamingBody -> ActionT e m ()
stream = ActionT . MS.modify . setContent . ContentStream
-- | Set the body of the response to the given 'BL.ByteString' value. Doesn't set the
-- \"Content-Type\" header, so you probably want to do that on your
-- own with 'setHeader'.
raw :: Monad m => BL.ByteString -> ActionT e m ()
raw = ActionT . MS.modify . setContent . ContentBuilder . fromLazyByteString
|
adamflott/scotty
|
Web/Scotty/Action.hs
|
bsd-3-clause
| 11,979
| 0
| 15
| 2,848
| 2,706
| 1,445
| 1,261
| 182
| 3
|
{-# LANGUAGE Haskell2010 #-}
{-# LINE 1 "Web/Scotty/Internal/Types.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Web.Scotty.Internal.Types where
import Blaze.ByteString.Builder (Builder)
import Control.Applicative
import qualified Control.Exception as E
import Control.Monad.Base (MonadBase, liftBase, liftBaseDefault)
import Control.Monad.Error.Class
import qualified Control.Monad.Fail as Fail
import Control.Monad.Reader
import Control.Monad.State
import Control.Monad.Trans.Control (MonadBaseControl, StM, liftBaseWith, restoreM, ComposeSt, defaultLiftBaseWith, defaultRestoreM, MonadTransControl, StT, liftWith, restoreT)
import Control.Monad.Trans.Except
import qualified Data.ByteString as BS
import Data.ByteString.Lazy.Char8 (ByteString)
import Data.Default.Class (Default, def)
import Data.String (IsString(..))
import Data.Text.Lazy (Text, pack)
import Data.Typeable (Typeable)
import Network.HTTP.Types
import Network.Wai hiding (Middleware, Application)
import qualified Network.Wai as Wai
import Network.Wai.Handler.Warp (Settings, defaultSettings, setFdCacheDuration)
import Network.Wai.Parse (FileInfo)
--------------------- Options -----------------------
data Options = Options { verbose :: Int -- ^ 0 = silent, 1(def) = startup banner
, settings :: Settings -- ^ Warp 'Settings'
-- Note: to work around an issue in warp,
-- the default FD cache duration is set to 0
-- so changes to static files are always picked
-- up. This likely has performance implications,
-- so you may want to modify this for production
-- servers using `setFdCacheDuration`.
}
instance Default Options where
def = Options 1 (setFdCacheDuration 0 defaultSettings)
----- Transformer Aware Applications/Middleware -----
type Middleware m = Application m -> Application m
type Application m = Request -> m Response
--------------- Scotty Applications -----------------
data ScottyState e m =
ScottyState { middlewares :: [Wai.Middleware]
, routes :: [Middleware m]
, handler :: ErrorHandler e m
}
instance Default (ScottyState e m) where
def = ScottyState [] [] Nothing
addMiddleware :: Wai.Middleware -> ScottyState e m -> ScottyState e m
addMiddleware m s@(ScottyState {middlewares = ms}) = s { middlewares = m:ms }
addRoute :: Middleware m -> ScottyState e m -> ScottyState e m
addRoute r s@(ScottyState {routes = rs}) = s { routes = r:rs }
addHandler :: ErrorHandler e m -> ScottyState e m -> ScottyState e m
addHandler h s = s { handler = h }
newtype ScottyT e m a = ScottyT { runS :: State (ScottyState e m) a }
deriving ( Functor, Applicative, Monad )
------------------ Scotty Errors --------------------
data ActionError e = Redirect Text
| Next
| Finish
| ActionError e
-- | In order to use a custom exception type (aside from 'Text'), you must
-- define an instance of 'ScottyError' for that type.
class ScottyError e where
stringError :: String -> e
showError :: e -> Text
instance ScottyError Text where
stringError = pack
showError = id
instance ScottyError e => ScottyError (ActionError e) where
stringError = ActionError . stringError
showError (Redirect url) = url
showError Next = pack "Next"
showError Finish = pack "Finish"
showError (ActionError e) = showError e
type ErrorHandler e m = Maybe (e -> ActionT e m ())
------------------ Scotty Actions -------------------
type Param = (Text, Text)
type File = (Text, FileInfo ByteString)
data ActionEnv = Env { getReq :: Request
, getParams :: [Param]
, getBody :: IO ByteString
, getBodyChunk :: IO BS.ByteString
, getFiles :: [File]
}
data RequestBodyState = BodyUntouched
| BodyCached ByteString [BS.ByteString] -- whole body, chunks left to stream
| BodyCorrupted
data BodyPartiallyStreamed = BodyPartiallyStreamed deriving (Show, Typeable)
instance E.Exception BodyPartiallyStreamed
data Content = ContentBuilder Builder
| ContentFile FilePath
| ContentStream StreamingBody
data ScottyResponse = SR { srStatus :: Status
, srHeaders :: ResponseHeaders
, srContent :: Content
}
instance Default ScottyResponse where
def = SR status200 [] (ContentBuilder mempty)
newtype ActionT e m a = ActionT { runAM :: ExceptT (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a }
deriving ( Functor, Applicative, MonadIO )
instance (Monad m, ScottyError e) => Monad (ActionT e m) where
return = ActionT . return
ActionT m >>= k = ActionT (m >>= runAM . k)
fail = ActionT . throwError . stringError
instance (Monad m, ScottyError e) => Fail.MonadFail (ActionT e m) where
fail = ActionT . throwError . stringError
instance ( Monad m, ScottyError e
) => Alternative (ActionT e m) where
empty = mzero
(<|>) = mplus
instance (Monad m, ScottyError e) => MonadPlus (ActionT e m) where
mzero = ActionT . ExceptT . return $ Left Next
ActionT m `mplus` ActionT n = ActionT . ExceptT $ do
a <- runExceptT m
case a of
Left _ -> runExceptT n
Right r -> return $ Right r
instance MonadTrans (ActionT e) where
lift = ActionT . lift . lift . lift
instance (ScottyError e, Monad m) => MonadError (ActionError e) (ActionT e m) where
throwError = ActionT . throwError
catchError (ActionT m) f = ActionT (catchError m (runAM . f))
instance (MonadBase b m, ScottyError e) => MonadBase b (ActionT e m) where
liftBase = liftBaseDefault
instance MonadTransControl (ActionT e) where
type StT (ActionT e) a = StT (StateT ScottyResponse) (StT (ReaderT ActionEnv) (StT (ExceptT (ActionError e)) a))
liftWith = \f ->
ActionT $ liftWith $ \run ->
liftWith $ \run' ->
liftWith $ \run'' ->
f $ run'' . run' . run . runAM
restoreT = ActionT . restoreT . restoreT . restoreT
instance (ScottyError e, MonadBaseControl b m) => MonadBaseControl b (ActionT e m) where
type StM (ActionT e m) a = ComposeSt (ActionT e) m a
liftBaseWith = defaultLiftBaseWith
restoreM = defaultRestoreM
------------------ Scotty Routes --------------------
data RoutePattern = Capture Text
| Literal Text
| Function (Request -> Maybe [Param])
instance IsString RoutePattern where
fromString = Capture . pack
|
phischu/fragnix
|
tests/packages/scotty/Web.Scotty.Internal.Types.hs
|
bsd-3-clause
| 7,462
| 0
| 16
| 2,247
| 1,812
| 1,013
| 799
| 131
| 1
|
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-
Copyright (C) - 2017 Róman Joost <roman@bromeco.de>
This file is part of gtfsschedule.
gtfsschedule 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.
gtfsschedule 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 gtfsschedule. If not, see <http://www.gnu.org/licenses/>.
-}
module TestCSVImport (importTests) where
import Fixtures
import qualified CSV.Import as CSV
import qualified GTFS.Database as DB
import GTFS.Schedule (ScheduleItem (..),
ScheduleState (..), Stop (..),
TimeSpec (..),
VehicleInformation (..), getSchedule)
import Data.Time.Calendar (fromGregorian)
import Data.Time.Clock (UTCTime (..), getCurrentTime)
import Data.Time.LocalTime (TimeOfDay (..))
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.HUnit (testCase, (@?=))
import Control.Exception.Lifted (onException)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8 (pack)
import Data.Conduit (yield, (.|), runConduit)
import Data.Conduit.Network (AppData, appSink)
import qualified Data.Text as T
import System.IO.Temp (withSystemTempFile)
importTests ::
TestTree
importTests = testGroup "import tests"
[ testImportWithExistingDBFile
, testImportWithoutExistingDBFile
]
testImportWithExistingDBFile :: TestTree
testImportWithExistingDBFile =
testCase "imports all successfully" $
withConcurrentTCPServer withHTTPAppData $
\port ->
do withSystemTempFile
"ImportTest"
(\tmpfile _ ->
do let url =
concat ["http://", serverHost, ":", show port]
CSV.createNewDatabase url tmpfile
schedule <-
getSchedule
tmpfile
Stop
{ stopIdentifier = "600029"
, stopWalktime = 7
, stopName = ""
}
(TimeSpec
(TimeOfDay 7 50 0)
(fromGregorian 2015 1 28))
3
schedule @?=
[ ScheduleItem
{ tripId = "QF0815-00"
, stop = Stop
{ stopIdentifier = "600029"
, stopWalktime = 7
, stopName = "not relevant"
}
, serviceName = "66 not relevant"
, scheduledDepartureTime = (TimeOfDay 8 5 0)
, departureDelay = 0
, departureTime = (TimeOfDay 8 5 0)
, scheduleType = SCHEDULED
, scheduleItemVehicleInformation = VehicleInformation Nothing Nothing
}])
testImportWithoutExistingDBFile :: TestTree
testImportWithoutExistingDBFile =
testCase "imports by creating DB file" $
withConcurrentTCPServer withHTTPAppData $
\port ->
do newdbfile <- generateTestUserDBFilePath "importsByCreatingDBfile"
onException (runImport port newdbfile) (cleanUpIfExist newdbfile)
now <- getCurrentTime
day <- DB.getLastUpdatedDatabase (T.pack newdbfile)
day @?= utctDay now
where
runImport p userdbfile = do
let url = concat ["http://", serverHost, ":", show p]
CSV.createNewDatabase url userdbfile
withHTTPAppData :: AppData -> IO ()
withHTTPAppData appData = runConduit $ src .| appSink appData
where
src = do
yield "HTTP/1.1 200 OK\r\nContent-Type: application/x-zip-compressed\r\n"
contents <- liftIO $ BS.readFile $ concat ["test", "/", "data", "/", "importtest.zip"]
let clength = BS.concat ["Content-Length: ", (C8.pack $ show $ BS.length contents), "\r\n"]
yield $ BS.concat [clength, "\r\n", contents]
|
romanofski/gtfsbrisbane
|
test/TestCSVImport.hs
|
bsd-3-clause
| 5,158
| 0
| 19
| 2,025
| 811
| 462
| 349
| 85
| 1
|
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Network/HTTP/Types/Status.hs" #-}
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable #-}
module Network.HTTP.Types.Status
( Status(..)
, mkStatus
, status100
, continue100
, status101
, switchingProtocols101
, status200
, ok200
, status201
, created201
, status202
, accepted202
, status203
, nonAuthoritative203
, status204
, noContent204
, status205
, resetContent205
, status206
, partialContent206
, status300
, multipleChoices300
, status301
, movedPermanently301
, status302
, found302
, status303
, seeOther303
, status304
, notModified304
, status305
, useProxy305
, status307
, temporaryRedirect307
, status308
, permanentRedirect308
, status400
, badRequest400
, status401
, unauthorized401
, status402
, paymentRequired402
, status403
, forbidden403
, status404
, notFound404
, status405
, methodNotAllowed405
, status406
, notAcceptable406
, status407
, proxyAuthenticationRequired407
, status408
, requestTimeout408
, status409
, conflict409
, status410
, gone410
, status411
, lengthRequired411
, status412
, preconditionFailed412
, status413
, requestEntityTooLarge413
, status414
, requestURITooLong414
, status415
, unsupportedMediaType415
, status416
, requestedRangeNotSatisfiable416
, status417
, expectationFailed417
, status418
, imATeaPot418
, status422
, unprocessableEntity422
, status428
, preconditionRequired428
, status429
, tooManyRequests429
, status431
, requestHeaderFieldsTooLarge431
, status500
, internalServerError500
, status501
, notImplemented501
, status502
, badGateway502
, status503
, serviceUnavailable503
, status504
, gatewayTimeout504
, status505
, status511
, networkAuthenticationRequired511
, httpVersionNotSupported505
, statusIsInformational
, statusIsSuccessful
, statusIsRedirection
, statusIsClientError
, statusIsServerError
) where
import qualified Data.ByteString as B
import Data.Typeable
-- | HTTP Status.
--
-- Only the 'statusCode' is used for comparisons.
--
-- Please use 'mkStatus' to create status codes from code and message, or the 'Enum' instance or the
-- status code constants (like 'ok200'). There might be additional record members in the future.
--
-- Note that the Show instance is only for debugging.
data Status
= Status { statusCode :: Int
, statusMessage :: B.ByteString
} deriving (Show, Typeable)
instance Eq Status where
Status { statusCode = a } == Status { statusCode = b } = a == b
instance Ord Status where
compare Status { statusCode = a } Status { statusCode = b } = a `compare` b
instance Enum Status where
fromEnum = statusCode
toEnum 100 = status100
toEnum 101 = status101
toEnum 200 = status200
toEnum 201 = status201
toEnum 202 = status202
toEnum 203 = status203
toEnum 204 = status204
toEnum 205 = status205
toEnum 206 = status206
toEnum 300 = status300
toEnum 301 = status301
toEnum 302 = status302
toEnum 303 = status303
toEnum 304 = status304
toEnum 305 = status305
toEnum 307 = status307
toEnum 308 = status308
toEnum 400 = status400
toEnum 401 = status401
toEnum 402 = status402
toEnum 403 = status403
toEnum 404 = status404
toEnum 405 = status405
toEnum 406 = status406
toEnum 407 = status407
toEnum 408 = status408
toEnum 409 = status409
toEnum 410 = status410
toEnum 411 = status411
toEnum 412 = status412
toEnum 413 = status413
toEnum 414 = status414
toEnum 415 = status415
toEnum 416 = status416
toEnum 417 = status417
toEnum 422 = status422
toEnum 428 = status428
toEnum 429 = status429
toEnum 431 = status431
toEnum 500 = status500
toEnum 501 = status501
toEnum 502 = status502
toEnum 503 = status503
toEnum 504 = status504
toEnum 505 = status505
toEnum 511 = status511
toEnum c = mkStatus c B.empty
-- | Create a Status from status code and message.
mkStatus :: Int -> B.ByteString -> Status
mkStatus i m = Status i m
-- | Continue 100
status100 :: Status
status100 = mkStatus 100 "Continue"
-- | Continue 100
continue100 :: Status
continue100 = status100
-- | Switching Protocols 101
status101 :: Status
status101 = mkStatus 101 "Switching Protocols"
-- | Switching Protocols 101
switchingProtocols101 :: Status
switchingProtocols101 = status101
-- | OK 200
status200 :: Status
status200 = mkStatus 200 "OK"
-- | OK 200
ok200 :: Status
ok200 = status200
-- | Created 201
status201 :: Status
status201 = mkStatus 201 "Created"
-- | Created 201
created201 :: Status
created201 = status201
-- | Accepted 202
status202 :: Status
status202 = mkStatus 202 "Accepted"
-- | Accepted 202
accepted202 :: Status
accepted202 = status202
-- | Non-Authoritative Information 203
status203 :: Status
status203 = mkStatus 203 "Non-Authoritative Information"
-- | Non-Authoritative Information 203
nonAuthoritative203 :: Status
nonAuthoritative203 = status203
-- | No Content 204
status204 :: Status
status204 = mkStatus 204 "No Content"
-- | No Content 204
noContent204 :: Status
noContent204 = status204
-- | Reset Content 205
status205 :: Status
status205 = mkStatus 205 "Reset Content"
-- | Reset Content 205
resetContent205 :: Status
resetContent205 = status205
-- | Partial Content 206
status206 :: Status
status206 = mkStatus 206 "Partial Content"
-- | Partial Content 206
partialContent206 :: Status
partialContent206 = status206
-- | Multiple Choices 300
status300 :: Status
status300 = mkStatus 300 "Multiple Choices"
-- | Multiple Choices 300
multipleChoices300 :: Status
multipleChoices300 = status300
-- | Moved Permanently 301
status301 :: Status
status301 = mkStatus 301 "Moved Permanently"
-- | Moved Permanently 301
movedPermanently301 :: Status
movedPermanently301 = status301
-- | Found 302
status302 :: Status
status302 = mkStatus 302 "Found"
-- | Found 302
found302 :: Status
found302 = status302
-- | See Other 303
status303 :: Status
status303 = mkStatus 303 "See Other"
-- | See Other 303
seeOther303 :: Status
seeOther303 = status303
-- | Not Modified 304
status304 :: Status
status304 = mkStatus 304 "Not Modified"
-- | Not Modified 304
notModified304 :: Status
notModified304 = status304
-- | Use Proxy 305
status305 :: Status
status305 = mkStatus 305 "Use Proxy"
-- | Use Proxy 305
useProxy305 :: Status
useProxy305 = status305
-- | Temporary Redirect 307
status307 :: Status
status307 = mkStatus 307 "Temporary Redirect"
-- | Temporary Redirect 307
temporaryRedirect307 :: Status
temporaryRedirect307 = status307
-- | Permanent Redirect 308
status308 :: Status
status308 = mkStatus 308 "Permanent Redirect"
-- | Permanent Redirect 308
permanentRedirect308 :: Status
permanentRedirect308 = status308
-- | Bad Request 400
status400 :: Status
status400 = mkStatus 400 "Bad Request"
-- | Bad Request 400
badRequest400 :: Status
badRequest400 = status400
-- | Unauthorized 401
status401 :: Status
status401 = mkStatus 401 "Unauthorized"
-- | Unauthorized 401
unauthorized401 :: Status
unauthorized401 = status401
-- | Payment Required 402
status402 :: Status
status402 = mkStatus 402 "Payment Required"
-- | Payment Required 402
paymentRequired402 :: Status
paymentRequired402 = status402
-- | Forbidden 403
status403 :: Status
status403 = mkStatus 403 "Forbidden"
-- | Forbidden 403
forbidden403 :: Status
forbidden403 = status403
-- | Not Found 404
status404 :: Status
status404 = mkStatus 404 "Not Found"
-- | Not Found 404
notFound404 :: Status
notFound404 = status404
-- | Method Not Allowed 405
status405 :: Status
status405 = mkStatus 405 "Method Not Allowed"
-- | Method Not Allowed 405
methodNotAllowed405 :: Status
methodNotAllowed405 = status405
-- | Not Acceptable 406
status406 :: Status
status406 = mkStatus 406 "Not Acceptable"
-- | Not Acceptable 406
notAcceptable406 :: Status
notAcceptable406 = status406
-- | Proxy Authentication Required 407
status407 :: Status
status407 = mkStatus 407 "Proxy Authentication Required"
-- | Proxy Authentication Required 407
proxyAuthenticationRequired407 :: Status
proxyAuthenticationRequired407 = status407
-- | Request Timeout 408
status408 :: Status
status408 = mkStatus 408 "Request Timeout"
-- | Request Timeout 408
requestTimeout408 :: Status
requestTimeout408 = status408
-- | Conflict 409
status409 :: Status
status409 = mkStatus 409 "Conflict"
-- | Conflict 409
conflict409 :: Status
conflict409 = status409
-- | Gone 410
status410 :: Status
status410 = mkStatus 410 "Gone"
-- | Gone 410
gone410 :: Status
gone410 = status410
-- | Length Required 411
status411 :: Status
status411 = mkStatus 411 "Length Required"
-- | Length Required 411
lengthRequired411 :: Status
lengthRequired411 = status411
-- | Precondition Failed 412
status412 :: Status
status412 = mkStatus 412 "Precondition Failed"
-- | Precondition Failed 412
preconditionFailed412 :: Status
preconditionFailed412 = status412
-- | Request Entity Too Large 413
status413 :: Status
status413 = mkStatus 413 "Request Entity Too Large"
-- | Request Entity Too Large 413
requestEntityTooLarge413 :: Status
requestEntityTooLarge413 = status413
-- | Request-URI Too Long 414
status414 :: Status
status414 = mkStatus 414 "Request-URI Too Long"
-- | Request-URI Too Long 414
requestURITooLong414 :: Status
requestURITooLong414 = status414
-- | Unsupported Media Type 415
status415 :: Status
status415 = mkStatus 415 "Unsupported Media Type"
-- | Unsupported Media Type 415
unsupportedMediaType415 :: Status
unsupportedMediaType415 = status415
-- | Requested Range Not Satisfiable 416
status416 :: Status
status416 = mkStatus 416 "Requested Range Not Satisfiable"
-- | Requested Range Not Satisfiable 416
requestedRangeNotSatisfiable416 :: Status
requestedRangeNotSatisfiable416 = status416
-- | Expectation Failed 417
status417 :: Status
status417 = mkStatus 417 "Expectation Failed"
-- | Expectation Failed 417
expectationFailed417 :: Status
expectationFailed417 = status417
-- | I'm a teapot 418
status418 :: Status
status418 = mkStatus 418 "I'm a teapot"
-- | I'm a teapot 418
imATeaPot418 :: Status
imATeaPot418 = status418
-- | Unprocessable Entity 422
-- (<https://tools.ietf.org/html/rfc4918 RFC 4918>)
status422 :: Status
status422 = mkStatus 422 "Unprocessable Entity"
-- | Unprocessable Entity 422
-- (<https://tools.ietf.org/html/rfc4918 RFC 4918>)
unprocessableEntity422 :: Status
unprocessableEntity422 = status422
-- | Precondition Required 428
-- (<https://tools.ietf.org/html/rfc6585 RFC 6585>)
status428 :: Status
status428 = mkStatus 428 "Precondition Required"
-- | Precondition Required 428
-- (<https://tools.ietf.org/html/rfc6585 RFC 6585>)
preconditionRequired428 :: Status
preconditionRequired428 = status428
-- | Too Many Requests 429
-- (<https://tools.ietf.org/html/rfc6585 RFC 6585>)
status429 :: Status
status429 = mkStatus 429 "Too Many Requests"
-- | Too Many Requests 429
-- (<https://tools.ietf.org/html/rfc6585 RFC 6585>)
tooManyRequests429 :: Status
tooManyRequests429 = status429
-- | Request Header Fields Too Large 431
-- (<https://tools.ietf.org/html/rfc6585 RFC 6585>)
status431 :: Status
status431 = mkStatus 431 "Request Header Fields Too Large"
-- | Request Header Fields Too Large 431
-- (<https://tools.ietf.org/html/rfc6585 RFC 6585>)
requestHeaderFieldsTooLarge431 :: Status
requestHeaderFieldsTooLarge431 = status431
-- | Internal Server Error 500
status500 :: Status
status500 = mkStatus 500 "Internal Server Error"
-- | Internal Server Error 500
internalServerError500 :: Status
internalServerError500 = status500
-- | Not Implemented 501
status501 :: Status
status501 = mkStatus 501 "Not Implemented"
-- | Not Implemented 501
notImplemented501 :: Status
notImplemented501 = status501
-- | Bad Gateway 502
status502 :: Status
status502 = mkStatus 502 "Bad Gateway"
-- | Bad Gateway 502
badGateway502 :: Status
badGateway502 = status502
-- | Service Unavailable 503
status503 :: Status
status503 = mkStatus 503 "Service Unavailable"
-- | Service Unavailable 503
serviceUnavailable503 :: Status
serviceUnavailable503 = status503
-- | Gateway Timeout 504
status504 :: Status
status504 = mkStatus 504 "Gateway Timeout"
-- | Gateway Timeout 504
gatewayTimeout504 :: Status
gatewayTimeout504 = status504
-- | HTTP Version Not Supported 505
status505 :: Status
status505 = mkStatus 505 "HTTP Version Not Supported"
-- | HTTP Version Not Supported 505
httpVersionNotSupported505 :: Status
httpVersionNotSupported505 = status505
-- | Network Authentication Required 511
-- (<https://tools.ietf.org/html/rfc6585 RFC 6585>)
status511 :: Status
status511 = mkStatus 511 "Network Authentication Required"
-- | Network Authentication Required 511
-- (<https://tools.ietf.org/html/rfc6585 RFC 6585>)
networkAuthenticationRequired511 :: Status
networkAuthenticationRequired511 = status511
-- | Informational class
statusIsInformational :: Status -> Bool
statusIsInformational (Status {statusCode=code}) = code >= 100 && code < 200
-- | Successful class
statusIsSuccessful :: Status -> Bool
statusIsSuccessful (Status {statusCode=code}) = code >= 200 && code < 300
-- | Redirection class
statusIsRedirection :: Status -> Bool
statusIsRedirection (Status {statusCode=code}) = code >= 300 && code < 400
-- | Client Error class
statusIsClientError :: Status -> Bool
statusIsClientError (Status {statusCode=code}) = code >= 400 && code < 500
-- | Server Error class
statusIsServerError :: Status -> Bool
statusIsServerError (Status {statusCode=code}) = code >= 500 && code < 600
|
phischu/fragnix
|
tests/packages/scotty/Network.HTTP.Types.Status.hs
|
bsd-3-clause
| 13,515
| 0
| 9
| 2,242
| 2,374
| 1,387
| 987
| 364
| 1
|
-- Ensure we don't expose any unfoldings to guarantee quick rebuilds
{-# OPTIONS_GHC -O0 #-}
-- If you want to customise your build you should copy this file from
-- hadrian/src/UserSettings.hs to hadrian/UserSettings.hs and edit your copy.
-- If you don't copy the file your changes will be tracked by git and you can
-- accidentally commit them.
--
-- See doc/user-settings.md for instructions, and src/Flavour.hs for auxiliary
-- functions for manipulating flavours.
-- Please update doc/user-settings.md when committing changes to this file.
module UserSettings (
userFlavours, userPackages, userDefaultFlavour,
verboseCommand, buildProgressColour, successColour, finalStage
) where
import Flavour
import Expression
import {-# SOURCE #-} Settings.Default
-- See doc/user-settings.md for instructions.
-- Please update doc/user-settings.md when committing changes to this file.
-- | Name of the default flavour, i.e the one used when no --flavour=<name>
-- argument is passed to Hadrian.
userDefaultFlavour :: String
userDefaultFlavour = "default"
-- | User-defined build flavours. See 'userFlavour' as an example.
userFlavours :: [Flavour]
userFlavours = [userFlavour] -- Add more build flavours if need be.
-- | This is an example user-defined build flavour. Feel free to modify it and
-- use by passing @--flavour=user@ from the command line.
userFlavour :: Flavour
userFlavour = defaultFlavour { name = "user" } -- Modify other settings here.
-- | Add user-defined packages. Note, this only lets Hadrian know about the
-- existence of a new package; to actually build it you need to create a new
-- build flavour, modifying the list of packages that are built by default.
userPackages :: [Package]
userPackages = []
-- | Set to 'True' to print full command lines during the build process. Note:
-- this is a 'Predicate', hence you can enable verbose output only for certain
-- targets, e.g.: @verboseCommand = package ghcPrim@.
verboseCommand :: Predicate
verboseCommand = do
verbosity <- expr getVerbosity
return $ verbosity >= Loud
-- | Set colour for build progress messages (e.g. executing a build command).
buildProgressColour :: BuildProgressColour
buildProgressColour = mkBuildProgressColour (Dull Magenta)
-- | Set colour for success messages (e.g. a package is built successfully).
successColour :: SuccessColour
successColour = mkSuccessColour (Dull Green)
-- | Stop after building the StageN compiler.
-- For example, setting the 'finalStage' to 'Stage1' will just build the
-- 'Stage1' compiler. Setting it to 'Stage3' will build the 'Stage3'
-- compiler. Setting it to 'Stage0' will mean nothing gets built at all.
finalStage :: Stage
finalStage = Stage2
|
sdiehl/ghc
|
hadrian/src/UserSettings.hs
|
bsd-3-clause
| 2,708
| 0
| 8
| 433
| 208
| 134
| 74
| 25
| 1
|
{-# LANGUAGE UnboxedTuples #-}
f :: x -> (x, x); f x = (x, x)
|
mpickering/hlint-refactor
|
tests/examples/Extensions29.hs
|
bsd-3-clause
| 62
| 0
| 6
| 15
| 32
| 19
| 13
| 2
| 1
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuantifiedConstraints #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
module T16666 where
$([d| class (c => d) => Implies c d
instance (c => d) => Implies c d
|])
|
sdiehl/ghc
|
testsuite/tests/th/T16666.hs
|
bsd-3-clause
| 324
| 0
| 6
| 59
| 21
| 16
| 5
| -1
| -1
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude, BangPatterns, MagicHash #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Bits
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- This module defines bitwise operations for signed and unsigned
-- integers. Instances of the class 'Bits' for the 'Int' and
-- 'Integer' types are available from this module, and instances for
-- explicitly sized integral types are available from the
-- "Data.Int" and "Data.Word" modules.
--
-----------------------------------------------------------------------------
module Data.Bits (
Bits(
(.&.), (.|.), xor,
complement,
shift,
rotate,
zeroBits,
bit,
setBit,
clearBit,
complementBit,
testBit,
bitSizeMaybe,
bitSize,
isSigned,
shiftL, shiftR,
unsafeShiftL, unsafeShiftR,
rotateL, rotateR,
popCount
),
FiniteBits(
finiteBitSize,
countLeadingZeros,
countTrailingZeros
),
bitDefault,
testBitDefault,
popCountDefault,
toIntegralSized
) where
-- Defines the @Bits@ class containing bit-based operations.
-- See library document for details on the semantics of the
-- individual operations.
#include "MachDeps.h"
#ifdef MIN_VERSION_integer_gmp
# define HAVE_INTEGER_GMP1 MIN_VERSION_integer_gmp(1,0,0)
#endif
import Data.Maybe
import GHC.Enum
import GHC.Num
import GHC.Base
import GHC.Real
#if HAVE_INTEGER_GMP1
import GHC.Integer.GMP.Internals (bitInteger, popCountInteger)
#endif
infixl 8 `shift`, `rotate`, `shiftL`, `shiftR`, `rotateL`, `rotateR`
infixl 7 .&.
infixl 6 `xor`
infixl 5 .|.
{-# DEPRECATED bitSize "Use 'bitSizeMaybe' or 'finiteBitSize' instead" #-} -- deprecated in 7.8
-- | The 'Bits' class defines bitwise operations over integral types.
--
-- * Bits are numbered from 0 with bit 0 being the least
-- significant bit.
class Eq a => Bits a where
{-# MINIMAL (.&.), (.|.), xor, complement,
(shift | (shiftL, shiftR)),
(rotate | (rotateL, rotateR)),
bitSize, bitSizeMaybe, isSigned, testBit, bit, popCount #-}
-- | Bitwise \"and\"
(.&.) :: a -> a -> a
-- | Bitwise \"or\"
(.|.) :: a -> a -> a
-- | Bitwise \"xor\"
xor :: a -> a -> a
{-| Reverse all the bits in the argument -}
complement :: a -> a
{-| @'shift' x i@ shifts @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
An instance can define either this unified 'shift' or 'shiftL' and
'shiftR', depending on which is more convenient for the type in
question. -}
shift :: a -> Int -> a
x `shift` i | i<0 = x `shiftR` (-i)
| i>0 = x `shiftL` i
| otherwise = x
{-| @'rotate' x i@ rotates @x@ left by @i@ bits if @i@ is positive,
or right by @-i@ bits otherwise.
For unbounded types like 'Integer', 'rotate' is equivalent to 'shift'.
An instance can define either this unified 'rotate' or 'rotateL' and
'rotateR', depending on which is more convenient for the type in
question. -}
rotate :: a -> Int -> a
x `rotate` i | i<0 = x `rotateR` (-i)
| i>0 = x `rotateL` i
| otherwise = x
{-
-- Rotation can be implemented in terms of two shifts, but care is
-- needed for negative values. This suggested implementation assumes
-- 2's-complement arithmetic. It is commented out because it would
-- require an extra context (Ord a) on the signature of 'rotate'.
x `rotate` i | i<0 && isSigned x && x<0
= let left = i+bitSize x in
((x `shift` i) .&. complement ((-1) `shift` left))
.|. (x `shift` left)
| i<0 = (x `shift` i) .|. (x `shift` (i+bitSize x))
| i==0 = x
| i>0 = (x `shift` i) .|. (x `shift` (i-bitSize x))
-}
-- | 'zeroBits' is the value with all bits unset.
--
-- The following laws ought to hold (for all valid bit indices @/n/@):
--
-- * @'clearBit' 'zeroBits' /n/ == 'zeroBits'@
-- * @'setBit' 'zeroBits' /n/ == 'bit' /n/@
-- * @'testBit' 'zeroBits' /n/ == False@
-- * @'popCount' 'zeroBits' == 0@
--
-- This method uses @'clearBit' ('bit' 0) 0@ as its default
-- implementation (which ought to be equivalent to 'zeroBits' for
-- types which possess a 0th bit).
--
-- @since 4.7.0.0
zeroBits :: a
zeroBits = clearBit (bit 0) 0
-- | @bit /i/@ is a value with the @/i/@th bit set and all other bits clear.
--
-- Can be implemented using `bitDefault' if @a@ is also an
-- instance of 'Num'.
--
-- See also 'zeroBits'.
bit :: Int -> a
-- | @x \`setBit\` i@ is the same as @x .|. bit i@
setBit :: a -> Int -> a
-- | @x \`clearBit\` i@ is the same as @x .&. complement (bit i)@
clearBit :: a -> Int -> a
-- | @x \`complementBit\` i@ is the same as @x \`xor\` bit i@
complementBit :: a -> Int -> a
-- | Return 'True' if the @n@th bit of the argument is 1
--
-- Can be implemented using `testBitDefault' if @a@ is also an
-- instance of 'Num'.
testBit :: a -> Int -> Bool
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. Returns Nothing
for types that do not have a fixed bitsize, like 'Integer'.
@since 4.7.0.0
-}
bitSizeMaybe :: a -> Maybe Int
{-| Return the number of bits in the type of the argument. The actual
value of the argument is ignored. The function 'bitSize' is
undefined for types that do not have a fixed bitsize, like 'Integer'.
-}
bitSize :: a -> Int
{-| Return 'True' if the argument is a signed type. The actual
value of the argument is ignored -}
isSigned :: a -> Bool
{-# INLINE setBit #-}
{-# INLINE clearBit #-}
{-# INLINE complementBit #-}
x `setBit` i = x .|. bit i
x `clearBit` i = x .&. complement (bit i)
x `complementBit` i = x `xor` bit i
{-| Shift the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'shiftR' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftL :: a -> Int -> a
{-# INLINE shiftL #-}
x `shiftL` i = x `shift` i
{-| Shift the argument left by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the 'bitSize'.
Defaults to 'shiftL' unless defined explicitly by an instance.
@since 4.5.0.0 -}
unsafeShiftL :: a -> Int -> a
{-# INLINE unsafeShiftL #-}
x `unsafeShiftL` i = x `shiftL` i
{-| Shift the first argument right by the specified number of bits. The
result is undefined for negative shift amounts and shift amounts
greater or equal to the 'bitSize'.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
An instance can define either this and 'shiftL' or the unified
'shift', depending on which is more convenient for the type in
question. -}
shiftR :: a -> Int -> a
{-# INLINE shiftR #-}
x `shiftR` i = x `shift` (-i)
{-| Shift the first argument right by the specified number of bits, which
must be non-negative an smaller than the number of bits in the type.
Right shifts perform sign extension on signed number types;
i.e. they fill the top bits with 1 if the @x@ is negative
and with 0 otherwise.
Defaults to 'shiftR' unless defined explicitly by an instance.
@since 4.5.0.0 -}
unsafeShiftR :: a -> Int -> a
{-# INLINE unsafeShiftR #-}
x `unsafeShiftR` i = x `shiftR` i
{-| Rotate the argument left by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateR' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateL :: a -> Int -> a
{-# INLINE rotateL #-}
x `rotateL` i = x `rotate` i
{-| Rotate the argument right by the specified number of bits
(which must be non-negative).
An instance can define either this and 'rotateL' or the unified
'rotate', depending on which is more convenient for the type in
question. -}
rotateR :: a -> Int -> a
{-# INLINE rotateR #-}
x `rotateR` i = x `rotate` (-i)
{-| Return the number of set bits in the argument. This number is
known as the population count or the Hamming weight.
Can be implemented using `popCountDefault' if @a@ is also an
instance of 'Num'.
@since 4.5.0.0 -}
popCount :: a -> Int
-- |The 'FiniteBits' class denotes types with a finite, fixed number of bits.
--
-- @since 4.7.0.0
class Bits b => FiniteBits b where
-- | Return the number of bits in the type of the argument.
-- The actual value of the argument is ignored. Moreover, 'finiteBitSize'
-- is total, in contrast to the deprecated 'bitSize' function it replaces.
--
-- @
-- 'finiteBitSize' = 'bitSize'
-- 'bitSizeMaybe' = 'Just' . 'finiteBitSize'
-- @
--
-- @since 4.7.0.0
finiteBitSize :: b -> Int
-- | Count number of zero bits preceding the most significant set bit.
--
-- @
-- 'countLeadingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
-- @
--
-- 'countLeadingZeros' can be used to compute log base 2 via
--
-- @
-- logBase2 x = 'finiteBitSize' x - 1 - 'countLeadingZeros' x
-- @
--
-- Note: The default implementation for this method is intentionally
-- naive. However, the instances provided for the primitive
-- integral types are implemented using CPU specific machine
-- instructions.
--
-- @since 4.8.0.0
countLeadingZeros :: b -> Int
countLeadingZeros x = (w-1) - go (w-1)
where
go i | i < 0 = i -- no bit set
| testBit x i = i
| otherwise = go (i-1)
w = finiteBitSize x
-- | Count number of zero bits following the least significant set bit.
--
-- @
-- 'countTrailingZeros' ('zeroBits' :: a) = finiteBitSize ('zeroBits' :: a)
-- 'countTrailingZeros' . 'negate' = 'countTrailingZeros'
-- @
--
-- The related
-- <http://en.wikipedia.org/wiki/Find_first_set find-first-set operation>
-- can be expressed in terms of 'countTrailingZeros' as follows
--
-- @
-- findFirstSet x = 1 + 'countTrailingZeros' x
-- @
--
-- Note: The default implementation for this method is intentionally
-- naive. However, the instances provided for the primitive
-- integral types are implemented using CPU specific machine
-- instructions.
--
-- @since 4.8.0.0
countTrailingZeros :: b -> Int
countTrailingZeros x = go 0
where
go i | i >= w = i
| testBit x i = i
| otherwise = go (i+1)
w = finiteBitSize x
-- The defaults below are written with lambdas so that e.g.
-- bit = bitDefault
-- is fully applied, so inlining will happen
-- | Default implementation for 'bit'.
--
-- Note that: @bitDefault i = 1 `shiftL` i@
--
-- @since 4.6.0.0
bitDefault :: (Bits a, Num a) => Int -> a
bitDefault = \i -> 1 `shiftL` i
{-# INLINE bitDefault #-}
-- | Default implementation for 'testBit'.
--
-- Note that: @testBitDefault x i = (x .&. bit i) /= 0@
--
-- @since 4.6.0.0
testBitDefault :: (Bits a, Num a) => a -> Int -> Bool
testBitDefault = \x i -> (x .&. bit i) /= 0
{-# INLINE testBitDefault #-}
-- | Default implementation for 'popCount'.
--
-- This implementation is intentionally naive. Instances are expected to provide
-- an optimized implementation for their size.
--
-- @since 4.6.0.0
popCountDefault :: (Bits a, Num a) => a -> Int
popCountDefault = go 0
where
go !c 0 = c
go c w = go (c+1) (w .&. (w - 1)) -- clear the least significant
{-# INLINABLE popCountDefault #-}
-- | Interpret 'Bool' as 1-bit bit-field
--
-- @since 4.7.0.0
instance Bits Bool where
(.&.) = (&&)
(.|.) = (||)
xor = (/=)
complement = not
shift x 0 = x
shift _ _ = False
rotate x _ = x
bit 0 = True
bit _ = False
testBit x 0 = x
testBit _ _ = False
bitSizeMaybe _ = Just 1
bitSize _ = 1
isSigned _ = False
popCount False = 0
popCount True = 1
-- | @since 4.7.0.0
instance FiniteBits Bool where
finiteBitSize _ = 1
countTrailingZeros x = if x then 0 else 1
countLeadingZeros x = if x then 0 else 1
-- | @since 2.01
instance Bits Int where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
zeroBits = 0
bit = bitDefault
testBit = testBitDefault
(I# x#) .&. (I# y#) = I# (x# `andI#` y#)
(I# x#) .|. (I# y#) = I# (x# `orI#` y#)
(I# x#) `xor` (I# y#) = I# (x# `xorI#` y#)
complement (I# x#) = I# (notI# x#)
(I# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = I# (x# `iShiftL#` i#)
| otherwise = I# (x# `iShiftRA#` negateInt# i#)
(I# x#) `shiftL` (I# i#) = I# (x# `iShiftL#` i#)
(I# x#) `unsafeShiftL` (I# i#) = I# (x# `uncheckedIShiftL#` i#)
(I# x#) `shiftR` (I# i#) = I# (x# `iShiftRA#` i#)
(I# x#) `unsafeShiftR` (I# i#) = I# (x# `uncheckedIShiftRA#` i#)
{-# INLINE rotate #-} -- See Note [Constant folding for rotate]
(I# x#) `rotate` (I# i#) =
I# ((x# `uncheckedIShiftL#` i'#) `orI#` (x# `uncheckedIShiftRL#` (wsib -# i'#)))
where
!i'# = i# `andI#` (wsib -# 1#)
!wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -}
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
popCount (I# x#) = I# (word2Int# (popCnt# (int2Word# x#)))
isSigned _ = True
-- | @since 4.6.0.0
instance FiniteBits Int where
finiteBitSize _ = WORD_SIZE_IN_BITS
countLeadingZeros (I# x#) = I# (word2Int# (clz# (int2Word# x#)))
countTrailingZeros (I# x#) = I# (word2Int# (ctz# (int2Word# x#)))
-- | @since 2.01
instance Bits Word where
{-# INLINE shift #-}
{-# INLINE bit #-}
{-# INLINE testBit #-}
(W# x#) .&. (W# y#) = W# (x# `and#` y#)
(W# x#) .|. (W# y#) = W# (x# `or#` y#)
(W# x#) `xor` (W# y#) = W# (x# `xor#` y#)
complement (W# x#) = W# (x# `xor#` mb#)
where !(W# mb#) = maxBound
(W# x#) `shift` (I# i#)
| isTrue# (i# >=# 0#) = W# (x# `shiftL#` i#)
| otherwise = W# (x# `shiftRL#` negateInt# i#)
(W# x#) `shiftL` (I# i#) = W# (x# `shiftL#` i#)
(W# x#) `unsafeShiftL` (I# i#) = W# (x# `uncheckedShiftL#` i#)
(W# x#) `shiftR` (I# i#) = W# (x# `shiftRL#` i#)
(W# x#) `unsafeShiftR` (I# i#) = W# (x# `uncheckedShiftRL#` i#)
(W# x#) `rotate` (I# i#)
| isTrue# (i'# ==# 0#) = W# x#
| otherwise = W# ((x# `uncheckedShiftL#` i'#) `or#` (x# `uncheckedShiftRL#` (wsib -# i'#)))
where
!i'# = i# `andI#` (wsib -# 1#)
!wsib = WORD_SIZE_IN_BITS# {- work around preprocessor problem (??) -}
bitSizeMaybe i = Just (finiteBitSize i)
bitSize i = finiteBitSize i
isSigned _ = False
popCount (W# x#) = I# (word2Int# (popCnt# x#))
bit = bitDefault
testBit = testBitDefault
-- | @since 4.6.0.0
instance FiniteBits Word where
finiteBitSize _ = WORD_SIZE_IN_BITS
countLeadingZeros (W# x#) = I# (word2Int# (clz# x#))
countTrailingZeros (W# x#) = I# (word2Int# (ctz# x#))
-- | @since 2.01
instance Bits Integer where
(.&.) = andInteger
(.|.) = orInteger
xor = xorInteger
complement = complementInteger
shift x i@(I# i#) | i >= 0 = shiftLInteger x i#
| otherwise = shiftRInteger x (negateInt# i#)
testBit x (I# i) = testBitInteger x i
zeroBits = 0
#if HAVE_INTEGER_GMP1
bit (I# i#) = bitInteger i#
popCount x = I# (popCountInteger x)
#else
bit = bitDefault
popCount = popCountDefault
#endif
rotate x i = shift x i -- since an Integer never wraps around
bitSizeMaybe _ = Nothing
bitSize _ = errorWithoutStackTrace "Data.Bits.bitSize(Integer)"
isSigned _ = True
-----------------------------------------------------------------------------
-- | Attempt to convert an 'Integral' type @a@ to an 'Integral' type @b@ using
-- the size of the types as measured by 'Bits' methods.
--
-- A simpler version of this function is:
--
-- > toIntegral :: (Integral a, Integral b) => a -> Maybe b
-- > toIntegral x
-- > | toInteger x == y = Just (fromInteger y)
-- > | otherwise = Nothing
-- > where
-- > y = toInteger x
--
-- This version requires going through 'Integer', which can be inefficient.
-- However, @toIntegralSized@ is optimized to allow GHC to statically determine
-- the relative type sizes (as measured by 'bitSizeMaybe' and 'isSigned') and
-- avoid going through 'Integer' for many types. (The implementation uses
-- 'fromIntegral', which is itself optimized with rules for @base@ types but may
-- go through 'Integer' for some type pairs.)
--
-- @since 4.8.0.0
toIntegralSized :: (Integral a, Integral b, Bits a, Bits b) => a -> Maybe b
toIntegralSized x -- See Note [toIntegralSized optimization]
| maybe True (<= x) yMinBound
, maybe True (x <=) yMaxBound = Just y
| otherwise = Nothing
where
y = fromIntegral x
xWidth = bitSizeMaybe x
yWidth = bitSizeMaybe y
yMinBound
| isBitSubType x y = Nothing
| isSigned x, not (isSigned y) = Just 0
| isSigned x, isSigned y
, Just yW <- yWidth = Just (negate $ bit (yW-1)) -- Assumes sub-type
| otherwise = Nothing
yMaxBound
| isBitSubType x y = Nothing
| isSigned x, not (isSigned y)
, Just xW <- xWidth, Just yW <- yWidth
, xW <= yW+1 = Nothing -- Max bound beyond a's domain
| Just yW <- yWidth = if isSigned y
then Just (bit (yW-1)-1)
else Just (bit yW-1)
| otherwise = Nothing
{-# INLINABLE toIntegralSized #-}
-- | 'True' if the size of @a@ is @<=@ the size of @b@, where size is measured
-- by 'bitSizeMaybe' and 'isSigned'.
isBitSubType :: (Bits a, Bits b) => a -> b -> Bool
isBitSubType x y
-- Reflexive
| xWidth == yWidth, xSigned == ySigned = True
-- Every integer is a subset of 'Integer'
| ySigned, Nothing == yWidth = True
| not xSigned, not ySigned, Nothing == yWidth = True
-- Sub-type relations between fixed-with types
| xSigned == ySigned, Just xW <- xWidth, Just yW <- yWidth = xW <= yW
| not xSigned, ySigned, Just xW <- xWidth, Just yW <- yWidth = xW < yW
| otherwise = False
where
xWidth = bitSizeMaybe x
xSigned = isSigned x
yWidth = bitSizeMaybe y
ySigned = isSigned y
{-# INLINE isBitSubType #-}
{- Note [Constant folding for rotate]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The INLINE on the Int instance of rotate enables it to be constant
folded. For example:
sumU . mapU (`rotate` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
Main.$wfold =
\ (ww_sO7 :: Int#) (ww1_sOb :: Int#) ->
case ww1_sOb of wild_XM {
__DEFAULT -> Main.$wfold (+# ww_sO7 56) (+# wild_XM 1);
10000000 -> ww_sO7
whereas before it was left as a call to $wrotate.
All other Bits instances seem to inline well enough on their
own to enable constant folding; for example 'shift':
sumU . mapU (`shift` 3) . replicateU 10000000 $ (7 :: Int)
goes to:
Main.$wfold =
\ (ww_sOb :: Int#) (ww1_sOf :: Int#) ->
case ww1_sOf of wild_XM {
__DEFAULT -> Main.$wfold (+# ww_sOb 56) (+# wild_XM 1);
10000000 -> ww_sOb
}
-}
-- Note [toIntegralSized optimization]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- The code in 'toIntegralSized' relies on GHC optimizing away statically
-- decidable branches.
--
-- If both integral types are statically known, GHC will be able optimize the
-- code significantly (for @-O1@ and better).
--
-- For instance (as of GHC 7.8.1) the following definitions:
--
-- > w16_to_i32 = toIntegralSized :: Word16 -> Maybe Int32
-- >
-- > i16_to_w16 = toIntegralSized :: Int16 -> Maybe Word16
--
-- are translated into the following (simplified) /GHC Core/ language:
--
-- > w16_to_i32 = \x -> Just (case x of _ { W16# x# -> I32# (word2Int# x#) })
-- >
-- > i16_to_w16 = \x -> case eta of _
-- > { I16# b1 -> case tagToEnum# (<=# 0 b1) of _
-- > { False -> Nothing
-- > ; True -> Just (W16# (narrow16Word# (int2Word# b1)))
-- > }
-- > }
|
snoyberg/ghc
|
libraries/base/Data/Bits.hs
|
bsd-3-clause
| 21,758
| 0
| 14
| 6,340
| 3,651
| 2,037
| 1,614
| 254
| 2
|
module Opaleye.SQLite.Column (module Opaleye.SQLite.Column,
Column,
Nullable,
unsafeCoerce,
unsafeCoerceColumn) where
import Opaleye.SQLite.Internal.Column (Column, Nullable, unsafeCoerce, unsafeCoerceColumn)
import qualified Opaleye.SQLite.Internal.Column as C
import qualified Opaleye.SQLite.Internal.HaskellDB.PrimQuery as HPQ
import qualified Opaleye.SQLite.PGTypes as T
import Prelude hiding (null)
-- | A NULL of any type
null :: Column (Nullable a)
null = C.Column (HPQ.ConstExpr HPQ.NullLit)
isNull :: Column (Nullable a) -> Column T.PGBool
isNull = C.unOp HPQ.OpIsNull
-- | If the @Column (Nullable a)@ is NULL then return the @Column b@
-- otherwise map the underlying @Column a@ using the provided
-- function.
--
-- The Opaleye equivalent of the 'Data.Maybe.maybe' function.
matchNullable :: Column b -> (Column a -> Column b) -> Column (Nullable a)
-> Column b
matchNullable replacement f x = C.unsafeIfThenElse (isNull x) replacement
(f (unsafeCoerceColumn x))
-- | If the @Column (Nullable a)@ is NULL then return the provided
-- @Column a@ otherwise return the underlying @Column a@.
--
-- The Opaleye equivalent of the 'Data.Maybe.fromMaybe' function
fromNullable :: Column a -> Column (Nullable a) -> Column a
fromNullable = flip matchNullable id
-- | The Opaleye equivalent of 'Data.Maybe.Just'
toNullable :: Column a -> Column (Nullable a)
toNullable = unsafeCoerceColumn
-- | If the argument is 'Data.Maybe.Nothing' return NULL otherwise return the
-- provided value coerced to a nullable type.
maybeToNullable :: Maybe (Column a) -> Column (Nullable a)
maybeToNullable = maybe null toNullable
-- | Cast a column to any other type. This is safe for some conversions such as uuid to text.
unsafeCast :: String -> Column a -> Column b
unsafeCast = C.unsafeCast
|
alanz/haskell-opaleye
|
opaleye-sqlite/src/Opaleye/SQLite/Column.hs
|
bsd-3-clause
| 1,966
| 0
| 10
| 444
| 382
| 213
| 169
| 26
| 1
|
import StackTest
import System.Directory (setPermissions, emptyPermissions, createDirectory)
main :: IO ()
main = do
createDirectory "unreachabledir"
setPermissions "unreachabledir" $ emptyPermissions
stack ["init"]
|
AndrewRademacher/stack
|
test/integration/tests/skip-unreachable-dirs/Main.hs
|
bsd-3-clause
| 230
| 0
| 8
| 36
| 60
| 30
| 30
| 7
| 1
|
module D200 where
import A200
|
oldmanmike/ghc
|
testsuite/tests/driver/D200.hs
|
bsd-3-clause
| 30
| 0
| 3
| 5
| 7
| 5
| 2
| 2
| 0
|
{-# LANGUAGE GADTs #-}
module T3638 where
data T a where TInt :: T Int
foo :: T Int -> Int
{-# NOINLINE [1] foo #-}
foo TInt = 0
{-# RULES "foo" forall x. foo x = case x of { TInt -> 0 } #-}
|
urbanslug/ghc
|
testsuite/tests/gadt/T3638.hs
|
bsd-3-clause
| 196
| 0
| 6
| 52
| 40
| 24
| 16
| 7
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Attoparsec.Text
import Data.Bool (bool)
import Data.Either (fromRight)
import Data.Foldable (find, traverse_)
import Data.Matrix (Matrix)
import qualified Data.Matrix as M
import Data.Text (Text)
import qualified Data.Text.IO as T
data BingoCard = BC (Matrix Bool) (Matrix Int)
type Game = ([Int], [BingoCard])
len :: Int
len = 5
gameP :: Text -> Game
gameP = fromRight (error "Bad parse") . parseOnly ((,) <$> (nums <* "\n") <*> many1' card)
where
nums = decimal `sepBy1'` ","
card = bc . M.fromLists <$> count len (count len (skipSpace *> decimal <* skipSpace))
bc = BC (M.matrix len len $ const False)
indices :: [Int]
indices = [1 .. len]
pairs :: [(Int, Int)]
pairs = [ (i, j) | i <- indices, j <- indices ]
won :: BingoCard -> Bool
won (BC marks _) = rows || cols || diags
where
rows = or [ and (i `M.getRow` marks) | i <- indices ]
cols = or [ and (i `M.getCol` marks) | i <- indices ]
diags = and (M.getDiag marks) || and (M.getDiag $ M.transpose marks)
mark :: Int -> BingoCard -> BingoCard
mark n (BC marks card) = BC m' card
where
m' = maybe marks (flip (M.setElem True) marks) $ find ((n ==) . (card M.!)) pairs
score :: Int -> BingoCard -> Int
score n (BC mask card) = n * sum unmarked
where unmarked = zipWith (\m c -> bool c 0 m) (M.toList mask) (M.toList card)
part1 :: Game -> Maybe Int
part1 (_ , []) = Nothing
part1 ([], _ ) = Nothing
part1 (n : ns, bcs) =
let bcs' = fmap (mark n) bcs
in case find won bcs' of
Nothing -> part1 (ns, bcs')
Just bc -> Just $ score n bc
part2 :: Game -> Maybe Int
part2 (_ , []) = Nothing
part2 ([], _ ) = Nothing
part2 (n : ns, [bc]) | won bc' = Just $ score n bc'
| otherwise = part2 (ns, [bc'])
where bc' = mark n bc
part2 (n : ns, bcs) = part2 (ns, filter (not . won) $ mark n <$> bcs)
main :: IO ()
main = do
input <- gameP <$> T.readFile "input.txt"
traverse_ (print . ($ input)) [part1, part2]
|
genos/online_problems
|
advent_of_code_2021/day04/Main.hs
|
mit
| 2,125
| 0
| 13
| 588
| 985
| 529
| 456
| 53
| 2
|
module ZebraPuzzle (Resident(..), Solution(..), solve) where
data Resident = Englishman | Spaniard | Ukrainian | Norwegian | Japanese
deriving (Eq, Show)
data Solution = Solution { waterDrinker :: Resident
, zebraOwner :: Resident
} deriving (Eq, Show)
solve :: Solution
solve = error "You need to implement this function."
|
exercism/xhaskell
|
exercises/practice/zebra-puzzle/src/ZebraPuzzle.hs
|
mit
| 380
| 0
| 8
| 105
| 98
| 60
| 38
| 8
| 1
|
{-# LANGUAGE Arrows #-}
{-# LANGUAGE TemplateHaskell #-}
import Text.XML.HXT.Core
import Text.XML.HXT.Arrow.XmlArrow (ArrowXml)
import Text.HandsomeSoup
import Control.Arrow
import Text.Read (readMaybe)
import Control.Monad
import Control.Lens
import Data.Maybe (listToMaybe, fromMaybe)
import Data.List (sortBy, filter, intercalate)
import Control.Concurrent.Async (mapConcurrently)
import System.Environment (getArgs)
import System.IO.Unsafe (unsafeInterleaveIO)
import Data.Time.LocalTime (LocalTime)
import Data.Time.Format (parseTime)
import System.Locale (defaultTimeLocale)
data Album = Album {
_artist :: String,
_title :: String,
_score :: Maybe Float,
_pubDate :: Maybe LocalTime,
_url :: String
}
makeLenses ''Album
instance Show Album where
show a = scoreStr ++ " " ++ a^.artist ++ " - " ++ a^.title ++ " " ++ a^.url
where
scoreStr = show $ fromMaybe 0 (a^.score)
album = proc li -> do
artist <- (css "h1" //> getText) -< li
title <- (css "h2" //> getText) -< li
url <- (css "a" ! "href") -< li
pubDate <- (css "h4" //> getText) -< li
returnA -< Album artist title Nothing (parsePFDate pubDate) $ "http://pitchfork.com" ++ url
albumScore :: ArrowXml a => a XmlTree (Maybe Float)
albumScore = css "span.score" //> getText >>> arr readMaybe
parsePFDate :: String -> Maybe LocalTime
parsePFDate = parseTime locale "%b %e, %Y"
where locale = defaultTimeLocale
maybeFirstTag arrow = listToMaybe `liftM` runX arrow
nextPageUrl = css "span.next-container .next" ! "href"
downloadAllAlbums :: IO [Album]
downloadAllAlbums =
downloadAllAlbums' Nothing
where
downloadAllAlbums' currentPage = do
(albums, nextPage) <- downloadAlbums currentPage
rest <- unsafeInterleaveIO $
case nextPage of
Nothing -> return []
_ -> downloadAllAlbums' nextPage
return $ albums ++ rest
downloadAlbums :: Maybe String -> IO ([Album], Maybe String)
downloadAlbums pageUrl = do
print $ "downloading " ++ url
albums <- runX $ index_doc >>> album_li_tags >>> album
nextPage <- maybeFirstTag $ index_doc >>> nextPageUrl
return (albums, liftM2 (++) (return "http://pitchfork.com") nextPage)
where
url = fromMaybe "http://pitchfork.com/reviews/albums/1/" pageUrl
index_doc = fromUrl url
album_li_tags = css "ul.object-grid ul li"
downloadScore :: Album -> IO Album
downloadScore album = do
maybeScore <- return . join =<< maybeFirstTag (album_doc >>> albumScore)
return $ setScore maybeScore album
where
album_doc = fromUrl $ album^.url
setScore :: Maybe Float -> Album -> Album
setScore = set score
main = do
-- download the albums
(liftM2 takeAfter) dateArgIO downloadAllAlbums
-- then fetch the scores for each album concurrently using async
>>= mapConcurrently downloadScore
-- then filter, sort and display the albums
>>= (filter (scoreGT 7) >>> sortBy compareScore >>> display)
where
takeAfter :: LocalTime -> [Album] -> [Album]
takeAfter dt = takeWhile (after dt)
after :: LocalTime -> Album -> Bool
after dt a = (a^.pubDate >= Just dt)
dateArgIO :: IO LocalTime
dateArgIO = do
maybeDateStr <- listToMaybe `liftM` getArgs
case maybeDateStr >>= parsePFDate of
Just dt -> return dt
Nothing -> (fail "Date not given")
compareScore :: Album -> Album -> Ordering
compareScore b a = compare (a^.score) (b^.score)
scoreGT :: Float -> Album -> Bool
scoreGT n a = a^.score > Just n
display :: [Album] -> IO ()
display = mapM_ print
|
ericmoritz/pitchfork-reviews
|
src/PitchforkReviews.hs
|
mit
| 3,584
| 1
| 15
| 762
| 1,115
| 577
| 538
| -1
| -1
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module Cenary.Utils.EvmAsm where
--------------------------------------------------------------------------------
import Data.Functor
import Data.Functor.Identity (Identity)
import Data.Monoid
import qualified Data.Text as T
import Text.Parsec as P
import Text.Parsec.Language
import Text.Parsec.String
import qualified Text.Parsec.Token as Tok
import Text.ParserCombinators.Parsec.Number
import Text.Printf
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
lexer :: Tok.TokenParser ()
lexer = Tok.makeTokenParser emptyDef
integer :: ParsecT String () Identity Integer
integer = Tok.integer lexer
whiteSpace :: ParsecT String () Identity ()
whiteSpace = Tok.whiteSpace lexer
newtype ByteCode = ByteCode { unByteCode :: T.Text }
deriving (Monoid)
asm :: [T.Text] -> T.Text
asm ix = unByteCode $ asm' ix
asm' :: [T.Text] -> ByteCode
asm' [] = ByteCode ""
asm' (input:xs) =
case parse instrParser "<instruction_set>" (T.unpack input) of
Left err -> error (show err)
Right code' -> code' <> asm' xs
toByteCode :: String -> Integer
toByteCode "STOP" = 0x00
toByteCode "ADD" = 0x01
toByteCode "MUL" = 0x02
toByteCode "SUB" = 0x03
toByteCode "DIV" = 0x04
toByteCode "POP" = 0x50
toByteCode "MLOAD" = 0x51
toByteCode "MSTORE" = 0x52
toByteCode "MSTORE8" = 0x53
toByteCode "JUMP" = 0x56
toByteCode "JUMPI" = 0x57
toByteCode "SWAP1" = 0x90
toByteCode "SWAP2" = 0x91
toByteCode "DUP1" = 0x80
toByteCode "JUMPDEST" = 0x5b
toByteCode "PC" = 0x58
toByteCode "LOG0" = 0xA0
toByteCode "LOG1" = 0xA1
toByteCode "LOG2" = 0xA2
toByteCode other = error $ "Instruction " <> other <> " is not recognised."
toByteCode1 :: String -> Integer -> [Integer]
toByteCode1 "PUSH" val = [0x7f, val]
toByteCode1 other _ = error $ "Instruction " <> other <> " is not recognised."
instruction :: Parser ByteCode
instruction = do
instr <- many1 alphaNum
arg <- optionMaybe (space >> hexadecimal)
let result = case arg of
Just val ->
let [instr', val'] = toByteCode1 instr val in
ByteCode (T.pack (printf "%02x" instr')) <> ByteCode (T.pack (printf "%064x" val'))
Nothing -> ByteCode $ T.pack $ printf "%02x" $ toByteCode instr
_ <- optionMaybe (spaces >> char '#' >> spaces)
return result
instrParser :: Parser ByteCode
instrParser = try instruction
P.<|> try (char '#' >> spaces $> ByteCode "")
P.<|> (whiteSpace $> ByteCode "")
|
yigitozkavci/ivy
|
src/Cenary/Utils/EvmAsm.hs
|
mit
| 2,707
| 0
| 20
| 539
| 782
| 405
| 377
| 69
| 2
|
{-# LANGUAGE UnicodeSyntax #-}
module Main (main) where
import Options.Applicative
import Prelude.Unicode
-- my modules
import M3U.Read (fromFile)
import M3U.Write (toOrderedMarkdown, toYAML)
data Options = Options { filePath ∷ String
, outputFormat ∷ String
}
optParser ∷ Parser Options
optParser = Options
<$> argument str (metavar "FILE")
<*> strOption (short 'f'
<> long "format"
<> metavar "FORMAT")
realMain ∷ Options → IO ()
realMain opts = do m3u ← fromFile $ filePath opts
case m3u of
Left e → print $ "Error parsing the M3U file: " ++ show e
Right m → putStrLn (case (outputFormat opts) of
"markdown" → toOrderedMarkdown m
"yaml" → toYAML m
_ → "Error: invalid outputFormat")
description ∷ String
description = "Convert an M3U playlist to another format"
main ∷ IO ()
main = realMain =<< (execParser $ info (helper <*> optParser)
(fullDesc <> progDesc description
<> header "m3u-converter"))
|
siddharthist/m3u-convert
|
src/Main.hs
|
mit
| 1,353
| 0
| 15
| 569
| 297
| 153
| 144
| 28
| 4
|
module GameState where
import Data.Array.IArray
import GOL
stepIntervalChange = 50.0
data GameState = GameState {
world :: World,
mode :: GOLState,
timeSinceLastUpdate :: Float,
lastIteration :: Integer,
window :: WindowConfig,
stepInterval :: Float
}
data WindowConfig = WindowConfig {
winWidth :: Int,
winHeight :: Int
}
data GOLState = Running | Paused
evolveState s = s { world = evolve $ world s }
setIterationTime t s = s { lastIteration = t }
resetTimeDelta s = s { timeSinceLastUpdate = 0 }
increaseTimeDelta t s = s { timeSinceLastUpdate = timeSinceLastUpdate s + t }
increaseStepInterval s = s { stepInterval = stepInterval s + stepIntervalChange }
decreaseStepInterval s =
if stepInterval s == 0.0
then s
else s { stepInterval = stepInterval s - stepIntervalChange }
pause :: GameState -> GameState
pause s = s { mode = Paused }
play :: GameState -> GameState
play s = s { mode = Running }
paused :: GameState -> Bool
paused s = case mode s of
Paused -> True
_ -> False
stepSimulation :: GameState -> Integer -> (Bool, GameState)
stepSimulation state time =
if paused state
then (False, setIterationTime time state)
else let deltaMs = psToMs $ time - lastIteration state
st = setIterationTime time $ increaseTimeDelta deltaMs state
in if timeSinceLastUpdate st >= stepInterval state
then (True, resetTimeDelta $ evolveState st)
else (False, st)
where psToMs ps = fromIntegral ps / 1000000000
setCellAt :: GameState -> Int -> Int -> Bool -> GameState
setCellAt state x y alive = let worldGrid = world state
newWorld = worldGrid { grid = grid worldGrid // [((x, y), alive)] }
in state { world = newWorld }
|
Lateks/gol
|
src/GameState.hs
|
mit
| 1,891
| 0
| 14
| 554
| 559
| 306
| 253
| -1
| -1
|
module Out.Other
( writeSonHier
, writeCCs
, writeLanguageTreeN
, writeSoundChange
) where
import ClassyPrelude
import Data.Language
import Data.Phoneme
import Data.Soundchange
import Out.Lexicon
-- write the sonority hierarchy
writeSonHier :: [Phoneme] -> [[Phoneme]] -> Text
writeSonHier vows cns = "\n\nSonority hierarchy: " ++ "\n/" ++ cListv ++ "/\n/" ++ intercalate "/\n/" cListc ++ "/\n" where
fListv = map writePhonemeIPA vows
cListv = intercalate "/, /" fListv
fListc = map (map writePhonemeIPA) (reverse cns)
cListc = map (intercalate "/, /") fListc
writeCCs :: [[Phoneme]] -> [[Phoneme]] -> Text
writeCCs onsets codas = "\n\nValid onsets: " ++ "\n/" ++ intercalate "/\n/" oList ++ "/" ++ "\n\nValid codas: " ++ "\n/" ++ intercalate "/\n/" cList ++ "/\n" where
oList = map (concatMap writePhonemeIPA) onsets
cList = map (concatMap writePhonemeIPA) codas
-- write language branches into Newick format
writeLanguageTreeN :: LanguageBranch -> Text
writeLanguageTreeN tree = writeLanguageBranchN tree ++ ";"
writeLanguageBranchN :: LanguageBranch -> Text
writeLanguageBranchN (LanguageBranch lang [] n) = fst (getNameMod lang) ++ snd (getNameMod lang) ++ getName lang -- ++ ":" ++ toString (fromIntegral n / 10)
writeLanguageBranchN (LanguageBranch lang branches n) = branchStuff ++ fst (getNameMod lang) ++ snd (getNameMod lang) ++ getName lang where -- ++ ":" ++ toString (fromIntegral n / 10) where
branchStuff = "(" ++ intercalate "," (map writeLanguageBranchN branches) ++ ")"
-- Write sound changes
writeSoundChange :: [Rule] -> Text
writeSoundChange rs = "\n<br>\nPhonological Changes: " ++ "\n<br>\n" ++ intercalate "\n<br>\n" (map tshow rs) ++ "\n"
|
Brightgalrs/con-lang-gen
|
src/Out/Other.hs
|
mit
| 1,687
| 0
| 11
| 263
| 478
| 248
| 230
| 28
| 1
|
module ArgumentParser where
-- This application has two flags -p and -h
data Flag = P | H
deriving Show
data Arguments = Arguments
{flag :: Maybe Flag,
parser :: Maybe String,
function :: Maybe String
} | None
deriving Show
stringToFlag :: String -> Maybe Flag
stringToFlag str
| str == "-p" = Just P
| str == "-h" = Just H
| otherwise = Nothing
stringToParser :: String -> Maybe String
stringToParser str
| length str > 0 = Just str
| otherwise = Nothing
stringToFunction :: String -> Maybe String
stringToFunction str
| length str > 0 = Just str
| otherwise = Nothing
extractArguments :: [String]-> Arguments
--When just one argument is provided, so it's either a -h flag or the function
extractArguments (args:[]) =
case stringToFlag args of
flag@(Just H) -> Arguments flag Nothing Nothing
Nothing -> Arguments Nothing Nothing (stringToFunction args)
_ -> None
extractArguments (flag:parser:function:[]) = Arguments (stringToFlag flag) (stringToParser parser) (stringToFunction function)
extractArguments _ = None
|
iostreamer-X/FuncShell
|
src/ArgumentParser.hs
|
mit
| 1,144
| 0
| 10
| 291
| 350
| 174
| 176
| 30
| 3
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE RecordWildCards #-}
module Data.Core.Graph
( Graph, Node, NodeSet, Edge(..)
, empty, fromEdges, fromAdj, isConsistent
, nodes, edges, children, parents, hasEdge
, edgeCount
, hull, rhull, hullFold, hullFoldM, rhullFold
, addEdge, addEdges, removeEdge, removeEdges
, addNode, removeNode, solitaireNodes
, edgesAdj
)
where
import Data.Core.Graph.NodeManager hiding (isConsistent, nodes)
import Data.Core.Graph.PureCore
|
factisresearch/graph-core
|
src/Data/Core/Graph.hs
|
mit
| 596
| 0
| 5
| 89
| 123
| 85
| 38
| 17
| 0
|
module L.CommandLine where
import L.Compiler hiding (Parser)
import Options.Applicative
addInfo :: String -> Parser a -> ParserInfo a
addInfo desc p =
info (helper <*> p)
(fullDesc <> progDesc desc <>
(header "The L Programming Language"))
osParser :: Parser String
osParser = strOption (
long "os" <>
metavar "operating system"
<> help "darwin|linux")
outputDirParser :: Parser String
outputDirParser = strOption (
long "outputDir" <>
short 'o' <>
metavar "outputDir" <>
help "the directory to write output files")
compileOptionsParser :: Parser CompilationOptions
compileOptionsParser = compOpts <$> optional osParser <*> optional outputDirParser
-- TODO: for many files later, use:
-- some (argument str (metavar "..."))
lStarFileParser :: Parser FilePath
lStarFileParser = argument str $ metavar "'.L* file'"
|
joshcough/L5-Haskell
|
src/L/CommandLine.hs
|
mit
| 852
| 0
| 10
| 154
| 214
| 107
| 107
| 23
| 1
|
{-# LANGUAGE OverloadedStrings #-}
import Frequency (frequency)
import Prelude hiding (unlines)
import Data.Text (Text, unlines)
import Criterion.Main (bench, bgroup, defaultMain, nf)
import Criterion.Types (Benchmark)
import Control.Concurrent (getNumCapabilities)
import Data.List (nub, sort, replicate)
odeAnDieFreude :: Text
odeAnDieFreude = unlines
[ "Freude schöner Götterfunken"
, "Tochter aus Elysium,"
, "Wir betreten feuertrunken,"
, "Himmlische, dein Heiligtum!"
, "Deine Zauber binden wieder"
, "Was die Mode streng geteilt;"
, "Alle Menschen werden Brüder,"
, "Wo dein sanfter Flügel weilt."
]
makeBench :: [Text] -> Int -> Benchmark
makeBench anthems workers = bench name $ nf (`frequency` anthems) workers
where name = show workers ++ " workers"
benchGroup :: Int -> [Int] -> Int -> Benchmark
benchGroup processors numWorkers numAnthems =
bgroup (show numAnthems ++ " anthems on " ++ show processors ++ " threads") (makeBench anthems <$> numWorkers)
where anthems = replicate numAnthems odeAnDieFreude
main :: IO ()
main = do threads <- getNumCapabilities
let numsOfWorkers = nub $ sort [1..threads]
numsOfAnthems = [500]
defaultMain $ benchGroup threads numsOfWorkers <$> numsOfAnthems
|
exercism/xhaskell
|
exercises/practice/parallel-letter-frequency/bench/Benchmark.hs
|
mit
| 1,408
| 0
| 12
| 370
| 329
| 181
| 148
| 30
| 1
|
-- | Internal helpers that provide strict atomic MutVar access.
--
-- These functions allow us to avoid the overhead of MVar as long
-- as we can factor the impure sections of code out in such a way
-- that the pure metric calculations can be executed without requiring
-- access to multiple MutVars at a time.
module Data.Metrics.Internal (
updateRef,
applyWithRef,
updateAndApplyToRef,
MV
) where
import Control.Monad.Primitive
import Data.Primitive.MutVar
-- | Perform a strict update on a MutVar. Pretty much identical to the strict variant of atomicModifyIORef.
updateRef :: PrimMonad m => MV m a -> (a -> a) -> m ()
updateRef r f = do
b <- atomicModifyMutVar r (\x -> let (a, b) = (f x, ()) in (a, a `seq` b))
b `seq` return b
-- | Strictly apply a function on a MutVar while blocking other access to it.
--
-- I really think this is probably not implemented correctly in terms of being excessively strict.
applyWithRef :: PrimMonad m => MV m a -> (a -> b) -> m b
applyWithRef r f = do
b <- atomicModifyMutVar r (\x -> let app = f x in let (a, b) = (x, app) in (a, a `seq` b))
b `seq` return b
-- | A function which combines the previous two, updating a value atomically
-- and then returning some value calculated with the update in a single step.
updateAndApplyToRef :: PrimMonad m => MV m a -> (a -> a) -> (a -> b) -> m b
updateAndApplyToRef r fa fb = do
b <- atomicModifyMutVar r $ \x ->
let appA = fa x in
let appB = fb appA in
let (a, b) = (appA, appB) in
(a, a `seq` b)
b `seq` return b
-- | MutVar (PrimState m) is a little verbose.
type MV m = MutVar (PrimState m)
|
graydon/metrics
|
src/Data/Metrics/Internal.hs
|
mit
| 1,620
| 0
| 18
| 352
| 462
| 248
| 214
| 24
| 1
|
module Data.Word
( Word(..)
, Morpheme(..)
, Meaning(..)
, Syllable(..)
, ConsCluster
) where
import ClassyPrelude hiding (Word)
import Data.List (elemIndex)
import Data.Phoneme
import Data.Inflection
-- Words have a tree-like structure where leaves are morphemes
data Word = Word { getMeaning :: Meaning, getLeft :: Morpheme, getRight :: Morpheme }
-- Syllabic morpheme (Sequence of syllables)
| MorphemeS { getMeaning :: Meaning, getMorphType :: MorphType, getSylls :: [Syllable] }
-- Phonemic morpheme (Unstructured sequence of phonemes)
| MorphemeP { getMeaning :: Meaning, getMorphType :: MorphType, getPhonemes :: [Phoneme] }
-- Consonantal morpheme (Disconnected sequences of consonants, ie. Semitic root)
| MorphemeC { getMeaning :: Meaning, getMorphType :: MorphType, getRadicals :: [[Phoneme]] }
-- Vocallic morpheme (Disconnected sequences of (typically) vowels, ie. Patterns/transfixes)
| MorphemeV { getMeaning :: Meaning, getMorphType :: MorphType, getPatterns :: [Syllable] } deriving (Eq, Show)
-- Clitics attach themselves to previous/next Words
-- They should probably be represented as a MorphType
-- | Proclitic Meaning [Syllable]
-- | Enclitic Meaning [Syllable] deriving (Eq, Show)
-- Morphemes can be either syllabized or unsyllablized
-- Need syllabized Morphemes to carry tone and stress
-- Need raw phonemes for unsyllabizable inflectional morphemes and stuff
type Morpheme = Word
-- Meanings are basically just English-language "senses"
-- Eventually Verbs will need to carry their Theta roles
data Meaning = Meaning { getLC :: LexCat, getStr :: Text, getAllExpress :: GramCatExpress }
| RootMeaning { getLC :: LexCat, getStr :: Text }
| InflMeaning { getLC :: LexCat, getOrder :: Int, getAllExpress :: GramCatExpress }
| DeriMeaning { getLC1 :: LexCat, getLC2 :: LexCat, getStr :: Text }
| CompMeaning { getLC :: LexCat, getLC1 :: LexCat, getLC2 :: LexCat, getStr :: Text }
deriving (Eq, Show, Read)
data Syllable = Syllable
{ getOnset :: [Phoneme]
, getNucleus :: Phoneme
, getCoda :: [Phoneme]
, getTone :: Tone
, getStress :: Stress
} deriving (Eq, Ord, Show)
type ConsCluster = [Phoneme]
|
Brightgalrs/con-lang-gen
|
src/Data/Word.hs
|
mit
| 2,370
| 0
| 10
| 569
| 436
| 284
| 152
| 30
| 0
|
-- Problems/Problem023.hs
module Problems.Problem023 (p23) where
import Data.IntSet (toList, fromList)
import Helpers.Numbers
main = print p23
p23 :: Int
p23 = sum [1..20161] - (sum $ nub' $ abundantSums) where
nub' = toList . fromList
abundantSums :: [Int]
abundantSums = [(x+y) | x <- ab, y <- ab, y >= x, (x+y) < 20162] where
ab = abundants
abundants :: [Int]
abundants = filter (\x -> (sum $ divisors x) > x) [12..20149]
|
Sgoettschkes/learning
|
haskell/ProjectEuler/src/Problems/Problem023.hs
|
mit
| 438
| 0
| 11
| 86
| 196
| 110
| 86
| 12
| 1
|
-- Copyright (c) Microsoft. All rights reserved.
-- Licensed under the MIT license. See LICENSE file in the project root for full license information.
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module Tests.Codegen
( verifyCodegen
, verifyCppCodegen
, verifyApplyCodegen
, verifyCsCodegen
) where
import System.FilePath
import Control.Monad
import Data.Monoid
import Data.Maybe
import Prelude
import Data.Algorithm.DiffContext
import Data.Text.Lazy (Text, unpack)
import qualified Data.ByteString.Char8 as BS
import Text.PrettyPrint (render, text)
import Test.Tasty
import Test.Tasty.Golden.Advanced
import Language.Bond.Codegen.Templates
import Language.Bond.Codegen.TypeMapping
import Language.Bond.Syntax.Types (Bond(..), Import, Declaration)
import Options
import IO
type Template = MappingContext -> String -> [Import] -> [Declaration] -> (String, Text)
verifyCppCodegen :: FilePath -> TestTree
verifyCppCodegen = verifyCodegen ["c++"]
verifyCsCodegen :: FilePath -> TestTree
verifyCsCodegen = verifyCodegen ["c#"]
verifyCodegen :: [String] -> FilePath -> TestTree
verifyCodegen args baseName =
testGroup baseName $
verifyFiles (processOptions args) baseName
verifyApplyCodegen :: [String] -> FilePath -> TestTree
verifyApplyCodegen args baseName =
testGroup baseName $
map (verifyFile options baseName cppTypeMapping "apply") templates
where
options = processOptions args
templates =
[ apply_h protocols (apply_attribute options)
, apply_cpp protocols
]
protocols =
[ Protocol "bond::CompactBinaryReader<bond::InputBuffer>"
"bond::CompactBinaryWriter<bond::OutputBuffer>"
, Protocol "bond::FastBinaryReader<bond::InputBuffer>"
"bond::FastBinaryWriter<bond::OutputBuffer>"
, Protocol "bond::SimpleBinaryReader<bond::InputBuffer>"
"bond::SimpleBinaryWriter<bond::OutputBuffer>"
]
verifyFiles :: Options -> FilePath -> [TestTree]
verifyFiles options baseName =
map (verify (typeMapping options) "") (templates options)
<>
extra options
where
verify = verifyFile options baseName
fieldMapping Cs {..} = if readonly_properties
then ReadOnlyProperties
else if fields
then PublicFields
else Properties
typeMapping Cpp {..} = maybe cppTypeMapping cppCustomAllocTypeMapping allocator
typeMapping Cs {} = csTypeMapping
templates Cpp {..} =
[ reflection_h
, types_cpp
, types_h header enum_header allocator
]
templates Cs {..} =
[ types_cs Class $ fieldMapping options
]
extra Cs {} =
[ testGroup "collection interfaces" $
map (verify csCollectionInterfacesTypeMapping "collection-interfaces") (templates options)
]
extra Cpp {..} =
[ testGroup "custom allocator" $
map (verify (cppCustomAllocTypeMapping "arena") "allocator")
(templates $ options { allocator = Just "arena" })
| isNothing allocator
]
verifyFile :: Options -> FilePath -> TypeMapping -> FilePath -> Template -> TestTree
verifyFile options baseName typeMapping subfolder template =
goldenTest suffix readGolden codegen cmp updateGolden
where
(suffix, _) = template (MappingContext typeMapping [] [] []) "" [] []
golden = "tests" </> "generated" </> subfolder </> baseName ++ suffix
readGolden = BS.readFile golden
updateGolden = BS.writeFile golden
codegen = do
aliasMapping <- parseAliasMappings $ using options
namespaceMapping <- parseNamespaceMappings $ namespace options
(Bond imports namespaces declarations) <- parseBondFile [] $ "tests" </> "schema" </> baseName <.> "bond"
let mappingContext = MappingContext typeMapping aliasMapping namespaceMapping namespaces
let (_, code) = template mappingContext baseName imports declarations
return $ BS.pack $ unpack code
cmp x y = return $ if x == y then Nothing else Just $ diff x y
diff x y = render $ prettyContextDiff
(text golden)
(text "test output")
(text . BS.unpack)
(getContextDiff 3 (BS.lines x) (BS.lines y))
|
alfpark/bond
|
compiler/tests/Tests/Codegen.hs
|
mit
| 4,370
| 0
| 15
| 1,057
| 1,047
| 552
| 495
| 94
| 6
|
-----------------------------------------------------------------------------
-- |
-- Module : Language.Krill.TypeChecker.Contractivity
-- Description : Check that recursive types are contractive
-- Maintainer : coskuacay@gmail.com
-- Stability : experimental
--
-- A (recursive) type is said to be contractive if its unfolding corresponds
-- to a (possibly infinite) tree, or equivalently, if there is a finite
-- unfolding that exposes a structural construct at the root of the type.
--
-- Since we use equirecursive types, we require all types to be contractive
-- for soundness.
-----------------------------------------------------------------------------
module Language.Krill.TypeChecker.Contractivity
( contractiveFile
, contractiveModule
) where
import Control.Arrow ((&&&))
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State
import qualified Data.Map.Strict as Map
import Text.PrettyPrint
import Text.PrettyPrint.HughesPJClass (Pretty (..), prettyShow)
import Language.Krill.Parser.Location (Located (..), SrcSpan)
import Language.Krill.Monad.Compiler
import Language.Krill.AST
type TypeDefs = Map.Map (Constructor SrcSpan) (TypeDef SrcSpan)
type Seen = Map.Map (Constructor SrcSpan) Bool
type Result = CompilerT (ReaderT TypeDefs (State Seen))
contractiveFile :: File SrcSpan -> Compiler ()
contractiveFile (File _ modules) = runAll_ (map contractiveModule modules)
contractiveModule :: Module SrcSpan -> Compiler ()
contractiveModule (Module _ ident typedefs _) = do
let m = runCompilerT (runAll_ $ map checkTypeDefError typedefs)
case evalState (runReaderT m typedefMap) Map.empty of
Left e -> throwError e
Right () -> return ()
where
conId (TypeDef _ con _) = con
typedefMap = Map.fromList $ map (conId &&& id) typedefs
checkTypeDefError :: TypeDef SrcSpan -> Result ()
checkTypeDefError def@(TypeDef annot _ _) = do
contractive <- checkTypeDef def
unless contractive $ compilerError annot $
text "Type definition is not contractive:" $$ pPrint def
checkTypeDef :: TypeDef SrcSpan -> Result Bool
checkTypeDef (TypeDef _ con t) = do
seen <- gets (Map.lookup con)
case seen of
Nothing -> do
modify (Map.insert con False)
r <- checkType t
modify (Map.insert con r)
return r
Just r -> return r
checkType :: Type SrcSpan -> Result Bool
checkType (TVar annot con) = do
def <- asks (Map.lookup con)
case def of
Nothing -> compilerError annot $
text "Undefined constructor:" <+> pPrint con
Just typedef -> checkTypeDef typedef
checkType (TUnit {}) = return True
checkType (TProduct {}) = return True
checkType (TArrow {}) = return True
checkType (TInternal {}) = return True
checkType (TExternal {}) = return True
checkType (TIntersect _ a b) = liftM and (runAll [checkType a, checkType b])
checkType (TUnion _ a b) = liftM and (runAll [checkType a, checkType b])
|
cacay/language-sill
|
Language/Krill/TypeChecker/Contractivity.hs
|
mit
| 2,918
| 0
| 15
| 503
| 851
| 433
| 418
| 55
| 2
|
{-# OPTIONS_GHC -Wall #-}
module Main where
import Test.Framework
import GHC.IO.Encoding
import qualified Tests.Old
import qualified Tests.Readers.LaTeX
import qualified Tests.Readers.Markdown
import qualified Tests.Writers.LaTeX
import qualified Tests.Writers.HTML
import qualified Tests.Writers.Native
import qualified Tests.Writers.Markdown
import qualified Tests.Writers.Plain
import qualified Tests.Shared
import qualified Tests.Walk
import Text.Pandoc.Shared (inDirectory)
import System.Environment (getArgs)
tests :: [Test]
tests = [ testGroup "Old" Tests.Old.tests
, testGroup "Shared" Tests.Shared.tests
, testGroup "Walk" Tests.Walk.tests
, testGroup "Writers"
[ testGroup "Native" Tests.Writers.Native.tests
, testGroup "LaTeX" Tests.Writers.LaTeX.tests
, testGroup "HTML" Tests.Writers.HTML.tests
, testGroup "Markdown" Tests.Writers.Markdown.tests
, testGroup "Plain" Tests.Writers.Plain.tests
]
, testGroup "Readers"
[ testGroup "LaTeX" Tests.Readers.LaTeX.tests
, testGroup "Markdown" Tests.Readers.Markdown.tests
]
]
main :: IO ()
main = do
setLocaleEncoding utf8
args <- getArgs
inDirectory "tests" $ defaultMainWithArgs tests args
|
timtylin/scholdoc
|
tests/test-scholdoc.hs
|
gpl-2.0
| 1,289
| 0
| 9
| 259
| 293
| 173
| 120
| 34
| 1
|
-- | Young tableaux and similar gadgets.
-- See e.g. William Fulton: Young Tableaux, with Applications to
-- Representation theory and Geometry (CUP 1997).
--
-- The convention is that we use
-- the English notation, and we store the tableaux as lists of the rows.
--
-- That is, the following standard tableau of shape [5,4,1]
--
-- > 1 3 4 6 7
-- > 2 5 8 10
-- > 9
--
-- is encoded conveniently as
--
-- > [ [ 1 , 3 , 4 , 6 , 7 ]
-- > , [ 2 , 5 , 8 ,10 ]
-- > , [ 9 ]
-- > ]
--
module Math.Combinat.Tableaux where
import Data.List
import Math.Combinat.Helper
import Math.Combinat.Numbers (factorial,binomial)
import Math.Combinat.Partitions
--------------------------------------------------------------------------------
-- * Basic stuff
type Tableau a = [[a]]
_shape :: Tableau a -> [Int]
_shape t = map length t
shape :: Tableau a -> Partition
shape t = toPartition (_shape t)
dualTableau :: Tableau a -> Tableau a
dualTableau = transpose
content :: Tableau a -> [a]
content = concat
-- | An element @(i,j)@ of the resulting tableau (which has shape of the
-- given partition) means that the vertical part of the hook has length @i@,
-- and the horizontal part @j@. The /hook length/ is thus @i+j-1@.
--
-- Example:
--
-- > > mapM_ print $ hooks $ toPartition [5,4,1]
-- > [(3,5),(2,4),(2,3),(2,2),(1,1)]
-- > [(2,4),(1,3),(1,2),(1,1)]
-- > [(1,1)]
--
hooks :: Partition -> Tableau (Int,Int)
hooks part = zipWith f p [1..] where
p = fromPartition part
q = _dualPartition p
f l i = zipWith (\x y -> (x-i+1,y)) q [l,l-1..1]
hookLengths :: Partition -> Tableau Int
hookLengths part = (map . map) (\(i,j) -> i+j-1) (hooks part)
--------------------------------------------------------------------------------
-- * Row and column words
rowWord :: Tableau a -> [a]
rowWord = concat . reverse
rowWordToTableau :: Ord a => [a] -> Tableau a
rowWordToTableau xs = reverse rows where
rows = break xs
break [] = [[]]
break [x] = [[x]]
break (x:xs@(y:_)) = if x>y
then [x] : break xs
else let (h:t) = break xs in (x:h):t
columnWord :: Tableau a -> [a]
columnWord = rowWord . transpose
columnWordToTableau :: Ord a => [a] -> Tableau a
columnWordToTableau = transpose . rowWordToTableau
--------------------------------------------------------------------------------
-- * Standard Young tableaux
-- | Standard Young tableaux of a given shape.
-- Adapted from John Stembridge,
-- <http://www.math.lsa.umich.edu/~jrs/software/SFexamples/tableaux>.
standardYoungTableaux :: Partition -> [Tableau Int]
standardYoungTableaux shape' = map rev $ tableaux shape where
shape = fromPartition shape'
rev = reverse . map reverse
tableaux :: [Int] -> [Tableau Int]
tableaux p =
case p of
[] -> [[]]
[n] -> [[[n,n-1..1]]]
_ -> worker (n,k) 0 [] p
where
n = sum p
k = length p
worker :: (Int,Int) -> Int -> [Int] -> [Int] -> [Tableau Int]
worker _ _ _ [] = []
worker nk i ls (x:rs) = case rs of
(y:_) -> if x==y
then worker nk (i+1) (x:ls) rs
else worker2 nk i ls x rs
[] -> worker2 nk i ls x rs
worker2 :: (Int,Int) -> Int -> [Int] -> Int -> [Int] -> [Tableau Int]
worker2 nk@(n,k) i ls x rs = new ++ worker nk (i+1) (x:ls) rs where
old = if x>1
then tableaux $ reverse ls ++ (x-1) : rs
else map ([]:) $ tableaux $ reverse ls ++ rs
a = k-1-i
new = {- debug ( i , a , head old , f a (head old) ) $ -}
map (f a) old
f :: Int -> Tableau Int -> Tableau Int
f _ [] = []
f 0 (t:ts) = (n:t) : f (-1) ts
f j (t:ts) = t : f (j-1) ts
-- | hook-length formula
countStandardYoungTableaux :: Partition -> Integer
countStandardYoungTableaux part = {- debug (hookLengths part) $ -}
factorial n `div` h where
h = product $ map fromIntegral $ concat $ hookLengths part
n = weight part
--------------------------------------------------------------------------------
-- * Semistandard Young tableaux
-- | Semistandard Young tableaux of given shape, \"naive\" algorithm
semiStandardYoungTableaux :: Int -> Partition -> [Tableau Int]
semiStandardYoungTableaux n part = worker (repeat 0) shape where
shape = fromPartition part
worker _ [] = [[]]
worker prevRow (s:ss)
= [ (r:rs) | r <- row n s 1 prevRow, rs <- worker (map (+1) r) ss ]
-- weekly increasing lists of length @len@, pointwise at least @xs@,
-- maximum value @n@, minimum value @prev@.
row :: Int -> Int -> Int -> [Int] -> [[Int]]
row _ 0 _ _ = [[]]
row n len prev (x:xs) = [ (a:as) | a <- [max x prev..n] , as <- row n (len-1) a xs ]
-- | Stanley's hook formula (cf. Fulton page 55)
countSemiStandardYoungTableaux :: Int -> Partition -> Integer
countSemiStandardYoungTableaux n shape = k `div` h where
h = product $ map fromIntegral $ concat $ hookLengths shape
k = product [ fromIntegral (n+j-i) | (i,j) <- elements shape ]
--------------------------------------------------------------------------------
|
garykrige/project_euler
|
Haskell/Math/Combinat/Tableaux.hs
|
gpl-2.0
| 5,031
| 0
| 15
| 1,140
| 1,631
| 885
| 746
| 84
| 9
|
{-
Copyright (C) 2006-8 John MacFarlane <jgm@berkeley.edu>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Writers.LaTeX
Copyright : Copyright (C) 2006-8 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' format into LaTeX.
-}
module Text.Pandoc.Writers.LaTeX ( writeLaTeX ) where
import Text.Pandoc.Definition
import Text.Pandoc.Shared
import Text.Pandoc.Templates
import Text.Printf ( printf )
import Data.List ( (\\), isSuffixOf, isPrefixOf, intersperse )
import Data.Char ( toLower )
import Control.Monad.State
import Text.PrettyPrint.HughesPJ hiding ( Str )
data WriterState =
WriterState { stInNote :: Bool -- @True@ if we're in a note
, stOLLevel :: Int -- level of ordered list nesting
, stOptions :: WriterOptions -- writer options, so they don't have to be parameter
, stVerbInNote :: Bool -- true if document has verbatim text in note
, stEnumerate :: Bool -- true if document needs fancy enumerated lists
, stTable :: Bool -- true if document has a table
, stStrikeout :: Bool -- true if document has strikeout
, stSubscript :: Bool -- true if document has subscript
, stUrl :: Bool -- true if document has visible URL link
, stGraphics :: Bool -- true if document contains images
, stLHS :: Bool -- true if document has literate haskell code
, stBook :: Bool -- true if document uses book or memoir class
}
-- | Convert Pandoc to LaTeX.
writeLaTeX :: WriterOptions -> Pandoc -> String
writeLaTeX options document =
evalState (pandocToLaTeX options document) $
WriterState { stInNote = False, stOLLevel = 1, stOptions = options,
stVerbInNote = False, stEnumerate = False,
stTable = False, stStrikeout = False, stSubscript = False,
stUrl = False, stGraphics = False,
stLHS = False, stBook = False }
pandocToLaTeX :: WriterOptions -> Pandoc -> State WriterState String
pandocToLaTeX options (Pandoc (Meta title authors date) blocks) = do
let template = writerTemplate options
let usesBookClass x = "\\documentclass" `isPrefixOf` x &&
("{memoir}" `isSuffixOf` x || "{book}" `isSuffixOf` x ||
"{report}" `isSuffixOf` x)
when (any usesBookClass (lines template)) $
modify $ \s -> s{stBook = True}
titletext <- liftM render $ inlineListToLaTeX title
authorsText <- mapM (liftM render . inlineListToLaTeX) authors
dateText <- liftM render $ inlineListToLaTeX date
body <- blockListToLaTeX blocks
let main = render body
st <- get
let context = writerVariables options ++
[ ("toc", if writerTableOfContents options then "yes" else "")
, ("body", main)
, ("title", titletext)
, ("date", dateText) ] ++
[ ("author", a) | a <- authorsText ] ++
[ ("xetex", "yes") | writerXeTeX options ] ++
[ ("verbatim-in-note", "yes") | stVerbInNote st ] ++
[ ("fancy-enums", "yes") | stEnumerate st ] ++
[ ("tables", "yes") | stTable st ] ++
[ ("strikeout", "yes") | stStrikeout st ] ++
[ ("subscript", "yes") | stSubscript st ] ++
[ ("url", "yes") | stUrl st ] ++
[ ("numbersections", "yes") | writerNumberSections options ] ++
[ ("lhs", "yes") | stLHS st ] ++
[ ("graphics", "yes") | stGraphics st ]
return $ if writerStandalone options
then renderTemplate context template
else main
-- escape things as needed for LaTeX
stringToLaTeX :: String -> String
stringToLaTeX = escapeStringUsing latexEscapes
where latexEscapes = backslashEscapes "{}$%&_#" ++
[ ('^', "\\^{}")
, ('\\', "\\textbackslash{}")
, ('~', "\\ensuremath{\\sim}")
, ('|', "\\textbar{}")
, ('<', "\\textless{}")
, ('>', "\\textgreater{}")
, ('\160', "~")
]
-- | Puts contents into LaTeX command.
inCmd :: String -> Doc -> Doc
inCmd cmd contents = char '\\' <> text cmd <> braces contents
-- | Remove all code elements from list of inline elements
-- (because it's illegal to have verbatim inside some command arguments)
deVerb :: [Inline] -> [Inline]
deVerb [] = []
deVerb ((Code str):rest) =
(TeX $ "\\texttt{" ++ stringToLaTeX str ++ "}"):(deVerb rest)
deVerb (other:rest) = other:(deVerb rest)
-- | Convert Pandoc block element to LaTeX.
blockToLaTeX :: Block -- ^ Block to convert
-> State WriterState Doc
blockToLaTeX Null = return empty
blockToLaTeX (Plain lst) = do
st <- get
let opts = stOptions st
wrapTeXIfNeeded opts True inlineListToLaTeX lst
blockToLaTeX (Para lst) = do
st <- get
let opts = stOptions st
result <- wrapTeXIfNeeded opts True inlineListToLaTeX lst
return $ result <> char '\n'
blockToLaTeX (BlockQuote lst) = do
contents <- blockListToLaTeX lst
return $ text "\\begin{quote}" $$ contents $$ text "\\end{quote}"
blockToLaTeX (CodeBlock (_,classes,_) str) = do
st <- get
env <- if writerLiterateHaskell (stOptions st) && "haskell" `elem` classes &&
"literate" `elem` classes
then do
modify $ \s -> s{ stLHS = True }
return "code"
else if stInNote st
then do
modify $ \s -> s{ stVerbInNote = True }
return "Verbatim"
else return "verbatim"
return $ text ("\\begin{" ++ env ++ "}\n") <> text str <>
text ("\n\\end{" ++ env ++ "}")
blockToLaTeX (RawHtml _) = return empty
blockToLaTeX (BulletList lst) = do
items <- mapM listItemToLaTeX lst
return $ text "\\begin{itemize}" $$ vcat items $$ text "\\end{itemize}"
blockToLaTeX (OrderedList (start, numstyle, numdelim) lst) = do
st <- get
let oldlevel = stOLLevel st
put $ st {stOLLevel = oldlevel + 1}
items <- mapM listItemToLaTeX lst
modify (\s -> s {stOLLevel = oldlevel})
exemplar <- if numstyle /= DefaultStyle || numdelim /= DefaultDelim
then do
modify $ \s -> s{ stEnumerate = True }
return $ char '[' <>
text (head (orderedListMarkers (1, numstyle,
numdelim))) <> char ']'
else return empty
let resetcounter = if start /= 1 && oldlevel <= 4
then text $ "\\setcounter{enum" ++
map toLower (toRomanNumeral oldlevel) ++
"}{" ++ show (start - 1) ++ "}"
else empty
return $ text "\\begin{enumerate}" <> exemplar $$ resetcounter $$
vcat items $$ text "\\end{enumerate}"
blockToLaTeX (DefinitionList lst) = do
items <- mapM defListItemToLaTeX lst
return $ text "\\begin{description}" $$ vcat items $$
text "\\end{description}"
blockToLaTeX HorizontalRule = return $ text $
"\\begin{center}\\rule{3in}{0.4pt}\\end{center}\n"
blockToLaTeX (Header level lst) = do
let lst' = deVerb lst
txt <- inlineListToLaTeX lst'
let noNote (Note _) = Str ""
noNote x = x
let lstNoNotes = processWith noNote lst'
-- footnotes in sections don't work unless you specify an optional
-- argument: \section[mysec]{mysec\footnote{blah}}
optional <- if lstNoNotes == lst'
then return empty
else do
res <- inlineListToLaTeX lstNoNotes
return $ char '[' <> res <> char ']'
let stuffing = optional <> char '{' <> txt <> char '}'
book <- liftM stBook get
return $ case (book, level) of
(True, 1) -> text "\\chapter" <> stuffing <> char '\n'
(True, 2) -> text "\\section" <> stuffing <> char '\n'
(True, 3) -> text "\\subsection" <> stuffing <> char '\n'
(True, 4) -> text "\\subsubsection" <> stuffing <> char '\n'
(False, 1) -> text "\\section" <> stuffing <> char '\n'
(False, 2) -> text "\\subsection" <> stuffing <> char '\n'
(False, 3) -> text "\\subsubsection" <> stuffing <> char '\n'
_ -> txt <> char '\n'
blockToLaTeX (Table caption aligns widths heads rows) = do
headers <- if all null heads
then return empty
else liftM ($$ text "\\hline") $ tableRowToLaTeX heads
captionText <- inlineListToLaTeX caption
rows' <- mapM tableRowToLaTeX rows
let colDescriptors = concat $ zipWith toColDescriptor widths aligns
let tableBody = text ("\\begin{tabular}{" ++ colDescriptors ++ "}") $$
headers $$ vcat rows' $$ text "\\end{tabular}"
let centered txt = text "\\begin{center}" $$ txt $$ text "\\end{center}"
modify $ \s -> s{ stTable = True }
return $ if isEmpty captionText
then centered tableBody <> char '\n'
else text "\\begin{table}[h]" $$ centered tableBody $$
inCmd "caption" captionText $$ text "\\end{table}\n"
toColDescriptor :: Double -> Alignment -> String
toColDescriptor 0 align =
case align of
AlignLeft -> "l"
AlignRight -> "r"
AlignCenter -> "c"
AlignDefault -> "l"
toColDescriptor width align = ">{\\PBS" ++
(case align of
AlignLeft -> "\\raggedright"
AlignRight -> "\\raggedleft"
AlignCenter -> "\\centering"
AlignDefault -> "\\raggedright") ++
"\\hspace{0pt}}p{" ++ printf "%.2f" width ++
"\\columnwidth}"
blockListToLaTeX :: [Block] -> State WriterState Doc
blockListToLaTeX lst = mapM blockToLaTeX lst >>= return . vcat
tableRowToLaTeX :: [[Block]] -> State WriterState Doc
tableRowToLaTeX cols = mapM blockListToLaTeX cols >>=
return . ($$ text "\\\\") . foldl (\row item -> row $$
(if isEmpty row then text "" else text " & ") <> item) empty
listItemToLaTeX :: [Block] -> State WriterState Doc
listItemToLaTeX lst = blockListToLaTeX lst >>= return . (text "\\item" $$) .
(nest 2)
defListItemToLaTeX :: ([Inline], [[Block]]) -> State WriterState Doc
defListItemToLaTeX (term, defs) = do
term' <- inlineListToLaTeX $ deVerb term
def' <- liftM (vcat . intersperse (text "")) $ mapM blockListToLaTeX defs
return $ text "\\item[" <> term' <> text "]" $$ def'
-- | Convert list of inline elements to LaTeX.
inlineListToLaTeX :: [Inline] -- ^ Inlines to convert
-> State WriterState Doc
inlineListToLaTeX lst = mapM inlineToLaTeX lst >>= return . hcat
isQuoted :: Inline -> Bool
isQuoted (Quoted _ _) = True
isQuoted Apostrophe = True
isQuoted _ = False
-- | Convert inline element to LaTeX
inlineToLaTeX :: Inline -- ^ Inline to convert
-> State WriterState Doc
inlineToLaTeX (Emph lst) =
inlineListToLaTeX (deVerb lst) >>= return . inCmd "emph"
inlineToLaTeX (Strong lst) =
inlineListToLaTeX (deVerb lst) >>= return . inCmd "textbf"
inlineToLaTeX (Strikeout lst) = do
contents <- inlineListToLaTeX $ deVerb lst
modify $ \s -> s{ stStrikeout = True }
return $ inCmd "sout" contents
inlineToLaTeX (Superscript lst) =
inlineListToLaTeX (deVerb lst) >>= return . inCmd "textsuperscript"
inlineToLaTeX (Subscript lst) = do
modify $ \s -> s{ stSubscript = True }
contents <- inlineListToLaTeX $ deVerb lst
-- oddly, latex includes \textsuperscript but not \textsubscript
-- so we have to define it (using a different name so as not to conflict with memoir class):
return $ inCmd "textsubscr" contents
inlineToLaTeX (SmallCaps lst) =
inlineListToLaTeX (deVerb lst) >>= return . inCmd "textsc"
inlineToLaTeX (Cite _ lst) =
inlineListToLaTeX lst
inlineToLaTeX (Code str) = do
st <- get
when (stInNote st) $ modify $ \s -> s{ stVerbInNote = True }
let chr = ((enumFromTo '!' '~') \\ str) !! 0
return $ text $ "\\verb" ++ [chr] ++ str ++ [chr]
inlineToLaTeX (Quoted SingleQuote lst) = do
contents <- inlineListToLaTeX lst
let s1 = if (not (null lst)) && (isQuoted (head lst))
then text "\\,"
else empty
let s2 = if (not (null lst)) && (isQuoted (last lst))
then text "\\,"
else empty
return $ char '`' <> s1 <> contents <> s2 <> char '\''
inlineToLaTeX (Quoted DoubleQuote lst) = do
contents <- inlineListToLaTeX lst
let s1 = if (not (null lst)) && (isQuoted (head lst))
then text "\\,"
else empty
let s2 = if (not (null lst)) && (isQuoted (last lst))
then text "\\,"
else empty
return $ text "``" <> s1 <> contents <> s2 <> text "''"
inlineToLaTeX Apostrophe = return $ char '\''
inlineToLaTeX EmDash = return $ text "---"
inlineToLaTeX EnDash = return $ text "--"
inlineToLaTeX Ellipses = return $ text "\\ldots{}"
inlineToLaTeX (Str str) = return $ text $ stringToLaTeX str
inlineToLaTeX (Math InlineMath str) = return $ char '$' <> text str <> char '$'
inlineToLaTeX (Math DisplayMath str) = return $ text "\\[" <> text str <> text "\\]"
inlineToLaTeX (TeX str) = return $ text str
inlineToLaTeX (HtmlInline _) = return empty
inlineToLaTeX (LineBreak) = return $ text "\\\\"
inlineToLaTeX Space = return $ char ' '
inlineToLaTeX (Link txt (src, _)) =
case txt of
[Code x] | x == src -> -- autolink
do modify $ \s -> s{ stUrl = True }
return $ text $ "\\url{" ++ x ++ "}"
_ -> do contents <- inlineListToLaTeX $ deVerb txt
return $ text ("\\href{" ++ src ++ "}{") <> contents <>
char '}'
inlineToLaTeX (Image _ (source, _)) = do
modify $ \s -> s{ stGraphics = True }
return $ text $ "\\includegraphics{" ++ source ++ "}"
inlineToLaTeX (Note contents) = do
st <- get
put (st {stInNote = True})
contents' <- blockListToLaTeX contents
modify (\s -> s {stInNote = False})
let rawnote = stripTrailingNewlines $ render contents'
-- note: a \n before } is needed when note ends with a Verbatim environment
let optNewline = "\\end{Verbatim}" `isSuffixOf` rawnote
return $ text "\\footnote{" <>
text rawnote <> (if optNewline then char '\n' else empty) <> char '}'
|
kowey/pandoc-old
|
src/Text/Pandoc/Writers/LaTeX.hs
|
gpl-2.0
| 15,320
| 0
| 25
| 4,407
| 4,284
| 2,171
| 2,113
| 286
| 16
|
module Compiler.Goto_While where
import qualified While as W
import qualified Goto as G
compile :: G.Program -> W.Program
compile p =
let c = G.free_register p ; h = c+1
in W.Seq (W.Inc h) $ W.While h $ body c h $ zip [0..] p
body c h ips = case ips of
[] -> W.Skip
(i,s) : rest ->
W.IfZ c (statement c h (i,s))
$ W.Seq (W.Dec c) $ body c h rest
statement c h (i,s) = case s of
G.Inc r -> W.Seq (W.Inc r) $ assign c (i+1)
G.Dec r -> W.Seq (W.Dec r) $ assign c (i+1)
G.Stop -> W.Dec h
G.Goto l -> assign c l
G.GotoZ r l -> W.IfZ r (assign c l) (assign c (i+1))
assign c i = foldr W.Seq W.Skip $ replicate i $ W.Inc c
|
marcellussiegburg/autotool
|
collection/src/Compiler/Goto_While.hs
|
gpl-2.0
| 655
| 0
| 13
| 177
| 412
| 206
| 206
| 19
| 5
|
module Print where
import Parse
import Data.List
import Data.String.Utils
escapeField :: String->String
showField :: Field->String
showEntry :: Entry->String
escapeField v = concat ["{",strip v,"}"]
showField (k,v) = concat ["\n ",k," = ",escapeField v]
showEntry (Entry name xs)
= "@" ++ doctype ++ " {" ++ name ++ "," ++ fStr ++ "\n}"
where fStr = intercalate "," (map showField fs)
([(_,doctype)],fs) = partition (\(k,_)->k=="doctype") xs
instance Show Entry where
show = showEntry
|
zaxtax/hsbib
|
Print.hs
|
gpl-2.0
| 532
| 0
| 10
| 119
| 217
| 120
| 97
| 15
| 1
|
module ATP.Util.Debug
( err
, assert
, impossible
, error
, trace
, trace'
, traceIn
, traceOut
, tracef, tracef'
, tracef2, tracef2'
, tracef3, tracef3'
, tracef4, tracef4'
, tracef5, tracef5'
, tracef6, tracef6'
)
where
import Prelude hiding (error)
import qualified ATP.Util.Print as PP
import ATP.Util.Print (Print, pPrint, (<+>))
import qualified Codec.Binary.UTF8.String as UString
import qualified Control.Exception as Exn
import qualified Debug.Trace as Trace
import qualified GHC.Err
traceP :: Bool
traceP = False
error :: PP.Doc -> a
error = GHC.Err.error . UString.encodeString . PP.render
assert :: Bool -> a -> a
assert = Exn.assert
trace :: String -> a -> a
trace s x = if traceP then Trace.trace (UString.encodeString s) x else x
impossible :: a
impossible = Exn.assert False undefined
trace' :: String -> PP.Doc -> a -> a
trace' name doc x =
let msg = UString.encodeString $ PP.render (PP.text name <+> doc) in
if traceP then Trace.trace msg x else x
traceIn :: String -> PP.Doc -> a -> a
traceIn name doc x =
let msg = UString.encodeString $ PP.render (PP.text (name ++ "<--") <+> doc) in
Trace.trace msg x
traceOut :: String -> PP.Doc -> a -> a
traceOut name doc x =
let msg = UString.encodeString $ PP.render (PP.text (name ++ "-->") <+> doc) in
Trace.trace msg x
err :: a
err = GHC.Err.error "Impossible"
tracef :: (Print a1, Print a2) => String -> (a1 -> a2) -> (a1 -> a2)
tracef name f x =
trace' (name ++ " <--") (pPrint x) $
let res = f x in
trace' (name ++" -->") (pPrint res) res
tracef' :: (Print a1) => String -> (a1 -> a2) -> (a1 -> a2)
tracef' name f x =
trace' (name ++ " <--") (pPrint x) $
f x
tracef2 :: (Print a1, Print a2, Print a3) => String -> (a1 -> a2 -> a3) -> (a1 -> a2 -> a3)
tracef2 name f x y =
trace' (name ++ " <--") (pPrint (x, y)) $
let res = f x y in
trace' (name ++" -->") (pPrint res) res
tracef2' :: (Print a1, Print a2) => String -> (a1 -> a2 -> a3) -> (a1 -> a2 -> a3)
tracef2' name f x y =
trace' (name ++ " <--") (pPrint (x, y)) $
f x y
tracef3 :: (Print a1, Print a2, Print a3, Print a4) => String -> (a1 -> a2 -> a3 -> a4) -> (a1 -> a2 -> a3 -> a4)
tracef3 name f x y =
trace' (name ++ " <--") (pPrint (x, y)) $
let res = f x y in
trace' (name ++" -->") (pPrint res) res
tracef3' :: (Print a1, Print a2, Print a3) => String -> (a1 -> a2 -> a3 -> a4) -> (a1 -> a2 -> a3 -> a4)
tracef3' name f x y =
trace' (name ++ " <--") (pPrint (x, y)) $
f x y
tracef4 :: (Print a1, Print a2, Print a3, Print a4, Print a5) => String -> (a1 -> a2 -> a3 -> a4 -> a5) -> (a1 -> a2 -> a3 -> a4 -> a5)
tracef4 name f x1 x2 x3 x4 =
trace' (name ++ " <--") (pPrint (x1, x2, x3, x4)) $
let res = f x1 x2 x3 x4 in
trace' (name ++" -->") (pPrint res) res
tracef4' :: (Print a1, Print a2, Print a3, Print a4) => String -> (a1 -> a2 -> a3 -> a4 -> a5) -> (a1 -> a2 -> a3 -> a4 -> a5)
tracef4' name f x1 x2 x3 x4 =
trace' (name ++ " <--") (pPrint (x1, x2, x3, x4)) $
f x1 x2 x3 x4
tracef5 :: (Print a1, Print a2, Print a3, Print a4, Print a5, Print a6) => String -> (a1 -> a2 -> a3 -> a4 -> a5 -> a6) -> (a1 -> a2 -> a3 -> a4 -> a5 -> a6)
tracef5 name f x1 x2 x3 x4 x5 =
trace' (name ++ " <--") (pPrint (x1, x2, x3, x4, x5)) $
let res = f x1 x2 x3 x4 x5 in
trace' (name ++" -->") (pPrint res) res
tracef5' :: (Print a1, Print a2, Print a3, Print a4, Print a5) => String -> (a1 -> a2 -> a3 -> a4 -> a5 -> a6) -> (a1 -> a2 -> a3 -> a4 -> a5 -> a6)
tracef5' name f x1 x2 x3 x4 x5 =
trace' (name ++ " <--") (pPrint (x1, x2, x3, x4, x5)) $
f x1 x2 x3 x4 x5
tracef6 :: (Print a1, Print a2, Print a3, Print a4, Print a5, Print a6, Print a7) => String -> (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7) -> (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7)
tracef6 name f x1 x2 x3 x4 x5 x6 =
trace' (name ++ " <--") (pPrint (x1, x2, x3, x4, x5, x6)) $
let res = f x1 x2 x3 x4 x5 x6 in
trace' (name ++" -->") (pPrint res) res
tracef6' :: (Print a1, Print a2, Print a3, Print a4, Print a5, Print a6) => String -> (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7) -> (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7)
tracef6' name f x1 x2 x3 x4 x5 x6 =
trace' (name ++ " <--") (pPrint (x1, x2, x3, x4, x5, x6)) $
f x1 x2 x3 x4 x5 x6
|
andre-artus/handbook-of-practical-logic-and-automated-reasoning-haskell
|
src/ATP/Util/Debug.hs
|
gpl-3.0
| 4,259
| 0
| 15
| 1,058
| 2,260
| 1,196
| 1,064
| 100
| 2
|
{- ============================================================================
| Copyright 2011 Matthew D. Steele <mdsteele@alum.mit.edu> |
| |
| This file is part of Fallback. |
| |
| Fallback 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. |
| |
| Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
{-# LANGUAGE GADTs #-}
module Fallback.View.Town
(TownAction(..), newTownView)
where
import Control.Applicative ((<$), (<$>))
import Control.Monad (guard, when)
import qualified Data.Set as Set
import Fallback.Constants (sidebarWidth, talkRadius)
import Fallback.Control.Script (Script, mapEffect)
import qualified Fallback.Data.Grid as Grid
import Fallback.Data.Color (Tint(Tint))
import Fallback.Data.Point
import Fallback.Draw
import Fallback.Event
import Fallback.Scenario.Triggers
(getAreaExits, getMonsterScript, scenarioTriggers)
import Fallback.State.Action (Targeting(TargetingAlly))
import Fallback.State.Area
import Fallback.State.Camera (camTopleft)
import Fallback.State.Creature
(CreaturePose(..), animOffset, ciStand, monstScript)
import Fallback.State.Doodad (DoodadHeight(..), paintDoodads)
import Fallback.State.Party
import Fallback.State.Resources (Resources, rsrcCharacterImages)
import Fallback.State.Simple (CharacterNumber)
import Fallback.State.Terrain
import Fallback.State.Town
import Fallback.Utility (flip3, maybeM)
import Fallback.View.Abilities
import Fallback.View.Base
import Fallback.View.Camera
import Fallback.View.Hover
import Fallback.View.Inventory
import Fallback.View.Sidebar
import Fallback.View.Upgrade
-------------------------------------------------------------------------------
data TownAction = TownSidebar SidebarAction
| TownAbilities AbilitiesAction
| TownInventory InventoryAction
| TownShopping ShoppingAction
| TownUpgrade UpgradeAction
--- | TownInteract (GridEntry Device)
| TownMove Direction
| TownScript (Script TownEffect ())
--- | TownTalk (GridEntry Monster)
| TownTargetPosition Position
| TownTargetCharacter CharacterNumber
| TownCancelTargeting
newTownView :: (MonadDraw m) => Resources -> m (View TownState TownAction)
newTownView resources = newCursorView resources $ \cursorSink -> do
let mapRect _ (w, h) = Rect sidebarWidth 0 (w - sidebarWidth) h
let sidebarRect _ (_, h) = Rect 0 0 sidebarWidth h
let abilitiesFn ts =
case tsPhase ts of
ChooseAbilityPhase ->
Just AbilitiesState { abilsActiveCharacter = tsActiveCharacter ts,
abilsInCombat = False,
abilsMetaAbilityTag = Nothing,
abilsParty = arsParty ts }
_ -> Nothing
let inventoryFn ts =
case tsPhase ts of
InventoryPhase mbItem ->
Just $ makeInventoryState ts (tsActiveCharacter ts) mbItem
_ -> Nothing
let shoppingFn ts =
case tsPhase ts of
ShoppingPhase mbItem forsale _ ->
Just $ makeShoppingState ts (tsActiveCharacter ts) mbItem forsale
_ -> Nothing
let upgradeFn ts =
case tsPhase ts of
UpgradePhase st sk ->
Just UpgradeState { upsActiveCharacter = tsActiveCharacter ts,
upsSpentSkills = sk,
upsSpentStats = st, upsParty = arsParty ts }
_ -> Nothing
hoverView cursorSink DefaultCursor <$> compoundViewM [
(subView sidebarRect . viewMap SidebarTown TownSidebar <$>
newSidebarView resources),
(subView mapRect <$> compoundViewM [
(newTownMapView resources cursorSink),
(newMaybeView abilitiesFn =<< fmap TownAbilities <$>
newAbilitiesView resources cursorSink),
(newMaybeView inventoryFn =<< fmap TownInventory <$>
newInventoryView resources cursorSink),
(newMaybeView shoppingFn =<< fmap TownShopping <$>
newShoppingView resources cursorSink),
(newMaybeView upgradeFn =<< fmap TownUpgrade <$>
newUpgradeView resources cursorSink)])]
newTownMapView :: (MonadDraw m) => Resources -> HoverSink Cursor
-> m (View TownState TownAction)
newTownMapView resources cursorSink = do
let
paint ts = do
let acs = tsCommon ts
let cameraTopleft = camTopleft $ acsCamera acs
-- TODO factor out duplicated code from here and Fallback.View.Combat
paintTerrain acs
paintRemains acs
paintAreaExits cameraTopleft (terrainMap $ acsTerrain acs) $
getAreaExits scenarioTriggers $ arsCurrentArea ts
paintDoodads cameraTopleft LowDood (acsDoodads acs)
paintFields resources cameraTopleft (acsVisible acs) (acsClock acs)
(acsFields acs)
paintMonsters acs False
paintParty resources cameraTopleft ts
paintDoodads cameraTopleft MidDood (acsDoodads acs)
tintNonVisibleTiles acs
paintDoodads cameraTopleft HighDood (acsDoodads acs)
-- Paint the targeting display, if any:
case tsPhase ts of
TargetingPhase (TownTargeting { ttTargeting = targeting }) -> do
mbMousePt <- getRelativeMousePos
paintTargeting cameraTopleft mbMousePt ts
(tsActiveCharacter ts) targeting (acsClock acs)
_ -> return ()
maybeM (acsMessage acs) (paintMessage resources)
handler ts EvTick = do
mbPt <- getRelativeMousePos
maybeM mbPt (setCursor ts)
maybe Ignore (Action . TownMove) <$> getArrowKeysDirection
handler ts (EvMouseMotion pt _) = Ignore <$ setCursor ts pt
handler ts (EvMouseDown pt) = do
whenWithinCanvas pt $ do
setCursor ts pt
case tsPhase ts of
WalkingPhase -> do
rect <- canvasRect
let townScript = maybe Suppress (Action . TownScript)
return $ mouseCase townScript townScript (Action . TownMove)
ts rect pt
ChooseAbilityPhase -> return Suppress
InventoryPhase _ -> return Suppress
UpgradePhase _ _ -> return Suppress
TargetingPhase _ ->
return $ Action $ TownTargetPosition $
pointPosition (pt `pAdd` (camTopleft $ arsCamera ts))
ScriptPhase _ -> return Suppress
ShoppingPhase _ _ _ -> return Suppress
handler ts (EvKeyDown KeyEscape _ _) = do
case tsPhase ts of
TargetingPhase _ -> return (Action TownCancelTargeting)
_ -> return Ignore
handler ts (EvKeyDown key _ _) = do
case keyCharacterNumber key of
Nothing -> return Ignore
Just charNum -> return $
case tsPhase ts of
TargetingPhase targeting ->
(case targeting of
TownTargeting { ttTargeting = TargetingAlly _ } ->
Action $ TownTargetCharacter charNum
_ -> Suppress) :: Action TownAction
_ -> Ignore
handler _ _ = return Ignore
mouseCase :: (Maybe (Script TownEffect ()) -> a)
-> (Maybe (Script TownEffect ()) -> a)
-> (Direction -> a) -> TownState -> IRect -> IPoint -> a
mouseCase monFn devFn dirFn ts rect pt =
let acs = tsCommon ts
pos = pointPosition (pt `pSub` rectTopleft rect `pAdd`
camTopleft (acsCamera acs))
checkRadius r s =
guard (pos `pSqDist` tsPartyPosition ts <= ofRadius r) >> s
search :: Grid.Grid b -> Maybe (Grid.Entry b)
search grid = do guard $ Set.member pos $ acsVisible acs
Grid.search pos grid
monFn' script = monFn $ checkRadius talkRadius $ Just script
devFn' ge = devFn $ checkRadius (devRadius $ Grid.geValue ge) $
Just $ mapEffect EffTownArea $
devInteract (Grid.geValue ge) ge $ tsActiveCharacter ts
getScript ge = do mscript <- monstScript (Grid.geValue ge)
Just (getMonsterScript scenarioTriggers
(arsCurrentArea ts) mscript ge)
in flip3 maybe monFn' (search (acsMonsters acs) >>= getScript) $
flip3 maybe devFn' (search (acsDevices acs)) $
dirFn $ ipointDir $ pt `pSub` rectCenter rect
setCursor :: (MonadHandler m) => TownState -> IPoint -> m ()
setCursor ts pt = do
rect <- canvasRect
when (rectContains rect pt) $ do
writeHoverSink cursorSink $
mouseCase (const TalkCursor) (const HandCursor) WalkCursor ts rect pt
return $ View paint handler
-------------------------------------------------------------------------------
-- paintTown :: TownState -> Paint ()
-- paintTown ts = do
-- rect <- canvasRect
-- let cameraTopleft = (round <$> tsCameraCenter ts) `pSub` rectCenter rect
-- let explored = tsExploredMap ts
-- paintTerrain cameraTopleft (tsTerrain ts) explored (tsClock ts)
-- paintMonsters cameraTopleft (tsVisible ts) [tsPartyPosition ts]
-- (gridElems $ tsMonsters ts)
-- paintParty cameraTopleft ts
-- tintNonVisibleTiles cameraTopleft explored (tsVisible ts)
-- maybeM (tsMessage ts) paintMessage
paintParty :: Resources -> IPoint -> TownState -> Paint ()
paintParty resources cameraTopleft ts = do
let pose = tsPartyPose ts
let rect = positionRect (tsPartyPosition ts) `rectPlus`
(animOffset (cpAnim pose) (tsPartyPosition ts) `pSub`
cameraTopleft)
let char = arsParty ts `partyGetCharacter` tsActiveCharacter ts
let sprite = ciStand (cpFaceDir pose) $
rsrcCharacterImages resources (chrClass char)
(chrAppearance char)
blitStretchTinted (Tint 255 255 255 (cpAlpha pose)) sprite rect
-------------------------------------------------------------------------------
|
mdsteele/fallback
|
src/Fallback/View/Town.hs
|
gpl-3.0
| 11,074
| 0
| 26
| 3,367
| 2,465
| 1,243
| 1,222
| 190
| 17
|
import FRP.Helm
import FRP.Helm.Graphics (Element(..))
import qualified FRP.Helm.Window as Window
import FRP.Helm.Animation (Frame, AnimationStatus(..), animate, absolute)
import FRP.Helm.Time (second, running, delta)
import FRP.Elerea.Simple
import Cell.Display (allGenFrames)
import LifeGame.Data.CellGrid (CellGrid(..), randCellGrid)
render :: Form -> (Int, Int) -> Element
render form (x, y) = collage x y $ [form]
main :: IO ()
main = do
cg <- randCellGrid 50 50
anim <- return . absolute $ allGenFrames cg (1 * second) 10
engine <- startup defaultConfig
run engine $ render <~ (animate anim running status) ~~ Window.dimensions engine
where
config = defaultConfig { windowTitle = "bats"
, windowDimensions = (500, 500)}
status = effectful $ getLine >>= \i -> return $
case i of
"Pause" -> Pause
"Stop" -> Stop
"Cycle" -> Cycle
|
qleguennec/bats
|
src/Main.hs
|
gpl-3.0
| 917
| 0
| 12
| 207
| 322
| 181
| 141
| 23
| 3
|
{-# LANGUAGE RecursiveDo, OverloadedStrings #-}
module Estuary.Widgets.Reflex where
-- This module is for definitions that extend the affordances of reflex and reflex-dom in
-- ways that are specific to the Estuary client but generically useful across multiple
-- widgets/settings/modules within the client.
import Reflex
import Reflex.Dom hiding (Delete,Insert)
import Data.Map
import Data.Text (Text)
import qualified Data.Text as T
import GHCJS.DOM.EventM
import qualified GHCJS.DOM.Types as G
import qualified GHCJS.DOM.GlobalEventHandlers as G
import qualified GHCJS.DOM.DocumentAndElementEventHandlers as G
import Data.Map
import Data.Maybe
import Data.List
import Data.Bool (bool)
import Data.Maybe
import Data.Monoid
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Fix
import GHCJS.DOM.HTMLSelectElement as Select
import Safe -- for readMay
import GHCJS.DOM.GlobalEventHandlers (change)
import Data.List (nub, elemIndex)
import Text.Read (readMaybe)
import qualified GHCJS.Types as T
import qualified GHCJS.Marshal.Pure as P
import Data.Functor.Misc -- For Const2
import Estuary.Types.Term
import Estuary.Types.Context
import Estuary.Types.Language
import Estuary.Types.TranslatableText
import Estuary.Tidal.Types
import Estuary.Types.Live
import Estuary.Types.Hint
-- the former 'dynEditor'...
dyn' :: MonadWidget t m => Dynamic t (m a) -> m (Dynamic t a)
dyn' x = do
initialWidget <- sample $ current x
widgetHold initialWidget $ updated x -- m (Dynamic t a)
-- for dynamic attributes
dynAttr :: Reflex t => Text -> Dynamic t Text -> Dynamic t (Map Text Text)
dynAttr k = fmap (Data.Map.singleton k)
-- a temporary button with class for the reference files
buttonWithClass' :: MonadWidget t m => Text -> m (Event t ())
buttonWithClass' s = do
(e, _) <- elAttr' "button" (fromList [("type", "button"), ("class", "ui-buttons code-font primary-color"), ("style", "background-color:transparent; border:none; cursor:help")]) $ text s
return $ domEvent Click e
-- a button with class
buttonWithClass :: MonadWidget t m => Text -> m (Event t ())
buttonWithClass s = do
(e, _) <- elAttr' "button" (fromList [("type", "button"), ("class", "ui-buttons other-borders code-font")]) $ text s
return $ domEvent Click e
buttonWithSettableClass :: MonadWidget t m => Text -> Text -> m (Event t ())
buttonWithSettableClass c s = do
(e, _) <- elAttr' "button" (fromList [("type", "button"), ("class", c)]) $ text s
return $ domEvent Click e
-- used in the footer
invisibleButton :: MonadWidget t m => m (Event t ())
invisibleButton = do
(e, _) <- elAttr' "button" (fromList [("type", "button"), ("class", "invisible-button")]) $ text "none"
return $ domEvent Click e
--button with dynamic label and settable class
dynButtonWSettableClass :: MonadWidget t m => Dynamic t Text -> Dynamic t Text -> m (Event t ())
dynButtonWSettableClass c s = dynE (buttonWithSettableClass <$> c <*> s)
-- dynButtonWSettableClass' :: MonadWidget t m => Dynamic t Text -> Dynamic t Text -> Dynamic t (m (Event t a))
-- dynButtonWSettableClass' c s = buttonWithSettableClass <$> c <*> s
--
--Button with dynamic label.
dynButton :: MonadWidget t m => Dynamic t Text -> m (Event t ())
dynButton = dynE . fmap buttonWithClass
dynButtonWithChild :: MonadWidget t m => String -> m () -> m (Event t ())
dynButtonWithChild cls child = do
(e, _) <- elAttr' "div" (fromList [("type", "button"), ("class", T.pack $ cls ++ " btn")]) child
return $ domEvent Click e
-- | dynE is like dyn from Reflex, specialized for widgets that return
-- events. A dynamic argument updates the widget, and the return value is
-- already flattened to just being the events returned by the child widget.
dynE :: MonadWidget t m => Dynamic t (m (Event t a)) -> m (Event t a)
dynE x = dyn x >>= switchPromptly never
-- a button that, instead of producing Event t (), produces an event of
-- some constant value
button' :: (MonadWidget t m) => Text -> a -> m (Event t a)
button' t r = do
x <- button t
return (r <$ x)
-- Button With Dynamic attributes
buttonDynAttrs :: MonadWidget t m => Text -> a -> Dynamic t (Map Text Text)-> m (Event t a)
buttonDynAttrs s val attrs = do
(e, _) <- elDynAttr' "button" attrs $ text s
let event = domEvent Click e
return (val <$ event)
-- Creates dropdown Menu with Subheaders
-- takes a Map of integers (the order everything should be displayed in)
-- to String tuples. The first String of the tuple indicates a subheader,
-- and the second indicates the selectable item under it. DropdownConfig options
-- expect the same as with a regular dropdown
dropdownOpts :: (MonadWidget t m) => Int -> Map Int (Text,Text) -> DropdownConfig t Int -> m (Dropdown t Int)
dropdownOpts k0 setUpMap (DropdownConfig setK attrs) = do
let options = fromList $ Prelude.zip (keys setUpMap) $ fmap snd $ elems setUpMap
let optGroups = fromList $ Prelude.zip (keys setUpMap) $ fmap fst $ elems setUpMap
let optGroupPositions = fmap (\x-> maybe (0) id $ Data.List.elemIndex x (elems optGroups)) $ nub $ elems optGroups -- [Int]
(eRaw, _) <- elDynAttr' "select" attrs $ do
let optionsWithDefault = constDyn $ if Data.Map.lookup k0 options == Nothing then Data.Map.union (k0 =: "") options else options
listWithKey optionsWithDefault $ \k v -> do
if not (elem k optGroupPositions) then blank else do
elAttr "optgroup" ("label"=:(maybe "" id $ Data.Map.lookup k optGroups)) $ blank
elAttr "option" ("value" =: (T.pack . show) k <> if k == k0 then "selected" =: "selected" else mempty) $ dynText v
let e = G.uncheckedCastTo HTMLSelectElement $ _el_element eRaw
performEvent_ $ fmap (Select.setValue e . show) setK
eChange <- wrapDomEvent e (`on` change) $ do
-- kStr <- fromMaybe "" <$> Select.getValue e
kStr <- Select.getValue e
return $ readMay kStr
let readKey mk = fromMaybe k0 $ do
k <- mk
guard $ Data.Map.member k options
return k
dValue <- (return . fmap readKey) =<< holdDyn (Just k0) (leftmost [eChange, fmap Just setK])
return $ Dropdown dValue (fmap readKey eChange) -- @clean this.
-- below this line from the former Estuary.Widgets.Generic
data EditSignal a = ChangeValue a | MakeNew | Close | DeleteMe | RepDiv | MakeGroup | MakeLayer
| RebuildMe | MakeL3 | MakeL4 | MakeRepOrDiv | Eval | DeleteContainer | LayerSplit | TransformMe deriving (Eq)
instance Functor EditSignal where
fmap f (ChangeValue x) = ChangeValue $ f x
toPotential::EditSignal a -> Potential a
toPotential (ChangeValue a) = Potential a
toPotential (MakeL3) = PotentialLiveness L3
toPotential (MakeL4) = PotentialLiveness L4
toPotential (Close) = Inert
toPotential (MakeRepOrDiv) = PotentialRepOrDiv
toPotential (MakeGroup) = PotentialMakeGroup
toPotential (MakeLayer) = PotentialMakeLayer
toPotential (DeleteMe) = PotentialDelete
toEditSigGenPat :: EditSignal a -> EditSignal (GeneralPattern a)
toEditSigGenPat (ChangeValue a) = ChangeValue (Atom a Inert Once)
toEditSigGenPat (MakeL4) = MakeL4
toEditSigGenPat (MakeL3) = MakeL3
toEditSigGenPat (MakeNew) =MakeNew
toEditSigGenPat (Close) = Close
toEditSigGenPat (DeleteMe) = DeleteMe
toEditSigGenPat (RepDiv) = RepDiv
toEditSigGenPat (MakeGroup) = MakeGroup
toEditSigGenPat (MakeLayer) = MakeLayer
toEditSigGenPat (RebuildMe) = RebuildMe
toEditSigGenPat (MakeRepOrDiv) = MakeRepOrDiv
toEditSigGenPat (Eval) = Eval
toEditSigGenPat (DeleteContainer) = DeleteContainer
toEditSigGenPat (LayerSplit) = LayerSplit
instance Show a => Show (EditSignal a) where
show (ChangeValue a) = show a
show MakeRepOrDiv = "* or /"
show Close = "close"
show DeleteMe = "delete"
show DeleteContainer ="delete container"
show MakeGroup = "[ ]"
show MakeLayer = "[,,]"
show RebuildMe = "RebuildMe"
show MakeL3 = "L3"
show MakeL4 = "L4"
show Eval = "eval"
show LayerSplit = "LayerSplit"
show TransformMe = "Transform"
isChangeValue::EditSignal a -> Bool
isChangeValue (ChangeValue _) = True
isChangeValue _ = False
--data EditSignal = DeleteMe | MakeGroup |
justChangeValues :: EditSignal a -> Maybe a
justChangeValues (ChangeValue x) = Just x
justChangeValues _ = Nothing
clickableDivDynAttrsWChild :: MonadWidget t m => Dynamic t (Map Text Text) -> m a -> m (Event t ()) -- return (Event t (), a)
clickableDivDynAttrsWChild attrs child = do
(element,_) <- elDynAttr' "div" attrs $ child
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (() <$) clickEv
clickableDivNoClass :: MonadWidget t m => m a -> m (Event t a) -- return (Event t (), a)
clickableDivNoClass child = do
(element, a) <- el' "div" $ child -- look elAttr' ::
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
let event = (a <$) clickEv
return event
-- clickableDivWithLabel :: MonadWidget t m => Text -> a -> m (Event t a, a)
-- clickableDivWithLabel label e = liftM (e <$) $ clickableDivNoClass $ text label
-- clickableA :: MonadWidget t m => Text -> m a -> m (Event t (), a)
-- clickableA label child = liftM (child <$) $ (clickableDivWithLabel $ text label)
-- return (event, child)
-- (element, a) <- el' "div" $ child
-- clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
-- let event = (() <$) clickEv
-- return $ a
-- clickableDivWithLabel :: MonadWidget t m => m a -> m (Event t ())
-- clickableDivWithLabel child = do
-- (element,_) <- el' "div" $ child
-- clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
-- return $ (() <$) clickEv
-- clickableDiv with class
clickableDiv :: MonadWidget t m => Text -> m a -> m (Event t ())
clickableDiv cssclass child = do
(element,_) <- elAttr' "div" attr $ child
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (() <$) clickEv
where
attr = singleton "class" cssclass
clickableDivClass :: MonadWidget t m => Text -> Text -> m (Event t ())
clickableDivClass label c = do
(element,_) <- elAttr' "div" (singleton "class" c) $ text label
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (() <$) clickEv
clickableDivClass' :: MonadWidget t m => Text -> Text -> a -> m (Event t a)
clickableDivClass' label c e = liftM (e <$) $ clickableDivClass label c
-- with displayed text that can change
clickableDivClass'':: MonadWidget t m => Dynamic t Text -> Text -> a -> m (Event t a)
clickableDivClass'' label c e = do
(element, _) <- elAttr' "div" ("class"=:c) $ dynText label
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (e <$) clickEv
mouseOverClickableDiv::MonadWidget t m => Dynamic t Text -> Text -> a -> m(Event t a)
mouseOverClickableDiv label c e = mdo
(element, _) <- elDynAttr' "div" attrs $ dynText label
mouseOver <- liftM (True <$) $ wrapDomEvent (_el_element element) (elementOnEventName Mouseover) mouseXY
mouseOut <- liftM (False <$) $ wrapDomEvent (_el_element element) (elementOnEventName Mouseout) mouseXY
isMouseOver <- holdDyn False $ leftmost [mouseOut, mouseOver]
let attrs = fmap (fromList . (\x-> [("class",c),x]) . ((,) "style") . bool "" ";background-color:rgba(144,238,144,0.2);") isMouseOver
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (e <$) clickEv
clickableDivAttrs::MonadWidget t m => Text -> a -> Map Text Text -> m (Event t a)
clickableDivAttrs label val attrs= do
(element,_) <- elAttr' "div" attrs $ text label
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (val <$) clickEv
clickableDivAttrs'::MonadWidget t m => Text -> a -> Map Text Text -> x -> y -> m (Dynamic t ((),Event t a))
clickableDivAttrs' label val attrs _ _= do
(element,_) <- elAttr' "div" attrs $ text label
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
let event = (val <$) clickEv
return $ constDyn ((),event)
clickableDivDynAttrs :: MonadWidget t m => Text -> a -> Dynamic t (Map Text Text) -> m (Event t a)
clickableDivDynAttrs label val attrs = do
(element,_) <- elDynAttr' "div" attrs $ text label
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (val <$) clickEv
-- with displayed text that can change
clickableSpanClass:: MonadWidget t m => Dynamic t Text -> Text -> a -> m (Event t a)
clickableSpanClass label c e = do
(element, _) <- elAttr' "span" ("class"=:c) $ dynText label
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (e <$) clickEv
clickableTdClass::MonadWidget t m => Dynamic t Text -> Dynamic t Text -> a -> m (Event t a)
clickableTdClass label c val = do
let attrs = fmap (singleton "class") c
(element, _) <- elDynAttr' "td" attrs $ dynText label
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ ((val) <$) clickEv
pingButton :: MonadWidget t m => Text -> m (Event t ())
pingButton label = liftM (() <$) $ button label
pingButton' :: MonadWidget t m => Text -> m (Dynamic t ((),Event t ()))
pingButton' label = do
x <- pingButton label
return $ constDyn ((),x)
pingButton'' :: MonadWidget t m => Text -> a -> b -> m (Dynamic t ((),Event t ()))
pingButton'' label _ _ = pingButton' label
pingButton''':: MonadWidget t m => Text -> Map Text Text -> a -> b -> m (Dynamic t ((),Event t (EditSignal ())))
pingButton''' label attrs _ _ = do
b <- buttonDynAttrs label (ChangeValue ()) $ constDyn attrs
return $ constDyn ((), b)
makeNewButton:: (MonadWidget t m)=> Text -> a -> b -> m (Dynamic t ((),Event t (EditSignal ())) )
makeNewButton label _ _ = do
a <- button label
return $ constDyn ((), ((MakeNew::EditSignal ()) <$) a)
tdButtonAttrs:: MonadWidget t m => Text -> a -> Map Text Text -> m (Event t a)
tdButtonAttrs s val attrs = do
(element, _) <- elAttr' "td" attrs $ text s
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ ((val) <$) clickEv
-- with displayed text that can change
tdButtonAttrs':: MonadWidget t m => Dynamic t Text -> a -> Map Text Text -> m (Event t a)
tdButtonAttrs' s val attrs = do
(element, _) <- elAttr' "td" attrs $ dynText s
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ ((val) <$) clickEv
tdPingButtonAttrs:: MonadWidget t m => Text -> Map Text Text -> a -> b -> m (Dynamic t ((),Event t (EditSignal ())))
tdPingButtonAttrs label attrs _ _ = el "td" $ do
b <- buttonDynAttrs label (ChangeValue ()) $ constDyn attrs
return $ constDyn ((), b)
growingTextInput::MonadWidget t m => TextInputConfig t -> m (TextInput t)
growingTextInput config = mdo
let attrs = _textInputConfig_attributes config
let dynAttrs = (\m w-> insertWith (T.append) "style" (T.pack $ ";width:"++ show (max 20 $ min 100 $ 8*T.length w) ++ "px" ++";") m) <$> attrs <*> (_textInput_value textField)
let newConfig = TextInputConfig (_textInputConfig_inputType config) (_textInputConfig_initialValue config) (_textInputConfig_setValue config) dynAttrs
textField <- textInput newConfig
return textField
whitespace:: (MonadWidget t m, Show a, Eq a)=> Dynamic t Liveness -> GeneralPattern a -> Text -> [EditSignal (GeneralPattern a)] -> () -> Event t (EditSignal (GeneralPattern a)) -> m (Dynamic t ((), Event t (EditSignal (GeneralPattern a)), Event t Hint))
whitespace liveness iVal cssClass popupList _ event = elAttr "div" ("style"=:"position:relative;display:inline-block") $ elClass "div" cssClass $ mdo
-- whitespace <- clickableDivClass'' (constDyn (case iVal of (Layers _ _)->", ";otherwise->" ")) "whiteSpaceClickable" ()
whitespace <- mouseOverClickableDiv (constDyn (case iVal of (Layers _ _)->", ";otherwise->" ")) "whiteSpaceAdd" ()
openCloseEvents <- toggle False $ leftmost [whitespace, closeEvents,(() <$) addEvent]
popupMenu <- liftM (switchPromptlyDyn) $ flippableWidget (return never) (whitespacePopup liveness popupList) False (updated openCloseEvents)
let addEvent = (ChangeValue (Blank Inert) <$) $ ffilter (\x-> if isJust x then fromJust (fmap (isChangeValue) x) else False) popupMenu
let livenessEv = fmap fromJust $ ffilter (\x-> x==Just MakeL3 || x == Just MakeL4 || x == Just Eval) popupMenu
let delContEv = fmap fromJust $ ffilter (\x-> x==Just DeleteContainer) popupMenu
let layerSplit = fmap fromJust $ ffilter (\x-> x==Just LayerSplit) popupMenu
let closeEvents = (() <$) $ ffilter (==Nothing) popupMenu
return $ constDyn ((),leftmost [livenessEv, addEvent,delContEv,layerSplit],never)
--where
-- iValSingle (Group (Live (xs,r) _) p) = iValSingle (xs!!0)
-- iValSingle (Group (Edited _ (xs,r)) p) = iValSingle (xs!!0)
-- iValSingle (Layers (Live (xs,r) _) p) = iValSingle (xs!!0)
-- iValSingle (Layers (Edited _ (xs,r)) p) = iValSingle (xs!!0)
-- iValSingle (Atom x p r) = Atom x p r
whitespacePopup::(MonadWidget t m,Show a)=> Dynamic t Liveness -> [EditSignal a] -> m (Event t (Maybe (EditSignal a)))
whitespacePopup liveness actionList = elClass "div" "popupMenu" $ do
let popupList = fmap (\x->clickableDivClass' (T.pack $ show x) "primary-color code-font background" (Just x)) actionList -- [m (Maybe (EditSignal))]
let events = Control.Monad.sequence popupList -- m (t a)
events' <- liftM (id) events
layerSplit <- clickableDivClass' "[ , ]" "primary-color code-font background" (LayerSplit)
liveWidget <- livenessCheckboxWidget (liveness)
closeMenu <- clickableDivClass' "close" "primary-color code-font background" (Nothing)
return $ leftmost $ events' ++[closeMenu, fmap Just liveWidget, fmap Just layerSplit]
livenessWidget::(MonadWidget t m) => Dynamic t Liveness -> m (Event t (EditSignal a))
livenessWidget liveness = elClass "div" "livenessWidget" $ mdo
let livenessText = fmap (\x->if x==L3 then "L3" else "L4") liveness
livenessButton <- clickableDivClass'' (livenessText) "livenessText" ()
eval <- clickableDivClass' "Eval" "L3Eval" Eval
let livenessChange = attachWith (\d e -> if d==L4 then MakeL3 else MakeL4) (current liveness) livenessButton
return $ leftmost [livenessChange,eval]
livenessCheckboxWidget::(MonadWidget t m ) => Dynamic t Liveness -> m (Event t (EditSignal a))
livenessCheckboxWidget liveness = elClass "div" "livenessWidget" $ do
text "Live"
let isLive = fmap (==L4) liveness
cb <- checkboxView (constDyn Data.Map.empty) isLive
eval <- clickableDivClass' "Eval" "L3Eval" Eval
return $ leftmost [fmap (\x-> if x then MakeL4 else MakeL3) cb,eval]
basicPopup::(MonadWidget t m,Show a)=> Dynamic t Liveness -> [EditSignal a] -> m (Event t (Maybe (EditSignal a)))
basicPopup liveness actionList = elClass "div" "popupMenu" $ do
let popupList = fmap (\x->clickableDivClass' (T.pack $ show x) "primary-color code-font background" (Just x)) actionList -- [m (Maybe (EditSignal))]
let events = Control.Monad.sequence popupList -- m (t a)
events' <- liftM (id) events
liveWidget <- livenessCheckboxWidget (liveness)
closeMenu <- clickableDivClass' "close" "primary-color code-font background" (Nothing)
return $ leftmost $ events' ++[closeMenu, fmap Just liveWidget]
samplePickerPopup::(MonadWidget t m)=> Dynamic t Liveness -> Map Int (Text,Text) -> [EditSignal Text] -> m (Event t (Maybe (EditSignal Text)),Event t Hint)
samplePickerPopup liveness sampleMap actionList = elClass "div" "popupMenu" $ do
dd <- dropdownOpts (-1) sampleMap def --defaults to -1 so that someone can select "~" (the first one) and have it register as a change
let sampleKey = _dropdown_value dd
let sampleChange = fmap (\x-> maybe ("~") (snd) $ Data.Map.lookup x sampleMap) sampleKey -- Dyn (editsignal Text)
let popupList = fmap (\x->clickableDivClass' (T.pack $ show x) "primary-color code-font background" (Just x)) actionList -- [m (Maybe (EditSignal))]
let events = Control.Monad.sequence popupList -- m (t a)
events' <- liftM (id) events
liveWidget <- livenessCheckboxWidget liveness
closeMenu <- clickableDivClass' "close" "primary-color code-font background" (Nothing)
return $ (leftmost $ events' ++[closeMenu, fmap Just liveWidget,fmap (Just . ChangeValue) (updated sampleChange)], fmap SampleHint $ ffilter (\x->if x =="~" then False else True) $ updated sampleChange)
repDivWidget'::MonadWidget t m => RepOrDiv -> Event t () -> m (Event t RepOrDiv)
repDivWidget' iVal _ = elClass "span" "repOrDiv" $ mdo
repDivButton <- clickableSpanClass showRep "repDivSpan" ()
repTog <- toggle iToggle repDivButton
let showRep = fmap (\x-> if x then " * " else " / ") repTog
let textAttrs = constDyn $ fromList $ zip ["min", "class"] ["1","repOrDivInput"]
textField <- textInput $ def & textInputConfig_attributes .~ textAttrs & textInputConfig_initialValue .~ (T.pack $ show iNum) & textInputConfig_inputType .~"number"
let numTextField = _textInput_value textField
let num = fmap (\str-> if isJust (readMaybe (T.unpack str)::Maybe Int) then (read (T.unpack str)::Int) else iNum) numTextField
let dynVal = (\tog val -> if tog then Rep val else Div val) <$> repTog <*> num
return $ updated dynVal
where
(iToggle, iNum) = case iVal of
(Rep x) -> (True,x)
(Div x) -> (False,x)
otherwise -> (True, 1)
repDivWidget''::MonadWidget t m => RepOrDiv -> Event t () -> m (Dynamic t RepOrDiv)
repDivWidget'' iVal _ = elClass "span" "repOrDiv" $ mdo
repDivButton <- clickableSpanClass showRep "repDivSpan" ()
repTog <- toggle iToggle repDivButton
let showRep = fmap (\x-> if x then " * " else " / ") repTog
let textAttrs = constDyn $ fromList $ zip ["min", "class"] ["1","repOrDivInput"]
textField <- textInput $ def & textInputConfig_attributes .~ textAttrs & textInputConfig_initialValue .~ (T.pack $ show iNum) & textInputConfig_inputType .~"number"
let numTextField = _textInput_value textField
let num = fmap (\str-> if isJust (readMaybe (T.unpack str)::Maybe Int) then (read (T.unpack str)::Int) else iNum) numTextField
return $ (\tog val -> if tog then Rep val else Div val) <$> repTog <*> num
where
(iToggle, iNum) = case iVal of
(Rep x) -> (True,x)
(Div x) -> (False,x)
otherwise -> (True, 1)
genericSignalMenu :: MonadWidget t m => m (Event t (Maybe (EditSignal a)))
genericSignalMenu = elAttr "div" (singleton "style" "top: 0px; left: 0px; position: absolute; z-index: 1;") $ do
a <- clickableDivClass' "Close" "primary-color code-font background" Nothing
b <- clickableDivClass' "-" "primary-color code-font background" (Just DeleteMe)
c <- clickableDivClass' "[]" "primary-color code-font background" (Just MakeGroup)
d <- clickableDivClass' "{}" "primary-color code-font background" (Just MakeLayer)
return $ leftmost [a,b,c,d]
popupSignalWidget :: MonadWidget t m => m (Event t (EditSignal a))
popupSignalWidget = elAttr "div" (singleton "style" "border: 1px solid black; position: relative; display: inline-block;") $ mdo
y <- popup popupEvents
x <- clickableWhiteSpace
let popupEvents = leftmost [Just genericSignalMenu <$ x,Nothing <$ y]
return $ (fmap fromJust . ffilter isJust) y
genericSignalWidget :: MonadWidget t m => m (Event t (EditSignal a))
genericSignalWidget = elClass "div" "genericSignalWidget" $ do
b <- button' "-" DeleteMe
c <- button' "[]" MakeGroup
d <- button' "{}" MakeLayer
return $ leftmost [b,c,d]
-- Used heavily in Help section
-- Contains the child in a hideable div with a class
hideableWidget :: MonadWidget t m => Dynamic t Bool -> Text -> m a -> m a
hideableWidget b c m = do
let attrs = fmap (bool (fromList [("hidden","true"),("class",c)]) (singleton "class" c)) b
elDynAttr "div" attrs m
-- Used for the terminal
-- Contains the child in a hideable div with no class
hideableWidget' :: MonadWidget t m => Dynamic t Bool -> m a -> m a
hideableWidget' b m = do
let attrs = fmap (bool (fromList [("hidden","true")]) (fromList [("visible","true")])) b
elDynAttr "div" attrs m
hideableWidgetWFlexColumn :: MonadWidget t m => Dynamic t Bool -> m a -> m a
hideableWidgetWFlexColumn b m = do
let attrs = fmap (bool (fromList [("hidden","true")]) (fromList [("style", "display: flex; flex-direction: column;")])) b
elDynAttr "div" attrs m
traceDynamic :: (MonadWidget t m, Show a) => String -> Dynamic t a -> m (Dynamic t a)
traceDynamic m x = do
initialValue <- sample $ current x
let x' = traceEvent m $ updated x
holdDyn initialValue x'
-- a hideable widget that is only built/rebuilt when it is made visible
deferredWidget :: (MonadFix m, DomBuilder t m, MonadSample t m, MonadHold t m, Adjustable t m, NotReady t m, PostBuild t m) => Text -> Dynamic t Bool -> Dynamic t (m ()) -> m ()
deferredWidget cssClass isVisible dynWidgets = do
initialVisibility <- sample $ current isVisible
defaultWidget <- sample $ current dynWidgets
let initialWidget = if initialVisibility then defaultWidget else return ()
isVisible' <- holdUniqDyn isVisible
let transitionsToVisible = ffilter (== True) $ updated isVisible'
let becomesVisible = tag (current dynWidgets) transitionsToVisible
let visibleChanges = gate (current isVisible) $ updated dynWidgets
let changes = leftmost [becomesVisible,visibleChanges]
let attrs = fmap (bool (fromList [("hidden","true"),("class",cssClass)]) (singleton "class" cssClass)) isVisible
elDynAttr "div" attrs $ widgetHold initialWidget changes
return ()
--this is a special type of tooltip that is used in statusWidget, tooltip has position relative
tooltipForScrollableTable :: DomBuilder t m => m a -> m b -> m a
tooltipForScrollableTable child popup = do
divClass "tooltip-scrollable-table" $ do
a <- child
elClass "span" "tooltiptext-scrollable-table" popup
return a
-- this is a standard tooltip that "overrides" the overflow hidden of its parents.
--this won't work fine if the label is inside a scrollable div.
tooltip :: DomBuilder t m => m a -> m b -> m a
tooltip child popup = do
elClass "div" "tooltip" $ do
a <- child
divClass "tooltipPosAbsolute" $ elClass "span" "tooltiptext code-font" popup
return a
-- a tooltip with settable class for the popup
tooltipNoPopUpClass :: DomBuilder t m => m a -> m b -> m a
tooltipNoPopUpClass child popup = do
elClass "div" "tooltip" $ do
a <- child
divClass "tooltipPosAbsolute" $ popup
return a
-- below this line is the former Estuary.Reflex.Container
widgetMap :: (MonadWidget t m,Ord k) => Map k (m a) -> Event t (Map k (m a)) -> m (Dynamic t (Map k a))
widgetMap iMap rebuild = do
let iWidget = sequence $ elems iMap -- :: m [a]
let rebuild' = fmap (sequence . elems) rebuild -- :: Event t (m [a])
widgets <- widgetHold iWidget rebuild' -- :: m (Dynamic t [a])
keys <- holdDyn (keys iMap) (fmap keys rebuild) -- :: m (Dynamic t [k])
return $ (\a b -> fromList $ zip a b) <$> keys <*> widgets
container' :: (Ord k, Num k, MonadWidget t m)
=> (v -> m a) -- a builder function from
-> Map k v -- an initial map of values
-> Event t (Map k (Construction v)) -- construction events
-> m (Dynamic t (Map k a))
container' build iMap cEvents = do
let iMap' = fmap build iMap
newMap <- foldDyn (\a b -> applyConstructionMap b a) iMap cEvents
let newMap' = fmap (fmap build) (updated newMap)
widgetMap iMap' newMap'
data Construction a = Insert a | Replace a | Delete deriving (Show)
-- given a Map and a Construction operation at a specifed key, return the new map
applyConstruction :: (Num k, Ord k) => Map k a -> (k,Construction a) -> Map k a
applyConstruction m (k,Replace a) = Data.Map.insert k a m
applyConstruction m (k,Delete) = Data.Map.delete k m
applyConstruction m (k,Insert a) = Data.Map.insert k a m'
where m' = mapKeys (f) m
f x | member k m = if (x>=k) then (x + 1) else x
| otherwise = x
-- given a Map and another map of Construction operations, return the resulting map
applyConstructionMap :: (Num k, Ord k) => Map k a -> Map k (Construction a) -> Map k a
applyConstructionMap oldMap cMap = foldlWithKey (\a k b -> applyConstruction a (k,b)) oldMap cMap
-- given a Map and another map of Construction operations, determine the complete
-- list of "construction" events as expected by the Reflex function listHoldWithKey
constructionDiff :: (Num k, Ord k, Eq v) => Map k v -> Map k (Construction v) -> Map k (Maybe v)
constructionDiff oldMap cMap = unions [deletions,additions,changes]
where newMap = applyConstructionMap oldMap cMap
deletions = fmap (const Nothing) $ Data.Map.difference oldMap newMap -- keys only in oldMap are deletions
additions = fmap (Just) $ Data.Map.difference newMap oldMap -- keys only in newMap are additions
changes = fmap (Just) $ intersection newMap $ Data.Map.filter (id) $ intersectionWith (/=) oldMap newMap
container :: (Ord k, Num k, Show k, Eq v, Show v, MonadWidget t m)
=> Map k v -- a map of initial values
-> Event t (Map k (Construction v)) -- construction events (replace/insert/delete)
-> Event t (Map k w) -- signaling events to be delivered to child widgets
-> (v -> Event t w -> m (Dynamic t (v,Event t x))) -- function to make a widget given initial value and signaling event
-> m ( (Dynamic t (Map k v)) , Event t (Map k x) )
container initialValue cEvents rEvents mkChild = mdo
let cEventsIn = cEvents
let existingMap' = values
let cEvents' = attachPromptlyDynWith (constructionDiff) existingMap' cEventsIn
let selector = fanMap rEvents
let mkChild' k v = mkChild v $ select selector $ (Const2 k)
widgets <- liftM (joinDynThroughMap) $ listHoldWithKey initialValue cEvents' mkChild' -- Dynamic t (Map k (v,Event t x))
let values = fmap (fmap (fst)) widgets
let events = switchPromptlyDyn $ fmap (mergeMap . fmap (snd)) widgets
return (values,events)
eitherContainer :: (Ord k, Num k, Show k, Eq v, Eq a, MonadWidget t m)
=> Map k (Either v a) -- a map of initial values
-> Event t (Map k (Construction (Either v a))) -- construction events (replace/insert/delete)
-> Event t (Map k w) -- signaling events to be delivered to child widgets of type v
-> Event t (Map k b) -- signaling events to be delivered to child widgets of type a
-> (v -> Event t w -> m (Dynamic t (v,Event t e))) -- function to build widgets for type v (returning events of type e)
-> (a -> Event t b -> m (Dynamic t (a,Event t e))) -- function to build widgets for type a (also returning events of type e)
-> m ( (Dynamic t (Map k (Either v a))) , Event t (Map k e) )
eitherContainer initialValues cEvents eventsToLeft eventsToRight buildLeft buildRight = mdo
let cEvents' = attachPromptlyDynWith (constructionDiff) values cEvents
widgets <- liftM (joinDynThroughMap) $ listHoldWithKey initialValues cEvents' mkChild
let values = fmap (fmap (fst)) widgets
let events = switchPromptlyDyn $ fmap (mergeMap . fmap (snd)) widgets
return (values,events)
where
mkChild k (Left x) = buildLeft x (select (fanMap eventsToLeft) (Const2 k)) >>= return . fmap (\(v,e)->(Left v,e))
mkChild k (Right x) = buildRight x (select (fanMap eventsToRight) (Const2 k)) >>= return . fmap (\(a,e)->(Right a,e))
-- for widgets returning a 3rd event channel (for hints)
eitherContainer4 :: (Ord k, Num k, Show k, Eq v, Eq a, MonadWidget t m)
=> Map k (Either v a) -- a map of initial values
-> Event t (Map k (Construction (Either v a))) -- construction events (replace/insert/delete)
-> Event t (Map k w) -- signaling events to be delivered to child widgets of type v
-> Event t (Map k b) -- signaling events to be delivered to child widgets of type a
-> (v -> Event t w -> m (Dynamic t (v,Event t e,Event t e1))) -- function to build widgets for type v (returning events of type e)
-> (a -> Event t b -> m (Dynamic t (a,Event t e,Event t e1))) -- function to build widgets for type a (also returning events of type e)
-> m ( (Dynamic t (Map k (Either v a))) , Event t (Map k e) , Event t e1 )
eitherContainer4 initialValues cEvents eventsToLeft eventsToRight buildLeft buildRight = mdo
let cEvents' = attachPromptlyDynWith (constructionDiff) values cEvents
widgets <- liftM (joinDynThroughMap) $ listHoldWithKey initialValues cEvents' mkChild -- m (Dynamic t (Map k a))
let values = fmap (fmap (\(a,_,_)->a)) widgets
let events = switchPromptlyDyn $ fmap (mergeMap . fmap ((\(_,b,_)->b))) widgets
let events2 = switchPromptlyDyn $ fmap (leftmost . elems . fmap ((\(_,_,c)->c))) widgets -- @ may drop some messages if multiple hints coincide...
return (values,events,events2)
where
mkChild k (Left x) = buildLeft x (select (fanMap eventsToLeft) (Const2 k)) >>= return . fmap (\(v,e,e2)->(Left v,e,e2))
mkChild k (Right x) = buildRight x (select (fanMap eventsToRight) (Const2 k)) >>= return . fmap (\(a,e,e2)->(Right a,e,e2))
-- Same as eitherContainer' but children take Dynamic value too
-- primarily (/for now) used for updating children with liveness values
--eitherContainerLive :: (Ord k, Num k, Show k, Eq v, Eq a, MonadWidget t m)
-- => Map k (Either v a) -- a map of initial values
-- -> Event t (Map k (Construction (Either v a))) -- construction events (replace/insert/delete)
-- -> Dynamic t c
-- -> Event t (Map k w) -- signaling events to be delivered to child widgets of type v
-- -> Event t (Map k b) -- signaling events to be delivered to child widgets of type a
-- -> (Dynamic t c -> v -> Event t w -> m (Dynamic t (v,Event t e))) -- function to build widgets for type v (returning events of type e)
-- -> (Dynamic t c -> a -> Event t b -> m (Dynamic t (a,Event t e))) -- function to build widgets for type a (also returning events of type e)
-- -> m ( (Dynamic t (Map k (Either v a))) , Event t (Map k e) )
--eitherContainerLive initialValues cEvents liveness eventsToLeft eventsToRight buildLeft buildRight = mdo
-- let cEvents' = attachDynWith (constructionDiff) values cEvents
-- widgets <- liftM (joinDynThroughMap) $ listHoldWithKey initialValues cEvents' mkChild
-- values <- mapDyn (fmap (fst)) widgets
-- events <- liftM (switchPromptlyDyn) $ mapDyn (mergeMap . fmap (snd)) widgets
-- return (values,events)
-- where
-- mkChild k (Left x) = buildLeft liveness x (select (fanMap eventsToLeft) (Const2 k)) >>= mapDyn (\(v,e)->(Left v,e))
-- mkChild k (Right x) = buildRight liveness x (select (fanMap eventsToRight) (Const2 k)) >>= mapDyn (\(a,e)->(Right a,e))
{- ???
maybeContainer :: (Ord k, Num k, Show k, Eq v, Eq a, MonadWidget t m)
=> Map k (Maybe v) -- a map of initial values
-> Event t (Map k (Construction (Maybe v)) -- construction events (replace/insert/delete)
-> Event t (Map k w) -- signaling events to be delivered to child widgets of type v
-> (v -> Event t w -> m a) -- function to build widgets for Just values
-> (Event t w -> m b) -- function to build widgets for Nothing values
-> m (Dynamic t (Map k a))
widgetAndSpace ::
=> (v -> Event t w -> m a)
-> m (Dynamic t a,)
-}
-- eitherContainer' is a variant of eitherContainer where the difference is that
-- only left values (not right) are included in the dynamic result:
eitherContainer' :: (Ord k, Num k, Show k, Eq v, Eq a, MonadWidget t m)
=> Map k (Either v a) -- a map of initial values
-> Event t (Map k (Construction (Either v a))) -- construction events (replace/insert/delete)
-> Event t (Map k w) -- signaling events to be delivered to child widgets of type v
-> Event t (Map k b) -- signaling events to be delivered to child widgets of type a
-> (v -> Event t w -> m (Dynamic t (v,Event t e))) -- function to build widgets for type v (returning events of type x)
-> (a -> Event t b -> m (Dynamic t (a,Event t e))) -- function to build widgets for type a (returning events of type c)
-> m ( (Dynamic t (Map k v)) , Event t (Map k e) )
eitherContainer' initialValues cEvents eventsToLeft eventsToRight buildLeft buildRight = do
(d,e) <- eitherContainer initialValues cEvents eventsToLeft eventsToRight buildLeft buildRight
let d' = fmap (Data.Map.mapMaybe (either (Just) (const Nothing))) d
return (d',e)
eitherContainer'' :: (Ord k, Num k, Show k, Eq v, Eq a, MonadWidget t m)
=> Map k (Either v a) -- a map of initial values
-> Event t (Map k (Construction (Either v a))) -- construction events (replace/insert/delete)
-> Event t (Map k w) -- signaling events to be delivered to child widgets of type v
-> Event t (Map k b) -- signaling events to be delivered to child widgets of type a
-> (v -> Event t w -> m (Dynamic t (v,Event t e,Event t h))) -- function to build widgets for type v (returning events of type e and f)
-> (a -> Event t b -> m (Dynamic t (a,Event t e,Event t h))) -- function to build widgets for type a (also returning events of type e and f)
-> m ( (Dynamic t (Map k (Either v a))) , Event t (Map k e), Event t h)
eitherContainer'' initialValues cEvents eventsToLeft eventsToRight buildLeft buildRight = mdo
let cEvents' = attachPromptlyDynWith (constructionDiff) values cEvents
widgets <- liftM (joinDynThroughMap) $ listHoldWithKey initialValues cEvents' mkChild
let values = fmap (fmap (\(x,_,_) -> x)) widgets
let eEvents = switchPromptlyDyn $ fmap (mergeMap . fmap (\(_,x,_) -> x)) widgets
let hEvents = switchPromptlyDyn $ fmap (leftmost . elems . fmap (\(_,_,x) -> x)) widgets
return (values,eEvents,hEvents)
where
mkChild k (Left x) = buildLeft x (select (fanMap eventsToLeft) (Const2 k)) >>= return . fmap (\(v,e,f)->(Left v,e,f))
mkChild k (Right x) = buildRight x (select (fanMap eventsToRight) (Const2 k)) >>= return . fmap (\(a,e,f)->(Right a,e,f))
eitherContainer''' :: (Ord k, Num k, Show k, Eq v, Eq a, MonadWidget t m)
=> Map k (Either v a) -- a map of initial values
-> Event t (Map k (Construction (Either v a))) -- construction events (replace/insert/delete)
-> Event t (Map k w) -- signaling events to be delivered to child widgets of type v
-> Event t (Map k b) -- signaling events to be delivered to child widgets of type a
-> (v -> Event t w -> m (Dynamic t (v,Event t e,Event t h))) -- function to build widgets for type v (returning events of type e and f)
-> (a -> Event t b -> m (Dynamic t (a,Event t e,Event t h))) -- function to build widgets for type a (returning events of type e and f)
-> m ( Dynamic t (Map k v) , Event t (Map k e), Event t h)
eitherContainer''' initialValues cEvents eventsToLeft eventsToRight buildLeft buildRight = do
(d,e,h) <- eitherContainer'' initialValues cEvents eventsToLeft eventsToRight buildLeft buildRight
let d' = fmap (Data.Map.mapMaybe (either (Just) (const Nothing))) d
return (d',e,h)
{-
eitherContainer'' :: (Ord k, Num k, Show k, Eq v, Eq a, MonadWidget t m)
=> Map k (Either v a)
-> Event t (Map k (Construction (Either v a)))
-> (v -> m (Dynamic t (v,Event t e)))
-> (a -> m (Event t c))
-> m ( Dynamic t (Map k v), Event t (Map k e), Event t (Map k c) )
eitherContainer'' i cEvents lBuild rBuild = mdo
widgets <- listHoldWithKey i cEvents? build -- m (Dynamic t (Map k (Either (Dynamic t (v,Event t e)) (Event t c))))
values <- liftM joinDynThroughMap $ forDyn widgets (fmapFstIntoMap . filterMapForOnlyLeftElements)
lEvents <- forDyn widgets (fmapSndIntoMap . filterMapForOnlyLeftElements)
rEvents <- forDyn widgets
widgets <- liftM (joinDynThroughMap) $ listHoldWithKey i cEvents' build
values <- mapDyn (fmap (fst)) widgets
events <- liftM (switchPromptlyDyn) $ mapDyn (mergeMap . fmap (snd)) widgets
return (values,lEvents,rEvents)
where
build _ (Left v) = lBuild v >>= mapDyn (\(v,e)-> Left (v,e))
build _ (Right a) = rBuild a >>= mapDyn (\c-> Right c)
-}
eitherWidget :: (MonadWidget t m)
=> (a -> Event t c -> m (Dynamic t (a,Event t d)))
-> (b -> Event t c -> m (Dynamic t (b,Event t d)))
-> Either a b -> Event t c -> m (Dynamic t ((Either a b),Event t d))
eitherWidget buildA buildB iValue c = either buildA' buildB' iValue
where
buildA' a = buildA a c >>= return . fmap (\(x,d) -> (Left x,d))
buildB' b = buildB b c >>= return . fmap (\(x,d) -> (Right x,d))
wfor :: (MonadWidget t m) => [a] -> (a -> m (Dynamic t b)) -> m (Dynamic t [b])
wfor iVals mkChild = do
widgets <- liftM (joinDynThroughMap) $ listHoldWithKey iMap never mkChild' -- m (Dynamic t [b]))
return $ fmap elems widgets
where
iMap = fromList $ zip [(0::Int)..] iVals
mkChild' _ a = mkChild a
wmap :: (MonadWidget t m) => (a -> m (Dynamic t b)) -> [a] -> m (Dynamic t [b])
wmap = flip wfor
resettableWidget :: MonadWidget t m => (a -> Event t b -> m (Dynamic t c)) -> a -> Event t b -> Event t a -> m (Dynamic t c)
resettableWidget f i e reset = liftM (join) $ widgetHold (f i e) $ fmap (\x -> f x e) reset
popup :: MonadWidget t m => Event t (Maybe (m (Event t a))) -> m (Event t a)
popup buildEvents = do
let buildEvents' = fmap (maybe (return never) id) buildEvents
liftM (switchPromptlyDyn) $ widgetHold (return never) buildEvents'
clickableWhiteSpace :: MonadWidget t m => m (Event t ())
clickableWhiteSpace = do
(element,_) <- elAttr' "div" (singleton "class" "clickableWhiteSpace") $ text "clickableWhiteSpace"
clickEv <- wrapDomEvent (_el_element element) (elementOnEventName Click) (mouseXY)
return $ (() <$) clickEv
flippableWidget :: MonadWidget t m => m a -> m a -> Bool -> Event t Bool -> m (Dynamic t a)
flippableWidget b1 b2 i e = widgetHold (bool b1 b2 i) $ fmap (bool b1 b2) e
|
d0kt0r0/estuary
|
client/src/Estuary/Widgets/Reflex.hs
|
gpl-3.0
| 42,233
| 0
| 25
| 8,486
| 13,959
| 7,015
| 6,944
| 549
| 6
|
{-# LANGUAGE NoMonomorphismRestriction #-}
module Plugins.DiagramStuff (
module Diagrams.Backend.SVG
,module Diagrams.Core
,module Diagrams.Prelude
,module Text.Blaze.Svg.Renderer.String
,rdia
) where
import Diagrams.Backend.SVG
import Diagrams.Core
import Diagrams.Prelude
import Text.Blaze.Svg.Renderer.String
import Plugins.LiteralString
rdia dia = stri $ renderSvg $ renderDia SVG (SVGOptions Absolute Nothing) ((dia # scale 100 # lw 1) :: Diagram SVG R2)
|
xpika/interpreter-haskell
|
Plugins/DiagramStuff.hs
|
gpl-3.0
| 488
| 0
| 11
| 78
| 128
| 76
| 52
| 13
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.