code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.DynamicWorkspaceOrder
-- Copyright : (c) Brent Yorgey 2009
-- License : BSD-style (see LICENSE)
--
-- Maintainer : <byorgey@gmail.com>
-- Stability : experimental
-- Portability : unportable
--
-- Remember a dynamically updateable ordering on workspaces, together
-- with tools for using this ordering with "XMonad.Actions.CycleWS"
-- and "XMonad.Hooks.DynamicLog".
--
-----------------------------------------------------------------------------
module XMonad.Actions.DynamicWorkspaceOrder
( -- * Usage
-- $usage
getWsCompareByOrder
, getSortByOrder
, swapWith
, moveTo
, moveToGreedy
, shiftTo
) where
import XMonad
import qualified XMonad.StackSet as W
import qualified XMonad.Util.ExtensibleState as XS
import XMonad.Util.WorkspaceCompare (WorkspaceCompare, WorkspaceSort, mkWsSort)
import XMonad.Actions.CycleWS (findWorkspace, WSType(..), Direction1D(..), doTo)
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Maybe (fromJust, fromMaybe)
import Data.Ord (comparing)
-- $usage
-- You can use this module by importing it into your ~\/.xmonad\/xmonad.hs file:
--
-- > import qualified XMonad.Actions.DynamicWorkspaceOrder as DO
--
-- Then add keybindings to swap the order of workspaces (these
-- examples use "XMonad.Util.EZConfig" emacs-style keybindings):
--
-- > , ("M-C-<R>", DO.swapWith Next NonEmptyWS)
-- > , ("M-C-<L>", DO.swapWith Prev NonEmptyWS)
--
-- See "XMonad.Actions.CycleWS" for information on the possible
-- arguments to 'swapWith'.
--
-- However, by itself this will do nothing; 'swapWith' does not change
-- the actual workspaces in any way. It simply keeps track of an
-- auxiliary ordering on workspaces. Anything which cares about the
-- order of workspaces must be updated to use the auxiliary ordering.
--
-- To change the order in which workspaces are displayed by
-- "XMonad.Hooks.DynamicLog", use 'getSortByOrder' in your
-- 'XMonad.Hooks.DynamicLog.ppSort' field, for example:
--
-- > ... dynamicLogWithPP $ byorgeyPP {
-- > ...
-- > , ppSort = DO.getSortByOrder
-- > ...
-- > }
--
-- To use workspace cycling commands like those from
-- "XMonad.Actions.CycleWS", use the versions of 'moveTo',
-- 'moveToGreedy', and 'shiftTo' exported by this module. For example:
--
-- > , ("M-S-<R>", DO.shiftTo Next HiddenNonEmptyWS)
-- > , ("M-S-<L>", DO.shiftTo Prev HiddenNonEmptyWS)
-- > , ("M-<R>", DO.moveTo Next HiddenNonEmptyWS)
-- > , ("M-<L>", DO.moveTo Prev HiddenNonEmptyWS)
--
-- For slight variations on these, use the source for examples and
-- tweak as desired.
-- | Extensible state storage for the workspace order.
data WSOrderStorage = WSO { unWSO :: Maybe (M.Map WorkspaceId Int) }
deriving (Typeable, Read, Show)
instance ExtensionClass WSOrderStorage where
initialValue = WSO Nothing
extensionType = PersistentExtension
-- | Lift a Map function to a function on WSOrderStorage.
withWSO :: (M.Map WorkspaceId Int -> M.Map WorkspaceId Int)
-> (WSOrderStorage -> WSOrderStorage)
withWSO f = WSO . fmap f . unWSO
-- | Update the ordering storage: initialize if it doesn't yet exist;
-- add newly created workspaces at the end as necessary.
updateOrder :: X ()
updateOrder = do
WSO mm <- XS.get
case mm of
Nothing -> do
-- initialize using ordering of workspaces from the user's config
ws <- asks (workspaces . config)
XS.put . WSO . Just . M.fromList $ zip ws [0..]
Just m -> do
-- check for new workspaces and add them at the end
curWs <- gets (S.fromList . map W.tag . W.workspaces . windowset)
let mappedWs = M.keysSet m
newWs = curWs `S.difference` mappedWs
nextIndex = 1 + maximum (-1 : M.elems m)
newWsIxs = zip (S.toAscList newWs) [nextIndex..]
XS.modify . withWSO . M.union . M.fromList $ newWsIxs
-- | A comparison function which orders workspaces according to the
-- stored dynamic ordering.
getWsCompareByOrder :: X WorkspaceCompare
getWsCompareByOrder = do
updateOrder
-- after the call to updateOrder we are guaranteed that the dynamic
-- workspace order is initialized and contains all existing
-- workspaces.
WSO (Just m) <- XS.get
return $ comparing (fromMaybe 1000 . flip M.lookup m)
-- | Sort workspaces according to the stored dynamic ordering.
getSortByOrder :: X WorkspaceSort
getSortByOrder = mkWsSort getWsCompareByOrder
-- | Swap the current workspace with another workspace in the stored
-- dynamic order.
swapWith :: Direction1D -> WSType -> X ()
swapWith dir which = findWorkspace getSortByOrder dir which 1 >>= swapWithCurrent
-- | Swap the given workspace with the current one.
swapWithCurrent :: WorkspaceId -> X ()
swapWithCurrent w = do
cur <- gets (W.currentTag . windowset)
swapOrder w cur
-- | Swap the two given workspaces in the dynamic order.
swapOrder :: WorkspaceId -> WorkspaceId -> X ()
swapOrder w1 w2 = do
io $ print (w1,w2)
WSO (Just m) <- XS.get
let [i1,i2] = map (fromJust . flip M.lookup m) [w1,w2]
XS.modify (withWSO (M.insert w1 i2 . M.insert w2 i1))
windows id -- force a status bar update
-- | View the next workspace of the given type in the given direction,
-- where \"next\" is determined using the dynamic workspace order.
moveTo :: Direction1D -> WSType -> X ()
moveTo dir t = doTo dir t getSortByOrder (windows . W.view)
-- | Same as 'moveTo', but using 'greedyView' instead of 'view'.
moveToGreedy :: Direction1D -> WSType -> X ()
moveToGreedy dir t = doTo dir t getSortByOrder (windows . W.greedyView)
-- | Shift the currently focused window to the next workspace of the
-- given type in the given direction, using the dynamic workspace order.
shiftTo :: Direction1D -> WSType -> X ()
shiftTo dir t = doTo dir t getSortByOrder (windows . W.shift)
|
MasseR/xmonadcontrib
|
XMonad/Actions/DynamicWorkspaceOrder.hs
|
bsd-3-clause
| 5,997
| 0
| 20
| 1,150
| 1,010
| 560
| 450
| 66
| 2
|
module Main where
import GHC
import Scion
import MonadUtils ( liftIO )
import qualified StringBuffer as SB
import Outputable
import HscTypes
import Data.Maybe
import Control.Monad
import System.Environment
main = runScion $ do
[working_dir, dist_dir] <- io $ getArgs
setWorkingDir working_dir
liftIO $ print working_dir
io $ print dist_dir
openCabalProject dist_dir
setDynFlagsFromCabal Library
setTargetsFromCabal Library
--load LoadAllTargets
flip foldModSummaries () $ \n ms -> do
io $ putStrLn $
showSDoc $ hang (ppr (ms_mod ms) <+> text (hscSourceString (ms_hsc_src ms)))
4 (ppr (ms_imps ms))
return ()
--liftIO $ print ("total", cs)
|
CristhianMotoche/scion
|
examples/GetImports.hs
|
bsd-3-clause
| 701
| 0
| 20
| 152
| 211
| 106
| 105
| 23
| 1
|
-- | Descripitons of items.
module Game.LambdaHack.Common.ItemDescription
( partItemN, partItem, partItemWs, partItemAW, partItemMediumAW, partItemWownW
, itemDesc, textAllAE, viewItem
) where
import Data.List
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as T
import qualified NLP.Miniutter.English as MU
import qualified Game.LambdaHack.Common.Color as Color
import qualified Game.LambdaHack.Common.Dice as Dice
import Game.LambdaHack.Common.EffectDescription
import Game.LambdaHack.Common.Flavour
import Game.LambdaHack.Common.Item
import Game.LambdaHack.Common.ItemStrongest
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.Msg
import Game.LambdaHack.Common.Time
import qualified Game.LambdaHack.Content.ItemKind as IK
-- | The part of speech describing the item parameterized by the number
-- of effects/aspects to show..
partItemN :: Int -> Int -> CStore -> Time -> ItemFull
-> (Bool, MU.Part, MU.Part)
partItemN fullInfo n c localTime itemFull =
let genericName = jname $ itemBase itemFull
in case itemDisco itemFull of
Nothing ->
let flav = flavourToName $ jflavour $ itemBase itemFull
in (False, MU.Text $ flav <+> genericName, "")
Just iDisco ->
let (toutN, it1) = case strengthFromEqpSlot IK.EqpSlotTimeout itemFull of
Nothing -> (0, [])
Just timeout ->
let timeoutTurns = timeDeltaScale (Delta timeTurn) timeout
charging startT = timeShift startT timeoutTurns > localTime
in (timeout, filter charging (itemTimer itemFull))
len = length it1
chargingAdj | toutN == 0 = "temporary"
| otherwise = "charging"
timer | len == 0 = ""
| itemK itemFull == 1 && len == 1 = "(" <> chargingAdj <> ")"
| otherwise = "(" <> tshow len <+> chargingAdj <> ")"
skipRecharging = fullInfo <= 4 && len >= itemK itemFull
effTs = filter (not . T.null)
$ textAllAE fullInfo skipRecharging c itemFull
ts = take n effTs
++ ["(...)" | length effTs > n]
++ [timer]
isUnique aspects = IK.Unique `elem` aspects
unique = case iDisco of
ItemDisco{itemAE=Just ItemAspectEffect{jaspects}} ->
isUnique jaspects
ItemDisco{itemKind} ->
isUnique $ IK.iaspects itemKind
capName = if unique
then MU.Capitalize $ MU.Text genericName
else MU.Text genericName
in (unique, capName, MU.Phrase $ map MU.Text ts)
-- | The part of speech describing the item.
partItem :: CStore -> Time -> ItemFull -> (Bool, MU.Part, MU.Part)
partItem = partItemN 5 4
textAllAE :: Int -> Bool -> CStore -> ItemFull -> [Text]
textAllAE fullInfo skipRecharging cstore ItemFull{itemBase, itemDisco} =
let features | fullInfo >= 9 = map featureToSuff $ sort $ jfeature itemBase
| otherwise = []
in case itemDisco of
Nothing -> features
Just ItemDisco{itemKind, itemAE} ->
let periodicAspect :: IK.Aspect a -> Bool
periodicAspect IK.Periodic = True
periodicAspect _ = False
timeoutAspect :: IK.Aspect a -> Bool
timeoutAspect IK.Timeout{} = True
timeoutAspect _ = False
noEffect :: IK.Effect -> Bool
noEffect IK.NoEffect{} = True
noEffect _ = False
hurtEffect :: IK.Effect -> Bool
hurtEffect (IK.Hurt _) = True
hurtEffect (IK.Burn _) = True
hurtEffect _ = False
notDetail :: IK.Effect -> Bool
notDetail IK.Explode{} = fullInfo >= 6
notDetail _ = True
active = cstore `elem` [CEqp, COrgan]
|| cstore == CGround && isJust (strengthEqpSlot itemBase)
splitAE :: (Num a, Show a, Ord a)
=> (a -> Text)
-> [IK.Aspect a] -> (IK.Aspect a -> Text)
-> [IK.Effect] -> (IK.Effect -> Text)
-> [Text]
splitAE reduce_a aspects ppA effects ppE =
let mperiodic = find periodicAspect aspects
mtimeout = find timeoutAspect aspects
mnoEffect = find noEffect effects
restAs = sort aspects
(hurtEs, restEs) = partition hurtEffect $ sort
$ filter notDetail effects
aes = if active
then map ppA restAs ++ map ppE restEs
else map ppE restEs ++ map ppA restAs
rechargingTs = T.intercalate (T.singleton ' ')
$ filter (not . T.null)
$ map ppE $ stripRecharging restEs
onSmashTs = T.intercalate (T.singleton ' ')
$ filter (not . T.null)
$ map ppE $ stripOnSmash restEs
durable = IK.Durable `elem` jfeature itemBase
periodicOrTimeout = case mperiodic of
_ | skipRecharging || T.null rechargingTs -> ""
Just IK.Periodic ->
case mtimeout of
Just (IK.Timeout 0) | not durable ->
"(each turn until gone:"
<+> rechargingTs <> ")"
Just (IK.Timeout t) ->
"(every" <+> reduce_a t <> ":"
<+> rechargingTs <> ")"
_ -> ""
_ -> case mtimeout of
Just (IK.Timeout t) ->
"(timeout" <+> reduce_a t <> ":"
<+> rechargingTs <> ")"
_ -> ""
onSmash = if T.null onSmashTs then ""
else "(on smash:" <+> onSmashTs <> ")"
noEff = case mnoEffect of
Just (IK.NoEffect t) -> [t]
_ -> []
in noEff ++ if fullInfo >= 5 || fullInfo >= 2 && null noEff
then [periodicOrTimeout] ++ map ppE hurtEs ++ aes
++ [onSmash | fullInfo >= 7]
else map ppE hurtEs
aets = case itemAE of
Just ItemAspectEffect{jaspects, jeffects} ->
splitAE tshow
jaspects aspectToSuffix
jeffects effectToSuffix
Nothing ->
splitAE (maybe "?" tshow . Dice.reduceDice)
(IK.iaspects itemKind) kindAspectToSuffix
(IK.ieffects itemKind) kindEffectToSuffix
in aets ++ features
-- TODO: use kit
partItemWs :: Int -> CStore -> Time -> ItemFull -> MU.Part
partItemWs count c localTime itemFull =
let (unique, name, stats) = partItem c localTime itemFull
in if unique && count == 1
then MU.Phrase ["the", name, stats]
else MU.Phrase [MU.CarWs count name, stats]
partItemAW :: CStore -> Time -> ItemFull -> MU.Part
partItemAW c localTime itemFull =
let (unique, name, stats) = partItemN 4 4 c localTime itemFull
in if unique
then MU.Phrase ["the", name, stats]
else MU.AW $ MU.Phrase [name, stats]
partItemMediumAW :: CStore -> Time -> ItemFull -> MU.Part
partItemMediumAW c localTime itemFull =
let (unique, name, stats) = partItemN 5 100 c localTime itemFull
in if unique
then MU.Phrase ["the", name, stats]
else MU.AW $ MU.Phrase [name, stats]
partItemWownW :: MU.Part -> CStore -> Time -> ItemFull -> MU.Part
partItemWownW partA c localTime itemFull =
let (_, name, stats) = partItemN 4 4 c localTime itemFull
in MU.WownW partA $ MU.Phrase [name, stats]
itemDesc :: CStore -> Time -> ItemFull -> Overlay
itemDesc c localTime itemFull =
let (_, name, stats) = partItemN 10 100 c localTime itemFull
nstats = makePhrase [name, stats]
desc = case itemDisco itemFull of
Nothing -> "This item is as unremarkable as can be."
Just ItemDisco{itemKind} -> IK.idesc itemKind
weight = jweight (itemBase itemFull)
(scaledWeight, unitWeight)
| weight > 1000 =
(tshow $ fromIntegral weight / (1000 :: Double), "kg")
| weight > 0 = (tshow weight, "g")
| otherwise = ("", "")
ln = abs $ fromEnum $ jlid (itemBase itemFull)
colorSymbol = uncurry (flip Color.AttrChar) (viewItem $ itemBase itemFull)
f = Color.AttrChar Color.defAttr
lxsize = fst normalLevelBound + 1 -- TODO
blurb =
"D" -- dummy
<+> nstats
<> ":"
<+> desc
<+> makeSentence ["Weighs", MU.Text scaledWeight <> unitWeight]
<+> makeSentence ["First found on level", MU.Text $ tshow ln]
splitBlurb = splitText lxsize blurb
attrBlurb = map (map f . T.unpack) splitBlurb
in encodeOverlay $ (colorSymbol : tail (head attrBlurb)) : tail attrBlurb
viewItem :: Item -> (Char, Color.Attr)
viewItem item = ( jsymbol item
, Color.defAttr {Color.fg = flavourToColor $ jflavour item} )
|
Concomitant/LambdaHack
|
Game/LambdaHack/Common/ItemDescription.hs
|
bsd-3-clause
| 9,060
| 0
| 28
| 3,070
| 2,696
| 1,396
| 1,300
| -1
| -1
|
{-# LANGUAGE QuasiQuotes #-}
import JSON
main :: IO ()
main = do
let twelve = 12::Int; name = "mr_konn"
print $ [js| {ident: `twelve, name: `name} |]
print $ [js| {ident: `twelve, name `name } |] -- cause a parse error.
|
nushio3/Paraiso
|
attic/QuasiQuote/MainJsonSyntaxError.hs
|
bsd-3-clause
| 228
| 0
| 9
| 50
| 61
| 36
| 25
| 7
| 1
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Defines tests of STG programs that are based on marshalling a value into
-- the STG, forcing a value, and marshalling that value out again for comparison
-- with a reference.
module Test.Machine.Evaluate.TestTemplates.MarshalledValue (
MarshalledValueTestSpec(..),
MarshalSourceSpec(..),
defSpec,
marshalledValueTest,
) where
import Data.List.NonEmpty (NonEmpty (..))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Text.Prettyprint.Doc
import Data.Text.Prettyprint.Doc.Render.Text
import Stg.Language
import Stg.Language.Prettyprint
import Stg.Machine
import Stg.Machine.Types
import Stg.Marshal
import Stg.Parser.QuasiQuoter (stg)
import Test.Orphans ()
import Test.Tasty
import Test.Tasty.QuickCheck
-- | Specifies a test that is based on marshalling a value out of the STG and
-- comparing it to a known value.
data MarshalledValueTestSpec input output = MarshalledValueTestSpec
{ testName :: Text
-- ^ The reference function's name. Used only for display purposes.
, failPredicate :: StgState -> Bool
-- ^ Fail if this predicate holds. This can be used to constrain the
-- heap size during the test, for example.
, sourceSpec :: input -> MarshalSourceSpec output
-- * STG program to run
, maxSteps :: Integer
-- ^ Maximum number of steps to take
, failWithInfo :: Bool
-- ^ Print program code and final state on test failure?
}
data MarshalSourceSpec output = MarshalSourceSpec
{ resultVar :: Var -- ^ value to observe the value of, e.g. @main@
, expectedValue :: output -- ^ expected result value
, source :: Program -- ^ STG program to run
}
defSpec :: MarshalledValueTestSpec input b
defSpec = MarshalledValueTestSpec
{ testName = "Default Haskell reference test spec template"
, maxSteps = 1024
, failWithInfo = False
, failPredicate = const False
, sourceSpec = \_ -> MarshalSourceSpec
{ resultVar = "main"
, expectedValue = error "No expected value generator set in test"
, source = [stg| main = \ -> DummySource |] }}
marshalledValueTest
:: forall input output.
( Show input, Arbitrary input
, Eq output, Show output, FromStg output, PrettyStgi output )
=> MarshalledValueTestSpec input output
-> TestTree
marshalledValueTest testSpec = testProperty (T.unpack (testName testSpec)) test
where
test :: ( Show input, Arbitrary input
, Eq output, Show output, FromStg output, PrettyStgi output )
=> input
-> Property
test input =
let program = initialState "main" (source (sourceSpec testSpec input))
states = evalsUntil
(RunForMaxSteps (maxSteps testSpec))
(HaltIf (const False))
(PerformGc (const Nothing))
program
verifyLoop (state :| _)
| failPredicate testSpec state =
fail_failPredicateTrue testSpec input state
verifyLoop (state :| rest) = case fromStg state (resultVar (sourceSpec testSpec input)) of
Left err -> case err of
TypeMismatch -> fail_typeMismatch testSpec input state
IsBlackhole -> continue state rest
IsWrongLambdaType LambdaFun -> fail_functionValue testSpec input state
IsWrongLambdaType LambdaThunk -> continue state rest
IsWrongLambdaType LambdaCon -> error
"Critial error in test: found a constructor, expected\
\ a constructor, but still ran into the failure case\
\ somehow. Please report this as a bug."
BadArity -> fail_conArity testSpec input state
NotFound{} -> fail_notFound testSpec input state
AddrNotOnHeap -> fail_addrNotOnHeap testSpec input state
NoConstructorMatch -> fail_NoConstructorMatch testSpec input state
Right actualValue -> assertEqual actualValue testSpec input state
continue lastState = \case
[] -> fail_valueNotFound testSpec input lastState
(x:xs) -> verifyLoop (x :| xs)
in verifyLoop states
assertEqual
:: forall input output. (Eq output, PrettyStgi output)
=> output
-> MarshalledValueTestSpec input output
-> input
-> StgState
-> Property
assertEqual
actual
testSpec
input
finalState
= counterexample (failText expected) (actual == expected)
where
expected :: output
expected = expectedValue (sourceSpec testSpec input)
failText :: PrettyStgi a => a -> String
failText ex = (T.unpack . renderStrict . layoutPretty defaultLayoutOptions . vsep)
[ "Machine produced an invalid result."
, "Expected:" <+> (prettyStgi ex :: Doc StgiAnn)
, "Actual: " <+> (prettyStgi actual :: Doc StgiAnn)
, if failWithInfo testSpec
then vsep
[ hang 4 (vsep ["Program:", prettyStgi (source (sourceSpec testSpec input))])
, hang 4 (vsep ["Final state:", prettyStgi finalState]) ]
else failWithInfoInfoText ]
failWithInfoInfoText :: Doc ann
failWithInfoInfoText = "Run test case with failWithInfo to see the final state."
fail_template
:: Doc StgiAnn
-> MarshalledValueTestSpec input a
-> input
-> StgState
-> Property
fail_template
failMessage
testSpec
input
finalState
= counterexample failText False
where
failText = (T.unpack . renderStrict . layoutPretty defaultLayoutOptions . vsep)
[ failMessage
, "Final machine state info:"
<+> (prettyStgi (stgInfo finalState) :: Doc StgiAnn)
, if failWithInfo testSpec
then vsep
[ hang 4 (vsep ["Program:", prettyStgi (source (sourceSpec testSpec input)) :: Doc StgiAnn])
, hang 4 (vsep ["Final state:", prettyStgi finalState :: Doc StgiAnn]) ]
else failWithInfoInfoText ]
fail_failPredicateTrue, fail_valueNotFound, fail_typeMismatch, fail_conArity,
fail_notFound, fail_addrNotOnHeap, fail_NoConstructorMatch, fail_functionValue
:: MarshalledValueTestSpec a b -> a -> StgState -> Property
fail_failPredicateTrue = fail_template "Failure predicate held for an intemediate state"
fail_valueNotFound = fail_template "None of the machine states produced a (marshallable)\
\ value to compare the expected value to"
fail_typeMismatch = fail_template "Type mismatch in input/expected output"
fail_conArity = fail_template "Bad constructor arity in created value"
fail_notFound = fail_template "Variable not found"
fail_addrNotOnHeap = fail_template "Address not found on heap"
fail_NoConstructorMatch = fail_template "No constructor match"
fail_functionValue = fail_template "Function value encountered; can only do algebraic"
|
quchen/stg
|
test/Testsuite/Test/Machine/Evaluate/TestTemplates/MarshalledValue.hs
|
bsd-3-clause
| 7,356
| 0
| 20
| 2,101
| 1,393
| 755
| 638
| 141
| 12
|
{-# LANGUAGE CPP, GADTs #-}
-- See Note [Deprecations in Hoopl] in Hoopl module
{-# OPTIONS_GHC -fno-warn-warnings-deprecations #-}
module CmmBuildInfoTables
( CAFSet, CAFEnv, cafAnal
, doSRTs, TopSRT, emptySRT, isEmptySRT, srtToData )
where
#include "HsVersions.h"
import Hoopl
import Digraph
import BlockId
import Bitmap
import CLabel
import PprCmmDecl ()
import Cmm
import CmmUtils
import CmmInfo
import Data.List
import DynFlags
import Maybes
import Outputable
import SMRep
import UniqSupply
import Util
import PprCmm()
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Monad
import qualified Prelude as P
import Prelude hiding (succ)
foldSet :: (a -> b -> b) -> b -> Set a -> b
foldSet = Set.foldr
-----------------------------------------------------------------------
-- SRTs
{- EXAMPLE
f = \x. ... g ...
where
g = \y. ... h ... c1 ...
h = \z. ... c2 ...
c1 & c2 are CAFs
g and h are local functions, but they have no static closures. When
we generate code for f, we start with a CmmGroup of four CmmDecls:
[ f_closure, f_entry, g_entry, h_entry ]
we process each CmmDecl separately in cpsTop, giving us a list of
CmmDecls. e.g. for f_entry, we might end up with
[ f_entry, f1_ret, f2_proc ]
where f1_ret is a return point, and f2_proc is a proc-point. We have
a CAFSet for each of these CmmDecls, let's suppose they are
[ f_entry{g_closure}, f1_ret{g_closure}, f2_proc{} ]
[ g_entry{h_closure, c1_closure} ]
[ h_entry{c2_closure} ]
Now, note that we cannot use g_closure and h_closure in an SRT,
because there are no static closures corresponding to these functions.
So we have to flatten out the structure, replacing g_closure and
h_closure with their contents:
[ f_entry{c2_closure, c1_closure}, f1_ret{c2_closure,c1_closure}, f2_proc{} ]
[ g_entry{c2_closure, c1_closure} ]
[ h_entry{c2_closure} ]
This is what flattenCAFSets is doing.
-}
-----------------------------------------------------------------------
-- Finding the CAFs used by a procedure
type CAFSet = Set CLabel
type CAFEnv = BlockEnv CAFSet
-- First, an analysis to find live CAFs.
cafLattice :: DataflowLattice CAFSet
cafLattice = DataflowLattice "live cafs" Set.empty add
where add _ (OldFact old) (NewFact new) = case old `Set.union` new of
new' -> (changeIf $ Set.size new' > Set.size old, new')
cafTransfers :: BwdTransfer CmmNode CAFSet
cafTransfers = mkBTransfer3 first middle last
where first _ live = live
middle m live = foldExpDeep addCaf m live
last l live = foldExpDeep addCaf l (joinOutFacts cafLattice l live)
addCaf e set = case e of
CmmLit (CmmLabel c) -> add c set
CmmLit (CmmLabelOff c _) -> add c set
CmmLit (CmmLabelDiffOff c1 c2 _) -> add c1 $ add c2 set
_ -> set
add l s = if hasCAF l then Set.insert (toClosureLbl l) s
else s
cafAnal :: CmmGraph -> CAFEnv
cafAnal g = dataflowAnalBwd g [] $ analBwd cafLattice cafTransfers
-----------------------------------------------------------------------
-- Building the SRTs
-- Description of the SRT for a given module.
-- Note that this SRT may grow as we greedily add new CAFs to it.
data TopSRT = TopSRT { lbl :: CLabel
, next_elt :: Int -- the next entry in the table
, rev_elts :: [CLabel]
, elt_map :: Map CLabel Int }
-- map: CLabel -> its last entry in the table
instance Outputable TopSRT where
ppr (TopSRT lbl next elts eltmap) =
text "TopSRT:" <+> ppr lbl
<+> ppr next
<+> ppr elts
<+> ppr eltmap
emptySRT :: MonadUnique m => m TopSRT
emptySRT =
do top_lbl <- getUniqueM >>= \ u -> return $ mkTopSRTLabel u
return TopSRT { lbl = top_lbl, next_elt = 0, rev_elts = [], elt_map = Map.empty }
isEmptySRT :: TopSRT -> Bool
isEmptySRT srt = null (rev_elts srt)
cafMember :: TopSRT -> CLabel -> Bool
cafMember srt lbl = Map.member lbl (elt_map srt)
cafOffset :: TopSRT -> CLabel -> Maybe Int
cafOffset srt lbl = Map.lookup lbl (elt_map srt)
addCAF :: CLabel -> TopSRT -> TopSRT
addCAF caf srt =
srt { next_elt = last + 1
, rev_elts = caf : rev_elts srt
, elt_map = Map.insert caf last (elt_map srt) }
where last = next_elt srt
srtToData :: TopSRT -> CmmGroup
srtToData srt = [CmmData sec (Statics (lbl srt) tbl)]
where tbl = map (CmmStaticLit . CmmLabel) (reverse (rev_elts srt))
sec = Section RelocatableReadOnlyData (lbl srt)
-- Once we have found the CAFs, we need to do two things:
-- 1. Build a table of all the CAFs used in the procedure.
-- 2. Compute the C_SRT describing the subset of CAFs live at each procpoint.
--
-- When building the local view of the SRT, we first make sure that all the CAFs are
-- in the SRT. Then, if the number of CAFs is small enough to fit in a bitmap,
-- we make sure they're all close enough to the bottom of the table that the
-- bitmap will be able to cover all of them.
buildSRT :: DynFlags -> TopSRT -> CAFSet -> UniqSM (TopSRT, Maybe CmmDecl, C_SRT)
buildSRT dflags topSRT cafs =
do let
-- For each label referring to a function f without a static closure,
-- replace it with the CAFs that are reachable from f.
sub_srt topSRT localCafs =
let cafs = Set.elems localCafs
mkSRT topSRT =
do localSRTs <- procpointSRT dflags (lbl topSRT) (elt_map topSRT) cafs
return (topSRT, localSRTs)
in if length cafs > maxBmpSize dflags then
mkSRT (foldl add_if_missing topSRT cafs)
else -- make sure all the cafs are near the bottom of the srt
mkSRT (add_if_too_far topSRT cafs)
add_if_missing srt caf =
if cafMember srt caf then srt else addCAF caf srt
-- If a CAF is more than maxBmpSize entries from the young end of the
-- SRT, then we add it to the SRT again.
-- (Note: Not in the SRT => infinitely far.)
add_if_too_far srt@(TopSRT {elt_map = m}) cafs =
add srt (sortBy farthestFst cafs)
where
farthestFst x y = case (Map.lookup x m, Map.lookup y m) of
(Nothing, Nothing) -> EQ
(Nothing, Just _) -> LT
(Just _, Nothing) -> GT
(Just d, Just d') -> compare d' d
add srt [] = srt
add srt@(TopSRT {next_elt = next}) (caf : rst) =
case cafOffset srt caf of
Just ix -> if next - ix > maxBmpSize dflags then
add (addCAF caf srt) rst
else srt
Nothing -> add (addCAF caf srt) rst
(topSRT, subSRTs) <- sub_srt topSRT cafs
let (sub_tbls, blockSRTs) = subSRTs
return (topSRT, sub_tbls, blockSRTs)
-- Construct an SRT bitmap.
-- Adapted from simpleStg/SRT.hs, which expects Id's.
procpointSRT :: DynFlags -> CLabel -> Map CLabel Int -> [CLabel] ->
UniqSM (Maybe CmmDecl, C_SRT)
procpointSRT _ _ _ [] =
return (Nothing, NoC_SRT)
procpointSRT dflags top_srt top_table entries =
do (top, srt) <- bitmap `seq` to_SRT dflags top_srt offset len bitmap
return (top, srt)
where
ints = map (expectJust "constructSRT" . flip Map.lookup top_table) entries
sorted_ints = sort ints
offset = head sorted_ints
bitmap_entries = map (subtract offset) sorted_ints
len = P.last bitmap_entries + 1
bitmap = intsToBitmap dflags len bitmap_entries
maxBmpSize :: DynFlags -> Int
maxBmpSize dflags = widthInBits (wordWidth dflags) `div` 2
-- Adapted from codeGen/StgCmmUtils, which converts from SRT to C_SRT.
to_SRT :: DynFlags -> CLabel -> Int -> Int -> Bitmap -> UniqSM (Maybe CmmDecl, C_SRT)
to_SRT dflags top_srt off len bmp
| len > maxBmpSize dflags || bmp == [toStgWord dflags (fromStgHalfWord (srtEscape dflags))]
= do id <- getUniqueM
let srt_desc_lbl = mkLargeSRTLabel id
section = Section RelocatableReadOnlyData srt_desc_lbl
tbl = CmmData section $
Statics srt_desc_lbl $ map CmmStaticLit
( cmmLabelOffW dflags top_srt off
: mkWordCLit dflags (fromIntegral len)
: map (mkStgWordCLit dflags) bmp)
return (Just tbl, C_SRT srt_desc_lbl 0 (srtEscape dflags))
| otherwise
= return (Nothing, C_SRT top_srt off (toStgHalfWord dflags (fromStgWord (head bmp))))
-- The fromIntegral converts to StgHalfWord
-- Gather CAF info for a procedure, but only if the procedure
-- doesn't have a static closure.
-- (If it has a static closure, it will already have an SRT to
-- keep its CAFs live.)
-- Any procedure referring to a non-static CAF c must keep live
-- any CAF that is reachable from c.
localCAFInfo :: CAFEnv -> CmmDecl -> (CAFSet, Maybe CLabel)
localCAFInfo _ (CmmData _ _) = (Set.empty, Nothing)
localCAFInfo cafEnv proc@(CmmProc _ top_l _ (CmmGraph {g_entry=entry})) =
case topInfoTable proc of
Just (CmmInfoTable { cit_rep = rep })
| not (isStaticRep rep) && not (isStackRep rep)
-> (cafs, Just (toClosureLbl top_l))
_other -> (cafs, Nothing)
where
cafs = expectJust "maybeBindCAFs" $ mapLookup entry cafEnv
-- Once we have the local CAF sets for some (possibly) mutually
-- recursive functions, we can create an environment mapping
-- each function to its set of CAFs. Note that a CAF may
-- be a reference to a function. If that function f does not have
-- a static closure, then we need to refer specifically
-- to the set of CAFs used by f. Of course, the set of CAFs
-- used by f must be included in the local CAF sets that are input to
-- this function. To minimize lookup time later, we return
-- the environment with every reference to f replaced by its set of CAFs.
-- To do this replacement efficiently, we gather strongly connected
-- components, then we sort the components in topological order.
mkTopCAFInfo :: [(CAFSet, Maybe CLabel)] -> Map CLabel CAFSet
mkTopCAFInfo localCAFs = foldl addToTop Map.empty g
where
addToTop env (AcyclicSCC (l, cafset)) =
Map.insert l (flatten env cafset) env
addToTop env (CyclicSCC nodes) =
let (lbls, cafsets) = unzip nodes
cafset = foldr Set.delete (foldl Set.union Set.empty cafsets) lbls
in foldl (\env l -> Map.insert l (flatten env cafset) env) env lbls
g = stronglyConnCompFromEdgedVerticesOrd
[ ((l,cafs), l, Set.elems cafs) | (cafs, Just l) <- localCAFs ]
flatten :: Map CLabel CAFSet -> CAFSet -> CAFSet
flatten env cafset = foldSet (lookup env) Set.empty cafset
where
lookup env caf cafset' =
case Map.lookup caf env of
Just cafs -> foldSet Set.insert cafset' cafs
Nothing -> Set.insert caf cafset'
bundle :: Map CLabel CAFSet
-> (CAFEnv, CmmDecl)
-> (CAFSet, Maybe CLabel)
-> (BlockEnv CAFSet, CmmDecl)
bundle flatmap (env, decl@(CmmProc infos _lbl _ g)) (closure_cafs, mb_lbl)
= ( mapMapWithKey get_cafs (info_tbls infos), decl )
where
entry = g_entry g
entry_cafs
| Just l <- mb_lbl = expectJust "bundle" $ Map.lookup l flatmap
| otherwise = flatten flatmap closure_cafs
get_cafs l _
| l == entry = entry_cafs
| Just info <- mapLookup l env = flatten flatmap info
| otherwise = Set.empty
-- the label might not be in the env if the code corresponding to
-- this info table was optimised away (perhaps because it was
-- unreachable). In this case it doesn't matter what SRT we
-- infer, since the info table will not appear in the generated
-- code. See #9329.
bundle _flatmap (_, decl) _
= ( mapEmpty, decl )
flattenCAFSets :: [(CAFEnv, [CmmDecl])] -> [(BlockEnv CAFSet, CmmDecl)]
flattenCAFSets cpsdecls = zipWith (bundle flatmap) zipped localCAFs
where
zipped = [ (env,decl) | (env,decls) <- cpsdecls, decl <- decls ]
localCAFs = unzipWith localCAFInfo zipped
flatmap = mkTopCAFInfo localCAFs -- transitive closure of localCAFs
doSRTs :: DynFlags
-> TopSRT
-> [(CAFEnv, [CmmDecl])]
-> IO (TopSRT, [CmmDecl])
doSRTs dflags topSRT tops
= do
let caf_decls = flattenCAFSets tops
us <- mkSplitUniqSupply 'u'
let (topSRT', gs') = initUs_ us $ foldM setSRT (topSRT, []) caf_decls
return (topSRT', reverse gs' {- Note [reverse gs] -})
where
setSRT (topSRT, rst) (caf_map, decl@(CmmProc{})) = do
(topSRT, srt_tables, srt_env) <- buildSRTs dflags topSRT caf_map
let decl' = updInfoSRTs srt_env decl
return (topSRT, decl': srt_tables ++ rst)
setSRT (topSRT, rst) (_, decl) =
return (topSRT, decl : rst)
buildSRTs :: DynFlags -> TopSRT -> BlockEnv CAFSet
-> UniqSM (TopSRT, [CmmDecl], BlockEnv C_SRT)
buildSRTs dflags top_srt caf_map
= foldM doOne (top_srt, [], mapEmpty) (mapToList caf_map)
where
doOne (top_srt, decls, srt_env) (l, cafs)
= do (top_srt, mb_decl, srt) <- buildSRT dflags top_srt cafs
return ( top_srt, maybeToList mb_decl ++ decls
, mapInsert l srt srt_env )
{-
- In each CmmDecl there is a mapping from BlockId -> CmmInfoTable
- The one corresponding to g_entry is the closure info table, the
rest are continuations.
- Each one needs an SRT.
- We get the CAFSet for each one from the CAFEnv
- flatten gives us
[(BlockEnv CAFSet, CmmDecl)]
-
-}
{- Note [reverse gs]
It is important to keep the code blocks in the same order,
otherwise binary sizes get slightly bigger. I'm not completely
sure why this is, perhaps the assembler generates bigger jump
instructions for forward refs. --SDM
-}
updInfoSRTs :: BlockEnv C_SRT -> CmmDecl -> CmmDecl
updInfoSRTs srt_env (CmmProc top_info top_l live g) =
CmmProc (top_info {info_tbls = mapMapWithKey updInfoTbl (info_tbls top_info)}) top_l live g
where updInfoTbl l info_tbl
= info_tbl { cit_srt = expectJust "updInfo" $ mapLookup l srt_env }
updInfoSRTs _ t = t
|
snoyberg/ghc
|
compiler/cmm/CmmBuildInfoTables.hs
|
bsd-3-clause
| 14,357
| 0
| 19
| 3,776
| 3,412
| 1,784
| 1,628
| 216
| 9
|
-- This is a quick hack for uploading packages to Hackage.
-- See http://hackage.haskell.org/trac/hackage/wiki/CabalUpload
module Distribution.Client.Upload (check, upload, report) where
import Distribution.Client.Types (Username(..), Password(..),Repo(..),RemoteRepo(..))
import Distribution.Client.HttpUtils
( HttpTransport(..), remoteRepoTryUpgradeToHttps )
import Distribution.Simple.Utils (notice, warn, info, die)
import Distribution.Verbosity (Verbosity)
import Distribution.Text (display)
import Distribution.Client.Config
import qualified Distribution.Client.BuildReports.Anonymous as BuildReport
import qualified Distribution.Client.BuildReports.Upload as BuildReport
import Network.URI (URI(uriPath), parseURI)
import System.IO (hFlush, stdin, stdout, hGetEcho, hSetEcho)
import Control.Exception (bracket)
import System.FilePath ((</>), takeExtension)
import qualified System.FilePath.Posix as FilePath.Posix ((</>))
import System.Directory
import Control.Monad (forM_, when)
type Auth = Maybe (String, String)
checkURI :: URI
Just checkURI = parseURI "http://hackage.haskell.org/cgi-bin/hackage-scripts/check-pkg"
upload :: HttpTransport -> Verbosity -> [Repo] -> Maybe Username -> Maybe Password -> [FilePath] -> IO ()
upload transport verbosity repos mUsername mPassword paths = do
targetRepo <-
case [ remoteRepo | Left remoteRepo <- map repoKind repos ] of
[] -> die $ "Cannot upload. No remote repositories are configured."
rs -> remoteRepoTryUpgradeToHttps transport (last rs)
let targetRepoURI = remoteRepoURI targetRepo
rootIfEmpty x = if null x then "/" else x
uploadURI = targetRepoURI {
uriPath = rootIfEmpty (uriPath targetRepoURI) FilePath.Posix.</> "upload"
}
Username username <- maybe promptUsername return mUsername
Password password <- maybe promptPassword return mPassword
let auth = Just (username,password)
flip mapM_ paths $ \path -> do
notice verbosity $ "Uploading " ++ path ++ "... "
handlePackage transport verbosity uploadURI auth path
promptUsername :: IO Username
promptUsername = do
putStr "Hackage username: "
hFlush stdout
fmap Username getLine
promptPassword :: IO Password
promptPassword = do
putStr "Hackage password: "
hFlush stdout
-- save/restore the terminal echoing status
passwd <- bracket (hGetEcho stdin) (hSetEcho stdin) $ \_ -> do
hSetEcho stdin False -- no echoing for entering the password
fmap Password getLine
putStrLn ""
return passwd
report :: Verbosity -> [Repo] -> Maybe Username -> Maybe Password -> IO ()
report verbosity repos mUsername mPassword = do
Username username <- maybe promptUsername return mUsername
Password password <- maybe promptPassword return mPassword
let auth = (username,password)
forM_ repos $ \repo -> case repoKind repo of
Left remoteRepo
-> do dotCabal <- defaultCabalDir
let srcDir = dotCabal </> "reports" </> remoteRepoName remoteRepo
-- We don't want to bomb out just because we haven't built any packages from this repo yet
srcExists <- doesDirectoryExist srcDir
when srcExists $ do
contents <- getDirectoryContents srcDir
forM_ (filter (\c -> takeExtension c == ".log") contents) $ \logFile ->
do inp <- readFile (srcDir </> logFile)
let (reportStr, buildLog) = read inp :: (String,String)
case BuildReport.parse reportStr of
Left errs -> do warn verbosity $ "Errors: " ++ errs -- FIXME
Right report' ->
do info verbosity $ "Uploading report for " ++ display (BuildReport.package report')
BuildReport.uploadReports verbosity auth (remoteRepoURI remoteRepo) [(report', Just buildLog)]
return ()
Right{} -> return ()
check :: HttpTransport -> Verbosity -> [FilePath] -> IO ()
check transport verbosity paths = do
flip mapM_ paths $ \path -> do
notice verbosity $ "Checking " ++ path ++ "... "
handlePackage transport verbosity checkURI Nothing path
handlePackage :: HttpTransport -> Verbosity -> URI -> Auth
-> FilePath -> IO ()
handlePackage transport verbosity uri auth path =
do resp <- postHttpFile transport verbosity uri path auth
case resp of
(200,_) -> do notice verbosity "Ok"
(code,err) -> do notice verbosity $ "Error uploading " ++ path ++ ": "
++ "http code " ++ show code ++ "\n"
++ err
|
enolan/cabal
|
cabal-install/Distribution/Client/Upload.hs
|
bsd-3-clause
| 4,804
| 0
| 30
| 1,264
| 1,298
| 660
| 638
| 86
| 3
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="sr-SP">
<title>Passive Scan Rules | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/pscanrules/src/main/javahelp/org/zaproxy/zap/extension/pscanrules/resources/help_sr_SP/helpset_sr_SP.hs
|
apache-2.0
| 979
| 78
| 66
| 160
| 415
| 210
| 205
| -1
| -1
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="id-ID">
<title>Menu Online | Eksistensi ZAP</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Kandungan</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Penunjuk</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Telusuri</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Kesukaan</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/onlineMenu/src/main/javahelp/org/zaproxy/zap/extension/onlineMenu/resources/help_id_ID/helpset_id_ID.hs
|
apache-2.0
| 978
| 78
| 66
| 159
| 413
| 209
| 204
| -1
| -1
|
module RmOneParameter.A1 where
import RmOneParameter.D1
sumSq xs ys= sum (map sq xs) + sumSquares xs
main = sumSq [1..4]
|
RefactoringTools/HaRe
|
test/testdata/RmOneParameter/A1.expected.hs
|
bsd-3-clause
| 125
| 0
| 8
| 23
| 52
| 27
| 25
| 4
| 1
|
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
--
-- Module : IDE.Command.VCS.SVN
-- Copyright : 2007-2011 Juergen Nicklisch-Franken, Hamish Mackenzie
-- License : GPL Nothing
--
-- Maintainer : maintainer@leksah.org
-- Stability : provisional
-- Portability :
--
-- | TODO use new runActionWithContext
--
-----------------------------------------------------------------------------
module IDE.Command.VCS.SVN (
commitAction
,updateAction
,viewLogAction
,mkSVNActions
) where
import IDE.Core.Types
import IDE.Core.State
import qualified IDE.Command.VCS.Common.Helper as Helper
import qualified IDE.Command.VCS.Types as Types
import qualified VCSGui.Common as VCSGUI
import qualified VCSGui.Svn as GUISvn
import qualified VCSWrapper.Svn as Wrapper.Svn
import qualified VCSWrapper.Common as Wrapper
import Graphics.UI.Gtk.ActionMenuToolbar.UIManager(MergeId)
import Control.Monad.Reader(liftIO,ask,lift)
import Data.IORef(atomicModifyIORef, IORef)
import Data.Either
import Data.Text (Text)
commitAction :: Types.VCSAction ()
commitAction = do
((_,_,mbMergeTool),package) <- ask
ide <- Types.askIDERef
createSVNActionFromContext $ GUISvn.showCommitGUI $ Helper.eMergeToolSetter ide package mbMergeTool
updateAction :: Types.VCSAction ()
updateAction = do
((_,_,mbMergeTool),package) <- ask
ideRef <- Types.askIDERef
createSVNActionFromContext $ GUISvn.showUpdateGUI $ Helper.eMergeToolSetter ideRef package mbMergeTool
viewLogAction :: Types.VCSAction ()
viewLogAction = createSVNActionFromContext GUISvn.showLogGUI
mkSVNActions :: [(Text, Types.VCSAction ())]
mkSVNActions = [
("_Commit", commitAction)
,("_View Log", viewLogAction)
,("_Update", updateAction)
]
--HELPERS
createSVNActionFromContext :: (Either GUISvn.Handler (Maybe Text)
-> Wrapper.Ctx())
-> Types.VCSAction ()
createSVNActionFromContext action = do
(mergeInfo, mbPw) <- Types.readIDE' vcsData
ide <- Types.askIDERef
case mbPw of
Nothing -> Helper.createActionFromContext $ action $ Left $ passwordHandler ide mergeInfo
Just mb -> Helper.createActionFromContext $ action $ Right mb
where
-- passwordHandler :: IORef IDE-> Maybe MergeId -> ((Maybe (Bool, Maybe Text)) -> Wrapper.Ctx ())
passwordHandler ide mbMergeInfo result = liftIO $
case result of
Just (True, pw) -> modifyIDE_' ide (\ide -> ide {vcsData = (mbMergeInfo, Just pw) })
_ -> return ()
modifyIDE_' ide f =
liftIO (atomicModifyIORef ide f')
where
f' a = (f a,())
|
573/leksah
|
src/IDE/Command/VCS/SVN.hs
|
gpl-2.0
| 2,832
| 0
| 17
| 643
| 630
| 359
| 271
| 52
| 3
|
module Range (prop_rng5, myfoldl) where
import Language.Haskell.Liquid.Prelude
{-@ invariant {v:Int| v >= 0} @-}
range :: Int -> Int -> [Int]
range i j = range' (j - i) i j
range' :: Int -> Int -> Int -> [Int]
range' d i j
| i < j = i : (range' (d-1) (i + 1) j)
| otherwise = []
sumTo = foldl (+) 0 . range 0
{-@ Decrease lgo 2 @-}
--myfoldl :: (Int -> Int -> Int) -> Int -> [Int] -> Int
myfoldl f z0 xs0 = lgo z0 xs0
where
lgo z [] = z
lgo z (x:xs) = lgo (f z x) xs
n = choose 0
m = choose 1
-- prop_rng1 = map (liquidAssertB . (0 <=)) $ range 0 n
-- prop_rng2 = map (liquidAssertB . (n <=)) $ range n 100
-- prop_rng3 = map (liquidAssertB . (n <=)) $ range n m
-- prop_rng4 = map (liquidAssertB . (<= m)) $ range n m
prop_rng5 = liquidAssertB (0 <= sumTo n)
|
abakst/liquidhaskell
|
tests/pos/range.hs
|
bsd-3-clause
| 833
| 0
| 10
| 246
| 261
| 139
| 122
| 15
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{-
Copyright (C) 2006-2015 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.RST
Copyright : Copyright (C) 2006-2015 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley.edu>
Stability : alpha
Portability : portable
Conversion of 'Pandoc' documents to reStructuredText.
reStructuredText: <http://docutils.sourceforge.net/rst.html>
-}
module Text.Pandoc.Writers.RST ( writeRST ) where
import Text.Pandoc.Definition
import Text.Pandoc.Options
import Text.Pandoc.Shared
import Text.Pandoc.Writers.Shared
import Text.Pandoc.Templates (renderTemplate')
import Text.Pandoc.Builder (deleteMeta)
import Data.Maybe (fromMaybe)
import Data.List ( isPrefixOf, stripPrefix, intersperse, transpose )
import Network.URI (isURI)
import Text.Pandoc.Pretty
import Control.Monad.State
import Control.Applicative ( (<$>) )
import Data.Char (isSpace, toLower)
type Refs = [([Inline], Target)]
data WriterState =
WriterState { stNotes :: [[Block]]
, stLinks :: Refs
, stImages :: [([Inline], (String, String, Maybe String))]
, stHasMath :: Bool
, stHasRawTeX :: Bool
, stOptions :: WriterOptions
, stTopLevel :: Bool
}
-- | Convert Pandoc to RST.
writeRST :: WriterOptions -> Pandoc -> String
writeRST opts document =
let st = WriterState { stNotes = [], stLinks = [],
stImages = [], stHasMath = False,
stHasRawTeX = False, stOptions = opts,
stTopLevel = True}
in evalState (pandocToRST document) st
-- | Return RST representation of document.
pandocToRST :: Pandoc -> State WriterState String
pandocToRST (Pandoc meta blocks) = do
opts <- liftM stOptions get
let colwidth = if writerWrapText opts
then Just $ writerColumns opts
else Nothing
let subtit = case lookupMeta "subtitle" meta of
Just (MetaBlocks [Plain xs]) -> xs
_ -> []
title <- titleToRST (docTitle meta) subtit
metadata <- metaToJSON opts
(fmap (render colwidth) . blockListToRST)
(fmap (trimr . render colwidth) . inlineListToRST)
$ deleteMeta "title" $ deleteMeta "subtitle" meta
body <- blockListToRST' True $ normalizeHeadings 1 blocks
notes <- liftM (reverse . stNotes) get >>= notesToRST
-- note that the notes may contain refs, so we do them first
refs <- liftM (reverse . stLinks) get >>= refsToRST
pics <- liftM (reverse . stImages) get >>= pictRefsToRST
hasMath <- liftM stHasMath get
rawTeX <- liftM stHasRawTeX get
let main = render colwidth $ foldl ($+$) empty $ [body, notes, refs, pics]
let context = defField "body" main
$ defField "toc" (writerTableOfContents opts)
$ defField "toc-depth" (show $ writerTOCDepth opts)
$ defField "math" hasMath
$ defField "title" (render Nothing title :: String)
$ defField "math" hasMath
$ defField "rawtex" rawTeX
$ metadata
if writerStandalone opts
then return $ renderTemplate' (writerTemplate opts) context
else return main
where
normalizeHeadings lev (Header l a i:bs) = Header lev a i:normalizeHeadings (lev+1) cont ++ normalizeHeadings lev bs'
where (cont,bs') = break (headerLtEq l) bs
headerLtEq level (Header l' _ _) = l' <= level
headerLtEq _ _ = False
normalizeHeadings lev (b:bs) = b:normalizeHeadings lev bs
normalizeHeadings _ [] = []
-- | Return RST representation of reference key table.
refsToRST :: Refs -> State WriterState Doc
refsToRST refs = mapM keyToRST refs >>= return . vcat
-- | Return RST representation of a reference key.
keyToRST :: ([Inline], (String, String))
-> State WriterState Doc
keyToRST (label, (src, _)) = do
label' <- inlineListToRST label
let label'' = if ':' `elem` ((render Nothing label') :: String)
then char '`' <> label' <> char '`'
else label'
return $ nowrap $ ".. _" <> label'' <> ": " <> text src
-- | Return RST representation of notes.
notesToRST :: [[Block]] -> State WriterState Doc
notesToRST notes =
mapM (\(num, note) -> noteToRST num note) (zip [1..] notes) >>=
return . vsep
-- | Return RST representation of a note.
noteToRST :: Int -> [Block] -> State WriterState Doc
noteToRST num note = do
contents <- blockListToRST note
let marker = ".. [" <> text (show num) <> "]"
return $ nowrap $ marker $$ nest 3 contents
-- | Return RST representation of picture reference table.
pictRefsToRST :: [([Inline], (String, String, Maybe String))]
-> State WriterState Doc
pictRefsToRST refs = mapM pictToRST refs >>= return . vcat
-- | Return RST representation of a picture substitution reference.
pictToRST :: ([Inline], (String, String,Maybe String))
-> State WriterState Doc
pictToRST (label, (src, _, mbtarget)) = do
label' <- inlineListToRST label
return $ nowrap
$ ".. |" <> label' <> "| image:: " <> text src
$$ case mbtarget of
Nothing -> empty
Just t -> " :target: " <> text t
-- | Escape special characters for RST.
escapeString :: String -> String
escapeString = escapeStringUsing (backslashEscapes "`\\|*_")
titleToRST :: [Inline] -> [Inline] -> State WriterState Doc
titleToRST [] _ = return empty
titleToRST tit subtit = do
title <- inlineListToRST tit
subtitle <- inlineListToRST subtit
return $ bordered title '=' $$ bordered subtitle '-'
bordered :: Doc -> Char -> Doc
bordered contents c =
if len > 0
then border $$ contents $$ border
else empty
where len = offset contents
border = text (replicate len c)
-- | Convert Pandoc block element to RST.
blockToRST :: Block -- ^ Block element
-> State WriterState Doc
blockToRST Null = return empty
blockToRST (Div attr bs) = do
contents <- blockListToRST bs
let startTag = ".. raw:: html" $+$ nest 3 (tagWithAttrs "div" attr)
let endTag = ".. raw:: html" $+$ nest 3 "</div>"
return $ blankline <> startTag $+$ contents $+$ endTag $$ blankline
blockToRST (Plain inlines) = inlineListToRST inlines
-- title beginning with fig: indicates that the image is a figure
blockToRST (Para [Image txt (src,'f':'i':'g':':':tit)]) = do
capt <- inlineListToRST txt
let fig = "figure:: " <> text src
let alt = ":alt: " <> if null tit then capt else text tit
return $ hang 3 ".. " (fig $$ alt $+$ capt) $$ blankline
blockToRST (Para inlines)
| LineBreak `elem` inlines = do -- use line block if LineBreaks
lns <- mapM inlineListToRST $ splitBy (==LineBreak) inlines
return $ (vcat $ map (hang 2 (text "| ")) lns) <> blankline
| otherwise = do
contents <- inlineListToRST inlines
return $ contents <> blankline
blockToRST (RawBlock f@(Format f') str)
| f == "rst" = return $ text str
| otherwise = return $ blankline <> ".. raw:: " <>
text (map toLower f') $+$
(nest 3 $ text str) $$ blankline
blockToRST HorizontalRule =
return $ blankline $$ "--------------" $$ blankline
blockToRST (Header level (name,classes,_) inlines) = do
contents <- inlineListToRST inlines
isTopLevel <- gets stTopLevel
if isTopLevel
then do
let headerChar = if level > 5 then ' ' else "=-~^'" !! (level - 1)
let border = text $ replicate (offset contents) headerChar
return $ nowrap $ contents $$ border $$ blankline
else do
let rub = "rubric:: " <> contents
let name' | null name = empty
| otherwise = ":name: " <> text name
let cls | null classes = empty
| otherwise = ":class: " <> text (unwords classes)
return $ nowrap $ hang 3 ".. " (rub $$ name' $$ cls) $$ blankline
blockToRST (CodeBlock (_,classes,kvs) str) = do
opts <- stOptions <$> get
let tabstop = writerTabStop opts
let startnum = maybe "" (\x -> " " <> text x) $ lookup "startFrom" kvs
let numberlines = if "numberLines" `elem` classes
then " :number-lines:" <> startnum
else empty
if "haskell" `elem` classes && "literate" `elem` classes &&
isEnabled Ext_literate_haskell opts
then return $ prefixed "> " (text str) $$ blankline
else return $
(case [c | c <- classes,
c `notElem` ["sourceCode","literate","numberLines"]] of
[] -> "::"
(lang:_) -> (".. code:: " <> text lang) $$ numberlines)
$+$ nest tabstop (text str) $$ blankline
blockToRST (BlockQuote blocks) = do
tabstop <- get >>= (return . writerTabStop . stOptions)
contents <- blockListToRST blocks
return $ (nest tabstop contents) <> blankline
blockToRST (Table caption _ widths headers rows) = do
caption' <- inlineListToRST caption
let caption'' = if null caption
then empty
else blankline <> text "Table: " <> caption'
headers' <- mapM blockListToRST headers
rawRows <- mapM (mapM blockListToRST) rows
-- let isSimpleCell [Plain _] = True
-- isSimpleCell [Para _] = True
-- isSimpleCell [] = True
-- isSimpleCell _ = False
-- let isSimple = all (==0) widths && all (all isSimpleCell) rows
let numChars = maximum . map offset
opts <- get >>= return . stOptions
let widthsInChars =
if all (== 0) widths
then map ((+2) . numChars) $ transpose (headers' : rawRows)
else map (floor . (fromIntegral (writerColumns opts) *)) widths
let hpipeBlocks blocks = hcat [beg, middle, end]
where h = maximum (map height blocks)
sep' = lblock 3 $ vcat (map text $ replicate h " | ")
beg = lblock 2 $ vcat (map text $ replicate h "| ")
end = lblock 2 $ vcat (map text $ replicate h " |")
middle = hcat $ intersperse sep' blocks
let makeRow = hpipeBlocks . zipWith lblock widthsInChars
let head' = makeRow headers'
let rows' = map makeRow rawRows
let border ch = char '+' <> char ch <>
(hcat $ intersperse (char ch <> char '+' <> char ch) $
map (\l -> text $ replicate l ch) widthsInChars) <>
char ch <> char '+'
let body = vcat $ intersperse (border '-') rows'
let head'' = if all null headers
then empty
else head' $$ border '='
return $ border '-' $$ head'' $$ body $$ border '-' $$ caption'' $$ blankline
blockToRST (BulletList items) = do
contents <- mapM bulletListItemToRST items
-- ensure that sublists have preceding blank line
return $ blankline $$ chomp (vcat contents) $$ blankline
blockToRST (OrderedList (start, style', delim) items) = do
let markers = if start == 1 && style' == DefaultStyle && delim == DefaultDelim
then take (length items) $ repeat "#."
else take (length items) $ orderedListMarkers
(start, style', delim)
let maxMarkerLength = maximum $ map length markers
let markers' = map (\m -> let s = maxMarkerLength - length m
in m ++ replicate s ' ') markers
contents <- mapM (\(item, num) -> orderedListItemToRST item num) $
zip markers' items
-- ensure that sublists have preceding blank line
return $ blankline $$ chomp (vcat contents) $$ blankline
blockToRST (DefinitionList items) = do
contents <- mapM definitionListItemToRST items
-- ensure that sublists have preceding blank line
return $ blankline $$ chomp (vcat contents) $$ blankline
-- | Convert bullet list item (list of blocks) to RST.
bulletListItemToRST :: [Block] -> State WriterState Doc
bulletListItemToRST items = do
contents <- blockListToRST items
return $ hang 3 "- " $ contents <> cr
-- | Convert ordered list item (a list of blocks) to RST.
orderedListItemToRST :: String -- ^ marker for list item
-> [Block] -- ^ list item (list of blocks)
-> State WriterState Doc
orderedListItemToRST marker items = do
contents <- blockListToRST items
let marker' = marker ++ " "
return $ hang (length marker') (text marker') $ contents <> cr
-- | Convert defintion list item (label, list of blocks) to RST.
definitionListItemToRST :: ([Inline], [[Block]]) -> State WriterState Doc
definitionListItemToRST (label, defs) = do
label' <- inlineListToRST label
contents <- liftM vcat $ mapM blockListToRST defs
tabstop <- get >>= (return . writerTabStop . stOptions)
return $ label' $$ nest tabstop (nestle contents <> cr)
-- | Convert list of Pandoc block elements to RST.
blockListToRST' :: Bool
-> [Block] -- ^ List of block elements
-> State WriterState Doc
blockListToRST' topLevel blocks = do
tl <- gets stTopLevel
modify (\s->s{stTopLevel=topLevel})
res <- vcat `fmap` mapM blockToRST blocks
modify (\s->s{stTopLevel=tl})
return res
blockListToRST :: [Block] -- ^ List of block elements
-> State WriterState Doc
blockListToRST = blockListToRST' False
-- | Convert list of Pandoc inline elements to RST.
inlineListToRST :: [Inline] -> State WriterState Doc
inlineListToRST lst =
mapM inlineToRST (removeSpaceAfterDisplayMath $ insertBS lst) >>= return . hcat
where -- remove spaces after displaymath, as they screw up indentation:
removeSpaceAfterDisplayMath (Math DisplayMath x : zs) =
Math DisplayMath x : dropWhile (==Space) zs
removeSpaceAfterDisplayMath (x:xs) = x : removeSpaceAfterDisplayMath xs
removeSpaceAfterDisplayMath [] = []
insertBS :: [Inline] -> [Inline] -- insert '\ ' where needed
insertBS (x:y:z:zs)
| isComplex y && surroundComplex x z =
x : y : RawInline "rst" "\\ " : insertBS (z:zs)
insertBS (x:y:zs)
| isComplex x && not (okAfterComplex y) =
x : RawInline "rst" "\\ " : insertBS (y : zs)
| isComplex y && not (okBeforeComplex x) =
x : RawInline "rst" "\\ " : insertBS (y : zs)
| otherwise =
x : insertBS (y : zs)
insertBS (x:ys) = x : insertBS ys
insertBS [] = []
surroundComplex :: Inline -> Inline -> Bool
surroundComplex (Str s@(_:_)) (Str s'@(_:_)) =
case (last s, head s') of
('\'','\'') -> True
('"','"') -> True
('<','>') -> True
('[',']') -> True
('{','}') -> True
_ -> False
surroundComplex _ _ = False
okAfterComplex :: Inline -> Bool
okAfterComplex Space = True
okAfterComplex LineBreak = True
okAfterComplex (Str (c:_)) = isSpace c || c `elem` ("-.,:;!?\\/'\")]}>–—" :: String)
okAfterComplex _ = False
okBeforeComplex :: Inline -> Bool
okBeforeComplex Space = True
okBeforeComplex LineBreak = True
okBeforeComplex (Str (c:_)) = isSpace c || c `elem` ("-:/'\"<([{–—" :: String)
okBeforeComplex _ = False
isComplex :: Inline -> Bool
isComplex (Emph _) = True
isComplex (Strong _) = True
isComplex (SmallCaps _) = True
isComplex (Strikeout _) = True
isComplex (Superscript _) = True
isComplex (Subscript _) = True
isComplex (Link _ _) = True
isComplex (Image _ _) = True
isComplex (Code _ _) = True
isComplex (Math _ _) = True
isComplex _ = False
-- | Convert Pandoc inline element to RST.
inlineToRST :: Inline -> State WriterState Doc
inlineToRST (Span _ ils) = inlineListToRST ils
inlineToRST (Emph lst) = do
contents <- inlineListToRST lst
return $ "*" <> contents <> "*"
inlineToRST (Strong lst) = do
contents <- inlineListToRST lst
return $ "**" <> contents <> "**"
inlineToRST (Strikeout lst) = do
contents <- inlineListToRST lst
return $ "[STRIKEOUT:" <> contents <> "]"
inlineToRST (Superscript lst) = do
contents <- inlineListToRST lst
return $ ":sup:`" <> contents <> "`"
inlineToRST (Subscript lst) = do
contents <- inlineListToRST lst
return $ ":sub:`" <> contents <> "`"
inlineToRST (SmallCaps lst) = inlineListToRST lst
inlineToRST (Quoted SingleQuote lst) = do
contents <- inlineListToRST lst
return $ "‘" <> contents <> "’"
inlineToRST (Quoted DoubleQuote lst) = do
contents <- inlineListToRST lst
return $ "“" <> contents <> "”"
inlineToRST (Cite _ lst) =
inlineListToRST lst
inlineToRST (Code _ str) = return $ "``" <> text str <> "``"
inlineToRST (Str str) = return $ text $ escapeString str
inlineToRST (Math t str) = do
modify $ \st -> st{ stHasMath = True }
return $ if t == InlineMath
then ":math:`" <> text str <> "`"
else if '\n' `elem` str
then blankline $$ ".. math::" $$
blankline $$ nest 3 (text str) $$ blankline
else blankline $$ (".. math:: " <> text str) $$ blankline
inlineToRST (RawInline f x)
| f == "rst" = return $ text x
| f == "latex" || f == "tex" = do
modify $ \st -> st{ stHasRawTeX = True }
return $ ":raw-latex:`" <> text x <> "`"
| otherwise = return empty
inlineToRST (LineBreak) = return cr -- there's no line break in RST (see Para)
inlineToRST Space = return space
-- autolink
inlineToRST (Link [Str str] (src, _))
| isURI src &&
if "mailto:" `isPrefixOf` src
then src == escapeURI ("mailto:" ++ str)
else src == escapeURI str = do
let srcSuffix = fromMaybe src (stripPrefix "mailto:" src)
return $ text srcSuffix
inlineToRST (Link [Image alt (imgsrc,imgtit)] (src, _tit)) = do
label <- registerImage alt (imgsrc,imgtit) (Just src)
return $ "|" <> label <> "|"
inlineToRST (Link txt (src, tit)) = do
useReferenceLinks <- get >>= return . writerReferenceLinks . stOptions
linktext <- inlineListToRST $ normalizeSpaces txt
if useReferenceLinks
then do refs <- get >>= return . stLinks
case lookup txt refs of
Just (src',tit') ->
if src == src' && tit == tit'
then return $ "`" <> linktext <> "`_"
else do -- duplicate label, use non-reference link
return $ "`" <> linktext <> " <" <> text src <> ">`__"
Nothing -> do
modify $ \st -> st { stLinks = (txt,(src,tit)):refs }
return $ "`" <> linktext <> "`_"
else return $ "`" <> linktext <> " <" <> text src <> ">`__"
inlineToRST (Image alternate (source, tit)) = do
label <- registerImage alternate (source,tit) Nothing
return $ "|" <> label <> "|"
inlineToRST (Note contents) = do
-- add to notes in state
notes <- gets stNotes
modify $ \st -> st { stNotes = contents:notes }
let ref = show $ (length notes) + 1
return $ " [" <> text ref <> "]_"
registerImage :: [Inline] -> Target -> Maybe String -> State WriterState Doc
registerImage alt (src,tit) mbtarget = do
pics <- get >>= return . stImages
txt <- case lookup alt pics of
Just (s,t,mbt) | (s,t,mbt) == (src,tit,mbtarget) -> return alt
_ -> do
let alt' = if null alt || alt == [Str ""]
then [Str $ "image" ++ show (length pics)]
else alt
modify $ \st -> st { stImages =
(alt', (src,tit, mbtarget)):stImages st }
return alt'
inlineListToRST txt
|
gbataille/pandoc
|
src/Text/Pandoc/Writers/RST.hs
|
gpl-2.0
| 20,497
| 0
| 21
| 5,752
| 6,381
| 3,202
| 3,179
| 397
| 28
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
-- | High-level representation of SOACs. When performing
-- SOAC-transformations, operating on normal 'Exp' values is somewhat
-- of a nuisance, as they can represent terms that are not proper
-- SOACs. In contrast, this module exposes a SOAC representation that
-- does not enable invalid representations (except for type errors).
--
-- Furthermore, while standard normalised Futhark requires that the inputs
-- to a SOAC are variables or constants, the representation in this
-- module also supports various index-space transformations, like
-- @replicate@ or @rearrange@. This is also very convenient when
-- implementing transformations.
--
-- The names exported by this module conflict with the standard Futhark
-- syntax tree constructors, so you are advised to use a qualified
-- import:
--
-- @
-- import Futhark.Analysis.HORep.SOAC (SOAC)
-- import qualified Futhark.Analysis.HORep.SOAC as SOAC
-- @
module Futhark.Analysis.HORep.SOAC
( -- * SOACs
SOAC (..),
Futhark.ScremaForm (..),
inputs,
setInputs,
lambda,
setLambda,
typeOf,
width,
-- ** Converting to and from expressions
NotSOAC (..),
fromExp,
toExp,
toSOAC,
-- * SOAC inputs
Input (..),
varInput,
identInput,
isVarInput,
isVarishInput,
addTransform,
addInitialTransforms,
inputArray,
inputRank,
inputType,
inputRowType,
transformRows,
transposeInput,
-- ** Input transformations
ArrayTransforms,
noTransforms,
nullTransforms,
(|>),
(<|),
viewf,
ViewF (..),
viewl,
ViewL (..),
ArrayTransform (..),
transformFromExp,
soacToStream,
)
where
import Data.Foldable as Foldable
import Data.Maybe
import qualified Data.Sequence as Seq
import Futhark.Construct hiding (toExp)
import Futhark.IR hiding
( Iota,
Rearrange,
Replicate,
Reshape,
Var,
typeOf,
)
import qualified Futhark.IR as Futhark
import Futhark.IR.SOACS.SOAC
( HistOp (..),
ScremaForm (..),
StreamForm (..),
StreamOrd (..),
scremaType,
)
import qualified Futhark.IR.SOACS.SOAC as Futhark
import Futhark.Transform.Rename (renameLambda)
import Futhark.Transform.Substitute
import Futhark.Util.Pretty (ppr, text)
import qualified Futhark.Util.Pretty as PP
-- | A single, simple transformation. If you want several, don't just
-- create a list, use 'ArrayTransforms' instead.
data ArrayTransform
= -- | A permutation of an otherwise valid input.
Rearrange Certs [Int]
| -- | A reshaping of an otherwise valid input.
Reshape Certs (ShapeChange SubExp)
| -- | A reshaping of the outer dimension.
ReshapeOuter Certs (ShapeChange SubExp)
| -- | A reshaping of everything but the outer dimension.
ReshapeInner Certs (ShapeChange SubExp)
| -- | Replicate the rows of the array a number of times.
Replicate Certs Shape
deriving (Show, Eq, Ord)
instance Substitute ArrayTransform where
substituteNames substs (Rearrange cs xs) =
Rearrange (substituteNames substs cs) xs
substituteNames substs (Reshape cs ses) =
Reshape (substituteNames substs cs) (substituteNames substs ses)
substituteNames substs (ReshapeOuter cs ses) =
ReshapeOuter (substituteNames substs cs) (substituteNames substs ses)
substituteNames substs (ReshapeInner cs ses) =
ReshapeInner (substituteNames substs cs) (substituteNames substs ses)
substituteNames substs (Replicate cs se) =
Replicate (substituteNames substs cs) (substituteNames substs se)
-- | A sequence of array transformations, heavily inspired by
-- "Data.Seq". You can decompose it using 'viewf' and 'viewl', and
-- grow it by using '|>' and '<|'. These correspond closely to the
-- similar operations for sequences, except that appending will try to
-- normalise and simplify the transformation sequence.
--
-- The data type is opaque in order to enforce normalisation
-- invariants. Basically, when you grow the sequence, the
-- implementation will try to coalesce neighboring permutations, for
-- example by composing permutations and removing identity
-- transformations.
newtype ArrayTransforms = ArrayTransforms (Seq.Seq ArrayTransform)
deriving (Eq, Ord, Show)
instance Semigroup ArrayTransforms where
ts1 <> ts2 = case viewf ts2 of
t :< ts2' -> (ts1 |> t) <> ts2'
EmptyF -> ts1
instance Monoid ArrayTransforms where
mempty = noTransforms
instance Substitute ArrayTransforms where
substituteNames substs (ArrayTransforms ts) =
ArrayTransforms $ substituteNames substs <$> ts
-- | The empty transformation list.
noTransforms :: ArrayTransforms
noTransforms = ArrayTransforms Seq.empty
-- | Is it an empty transformation list?
nullTransforms :: ArrayTransforms -> Bool
nullTransforms (ArrayTransforms s) = Seq.null s
-- | Decompose the input-end of the transformation sequence.
viewf :: ArrayTransforms -> ViewF
viewf (ArrayTransforms s) = case Seq.viewl s of
t Seq.:< s' -> t :< ArrayTransforms s'
Seq.EmptyL -> EmptyF
-- | A view of the first transformation to be applied.
data ViewF
= EmptyF
| ArrayTransform :< ArrayTransforms
-- | Decompose the output-end of the transformation sequence.
viewl :: ArrayTransforms -> ViewL
viewl (ArrayTransforms s) = case Seq.viewr s of
s' Seq.:> t -> ArrayTransforms s' :> t
Seq.EmptyR -> EmptyL
-- | A view of the last transformation to be applied.
data ViewL
= EmptyL
| ArrayTransforms :> ArrayTransform
-- | Add a transform to the end of the transformation list.
(|>) :: ArrayTransforms -> ArrayTransform -> ArrayTransforms
(|>) = flip $ addTransform' extract add $ uncurry (flip (,))
where
extract ts' = case viewl ts' of
EmptyL -> Nothing
ts'' :> t' -> Just (t', ts'')
add t' (ArrayTransforms ts') = ArrayTransforms $ ts' Seq.|> t'
-- | Add a transform at the beginning of the transformation list.
(<|) :: ArrayTransform -> ArrayTransforms -> ArrayTransforms
(<|) = addTransform' extract add id
where
extract ts' = case viewf ts' of
EmptyF -> Nothing
t' :< ts'' -> Just (t', ts'')
add t' (ArrayTransforms ts') = ArrayTransforms $ t' Seq.<| ts'
addTransform' ::
(ArrayTransforms -> Maybe (ArrayTransform, ArrayTransforms)) ->
(ArrayTransform -> ArrayTransforms -> ArrayTransforms) ->
((ArrayTransform, ArrayTransform) -> (ArrayTransform, ArrayTransform)) ->
ArrayTransform ->
ArrayTransforms ->
ArrayTransforms
addTransform' extract add swap t ts =
fromMaybe (t `add` ts) $ do
(t', ts') <- extract ts
combined <- uncurry combineTransforms $ swap (t', t)
Just $
if identityTransform combined
then ts'
else addTransform' extract add swap combined ts'
identityTransform :: ArrayTransform -> Bool
identityTransform (Rearrange _ perm) =
Foldable.and $ zipWith (==) perm [0 ..]
identityTransform _ = False
combineTransforms :: ArrayTransform -> ArrayTransform -> Maybe ArrayTransform
combineTransforms (Rearrange cs2 perm2) (Rearrange cs1 perm1) =
Just $ Rearrange (cs1 <> cs2) $ perm2 `rearrangeCompose` perm1
combineTransforms _ _ = Nothing
-- | Given an expression, determine whether the expression represents
-- an input transformation of an array variable. If so, return the
-- variable and the transformation. Only 'Rearrange' and 'Reshape'
-- are possible to express this way.
transformFromExp :: Certs -> Exp rep -> Maybe (VName, ArrayTransform)
transformFromExp cs (BasicOp (Futhark.Rearrange perm v)) =
Just (v, Rearrange cs perm)
transformFromExp cs (BasicOp (Futhark.Reshape shape v)) =
Just (v, Reshape cs shape)
transformFromExp cs (BasicOp (Futhark.Replicate shape (Futhark.Var v))) =
Just (v, Replicate cs shape)
transformFromExp _ _ = Nothing
-- | One array input to a SOAC - a SOAC may have multiple inputs, but
-- all are of this form. Only the array inputs are expressed with
-- this type; other arguments, such as initial accumulator values, are
-- plain expressions. The transforms are done left-to-right, that is,
-- the first element of the 'ArrayTransform' list is applied first.
data Input = Input ArrayTransforms VName Type
deriving (Show, Eq, Ord)
instance Substitute Input where
substituteNames substs (Input ts v t) =
Input
(substituteNames substs ts)
(substituteNames substs v)
(substituteNames substs t)
-- | Create a plain array variable input with no transformations.
varInput :: HasScope t f => VName -> f Input
varInput v = withType <$> lookupType v
where
withType = Input (ArrayTransforms Seq.empty) v
-- | Create a plain array variable input with no transformations, from an 'Ident'.
identInput :: Ident -> Input
identInput v = Input (ArrayTransforms Seq.empty) (identName v) (identType v)
-- | If the given input is a plain variable input, with no transforms,
-- return the variable.
isVarInput :: Input -> Maybe VName
isVarInput (Input ts v _) | nullTransforms ts = Just v
isVarInput _ = Nothing
-- | If the given input is a plain variable input, with no non-vacuous transforms,
-- return the variable.
isVarishInput :: Input -> Maybe VName
isVarishInput (Input ts v t)
| nullTransforms ts = Just v
| Reshape cs [DimCoercion _] :< ts' <- viewf ts,
cs == mempty =
isVarishInput $ Input ts' v t
isVarishInput _ = Nothing
-- | Add a transformation to the end of the transformation list.
addTransform :: ArrayTransform -> Input -> Input
addTransform tr (Input trs a t) =
Input (trs |> tr) a t
-- | Add several transformations to the start of the transformation
-- list.
addInitialTransforms :: ArrayTransforms -> Input -> Input
addInitialTransforms ts (Input ots a t) = Input (ts <> ots) a t
-- | Convert SOAC inputs to the corresponding expressions.
inputsToSubExps ::
(MonadBuilder m) =>
[Input] ->
m [VName]
inputsToSubExps = mapM inputToExp'
where
inputToExp' (Input (ArrayTransforms ts) a _) =
foldlM transform a ts
transform ia (Replicate cs n) =
certifying cs $
letExp "repeat" $ BasicOp $ Futhark.Replicate n (Futhark.Var ia)
transform ia (Rearrange cs perm) =
certifying cs $
letExp "rearrange" $ BasicOp $ Futhark.Rearrange perm ia
transform ia (Reshape cs shape) =
certifying cs $
letExp "reshape" $ BasicOp $ Futhark.Reshape shape ia
transform ia (ReshapeOuter cs shape) = do
shape' <- reshapeOuter shape 1 . arrayShape <$> lookupType ia
certifying cs $
letExp "reshape_outer" $ BasicOp $ Futhark.Reshape shape' ia
transform ia (ReshapeInner cs shape) = do
shape' <- reshapeInner shape 1 . arrayShape <$> lookupType ia
certifying cs $
letExp "reshape_inner" $ BasicOp $ Futhark.Reshape shape' ia
-- | Return the array name of the input.
inputArray :: Input -> VName
inputArray (Input _ v _) = v
-- | Return the type of an input.
inputType :: Input -> Type
inputType (Input (ArrayTransforms ts) _ at) =
Foldable.foldl transformType at ts
where
transformType t (Replicate _ shape) =
arrayOfShape t shape
transformType t (Rearrange _ perm) =
rearrangeType perm t
transformType t (Reshape _ shape) =
t `setArrayShape` newShape shape
transformType t (ReshapeOuter _ shape) =
let Shape oldshape = arrayShape t
in t `setArrayShape` Shape (newDims shape ++ drop 1 oldshape)
transformType t (ReshapeInner _ shape) =
let Shape oldshape = arrayShape t
in t `setArrayShape` Shape (take 1 oldshape ++ newDims shape)
-- | Return the row type of an input. Just a convenient alias.
inputRowType :: Input -> Type
inputRowType = rowType . inputType
-- | Return the array rank (dimensionality) of an input. Just a
-- convenient alias.
inputRank :: Input -> Int
inputRank = arrayRank . inputType
-- | Apply the transformations to every row of the input.
transformRows :: ArrayTransforms -> Input -> Input
transformRows (ArrayTransforms ts) =
flip (Foldable.foldl transformRows') ts
where
transformRows' inp (Rearrange cs perm) =
addTransform (Rearrange cs (0 : map (+ 1) perm)) inp
transformRows' inp (Reshape cs shape) =
addTransform (ReshapeInner cs shape) inp
transformRows' inp (Replicate cs n)
| inputRank inp == 1 =
Rearrange mempty [1, 0]
`addTransform` (Replicate cs n `addTransform` inp)
| otherwise =
Rearrange mempty (2 : 0 : 1 : [3 .. inputRank inp])
`addTransform` ( Replicate cs n
`addTransform` (Rearrange mempty (1 : 0 : [2 .. inputRank inp -1]) `addTransform` inp)
)
transformRows' inp nts =
error $ "transformRows: Cannot transform this yet:\n" ++ show nts ++ "\n" ++ show inp
-- | Add to the input a 'Rearrange' transform that performs an @(k,n)@
-- transposition. The new transform will be at the end of the current
-- transformation list.
transposeInput :: Int -> Int -> Input -> Input
transposeInput k n inp =
addTransform (Rearrange mempty $ transposeIndex k n [0 .. inputRank inp -1]) inp
-- | A definite representation of a SOAC expression.
data SOAC rep
= Stream SubExp (StreamForm rep) (Lambda rep) [SubExp] [Input]
| Scatter SubExp (Lambda rep) [Input] [(Shape, Int, VName)]
| Screma SubExp (ScremaForm rep) [Input]
| Hist SubExp [HistOp rep] (Lambda rep) [Input]
deriving (Eq, Show)
instance PP.Pretty Input where
ppr (Input (ArrayTransforms ts) arr _) = foldl f (ppr arr) ts
where
f e (Rearrange cs perm) =
text "rearrange" <> ppr cs <> PP.apply [PP.apply (map ppr perm), e]
f e (Reshape cs shape) =
text "reshape" <> ppr cs <> PP.apply [PP.apply (map ppr shape), e]
f e (ReshapeOuter cs shape) =
text "reshape_outer" <> ppr cs <> PP.apply [PP.apply (map ppr shape), e]
f e (ReshapeInner cs shape) =
text "reshape_inner" <> ppr cs <> PP.apply [PP.apply (map ppr shape), e]
f e (Replicate cs ne) =
text "replicate" <> ppr cs <> PP.apply [ppr ne, e]
instance PrettyRep rep => PP.Pretty (SOAC rep) where
ppr (Screma w form arrs) = Futhark.ppScrema w arrs form
ppr (Hist len ops bucket_fun imgs) = Futhark.ppHist len imgs ops bucket_fun
ppr soac = text $ show soac
-- | Returns the inputs used in a SOAC.
inputs :: SOAC rep -> [Input]
inputs (Stream _ _ _ _ arrs) = arrs
inputs (Scatter _len _lam ivs _as) = ivs
inputs (Screma _ _ arrs) = arrs
inputs (Hist _ _ _ inps) = inps
-- | Set the inputs to a SOAC.
setInputs :: [Input] -> SOAC rep -> SOAC rep
setInputs arrs (Stream w form lam nes _) =
Stream (newWidth arrs w) form lam nes arrs
setInputs arrs (Scatter w lam _ivs as) =
Scatter (newWidth arrs w) lam arrs as
setInputs arrs (Screma w form _) =
Screma w form arrs
setInputs inps (Hist w ops lam _) =
Hist w ops lam inps
newWidth :: [Input] -> SubExp -> SubExp
newWidth [] w = w
newWidth (inp : _) _ = arraySize 0 $ inputType inp
-- | The lambda used in a given SOAC.
lambda :: SOAC rep -> Lambda rep
lambda (Stream _ _ lam _ _) = lam
lambda (Scatter _len lam _ivs _as) = lam
lambda (Screma _ (ScremaForm _ _ lam) _) = lam
lambda (Hist _ _ lam _) = lam
-- | Set the lambda used in the SOAC.
setLambda :: Lambda rep -> SOAC rep -> SOAC rep
setLambda lam (Stream w form _ nes arrs) =
Stream w form lam nes arrs
setLambda lam (Scatter len _lam ivs as) =
Scatter len lam ivs as
setLambda lam (Screma w (ScremaForm scan red _) arrs) =
Screma w (ScremaForm scan red lam) arrs
setLambda lam (Hist w ops _ inps) =
Hist w ops lam inps
-- | The return type of a SOAC.
typeOf :: SOAC rep -> [Type]
typeOf (Stream w _ lam nes _) =
let accrtps = take (length nes) $ lambdaReturnType lam
arrtps =
[ arrayOf (stripArray 1 t) (Shape [w]) NoUniqueness
| t <- drop (length nes) (lambdaReturnType lam)
]
in accrtps ++ arrtps
typeOf (Scatter _w lam _ivs dests) =
zipWith arrayOfShape val_ts ws
where
indexes = sum $ zipWith (*) ns $ map length ws
val_ts = drop indexes $ lambdaReturnType lam
(ws, ns, _) = unzip3 dests
typeOf (Screma w form _) =
scremaType w form
typeOf (Hist _ ops _ _) = do
op <- ops
map (`arrayOfShape` histShape op) (lambdaReturnType $ histOp op)
-- | The "width" of a SOAC is the expected outer size of its array
-- inputs _after_ input-transforms have been carried out.
width :: SOAC rep -> SubExp
width (Stream w _ _ _ _) = w
width (Scatter len _lam _ivs _as) = len
width (Screma w _ _) = w
width (Hist w _ _ _) = w
-- | Convert a SOAC to the corresponding expression.
toExp ::
(MonadBuilder m, Op (Rep m) ~ Futhark.SOAC (Rep m)) =>
SOAC (Rep m) ->
m (Exp (Rep m))
toExp soac = Op <$> toSOAC soac
-- | Convert a SOAC to a Futhark-level SOAC.
toSOAC :: MonadBuilder m => SOAC (Rep m) -> m (Futhark.SOAC (Rep m))
toSOAC (Stream w form lam nes inps) =
Futhark.Stream w <$> inputsToSubExps inps <*> pure form <*> pure nes <*> pure lam
toSOAC (Scatter w lam ivs dests) =
Futhark.Scatter w <$> inputsToSubExps ivs <*> pure lam <*> pure dests
toSOAC (Screma w form arrs) =
Futhark.Screma w <$> inputsToSubExps arrs <*> pure form
toSOAC (Hist w ops lam arrs) =
Futhark.Hist w <$> inputsToSubExps arrs <*> pure ops <*> pure lam
-- | The reason why some expression cannot be converted to a 'SOAC'
-- value.
data NotSOAC
= -- | The expression is not a (tuple-)SOAC at all.
NotSOAC
deriving (Show)
-- | Either convert an expression to the normalised SOAC
-- representation, or a reason why the expression does not have the
-- valid form.
fromExp ::
(Op rep ~ Futhark.SOAC rep, HasScope rep m) =>
Exp rep ->
m (Either NotSOAC (SOAC rep))
fromExp (Op (Futhark.Stream w as form nes lam)) =
Right . Stream w form lam nes <$> traverse varInput as
fromExp (Op (Futhark.Scatter w ivs lam as)) =
Right <$> (Scatter w lam <$> traverse varInput ivs <*> pure as)
fromExp (Op (Futhark.Screma w arrs form)) =
Right . Screma w form <$> traverse varInput arrs
fromExp (Op (Futhark.Hist w arrs ops lam)) =
Right . Hist w ops lam <$> traverse varInput arrs
fromExp _ = pure $ Left NotSOAC
-- | To-Stream translation of SOACs.
-- Returns the Stream SOAC and the
-- extra-accumulator body-result ident if any.
soacToStream ::
(MonadFreshNames m, Buildable rep, Op rep ~ Futhark.SOAC rep) =>
SOAC rep ->
m (SOAC rep, [Ident])
soacToStream soac = do
chunk_param <- newParam "chunk" $ Prim int64
let chvar = Futhark.Var $ paramName chunk_param
(lam, inps) = (lambda soac, inputs soac)
w = width soac
lam' <- renameLambda lam
let arrrtps = mapType w lam
-- the chunked-outersize of the array result and input types
loutps = [arrayOfRow t chvar | t <- map rowType arrrtps]
lintps = [arrayOfRow t chvar | t <- map inputRowType inps]
strm_inpids <- mapM (newParam "inp") lintps
-- Treat each SOAC case individually:
case soac of
Screma _ form _
| Just _ <- Futhark.isMapSOAC form -> do
-- Map(f,a) => is translated in strem's body to:
-- let strm_resids = map(f,a_ch) in strm_resids
--
-- array result and input IDs of the stream's lambda
strm_resids <- mapM (newIdent "res") loutps
let insoac =
Futhark.Screma chvar (map paramName strm_inpids) $
Futhark.mapSOAC lam'
insstm = mkLet strm_resids $ Op insoac
strmbdy = mkBody (oneStm insstm) $ map (subExpRes . Futhark.Var . identName) strm_resids
strmpar = chunk_param : strm_inpids
strmlam = Lambda strmpar strmbdy loutps
empty_lam = Lambda [] (mkBody mempty []) []
-- map(f,a) creates a stream with NO accumulators
return (Stream w (Parallel Disorder Commutative empty_lam) strmlam [] inps, [])
| Just (scans, _) <- Futhark.isScanomapSOAC form,
Futhark.Scan scan_lam nes <- Futhark.singleScan scans -> do
-- scanomap(scan_lam,nes,map_lam,a) => is translated in strem's body to:
-- 1. let (scan0_ids,map_resids) = scanomap(scan_lam, nes, map_lam, a_ch)
-- 2. let strm_resids = map (acc `+`,nes, scan0_ids)
-- 3. let outerszm1id = sizeof(0,strm_resids) - 1
-- 4. let lasteel_ids = if outerszm1id < 0
-- then nes
-- else strm_resids[outerszm1id]
-- 5. let acc' = acc + lasteel_ids
-- {acc', strm_resids, map_resids}
-- the array and accumulator result types
let scan_arr_ts = map (`arrayOfRow` chvar) $ lambdaReturnType scan_lam
map_arr_ts = drop (length nes) loutps
accrtps = lambdaReturnType scan_lam
-- array result and input IDs of the stream's lambda
strm_resids <- mapM (newIdent "res") scan_arr_ts
scan0_ids <- mapM (newIdent "resarr0") scan_arr_ts
map_resids <- mapM (newIdent "map_res") map_arr_ts
lastel_ids <- mapM (newIdent "lstel") accrtps
lastel_tmp_ids <- mapM (newIdent "lstel_tmp") accrtps
empty_arr <- newIdent "empty_arr" $ Prim Bool
inpacc_ids <- mapM (newParam "inpacc") accrtps
outszm1id <- newIdent "szm1" $ Prim int64
-- 1. let (scan0_ids,map_resids) = scanomap(scan_lam,nes,map_lam,a_ch)
let insstm =
mkLet (scan0_ids ++ map_resids) . Op $
Futhark.Screma chvar (map paramName strm_inpids) $
Futhark.scanomapSOAC [Futhark.Scan scan_lam nes] lam'
-- 2. let outerszm1id = chunksize - 1
outszm1stm =
mkLet [outszm1id] . BasicOp $
BinOp
(Sub Int64 OverflowUndef)
(Futhark.Var $ paramName chunk_param)
(constant (1 :: Int64))
-- 3. let lasteel_ids = ...
empty_arr_stm =
mkLet [empty_arr] . BasicOp $
CmpOp
(CmpSlt Int64)
(Futhark.Var $ identName outszm1id)
(constant (0 :: Int64))
leltmpstms =
zipWith
( \lid arrid ->
mkLet [lid] . BasicOp $
Index (identName arrid) $
fullSlice
(identType arrid)
[DimFix $ Futhark.Var $ identName outszm1id]
)
lastel_tmp_ids
scan0_ids
lelstm =
mkLet lastel_ids $
If
(Futhark.Var $ identName empty_arr)
(mkBody mempty $ subExpsRes nes)
( mkBody (stmsFromList leltmpstms) $
varsRes $ map identName lastel_tmp_ids
)
$ ifCommon $ map identType lastel_tmp_ids
-- 4. let strm_resids = map (acc `+`,nes, scan0_ids)
maplam <- mkMapPlusAccLam (map (Futhark.Var . paramName) inpacc_ids) scan_lam
let mapstm =
mkLet strm_resids . Op $
Futhark.Screma chvar (map identName scan0_ids) (Futhark.mapSOAC maplam)
-- 5. let acc' = acc + lasteel_ids
addlelbdy <-
mkPlusBnds scan_lam $
map Futhark.Var $
map paramName inpacc_ids ++ map identName lastel_ids
-- Finally, construct the stream
let (addlelstm, addlelres) = (bodyStms addlelbdy, bodyResult addlelbdy)
strmbdy =
mkBody (stmsFromList [insstm, outszm1stm, empty_arr_stm, lelstm, mapstm] <> addlelstm) $
addlelres ++ map (subExpRes . Futhark.Var . identName) (strm_resids ++ map_resids)
strmpar = chunk_param : inpacc_ids ++ strm_inpids
strmlam = Lambda strmpar strmbdy (accrtps ++ loutps)
return
( Stream w Sequential strmlam nes inps,
map paramIdent inpacc_ids
)
| Just (reds, _) <- Futhark.isRedomapSOAC form,
Futhark.Reduce comm lamin nes <- Futhark.singleReduce reds -> do
-- Redomap(+,lam,nes,a) => is translated in strem's body to:
-- 1. let (acc0_ids,strm_resids) = redomap(+,lam,nes,a_ch) in
-- 2. let acc' = acc + acc0_ids in
-- {acc', strm_resids}
let accrtps = take (length nes) $ lambdaReturnType lam
-- the chunked-outersize of the array result and input types
loutps' = drop (length nes) loutps
-- the lambda with proper index
foldlam = lam'
-- array result and input IDs of the stream's lambda
strm_resids <- mapM (newIdent "res") loutps'
inpacc_ids <- mapM (newParam "inpacc") accrtps
acc0_ids <- mapM (newIdent "acc0") accrtps
-- 1. let (acc0_ids,strm_resids) = redomap(+,lam,nes,a_ch) in
let insoac =
Futhark.Screma
chvar
(map paramName strm_inpids)
$ Futhark.redomapSOAC [Futhark.Reduce comm lamin nes] foldlam
insstm = mkLet (acc0_ids ++ strm_resids) $ Op insoac
-- 2. let acc' = acc + acc0_ids in
addaccbdy <-
mkPlusBnds lamin $
map Futhark.Var $
map paramName inpacc_ids ++ map identName acc0_ids
-- Construct the stream
let (addaccstm, addaccres) = (bodyStms addaccbdy, bodyResult addaccbdy)
strmbdy =
mkBody (oneStm insstm <> addaccstm) $
addaccres ++ map (subExpRes . Futhark.Var . identName) strm_resids
strmpar = chunk_param : inpacc_ids ++ strm_inpids
strmlam = Lambda strmpar strmbdy (accrtps ++ loutps')
lam0 <- renameLambda lamin
return (Stream w (Parallel InOrder comm lam0) strmlam nes inps, [])
-- Otherwise it cannot become a stream.
_ -> return (soac, [])
where
mkMapPlusAccLam ::
(MonadFreshNames m, Buildable rep) =>
[SubExp] ->
Lambda rep ->
m (Lambda rep)
mkMapPlusAccLam accs plus = do
let (accpars, rempars) = splitAt (length accs) $ lambdaParams plus
parstms =
zipWith
(\par se -> mkLet [paramIdent par] (BasicOp $ SubExp se))
accpars
accs
plus_bdy = lambdaBody plus
newlambdy =
Body
(bodyDec plus_bdy)
(stmsFromList parstms <> bodyStms plus_bdy)
(bodyResult plus_bdy)
renameLambda $ Lambda rempars newlambdy $ lambdaReturnType plus
mkPlusBnds ::
(MonadFreshNames m, Buildable rep) =>
Lambda rep ->
[SubExp] ->
m (Body rep)
mkPlusBnds plus accels = do
plus' <- renameLambda plus
let parstms =
zipWith
(\par se -> mkLet [paramIdent par] (BasicOp $ SubExp se))
(lambdaParams plus')
accels
body = lambdaBody plus'
return $ body {bodyStms = stmsFromList parstms <> bodyStms body}
|
diku-dk/futhark
|
src/Futhark/Analysis/HORep/SOAC.hs
|
isc
| 26,861
| 0
| 25
| 6,920
| 7,311
| 3,729
| 3,582
| 503
| 5
|
import Data.Char (toLower, isSpace)
palindromePermutation :: String -> Bool
palindromePermutation s = length oddLetters <= 1
where cleanString = filter (not . isSpace) $ map toLower s
oddLetters = odd cleanString []
odd [] acc = acc
odd (x:xs) acc | x `elem` acc = odd xs (filter (/= x) acc)
| otherwise = odd xs (x:acc)
|
Kiandr/CrackingCodingInterview
|
Haskell/src/chapter-1/palindrome-permutation.hs
|
mit
| 371
| 0
| 11
| 107
| 155
| 79
| 76
| 8
| 2
|
-- | 'Strive.Actions.Clubs'
module Strive.Options.Clubs
( GetClubMembersOptions
, GetClubActivitiesOptions(..)
) where
import Data.Default (Default, def)
import Data.Time.Clock (UTCTime)
import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds)
import Network.HTTP.Types (QueryLike, toQuery)
import Strive.Internal.Options (PaginationOptions)
-- | 'Strive.Actions.getClubMembers'
type GetClubMembersOptions = PaginationOptions
-- | 'Strive.Actions.getClubActivities'
data GetClubActivitiesOptions = GetClubActivitiesOptions
{ getClubActivitiesOptions_before :: Maybe UTCTime
, getClubActivitiesOptions_after :: Maybe UTCTime
, getClubActivitiesOptions_page :: Integer
, getClubActivitiesOptions_perPage :: Integer
}
deriving Show
instance Default GetClubActivitiesOptions where
def = GetClubActivitiesOptions
{ getClubActivitiesOptions_before = Nothing
, getClubActivitiesOptions_after = Nothing
, getClubActivitiesOptions_page = 1
, getClubActivitiesOptions_perPage = 200
}
instance QueryLike GetClubActivitiesOptions where
toQuery options = toQuery
[ ( "before"
, fmap
(show . utcTimeToPOSIXSeconds)
(getClubActivitiesOptions_before options)
)
, ( "after"
, fmap
(show . utcTimeToPOSIXSeconds)
(getClubActivitiesOptions_after options)
)
, ("page", Just (show (getClubActivitiesOptions_page options)))
, ("per_page", Just (show (getClubActivitiesOptions_perPage options)))
]
|
tfausak/strive
|
source/library/Strive/Options/Clubs.hs
|
mit
| 1,494
| 0
| 13
| 253
| 291
| 173
| 118
| 33
| 0
|
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE DataKinds #-}
module Text.XML.Pugi.Foreign.Types where
import Foreign.ForeignPtr
import Foreign.Ptr
import qualified Data.ByteString as S
data MutableFlag = Mutable | Immutable
data NodeKind = Element -- ^ \<name\>children\</name\>
| PCData -- ^ value
| CData -- ^ \<![CDATA[value]]\>
| Comment -- ^ \<!--value--\>
| Pi -- ^ \<?name value?>
| Declaration -- ^ \<?name?\>
| Doctype -- ^ \<!DOCTYPE value\>
| Unknown
newtype Document_ (k :: NodeKind) (m :: MutableFlag) = Document (ForeignPtr (Document_ k m))
type Document = Document_ 'Unknown 'Immutable
type MutableDocument = Document_ 'Unknown 'Mutable
newtype Node_ (k :: NodeKind) (m :: MutableFlag) = Node (ForeignPtr (Node_ k m))
type Node = Node_ 'Unknown 'Immutable
type MutableNode k = Node_ k 'Mutable
newtype ParseResult = ParseResult (Ptr ParseResult)
newtype XPath (rt :: k) = XPath (ForeignPtr (XPath rt))
data NodeSet (m :: MutableFlag) = NodeSet Int (ForeignPtr (NodeSet m))
instance Show (NodeSet m) where
show (NodeSet i _) = "NodeSet " ++ show i ++ " items"
data Attr
data XNode
type Attribute = (S.ByteString, S.ByteString)
type XPathNode m = Either (Node_ 'Unknown m) Attribute
|
philopon/pugixml-hs
|
Text/XML/Pugi/Foreign/Types.hs
|
mit
| 1,374
| 0
| 10
| 302
| 363
| 217
| 146
| -1
| -1
|
module Constants
( impConsonants
, phonemeDistance
) where
import ClassyPrelude
import Data.Phoneme
-- Impossible consonants filter
-- True = impossible
impConsonants :: Phoneme -> Bool
impConsonants c@(Consonant p m h a)
-- Silibants are restricted to these Places
| p `notElem` [DENTIALVEOLAR, DENTAL, LAMINALALVEOLAR, APICOALVEOLAR, PALATOALVEOLAR, APICALRETROFLEX, ALVEOLOPALATAL, RETROFLEX] && m `elem` [SILIBANT, SAFFRICATE] = True
-- Laterals are restricted from these Places
| p `elem` [BILABIAL, LABIODENTAL, EPIPHARYNGEAL, PHARYNGEAL, EPIGLOTTAL, GLOTTAL] && m `elem` [LAFFRICATE, LAPPROXIMANT, LFRICATIVE, LFRICATIVE, LFLAP] = True
-- Flaps and Trills are restricted from these Places
| p `elem` [ALVEOLOPALATAL, PALATAL, VELAR, GLOTTAL] && m `elem` [FLAP, TRILL] = True
-- Only *Voiceless* Stops/Affricates are allowed in these Places
| p `elem` [EPIPHARYNGEAL, PHARYNGEAL, GLOTTAL] && m `elem` [STOP, AFFRICATE] && h /= VOICELESS = True
-- Only Stops, Affricates, and Clicks can be Aspirated
| m `notElem` [STOP, AFFRICATE, SAFFRICATE, LAFFRICATE, CLICK] && h == ASPIRATED = True
-- Nasals are restricted from these Places
| p `elem` [EPIPHARYNGEAL, PHARYNGEAL, EPIGLOTTAL, GLOTTAL] && m == NASAL = True
-- Fricatives and Approximants happen Pharyngeral-ly (or Epiglotto-pharyngeal-ly)
| p == EPIGLOTTAL && m `elem` [FRICATIVE, APPROXIMANT, AFFRICATE] = True
-- Stops, Trills, and Flaps happen Epiglottal-ly (or Epiglotto-pharyngeal-ly)
| p == PHARYNGEAL && m `elem` [STOP, TRILL, FLAP, AFFRICATE] = True
-- Ejectives are basically always Voiceless
| h /= VOICELESS && a == EJECTIVE = True
-- Ejectives are always Obstruents (No Silibants though?)
| m `notElem` [STOP, AFFRICATE, FRICATIVE, LAFFRICATE, LFRICATIVE] && a == EJECTIVE = True
-- Implosives are basically always Stops
| m /= STOP && a == IMPLOSIVE = True
-- Implosives are basically never anything past Uvular
| a == IMPLOSIVE && p `elem` [PHARYNGEAL, EPIPHARYNGEAL, EPIGLOTTAL, GLOTTAL] = True
-- Clicks are never anything but Lingual Ingressive and vice versa
| m == CLICK && a /= LINGUAL || m /= CLICK && a == LINGUAL = True
-- Clicks are restricted from these Places
| m == CLICK && p `elem` [VELAR, UVULAR, PHARYNGEAL, EPIPHARYNGEAL, EPIGLOTTAL, GLOTTAL] = True
-- Clicks are restricted to these Phonations
| m == CLICK && h `notElem` [MODAL, VOICELESS, BREATHY, ASPIRATED] = True
-- Check coarticulated
| (\case COARTICULATED{} -> True; _ -> False) p = impCoarticulated c
-- Otherwise, false
| otherwise = False
impConsonants _ = False
impCoarticulated :: Phoneme -> Bool
impCoarticulated (Consonant (COARTICULATED p1 p2) m h a)
-- Let's not do triple/quadruple articulation...
| (\case COARTICULATED{} -> True; _ -> False) p1 || (\case COARTICULATED{} -> True; _ -> False) p2 = True
-- Coarticulated constants can't have the same POA, that'd be dumb
| p1 == p2 = True
-- Keep places in order (front to back)
| p1 > p2 = True
-- If either Place is impossible, the whole thing is
| impConsonants (Consonant p1 m h a) || impConsonants (Consonant p2 m h a) = True
-- Coarticulated constants are restricted to these Manners
| m `notElem` [NASAL, STOP, APPROXIMANT, LAPPROXIMANT] = True
-- Glottis is not considered an articulator in this case
| p1 == GLOTTAL || p2 == GLOTTAL = True
-- Restrictions on Coart Stops: Too close together
| m `elem` [STOP, NASAL] && p1 == BILABIAL && p2 == INTERDENTAL = True
-- (Bi)Labial-Dorsal Stops are fine
| m `elem` [STOP, NASAL] && p1 == BILABIAL && p2 `elem` [ALVEOLOPALATAL, PALATAL, VELAR, UVULAR] = False
-- Other Labial-Dorsal's are too rare
| m `elem` [STOP, NASAL] && p1 `elem` [LABIODENTAL, LINGUOLABIAL] && p2 `elem` [ALVEOLOPALATAL, PALATAL, VELAR, UVULAR] = True
-- Labial-Coronal is too rare
| m `elem` [STOP, NASAL] && p1 `elem` [BILABIAL, LABIODENTAL, LINGUOLABIAL] && p2 `elem` [INTERDENTAL, DENTAL, DENTIALVEOLAR, LAMINALALVEOLAR, APICOALVEOLAR, PALATOALVEOLAR, APICALRETROFLEX, RETROFLEX] = True
-- Labial-Pharyngeal is unheard of
| m `elem` [STOP, NASAL] && p1 `elem` [BILABIAL, LABIODENTAL, LINGUOLABIAL] && p2 `elem` [PHARYNGEAL, EPIPHARYNGEAL, EPIGLOTTAL, GLOTTAL] = True
-- Coronal-Dorsal is too rare
| m `elem` [STOP, NASAL] && p1 `elem` [INTERDENTAL, DENTAL, DENTIALVEOLAR, LAMINALALVEOLAR, APICOALVEOLAR, PALATOALVEOLAR, APICALRETROFLEX, RETROFLEX] && p2 `elem` [ALVEOLOPALATAL, PALATAL, VELAR, UVULAR] = True
-- Coronal-Pharyngeal is unheard of
| m `elem` [STOP, NASAL] && p1 `elem` [INTERDENTAL, DENTAL, DENTIALVEOLAR, LAMINALALVEOLAR, APICOALVEOLAR, PALATOALVEOLAR, APICALRETROFLEX, RETROFLEX] && p2 `elem` [PHARYNGEAL, EPIPHARYNGEAL, EPIGLOTTAL, GLOTTAL] = True
-- Dorsal-Pharyngeal is too rare
| m `elem` [STOP, NASAL] && p1 `elem` [ALVEOLOPALATAL, PALATAL, VELAR, UVULAR] && p2 `elem` [PHARYNGEAL, EPIPHARYNGEAL, EPIGLOTTAL, GLOTTAL] = True
-- Otherwise, False
| otherwise = False
-- Calculates an approximate similarity between two phonemes
-- Max of ~30
phonemeDistance :: Phoneme -> Phoneme -> Int
--distances bewteen two vowels (manhattan distance, sorta)
phonemeDistance (Vowel h1 b1 r1 l1) (Vowel h2 b2 r2 l2) = 2 * abs (fromEnum h1 - fromEnum h2)
+ 2 * abs (fromEnum b1 - fromEnum b2)
+ 5 * abs (fromEnum r1 - fromEnum r2)
+ 3 * abs (fromEnum l1 - fromEnum l2)
-- Distances between two consonants (manhattan distance, sorta)
phonemeDistance (Consonant p1 m1 h1 a1) (Consonant p2 m2 h2 a2) = 2 * placeDistance p1 p2
+ 2 * mannerDistance m1 m2
+ 1 * phonationDistance h1 h2
+ 1 * airstreamDistance a1 a2
-- Distances a vowel and diphthong (average distance from vowel to the two end points)
phonemeDistance (vow@Vowel{}) (Diphthong b2 r2 h2 b3 r3 h3 l2) = truncate result where
result = realToFrac (phonemeDistance vow (Vowel b2 r2 h2 l2) + phonemeDistance vow (Vowel b3 r3 h3 l2)) / 2
phonemeDistance (diph@Diphthong{}) (vow@Vowel{}) = phonemeDistance vow diph
-- Distance between two diphthongs (cosine distance)
phonemeDistance (Diphthong b1 r1 h1 b2 h2 r2 l1) (Diphthong b3 r3 h3 b4 r4 h4 l2) = round (24 * cosDist) + 3 * abs (fromEnum l1 - fromEnum l2) where
dp = ((fromEnum h1 - fromEnum h2) * (fromEnum h3 - fromEnum h4))
+ ((fromEnum b1 - fromEnum b2) * (fromEnum b3 - fromEnum b4))
+ ((fromEnum r1 - fromEnum r2) * (fromEnum r3 - fromEnum r4))
mags = sqrt (fromIntegral ((fromEnum h1 - fromEnum h2) ^ 2 + (fromEnum b1 - fromEnum b2) ^ 2 + (fromEnum r1 - fromEnum r2) ^ 2))
* sqrt (fromIntegral ((fromEnum h3 - fromEnum h4) ^ 2 + (fromEnum b3 - fromEnum b4) ^ 2 + (fromEnum r3 - fromEnum r4) ^ 2))
cosDist = realToFrac dp / realToFrac mags
-- Semivowels...
phonemeDistance (Consonant PALATAL APPROXIMANT MODAL PULMONIC) (Vowel CLOSE BACK UNROUNDED _ ) = 10
phonemeDistance (Vowel CLOSE BACK UNROUNDED _) (Consonant PALATAL APPROXIMANT MODAL PULMONIC) = 10
phonemeDistance (Consonant VELAR APPROXIMANT MODAL PULMONIC) (Vowel CLOSE BACK ROUNDED _) = 10
phonemeDistance (Vowel CLOSE BACK ROUNDED _) (Consonant VELAR APPROXIMANT MODAL PULMONIC) = 10
phonemeDistance (Consonant PHARYNGEAL APPROXIMANT MODAL PULMONIC) (Vowel OPEN BACK UNROUNDED _) = 10
phonemeDistance (Vowel OPEN BACK UNROUNDED _) (Consonant PHARYNGEAL APPROXIMANT MODAL PULMONIC) = 10
-- Everything else
phonemeDistance _ _ = 60
mannerDistance :: Manner -> Manner -> Int
mannerDistance NASAL STOP = 1
mannerDistance STOP SAFFRICATE = 1
mannerDistance STOP AFFRICATE = 1
mannerDistance STOP SILIBANT = 3
mannerDistance STOP FRICATIVE = 3
mannerDistance STOP FLAP = 2
mannerDistance STOP TRILL = 3
mannerDistance STOP LAFFRICATE = 1
mannerDistance STOP LFLAP = 2
mannerDistance SAFFRICATE AFFRICATE = 1
mannerDistance SAFFRICATE SILIBANT = 1
mannerDistance SAFFRICATE LAFFRICATE = 1
mannerDistance AFFRICATE LAFFRICATE = 1
mannerDistance AFFRICATE FRICATIVE = 1
mannerDistance SILIBANT FRICATIVE = 1
mannerDistance SILIBANT APPROXIMANT = 2
mannerDistance FRICATIVE APPROXIMANT = 1
mannerDistance FRICATIVE LFRICATIVE = 1
mannerDistance APPROXIMANT LAPPROXIMANT = 1
mannerDistance FLAP LFLAP = 1
mannerDistance STOP NASAL = 1
mannerDistance SAFFRICATE STOP = 1
mannerDistance AFFRICATE STOP = 1
mannerDistance SILIBANT STOP = 3
mannerDistance FRICATIVE STOP = 3
mannerDistance FLAP STOP = 2
mannerDistance TRILL STOP = 3
mannerDistance LAFFRICATE STOP = 1
mannerDistance LFLAP STOP = 2
mannerDistance AFFRICATE SAFFRICATE = 1
mannerDistance SILIBANT SAFFRICATE = 1
mannerDistance LAFFRICATE SAFFRICATE = 1
mannerDistance LAFFRICATE AFFRICATE = 1
mannerDistance FRICATIVE AFFRICATE= 1
mannerDistance FRICATIVE SILIBANT = 1
mannerDistance APPROXIMANT SILIBANT = 2
mannerDistance APPROXIMANT FRICATIVE = 1
mannerDistance LFRICATIVE FRICATIVE = 1
mannerDistance LAPPROXIMANT APPROXIMANT = 1
mannerDistance LFLAP FLAP = 1
mannerDistance x y | x == y = 0
| otherwise = 5
placeDistance :: Place -> Place -> Int
placeDistance BILABIAL LABIODENTAL = 2
placeDistance BILABIAL LINGUOLABIAL = 3
placeDistance LABIODENTAL INTERDENTAL = 3
placeDistance LINGUOLABIAL INTERDENTAL = 2
placeDistance INTERDENTAL DENTIALVEOLAR = 2
placeDistance INTERDENTAL DENTAL = 2
placeDistance DENTIALVEOLAR LAMINALALVEOLAR = 2
placeDistance DENTIALVEOLAR DENTAL = 1
placeDistance LAMINALALVEOLAR APICOALVEOLAR = 1
placeDistance LAMINALALVEOLAR PALATOALVEOLAR = 2
placeDistance PALATOALVEOLAR APICALRETROFLEX = 1
placeDistance PALATOALVEOLAR ALVEOLOPALATAL = 3
placeDistance APICOALVEOLAR APICALRETROFLEX = 1
placeDistance APICALRETROFLEX RETROFLEX = 2
placeDistance APICALRETROFLEX ALVEOLOPALATAL = 2
placeDistance RETROFLEX ALVEOLOPALATAL = 3
placeDistance RETROFLEX PALATAL = 3
placeDistance ALVEOLOPALATAL PALATAL = 2
placeDistance PALATAL VELAR = 2
placeDistance VELAR UVULAR = 2
placeDistance UVULAR PHARYNGEAL = 3
placeDistance PHARYNGEAL EPIPHARYNGEAL = 1
placeDistance EPIPHARYNGEAL EPIGLOTTAL = 1
placeDistance EPIGLOTTAL GLOTTAL = 2
placeDistance LABIODENTAL BILABIAL = 2
placeDistance LINGUOLABIAL BILABIAL = 3
placeDistance INTERDENTAL LABIODENTAL = 3
placeDistance INTERDENTAL LINGUOLABIAL = 2
placeDistance DENTIALVEOLAR INTERDENTAL = 2
placeDistance DENTAL INTERDENTAL = 2
placeDistance LAMINALALVEOLAR DENTIALVEOLAR = 2
placeDistance DENTAL DENTIALVEOLAR = 1
placeDistance APICOALVEOLAR LAMINALALVEOLAR = 1
placeDistance PALATOALVEOLAR LAMINALALVEOLAR = 2
placeDistance APICALRETROFLEX PALATOALVEOLAR = 1
placeDistance ALVEOLOPALATAL PALATOALVEOLAR = 3
placeDistance APICALRETROFLEX APICOALVEOLAR = 1
placeDistance RETROFLEX APICALRETROFLEX = 2
placeDistance ALVEOLOPALATAL APICALRETROFLEX = 2
placeDistance ALVEOLOPALATAL RETROFLEX = 3
placeDistance PALATAL RETROFLEX = 3
placeDistance PALATAL ALVEOLOPALATAL = 2
placeDistance VELAR PALATAL = 2
placeDistance UVULAR VELAR = 2
placeDistance PHARYNGEAL UVULAR = 3
placeDistance EPIPHARYNGEAL PHARYNGEAL = 1
placeDistance EPIGLOTTAL EPIPHARYNGEAL = 1
placeDistance GLOTTAL EPIGLOTTAL = 2
placeDistance (COARTICULATED p1 p2) (COARTICULATED p3 p4) = round (realToFrac (placeDistance p1 p3 + placeDistance p2 p4)/2)
placeDistance x y | x == y = 0
| otherwise = 5
phonationDistance :: Phonation -> Phonation -> Int
phonationDistance VOICELESS BREATHY = 1
phonationDistance VOICELESS SLACK = 2
phonationDistance VOICELESS MODAL = 5
phonationDistance VOICELESS STIFF = 4
phonationDistance VOICELESS CREAKY = 3
phonationDistance BREATHY SLACK = 1
phonationDistance BREATHY MODAL = 2
phonationDistance BREATHY STIFF = 4
phonationDistance BREATHY CREAKY = 4
phonationDistance SLACK MODAL = 1
phonationDistance SLACK STIFF = 3
phonationDistance SLACK CREAKY = 3
phonationDistance MODAL STIFF = 1
phonationDistance MODAL CREAKY = 2
phonationDistance STIFF CREAKY = 1
phonationDistance ASPIRATED VOICELESS = 2
phonationDistance ASPIRATED BREATHY = 3
phonationDistance ASPIRATED SLACK = 4
phonationDistance ASPIRATED MODAL = 5
phonationDistance ASPIRATED STIFF = 5
phonationDistance ASPIRATED CREAKY = 5
phonationDistance BREATHY VOICELESS = 1
phonationDistance SLACK VOICELESS = 2
phonationDistance MODAL VOICELESS = 5
phonationDistance STIFF VOICELESS = 4
phonationDistance CREAKY VOICELESS = 3
phonationDistance SLACK BREATHY = 1
phonationDistance MODAL BREATHY = 2
phonationDistance STIFF BREATHY = 4
phonationDistance CREAKY BREATHY = 4
phonationDistance MODAL SLACK = 1
phonationDistance STIFF SLACK = 3
phonationDistance CREAKY SLACK = 3
phonationDistance STIFF MODAL = 1
phonationDistance CREAKY MODAL = 2
phonationDistance CREAKY STIFF = 1
phonationDistance VOICELESS ASPIRATED = 2
phonationDistance BREATHY ASPIRATED = 3
phonationDistance SLACK ASPIRATED = 4
phonationDistance MODAL ASPIRATED = 5
phonationDistance STIFF ASPIRATED = 5
phonationDistance CREAKY ASPIRATED = 5
phonationDistance x y | x == y = 0
| otherwise = 5
airstreamDistance :: Airstream -> Airstream -> Int
airstreamDistance PULMONIC EJECTIVE = 1
airstreamDistance EJECTIVE PULMONIC = 1
airstreamDistance EJECTIVE IMPLOSIVE = 1
airstreamDistance IMPLOSIVE EJECTIVE = 1
airstreamDistance IMPLOSIVE LINGUAL = 3
airstreamDistance LINGUAL IMPLOSIVE = 3
airstreamDistance x y | x == y = 0
| otherwise = 5
|
Brightgalrs/con-lang-gen
|
src/Constants.hs
|
mit
| 13,519
| 0
| 19
| 2,513
| 3,952
| 2,082
| 1,870
| -1
| -1
|
module Step4 where
import Text.Read (readMaybe)
-- Подготовка к монадам
-- чистые функции легко комбинировать
pureFloor :: Double -> Int
pureFloor x = floor x
pureGt :: Int -> Bool
pureGt y = y >= 0
pureShow :: Bool -> String
pureShow z = "pureShow => " ++ show z
-- all the chain
pureTest :: Double -> String
pureTest x = pureShow (pureGt (pureFloor x))
-- pureTest = pureShow . pureGt . pureFloor -- point-free style
pureBind :: a -> (a -> b) -> b
pureBind x f = undefined -- TODO
pureChain1 :: Double -> Int
pureChain1 x1 = pureBind x1 pureFloor
pureChain1a :: Double -> Int
pureChain1a x1 = pureBind x1 (\x -> pureFloor x)
pureChain1b :: Double -> Int
pureChain1b x1 = pureBind x1 (\x -> pureBind (pureFloor x) id)
---------------------------------
-- добавим ещё один шаг к цепочку
pureChain2 :: Double -> Bool
pureChain2 x1 = pureBind x1 (\x ->
pureBind (pureFloor x) (\y ->
pureBind (pureGt y) id))
---------------------------------
-- добавим последний шаг к цепочку
-- TODO fix compilation error
-- pureChain3 :: Double -> String
-- pureChain3 x1 = pureBind x1 (\x ->
-- pureBind (pureFloor x) (\y ->
-- pureBind (pureGt y) id))
---------------------------------------------------
-- Логгирование в чистых функциях, омг
-- TODO напишите типы
logFloor x = (floor x, show x ++ " was floored \n")
logGt y = (y >= 0, show y ++ " compared with 0 \n")
logShow z = ("<<<" ++ show z ++ ">>>", show z ++ " converted to string\n")
-- как теперь их сочетать?
logChain3a :: Double -> (String, String)
logChain3a x = undefined -- TODO написать определение
-- подсказка для 2-х функций
-- test2 x =
-- let (x1, l1) = loggableFloor x in
-- let (x2, l2) = loggableGt x1 in
-- (x2, l1 ++ l2)
logBind :: (a, String) -> (a -> (b, String)) -> (b, String)
logBind x f = undefined -- TODO написать определение
logChain3b = undefined -- TODO то же самое, что но используя logBind
---------------------------------------------------
-- TODO напишите типы
multivaluedFloor x = [floor x, ceiling x]
multivaluedGt y = [y <= 0, y == 0, y >= 0]
multivaluedShow z = ["<<<" ++ show z ++ ">>>"]
multivaluedTest :: Double -> [String]
multivaluedTest = undefined -- TODO написать определение
-- подсказка concat :: [[a]] -> [a]
---------------------------------------------------
-- функции readMaybe возвращают либо Nothing, либо Just x
sumMaybe :: Maybe Integer
sumMaybe =
case readMaybe "12" of
Nothing -> Nothing
Just x ->
case readMaybe "34" of
Nothing -> Nothing
Just y ->
case readMaybe "56" of
Nothing -> Nothing
Just z -> Just (x + y + z)
|
nlinker/haskell-you-could
|
src/Step4.hs
|
mit
| 2,982
| 0
| 17
| 590
| 667
| 362
| 305
| 46
| 4
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
module Database.Neo4j.Batch.Node where
import Data.String (fromString)
import qualified Data.Aeson as J
import qualified Data.Text as T
import qualified Network.HTTP.Types as HT
import qualified Database.Neo4j.Graph as G
import Database.Neo4j.Batch.Types
import Database.Neo4j.Types
class NodeBatchIdentifier a where
getNodeBatchId :: a -> T.Text
instance NodeBatchIdentifier Node where
getNodeBatchId = urlMinPath . runNodePath . nodePath
instance NodeBatchIdentifier NodeUrl where
getNodeBatchId = urlMinPath . runNodeUrl
instance NodeBatchIdentifier NodePath where
getNodeBatchId = urlMinPath . runNodePath
instance NodeBatchIdentifier (BatchFuture Node) where
getNodeBatchId (BatchFuture bId) = "{" <> (fromString . show) bId <> "}"
-- | Batch operation to create a node
createNode :: Properties -> Batch (BatchFuture Node)
createNode props = nextState cmd
where cmd = defCmd{cmdMethod = HT.methodPost, cmdPath = "/node", cmdBody = J.toJSON props, cmdParse = parser}
parser n = G.addNode (tryParseBody n)
-- | Batch operation to create a node and assign it a name to easily retrieve it from the resulting graph of the batch
createNamedNode :: String -> Properties -> Batch (BatchFuture Node)
createNamedNode name props = nextState cmd
where cmd = defCmd{cmdMethod = HT.methodPost, cmdPath = "/node", cmdBody = J.toJSON props, cmdParse = parser}
parser n = G.addNamedNode name (tryParseBody n)
-- | Batch operation to get a node from the DB
getNode :: NodeBatchIdentifier a => a -> Batch (BatchFuture Node)
getNode n = nextState cmd
where cmd = defCmd{cmdMethod = HT.methodGet, cmdPath = getNodeBatchId n, cmdBody = "", cmdParse = parser}
parser jn = G.addNode (tryParseBody jn)
-- | Batch operation to get a node from the DB and assign it a name
getNamedNode :: NodeBatchIdentifier a => String -> a -> Batch (BatchFuture Node)
getNamedNode name n = nextState cmd
where cmd = defCmd{cmdMethod = HT.methodGet, cmdPath = getNodeBatchId n, cmdBody = "", cmdParse = parser}
parser jn = G.addNamedNode name (tryParseBody jn)
-- | Batch operation to delete a node
deleteNode :: NodeBatchIdentifier a => a -> Batch (BatchFuture ())
deleteNode n = nextState cmd
where cmd = defCmd{cmdMethod = HT.methodDelete, cmdPath = getNodeBatchId n, cmdBody = "", cmdParse = parser}
parser f = G.deleteNode (NodeUrl $ tryParseFrom f)
|
asilvestre/haskell-neo4j-rest-client
|
src/Database/Neo4j/Batch/Node.hs
|
mit
| 2,494
| 0
| 10
| 456
| 670
| 368
| 302
| 40
| 1
|
{-# htermination sequence :: Monad m => [m a] -> m [a] #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_sequence_1.hs
|
mit
| 59
| 0
| 2
| 13
| 3
| 2
| 1
| 1
| 0
|
import Test.HUnit (Assertion, (@=?), runTestTT, Test(..), Counts(..))
import System.Exit (ExitCode(..), exitWith)
import Sublist (Sublist(Equal, Sublist, Superlist, Unequal), sublist)
exitProperly :: IO Counts -> IO ()
exitProperly m = do
counts <- m
exitWith $ if failures counts /= 0 || errors counts /= 0 then ExitFailure 1 else ExitSuccess
testCase :: String -> Assertion -> Test
testCase label assertion = TestLabel label (TestCase assertion)
main :: IO ()
main = exitProperly $ runTestTT $ TestList
[ TestList sublistTests ]
sublistTests :: [Test]
sublistTests =
[
-- testCase "empty equals empty" $ do
-- Equal @=? sublist "" ""
-- ,
testCase "empty is a sublist of anything" $ do
Sublist @=? sublist "" "asdf"
, testCase "anything is a superlist of empty" $ do
Superlist @=? sublist "asdf" ""
, testCase "1 is not 2" $ do
Unequal @=? sublist "1" "2"
, testCase "compare larger equal lists" $ do
let xs = replicate 1000 'x'
Equal @=? sublist xs xs
, testCase "sublist at start" $ do
Sublist @=? sublist "123" "12345"
, testCase "sublist in middle" $ do
Sublist @=? sublist "432" "54321"
, testCase "sublist at end" $ do
Sublist @=? sublist "345" "12345"
, testCase "partially matching sublist at start" $ do
Sublist @=? sublist "112" "1112"
, testCase "sublist early in huge list" $ do
Sublist @=? sublist [3, 4, 5] [1 .. 1000000 :: Int]
, testCase "huge sublist not in huge list" $ do
Unequal @=? sublist [10 .. 1000001] [1 .. 1000000 :: Int]
, testCase "superlist at start" $ do
Superlist @=? sublist "12345" "123"
, testCase "superlist in middle" $ do
Superlist @=? sublist "54321" "432"
, testCase "superlist at end" $ do
Superlist @=? sublist "12345" "345"
, testCase "partially matching superlist at start" $ do
Superlist @=? sublist "1112" "112"
, testCase "superlist early in huge list" $ do
Superlist @=? sublist [1 .. 1000000] [3, 4, 5 :: Int]
, testCase "recurring values sublist" $ do
Sublist @=? sublist "12123" "1231212321"
, testCase "recurring values unequal" $ do
Unequal @=? sublist "12123" "1231232321"
]
|
tonyfischetti/exercism
|
haskell/sublist/sublist_test.hs
|
mit
| 2,167
| 0
| 12
| 483
| 660
| 335
| 325
| 50
| 2
|
module Method where
import Attribute
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString as B
import Data.Word
import Data.Binary.Get
data Method = Method {
m_access_flags :: Word16,
m_name_index :: Word16,
m_descriptor_index :: Word16,
m_attributes :: [Attribute]
} deriving Show
getMethod = do
access_flags <- getWord16be
name_index <- getWord16be
descriptor_index <- getWord16be
attribute_count <- getWord16be
attributes <- getAttributes (fromIntegral attribute_count)
return (Method access_flags name_index descriptor_index attributes)
getMethods 0 = return []
getMethods n = do
method <- getMethod
rest <- getMethods (n - 1)
return (method:rest)
|
cwgreene/javaclassreader
|
src/Method.hs
|
mit
| 753
| 0
| 10
| 162
| 199
| 107
| 92
| 24
| 1
|
-- | A neat idea. The type in this module WriterC is a Contravariant
-- Functor which allows a user to easily combine writers in interesting
-- fashion with the use of 'contramap'. It's not really necessary, but fun.
module BACnet.Writer.WriterC where
import BACnet.Writer.Core
import BACnet.Writer
import BACnet.Prim (characterStringValue, CharacterString, octetStringBytes, OctetString)
import Data.Word
import Data.Int
import Data.Functor.Contravariant
writerMap :: (b -> a) -> WriterC a -> WriterC b
writerMap f wa = W' (unWriterC wa . f)
instance Contravariant WriterC where
contramap = writerMap
newtype WriterC a = W' { unWriterC :: a -> Writer }
runW' :: WriterC a -> a -> [Word8]
runW' w = runW . unWriterC w
-- Sample WriterC instances
writeUnsignedAP1 :: WriterC Word32
writeUnsignedAP1 = W' writeUnsignedAP
writeUnsignedAP2 :: WriterC Word8
writeUnsignedAP2 = fromIntegral >$< writeUnsignedAP1
writeEvenAP :: WriterC Word32
writeEvenAP = (*2) >$< writeUnsignedAP1
writeNumSat :: (Word32 -> Bool) -> WriterC Word32
writeNumSat = (>$< W' writeBoolAP)
lengthS :: String -> Int32
lengthS = fromIntegral . length
writeStringLength :: WriterC String
writeStringLength = lengthS >$< W' writeSignedAP
writeBoolIfStringIsNotEmpty :: WriterC String
writeBoolIfStringIsNotEmpty = not . Prelude.null >$< W' writeBoolAP
-- Example of converting writeStringAP to be writeCharacterStringAP
writeCharacterStringAP :: WriterC CharacterString
writeCharacterStringAP = characterStringValue >$< W' writeStringAP
writeOctetStringAP' :: WriterC OctetString
writeOctetStringAP' = octetStringBytes >$< W' writeOctetStringAP
|
michaelgwelch/bacnet
|
src/BACnet/Writer/WriterC.hs
|
mit
| 1,637
| 0
| 8
| 240
| 361
| 198
| 163
| -1
| -1
|
{-# LANGUAGE FlexibleInstances #-}
module Test.Data.Raft.Node where
import qualified Data.Sequence as Seq
import Test.QuickCheck.Instances ()
import Test.Tasty.QuickCheck
import Data.Raft.Entry
import Data.Raft.Log
import Data.Raft.Node
import Data.Raft.NodeIdentifier
import Data.Raft.Standing
import Data.Raft.Term
import Data.RaftPrelude
import Test.Data.Raft.Log
import Test.Data.Raft.NodeIdentifier
import Test.Data.Raft.Standing
type IntNode = Node SelfId CandidateId LeaderId
instance Arbitrary (Node Int Int Int) where
arbitrary = genericNode
genericNode :: Gen IntNode
genericNode = Node
<$> arbitrary
<*> arbitrary
<*> arbitrary
genericFollowerNode :: Gen IntNode
genericFollowerNode = Node
<$> genericFollowerStanding
<*> arbitrary
<*> arbitrary
genericCandidateNode :: Gen IntNode
genericCandidateNode = Node
<$> genericCandidateStanding
<*> arbitrary
<*> arbitrary
genericLeaderNode :: Gen IntNode
genericLeaderNode = Node
<$> genericLeaderStanding
<*> arbitrary
<*> arbitrary
genericNonLeaderNode :: Gen IntNode
genericNonLeaderNode = oneof
[ genericFollowerNode
, genericCandidateNode
]
followerNodeAtTerm :: Term -> Gen IntNode
followerNodeAtTerm term = Node
<$> followerStandingAtTerm term
<*> arbitrary
<*> arbitrary
followerNodeSupporting :: NodeIdentifier Int -> Gen IntNode
followerNodeSupporting ident = Node
<$> followerStandingSupporting ident
<*> arbitrary
<*> arbitrary
followerNodeSupportingArbitrary :: Gen IntNode
followerNodeSupportingArbitrary = followerNodeSupporting =<< arbitrary
followerNodeSupportingNoneWithMinimumLog :: Int -> Gen IntNode
followerNodeSupportingNoneWithMinimumLog minLogSize = do
log'@(Log s _) <- scale (\s -> (s + 1) * minLogSize) genericLog
let term = case Seq.viewr s of
EmptyR -> error "Log was constructed with no values."
_ :> last' -> entryTerm last'
Node
<$> followerStandingAtTerm term
<*> arbitrary
<*> pure log'
followerNodeWithExpiredTimeout :: Gen (IntNode, CurrentTime)
followerNodeWithExpiredTimeout = do
(stand, ctime) <- followerStandingWithExpiredTimeout
st <- arbitrary
log' <- arbitrary
return (Node stand st log', ctime)
candidateNodeWithExpiredTimeout :: Gen (IntNode, CurrentTime)
candidateNodeWithExpiredTimeout = do
(stand, ctime) <- candidateStandingWithExpiredTimeout
st <- arbitrary
log' <- arbitrary
return (Node stand st log', ctime)
leaderNodeWithExpiredTimeout :: Gen (IntNode, CurrentTime)
leaderNodeWithExpiredTimeout = do
(stand, ctime) <- leaderStandingWithExpiredTimeout
st <- arbitrary
log' <- arbitrary
return (Node stand st log', ctime)
|
AndrewRademacher/zotac
|
test/Test/Data/Raft/Node.hs
|
mit
| 2,810
| 0
| 13
| 566
| 660
| 350
| 310
| 82
| 2
|
module AnalysisTests(allAnalysisTests,
allModificationCountsTests) where
import Data.Map as M
import Analysis
import TestUtils
allAnalysisTests = do
allModificationCountsTests
allModificationCountsTests = do
testFunction modificationCounts modCountsCases
modCountsCases =
[([], M.empty),
([["a"]], M.fromList [("a", 1)]),
([["x", "y"], ["x", "k"]], M.fromList [("x", 2), ("y", 1), ("k", 1)])]
|
dillonhuff/GitVisualizer
|
test/AnalysisTests.hs
|
gpl-2.0
| 431
| 0
| 9
| 79
| 152
| 94
| 58
| 13
| 1
|
module DMARCAggregateReportTest where
import Test.Framework (testGroup)
import Test.Framework.Providers.HUnit
import Test.HUnit
import Data.Either (isRight)
import Data.String (fromString)
import System.Time (CalendarTime, ClockTime(TOD), toUTCTime)
import qualified Data.ByteString.Lazy as LazyByteString (fromStrict, ByteString)
import Data.ByteString.Lazy.Char8 (pack)
import qualified Data.DMARCAggregateReport as DM
allTests _ = testGroup "DMARCAggregateReport Tests" [
testCase "Parses valid report" testParsesValid,
testCase "Bad XML report" testFailsInvalidXml,
testCase "Bad format report" testFailsInvalidFormat]
testParsesValid = assertEqual "Parse result is success" True (isRight result)
where
result = DM.parseReport $ fromString $ makeReport "127.0.0.1" "pass" "pass"
testFailsInvalidXml = assertEqual "Parse result is invalid XML" True (invalidXml result)
where
invalidXml (Left DM.XMLParseFailure) = True
invalidXml _ = False
result = DM.parseReport $ fromString "invalid xml"
testFailsInvalidFormat = assertEqual "Parse result is invalid format" True (invalidFormat result)
where
invalidFormat (Left DM.InvalidDocument) = True
invalidFormat _ = False
result = DM.parseReport $ fromString doc
doc = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><doc></doc>"
makeReport ip spf dkim = "\
\<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\
\<feedback>\
\<report_metadata>\
\<org_name>google.com</org_name>\
\<email>noreply-dmarc-support@google.com</email>\
\<extra_contact_info>https://support.google.com/a/answer/2466580</extra_contact_info>\
\<report_id>11234</report_id>\
\<date_range>\
\<begin>1439942400</begin>\
\<end>1440028799</end>\
\</date_range>\
\</report_metadata>\
\<policy_published>\
\<domain>example.com</domain>\
\<adkim>r</adkim>\
\<aspf>r</aspf>\
\<p>reject</p>\
\<sp>reject</sp>\
\<pct>100</pct>\
\</policy_published>\
\<record>\
\<row>\
\<source_ip>" ++ ip ++ "</source_ip>\
\<count>2</count>\
\<policy_evaluated>\
\<disposition>none</disposition>\
\<dkim>" ++ dkim ++ "</dkim>\
\<spf>" ++ spf ++ "</spf>\
\</policy_evaluated>\
\</row>\
\<identifiers>\
\<header_from>example.com</header_from>\
\</identifiers>\
\<auth_results>\
\<dkim>\
\<domain>example.com</domain>\
\<result>pass</result>\
\</dkim>\
\<spf>\
\<domain>example.com</domain>\
\<result>pass</result>\
\</spf>\
\</auth_results>\
\</record>\
\</feedback>"
|
splondike/dmarc-check
|
src-test/DMARCAggregateReportTest.hs
|
gpl-2.0
| 2,763
| 0
| 10
| 622
| 339
| 186
| 153
| 29
| 2
|
{-# LANGUAGE NoMonomorphismRestriction #-}
-----------------------------------------------------------------------------
-- |
-- Module :
-- Copyright : (c) 2013 Boyun Tang
-- License : BSD-style
-- Maintainer : tangboyun@hotmail.com
-- Stability : experimental
-- Portability : ghc
--
--
--
-----------------------------------------------------------------------------
module MiRanda.Diagram.Icon
(
onlyM
, mAndT
, true
, false
)
where
import Diagrams.Prelude
import Data.Colour.Names
mChar c = text "M" # fc c # bold <>
roundedRect 1.5 1.5 0.375
# lw 0.15
# lc c
tChar c = text "T" # fc c # bold <>
roundedRect 1.5 1.5 0.375
# lw 0.15
# lc c
utf8Font = "DejaVu Sans YuanTi Condensed"
onlyM = mChar forestgreen # centerXY
mAndT = centerXY $ mChar forestgreen ||| strutX 0.25 ||| tChar crimson
true = scale 2 $ text "✔" # fc forestgreen # font utf8Font <>
rect 0.7 1 # lcA transparent
false = scale 2 $ text "✘" # fc crimson # font utf8Font <>
rect 0.7 1 # lcA transparent
|
tangboyun/miranda
|
src/MiRanda/Diagram/Icon.hs
|
gpl-3.0
| 1,116
| 0
| 10
| 298
| 272
| 137
| 135
| 24
| 1
|
no :: a -> Bool
no _ = False
|
hmemcpy/milewski-ctfp-pdf
|
src/content/1.5/code/haskell/snippet04.hs
|
gpl-3.0
| 28
| 0
| 5
| 8
| 18
| 9
| 9
| 2
| 1
|
module Common.AniTimer (
AniTimer, resetTimer, setTimer, advanceFrames
) where
import Control.Monad.State
data AniTimer = AniTimer {
ttFrameSwap :: Double
} deriving (Eq, Show)
resetTimer :: AniTimer
resetTimer = AniTimer {ttFrameSwap = 0}
setTimer :: Double -> AniTimer
setTimer delay = AniTimer {ttFrameSwap = delay}
advanceFrames :: Int -> Double -> State AniTimer Int
advanceFrames delay frameDelay = do
timer <- get
let anidiff = (ttFrameSwap timer) - (fromIntegral delay)
put$ timer {ttFrameSwap = if anidiff < 0
then frameDelay + (anidiff `realMod` frameDelay)
else anidiff
}
return$ if anidiff < 0
then (truncate(abs anidiff / frameDelay)) + 1 else 0
realMod :: Double -> Double -> Double
x `realMod` y = x - (y * (fromIntegral$truncate (x / y)))
|
CLowcay/CC_Clones
|
src/Common/AniTimer.hs
|
gpl-3.0
| 777
| 12
| 14
| 141
| 299
| 163
| 136
| 21
| 3
|
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Grid.GridData.Fancy.ShadeGeneral
(
ShadeGeneral (..),
loadShadeGeneral,
unloadShadeGeneral,
) where
import MyPrelude
import File
import OpenGL
import OpenGL.Helpers
import OpenGL.Shade
-- | shader for general drawing. to be continued...
data ShadeGeneral =
ShadeGeneral
{
shadeGeneralPrg :: !GLuint,
shadeGeneralUniAlpha :: !GLint,
shadeGeneralUniProjModvMatrix :: !GLint
}
loadShadeGeneral :: IO ShadeGeneral
loadShadeGeneral = do
vsh <- fileStaticData "shaders/General.vsh"
fsh <- fileStaticData "shaders/General.fsh"
prg <- createPrg vsh fsh [ (attPos, "a_pos"),
(attTexCoord, "a_texcoord") ]
[ (tex0, "u_tex") ]
uAlpha <- getUniformLocation prg "u_alpha"
uProjModvMatrix <- getUniformLocation prg "u_projmodv_matrix"
return ShadeGeneral
{
shadeGeneralPrg = prg,
shadeGeneralUniAlpha = uAlpha,
shadeGeneralUniProjModvMatrix = uProjModvMatrix
}
unloadShadeGeneral :: ShadeGeneral -> IO ()
unloadShadeGeneral sh = do
return ()
|
karamellpelle/grid
|
source/Game/Grid/GridData/Fancy/ShadeGeneral.hs
|
gpl-3.0
| 1,930
| 0
| 10
| 485
| 249
| 145
| 104
| 37
| 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.YouTubeReporting.Jobs.Reports.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 reports created by a specific job. Returns NOT_FOUND if the job
-- does not exist.
--
-- /See:/ <https://developers.google.com/youtube/reporting/v1/reports/ YouTube Reporting API Reference> for @youtubereporting.jobs.reports.list@.
module Network.Google.Resource.YouTubeReporting.Jobs.Reports.List
(
-- * REST Resource
JobsReportsListResource
-- * Creating a Request
, jobsReportsList
, JobsReportsList
-- * Request Lenses
, jrlCreatedAfter
, jrlXgafv
, jrlJobId
, jrlUploadProtocol
, jrlAccessToken
, jrlUploadType
, jrlStartTimeAtOrAfter
, jrlStartTimeBefore
, jrlOnBehalfOfContentOwner
, jrlPageToken
, jrlPageSize
, jrlCallback
) where
import Network.Google.Prelude
import Network.Google.YouTubeReporting.Types
-- | A resource alias for @youtubereporting.jobs.reports.list@ method which the
-- 'JobsReportsList' request conforms to.
type JobsReportsListResource =
"v1" :>
"jobs" :>
Capture "jobId" Text :>
"reports" :>
QueryParam "createdAfter" DateTime' :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "startTimeAtOrAfter" DateTime' :>
QueryParam "startTimeBefore" DateTime' :>
QueryParam "onBehalfOfContentOwner" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListReportsResponse
-- | Lists reports created by a specific job. Returns NOT_FOUND if the job
-- does not exist.
--
-- /See:/ 'jobsReportsList' smart constructor.
data JobsReportsList =
JobsReportsList'
{ _jrlCreatedAfter :: !(Maybe DateTime')
, _jrlXgafv :: !(Maybe Xgafv)
, _jrlJobId :: !Text
, _jrlUploadProtocol :: !(Maybe Text)
, _jrlAccessToken :: !(Maybe Text)
, _jrlUploadType :: !(Maybe Text)
, _jrlStartTimeAtOrAfter :: !(Maybe DateTime')
, _jrlStartTimeBefore :: !(Maybe DateTime')
, _jrlOnBehalfOfContentOwner :: !(Maybe Text)
, _jrlPageToken :: !(Maybe Text)
, _jrlPageSize :: !(Maybe (Textual Int32))
, _jrlCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'JobsReportsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'jrlCreatedAfter'
--
-- * 'jrlXgafv'
--
-- * 'jrlJobId'
--
-- * 'jrlUploadProtocol'
--
-- * 'jrlAccessToken'
--
-- * 'jrlUploadType'
--
-- * 'jrlStartTimeAtOrAfter'
--
-- * 'jrlStartTimeBefore'
--
-- * 'jrlOnBehalfOfContentOwner'
--
-- * 'jrlPageToken'
--
-- * 'jrlPageSize'
--
-- * 'jrlCallback'
jobsReportsList
:: Text -- ^ 'jrlJobId'
-> JobsReportsList
jobsReportsList pJrlJobId_ =
JobsReportsList'
{ _jrlCreatedAfter = Nothing
, _jrlXgafv = Nothing
, _jrlJobId = pJrlJobId_
, _jrlUploadProtocol = Nothing
, _jrlAccessToken = Nothing
, _jrlUploadType = Nothing
, _jrlStartTimeAtOrAfter = Nothing
, _jrlStartTimeBefore = Nothing
, _jrlOnBehalfOfContentOwner = Nothing
, _jrlPageToken = Nothing
, _jrlPageSize = Nothing
, _jrlCallback = Nothing
}
-- | If set, only reports created after the specified date\/time are
-- returned.
jrlCreatedAfter :: Lens' JobsReportsList (Maybe UTCTime)
jrlCreatedAfter
= lens _jrlCreatedAfter
(\ s a -> s{_jrlCreatedAfter = a})
. mapping _DateTime
-- | V1 error format.
jrlXgafv :: Lens' JobsReportsList (Maybe Xgafv)
jrlXgafv = lens _jrlXgafv (\ s a -> s{_jrlXgafv = a})
-- | The ID of the job.
jrlJobId :: Lens' JobsReportsList Text
jrlJobId = lens _jrlJobId (\ s a -> s{_jrlJobId = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
jrlUploadProtocol :: Lens' JobsReportsList (Maybe Text)
jrlUploadProtocol
= lens _jrlUploadProtocol
(\ s a -> s{_jrlUploadProtocol = a})
-- | OAuth access token.
jrlAccessToken :: Lens' JobsReportsList (Maybe Text)
jrlAccessToken
= lens _jrlAccessToken
(\ s a -> s{_jrlAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
jrlUploadType :: Lens' JobsReportsList (Maybe Text)
jrlUploadType
= lens _jrlUploadType
(\ s a -> s{_jrlUploadType = a})
-- | If set, only reports whose start time is greater than or equal the
-- specified date\/time are returned.
jrlStartTimeAtOrAfter :: Lens' JobsReportsList (Maybe UTCTime)
jrlStartTimeAtOrAfter
= lens _jrlStartTimeAtOrAfter
(\ s a -> s{_jrlStartTimeAtOrAfter = a})
. mapping _DateTime
-- | If set, only reports whose start time is smaller than the specified
-- date\/time are returned.
jrlStartTimeBefore :: Lens' JobsReportsList (Maybe UTCTime)
jrlStartTimeBefore
= lens _jrlStartTimeBefore
(\ s a -> s{_jrlStartTimeBefore = a})
. mapping _DateTime
-- | The content owner\'s external ID on which behalf the user is acting on.
-- If not set, the user is acting for himself (his own channel).
jrlOnBehalfOfContentOwner :: Lens' JobsReportsList (Maybe Text)
jrlOnBehalfOfContentOwner
= lens _jrlOnBehalfOfContentOwner
(\ s a -> s{_jrlOnBehalfOfContentOwner = a})
-- | A token identifying a page of results the server should return.
-- Typically, this is the value of ListReportsResponse.next_page_token
-- returned in response to the previous call to the \`ListReports\` method.
jrlPageToken :: Lens' JobsReportsList (Maybe Text)
jrlPageToken
= lens _jrlPageToken (\ s a -> s{_jrlPageToken = a})
-- | Requested page size. Server may return fewer report types than
-- requested. If unspecified, server will pick an appropriate default.
jrlPageSize :: Lens' JobsReportsList (Maybe Int32)
jrlPageSize
= lens _jrlPageSize (\ s a -> s{_jrlPageSize = a}) .
mapping _Coerce
-- | JSONP
jrlCallback :: Lens' JobsReportsList (Maybe Text)
jrlCallback
= lens _jrlCallback (\ s a -> s{_jrlCallback = a})
instance GoogleRequest JobsReportsList where
type Rs JobsReportsList = ListReportsResponse
type Scopes JobsReportsList =
'["https://www.googleapis.com/auth/yt-analytics-monetary.readonly",
"https://www.googleapis.com/auth/yt-analytics.readonly"]
requestClient JobsReportsList'{..}
= go _jrlJobId _jrlCreatedAfter _jrlXgafv
_jrlUploadProtocol
_jrlAccessToken
_jrlUploadType
_jrlStartTimeAtOrAfter
_jrlStartTimeBefore
_jrlOnBehalfOfContentOwner
_jrlPageToken
_jrlPageSize
_jrlCallback
(Just AltJSON)
youTubeReportingService
where go
= buildClient
(Proxy :: Proxy JobsReportsListResource)
mempty
|
brendanhay/gogol
|
gogol-youtube-reporting/gen/Network/Google/Resource/YouTubeReporting/Jobs/Reports/List.hs
|
mpl-2.0
| 7,926
| 0
| 23
| 1,917
| 1,235
| 709
| 526
| 172
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.CodeDeploy.CreateDeploymentGroup
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Creates a new deployment group for application revisions to be deployed to.
--
-- <http://docs.aws.amazon.com/codedeploy/latest/APIReference/API_CreateDeploymentGroup.html>
module Network.AWS.CodeDeploy.CreateDeploymentGroup
(
-- * Request
CreateDeploymentGroup
-- ** Request constructor
, createDeploymentGroup
-- ** Request lenses
, cdgApplicationName
, cdgAutoScalingGroups
, cdgDeploymentConfigName
, cdgDeploymentGroupName
, cdgEc2TagFilters
, cdgServiceRoleArn
-- * Response
, CreateDeploymentGroupResponse
-- ** Response constructor
, createDeploymentGroupResponse
-- ** Response lenses
, cdgrDeploymentGroupId
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.CodeDeploy.Types
import qualified GHC.Exts
data CreateDeploymentGroup = CreateDeploymentGroup
{ _cdgApplicationName :: Text
, _cdgAutoScalingGroups :: List "autoScalingGroups" Text
, _cdgDeploymentConfigName :: Maybe Text
, _cdgDeploymentGroupName :: Text
, _cdgEc2TagFilters :: List "ec2TagFilters" EC2TagFilter
, _cdgServiceRoleArn :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'CreateDeploymentGroup' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cdgApplicationName' @::@ 'Text'
--
-- * 'cdgAutoScalingGroups' @::@ ['Text']
--
-- * 'cdgDeploymentConfigName' @::@ 'Maybe' 'Text'
--
-- * 'cdgDeploymentGroupName' @::@ 'Text'
--
-- * 'cdgEc2TagFilters' @::@ ['EC2TagFilter']
--
-- * 'cdgServiceRoleArn' @::@ 'Maybe' 'Text'
--
createDeploymentGroup :: Text -- ^ 'cdgApplicationName'
-> Text -- ^ 'cdgDeploymentGroupName'
-> CreateDeploymentGroup
createDeploymentGroup p1 p2 = CreateDeploymentGroup
{ _cdgApplicationName = p1
, _cdgDeploymentGroupName = p2
, _cdgDeploymentConfigName = Nothing
, _cdgEc2TagFilters = mempty
, _cdgAutoScalingGroups = mempty
, _cdgServiceRoleArn = Nothing
}
-- | The name of an existing AWS CodeDeploy application within the AWS user
-- account.
cdgApplicationName :: Lens' CreateDeploymentGroup Text
cdgApplicationName =
lens _cdgApplicationName (\s a -> s { _cdgApplicationName = a })
-- | A list of associated Auto Scaling groups.
cdgAutoScalingGroups :: Lens' CreateDeploymentGroup [Text]
cdgAutoScalingGroups =
lens _cdgAutoScalingGroups (\s a -> s { _cdgAutoScalingGroups = a })
. _List
-- | If specified, the deployment configuration name must be one of the predefined
-- values, or it can be a custom deployment configuration:
--
-- CodeDeployDefault.AllAtOnce deploys an application revision to up to all of
-- the Amazon EC2 instances at once. The overall deployment succeeds if the
-- application revision deploys to at least one of the instances. The overall
-- deployment fails after the application revision fails to deploy to all of the
-- instances. For example, for 9 instances, deploy to up to all 9 instances at
-- once. The overall deployment succeeds if any of the 9 instances is
-- successfully deployed to, and it fails if all 9 instances fail to be deployed
-- to. CodeDeployDefault.HalfAtATime deploys to up to half of the instances at a
-- time (with fractions rounded down). The overall deployment succeeds if the
-- application revision deploys to at least half of the instances (with
-- fractions rounded up); otherwise, the deployment fails. For example, for 9
-- instances, deploy to up to 4 instances at a time. The overall deployment
-- succeeds if 5 or more instances are successfully deployed to; otherwise, the
-- deployment fails. Note that the deployment may successfully deploy to some
-- instances, even if the overall deployment fails. CodeDeployDefault.OneAtATime
-- deploys the application revision to only one of the instances at a time. The
-- overall deployment succeeds if the application revision deploys to all of the
-- instances. The overall deployment fails after the application revision first
-- fails to deploy to any one instance. For example, for 9 instances, deploy to
-- one instance at a time. The overall deployment succeeds if all 9 instances
-- are successfully deployed to, and it fails if any of one of the 9 instances
-- fail to be deployed to. Note that the deployment may successfully deploy to
-- some instances, even if the overall deployment fails. This is the default
-- deployment configuration if a configuration isn't specified for either the
-- deployment or the deployment group. To create a custom deployment
-- configuration, call the create deployment configuration operation.
cdgDeploymentConfigName :: Lens' CreateDeploymentGroup (Maybe Text)
cdgDeploymentConfigName =
lens _cdgDeploymentConfigName (\s a -> s { _cdgDeploymentConfigName = a })
-- | The name of an existing deployment group for the specified application.
cdgDeploymentGroupName :: Lens' CreateDeploymentGroup Text
cdgDeploymentGroupName =
lens _cdgDeploymentGroupName (\s a -> s { _cdgDeploymentGroupName = a })
-- | The Amazon EC2 tags to filter on.
cdgEc2TagFilters :: Lens' CreateDeploymentGroup [EC2TagFilter]
cdgEc2TagFilters = lens _cdgEc2TagFilters (\s a -> s { _cdgEc2TagFilters = a }) . _List
-- | A service role ARN that allows AWS CodeDeploy to act on the user's behalf
-- when interacting with AWS services.
cdgServiceRoleArn :: Lens' CreateDeploymentGroup (Maybe Text)
cdgServiceRoleArn =
lens _cdgServiceRoleArn (\s a -> s { _cdgServiceRoleArn = a })
newtype CreateDeploymentGroupResponse = CreateDeploymentGroupResponse
{ _cdgrDeploymentGroupId :: Maybe Text
} deriving (Eq, Ord, Read, Show, Monoid)
-- | 'CreateDeploymentGroupResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'cdgrDeploymentGroupId' @::@ 'Maybe' 'Text'
--
createDeploymentGroupResponse :: CreateDeploymentGroupResponse
createDeploymentGroupResponse = CreateDeploymentGroupResponse
{ _cdgrDeploymentGroupId = Nothing
}
-- | A unique deployment group ID.
cdgrDeploymentGroupId :: Lens' CreateDeploymentGroupResponse (Maybe Text)
cdgrDeploymentGroupId =
lens _cdgrDeploymentGroupId (\s a -> s { _cdgrDeploymentGroupId = a })
instance ToPath CreateDeploymentGroup where
toPath = const "/"
instance ToQuery CreateDeploymentGroup where
toQuery = const mempty
instance ToHeaders CreateDeploymentGroup
instance ToJSON CreateDeploymentGroup where
toJSON CreateDeploymentGroup{..} = object
[ "applicationName" .= _cdgApplicationName
, "deploymentGroupName" .= _cdgDeploymentGroupName
, "deploymentConfigName" .= _cdgDeploymentConfigName
, "ec2TagFilters" .= _cdgEc2TagFilters
, "autoScalingGroups" .= _cdgAutoScalingGroups
, "serviceRoleArn" .= _cdgServiceRoleArn
]
instance AWSRequest CreateDeploymentGroup where
type Sv CreateDeploymentGroup = CodeDeploy
type Rs CreateDeploymentGroup = CreateDeploymentGroupResponse
request = post "CreateDeploymentGroup"
response = jsonResponse
instance FromJSON CreateDeploymentGroupResponse where
parseJSON = withObject "CreateDeploymentGroupResponse" $ \o -> CreateDeploymentGroupResponse
<$> o .:? "deploymentGroupId"
|
dysinger/amazonka
|
amazonka-codedeploy/gen/Network/AWS/CodeDeploy/CreateDeploymentGroup.hs
|
mpl-2.0
| 8,355
| 0
| 10
| 1,607
| 830
| 508
| 322
| 93
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import Control.Monad (forM_)
import Control.Exception.Base (bracket)
-- For IsString / OverloadedStrings
import Data.ByteString.Char8 (ByteString, unpack)
import Data.ByteString.Lazy.Char8 ()
import Network.Socket
import qualified Network.Arakoon.Client as A
host :: String
host = "127.0.0.1"
port :: PortNumber
port = 4000
clusterId :: A.ClusterId
clusterId = "arakoon"
protocolVersion :: A.ProtocolVersion
protocolVersion = 1
main :: IO ()
main = withSocketsDo $ do
addr <- inet_addr host
bracket
(socket AF_INET Stream defaultProtocol)
sClose
$ \s -> do
connect s $ SockAddrInet port addr
A.sendPrologue s clusterId protocolVersion
putStr "ping: "
A.ping s "clientid" clusterId >>= print
putStr "version: "
A.version s >>= print
putStr "whoMaster: "
A.whoMaster s >>= print
putStr "set: "
A.set s "key" "value" >>= print
putStr "get: "
A.get s False "key" >>= print
putStr "delete: "
A.delete s "key" >>= print
putStr "sequence assertExists (fails): "
A.sequence s [A.SequenceAssertExists "key"] >>= print
putStr "syncedSequence: "
A.syncedSequence s [ A.SequenceAssert "key" Nothing
, A.SequenceSet "key" "value"
, A.SequenceAssertExists "key"
, A.SequenceAssert "key" (Just "value")
, A.SequenceDelete "key"
, A.SequenceAssert "key" Nothing
, A.SequenceSet "key" "value"
, A.SequenceSet "key2" "value2"
] >>= print
putStr "rangeEntries: "
A.rangeEntries s False (Just "key") True (Just "key3") True (-1) >>= print
A.sequence s Nothing >>= print
A.sequence s (Just $ A.SequenceSet "key3" "value3") >>= print
putStrLn "Statistics:"
A.statistics s >>= \r -> case r of
Left{} -> print r
Right (A.NodeStatistics i) -> forM_ i $ printStatistics " "
printStatistics :: String -> (ByteString, A.FieldValue) -> IO ()
printStatistics p (n, i) = case i of
A.FVInt32 v -> putStrLn $ p ++ unpack n ++ ": i32 " ++ show v
A.FVInt64 v -> putStrLn $ p ++ unpack n ++ ": i64 " ++ show v
A.FVFloat v -> putStrLn $ p ++ unpack n ++ ": d " ++ show v
A.FVString v -> putStrLn $ p ++ unpack n ++ ": s " ++ show v
A.FVList v -> case v of
[] -> putStrLn $ p ++ unpack n ++ ": []"
_ -> do
putStrLn $ p ++ unpack n ++ ":"
forM_ v $ printStatistics $ p ++ " "
|
NicolasT/harakoon
|
bin/demo.hs
|
lgpl-2.1
| 2,867
| 0
| 20
| 1,030
| 863
| 414
| 449
| 68
| 6
|
import Test.Hspec
import Data.List
import Digits
digits_sum :: Integral x => x -> x
digits_sum x = foldl (+) 0 (digits_list x)
-- Tests + result print
main = hspec $ do
describe "Dummy" $ do
it "dummy test" $ do
True `shouldBe` True
describe "Euler test" $ do
it "2^15 digits sum" $ do
(digits_sum (2^15)) `shouldBe` 26
describe "Euler actual problem" $ do
it "2^1000 digits sum" $ do
putStrLn ("res = " ++ show (digits_sum (2^1000)))
|
orbitgray/ProjectEuler
|
haskell/016.hs
|
lgpl-3.0
| 509
| 0
| 21
| 153
| 183
| 89
| 94
| 15
| 1
|
module Util where
import Test.QuickCheck
halfSize :: (Int -> Gen a) -> Gen a
halfSize m = sized $ \s -> resize (s `div` 2) (m s)
divSize :: Int -> (Int -> Gen a) -> Gen a
divSize d m = sized $ \s -> resize (s `div` d) (m s)
coordss :: Int -> Int -> [[Int]]
coordss n _ | n < 0 = [[]]
coordss 0 d = [replicate d 0]
coordss n d = concat [ map (++ replicate t n) (coordss (n-1) (d-t)) | t <- [0..d] ]
|
danr/structural-induction
|
test/Util.hs
|
lgpl-3.0
| 403
| 0
| 11
| 99
| 260
| 137
| 123
| 10
| 1
|
module Main where
import Control.Concurrent (threadDelay, forkIO)
import Control.Monad (liftM, when)
import Control.Monad.Trans (liftIO)
import qualified Graphics.UI.Gtk as GTK
import Graphics.UI.Gtk.Builder (builderNew, builderAddFromFile, builderGetObject)
import Data.Board (Board, newBoard, emptyBoard)
import Interface.Board (Cell, BoardState(..), translate)
import UI.SharedMem (Display(..), initDisplay, Mem, newMem, atomically,
display, alterBoard, alterDisplay, cellAt, mapPair)
import UI.Board (drawBoard, highlightCell)
main :: IO ()
main = do
state <- atomically $ newMem initBoard initDisplay
GTK.initGUI
builder <- builderNew
builderAddFromFile builder "UI/life.glade"
mainWin <- builderGetObject builder GTK.castToWindow "mainWin"
mainWin `GTK.on` GTK.deleteEvent $ liftIO GTK.mainQuit >> return False
GTK.widgetShowAll mainWin
gameView <- builderGetObject builder GTK.castToDrawingArea "gameView"
viewport <- GTK.widgetGetDrawWindow gameView
[nextBtn, prevBtn] <- sequence $
map (getButton builder) ["nextBtn", "prevBtn"]
[alterBtn, playBtn] <- sequence $
map (getToggle builder) ["alterBtn", "playBtn"]
arrowCursor <- GTK.cursorNew GTK.Arrow
GTK.drawWindowSetCursor viewport $ Just arrowCursor
GTK.widgetAddEvents gameView [GTK.PointerMotionMask]
mainWin `GTK.on` GTK.keyPressEvent $ keyMoveDisplay state viewport
gameView `GTK.on` GTK.exposeEvent $ do
liftIO $ do
updateDisplaySize gameView state
drawBoard viewport state
return False
gameView `GTK.on` GTK.motionNotifyEvent $ do
liftIO $ GTK.toggleButtonGetActive alterBtn >>= \alt -> when alt $
liftM (mapPair $ flip div 10) (GTK.widgetGetPointer gameView)
>>= highlightCell viewport state
return False
gameView `GTK.on` GTK.leaveNotifyEvent $ do
liftIO $ drawBoard viewport state
return False
gameView `GTK.on` GTK.buttonPressEvent $ do
liftIO $ GTK.toggleButtonGetActive alterBtn >>= \alt -> when alt $ do
cell <- GTK.widgetGetPointer gameView >>= cellFromCoordinates state
atomically $ alterBoard (alter cell) state
return False
let withBoard f = liftIO (alterBoardAction state viewport f) >> return False
nextBtn `GTK.on` GTK.buttonReleaseEvent $ withBoard next
prevBtn `GTK.on` GTK.buttonReleaseEvent $ withBoard previous
playBtn `GTK.on` GTK.buttonReleaseEvent $ do
isOn <- liftIO $ GTK.toggleButtonGetActive playBtn
liftIO . atomically $ alterDisplay (\d -> d { autoNext = not isOn }) state
return False
forkIO $ autoPlay state viewport
GTK.mainGUI
where
initBoard = newBoard [(3, 4), (3, 5), (3, 6)]
getButton bld name = builderGetObject bld GTK.castToButton name
getToggle bld name = builderGetObject bld GTK.castToToggleButton name
alterBoardAction :: BoardState b => Mem b -> GTK.DrawWindow -> (b -> b) -> IO ()
alterBoardAction state viewport f = do
atomically $ alterBoard f state
drawBoard viewport state
keyMoveDisplay :: BoardState b => Mem b -> GTK.DrawWindow -> GTK.EventM GTK.EKey Bool
keyMoveDisplay state viewport = do
movement <- liftM keyToMvmnt GTK.eventKeyVal
liftIO $ do
atomically $ alterDisplay (move movement) state
drawBoard viewport state
return True
where
keyToMvmnt 65361 = ((-1), 0) -- left
keyToMvmnt 65362 = (0, (-1)) -- up
keyToMvmnt 65363 = (1, 0) -- right
keyToMvmnt 65364 = (0, 1) -- down
keyToMvmnt _ = (0, 0)
move (x, y) displ = let (fx, fy) = firstCell displ
(lx, ly) = lastCell displ in displ {
firstCell = (fx + x, fy + y),
lastCell = (lx + x, ly + y)
}
updateDisplaySize :: (BoardState b, GTK.WidgetClass v) => v -> Mem b -> IO ()
updateDisplaySize view mem = liftIO $ do
(width, height) <- liftM rectSize $ GTK.widgetGetAllocation view
let size = (width `div` 10, height `div` 10)
atomically $ do
first <- liftM firstCell $ display mem
alterDisplay (update $ translate first size) mem
where
rectSize (GTK.Rectangle fx fy lx ly) = (lx - fx, ly - fy)
update cell disp = disp { lastCell = cell }
cellFromCoordinates :: Mem b -> (Int, Int) -> IO Cell
cellFromCoordinates state coords = atomically $ cellAt state coords
autoPlay :: BoardState b => Mem b -> GTK.DrawWindow -> IO ()
autoPlay state view = do
auto <- atomically $ liftM autoNext (display state)
when auto $ GTK.postGUIAsync $ alterBoardAction state view next
threadDelay 1000000
autoPlay state view
|
Sventimir/game-of-life
|
Main.hs
|
apache-2.0
| 5,064
| 0
| 18
| 1,473
| 1,613
| 811
| 802
| 97
| 5
|
module DVPMessage where
import NetAddress
data DVPVec = DVPVec {dvPAddr :: NetAddress, dvpCost :: Int} deriving Show
type DVPMsg = [DVPVec]
|
hdb3/FP-Router
|
DVPMessage.hs
|
apache-2.0
| 141
| 0
| 8
| 22
| 40
| 26
| 14
| 4
| 0
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Primitive Definitions for Compiler-Wide Terms.
module Language.K3.Core.Common (
Identifier,
NoneMutability(..),
UID(..),
gUID,
ParGenSymS(..),
zerosymS,
resetsymS,
contigsymS,
contigsymAtS,
lowerboundsymS,
advancesymS,
rewindsymS,
forksymS,
gensym,
Address(..),
defaultAddress,
Span(..),
coverSpans,
prefixSpan,
EndpointSpec(..),
IShow(..),
IRead(..),
ireadEither,
iread,
addAssoc,
insertAssoc,
removeAssoc,
replaceAssoc,
modifyAssoc,
HasUID(..),
HasSpan(..)
) where
import Control.Concurrent.MVar
import Control.DeepSeq
import Data.Binary ( Binary )
import Data.Serialize ( Serialize )
import qualified Data.Binary as B
import qualified Data.Serialize as S
import Data.Char
import Data.Hashable ( Hashable(..) )
import Data.IORef
import Data.Typeable
import Data.Word ( Word8 )
import Data.HashMap.Lazy ( HashMap )
import qualified Data.HashMap.Lazy as HashMap ( toList, fromList )
import Criterion.Types
import GHC.Generics (Generic)
import Text.ParserCombinators.ReadP as TP
import Text.ParserCombinators.ReadPrec as TRP
import Text.Read as TR
import Language.K3.Utils.Pretty
-- | Identifiers are used everywhere.
type Identifier = String
-- | Address implementation
data Address = Address !(String, Int) deriving (Eq, Ord, Typeable, Generic)
defaultAddress :: Address
defaultAddress = Address ("127.0.0.1", 40000)
-- | Spans are either locations in the program source, or generated code.
data Span
= Span !String !Int !Int !Int !Int
-- ^ Source name, start line and column, end line and column.
| GeneratedSpan !Word8
-- ^ Generator-specific metadata.
deriving (Eq, Ord, Read, Show, Typeable, Generic)
-- | Unique identifiers for AST nodes.
data UID = UID !Int deriving (Eq, Ord, Read, Show, Typeable, Generic)
instance Hashable UID
gUID :: UID -> Int
gUID (UID i) = i
{- Symbol generation -}
data ParGenSymS = ParGenSymS { stride :: !Int, offset :: !Int, current :: !Int }
deriving (Eq, Ord, Read, Show, Generic)
zerosymS :: Int -> Int -> ParGenSymS
zerosymS str off = ParGenSymS str off off
resetsymS :: ParGenSymS -> ParGenSymS
resetsymS (ParGenSymS str off _) = ParGenSymS str off off
contigsymS :: ParGenSymS
contigsymS = ParGenSymS 1 0 0
contigsymAtS :: Int -> ParGenSymS
contigsymAtS cur = ParGenSymS 1 0 cur
lowerboundsymS :: Int -> ParGenSymS -> ParGenSymS
lowerboundsymS lb s@(ParGenSymS str off cur)
| cur <= lb = ParGenSymS str off ((lb `divceil` str) * str + off)
| otherwise = s
where divceil x y = let (a,b) = x `divMod` y in (a + (if b == 0 then 0 else 1))
advancesymS :: Int -> ParGenSymS -> Maybe ParGenSymS
advancesymS deltaOff (ParGenSymS str off i)
| deltaOff + off >= str = Nothing
| otherwise = Just $ ParGenSymS str (off + deltaOff) i
rewindsymS :: ParGenSymS -> ParGenSymS -> ParGenSymS
rewindsymS (ParGenSymS sa oa ca) (ParGenSymS sb ob cb) = ParGenSymS (max sa sb) (min oa ob) (max ca cb)
forksymS :: Int -> ParGenSymS -> ParGenSymS
forksymS i (ParGenSymS str off cur)
| i > 0 = ParGenSymS (i*str) off cur
| otherwise = error "Invalid symbol generator fork factor."
gensym :: ParGenSymS -> (ParGenSymS, Int)
gensym (ParGenSymS str off cur) = (ParGenSymS str off (cur + str), cur + off)
instance NFData ParGenSymS
instance Binary ParGenSymS
instance Serialize ParGenSymS
-- |Mutability modes for @CNone@. These are kept distinct from the expression
-- annotations because e.g. @mut (mut None mut, mut None mut)@ must have a
-- place to put each @mut@ without overlapping.
data NoneMutability
= NoneMut
| NoneImmut
deriving (Eq, Ord, Read, Show, Typeable, Generic)
-- | Endpoint types.
data EndpointSpec
= ValueEP
| BuiltinEP String String
-- ^ Builtin endpoint type (stdin/stdout/stderr), format
| FileEP String Bool String
-- ^ File path (as expression or literal), text/binary, format
| FileSeqEP String Bool String
-- ^ File sequence path collection (as expression), text/binary, format
| FileMuxEP String Bool String
-- ^ File path collection (as expression), text/binary, format
| FileMuxseqEP String Bool String
-- ^ File sequence collection (as expression), text/binary, format
| PolyFileMuxEP String Bool String String String
-- ^ File path collection, text/binary, format, order file, rebatch size variable
| PolyFileMuxSeqEP String Bool String String String
-- ^ File sequence collection, text/binary, format, order file, rebatch size variable
| NetworkEP String Bool String
-- ^ Address, text/binary, format
deriving (Eq, Ord, Read, Show, Typeable, Generic)
-- | Union two spans.
coverSpans :: Span -> Span -> Span
coverSpans (Span n l1 c1 _ _) (Span _ _ _ l2 c2) = Span n l1 c1 l2 c2
coverSpans s@(Span _ _ _ _ _) (GeneratedSpan _) = s
coverSpans (GeneratedSpan _) s@(Span _ _ _ _ _) = s
coverSpans (GeneratedSpan s1) (GeneratedSpan s2) =
GeneratedSpan $! fromIntegral ((fromIntegral s1 :: Int) `hashWithSalt` s2)
-- | Left extension of a span.
prefixSpan :: Int -> Span -> Span
prefixSpan i (Span n l1 c1 l2 c2) = Span n l1 (c1-i) l2 c2
prefixSpan _ s = s
-- | Associative lists
-- | Adds an association at the head of the list, allowing for duplicates.
addAssoc :: Eq a => [(a,b)] -> a -> b -> [(a,b)]
addAssoc l a b = (a,b):l
-- | Adds an association only if it does not already exist in the list.
insertAssoc :: Eq a => [(a,b)] -> a -> b -> [(a,b)]
insertAssoc l a b = maybe (addAssoc l a b) (const l) $ lookup a l
-- | Removes all associations matching the given key from the list.
removeAssoc :: Eq a => [(a,b)] -> a -> [(a,b)]
removeAssoc l a = filter ((a /=) . fst) l
-- | Replaces all associations matching the given key, with a single new association.
replaceAssoc :: Eq a => [(a,b)] -> a -> b -> [(a,b)]
replaceAssoc l a b = addAssoc (removeAssoc l a) a b
-- | Applies a modifier to the first occurrence of the key, replacing all associations
-- with the result of the modifier.
modifyAssoc :: Eq a => [(a,b)] -> a -> (Maybe b -> (c, Maybe b)) -> (c, [(a,b)])
modifyAssoc l k f = case f $ lookup k l of
(r, Nothing) -> (r, l)
(r, Just nv) -> (r, replaceAssoc l k nv)
{- Instance implementations -}
instance NFData Address
instance NFData Span
instance NFData UID
instance NFData NoneMutability
instance NFData EndpointSpec
instance Binary Address
instance Binary Span
instance Binary UID
instance Binary NoneMutability
instance Binary EndpointSpec
instance Serialize Address
instance Serialize Span
instance Serialize UID
instance Serialize NoneMutability
instance Serialize EndpointSpec
instance Show Address where
show (Address (host, port)) = host ++ ":" ++ show port
instance Read Address where
readPrec = parens $ do
host <- lift $ munch1 $ \c -> isAlpha c || isDigit c || c == '.'
Symbol ":" <- lexP
port <- readPrec
return (Address (host, port))
instance Hashable Address where
hashWithSalt salt (Address (host,port)) = hashWithSalt salt (host, port)
instance Pretty Address where
prettyLines addr = [show addr]
instance Pretty UID where
prettyLines (UID n) = [show n]
-- | Show and read of impure values
class IShow a where
ishow :: a -> IO String
instance (Show a) => IShow a where
ishow = return . show
class IRead a where
ireadPrec :: ReadPrec (IO a)
instance (Read a) => IRead a where
ireadPrec = readPrec >>= return . return
ireadEither :: (IRead a) => String -> IO (Either String a)
ireadEither s =
case [ x | (x,"") <- readPrec_to_S read' minPrec s ] of
[x] -> x >>= return . Right
[] -> return $ Left "iread: no parse"
_ -> return $ Left "iread: ambiguous parse"
where
read' = do
x <- ireadPrec
TRP.lift TP.skipSpaces
return x
iread :: (IRead a) => String -> IO a
iread s = ireadEither s >>= return . either error id
-- | IShow, and IRead instance for mutable values.
instance (IShow a) => IShow (IORef a) where
ishow r = readIORef r >>= ishow >>= return . ("IORef " ++)
instance (IShow a) => IShow (MVar a) where
ishow mv = readMVar mv >>= ishow >>= return . ("MVar " ++)
instance (IRead a) => IRead (IORef a) where
ireadPrec = parens ( do
TR.Ident s <- TR.lexP
case s of
"IORef" -> ireadPrec >>= return . (>>= newIORef)
_ -> TRP.pfail
)
instance (IRead a) => IRead (MVar a) where
ireadPrec = parens ( do
TR.Ident s <- TR.lexP
case s of
"MVar" -> ireadPrec >>= return . (>>= newMVar)
_ -> TRP.pfail
)
class HasUID a where
getUID :: a -> Maybe UID
class HasSpan a where
getSpan :: a -> Maybe Span
{- Additional instances -}
instance (Binary k, Binary v, Eq k, Hashable k) => Binary (HashMap k v) where
put = B.put . HashMap.toList
get = fmap HashMap.fromList B.get
instance (Serialize k, Serialize v, Eq k, Hashable k) => Serialize (HashMap k v) where
put = S.put . HashMap.toList
get = fmap HashMap.fromList S.get
instance Serialize Measured where
put Measured{..} = do
S.put measTime; S.put measCpuTime; S.put measCycles; S.put measIters
S.put measAllocated; S.put measNumGcs; S.put measBytesCopied
S.put measMutatorWallSeconds; S.put measMutatorCpuSeconds
S.put measGcWallSeconds; S.put measGcCpuSeconds
get = Measured <$> S.get <*> S.get <*> S.get <*> S.get
<*> S.get <*> S.get <*> S.get <*> S.get <*> S.get <*> S.get <*> S.get
|
DaMSL/K3
|
src/Language/K3/Core/Common.hs
|
apache-2.0
| 9,734
| 0
| 17
| 2,127
| 3,169
| 1,683
| 1,486
| 240
| 3
|
module Main where
import Distribution.Text (display)
import Paths_git_sanity (version)
import System.Environment
import System.Exit
import Git.Sanity (analyze)
name :: String
name = "git-sanity"
help :: IO ()
help = putStrLn $
unlines [ concat ["Usage: ", name, " [check [<revision range>]]" ]
, " [--help]"
, " [--version]"
, ""
, " <revision range> Check only commits in the specified revision range."
, ""
, "When no <revision range> is specified, it defaults to HEAD (i.e. the whole history leading to the current commit)."
, ""
, "In order to integrate nicely as a pre-push githooks (http://git-scm.com/docs/githooks.html),"
, "a <revision range> of 'origin/$branch~1..HEAD'[1] can be used."
, ""
, "[1] Where 'branch' is a variable defined as 'branch=$(git symbolic-ref --short HEAD)'" ]
main :: IO ()
main = do
args <- getArgs
run args where
check range = do
(exitCode, total) <- analyze range
if total == 0 then
exitWith exitCode
else do
putStrLn ""
putStrLn $ concat [name, ": ", show total, " insane commit(s)."]
exitFailure
run ["check", range] = check range
run ["check"] = check "HEAD"
run ["--version"] = putStrLn $ concat [name, ": ", display version]
run ["--help"] = help
run [] = help
run (x:_) = do
putStrLn $ concat [name, ": '", x,"' is not a valid command. See '", name, " --help'."]
exitWith (ExitFailure 1)
|
aloiscochard/git-sanity
|
src/Main.hs
|
apache-2.0
| 1,625
| 0
| 15
| 514
| 365
| 197
| 168
| 42
| 7
|
module FractalFlame.Flam3.Types.Flame where
import FractalFlame.Camera.Types.Camera
import FractalFlame.Flam3.Types.Xform
import FractalFlame.Flam3.Types.Color
import FractalFlame.Palette.Types.Palette
import FractalFlame.Types.Base
import FractalFlame.Types.Size
data FlameColors = ColorList [Color] | ColorPalette Palette
data Flame = Flame {
colors :: FlameColors
, xforms :: [Xform]
, finalXform :: Maybe Xform
, camera :: Camera
, symmetry :: Int
, gamma :: Coord
, vibrancy :: Coord
, quality :: Int
}
|
anthezium/fractal_flame_renderer_haskell
|
FractalFlame/Flam3/Types/Flame.hs
|
bsd-2-clause
| 556
| 0
| 9
| 109
| 128
| 84
| 44
| 17
| 0
|
-- http://www.codewars.com/kata/54da539698b8a2ad76000228
module Codewars.Kata.TenMinuteWalk where
isValidWalk :: String -> Bool
isValidWalk walk = not (null w') && null w'' && f 'n' == f 's' && f 'e' == f 'w' where
w' = drop 9 walk
(_:w'') = w'
f ch = length $ filter (==ch) walk
|
Bodigrim/katas
|
src/haskell/6-Take-a-Ten-Minute-Walk.hs
|
bsd-2-clause
| 295
| 0
| 12
| 63
| 115
| 58
| 57
| 6
| 1
|
{-# LANGUAGE RecordWildCards #-}
-----------------------------------------------------------------------------
-- |
-- Module : FFICXX.Generate.Code.Dependency
-- Copyright : (c) 2011-2013 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <ianwookim@gmail.com>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module FFICXX.Generate.Code.Dependency where
import Control.Applicative
import Data.Function (on)
import Data.List
import Data.Maybe
import System.FilePath
--
import FFICXX.Generate.Type.Class
--
-- import Debug.Trace
-- |
mkPkgHeaderFileName ::Class -> String
mkPkgHeaderFileName c =
(cabal_cheaderprefix.class_cabal) c ++ class_name c <.> "h"
-- |
mkPkgCppFileName ::Class -> String
mkPkgCppFileName c =
(cabal_cheaderprefix.class_cabal) c ++ class_name c <.> "cpp"
-- |
mkPkgIncludeHeadersInH :: Class -> [String]
mkPkgIncludeHeadersInH c =
let pkgname = (cabal_pkgname . class_cabal) c
extclasses = (filter ((/= pkgname) . cabal_pkgname . class_cabal) . mkModuleDepCpp) c
extheaders = nub . map ((++"Type.h") . cabal_pkgname . class_cabal) $ extclasses
in map mkPkgHeaderFileName (class_allparents c) ++ extheaders
-- |
mkPkgIncludeHeadersInCPP :: Class -> [String]
mkPkgIncludeHeadersInCPP = map mkPkgHeaderFileName . mkModuleDepCpp
-- |
mkCIH :: (Class->([Namespace],[String])) -- ^ (mk namespace and include headers)
-> Class
-> ClassImportHeader
mkCIH mkNSandIncHdrs c = let r = ClassImportHeader c
(mkPkgHeaderFileName c)
((fst . mkNSandIncHdrs) c)
(mkPkgCppFileName c)
(mkPkgIncludeHeadersInH c)
(mkPkgIncludeHeadersInCPP c)
((snd . mkNSandIncHdrs) c)
in r
-- |
extractClassFromType :: Types -> Maybe Class
extractClassFromType Void = Nothing
extractClassFromType SelfType = Nothing
extractClassFromType (CT _ _) = Nothing
extractClassFromType (CPT (CPTClass c) _) = Just c
extractClassFromType (CPT (CPTClassRef c) _) = Just c
-- | class dependency for a given function
data Dep4Func = Dep4Func { returnDependency :: Maybe Class
, argumentDependency :: [Class] }
-- |
extractClassDep :: Function -> Dep4Func
extractClassDep (Constructor args _) = Dep4Func Nothing (catMaybes (map (extractClassFromType.fst) args))
extractClassDep (Virtual ret _ args _) =
Dep4Func (extractClassFromType ret) (mapMaybe (extractClassFromType.fst) args)
extractClassDep (NonVirtual ret _ args _) =
Dep4Func (extractClassFromType ret) (mapMaybe (extractClassFromType.fst) args)
extractClassDep (Static ret _ args _) =
Dep4Func (extractClassFromType ret) (mapMaybe (extractClassFromType.fst) args)
{- extractClassDep (AliasVirtual ret _ args _) =
Dep4Func (extractClassFromType ret) (mapMaybe (extractClassFromType.fst) args) -}
extractClassDep (Destructor _) =
Dep4Func Nothing []
extractClassDepForTopLevelFunction :: TopLevelFunction -> Dep4Func
extractClassDepForTopLevelFunction f =
Dep4Func (extractClassFromType ret) (mapMaybe (extractClassFromType.fst) args)
where ret = case f of
TopLevelFunction {..} -> toplevelfunc_ret
TopLevelVariable {..} -> toplevelvar_ret
args = case f of
TopLevelFunction {..} -> toplevelfunc_args
TopLevelVariable {..} -> []
-- |
mkModuleDepRaw :: Class -> [Class]
mkModuleDepRaw c = (nub . filter (/= c) . mapMaybe (returnDependency.extractClassDep) . class_funcs) c
-- |
mkModuleDepHighNonSource :: Class -> [Class]
mkModuleDepHighNonSource c =
let fs = class_funcs c
pkgname = (cabal_pkgname . class_cabal) c
extclasses = (filter (\x-> x /= c && ((/= pkgname) . cabal_pkgname . class_cabal) x) . concatMap (argumentDependency.extractClassDep)) fs
parents = class_parents c
in nub (parents ++ extclasses)
-- |
mkModuleDepHighSource :: Class -> [Class]
mkModuleDepHighSource c =
let fs = class_funcs c
pkgname = (cabal_pkgname . class_cabal) c
in nub . filter (\x-> x /= c && not (x `elem` class_parents c) && (((== pkgname) . cabal_pkgname . class_cabal) x)) . concatMap (argumentDependency.extractClassDep) $ fs
-- |
mkModuleDepCpp :: Class -> [Class]
mkModuleDepCpp c =
let fs = class_funcs c
in nub . filter (/= c) $
mapMaybe (returnDependency.extractClassDep) fs
++ concatMap (argumentDependency.extractClassDep) fs
++ (class_parents c)
-- |
mkModuleDepFFI4One :: Class -> [Class]
mkModuleDepFFI4One c =
let fs = class_funcs c
in (++) <$> mapMaybe (returnDependency.extractClassDep)
<*> concatMap (argumentDependency.extractClassDep)
$ fs
-- |
mkModuleDepFFI :: Class -> [Class]
mkModuleDepFFI c =
let ps = class_allparents c
alldeps' = (concatMap mkModuleDepFFI4One ps) ++ mkModuleDepFFI4One c
alldeps = nub (filter (/= c) alldeps')
in alldeps
mkClassModule :: (Class->([Namespace],[String]))
-> Class
-> ClassModule
mkClassModule mkincheaders c =
let r = (ClassModule <$> getClassModuleBase
<*> pure
<*> return . mkCIH mkincheaders
<*> highs_nonsource
<*> raws
<*> highs_source
<*> ffis
) c
in r
where highs_nonsource = map getClassModuleBase . mkModuleDepHighNonSource
raws = map getClassModuleBase . mkModuleDepRaw
highs_source = map getClassModuleBase . mkModuleDepHighSource
ffis = map getClassModuleBase . mkModuleDepFFI
mkAll_ClassModules_CIH_TIH :: (String,Class->([Namespace],[String])) -- ^ (package name,mkIncludeHeaders)
-> ([Class],[TopLevelFunction])
-> ([ClassModule],[ClassImportHeader],TopLevelImportHeader)
mkAll_ClassModules_CIH_TIH (pkgname,mkNSandIncHdrs) (cs,fs) =
let ms = map (mkClassModule mkNSandIncHdrs) cs
cmpfunc x y = class_name (cihClass x) == class_name (cihClass y)
cihs = nubBy cmpfunc (concatMap cmCIH ms)
-- for toplevel
tl_cs1 = concatMap (argumentDependency . extractClassDepForTopLevelFunction) fs
tl_cs2 = mapMaybe (returnDependency . extractClassDepForTopLevelFunction) fs
tl_cs = nubBy ((==) `on` class_name) (tl_cs1 ++ tl_cs2)
tl_cihs = catMaybes $
foldr (\c acc-> (find (\x -> (class_name . cihClass) x == class_name c) cihs):acc) [] tl_cs
--
tih = TopLevelImportHeader (pkgname ++ "TopLevel") tl_cihs fs
in (ms,cihs,tih)
mkHSBOOTCandidateList :: [ClassModule] -> [String]
mkHSBOOTCandidateList ms = nub (concatMap cmImportedModulesHighSource ms)
|
Gabriel439/fficxx
|
lib/FFICXX/Generate/Code/Dependency.hs
|
bsd-2-clause
| 7,019
| 0
| 21
| 1,748
| 1,865
| 994
| 871
| 126
| 3
|
{-# LANGUAGE OverloadedStrings #-}
module HEP.Automation.Model.Server.Type where
import Control.Applicative
import Data.Text.Encoding as E
import Data.UUID
import qualified Data.ByteString.Char8 as C
import qualified Data.ByteString as B
import Yesod.Dispatch
import Text.Blaze
import HEP.Automation.Model.Type
-- import Debug.Trace
import Data.Acid
instance SinglePiece UUID where
fromSinglePiece = fromString . C.unpack . E.encodeUtf8
toSinglePiece = E.decodeUtf8 . C.pack . toString
instance ToHtml UUID where
toHtml = toHtml . toString
data ModelServer = ModelServer {
server_acid :: AcidState ModelInfoRepository
}
|
wavewave/model-server
|
lib/HEP/Automation/Model/Server/Type.hs
|
bsd-2-clause
| 637
| 0
| 9
| 90
| 145
| 89
| 56
| 18
| 0
|
{-# OPTIONS_GHC -fno-cse #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Main (main) where
import Control.Exception (SomeException)
import Control.Monad (when)
import Control.Monad.CatchIO (try)
import Control.Monad.Trans (liftIO)
import qualified Data.ByteString.Char8 as BC
import qualified Data.Map as M
import qualified Data.Text as T
import Data.Version (showVersion)
import Paths_rescoyl (version)
import Snap.Http.Server
import Snap.Snaplet
import Snap.Snaplet.Session.Backends.CookieSession
import System.Console.CmdArgs.Implicit
import System.Directory (canonicalizePath, createDirectoryIfMissing)
import System.IO (hPutStrLn, stderr)
import Rescoyl.Handlers
import Rescoyl.Simple
import Rescoyl.Types
main :: IO ()
main = (runCmd =<<) $ cmdArgs $
modes
[ cmdServe
, cmdReadImageIndex
, cmdAddUser
]
&= summary versionString
&= program "rescoyl"
-- | String with the program name, version and copyright.
versionString :: String
versionString = "rescoyl " ++ showVersion version ++
" - Copyright (c) 2013-2104 Vo Minh Thu."
-- | Data type representing the different command-line subcommands.
data Cmd =
CmdServe
{ cmdServeEndpoint :: String
, cmdStore :: String
}
| CmdReadImageIndex
{ cmdStore :: String
, cmdNamespace :: String
, cmdRepository :: String
}
| CmdAddUser
{ cmdStore :: String
}
deriving (Data, Typeable)
-- | Create a 'Serve' command.
cmdServe :: Cmd
cmdServe = CmdServe
{ cmdServeEndpoint = "registry.local"
&= explicit
&= name "endpoint"
, cmdStore = "store"
&= explicit
&= name "store"
&= help "Path to the directory where to save files."
} &= help "Start the HTTP server."
&= explicit
&= name "serve"
-- | Create a 'ReadImageIndex' command.
cmdReadImageIndex :: Cmd
cmdReadImageIndex = CmdReadImageIndex
{ cmdStore = "store"
&= explicit
&= name "store"
&= help "Path to the directory where to save files."
, cmdNamespace = def
&= explicit
&= name "namespace"
&= help "Namespace for which the index must be read."
, cmdRepository = def
&= explicit
&= name "repository"
&= help "Repository for which the index must be read."
} &= help "Read the image index (for debugging)."
&= explicit
&= name "read-image-index"
-- | Create a 'AddUser' command.
cmdAddUser :: Cmd
cmdAddUser = CmdAddUser
{ cmdStore = "store"
&= explicit
&= name "store"
&= help "Path to the directory where to save files."
} &= help "Add a user (prompt interactively for a password)."
&= explicit
&= name "add-user"
-- serveSnaplet' :: Config Snap AppConfig -> SnapletInit b b -> IO ()
-- | Similar to the standard serveSnaplet but does not parse the command-line.
serveSnaplet' config initializer = do
(msgs, handler, doCleanup) <- runSnaplet (Just "devel") initializer
(conf, site) <- combineConfig config handler
createDirectoryIfMissing False "log"
let serve = simpleHttpServe conf
when (loggingEnabled conf) $ liftIO $ hPutStrLn stderr $ T.unpack msgs
_ <- try $ serve $ site
:: IO (Either SomeException ())
doCleanup
where
loggingEnabled = not . (== Just False) . getVerbose
runCmd :: Cmd -> IO ()
runCmd CmdServe{..} = do
static <- canonicalizePath cmdStore
let config =
setBind "0.0.0.0" $
setPort 80 $
defaultConfig
serveSnaplet' config $ appInit static [cmdServeEndpoint]
runCmd CmdReadImageIndex{..} = do
static <- canonicalizePath cmdStore
minfo <- readImageIndex' static (BC.pack cmdNamespace)
(BC.pack cmdRepository)
print minfo
runCmd CmdAddUser{..} = do
static <- canonicalizePath cmdStore
us <- readUsers static
(login, hashedPassword) <- makeUser
let us' = (M.insert login hashedPassword (fst us), snd us)
writeUsers static us'
appInit :: FilePath -> [String] -> SnapletInit App App
appInit static endpoints = makeSnaplet "rescoyl" description Nothing $ do
s <- nestSnaplet "session" sess $
initCookieSessionManager "session.key" "session" Nothing
us <- liftIO $ initUserBackend static
r <- liftIO $ initRegistryBackend static
addRoutes $ routes endpoints
wrapSite catch500
return $ App s us r
where description = "Rescoyl, a private Docker registry."
|
noteed/rescoyl
|
bin/rescoyl.hs
|
bsd-3-clause
| 4,318
| 0
| 13
| 870
| 1,059
| 551
| 508
| 122
| 1
|
{-
-}
import qualified Data.List as List
import qualified Data.Ord as Ord
import qualified Data.MemoCombinators as Memo
import qualified Zora.List as ZList
import Data.Maybe
import System.Random
type Card = String
type Square = String
type Roll = (Integer, Integer)
sentinel_roll :: Roll
sentinel_roll = (-1, -1)
shuffle' :: (Eq a) => [a] -> [a]
shuffle' = flip ZList.shuffle $ 280172349
cc_cards_src :: [Card]
cc_cards_src
= cycle
. shuffle'
. concat
$ [["GO", "JAIL"], replicate (16-2) "_"]
ch_cards_src :: [Card]
ch_cards_src
= cycle
. shuffle'
. concat
$ [["GO", "JAIL", "C1", "E3", "H2", "R1", "NEXTR", "NEXTR", "NEXTU", "-3"], replicate (16-10) "_"]
squares_finite_src :: [Square]
squares_finite_src = ["GO", "A1", "CC1", "A2", "T1", "R1", "B1", "CH1", "B2", "B3", "JAIL", "C1", "U1", "C2", "C3", "R2", "D1", "CC2", "D2", "D3", "FP", "E1", "CH2", "E2", "E3", "R3", "F1", "F2", "U2", "F3", "G2J", "G1", "G2", "CC3", "G3", "R4", "CH3", "H1", "T2", "H2"]
squares_src :: [Square]
squares_src = cycle squares_finite_src
dice_rolls_src :: [Roll]
dice_rolls_src
= preprocess
. ZList.pairify
$ random_integers (1, 4) 193105965
where
preprocess :: [(Integer, Integer)] -> [(Integer, Integer)]
preprocess = concat . map adjust_group . List.group
adjust_group :: [(Integer, Integer)] -> [(Integer, Integer)]
adjust_group l = if length l < 3
then l
else (replicate 2 (head l)) ++ (replicate ((length l) - 2) sentinel_roll)
calc_num_squares_to_advance :: [Square] -> Card -> Roll -> Integer
calc_num_squares_to_advance squares card roll@(r1, r2)= case card of
"_" -> r1 + r2
"NEXTR" -> minimum . map (n_until squares) $ ["R1", "R2", "R3", "R4"]
"NEXTU" -> minimum . map (n_until squares) $ ["U1", "U2"]
"-3" -> let x = -3 + r1 + r2 in
if x >= 0 then x else
(ZList.length' squares_finite_src) - 1
_ -> n_until squares card
n_until :: [Square] -> Card -> Integer
n_until squares card
= ZList.length'
. takeWhile (/= card)
$ squares
num_to_drop :: Card -> Card -> [Square] -> Roll -> Int
num_to_drop cc ch squares roll@(r1, r2) = fromInteger $
if roll == sentinel_roll
then n_until squares "JAIL"
else case hit_square_pre_cards squares roll of
"G2J" -> n_until squares "JAIL"
"CC*" -> calc_num_squares_to_advance squares cc roll
"CH*" -> calc_num_squares_to_advance squares ch roll
_ -> r1 + r2
hit_square_pre_cards :: [Square] -> Roll -> Square
hit_square_pre_cards squares roll@(r1, r2) =
if roll == sentinel_roll
then head squares
else case x' of
"CC" -> "CC*"
"CH" -> "CH*"
_ -> x
where
x' = take 2 x
x = squares !! (fromInteger $ r1 + r2)
get_squares_hit' :: [Roll] -> [Card] -> [Card] -> [Square] -> [Square]
get_squares_hit'
dice_rolls@(roll:dice_rolls')
cc_cards@(cc:_)
ch_cards@(ch:_)
squares
= (:) (head squares') $ get_squares_hit' dice_rolls' cc_cards' ch_cards' squares'
where
dice_rolls' :: [Roll]
dice_rolls' = tail dice_rolls
squares' :: [Square]
squares' = drop num_to_drop' squares
cc_cards' :: [Card]
cc_cards' = if hit_square_pre_cards squares roll == "CC*" then tail cc_cards else cc_cards
ch_cards' :: [Card]
ch_cards' = if hit_square_pre_cards squares roll == "CH*" then tail ch_cards else ch_cards
num_to_drop' :: Int
num_to_drop' = num_to_drop cc ch squares roll
len :: Double
len = 1000000.0
squares_hit :: [Square]
squares_hit = take (round len)
$ get_squares_hit'
dice_rolls_src
cc_cards_src
ch_cards_src
squares_src
random_integers :: (Integer, Integer) -> Integer -> [Integer]
random_integers range seed = randomRs range . mkStdGen $ fromInteger seed
frequencies :: [(Square, Double)]
frequencies
= reverse
. List.sortBy (Ord.comparing snd)
. ZList.map_keep calc_frequency
$ squares_finite_src
where
calc_frequency :: Square -> Double
calc_frequency
= (/ (len))
. fromIntegral
. length
. (flip List.elemIndices $ squares_hit)
modal_string :: String
modal_string =
concatMap
( show
. fromJust
. (flip List.elemIndex $ squares_finite_src)
. fst )
$ take 3 frequencies
main :: IO ()
main = do
(putStrLn . show) $ modal_string
|
bgwines/project-euler
|
src/solved/problem84.hs
|
bsd-3-clause
| 4,123
| 54
| 14
| 774
| 1,563
| 872
| 691
| 124
| 6
|
module Main where
import qualified MainTools as T (main)
import System.Environment (getArgs)
main :: IO ()
main = getArgs >>= \(src : args) -> T.main ("-e" : "main" : [src]) args
>>= putStr
|
YoshikuniJujo/toyhaskell_haskell
|
src/runtoy.hs
|
bsd-3-clause
| 193
| 0
| 11
| 36
| 81
| 47
| 34
| 6
| 1
|
------------------------------------------------------------------------------
-- | A DSL for generating SVG transform strings.
------------------------------------------------------------------------------
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Graphics.HSD3.D3.Style where
import Control.Monad
import Language.Javascript.JMacro
import Graphics.HSD3.D3.Cursor
import Graphics.HSD3.D3.Graph
import Graphics.HSD3.D3.Scope
import Graphics.HSD3.D3.Selection
------------------------------------------------------------------------------
-- | Orientation type represents ... orientation!
data Orientation = Horizontal | Vertical
data Color = Hex String | URL String | RGB Int Int Int
instance ToJExpr Color where
toJExpr (Hex c) = toJExpr c
toJExpr (URL c) = toJExpr $ "url(#" ++ c ++ ")"
toJExpr (RGB a b c) = toJExpr $
"rgb(" ++ show a ++ "," ++ show b ++ "," ++ show c ++ ")"
instance ToCursor s a Color where
toCursor = return . toJExpr
gradient :: (ToCursor s a b, ToCursor s a c) =>
Orientation -> String -> b -> c -> GraphT s a JExpr
gradient ori name from to =
append "linearGradient" `with` do
attr "id" name
attr "x1" "0%"
attr "y1" "0%"
case ori of
Vertical -> do
attr "x2" "0%"
attr "y2" "100%"
Horizontal -> do
attr "x2" "100%"
attr "y2" "0%"
attr "spreadMethod" "pad"
void $ append "stop" `with` do
attr "offset" "0%"
attr "stop-color" from
attr "stop-opacity" (1 :: Double)
void $ append "stop" `with`do
attr "offset" "100%"
attr "stop-color" to
attr "stop-opacity" (1 :: Double)
dropShadow :: String -> GraphT s a JExpr
dropShadow name =
append "filter" `with` do
attr "id" name
attr "height" "130%"
void $ append "feGaussianBlur" `with` do
attr "in" "SourceAlpha"
attr "stdDeviation" (5 :: Double)
attr "result" "blur"
void $ append "feOffset" `with` do
attr "in" "blur"
attr "dx" (5 :: Double)
attr "dy" (5 :: Double)
attr "result" "offsetBlur"
append "feMerge" `with` do
void $ append "feMergeNode" `with`
attr "in" "offsetBlur"
void $ append "feMergeNode" `with`
attr "in" "SourceGraphic"
------------------------------------------------------------------------------
|
Soostone/hs-d3
|
src/Graphics/HSD3/D3/Style.hs
|
bsd-3-clause
| 2,710
| 0
| 13
| 773
| 676
| 336
| 340
| 63
| 2
|
{-# LANGUAGE
UndecidableInstances
, FlexibleInstances
, MultiParamTypeClasses
, KindSignatures
, IncoherentInstances
#-}
module Annotation.HDebug where
import Control.Applicative
import Control.Category
import Control.Monad.Trans
import Annotation.HAnnotation
import Generics.HigherOrder
import Prelude hiding ((.), id, read)
-- Higher order show type class.
class HShow h where
hshow :: h ix -> String
instance HShow (h (HFixA a h)) => Show (h (HFixA a h) ix) where
show = hshow
-- Higher order debug annotation.
newtype HDebug (h :: (* -> *) -> (* -> *))
(a :: (* -> *))
(ix :: *)
= HDebug { unHDebug :: h a ix }
instance HShow (h a) => HShow (HDebug h a) where
hshow (HDebug h) = "HDebug (" ++ hshow h ++ ")"
instance (Applicative m, MonadIO m, HShow (h (HFixA HDebug h))) => AnnO HDebug h phi m where
annO _ (HInA (HDebug h)) = printer "query" h
annO _ (HInF h ) = return h
instance (Applicative m, MonadIO m, HShow (h (HFixA HDebug h))) => AnnI HDebug h phi m where
annI _ h = HInA . HDebug <$> printer "produce" h
instance (Applicative m, MonadIO m, HShow (h (HFixA HDebug h))) => AnnIO HDebug h phi m
printer :: (MonadIO m, Show (b ix)) => String -> b ix -> m (b ix)
printer s = (\f -> liftIO (print s >> print (show f)) >> return f)
|
sebastiaanvisser/islay
|
src/Annotation/HDebug.hs
|
bsd-3-clause
| 1,332
| 0
| 13
| 318
| 547
| 288
| 259
| -1
| -1
|
{-# LANGUAGE FlexibleContexts #-}
--------------------------------------------------------------------------------
-- |
-- Module : Network.OpenID.Utils
-- Copyright : (c) Trevor Elliott, 2008
-- License : BSD3
--
-- Maintainer :
-- Stability :
-- Portability :
--
module Network.OpenID.Utils (
-- * General Helpers
readMaybe
, breaks
, split
, roll
, unroll
, btwoc
-- * OpenID Defaults
, defaultModulus
, openidNS
-- * MonadLib helpers
, readM
, lookupParam
, readParam
, withResponse
) where
-- friends
import Network.OpenID.Types
-- libraries
import Data.Bits
import Data.Char
import Data.List
import Data.Maybe
import Data.Word
import MonadLib
import Network.HTTP
import Network.Stream
-- General Helpers -------------------------------------------------------------
-- | Read, maybe.
readMaybe :: Read a => String -> Maybe a
readMaybe str = case reads str of
[(x,"")] -> Just x
_ -> Nothing
-- | Break up a string by a predicate.
breaks :: (a -> Bool) -> [a] -> [[a]]
breaks p xs = case break p xs of
(as,_:bs) -> as : breaks p bs
(as,_) -> [as]
-- | Spit a list into a pair, removing the element that caused the predicate to
-- succeed.
split :: (a -> Bool) -> [a] -> ([a],[a])
split p as = case break p as of
(xs,_:ys) -> (xs,ys)
pair -> pair
-- | Build an Integer out of a big-endian list of bytes.
roll :: [Word8] -> Integer
roll = foldr step 0 . reverse
where step n acc = acc `shiftL` 8 .|. fromIntegral n
-- | Turn an Integer into a big-endian list of bytes
unroll :: Integer -> [Word8]
unroll = reverse . unfoldr step
where
step 0 = Nothing
step i = Just (fromIntegral i, i `shiftR` 8)
-- | Pad out a list of bytes to represent a positive, big-endian list of bytes.
btwoc :: [Word8] -> [Word8]
btwoc [] = [0x0]
btwoc bs@(x:_) | testBit x 7 = 0x0 : bs
| otherwise = bs
-- OpenID Defaults -------------------------------------------------------------
-- | The OpenID-2.0 namespace.
openidNS :: String
openidNS = "http://specs.openid.net/auth/2.0"
-- | Default modulus for Diffie-Hellman key exchange.
defaultModulus :: Integer
defaultModulus = 0xDCF93A0B883972EC0E19989AC5A2CE310E1D37717E8D9571BB7623731866E61EF75A2E27898B057F9891C2E27A639C3F29B60814581CD3B2CA3986D2683705577D45C2E7E52DC81C7A171876E5CEA74B1448BFDFAF18828EFD2519F14E45E3826634AF1949E5B535CC829A483B8A76223E5D490A257F05BDFF16F2FB22C583AB
-- MonadLib Helpers ------------------------------------------------------------
-- | Read inside of an Exception monad
readM :: (ExceptionM m e, Read a) => e -> String -> m a
readM e str = case reads str of
[(x,"")] -> return x
_ -> raise e
-- | Lookup parameters inside an exception handling monad
lookupParam :: ExceptionM m Error => String -> Params -> m String
lookupParam k ps = maybe err return (lookup k ps)
where err = raise $ Error $ "field not present: " ++ k
-- | Read a field
readParam :: (Read a, ExceptionM m Error) => String -> Params -> m a
readParam k ps = readM err =<< lookupParam k ps
where err = Error ("unable to read field: " ++ k)
-- | Make an HTTP request, and run a function with a successful response
withResponse :: ExceptionM m Error
=> Either ConnError (Response String) -> (Response String -> m a) -> m a
withResponse (Left err) _ = raise $ Error $ show err
withResponse (Right rsp) f = f rsp
|
substack/hsopenid
|
src/Network/OpenID/Utils.hs
|
bsd-3-clause
| 3,423
| 0
| 10
| 704
| 863
| 473
| 390
| 64
| 2
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- |Pretty instances for some basic Haskell types and for data type models
module ZM.Pretty
( module Data.Model.Pretty
, hex
, unPrettyRef
, prettyList
, prettyTuple
)
where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Short as SBS
import Flat ( UTF16Text(..)
, UTF8Text(..)
)
import Data.Foldable ( toList )
import Data.Int
import Data.List
import qualified Data.Map as M
import Data.Model.Pretty
import Data.Model.Util
-- import Data.Ord
import qualified Data.Sequence as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.Word
import Numeric ( readHex )
import Text.ParserCombinators.ReadP
hiding ( char )
-- import Text.PrettyPrint
import Text.PrettyPrint.HughesPJClass
import qualified Text.PrettyPrint.HughesPJClass
as P
import ZM.BLOB
import ZM.Model ( )
import ZM.Pretty.Base
import ZM.Types
{-|
Convert the textual representation of a hash code to its equivalent value
>>> unPrettyRef "Kb53bec846608"
SHAKE128_48 181 59 236 132 102 8
>>> unPrettyRef "Kb53bec8466080000"
*** Exception: unPrettyRef: unknown code "b53bec8466080000"
...
-}
unPrettyRef :: String -> SHAKE128_48 a
--unPrettyRef ('K':code) = let [k1,k2,k3,k4,k5,k6] = readHexCode code in SHAKE128_48 k1 k2 k3 k4 k5 k6
unPrettyRef ('K' : code) = case readHexCode code of
[k1, k2, k3, k4, k5, k6] -> SHAKE128_48 k1 k2 k3 k4 k5 k6
_ -> error $ "unPrettyRef: unknown code " ++ show code
unPrettyRef code = error $ "unPrettyRef: unknown code " ++ show code
{-|Display a list of Docs, as a tuple with spaced elements
>>> prettyTuple (map pPrint [11,22,33::Word8])
(11, 22, 33)
-}
prettyTuple :: [Doc] -> Doc
prettyTuple = parens . fsep . punctuate comma
{-|Display a list of Docs, with spaced elements
>>> prettyList (map pPrint [11,22,33::Word8])
[11, 22, 33]
-}
prettyList :: [Doc] -> Doc
--prettyList = brackets . hcat . punctuate comma
prettyList = brackets . fsep . punctuate comma
instance Pretty TypedDecodeException where
pPrint (UnknownMetaModel m) = text "Unknown meta model" P.<> pPrint m
pPrint (WrongType e a) =
let et = prettyShow e
at = prettyShow a
in text
. unwords
$ ["Was expecting type:\n", et, "\n\nBut the data has type:\n", at]
pPrint (DecodeError e) = pPrint (show e)
instance Show a => Pretty (TypedValue a) where
pPrint (TypedValue t v) = text (show v) <+> text "::" <+> pPrint t
-- TODO: merge with similar code in `model` package
instance Pretty AbsTypeModel where
pPrint (TypeModel t e) = vspacedP
[ text "Type:"
, vcat [pPrint t P.<> text ":", pPrint (e, t)]
-- ,vcat [pPrint t <> text ":",pPrint (declName <$> solveAll e t)]
, text "Environment:"
, pPrint e
]
instance {-# OVERLAPS #-} Pretty AbsEnv where
-- Previous
-- pPrint e = vspacedP . map (\(ref,adt) -> vcat [pPrint ref <> text ":",pPrint . CompactPretty $ (e,adt)]) . sortedEnv $ e
pPrint e =
vspacedP
. map (\(ref, adt) -> pPrint (refADT e ref adt) P.<> char ';')
. sortedEnv
$ e
sortedEnv
:: M.Map a (ADT Identifier Identifier (ADTRef AbsRef))
-> [(a, ADT Identifier Identifier (ADTRef AbsRef))]
sortedEnv = sortOn snd . M.assocs
refADT
:: ( Pretty p
, Convertible name String
, Show k
, Ord k
, Pretty k
, Convertible a String
)
=> M.Map k (ADT a consName1 ref)
-> p
-> ADT name consName2 (ADTRef k)
-> ADT QualName consName2 (TypeRef QualName)
-- refADT env ref adt =
-- let name = fullName ref adt
-- in ADT name (declNumParameters adt) ((solveS name <$>) <$> declCons adt)
-- where -- solveS _ (Var n) = TypVar n
-- -- solveS _ (Ext k) = TypRef . fullName k . solve k $ env
-- -- solveS name Rec = TypRef name
-- solveS name = (fullName <$>) . toTypeRef name
-- fullName ref adt = QualName "" (prettyShow ref) (convert $ declName adt)
refADT env ref adt =
let name = fullName ref adt
in ADT name (declNumParameters adt) ((solveS name <$>) <$> declCons adt)
where
solveS _ (Var n) = TypVar n
solveS _ (Ext k) = TypRef . fullName k . solve k $ env
solveS name Rec = TypRef name
--fullName ref adt = QualName "" (prettyShow ref) (convert $ declName adt)
fullName ref adt = QualName "" (convert $ declName adt) (prettyShow ref)
instance {-# OVERLAPS #-} Pretty (AbsEnv,AbsType) where
pPrint (env, t) = pPrint (declName <$> solveAll env t)
instance {-# OVERLAPS #-} Pretty (AbsEnv,AbsADT) where
pPrint (env, adt) =
pPrint $ substAbsADT (\ref -> declName $ solve ref env) adt
-- |Convert references in an absolute definition to their textual form (useful for display)
-- stringADT :: AbsEnv -> AbsADT -> ADT Identifier Identifier (TypeRef Identifier)
-- stringADT env adt =
-- let name = declName adt
-- in ADT name (declNumParameters adt) ((solveS name <$>) <$> declCons adt)
-- where solveS _ (Var n) = TypVar n
-- solveS _ (Ext k) = TypRef . declName . solve k $ env
-- solveS name Rec = TypRef name
-- strADT :: AbsEnv -> AbsADT -> ADT Identifier Identifier (TypeRef Identifier)
--stringADT :: AbsEnv -> AbsADT -> ADT Identifier Identifier (TypeRef Identifier)
-- stringADT = substADT (\env k -> declName $ solve k env)
-- stringADT = substAbsADT declName
-- substAbsADT f env adt = ((\ref -> f $ solve ref env) <$>) <$> (toTypeRef (absRef adt) <$> adt)
-- substADT k env adt = (k env <$>) <$> (toTypeRef (absRef adt) <$> adt)
instance Pretty Identifier where
pPrint = text . convert
instance {-# OVERLAPS #-} Pretty a => Pretty (String,ADTRef a) where
pPrint (_, Var v) = varP v
pPrint (n, Rec ) = text n
pPrint (_, Ext r) = pPrint r
instance Pretty a => Pretty (ADTRef a) where
pPrint (Var v) = varP v
pPrint Rec = char '\x21AB'
pPrint (Ext r) = pPrint r
readHexCode :: String -> [Word8]
readHexCode = readCode []
readCode :: [Word8] -> String -> [Word8]
readCode bs [] = reverse bs
readCode bs s = let (h, t) = splitAt 2 s in readCode (rdHex h : bs) t
{-| Read the last 2 characters as an hex value between 0 and FF
>>> rdHex ""
*** Exception: rdHex: cannot parse
...
>>> rdHex "3"
3
>>> rdHex "08"
8
>>> rdHex "FF07"
7
-}
rdHex :: String -> Word8
rdHex s = case readP_to_S (readS_to_P readHex) s of
[(b, "")] -> b
_ -> error $ "rdHex: cannot parse " ++ s
-- instance Pretty a => Pretty (Array a) where pPrint (Array vs) = text "Array" <+> pPrint vs
-- instance Pretty a => Pretty (Array a) where pPrint (Array vs) = pPrint vs
instance Pretty a => Pretty (S.Seq a) where
pPrint = pPrint . toList
instance Pretty a => Pretty (NonEmptyList a) where
pPrint = pPrint . toList
instance Pretty NoEncoding where
pPrint = text . show
instance Pretty encoding => Pretty (BLOB encoding) where
pPrint (BLOB enc bs) = text "BLOB" <+> pPrint enc <+> pPrint bs
instance {-# OVERLAPS #-} Pretty (BLOB UTF8Encoding) where
pPrint = pPrint . T.decodeUtf8 . unblob
instance {-# OVERLAPS #-} Pretty (BLOB UTF16LEEncoding) where
pPrint = pPrint . T.decodeUtf16LE . unblob
instance Pretty T.Text where
pPrint = text . T.unpack
instance Pretty UTF8Text where
pPrint (UTF8Text t) = pPrint t
instance Pretty UTF16Text where
pPrint (UTF16Text t) = pPrint t
instance Pretty Word where
pPrint = text . show
instance Pretty Word8 where
pPrint = text . show
instance Pretty Word16 where
pPrint = text . show
instance Pretty Word32 where
pPrint = text . show
instance Pretty Word64 where
pPrint = text . show
instance Pretty Int8 where
pPrint = text . show
instance Pretty Int16 where
pPrint = text . show
instance Pretty Int32 where
pPrint = text . show
instance Pretty Int64 where
pPrint = text . show
instance Pretty B.ByteString where
pPrint = pPrint . B.unpack
instance Pretty L.ByteString where
pPrint = pPrint . L.unpack
instance Pretty SBS.ShortByteString where
pPrint = pPrint . SBS.unpack
instance (Pretty a,Pretty b) => Pretty (M.Map a b) where
pPrint m = text "Map" <+> pPrint (M.assocs m)
instance (Pretty a, Pretty b, Pretty c, Pretty d, Pretty e, Pretty f, Pretty g, Pretty h, Pretty i) => Pretty (a, b, c, d, e, f, g, h, i) where
pPrintPrec l _ (a, b, c, d, e, f, g, h, i) = prettyTuple
[ pPrint0 l a
, pPrint0 l b
, pPrint0 l c
, pPrint0 l d
, pPrint0 l e
, pPrint0 l f
, pPrint0 l g
, pPrint0 l h
, pPrint0 l i
]
pPrint0 :: Pretty a => PrettyLevel -> a -> Doc
pPrint0 l = pPrintPrec l 0
-- instance (Pretty a,Pretty l) => Pretty (Label a l) where
-- pPrint (Label a Nothing) = pPrint a
-- pPrint (Label _ (Just l)) = pPrint l
|
tittoassini/typed
|
src/ZM/Pretty.hs
|
bsd-3-clause
| 9,365
| 0
| 15
| 2,479
| 2,268
| 1,214
| 1,054
| 171
| 3
|
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
module Bytecode.Definition where
import Bytecode.Instruction
import qualified Data.Foldable as Foldable
import qualified Data.Traversable as Traversable
data Definition symbol
= Definition
{ definitionSymbol :: symbol
, definitionBody :: DefinitionBody symbol
}
deriving (Show, Functor, Traversable.Traversable, Foldable.Foldable)
data DefinitionBody symbol
= DefinitionBodyCaf [Instruction symbol] -- evaluated at initialization, creates the CAF thunk
| DefinitionBodyLambda Int [ExecCont symbol] -- evaluated at runtime
deriving (Show, Functor, Traversable.Traversable, Foldable.Foldable)
|
exFalso/lambda
|
src/lib/Bytecode/Definition.hs
|
bsd-3-clause
| 745
| 0
| 9
| 132
| 132
| 79
| 53
| 16
| 0
|
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
[lq| permutations :: ts:[a] -> [[a]] / [(len ts), 1, 0] |]
permutations :: [a] -> [[a]]
permutations xs0 = xs0 : perms xs0 []
[lq| perms :: ts:[a] -> is:[a] -> [[a]] / [((len ts)+(len is)), 0, (len ts)] |]
perms :: [a] -> [a] -> [[a]]
perms [] _ = []
perms (t:ts) is = foldr interleave (perms ts (t:is)) (permutations is)
where interleave xs r = let (_,zs) = interleave' id xs r in zs
interleave' _ [] r = (ts, r)
interleave' f (y:ys) r = let (us,zs) = interleave' (f . (y:)) ys r
in (y:us, f (t:y:us) : zs)
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/Permutation.hs
|
bsd-3-clause
| 669
| 0
| 14
| 222
| 280
| 151
| 129
| 13
| 2
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
module Control.Lens.Union.Generics
( Ixed
, Ixed'
, ix
, Nat (..)
, N0, N1, N2, N3, N4, N5, N6, N7, N8
) where
import Control.Applicative
import Control.Lens.Iso
import Control.Lens.Prism
import Control.Lens.Tuple.Internal
import Data.Proxy
import GHC.Generics (Generic (..), (:+:) (..), (:*:) (..), K1 (..), M1 (..), U1 (..))
import GHC.Generics.Lens.Extras
import Type.Nat
type Ixed n s t a b = (Generic s, Generic t, GIxed n (Rep s) (Rep t) a b)
type Ixed' n s a = Ixed n s s a a
ix :: Ixed n s t a b => f n -> Prism s t a b
{-# INLINE ix #-}
ix n = rep.gix n
#ifndef HLINT
class GIxed (n :: Nat) s t a b | s -> a, t -> b, s b -> t, t a -> s where
gix :: f n -> Prism (s x) (t x) a b
#endif
instance GIxed N0 U1 U1 () () where
{-# INLINE gix #-}
gix _ = prism (const U1) (const $ Right ())
instance GIxed N0 (K1 i a) (K1 i b) a b where
{-# INLINE gix #-}
gix _ = iso unK1 K1
instance GIxed n s t a b => GIxed n (M1 i c s) (M1 i c t) a b where
{-# INLINE gix #-}
gix n = iso unM1 M1 . gix n
instance GIxed' (GSize s :> n) n s s' t t' a b
=> GIxed n (s :+: s') (t :+: t') a b where
{-# INLINE gix #-}
gix = gix' (Proxy :: Proxy (GSize s :> n))
instance (GIsHList s, GIsHList t, GIsHList s', GIsHList t',
IsHList a, List a ~ GCons s (GList s'),
IsHList b, List b ~ GCons t (GList t'))
=> GIxed N0 (s :*: s') (t :*: t') a b where
{-# INLINE gix #-}
gix _ = iso (fromHList . gtoHList) (gfromHList . toHList)
#ifndef HLINT
class GIxed' (p :: Bool) (n :: Nat) s s' t t' a b | s s' -> a
, t t' -> b
, s s' b -> t t'
, t t' a -> s s' where
gix' :: f p -> g n -> Prism ((s :+: s') x) ((t :+: t') x) a b
#endif
instance (GIxed n s t a b, s' ~ t') => GIxed' True n s s' t t' a b where
{-# INLINE gix' #-}
gix' _ n = dimap (gsum Left Right) (either (fmap L1) (pure . R1)) . left' . gix n
instance (GIxed (GSize s :- n) s' t' a b, s ~ t)
=> GIxed' False n s s' t t' a b where
{-# INLINE gix' #-}
gix' _ _ = dimap (gsum Left Right) (either (pure . L1) (fmap R1)) . right' .
gix (Proxy :: Proxy (GSize s :- n))
gsum :: (a x -> r) -> (b x -> r) -> (a :+: b) x -> r
{-# INLINE gsum #-}
gsum f _ (L1 a) = f a
gsum _ f (R1 a) = f a
#ifndef HLINT
type family GSize (f :: * -> *) :: Nat
#endif
type instance GSize U1 = S Z
type instance GSize (K1 i c) = S Z
type instance GSize (M1 i c f) = GSize f
type instance GSize (a :+: b) = GSize a :+ GSize b
type instance GSize (a :*: b) = S Z
|
sonyandy/wart
|
src/Control/Lens/Union/Generics.hs
|
bsd-3-clause
| 3,063
| 0
| 13
| 907
| 1,330
| 732
| 598
| 76
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
module Data.Geodetic(
module G
) where
import Data.Geodetic.ECEF as G
import Data.Geodetic.Ellipsoid as G
import Data.Geodetic.EllipsoidReaderT as G
import Data.Geodetic.HasDoubles as G
import Data.Geodetic.LLH as G
import Data.Geodetic.LL as G
import Data.Geodetic.Sphere as G
import Data.Geodetic.XY as G
|
NICTA/coordinate
|
src/Data/Geodetic.hs
|
bsd-3-clause
| 346
| 0
| 4
| 46
| 77
| 57
| 20
| 11
| 0
|
{-# LANGUAGE NamedFieldPuns, OverloadedStrings #-}
module MusicPad.Model.Verse where
import MusicPad.Env
import Prelude ()
import qualified Prelude as P
import MusicPad.Model.Sample
mod_verse_at :: Game State -> Int -> (Verse -> Verse) -> IO ()
mod_verse_at g i f = do
with_state g - \_state -> do
let verse_index = _state.song.current_verse_index
current_verse = _state.song.verses.at verse_index
new_verse = f current_verse
g.state $~ set (__song > __verses) (_state.song.verses.replace_at verse_index new_verse)
mod_current_verse :: Game State -> (Verse -> Verse) -> IO ()
mod_current_verse g f = do
with_state g - \_state -> do
let verse_index = _state.song.current_verse_index
mod_verse_at g verse_index f
query_verse_at :: Game State -> Int -> (Verse -> a) -> IO a
query_verse_at g i f = do
with_state g - \_state -> do
let verse_index = _state.song.current_verse_index
current_verse = _state.song.verses.at verse_index
r = f current_verse
return r
query_current_verse :: Game State -> (Verse -> a) -> IO a
query_current_verse g f = do
with_state g - \_state -> do
let verse_index = _state.song.current_verse_index
query_verse_at g verse_index f
get_current_verse_index :: Game State -> IO Int
get_current_verse_index g = do
with_state g - song > current_verse_index > return
get_current_verse :: Game State -> IO Verse
get_current_verse g = do
with_state g - \_state -> do
let verse_index = _state.song.current_verse_index
return - _state.song.verses.at verse_index
set_active_verse_on_object :: Game State -> TVar (GameObject State) -> Int -> IO ()
set_active_verse_on_object g o i = do
set_active_verse_only g i
update_all_verse_color g
set_active_verse_only :: Game State -> Int -> IO ()
set_active_verse_only g i = do
g.state $~ set (__song > __current_verse_index) i
update_all_verse_color :: Game State -> IO ()
update_all_verse_color g = do
_current_verse_index <- get_current_verse_index g
_scene <- read - g.scene
_scene.objects.filterT (tag > is (Just - Tag "verse")) >>= mapM_ (\x ->
x.verse_data.wantM - \attr -> do
let _verse_no = attr.verse_no
if _current_verse_index == _verse_no
then
x $~ mod __renderer ( fmap - set (__materials) [ Linked - "VerseEnabled" ] )
else
x $~ mod __renderer ( fmap - set (__materials) [ Linked - "VerseDisabled" ] )
)
verse_data :: TVar (GameObject State) -> IO (Maybe VerseObjectData)
verse_data = object_data
|
nfjinjing/level5
|
src/MusicPad/Model/Verse.hs
|
bsd-3-clause
| 2,568
| 0
| 22
| 550
| 854
| 417
| 437
| -1
| -1
|
module App.Views.Posts.New where
import Config.Master
import Turbinado.View
import Turbinado.View.Helpers
import Control.Monad.Trans
markup :: View XML
markup = <div>
<h1>New Post </h1>
<form action=(getViewDataValue_u "save-url" :: View String) method="post">
Title :
<input type="text" id="title" name="title"></input><br /><br />
<textarea name="content" id="content" cols="40" rows="5">
</textarea>
<br />
<input type="submit" value="Save" />
</form>
</div>-- SPLIT HERE
|
abuiles/turbinado-blog
|
tmp/compiled/App/Views/Posts/New.hs
|
bsd-3-clause
| 691
| 31
| 20
| 268
| 215
| 110
| 105
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
module Tests.Hakit.TestHakit where
import Test.HUnit
import Hakit
import qualified Data.Text as T
want what got verdict = assertBool (show what ++ "\n" ++ show got) verdict
cases1 = [
(["author" .- ["name" .- "Joe", "age" .- 30]], "author.name", d "Joe"),
(["x" .- ["y" .- ["z" .- "val"]]], "x.y.z", d "val"),
(["x" .- [d "a", d "b", d "c"]], "x[0]", d "a"),
(["x" .- ["y" .- [d "a", d ["field1" .- "val1", "field2" .- "val2"], d "c"]]], "x.y[1].field2", d "val2")
]
t f cs = TestCase $ mapM_ f1 cs
where
f1 c =
let res = f (e2 c) (dm $ e1 c)
check = e3 c
in want check res $ res == check
testGet = t get cases1
cases2 = [
(["x" .- ["y" .- "Yo."]], "x.y", True),
(["x" .- ["y" .- "Hey."]], "x.z", False)
]
testExists = t exists cases2
cases3 = [
(["x" .- "Boo"], ("x", "Wut?"), ["x" .- "Wut?"]), -- Modifying existing key.
(["x" .- "Boo"], ("y", "Wut?"), ["y" .- "Wut?", "x" .- "Boo"]), -- Setting nonexisting key.
(
["x" .- "y"],
("a.b.c.d", "X"),
[
"x" .- "y",
"a" .- [
"b" .- [
"c" .- [
"d" .- "X"
]
]
]
]
),
(
["x" .- "y"],
("x.a", "X"),
["x" .- "y"]
),
(
[
"x" .- [
"y" .- "Hey."
]
],
("x.z", "Hi."),
[
"x" .- [
"y" .- "Hey.",
"z" .- "Hi."
]
]
),
(
[
"x" .- [
"y" .- "Cheers.",
"z" .- [d 42, d ["a" .- ["b" .- ["c" .- "X"]]]]
]
],
("x.z.1.a.b.d", "Y"),
[
"x" .- [
"y" .- "Cheers.",
"z" .- [d 42, d ["a" .- ["b" .- ["c" .- "X", "d" .- "Y"]]]]
]
]
),
(
[
"x" .- [
"y" .- "Cheers.",
"z" .- [d 42, d "X"]
]
],
("x.z.1", "Y"),
[
"x" .- [
"y" .- "Cheers.",
"z" .- [d 42, d "Y"]
]
]
),
(
[
"x" .- [
"y" .- [d 42]
]
],
("x.y.1", "Hey."),
[
"x" .- [
"y" .- [d 42]
]
]
)
]
testSet = TestCase $ mapM_ f cases3
where
f c =
let res = set (fst $ e2 c) (snd $ e2 c) (dm $ e1 c)
check = dm $ e3 c
in want check res $ res == check
cases4 :: [([(T.Text, DocVal)], T.Text, [(T.Text, DocVal)])]
cases4 = [
(
["x" .- "Boo"],
"x",
[]
),
(
[
"x" .- [
"y" .- "Cheers.",
"z" .- [d 42, d ["a" .- ["b" .- ["c" .- "X"]]]]
]
],
"x.z",
[
"x" .- [
"y" .- "Cheers."
]
]
),
(
[
"x" .- [
"y" .- "Cheers.",
"z" .- [d 42, d ["a" .- ["b" .- ["c" .- "X"]], "d" .- "Y"]]
]
],
"x.z.1.a",
[
"x" .- [
"y" .- "Cheers.",
"z" .- [d 42, d ["d" .- "Y"]]
]
]
)
]
testUnset = TestCase $ mapM_ f cases4
where
f c =
let res = unset (e2 c) (dm $ e1 c)
check = dm $ e3 c
in want check res $ res == check
cases5 = [
("{\"a\":42}", ["a" .- 42]),
("{\"a\":43, \"b\":[1,2,3]}", ["a" .- 43, "b" .- [d 1, d 2, d 3]]),
(
"{\"a\": {\"b\": 44}}",
[
"a" .- [
"b" .- 44
]
]
)
]
testFromJSON = TestCase $ mapM_ f cases5
where
f c =
let parsed = fromJSON $ fst c
check = dm $ snd c
in want check parsed $ parsed == check
cases6 = [
(["a" .- 42], "{\"a\":42}"),
(["a" .- 43, "b" .- [d 1, d 2, d 3]], "{\"a\":43, \"b\":[1,2,3]}")
]
testToJSON = TestCase $ mapM_ f cases6
where
f c =
let stringed = toJSON . dm $ fst c
check = snd c
in want check stringed $ stringed == check
cases7 = [
(
)
]
testMa = TestCase $ mapM_ f cases6
where
f c =
let stringed = toJSON . dm $ fst c
check = snd c
in want check stringed $ stringed == check
tests = TestList [
TestLabel "testGet" testGet,
TestLabel "testExists" testExists,
TestLabel "testSet" testSet,
TestLabel "testUnset" testUnset,
TestLabel "testFromJSON" testFromJSON,
TestLabel "testToJSON" testToJSON
]
|
crufter/hakit
|
tests/hakit/testHakit.hs
|
bsd-3-clause
| 4,973
| 0
| 18
| 2,415
| 1,746
| 968
| 778
| 145
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.Text.Lazy as T
import qualified Data.Text.Lazy.IO as T
import Clay hiding (div,filter)
import qualified Clay as C
import Clay.Property as CP
import Clay.Filter as CF
import Control.Arrow ((>>>))
import qualified Clay.Stylesheet as CC
main :: IO ()
main = T.putStr $ renderWith compact [] $ do
fontSetting
codeCss
colors
fontSetting :: Css
fontSetting = fontFace $ do
fontFamily ["Hasklig"] []
fontFaceSrc [FontFaceSrcUrl "../fonts/Hasklig-Medium.otf" (Just OpenType)]
codeCss :: Css
codeCss = pre ? do
margin 0 10 0 $ px 10
padding 9 9 9 $ px 9
backgroundColor "#FDF6E3"
border solid (px 1) (rgba 0 0 0 128)
fontSize $ px 14
borderRadius 5 5 5 $ px 5
textRendering optimizeLegibility
whiteSpace preWrap
code ? do
borderStyle none
display block
boxShadow none none none none
fontFamily ["Hasklig", "Monaco", "Menlo"
, "Consolas", "Courier New"] [monospace]
-- overflowWrap :: Val a => Key a -> a -> Css
-- overflowWrap = CC.key
colors :: Css
colors = star # ".sourceCode" ? do
mapM_ (\(sel,c) -> sel ? color c) csss
return ()
where
csss =
[ (".kw","#268BD2")
, (".dt","#268BD2")
, (foldr1 mappend [".dv",".bn",".fl"],"#D33682")
, (".ch","#DC322F")
, (".st","#2AA198")
, (".co","#93A1A1")
, (".ot","#A57800")
, (".al","#CB4B16")
, (".fu","#268BD2")
-- , (".re"," ")
, (".er","#D30102")]
|
kiripon/gh-pages
|
css/syntax.hs
|
bsd-3-clause
| 1,509
| 0
| 12
| 357
| 511
| 280
| 231
| 50
| 1
|
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.C.Types
-- Copyright : (c) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Mapping of C types to corresponding Haskell types.
--
-----------------------------------------------------------------------------
module Foreign.C.Types
( -- * Representations of C types
#ifndef __NHC__
-- $ctypes
-- ** Integral types
-- | These types are are represented as @newtype@s of
-- types in "Data.Int" and "Data.Word", and are instances of
-- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',
-- 'Prelude.Show', 'Prelude.Enum', 'Typeable', 'Storable',
-- 'Prelude.Bounded', 'Prelude.Real', 'Prelude.Integral' and
-- 'Bits'.
CChar, CSChar, CUChar
, CShort, CUShort, CInt, CUInt
, CLong, CULong
, CPtrdiff, CSize, CWchar, CSigAtomic
, CLLong, CULLong
, CIntPtr, CUIntPtr
, CIntMax, CUIntMax
-- ** Numeric types
-- | These types are are represented as @newtype@s of basic
-- foreign types, and are instances of
-- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',
-- 'Prelude.Show', 'Prelude.Enum', 'Typeable' and 'Storable'.
, CClock, CTime
-- ** Floating types
-- | These types are are represented as @newtype@s of
-- 'Prelude.Float' and 'Prelude.Double', and are instances of
-- 'Prelude.Eq', 'Prelude.Ord', 'Prelude.Num', 'Prelude.Read',
-- 'Prelude.Show', 'Prelude.Enum', 'Typeable', 'Storable',
-- 'Prelude.Real', 'Prelude.Fractional', 'Prelude.Floating',
-- 'Prelude.RealFrac' and 'Prelude.RealFloat'.
, CFloat, CDouble, CLDouble
#else
-- Exported non-abstractly in nhc98 to fix an interface file problem.
CChar(..), CSChar(..), CUChar(..)
, CShort(..), CUShort(..), CInt(..), CUInt(..)
, CLong(..), CULong(..)
, CPtrdiff(..), CSize(..), CWchar(..), CSigAtomic(..)
, CLLong(..), CULLong(..)
, CClock(..), CTime(..)
, CFloat(..), CDouble(..), CLDouble(..)
#endif
-- ** Other types
-- Instances of: Eq and Storable
, CFile, CFpos, CJmpBuf
) where
#ifndef __NHC__
import Foreign.Storable
import Data.Bits ( Bits(..) )
import Data.Int ( Int8, Int16, Int32, Int64 )
import Data.Word ( Word8, Word16, Word32, Word64 )
import Data.Typeable
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.Float
import GHC.Enum
import GHC.Real
import GHC.Show
import GHC.Read
import GHC.Num
#else
import Control.Monad ( liftM )
#endif
#ifdef __HUGS__
import Hugs.Ptr ( castPtr )
#endif
#include "HsBaseConfig.h"
#include "CTypes.h"
-- | Haskell type representing the C @char@ type.
INTEGRAL_TYPE(CChar,tyConCChar,"CChar",HTYPE_CHAR)
-- | Haskell type representing the C @signed char@ type.
INTEGRAL_TYPE(CSChar,tyConCSChar,"CSChar",HTYPE_SIGNED_CHAR)
-- | Haskell type representing the C @unsigned char@ type.
INTEGRAL_TYPE(CUChar,tyConCUChar,"CUChar",HTYPE_UNSIGNED_CHAR)
-- | Haskell type representing the C @short@ type.
INTEGRAL_TYPE(CShort,tyConCShort,"CShort",HTYPE_SHORT)
-- | Haskell type representing the C @unsigned short@ type.
INTEGRAL_TYPE(CUShort,tyConCUShort,"CUShort",HTYPE_UNSIGNED_SHORT)
-- | Haskell type representing the C @int@ type.
INTEGRAL_TYPE(CInt,tyConCInt,"CInt",HTYPE_INT)
-- | Haskell type representing the C @unsigned int@ type.
INTEGRAL_TYPE(CUInt,tyConCUInt,"CUInt",HTYPE_UNSIGNED_INT)
-- | Haskell type representing the C @long@ type.
INTEGRAL_TYPE(CLong,tyConCLong,"CLong",HTYPE_LONG)
-- | Haskell type representing the C @unsigned long@ type.
INTEGRAL_TYPE(CULong,tyConCULong,"CULong",HTYPE_UNSIGNED_LONG)
-- | Haskell type representing the C @long long@ type.
INTEGRAL_TYPE(CLLong,tyConCLLong,"CLLong",HTYPE_LONG_LONG)
-- | Haskell type representing the C @unsigned long long@ type.
INTEGRAL_TYPE(CULLong,tyConCULLong,"CULLong",HTYPE_UNSIGNED_LONG_LONG)
{-# RULES
"fromIntegral/a->CChar" fromIntegral = \x -> CChar (fromIntegral x)
"fromIntegral/a->CSChar" fromIntegral = \x -> CSChar (fromIntegral x)
"fromIntegral/a->CUChar" fromIntegral = \x -> CUChar (fromIntegral x)
"fromIntegral/a->CShort" fromIntegral = \x -> CShort (fromIntegral x)
"fromIntegral/a->CUShort" fromIntegral = \x -> CUShort (fromIntegral x)
"fromIntegral/a->CInt" fromIntegral = \x -> CInt (fromIntegral x)
"fromIntegral/a->CUInt" fromIntegral = \x -> CUInt (fromIntegral x)
"fromIntegral/a->CLong" fromIntegral = \x -> CLong (fromIntegral x)
"fromIntegral/a->CULong" fromIntegral = \x -> CULong (fromIntegral x)
"fromIntegral/a->CLLong" fromIntegral = \x -> CLLong (fromIntegral x)
"fromIntegral/a->CULLong" fromIntegral = \x -> CULLong (fromIntegral x)
"fromIntegral/CChar->a" fromIntegral = \(CChar x) -> fromIntegral x
"fromIntegral/CSChar->a" fromIntegral = \(CSChar x) -> fromIntegral x
"fromIntegral/CUChar->a" fromIntegral = \(CUChar x) -> fromIntegral x
"fromIntegral/CShort->a" fromIntegral = \(CShort x) -> fromIntegral x
"fromIntegral/CUShort->a" fromIntegral = \(CUShort x) -> fromIntegral x
"fromIntegral/CInt->a" fromIntegral = \(CInt x) -> fromIntegral x
"fromIntegral/CUInt->a" fromIntegral = \(CUInt x) -> fromIntegral x
"fromIntegral/CLong->a" fromIntegral = \(CLong x) -> fromIntegral x
"fromIntegral/CULong->a" fromIntegral = \(CULong x) -> fromIntegral x
"fromIntegral/CLLong->a" fromIntegral = \(CLLong x) -> fromIntegral x
"fromIntegral/CULLong->a" fromIntegral = \(CULLong x) -> fromIntegral x
#-}
-- | Haskell type representing the C @float@ type.
FLOATING_TYPE(CFloat,tyConCFloat,"CFloat",HTYPE_FLOAT)
-- | Haskell type representing the C @double@ type.
FLOATING_TYPE(CDouble,tyConCDouble,"CDouble",HTYPE_DOUBLE)
-- HACK: Currently no long double in the FFI, so we simply re-use double
-- | Haskell type representing the C @long double@ type.
FLOATING_TYPE(CLDouble,tyConCLDouble,"CLDouble",HTYPE_DOUBLE)
{-# RULES
"realToFrac/a->CFloat" realToFrac = \x -> CFloat (realToFrac x)
"realToFrac/a->CDouble" realToFrac = \x -> CDouble (realToFrac x)
"realToFrac/a->CLDouble" realToFrac = \x -> CLDouble (realToFrac x)
"realToFrac/CFloat->a" realToFrac = \(CFloat x) -> realToFrac x
"realToFrac/CDouble->a" realToFrac = \(CDouble x) -> realToFrac x
"realToFrac/CLDouble->a" realToFrac = \(CLDouble x) -> realToFrac x
#-}
-- | Haskell type representing the C @ptrdiff_t@ type.
INTEGRAL_TYPE(CPtrdiff,tyConCPtrdiff,"CPtrdiff",HTYPE_PTRDIFF_T)
-- | Haskell type representing the C @size_t@ type.
INTEGRAL_TYPE(CSize,tyConCSize,"CSize",HTYPE_SIZE_T)
-- | Haskell type representing the C @wchar_t@ type.
INTEGRAL_TYPE(CWchar,tyConCWchar,"CWchar",HTYPE_WCHAR_T)
-- | Haskell type representing the C @sig_atomic_t@ type.
INTEGRAL_TYPE(CSigAtomic,tyConCSigAtomic,"CSigAtomic",HTYPE_SIG_ATOMIC_T)
{-# RULES
"fromIntegral/a->CPtrdiff" fromIntegral = \x -> CPtrdiff (fromIntegral x)
"fromIntegral/a->CSize" fromIntegral = \x -> CSize (fromIntegral x)
"fromIntegral/a->CWchar" fromIntegral = \x -> CWchar (fromIntegral x)
"fromIntegral/a->CSigAtomic" fromIntegral = \x -> CSigAtomic (fromIntegral x)
"fromIntegral/CPtrdiff->a" fromIntegral = \(CPtrdiff x) -> fromIntegral x
"fromIntegral/CSize->a" fromIntegral = \(CSize x) -> fromIntegral x
"fromIntegral/CWchar->a" fromIntegral = \(CWchar x) -> fromIntegral x
"fromIntegral/CSigAtomic->a" fromIntegral = \(CSigAtomic x) -> fromIntegral x
#-}
-- | Haskell type representing the C @clock_t@ type.
ARITHMETIC_TYPE(CClock,tyConCClock,"CClock",HTYPE_CLOCK_T)
-- | Haskell type representing the C @time_t@ type.
ARITHMETIC_TYPE(CTime,tyConCTime,"CTime",HTYPE_TIME_T)
-- FIXME: Implement and provide instances for Eq and Storable
-- | Haskell type representing the C @FILE@ type.
data CFile = CFile
-- | Haskell type representing the C @fpos_t@ type.
data CFpos = CFpos
-- | Haskell type representing the C @jmp_buf@ type.
data CJmpBuf = CJmpBuf
INTEGRAL_TYPE(CIntPtr,tyConCIntPtr,"CIntPtr",HTYPE_INTPTR_T)
INTEGRAL_TYPE(CUIntPtr,tyConCUIntPtr,"CUIntPtr",HTYPE_UINTPTR_T)
INTEGRAL_TYPE(CIntMax,tyConCIntMax,"CIntMax",HTYPE_INTMAX_T)
INTEGRAL_TYPE(CUIntMax,tyConCUIntMax,"CUIntMax",HTYPE_UINTMAX_T)
{-# RULES
"fromIntegral/a->CIntPtr" fromIntegral = \x -> CIntPtr (fromIntegral x)
"fromIntegral/a->CUIntPtr" fromIntegral = \x -> CUIntPtr (fromIntegral x)
"fromIntegral/a->CIntMax" fromIntegral = \x -> CIntMax (fromIntegral x)
"fromIntegral/a->CUIntMax" fromIntegral = \x -> CUIntMax (fromIntegral x)
#-}
-- C99 types which are still missing include:
-- wint_t, wctrans_t, wctype_t
{- $ctypes
These types are needed to accurately represent C function prototypes,
in order to access C library interfaces in Haskell. The Haskell system
is not required to represent those types exactly as C does, but the
following guarantees are provided concerning a Haskell type @CT@
representing a C type @t@:
* If a C function prototype has @t@ as an argument or result type, the
use of @CT@ in the corresponding position in a foreign declaration
permits the Haskell program to access the full range of values encoded
by the C type; and conversely, any Haskell value for @CT@ has a valid
representation in C.
* @'sizeOf' ('Prelude.undefined' :: CT)@ will yield the same value as
@sizeof (t)@ in C.
* @'alignment' ('Prelude.undefined' :: CT)@ matches the alignment
constraint enforced by the C implementation for @t@.
* The members 'peek' and 'poke' of the 'Storable' class map all values
of @CT@ to the corresponding value of @t@ and vice versa.
* When an instance of 'Prelude.Bounded' is defined for @CT@, the values
of 'Prelude.minBound' and 'Prelude.maxBound' coincide with @t_MIN@
and @t_MAX@ in C.
* When an instance of 'Prelude.Eq' or 'Prelude.Ord' is defined for @CT@,
the predicates defined by the type class implement the same relation
as the corresponding predicate in C on @t@.
* When an instance of 'Prelude.Num', 'Prelude.Read', 'Prelude.Integral',
'Prelude.Fractional', 'Prelude.Floating', 'Prelude.RealFrac', or
'Prelude.RealFloat' is defined for @CT@, the arithmetic operations
defined by the type class implement the same function as the
corresponding arithmetic operations (if available) in C on @t@.
* When an instance of 'Bits' is defined for @CT@, the bitwise operation
defined by the type class implement the same function as the
corresponding bitwise operation in C on @t@.
-}
#else /* __NHC__ */
import NHC.FFI
( CChar(..), CSChar(..), CUChar(..)
, CShort(..), CUShort(..), CInt(..), CUInt(..)
, CLong(..), CULong(..), CLLong(..), CULLong(..)
, CPtrdiff(..), CSize(..), CWchar(..), CSigAtomic(..)
, CClock(..), CTime(..)
, CFloat(..), CDouble(..), CLDouble(..)
, CFile, CFpos, CJmpBuf
, Storable(..)
)
import Data.Bits
import NHC.SizedTypes
#define INSTANCE_BITS(T) \
instance Bits T where { \
(T x) .&. (T y) = T (x .&. y) ; \
(T x) .|. (T y) = T (x .|. y) ; \
(T x) `xor` (T y) = T (x `xor` y) ; \
complement (T x) = T (complement x) ; \
shift (T x) n = T (shift x n) ; \
rotate (T x) n = T (rotate x n) ; \
bit n = T (bit n) ; \
setBit (T x) n = T (setBit x n) ; \
clearBit (T x) n = T (clearBit x n) ; \
complementBit (T x) n = T (complementBit x n) ; \
testBit (T x) n = testBit x n ; \
bitSize (T x) = bitSize x ; \
isSigned (T x) = isSigned x }
INSTANCE_BITS(CChar)
INSTANCE_BITS(CSChar)
INSTANCE_BITS(CUChar)
INSTANCE_BITS(CShort)
INSTANCE_BITS(CUShort)
INSTANCE_BITS(CInt)
INSTANCE_BITS(CUInt)
INSTANCE_BITS(CLong)
INSTANCE_BITS(CULong)
INSTANCE_BITS(CLLong)
INSTANCE_BITS(CULLong)
INSTANCE_BITS(CPtrdiff)
INSTANCE_BITS(CWchar)
INSTANCE_BITS(CSigAtomic)
INSTANCE_BITS(CSize)
#endif
|
alekar/hugs
|
packages/base/Foreign/C/Types.hs
|
bsd-3-clause
| 11,978
| 14
| 6
| 1,984
| 746
| 467
| 279
| -1
| -1
|
module Data.Students where
import Data.Semester
{- |
'Students' represents a group of semester-groups which take part in
a lecture
-}
data Students = Students { semester :: [Semester]
, count :: Int
}
deriving (Show,Eq)
instance Num Students where
Students a b + Students c d = Students (a++c) (b + d)
Students a b * Students c d = Students (a++c) (b * d)
abs = id
signum = const 1
fromInteger = Students [] . fromInteger
instance Ord Students where
Students a x <= Students b y = compare x y /= GT
Students a x < Students b y = compare x y == LT
Students a x >= Students b y = compare x y /= LT
Students a x > Students b y = compare x y == GT
|
spirit-fhs/core
|
Data/Students.hs
|
bsd-3-clause
| 733
| 0
| 9
| 223
| 290
| 141
| 149
| 16
| 0
|
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies #-}
{-# LANGUAGE OverloadedStrings, GADTs, FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving, MultiParamTypeClasses #-}
module Schema where
import Database.Persist
import Database.Persist.Postgresql
import Database.Persist.TH (mkPersist, mkMigrate, persistLowerCase, share, sqlSettings)
import Data.Text
import Data.Time
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Subscription
adapter Text
topic Text
expiry UTCTime Maybe
AdapterTopic adapter topic
deriving Show
|]
|
keithduncan/chatterbox
|
src/db/Schema.hs
|
mit
| 591
| 0
| 7
| 83
| 75
| 47
| 28
| 10
| 0
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[PatSyn]{@PatSyn@: Pattern synonyms}
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module Eta.BasicTypes.PatSyn (
-- * Main data types
PatSyn, mkPatSyn,
-- ** Type deconstruction
patSynName, patSynArity, patSynIsInfix,
patSynArgs, patSynTyDetails, patSynType,
patSynMatcher, patSynBuilder,
patSynExTyVars, patSynSig,
patSynInstArgTys, patSynInstResTy,
tidyPatSynIds
) where
#include "HsVersions.h"
import Eta.Types.Type
import Eta.TypeCheck.TcType( mkSigmaTy )
import Eta.BasicTypes.Name
import Eta.Utils.Outputable
import Eta.BasicTypes.Unique
import Eta.Utils.Util
import Eta.BasicTypes.BasicTypes
import Eta.Utils.FastString
import Eta.BasicTypes.Var
import Eta.HsSyn.HsBinds( HsPatSynDetails(..) )
import qualified Data.Data as Data
import qualified Data.Typeable
import Data.Function
{-
************************************************************************
* *
\subsection{Pattern synonyms}
* *
************************************************************************
-}
-- | A pattern synonym
-- See Note [Pattern synonym representation]
data PatSyn
= MkPatSyn {
psName :: Name,
psUnique :: Unique, -- Cached from Name
psArgs :: [Type],
psArity :: Arity, -- == length psArgs
psInfix :: Bool, -- True <=> declared infix
psUnivTyVars :: [TyVar], -- Universially-quantified type variables
psReqTheta :: ThetaType, -- Required dictionaries
psExTyVars :: [TyVar], -- Existentially-quantified type vars
psProvTheta :: ThetaType, -- Provided dictionaries
psOrigResTy :: Type, -- Mentions only psUnivTyVars
-- See Note [Matchers and builders for pattern synonyms]
psMatcher :: (Id, Bool),
-- Matcher function.
-- If Bool is True then prov_theta and arg_tys are empty
-- and type is
-- forall (r :: ?) univ_tvs. req_theta
-- => res_ty
-- -> (forall ex_tvs. Void# -> r)
-- -> (Void# -> r)
-- -> r
--
-- Otherwise type is
-- forall (r :: ?) univ_tvs. req_theta
-- => res_ty
-- -> (forall ex_tvs. prov_theta => arg_tys -> r)
-- -> (Void# -> r)
-- -> r
psBuilder :: Maybe (Id, Bool)
-- Nothing => uni-directional pattern synonym
-- Just (builder, is_unlifted) => bi-directional
-- Builder function, of type
-- forall univ_tvs, ex_tvs. (prov_theta, req_theta)
-- => arg_tys -> res_ty
-- See Note [Builder for pattern synonyms with unboxed type]
}
deriving Data.Typeable.Typeable
{-
Note [Pattern synonym representation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following pattern synonym declaration
pattern P x = MkT [x] (Just 42)
where
data T a where
MkT :: (Show a, Ord b) => [b] -> a -> T a
so pattern P has type
b -> T (Maybe t)
with the following typeclass constraints:
provides: (Show (Maybe t), Ord b)
requires: (Eq t, Num t)
In this case, the fields of MkPatSyn will be set as follows:
psArgs = [b]
psArity = 1
psInfix = False
psUnivTyVars = [t]
psExTyVars = [b]
psProvTheta = (Show (Maybe t), Ord b)
psReqTheta = (Eq t, Num t)
psOrigResTy = T (Maybe t)
Note [Matchers and builders for pattern synonyms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For each pattern synonym P, we generate
* a "matcher" function, used to desugar uses of P in patterns,
which implements pattern matching
* A "builder" function (for bidirectional pattern synonyms only),
used to desugar uses of P in expressions, which constructs P-values.
For the above example, the matcher function has type:
$mP :: forall (r :: ?) t. (Eq t, Num t)
=> T (Maybe t)
-> (forall b. (Show (Maybe t), Ord b) => b -> r)
-> (Void# -> r)
-> r
with the following implementation:
$mP @r @t $dEq $dNum scrut cont fail
= case scrut of
MkT @b $dShow $dOrd [x] (Just 42) -> cont @b $dShow $dOrd x
_ -> fail Void#
Notice that the return type 'r' has an open kind, so that it can
be instantiated by an unboxed type; for example where we see
f (P x) = 3#
The extra Void# argument for the failure continuation is needed so that
it is lazy even when the result type is unboxed.
For the same reason, if the pattern has no arguments, an extra Void#
argument is added to the success continuation as well.
For *bidirectional* pattern synonyms, we also generate a "builder"
function which implements the pattern synonym in an expression
context. For our running example, it will be:
$bP :: forall t b. (Show (Maybe t), Ord b, Eq t, Num t)
=> b -> T (Maybe t)
$bP x = MkT [x] (Just 42)
NB: the existential/universal and required/provided split does not
apply to the builder since you are only putting stuff in, not getting
stuff out.
Injectivity of bidirectional pattern synonyms is checked in
tcPatToExpr which walks the pattern and returns its corresponding
expression when available.
Note [Builder for pattern synonyms with unboxed type]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For bidirectional pattern synonyms that have no arguments and have an
unboxed type, we add an extra Void# argument to the builder, else it
would be a top-level declaration with an unboxed type.
pattern P = 0#
$bP :: Void# -> Int#
$bP _ = 0#
This means that when typechecking an occurrence of P in an expression,
we must remember that the builder has this void argument. This is
done by TcPatSyn.patSynBuilderOcc.
************************************************************************
* *
\subsection{Instances}
* *
************************************************************************
-}
instance Eq PatSyn where
(==) = (==) `on` getUnique
(/=) = (/=) `on` getUnique
instance Ord PatSyn where
(<=) = (<=) `on` getUnique
(<) = (<) `on` getUnique
(>=) = (>=) `on` getUnique
(>) = (>) `on` getUnique
compare = compare `on` getUnique
instance Uniquable PatSyn where
getUnique = psUnique
instance NamedThing PatSyn where
getName = patSynName
instance Outputable PatSyn where
ppr = ppr . getName
instance OutputableBndr PatSyn where
pprInfixOcc = pprInfixName . getName
pprPrefixOcc = pprPrefixName . getName
instance Data.Data PatSyn where
-- don't traverse?
toConstr _ = abstractConstr "PatSyn"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "PatSyn"
{-
************************************************************************
* *
\subsection{Construction}
* *
************************************************************************
-}
-- | Build a new pattern synonym
mkPatSyn :: Name
-> Bool -- ^ Is the pattern synonym declared infix?
-> ([TyVar], ThetaType) -- ^ Universially-quantified type variables
-- and required dicts
-> ([TyVar], ThetaType) -- ^ Existentially-quantified type variables
-- and provided dicts
-> [Type] -- ^ Original arguments
-> Type -- ^ Original result type
-> (Id, Bool) -- ^ Name of matcher
-> Maybe (Id, Bool) -- ^ Name of builder
-> PatSyn
mkPatSyn name declared_infix
(univ_tvs, req_theta)
(ex_tvs, prov_theta)
orig_args
orig_res_ty
matcher builder
= MkPatSyn {psName = name, psUnique = getUnique name,
psUnivTyVars = univ_tvs, psExTyVars = ex_tvs,
psProvTheta = prov_theta, psReqTheta = req_theta,
psInfix = declared_infix,
psArgs = orig_args,
psArity = length orig_args,
psOrigResTy = orig_res_ty,
psMatcher = matcher,
psBuilder = builder }
-- | The 'Name' of the 'PatSyn', giving it a unique, rooted identification
patSynName :: PatSyn -> Name
patSynName = psName
patSynType :: PatSyn -> Type
-- The full pattern type, used only in error messages
patSynType (MkPatSyn { psUnivTyVars = univ_tvs, psReqTheta = req_theta
, psExTyVars = ex_tvs, psProvTheta = prov_theta
, psArgs = orig_args, psOrigResTy = orig_res_ty })
= mkSigmaTy univ_tvs req_theta $
mkSigmaTy ex_tvs prov_theta $
mkFunTys orig_args orig_res_ty
-- | Should the 'PatSyn' be presented infix?
patSynIsInfix :: PatSyn -> Bool
patSynIsInfix = psInfix
-- | Arity of the pattern synonym
patSynArity :: PatSyn -> Arity
patSynArity = psArity
patSynArgs :: PatSyn -> [Type]
patSynArgs = psArgs
patSynTyDetails :: PatSyn -> HsPatSynDetails Type
patSynTyDetails (MkPatSyn { psInfix = is_infix, psArgs = arg_tys })
| is_infix, [left,right] <- arg_tys
= InfixPatSyn left right
| otherwise
= PrefixPatSyn arg_tys
patSynExTyVars :: PatSyn -> [TyVar]
patSynExTyVars = psExTyVars
patSynSig :: PatSyn -> ([TyVar], [TyVar], ThetaType, ThetaType, [Type], Type)
patSynSig (MkPatSyn { psUnivTyVars = univ_tvs, psExTyVars = ex_tvs
, psProvTheta = prov, psReqTheta = req
, psArgs = arg_tys, psOrigResTy = res_ty })
= (univ_tvs, ex_tvs, prov, req, arg_tys, res_ty)
patSynMatcher :: PatSyn -> (Id,Bool)
patSynMatcher = psMatcher
patSynBuilder :: PatSyn -> Maybe (Id, Bool)
patSynBuilder = psBuilder
tidyPatSynIds :: (Id -> Id) -> PatSyn -> PatSyn
tidyPatSynIds tidy_fn ps@(MkPatSyn { psMatcher = matcher, psBuilder = builder })
= ps { psMatcher = tidy_pr matcher, psBuilder = fmap tidy_pr builder }
where
tidy_pr (id, dummy) = (tidy_fn id, dummy)
patSynInstArgTys :: PatSyn -> [Type] -> [Type]
-- Return the types of the argument patterns
-- e.g. data D a = forall b. MkD a b (b->a)
-- pattern P f x y = MkD (x,True) y f
-- D :: forall a. forall b. a -> b -> (b->a) -> D a
-- P :: forall c. forall b. (b->(c,Bool)) -> c -> b -> P c
-- patSynInstArgTys P [Int,bb] = [bb->(Int,Bool), Int, bb]
-- NB: the inst_tys should be both universal and existential
patSynInstArgTys (MkPatSyn { psName = name, psUnivTyVars = univ_tvs
, psExTyVars = ex_tvs, psArgs = arg_tys })
inst_tys
= ASSERT2( length tyvars == length inst_tys
, ptext (sLit "patSynInstArgTys") <+> ppr name $$ ppr tyvars $$ ppr inst_tys )
map (substTyWith tyvars inst_tys) arg_tys
where
tyvars = univ_tvs ++ ex_tvs
patSynInstResTy :: PatSyn -> [Type] -> Type
-- Return the type of whole pattern
-- E.g. pattern P x y = Just (x,x,y)
-- P :: a -> b -> Just (a,a,b)
-- (patSynInstResTy P [Int,Bool] = Maybe (Int,Int,Bool)
-- NB: unlikepatSynInstArgTys, the inst_tys should be just the *universal* tyvars
patSynInstResTy (MkPatSyn { psName = name, psUnivTyVars = univ_tvs
, psOrigResTy = res_ty })
inst_tys
= ASSERT2( length univ_tvs == length inst_tys
, ptext (sLit "patSynInstResTy") <+> ppr name $$ ppr univ_tvs $$ ppr inst_tys )
substTyWith univ_tvs inst_tys res_ty
|
rahulmutt/ghcvm
|
compiler/Eta/BasicTypes/PatSyn.hs
|
bsd-3-clause
| 12,214
| 0
| 14
| 3,773
| 1,461
| 887
| 574
| 134
| 1
|
-- |
-- Module: Data.STM.TCursor
-- Copyright: (c) Joseph Adams 2012
-- License: BSD3
-- Maintainer: joeyadams3.14159@gmail.com
-- Portability: Requires STM
--
-- This module provides an API very similar to "Control.Concurrent.STM.TChan".
-- However, unlike 'TChan':
--
-- * It is based on "Data.STM.TList", rather than using an abstract internal
-- representation.
--
-- * It separates the read end and write end. This means if the channel has no
-- readers, items written with 'writeTCursor' can be garbage collected.
--
-- Here is an implementation of 'TChan' based on 'TCursor':
--
-- >type TChan a = (TCursor a, TCursor a)
-- >
-- >newTChan = newTCursorPair
-- >
-- >newTChanIO = newTCursorPairIO
-- >
-- >readTChan = readTCursor . fst
-- >
-- >writeTChan = writeTCursor . snd
-- >
-- >dupTChan (_, writeEnd) = do
-- > newReadEnd <- dupTCursor writeEnd
-- > return (newReadEnd, writeEnd)
-- >
-- >unGetTChan = unGetTCursor . fst
-- >
-- >isEmptyTChan = isEmptyTCursor . fst
module Data.STM.TCursor (
-- * The TCursor type
-- $tcursor
TCursor,
-- * Construction
newTCursorPair,
newTCursorPairIO,
dupTCursor,
-- * Reading and writing
readTCursor,
tryReadTCursor,
writeTCursor,
unGetTCursor,
isEmptyTCursor,
) where
import Prelude hiding (null)
import Data.STM.TList
import Control.Concurrent.STM
import Control.Monad (liftM2)
-- | A 'TCursor' is a mutable cursor used for traversing items. While 'uncons'
-- and 'append' return the subsequent 'TList', 'readTCursor' and 'writeTCursor'
-- modify the cursor in-place, and thus behave more like 'readTChan' and
-- 'writeTChan'.
type TCursor a = TVar (TList a)
-- | /O(1)/. Construct an empty channel, returning the read cursor ('fst') and
-- write cursor ('snd').
newTCursorPair :: STM (TCursor a, TCursor a)
newTCursorPair = do
hole <- empty
liftM2 (,) (newTVar hole) (newTVar hole)
-- | /O(1)/. 'IO' variant of 'newCursorPair'. See 'newTVarIO' for the
-- rationale.
newTCursorPairIO :: IO (TCursor a, TCursor a)
newTCursorPairIO = do
hole <- emptyIO
liftM2 (,) (newTVarIO hole) (newTVarIO hole)
-- | /O(1)/. Read the next item and advance the cursor. 'retry' if the
-- channel is currently empty.
--
-- This should be called on the /read/ cursor of the channel.
readTCursor :: TCursor a -> STM a
readTCursor cursor =
readTVar cursor >>=
uncons retry
(\x xs -> do writeTVar cursor xs
return x)
-- | /O(1)/. Like 'readTCursor', but return 'Nothing', rather than 'retry'ing,
-- if the list is currently empty.
tryReadTCursor :: TCursor a -> STM (Maybe a)
tryReadTCursor cursor =
readTVar cursor >>=
uncons (return Nothing)
(\x xs -> do writeTVar cursor xs
return (Just x))
-- | /O(1)/. Append an item and advance the cursor.
--
-- This should be called on the /write/ cursor of the channel. See 'append'
-- for more details.
writeTCursor :: TCursor a -> a -> STM ()
writeTCursor cursor x =
readTVar cursor >>= flip append x >>= writeTVar cursor
-- | /O(1)/. Make a copy of a 'TCursor'. Modifying the old cursor with
-- 'readTCursor' or 'writeTCursor' will not affect the new cursor, and vice
-- versa.
dupTCursor :: TCursor a -> STM (TCursor a)
dupTCursor cursor = readTVar cursor >>= newTVar
-- | /O(1)/. Put an item back on the channel, where it will be the next item
-- read by 'readTCursor'.
--
-- This should be called on the /read/ cursor of the channel.
unGetTCursor :: TCursor a -> a -> STM ()
unGetTCursor cursor x =
readTVar cursor >>= cons x >>= writeTVar cursor
-- | /O(1)/. Return 'True' if the channel is empty.
--
-- This should be called on the /read/ cursor of the channel.
isEmptyTCursor :: TCursor a -> STM Bool
isEmptyTCursor cursor = readTVar cursor >>= null
|
abailly/kontiki
|
ring-buffer/src/Data/STM/TCursor.hs
|
bsd-3-clause
| 3,874
| 0
| 13
| 849
| 565
| 316
| 249
| 45
| 1
|
{-# LANGUAGE DefaultSignatures, RecordWildCards #-}
module Servant.Server.Auth.Token.Persistent.Schema where
import Data.Text
import Data.Time
import Database.Persist.Sql (Key, SqlBackend, ToBackendKey, fromSqlKey,
toSqlKey)
import Database.Persist.TH
import GHC.Generics (Generic)
import Servant.API.Auth.Token
import Servant.Server.Auth.Token.Common (ConvertableKey, fromKey,
toKey)
import qualified Servant.Server.Auth.Token.Model as M
share [mkPersist sqlSettings
, mkDeleteCascade sqlSettings
, mkMigrate "migrateAll"] [persistLowerCase|
UserImpl
login Login
password Password -- encrypted with salt
email Email
UniqueLogin login
deriving Generic Show
UserPerm
user UserImplId
permission Permission
deriving Generic Show
AuthToken
value SimpleToken
user UserImplId
expire UTCTime
deriving Generic Show
UserRestore
value RestoreCode
user UserImplId
expire UTCTime
deriving Generic Show
UserSingleUseCode
value SingleUseCode
user UserImplId
expire UTCTime Maybe -- Nothing is code that never expires
used UTCTime Maybe
deriving Generic Show
AuthUserGroup
name Text
parent AuthUserGroupId Maybe
deriving Generic Show
AuthUserGroupUsers
group AuthUserGroupId
user UserImplId
deriving Generic Show
AuthUserGroupPerms
group AuthUserGroupId
permission Permission
deriving Generic Show
|]
-- | Defines way to convert from persistent struct to model struct and vice versa.
--
-- Warning: default implementation is done via 'unsafeCoerce#', so make sure that
-- structure of 'a' and 'b' is completely identical.
class ConvertStorage a b | a -> b, b -> a where
-- | Convert to internal representation
convertTo :: b -> a
default convertTo :: (ToBackendKey SqlBackend r, a ~ Key r, ConvertableKey b) => b -> a
convertTo = toSqlKey . fromKey
-- | Convert from internal representation
convertFrom :: a -> b
default convertFrom :: (ToBackendKey SqlBackend r, a ~ Key r, ConvertableKey b) => a -> b
convertFrom = toKey . fromSqlKey
instance ConvertStorage UserImpl M.UserImpl where
convertTo M.UserImpl{..} =
UserImpl { userImplLogin = userImplLogin
, userImplPassword = userImplPassword
, userImplEmail = userImplEmail
}
convertFrom UserImpl{..} =
M.UserImpl { userImplLogin = userImplLogin
, userImplPassword = userImplPassword
, userImplEmail = userImplEmail
}
instance ConvertStorage UserPerm M.UserPerm where
convertTo M.UserPerm{..} =
UserPerm { userPermUser = convertTo userPermUser
, userPermPermission = userPermPermission
}
convertFrom UserPerm{..} =
M.UserPerm { userPermUser = convertFrom userPermUser
, userPermPermission = userPermPermission
}
instance ConvertStorage AuthToken M.AuthToken where
convertTo M.AuthToken{..} =
AuthToken { authTokenValue = authTokenValue
, authTokenUser = convertTo authTokenUser
, authTokenExpire = authTokenExpire
}
convertFrom AuthToken{..} =
M.AuthToken { authTokenValue = authTokenValue
, authTokenUser = convertFrom authTokenUser
, authTokenExpire = authTokenExpire
}
instance ConvertStorage UserRestore M.UserRestore where
convertTo M.UserRestore{..} =
UserRestore { userRestoreValue = userRestoreValue
, userRestoreUser = convertTo userRestoreUser
, userRestoreExpire = userRestoreExpire
}
convertFrom UserRestore{..} =
M.UserRestore { userRestoreValue = userRestoreValue
, userRestoreUser = convertFrom userRestoreUser
, userRestoreExpire = userRestoreExpire
}
instance ConvertStorage UserSingleUseCode M.UserSingleUseCode where
convertTo M.UserSingleUseCode{..} =
UserSingleUseCode { userSingleUseCodeValue = userSingleUseCodeValue
, userSingleUseCodeUser = convertTo userSingleUseCodeUser
, userSingleUseCodeExpire = userSingleUseCodeExpire
, userSingleUseCodeUsed = userSingleUseCodeUsed
}
convertFrom UserSingleUseCode{..} =
M.UserSingleUseCode { userSingleUseCodeValue = userSingleUseCodeValue
, userSingleUseCodeUser = convertFrom userSingleUseCodeUser
, userSingleUseCodeExpire = userSingleUseCodeExpire
, userSingleUseCodeUsed = userSingleUseCodeUsed
}
instance ConvertStorage AuthUserGroup M.AuthUserGroup where
convertTo M.AuthUserGroup{..} =
AuthUserGroup { authUserGroupName = authUserGroupName
, authUserGroupParent = convertTo <$> authUserGroupParent
}
convertFrom AuthUserGroup{..} =
M.AuthUserGroup { authUserGroupName = authUserGroupName
, authUserGroupParent = convertFrom <$> authUserGroupParent
}
instance ConvertStorage AuthUserGroupUsers M.AuthUserGroupUsers where
convertTo M.AuthUserGroupUsers{..} =
AuthUserGroupUsers { authUserGroupUsersGroup = convertTo authUserGroupUsersGroup
, authUserGroupUsersUser = convertTo authUserGroupUsersUser
}
convertFrom AuthUserGroupUsers{..} =
M.AuthUserGroupUsers { authUserGroupUsersGroup = convertFrom authUserGroupUsersGroup
, authUserGroupUsersUser = convertFrom authUserGroupUsersUser
}
instance ConvertStorage AuthUserGroupPerms M.AuthUserGroupPerms where
convertTo M.AuthUserGroupPerms{..} =
AuthUserGroupPerms { authUserGroupPermsGroup = convertTo authUserGroupPermsGroup
, authUserGroupPermsPermission = authUserGroupPermsPermission
}
convertFrom AuthUserGroupPerms{..} =
M.AuthUserGroupPerms { authUserGroupPermsGroup = convertFrom authUserGroupPermsGroup
, authUserGroupPermsPermission = authUserGroupPermsPermission
}
instance ConvertStorage UserImplId M.UserImplId
instance ConvertStorage UserPermId M.UserPermId
instance ConvertStorage AuthTokenId M.AuthTokenId
instance ConvertStorage UserRestoreId M.UserRestoreId
instance ConvertStorage UserSingleUseCodeId M.UserSingleUseCodeId
instance ConvertStorage AuthUserGroupId M.AuthUserGroupId
instance ConvertStorage AuthUserGroupUsersId M.AuthUserGroupUsersId
instance ConvertStorage AuthUserGroupPermsId M.AuthUserGroupPermsId
|
ivan-m/servant-auth-token
|
servant-auth-token-persistent/src/Servant/Server/Auth/Token/Persistent/Schema.hs
|
bsd-3-clause
| 6,866
| 0
| 11
| 1,861
| 1,043
| 580
| 463
| -1
| -1
|
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Fix
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2002
-- License : BSD-style (see the file libraries/base/LICENSE)
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Monadic fixpoints.
--
-- For a detailed discussion, see Levent Erkok's thesis,
-- /Value Recursion in Monadic Computations/, Oregon Graduate Institute, 2002.
--
-----------------------------------------------------------------------------
module Control.Monad.Fix (
MonadFix(
mfix -- :: (a -> m a) -> m a
),
fix -- :: (a -> a) -> a
) where
import Prelude
import System.IO
import Control.Monad.Instances ()
-- | @'fix' f@ is the least fixed point of the function @f@,
-- i.e. the least defined @x@ such that @f x = x@.
fix :: (a -> a) -> a
fix f = let x = f x in x
-- | Monads having fixed points with a \'knot-tying\' semantics.
-- Instances of 'MonadFix' should satisfy the following laws:
--
-- [/purity/]
-- @'mfix' ('return' . h) = 'return' ('fix' h)@
--
-- [/left shrinking/ (or /tightening/)]
-- @'mfix' (\\x -> a >>= \\y -> f x y) = a >>= \\y -> 'mfix' (\\x -> f x y)@
--
-- [/sliding/]
-- @'mfix' ('Control.Monad.liftM' h . f) = 'Control.Monad.liftM' h ('mfix' (f . h))@,
-- for strict @h@.
--
-- [/nesting/]
-- @'mfix' (\\x -> 'mfix' (\\y -> f x y)) = 'mfix' (\\x -> f x x)@
--
-- This class is used in the translation of the recursive @do@ notation
-- supported by GHC and Hugs.
class (Monad m) => MonadFix m where
-- | The fixed point of a monadic computation.
-- @'mfix' f@ executes the action @f@ only once, with the eventual
-- output fed back as the input. Hence @f@ should not be strict,
-- for then @'mfix' f@ would diverge.
mfix :: (a -> m a) -> m a
-- Instances of MonadFix for Prelude monads
-- Maybe:
instance MonadFix Maybe where
mfix f = let a = f (unJust a) in a
where unJust (Just x) = x
-- List:
instance MonadFix [] where
mfix f = case fix (f . head) of
[] -> []
(x:_) -> x : mfix (tail . f)
-- IO:
instance MonadFix IO where
mfix = fixIO
instance MonadFix ((->) r) where
mfix f = \ r -> let a = f a r in a
|
kaoskorobase/mescaline
|
resources/hugs/packages/base/Control/Monad/Fix.hs
|
gpl-3.0
| 2,333
| 8
| 12
| 531
| 350
| 202
| 148
| 24
| 1
|
module Journal
( appendEntry
, newJournal
, removeJournal
, viewJournal
) where
import Entry
import Control.Monad
import Control.Monad.IO.Class
import Data.Time.LocalTime
import System.Console.Haskeline
import System.Directory
import System.IO
import System.IO.Error
-- Utility Functions
journalFolder :: String -> IO FilePath
journalFolder x = liftM (\h -> h ++ "/journals/" ++ x ++ ".txt") getHomeDirectory
openJournal :: String -> IOMode -> IO Handle
openJournal n m = journalFolder n >>= flip openFile m
-- Writing to journal files
appendEntry :: String -> InputT IO ()
appendEntry n = do
eitherJournal <- liftIO $ tryIOError $ openJournal n AppendMode
case eitherJournal of
Left e -> when (isDoesNotExistError e) $ liftIO (newJournal n) >> appendEntry n
Right h -> getInputLine "> " >>= \i -> case i of
Nothing -> return ()
Just i' -> liftIO $ getZonedTime >>= hAppendJournal h . flip Entry i'
hAppendJournal :: Handle -> Entry -> IO ()
hAppendJournal h e = hPrint h e >> hClose h
-- Creating journals
newJournal :: String -> IO ()
newJournal n = openJournal n ReadWriteMode >>= \h -> hPutStrLn h n >> hClose h
-- Removing journals
removeJournal :: String -> InputT IO ()
removeJournal n = do
f <- liftIO $ journalFolder n
exists <- liftIO $ doesFileExist f
if exists
then do
i <- getInputLine $ "Are you sure you want to remove the journal " ++ show n ++ "? Enter (Y)es or (N)o: "
case i of
Just "Yes" -> liftIO $ removeFile f
Just "Y" -> liftIO $ removeFile f
_ -> return ()
else outputStrLn $ "Journal " ++ n ++ " does not exist"
-- Viewing Logs
viewJournal :: String -> IO ()
viewJournal n = do
f <- journalFolder n
exists <- doesFileExist f
if exists
then openFile f ReadMode >>= \h -> hGetContents h >>= putStrLn >> hClose h
else putStrLn $ "Journal " ++ n ++ " does not exist"
|
dwnusbaum/log
|
Journal.hs
|
bsd-2-clause
| 2,016
| 0
| 17
| 544
| 631
| 311
| 320
| 48
| 4
|
-----------------------------------------------------------------------------
-- |
-- DEPRECATED: use @Language.Haskell.Interpreter.Unsafe@ instead.
-----------------------------------------------------------------------------
module Language.Haskell.Interpreter.GHC.Unsafe
{-# DEPRECATED "Import Language.Haskell.Interpreter.Unsafe instead." #-}
(
module Language.Haskell.Interpreter.Unsafe
)
where
import Language.Haskell.Interpreter.Unsafe
|
konn/hint-forked
|
src/Language/Haskell/Interpreter/GHC/Unsafe.hs
|
bsd-3-clause
| 449
| 0
| 5
| 30
| 31
| 24
| 7
| 5
| 0
|
module TestRec where
import Prelude hiding (foldl)
data L a = N | C { hd :: a
, tl :: L a }
{-@ data L [llen] a = N | C { hd :: a
, tl :: L a }
@-}
{-@ invariant {v:L a | 0 <= llen v} @-}
{-@ measure llen @-}
llen :: L a -> Int
llen N = 0
llen (C x xs) = 1 + llen xs
reverse :: L a -> L a
reverse xs = go N xs
where
{-@ go :: acc:_ -> xs:_ -> _ / [llen xs] @-}
go acc N = acc
go acc (C x xs) = go (C x acc) xs
mapL f N = N
mapL f (C x xs) = C (f x) (mapL f xs)
|
ssaavedra/liquidhaskell
|
tests/pos/testRec.hs
|
bsd-3-clause
| 547
| 0
| 9
| 222
| 206
| 108
| 98
| 13
| 2
|
module Database.Persist.Types
( module Database.Persist.Types.Base
, SomePersistField (..)
, Update (..)
, BackendSpecificUpdate
, SelectOpt (..)
, Filter (..)
, FilterValue (..)
, BackendSpecificFilter
, Key
, Entity (..)
) where
import Database.Persist.Types.Base
import Database.Persist.Class.PersistField
import Database.Persist.Class.PersistEntity
|
creichert/persistent
|
persistent/Database/Persist/Types.hs
|
mit
| 398
| 0
| 5
| 82
| 89
| 63
| 26
| 14
| 0
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="es-ES">
<title>Common Library</title>
<maps>
<homeID>commonlib</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/commonlib/src/main/javahelp/help_es_ES/helpset_es_ES.hs
|
apache-2.0
| 965
| 77
| 66
| 156
| 407
| 206
| 201
| -1
| -1
|
{-# LANGUAGE PolyKinds, TypeFamilies, DataKinds #-}
class C a where
type T (n :: a)
instance C a => C b => C (a, b) where
type T '(n, m) = (T n, T m)
-- but this worked fine:
--
-- instance (C a, C b) => C (a, b) where
-- type T '(n, m) = (T n, T m)
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_fail/T16394.hs
|
bsd-3-clause
| 263
| 5
| 7
| 75
| 71
| 42
| 29
| -1
| -1
|
{-# LANGUAGE UnboxedTuples #-}
module T14740 where
x :: ((##)) => ()
x = ()
|
shlevy/ghc
|
testsuite/tests/parser/should_fail/T14740.hs
|
bsd-3-clause
| 78
| 0
| 6
| 17
| 28
| 18
| 10
| -1
| -1
|
module Deadlock where
import Distribution.TestSuite
import Lib
tests :: IO [Test]
tests = return [nullt x | x <- [1 .. 1000]]
|
tolysz/prepare-ghcjs
|
spec-lts8/cabal/Cabal/tests/PackageTests/TestSuiteTests/LibV09/tests/Deadlock.hs
|
bsd-3-clause
| 130
| 0
| 9
| 26
| 51
| 29
| 22
| 5
| 1
|
{-# LANGUAGE Arrows #-}
module T5022 ( pIterate ) where
import Prelude hiding ( init )
returnA :: b -> b
returnA = id
------------
newtype State s a = State { unState :: [a] }
------------
pIterate :: a -> [a]
pIterate =
proc x -> do
rec
as <- unState -< s
let s = State (x:as)
returnA -< as
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/arrows/should_compile/T5022.hs
|
bsd-3-clause
| 328
| 1
| 15
| 98
| 117
| 67
| 50
| 13
| 1
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.HTMLHRElement (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.HTMLHRElement
#else
module Graphics.UI.Gtk.WebKit.DOM.HTMLHRElement
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.HTMLHRElement
#else
import Graphics.UI.Gtk.WebKit.DOM.HTMLHRElement
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/HTMLHRElement.hs
|
mit
| 450
| 0
| 5
| 39
| 33
| 26
| 7
| 4
| 0
|
import Data.Maybe
-- If on day 1 we deposit x and on day 2 we deposit y, then the balance is:
--
-- Day | Balance
-- ----------------------
-- 1 | x
-- 2 | x + y
-- 3 | 2x + y
-- 4 | 3x + 2y
-- 5 | 5x + 3y
-- ................
-- n | F_n * x + F_{n-1} * y
--
-- where F_i is the ith Fibonacci number.
--
-- Thus, our problem is to find x and y to maximize n for which
--
-- F_n * x + F_{n-1} * y = 1000000
--
-- where x and y are nonnegative integers.
-- First, rather than peppering the code with 1000000, let's define it as a
-- constant.
target :: Int
target = 1000000
-- Since this is Haskell, we can create the infinite stream of Fibonacci
-- numbers and then use only what we need from it.
fib :: [Int]
fib = 1 : 1 : zipWith (+) fib (tail fib)
-- Since all numbers are positive, we only need the first few Fibonacci
-- numbers: only those smaller than `target`.
valid_fibs :: [Int]
valid_fibs = takeWhile (<= target) fib
-- We want the maximum n, so we want the maximum Fibbonacci coefficients.
-- Thus, we reverse the above list
candidates :: [Int]
candidates = reverse valid_fibs
-- The equation has two consecutive Fibbonacci coefficients, so we pair them.
pairs :: [(Int, Int)]
pairs = zip candidates (tail candidates)
-- Detemrine all solutions of F_n * x + F_{n-1} * y = t
-- Assumes that the second argument is a pair of consecutive Fibbonacci
-- numbers in decreasing order.
solve :: Int -> (Int, Int) -> [(Int, Int)]
solve t (a, b)
| t < a = []
| t == a = [(1, 0)]
| otherwise = catMaybes $ map find_y possible_xs
where
possible_xs = [0 .. (t `div` a)]
find_y x
| left `mod` b == 0 = Just (x, left `div` b)
| otherwise = Nothing
where
left = t - a * x
-- Find al solutions that lead to target
allSols :: Int -> [(Int, Int)]
allSols t = concatMap (solve t) pairs
-- Display the solutions in a nice format, and have a main
main = mapM_ print $ allSols target
|
mihaimaruseac/blog-demos
|
mpmp/6/main.hs
|
mit
| 2,006
| 3
| 9
| 525
| 405
| 230
| 175
| 24
| 1
|
{-# LANGUAGE CPP, OverloadedStrings, ForeignFunctionInterface, QuasiQuotes #-}
module TankGauge where
import JavaScript.Canvas
import GHCJS.Foreign
import Control.Applicative
import Control.Concurrent
import GHCJS.Foreign.QQ
import Data.Text
import Text.Printf
newtype Scale = Scale { unScale :: (Int, Int) } deriving (Eq, Show)
data TankColor = BlueTank | BlackTank deriving (Show, Eq)
type RenderableTank = TankGauge Image
type RawTank = TankGauge TankColor
data TankGauge imgType = TankGauge {
tankGaugeMaxLevel :: Double
, tankGaugeCurrentLevel :: Double
, tankGaugeColor :: imgType
} deriving (Show, Eq)
toRenderable :: RawTank -> IO RenderableTank
toRenderable (TankGauge maxLevel currentLevel color) = TankGauge maxLevel currentLevel <$> getImage color
testGauge :: RawTank
testGauge = TankGauge 200 100 BlueTank
testGauge2 :: RawTank
testGauge2 = TankGauge 200 150 BlackTank
getImage :: TankColor -> IO Image
getImage BlueTank = createImage "static/img/blue-tank.png"
getImage BlackTank = createImage "static/img/black-tank.png"
scaleWidthHeight :: Scale -> (Int,Int) -> (Int, Int)
scaleWidthHeight (Scale (absWidth, absHeight)) (width, height) = (floor width' , floor height')
where width' = (fromIntegral $ width * absWidth) / 1000.0 :: Double
height' = (fromIntegral $ height * absHeight )/ 1000.0 :: Double
drawTankGauge :: Context -> IO ()
drawTankGauge ctx = do
i <- createImage "static/img/green-tank.png"
renderableGauge <- toRenderable testGauge
let render = drawTank ctx i renderableGauge
scale 3 3 ctx
mapM_ (\ p -> onAnimation $ clearRect 0 0 2000 2000 ctx >> render (easeIn 1.0 p) ) $ [0.0,0.02..1.0]
easeIn :: Double -> Double -> Double
easeIn maxP t = maxP * if t < 0.5
then 2*t*t
else -1+(4-2*t)*t
drawTank :: Context -> Image -> RenderableTank -> Double -> IO ()
drawTank ctx baseImg (TankGauge maxVal val overlay) progress = do
let fullPercentage = progress * (val / maxVal)
currentAnimVal = progress * val
drawImage baseImg 0 0 124 200 ctx
drawImagePercentage ctx overlay (124,200) fullPercentage
drawLines ctx
translate 0 (190 - 180 * fullPercentage) ctx
drawCenterLine ctx
translate 155 0 ctx
drawTriangle ctx
drawPrecentage ctx currentAnimVal
translate (-155) 0 ctx
translate 0 (- (190 - 180 * fullPercentage)) ctx
return ()
drawPrecentage :: Context -> Double -> IO ()
drawPrecentage ctx val = do
let dx = 10
dy = 4
translate dx dy ctx
font "12px Georgia" ctx
fillText (pack $ printf "%.2f\n" (val)) 0 0 ctx
translate (-dx) (-dy) ctx
-- | Given an image, (width, height) and the height percentage,
-- draw an image starting from the bottom of the screen until it hits correct percent of
-- the image using drawImageSlice
drawImagePercentage :: Context -> Image -> (Double, Double) -> Double -> IO ()
drawImagePercentage ctx img (ctxWidth, ctxHeight) perc = do
(imgWidth, imgHeight) <- imageDimensions img
let sPerc = scalePerc (0.05, 0.9) perc
sx = 0
sHeight = imgHeight * sPerc
sy = imgHeight - sHeight
sWidth = imgWidth
dx = 0
dWidth = ctxWidth
dHeight = ctxHeight * sPerc
dy = ctxHeight - dHeight
drawImageSlice img sx sy sWidth sHeight dx dy dWidth dHeight ctx
scalePerc :: (Double,Double) -> Double -> Double
scalePerc (minP, maxP) p = minP + (maxP * p)
drawTriangle :: Context -> IO ()
drawTriangle ctx = do
beginPath ctx
moveTo 0 0 ctx
lineTo 7.6 (-7.8) ctx
lineTo 7.6 (7.8) ctx
fill ctx
closePath ctx
drawCenterLine :: Context -> IO ()
drawCenterLine ctx = do
beginPath ctx
lineWidth 0.5 ctx
moveTo 5 0 ctx
lineTo 155 0 ctx
stroke ctx
closePath ctx
drawLines :: Context -> IO ()
drawLines ctx = do
beginPath ctx
moveTo 155 10 ctx
lineTo 155 190 ctx
lineWidth 2 ctx
stroke ctx
lineWidth 1 ctx
translate 150 10 ctx
mapM_ makeTick [0,18..180]
translate (-150) (-10) ctx
where makeTick :: Double -> IO ()
makeTick y = do
beginPath ctx
moveTo 0 (y) ctx
lineTo 6 (y) ctx
stroke ctx
closePath ctx
-----------------------------------------------------
-- Below are functions that I needed that aren't in
-- the canvas library right now
-----------------------------------------------------
-- | Look at https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Using_images#Slicing for more
-- info
drawImageSlice :: Image -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Double -> Context -> IO ()
drawImageSlice img sx sy sWidth sHeight dx dy dWidth dHeight ctx = do
[js_|`ctx.drawImage(`img, `sx, `sy, `sWidth, `sHeight, `dx, `dy, `dWidth, `dHeight)|]
imageDimensions :: Image -> IO (Double, Double)
imageDimensions img = (,) <$> (imageWidth img) <*> (imageHeight img)
imageHeight :: Image -> IO Double
imageHeight img = [js|`img.height|]
imageWidth :: Image -> IO Double
imageWidth img = [js|`img.width|]
onAnimation :: IO () -> IO ()
onAnimation action = do
mv <- newEmptyMVar
cb <- syncCallback NeverRetain True (action >> putMVar mv ())
[js_|window.requestAnimationFrame(`cb)|]
takeMVar mv
-- | Load an image into a JSRef wrapper
-- and wait for the image to be loaded
createImage :: String -> IO Image
createImage imageName = do
image <- newImage
[js_| `image.src = `imageName|]
mv <- newEmptyMVar
cb <- syncCallback NeverRetain True (putMVar mv ()) -- Put the mvar when the image has been loaded
[js_|`image.onload = `cb|]
_ <- takeMVar mv
return image
newImage :: IO Image
newImage = [js| new Image() |]
|
plow-technologies/shakespeare-dynamic
|
ghcjs-shakespeare-dynamic/example/TankGauge.hs
|
mit
| 5,628
| 0
| 16
| 1,171
| 1,806
| 913
| 893
| 140
| 2
|
module Ch2Probs where
{----1-----------
*Ch2Prob> (2^3)*4
32
*Ch2Prob> 2^3*4
32
*Ch2Prob> (2^3*4)
32
*Ch2Prob> 2^(3*4)
4096
------2---------
*Ch2Prob> 2*3 + 4*5
26
*Ch2Prob> 2*(3 + 4)*5
70
*Ch2Prob> (2*3 + 4)*5
50
*Ch2Prob> 2*(3 + 4*5)
46
-------3----------
*Ch2Prob> 2+3*4^5
3074
*Ch2Prob> (2+3*4)^5
537824
*Ch2Prob> 2+3*(4^5)
3074
*Ch2Prob> (2+3)*4^5
5120
*Ch2Probs> 2+(3*4)^5
248834
-}
-- 2.3 Function application
f = \a -> b+c*d
where
b = 7
c = 8
d = 9
{- f :: a -> Integer
- f :: a -> Int
- f :: a -> Float
- f :: a -> Double
-
n = a `div` length xs
where
a = 10
xs = [1, 2, 3, 4, 5]
-}
double x = x+x
quadruple x = double(double x)
{-
*Ch2Probs> take (double 2) [5,4,3,2,1,0]
[5,4,3,2]
-}
average ns = sum ns `div` length ns
-- *Ch2Probs> average [5,4,3,2,1,0]
-- 2
factorial n = product[1..n]
-- lib function "last", that takes last element from a [xs] list.
astL xs = [xs!!x|x <-[(length xs)-1]]
asTL xs = concat ([drop x xs| x <-[(length xs)-1]])
-- [xs!!((length xs)-1)]
-- [[5,4,3,2,1,0]!!x|x <-[(length[5,4,3,2,1,0])-1]]
-- Prelude> astL [5,4,3,2,1,0]
-- [0]
-- redo init
-- in 2 different ways.
-- concat[(take x [5,4,3,2,1,0])|x <-[(length[5,4,3,2,1,0])-1]]
nitI xs = take ((length xs)-1)xs
-- Prelude> niti [5,4,3,2,1,0]
-- [5,4,3,2,1]
|
HaskellForCats/HaskellForCats
|
MenaBeginning/Ch002-Ch03/ch2Probs.hs
|
mit
| 1,796
| 0
| 13
| 761
| 225
| 125
| 100
| 12
| 1
|
module Main where
import Network.IRC.Client.Core
import Prelude
-- | main function
main :: IO ()
main = defaultMain
|
cosmo0920/hs-IRC
|
hs-IRC.hs
|
mit
| 117
| 0
| 6
| 19
| 30
| 19
| 11
| 5
| 1
|
import Control.Monad.Writer
newtype DiffList a = DiffList {getDiffList :: [a] -> [a]}
toDiffList :: [a] -> DiffList a
toDiffList xs = DiffList (xs++)
fromDiffList :: DiffList a -> [a]
fromDiffList (DiffList f) = f []
instance Monoid (DiffList a) where
mempty = DiffList (\xs -> [] ++ xs)
(DiffList f) `mappend` (DiffList g) = DiffList (\xs -> f (g xs))
--finalCountDown :: Int -> Writer (DiffList String) ()
--finalCountDown 0 = do
-- tell (toDiffList ["0"])
--finalCountDown x = do
-- finalCountDown (x-1)
-- tell (toDiffList [show x])
finalCountDown :: Int -> Writer [String] ()
finalCountDown 0 = do
tell ["0"]
finalCountDown x = do
finalCountDown (x-1)
tell [show x]
|
RAFIRAF/HASKELL
|
For a Few Monads More/finalCountdown.hs
|
mit
| 765
| 0
| 11
| 204
| 251
| 134
| 117
| 15
| 1
|
{-# LANGUAGE LambdaCase, TupleSections, OverloadedStrings #-}
{-# LANGUAGE TypeFamilies, FlexibleContexts #-}
module HFish.Parser.Parser where
import qualified HFish.Parser.Redirect as Redirect
import HFish.Parser.Common
import HFish.Parser.Gen
import HFish.Parser.Glob
import Fish.Lang
import Fish.Lang.Unit
import Text.Parser.Permutation
import Text.Parser.Combinators
import Text.Parser.LookAhead
import Text.Parser.Char hiding (space,spaces)
import Data.Functor
import Data.Bool
import Data.Semigroup hiding (option)
import Data.NText
import qualified Data.Char as C
import qualified Data.Text as T
import qualified Data.List.NonEmpty as N
import Control.Applicative
import Control.Monad
import Control.Monad.State
program :: P m => m (Prog T.Text ())
program = prog <* eof
prog :: P m => m (Prog T.Text ())
prog = stmtSep *>
( Prog ()
<$> (compStmt `sepEndBy` stmtSep1) )
<?> "code-block"
progN :: P m => m (Prog T.Text ())
progN = stmtSep1 *>
( Prog ()
<$> (compStmt `sepEndBy` stmtSep1) )
<?> "code-block"
exprs :: P m => m (Exprs T.Text ())
exprs = Exprs ()
<$> (expr `sepEndBy` spaces1)
<?> "expressions"
compStmt :: P m => m (CompStmt T.Text ())
compStmt = do
st <- stmt
option (Simple () st)
( spaces *>
( piped st <|> forked st ) )
where
piped st = Piped ()
<$> ( sym "|" $> Fd1
<|> sym "1>|" $> Fd1
<|> sym "2>|" $> Fd2 )
<*> return st
<*> compStmt
<?> "pipe"
forked st =
sym "&"
$> Forked () st
<?> "fork-symbol"
stmt :: P m => m (Stmt T.Text ())
stmt = do
st <- plain
option st $ try (RedirectedSt () st <$> redirects)
<?> "statement"
where
redirects =
N.fromList
<$> some redirect
<?> "redirections"
plain = choice [
commentSt
,funSt
,whileSt
,forSt
,ifSt
,switchSt
,beginSt
,andSt
,orSt
,notSt
,cmdSt
]
commentSt :: P m => m (Stmt T.Text ())
commentSt = (CommentSt () . T.pack)
<$> (char '#' *> many (notChar '\n'))
<?> "comment-statement"
cmdSt :: P m => m (Stmt T.Text ())
cmdSt = CmdSt () <$> (expr `sepEndByNonEmpty` spaces1)
<?> "command-statement"
funSt :: P m => m (Stmt T.Text ())
funSt = sym1 "function" *> (
FunctionSt ()
<$> lexemeN funIdent
<*> exprs
<*> progN
) <* symN "end"
<?> "function-statement"
whileSt :: P m => m (Stmt T.Text ())
whileSt = sym1 "while" *>
(WhileSt ()
<$> stmt
<*> progN <* symN "end")
<?> "while-statement"
forSt :: P m => m (Stmt T.Text ())
forSt = sym1 "for" *>
( ForSt ()
<$> (lexeme1 varIdent <* sym1 "in")
<*> exprs
<*> progN ) <* symN "end"
<?> "for-statement"
ifSt :: P m => m (Stmt T.Text ())
ifSt =
( IfSt () . N.fromList
<$> ( (:) <$> ifblock <*> many elif )
<*> optional el ) <* symN "end"
<?> "if-statement"
where
ifblock = sym1 "if" *>
((,) <$> stmt <*> progN)
elif =
lexeme1 (string "else" *> spaces1 *> string "if")
*> ((,) <$> stmt <*> progN)
el = symN "else" *> progN
switchSt :: P m => m (Stmt T.Text ())
switchSt = sym1 "switch" *>
( SwitchSt ()
<$> lexemeN expr
<*> ( stmtSep1 *>
( N.fromList <$> some switchCase ) ) )
<* symN "end"
<?> "switch-statement"
where
switchCase = sym1 "case" *>
( (,) <$> lexemeN expr <*> progN )
beginSt :: P m => m (Stmt T.Text ())
beginSt = symN "begin"
*> ( BeginSt () <$> progN )
<* symN "end"
andSt :: P m => m (Stmt T.Text ())
andSt = sym1 "and"
*> (AndSt () <$> stmt)
<?> "and-statement"
orSt :: P m => m (Stmt T.Text ())
orSt = sym1 "or"
*> (OrSt () <$> stmt)
<?> "or-statement"
notSt :: P m => m (Stmt T.Text ())
notSt = sym1 "not"
*> (NotSt () <$> stmt)
<?> "not-statement"
expr :: P m => m (Expr T.Text ())
expr = do
s <- exprSimple
option s (ConcatE () s <$> expr)
<?> "expression"
where
exprSimple = choice
[ strlike
,varRefE
,cmdSubstE
,bracesE
,globE
,homeDirE ]
varRefE :: P m => m (Expr T.Text ())
varRefE =
( VarRefE () False <$> varRef False )
<|> ( VarRefE () True <$> varRef True )
<?> "variable-reference"
bracesE :: P m => m (Expr T.Text ())
bracesE = BracesE () <$> (
start *> body <* end
) <?> "braces-substitution"
where
start = char '{'
end = char '}' <?> "end of braces-substitution"
body = expr `sepBy` char ','
cmdSubstE :: P m => m (Expr T.Text ())
cmdSubstE = CmdSubstE ()
<$> cmdRef
<?> "command-substitution"
globE :: P m => m (Expr T.Text ())
globE = GlobE ()
<$> glob
<?> "glob-pattern"
homeDirE :: P m => m (Expr T.Text ())
homeDirE = char '~' $> HomeDirE () <?> "~"
redirect :: P m => m (Redirect (Expr T.Text ()))
redirect = Redirect.redirect (lexemeN expr)
ref :: P m => m i -> m (Ref i)
ref q =
optional (start *> body <* end)
<?> "array-reference"
where
start = sym "[" <?> "index-range"
end = char ']' <?> "end of index-range"
body = range `sepEndBy` spaces1
range = do
i <- q
option (Index i) ( Range i <$> (sym "..." *> q) )
cmdRef :: P m => m (CmdRef T.Text ())
cmdRef =
CmdRef ()
<$> body
<*> ref expr
where
body = start *> prog <* end
start = sym "(" <?> "command-substitution"
end = char ')' <?> "end of command-substitution"
varRef :: P m => Bool -> m (VarRef T.Text ())
varRef q = VarRef ()
<$> try name
<*> ref expr
<?> "variable-reference"
where
name = char (if q then '&' else '$') *>
parseEither (varRef q) varIdent
strlike :: P m => m (Expr T.Text ())
strlike =
strSQ
<|> strDQ
<|> strNQ
<?> "string"
strSQ :: P m => m (Expr T.Text ())
strSQ = (StringE () . pack)
<$> ( start *>
strGen allowed escPass escSwallow escIgnore allowEmpty
<* end )
where
start = char '\''
end = char '\'' <?> "end of string"
allowed = noneOf' "'\\"
escPass = oneOf' "'\\"
escSwallow = mzero
escIgnore = noneOf' "'\\"
allowEmpty = True
strDQ :: P m => m (Expr T.Text ())
strDQ = (StringE () . pack)
<$> ( start *>
strGen allowed escPass escSwallow escIgnore allowEmpty
<* end )
where
start = char '"'
end = char '"' <?> "end of string"
allowed = noneOf' "\"\\\n"
escPass = oneOf' "\"\\"
escSwallow = char '\n'
escIgnore = noneOf' "\n\"\\"
allowEmpty = True
strNQ :: P m => m (Expr T.Text ())
strNQ = do
(StringE () . pack)
<$> strGen allowed escPass escSwallow escIgnore allowEmpty
where
invalid =
"\n\t $&\\*?~%#(){}[]<>^;,\"\'|012."
allowed =
noneOf' invalid
<|> try ( oneOf' "012" <* notFollowedBy (oneOf' "><") )
<|> try ( char '.' <* notFollowedBy (string "..") )
escPass =
(escapeSequence <$> oneOf' "ntfrvabe")
<|> try (char 'c' *> anyChar >>= controlSequence)
<|> notChar '\n'
escSwallow = char '\n'
escIgnore = mzero
allowEmpty = False
escapeSequence :: Char -> Char
escapeSequence = \case
'n' -> '\n'
't' -> '\t'
'f' -> '\f'
'r' -> '\r'
'v' -> '\v'
'a' -> '\a'
'b' -> '\b'
'e' -> C.chr 0x1B
controlSequence :: MonadPlus m => Char -> m Char
controlSequence = \case
'@' -> return (C.chr 0)
'[' -> return (C.chr 0x1B)
'\\' -> return (C.chr 0x1C)
']' -> return (C.chr 0x1D)
'^' -> return (C.chr 0x1E)
'_' -> return (C.chr 0x1F)
'?' -> return (C.chr 0x7F)
c ->
let i = C.ord c - C.ord 'a'
in if i >= 0 && i <= C.ord 'z'
then return (C.chr i)
else mzero
varIdent :: P m => m (VarIdent T.Text ())
varIdent = (VarIdent () . mkNText . T.pack)
<$> ((:) <$> letter <*> many (alphaNum <|> char '_'))
<?> "variable-identifier"
funIdent :: P m => m (FunIdent T.Text ())
funIdent = (FunIdent () . mkNText . T.pack)
<$> some ( alphaNum <|> oneOf "_-" )
<?> "function-identifier"
|
xaverdh/hfish-parser
|
HFish/Parser/Parser.hs
|
mit
| 7,962
| 0
| 17
| 2,247
| 3,210
| 1,622
| 1,588
| 283
| 16
|
module Wrapper where
import Data.Char
import Data.List
import Data.Maybe
import System.Random
import DataTypes
import FleetParser
data Interface = Interface
{ iEmptyField :: Field
, iEmptyFleet :: Fleet
, iExampleFleet :: Fleet
, iShootAtCoordinate :: Field -> Coord -> Fleet -> (Field, Int)
, iAllShipsSunken :: Field -> Bool
, iPrintField :: Field -> IO ()
, iShuffleShots :: StdGen -> [(Coord)] -> [(Coord)]
, iFullShots :: [(Coord)]
, iAddToFleet :: Fleet -> Boat -> (Fleet, Bool)
, iIsValidFleet :: Fleet -> Bool
, iSinkShip :: [Direction] -> Field -> Fleet -> Coord -> [Coord] -> (Field, [Coord])
, iDirections :: [Direction]
, iDraw :: [Coord] -> Fleet -> IO ()
, iPrintFleet :: Fleet -> IO ()
}
startGame :: Interface -> IO ()
startGame i = do
putStrLn "Welcome to the game of Battleship!"
putStrLn "Please provide a name of a file containing a fleet"
fp <- getLine
contents <- readFile fp
let f = pFleet contents
if (isJust f)
then
if (iIsValidFleet i (fst(fromJust f)))
then do
putStrLn "This is the fleet"
iPrintFleet i (fst(fromJust f))
putStrLn "Computer will shoot you now..."
runGame i (fst(fromJust f))
else do putStrLn "The fleet in the file is not valid. Try another one? y/n"
answ <- getLine
case answ of
"y" -> startGame i
"n" -> putStrLn "Bye bye!"
else do
putStrLn "Could not read the fleet from a file. Try another one? y/n"
answ <- getLine
case answ of
"y" -> startGame i
"n" -> putStrLn "Bye bye!"
-- Takes a fleet as a parameter and starts the game
runGame :: Interface -> Fleet -> IO ()
runGame i f = do
putStrLn "*** The initial field***"
iPrintField i (iEmptyField i)
g <- newStdGen
putStrLn "*** Go! ***"
let shots = iShuffleShots i g (iFullShots i)
gameLoop i 0 (iEmptyField i) f shots
gameLoop :: Interface -> Int -> Field -> Fleet -> [(Coord)] -> IO ()
gameLoop i num field fleet [] = print "No shots left."
gameLoop i num field fleet shots = do
if (iAllShipsSunken i field)
then
finish num
else
do
let c = head shots
res = iShootAtCoordinate i field c fleet
case snd res of
0 -> do
putStrLn ("Miss at " ++ show c ++ " !")
iPrintField i (fst res)
gameLoop i (num + 1) (fst res) fleet (tail shots)
1 -> do
putStrLn ("Hit at " ++ show c ++ " !")
iPrintField i (fst res)
let sinkRes = iSinkShip i (iDirections i) (fst res) fleet c (tail shots)
iDraw i ((tail shots)\\(snd sinkRes)) fleet
iPrintField i (fst sinkRes)
let us = (length shots) - (length (snd sinkRes))
gameLoop i (num + us) (fst sinkRes) fleet (snd sinkRes)
2 -> do
putStrLn ("Sink at" ++ show c ++ "!")
iPrintField i (fst res)
gameLoop i (num + 1) (fst res) fleet (tail shots)
finish :: Int -> IO ()
finish shots = do
putStrLn ("The computer beat you with " ++ show shots ++ " shots.")
|
tdeekens/tda452-code
|
Lab-4-Submission/Wrapper.hs
|
mit
| 3,296
| 2
| 22
| 1,111
| 1,105
| 549
| 556
| 83
| 5
|
{-# LANGUAGE TupleSections, RecordWildCards, TemplateHaskell #-}
module Outer.Types where
import Data.Data
import Data.Functor
import Data.List
import Data.Foldable (foldlM)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Control.Monad.State
import Control.Monad.Except
import Control.Monad.Writer
import Control.Lens
import Outer.AST
import Common.Pretty (PP(..), (<+>))
import qualified Common.Pretty as PP
import Common.SrcLoc
import Common.Error
import Common.Types
import Debug.Trace
instance PP TyVarId' where
pp (Flexible v) = pp v
pp (Rigid v) = PP.text "R!" <> pp v
unPrimeTyVarId :: TyVarId' -> TyVarId
unPrimeTyVarId (Flexible v) = v
unPrimeTyVarId (Rigid v) = v
-- * Type checking state monad
-- | Assumes ALL variables have different IDs (Rewriting phase needed!)
type TcMonad a = WriterT [Constraint]
(StateT TcState
(Either Message)) a
data Constraint = Equal OTcType' OTcType' String deriving (Eq, Show)
data TcState = TcState { freshNum :: !Int
, _tcEnv :: OTcEnv'
}
deriving (Eq, Show)
makeLenses ''TcState
runTc :: OTcEnv' -> TcMonad a -> Either Message (a, [Constraint])
runTc tcEnv m = evalStateT (runWriterT m) (TcState 0 tcEnv)
getTc :: TcMonad OTcEnv'
getTc = liftM _tcEnv get
putTc :: OTcEnv' -> TcMonad ()
putTc = modifyTc . const
modifyTc :: (OTcEnv' -> OTcEnv') -> TcMonad ()
modifyTc = modify . over tcEnv
-- | Runs a computation, then resets the state to its initial value.
localTc :: TcMonad a -> TcMonad a
localTc m = do
env <- getTc
x <- m
putTc env
return x
tcLookupVar :: VarId -> TcMonad OScheme'
tcLookupVar x = do
TcEnv{varEnv = m} <- getTc
case Map.lookup x m of
Just ty -> return ty
Nothing -> throwTypeE noLoc "Unbound Variable" x
tcLookupCon :: ConId -> TcMonad OScheme'
tcLookupCon x = do
TcEnv{conEnv = m} <- getTc
case Map.lookup x m of
Just ty -> return ty
Nothing -> throwTypeE noLoc "Unknown Constructor" x
fresh :: TcMonad TyVarId
fresh = do
i@TcState{freshNum = s} <- get
put $ i{freshNum = succ s}
return $ "@" ++ show s
equate :: OTcType' -> OTcType' -> String -> TcMonad ()
equate t1 t2 s | t1 == t2 = return ()
| otherwise = tell [Equal t1 t2 s]
equateTyMaybe :: Maybe Exp -> TcMonad (Maybe Exp)
equateTyMaybe Nothing = return Nothing
equateTyMaybe (Just e) = do
(e',t) <- inferTy e
-- TODO: Should this return updated exp? Disallowing typeclasses in weights seems ok
equate tc_int_tycon t $ show ("Disj/weight", e)
return (Just e')
inferTy :: Exp -> TcMonad (Exp, OTcType')
inferTy (Var (x, _)) = do
tx <- tcLookupVar x >>= instantiate
return (Var (x, Just tx), tx)
inferTy (Con c) = tcLookupCon c >>= (((Con c,) <$>) . instantiate)
inferTy (Lit lit) = (Lit lit,) <$> inferLit lit
inferTy (Unop op e) = do
to <- inferOp1 op
(e', te) <- inferTy e
equate to te $ show ("Unop", op, e)
return (Unop op e', to)
inferTy (Conj e1 e2) = do
(e1', t1) <- inferTy e1
(e2', t2) <- inferTy e2
equate tc_bool_tycon t1 $ show ("Conj-1", e1)
equate tc_bool_tycon t2 $ show ("Conj-2", e2)
return (Conj e1' e2', tc_bool_tycon)
inferTy (Disj ne1 e1 ne2 e2) = do
ne1' <- equateTyMaybe ne1
ne2' <- equateTyMaybe ne2
(e1', t1) <- inferTy e1
(e2', t2) <- inferTy e2
equate tc_bool_tycon t1 $ show ("Disj-1", e1)
equate tc_bool_tycon t2 $ show ("Disj-2", e2)
return (Disj ne1' e1' ne2' e2', tc_bool_tycon)
inferTy (Binop e1 op e2) = do
(t1, t2, tr) <- inferOp2 op
(e1', t1') <- inferTy e1
(e2', t2') <- inferTy e2
equate t1 t1' $ show ("Binop", op, e1)
equate t2 t2' $ show ("Binop", op, e2)
return (Binop e1' op e2', tr)
inferTy (Fun vs e) = do
m <- getTc
tvs <- mapM (const $ Flexible <$> fresh) vs
tr <- Flexible <$> fresh
let assoc = Map.fromList . zip (map fst vs) $ Forall Set.empty <$> TcVar <$> tvs
(e', tr') <- localTc $ do
putTc m{varEnv = assoc `Map.union` varEnv m}
inferTy e
equate (TcVar tr) tr' $ "unnamed fun " ++ show (vs, e)
putTc m
return (Fun vs e', funify tvs tr)
inferTy (App e1 e2) = do
(e1', t1) <- inferTy e1
(e2', t2) <- inferTy e2
tv <- TcVar <$> Flexible <$> fresh
equate t1 (TcFun t2 tv) $ show ("App", e1, e2)
return (App e1' e2', tv)
inferTy (If e1 e2 e3) = do
(e1', t1) <- inferTy e1
(e2', t2) <- inferTy e2
(e3', t3) <- inferTy e3
equate t1 tc_bool_tycon $ show ("If1", e1)
equate t2 t3 $ show ("If23", e2, e3)
return (If e1' e2' e3', t2)
inferTy (Case e alts) = do
(e', t) <- inferTy e
(alts', ts) <- unzip <$> mapM (inferTyAlt t) alts
case ts of
x:xs -> do
forM_ xs $ \x' -> equate x x' $ show ("Pat Res", x, x')
return (Case e' alts', x)
_ -> error "Empty branch"
--inferTy (Let binds e) = localTc $ do
-- inferTyDecls binds
-- inferTy e
--inferTy (Fix e) = inferTy e
--inferTy (FixN n e) = inferTy e
inferTy (Fresh x t en e) = do
-- en denotes an integer expression
(en', tn) <- inferTy en
equate tn tc_int_tycon $ show ("Fresh", en, "Int")
-- x is a fresh variable of type t.
-- TODO: What about polymorphic/rigid/flexible?
modifyTc $ \m -> m{varEnv = Map.insert x (Forall Set.empty $ Rigid <$> t) (varEnv m)}
(e', t') <- inferTy e
return (Fresh x t en' e', t')
inferTy (Inst e x) = do
(e', t) <- inferTy e
tx <- tcLookupVar x >>= instantiate
equate tx tc_int_tycon $ show ("Inst", x, tx)
return (Inst e' x, t)
inferTy (Collect e1 e2) = do
(e1', _) <- inferTy e1
(e2', t2) <- inferTy e2
return (Collect e1' e2', t2)
inferTy (TRACE x e) = do
(e',t) <- inferTy e
return (TRACE x e', t)
inferTyAlt :: OTcType' -> Outer.AST.Alt -> TcMonad (Outer.AST.Alt, OTcType')
inferTyAlt t (Outer.AST.Alt loc weight p e) = localTc $ do
inferTyPat t p
(e', t) <- inferTy e
return (Outer.AST.Alt loc weight p e', t)
inferTyPat :: OTcType' -> Pat -> TcMonad ()
inferTyPat t (PVar x) = modifyTc $ \m ->
m{varEnv = Map.insert x (Forall Set.empty t) (varEnv m)}
inferTyPat t (PLit lit) = do
t' <- inferLit lit
equate t t' $ show ("PLit", lit)
inferTyPat t (PApp x pats) = do
t' <- tcLookupCon x >>= instantiate
equate t (resultType t') $ show ("PatApp", x, t)
let go (TcCon _ _ _) [] = return ()
go (TcFun t1 t2) (p:ps) = do
inferTyPat t1 p
go t2 ps
go p _ = throwTypeE noLoc "Mismatch in pattern types" (show p)
go t' pats
inferTyPat _t PWild = return ()
-- | @tcAppify C [v1 .. vn] [t1 .. tn] := t1 -> .. -> tn -> C v1 .. vn@
tcAppify :: c -> [v] -> [TcType c v] -> TcType c v
tcAppify cid vars ts = mkFun ts $ TcCon cid (length vars) (map TcVar vars)
-- | @funify [v1 .. vn] v := v1 -> .. -> vn -> v@
funify :: [v] -> v -> TcType c v
funify xs r = mkFun (TcVar <$> xs) (TcVar r)
dataDecl, sigDecl, classDecl :: Decl -> TcMonad ()
-- | Add user-defined types to the environment.
-- TODO: Check well-formedness of type definitions.
dataDecl (DataDecl loc cid vars cdecls) = do
tcEnv <- getTc
when (Map.member cid $ tyConEnv tcEnv)
$ throwTypeE loc "Multiple type definitions with the same name." cid
case let vs = sort vars
in find (uncurry (==)) $ zip vs (tail vs) of
Nothing -> return ()
Just (v, _) -> throwTypeE loc "Duplicate type variable in type definition."
$ "At type " ++ cid ++ ", duplicate " ++ v
let vars' = Rigid <$> vars
conEnv' = foldl' (\m (ConDecl dcid t) ->
Map.insert dcid
(Forall (Set.fromList vars')
(tcAppify cid vars' ((<$>) Rigid <$> t))) m
) (conEnv tcEnv) cdecls
tyConEnv' = Map.insert cid (vars', conId <$> cdecls) (tyConEnv tcEnv)
conIndices' = Map.union (conIndices tcEnv) $
Map.fromList $ zipWith (\(ConDecl dcid _) i -> (dcid, i)) cdecls [1 ..]
putTc $ tcEnv
{ conEnv = conEnv'
, tyConEnv = tyConEnv'
, conIndices = conIndices' }
where
conId (ConDecl c _) = c
dataDecl _ = return ()
-- | Add all functions to the environment, with their signature whenever
-- it is provided. Functions that do not have a signature can
-- be recognized from their type @Forall [] v@ where @v@ is just a
-- /flexible/ type variable.
-- | TODO: should it do something about class constraints?
sigDecl (TypeSig loc f bindings ty) = do
tcEnv <- getTc
case Map.lookup f $ varEnv tcEnv of
Just (Forall _ (TcVar (Flexible _))) ->
throwTypeE loc "Function signature must appear before its definition." f
Just _ -> throwTypeE loc "More than one signature for one identifier." f
Nothing -> do
let ty' = Rigid <$> ty
vs = fv ty'
sch = Forall vs ty'
putTc $ tcEnv{varEnv = Map.insert f sch $ varEnv tcEnv}
sigDecl (FunDecl _ f _ _ _) = do
tcEnv <- getTc
case Map.lookup f $ varEnv tcEnv of
Just _ -> return ()
Nothing -> do
tv <- TcVar <$> Flexible <$> fresh
let sch = Forall Set.empty tv
putTc $ tcEnv{varEnv = Map.insert f sch $ varEnv tcEnv}
sigDecl _ = return ()
-- Handle a class (basically signatures for the bindings)
classDecl (ClassDecl loc cid cty binds) =
forM_ binds $ \(fid, ty) -> do
tcEnv <- getTc
-- check that fv cty = fv ty'?
let ty' = Flexible <$> ty
vs = fv ty'
sch = Forall vs ty'
-- traceShowM ("Registering ", fid, sch)
putTc $ tcEnv{varEnv = Map.insert fid sch $ varEnv tcEnv}
-- Add an empty binding for the function "fid" in the REnv
-- (Ensures that we can identify which functions are typeclass-based, fast)
-- registerClassFun fid
classDecl _ = return ()
instanceDecl, funDecl :: Decl -> TcMonad Decl
-- | Do type inference on instance definitions
-- Before handling exactly as a function need to unify
-- tyvar in class X tyvar
-- with
-- ty in instance {... =>} X ty
instanceDecl (InstanceDecl loc cid ty ctrs binds) = do
binds' <- forM binds $ \(fid, args, exp,_) -> do
tcEnv <- getTc
-- simulating instantiation
let (Forall vs fty') = varEnv tcEnv Map.! fid
[v] = Set.toList vs
w <- (const $ TcVar <$> Flexible <$> fresh) v
equate w (Rigid <$> ty) $ "instance " ++ cid
let fty = subst (mkSub [v] [w]) fty'
tvs <- mapM (const $ Flexible <$> fresh) args
tr <- Flexible <$> fresh
equate fty (funify tvs tr) $ "fun " ++ fid
let assoc = Map.fromList . zip (map fst args) $ Forall Set.empty <$> TcVar <$> tvs
(exp', tr') <- localTc $ do
putTc tcEnv{varEnv = assoc `Map.union` varEnv tcEnv}
inferTy exp
equate (TcVar tr) tr' $ "fun " ++ fid
-- Restore type environment
putTc tcEnv
return (fid, args, exp', Just fty)
return (InstanceDecl loc cid ty ctrs binds')
-- Register new type in REnv (sticks after restore!)
-- The expression should also be class/inlined
-- registerInstance fid args exp' fty
instanceDecl d = return d
-- | Do type inference on a (recursive) function declaration
-- Get fresh variables for all arguments and result
-- Equate function with the functional type comprised of the fresh variables
-- Fully extend the environment to infer the type of e
-- Equate the result with the fresh variable for the result
-- Return the type variable that corresponds to the function
funDecl d@(FunDecl loc f args e _) = do
m <- getTc
fty <- rigidify $ varEnv m Map.! f
tvs <- mapM (const $ Flexible <$> fresh) args
tr <- Flexible <$> fresh
equate fty (funify tvs tr) $ "fun " ++ f
let assoc = Map.fromList . zip (map fst args) $ Forall Set.empty <$> TcVar <$> tvs
(e',tr') <- localTc $ do
putTc m{varEnv = assoc `Map.union` varEnv m}
inferTy e
equate (TcVar tr) tr' $ "fun " ++ f
putTc m
return (FunDecl loc f args e' (Just fty))
funDecl d = return d
-- | Work in several passes, so that functions can all call each other
-- and have access to all defined types.
inferTyDecls :: [Decl] -> TcMonad [Decl]
inferTyDecls prg = do
mapM_ dataDecl prg
mapM_ sigDecl prg
mapM_ classDecl prg
prg' <- mapM instanceDecl prg
mapM funDecl prg'
-- | Returns the type of the literal
inferLit :: Literal -> TcMonad OTcType'
inferLit (LitInt _) = return tc_int_tycon
-- | Returns the type of the unary operator. Assumes type is preserved
inferOp1 :: Op1 -> TcMonad OTcType'
inferOp1 OpNeg = return tc_int_tycon
inferOp1 OpNot = return tc_bool_tycon
-- | Returns the argument types and result type for a binop.
inferOp2 :: Op2 -> TcMonad (OTcType', OTcType', OTcType')
inferOp2 OpPlus = return (tc_int_tycon, tc_int_tycon, tc_int_tycon)
inferOp2 OpMinus = return (tc_int_tycon, tc_int_tycon, tc_int_tycon)
inferOp2 OpTimes = return (tc_int_tycon, tc_int_tycon, tc_int_tycon)
inferOp2 OpDiv = return (tc_int_tycon, tc_int_tycon, tc_int_tycon)
inferOp2 OpMod = return (tc_int_tycon, tc_int_tycon, tc_int_tycon)
inferOp2 OpEq = return (tc_int_tycon, tc_int_tycon, tc_bool_tycon)
inferOp2 OpNe = return (tc_int_tycon, tc_int_tycon, tc_bool_tycon)
inferOp2 OpLt = return (tc_int_tycon, tc_int_tycon, tc_bool_tycon)
inferOp2 OpGt = return (tc_int_tycon, tc_int_tycon, tc_bool_tycon)
inferOp2 OpLe = return (tc_int_tycon, tc_int_tycon, tc_bool_tycon)
inferOp2 OpGe = return (tc_int_tycon, tc_int_tycon, tc_bool_tycon)
-- | Pretty Printing
instance PP Constraint where
pp (Equal t1 t2 err) = pp t1 <+> PP.text "=" <+> pp t2 <+> PP.text "AT" <+> PP.text err
type Substitution = TSubstitution TyConId TyVarId'
mgu :: OTcType' -> OTcType' -> String -> Either Message Substitution
mgu (TcFun l1 r1) (TcFun l2 r2) err = do
s1 <- mgu l1 l2 err
s2 <- mgu (subst s1 r1) (subst s1 r2) err
return $ s1 `after` s2
mgu (TcVar a@(Flexible _)) t _err = varAsgn a t
mgu t (TcVar a@(Flexible _)) _err = varAsgn a t
mgu (TcVar (Rigid a)) (TcVar (Rigid b)) _err | a == b = return emptySub
mgu (TcCon c1 n1 ts1) (TcCon c2 n2 ts2) err
| c1 == c2 && n1 == n2 =
-- traceShow ("Here", c1, n1, "Folding over", ts1, ts2) $
foldM (\s (t1,t2) -> do
s' <- mgu (subst s t1) (subst s t2) err
return $ s `after` s'
) emptySub (zip ts1 ts2)
| otherwise = throwTypeE noLoc "Mismatched constructors"
(show (c1,n1) ++ " - " ++ show (c2,n2) ++ " AT " ++ err)
mgu t1 t2 err =
throwTypeE noLoc "Types do not unify"
(show t1 ++ " - " ++ show t2 ++ " AT " ++ err)
fv :: Ord v => TcType c v -> Set v
fv (TcVar v) = Set.singleton v
fv (TcFun t1 t2) = (fv t1) `Set.union` (fv t2)
fv (TcCon _ _ ts) = Set.unions (map fv ts)
varAsgn :: TyVarId' -> OTcType' -> Either Message Substitution
varAsgn a t
| t == TcVar a = return emptySub
| a `Set.member` (fv t) =
throwTypeE noLoc "Occur check fails" (show a ++ " in " ++ show t)
| otherwise = return $ mkSub [a] [t]
instantiate :: OScheme' -> TcMonad OTcType'
instantiate (Forall vs ty) = do
let vs' = Set.toList vs
ws <- mapM (const $ TcVar <$> Flexible <$> fresh) vs'
return $ subst (mkSub vs' ws) ty
-- | Turn a type scheme into a type, universally quantified variables
-- become rigid variables.
rigidify :: OScheme' -> TcMonad OTcType'
rigidify (Forall vs ty) = do
let vs' = Set.toList vs
ws <- mapM (const $ TcVar <$> Rigid <$> fresh) vs'
return $ subst (mkSub vs' ws) ty
{-
generalize :: OTcType' -> [Constraint] -> TcMonad OScheme'
generalize ty constraints = do
case solve constraints of
Left err -> throwError err
Right s -> do
env <- getTc
let fvs = fv (subst s ty) `minus` fvEnv (substEnv s (varEnv env))
return $ Forall fvs ty
fvEnv :: Map VarId OScheme' -> Set TyVarId'
fvEnv m = Map.foldr gather Set.empty m where
gather (Forall vs ty) s = (fv ty `minus` vs) `Set.union` s
minus :: Ord a => Set a -> Set a -> Set a
minus = Set.foldr Set.delete
-}
-- | Generalize the type of functions that do not have an explicit signature.
substEnv :: Substitution -> Map VarId OScheme' -> Map VarId OScheme'
substEnv s env = Map.map (substs s) env where
substs sub (Forall _ ty@(TcVar (Flexible _))) =
let ty' = subst sub ty
vs' = fv ty'
in Forall vs' ty'
substs _sub scheme = scheme -- Explicit type signature.
solve :: [Constraint] -> Either Message Substitution
solve cs =
foldM (\s1 (Equal t1 t2 err) -> do
s2 <- mgu (subst s1 t1) (subst s1 t2) err
return (s2 `after` s1)
) emptySub cs
substExp :: Substitution -> Exp -> Exp
substExp s (Var (x, Just t)) = Var (x, Just $ subst s t)
substExp s (Var (x, Nothing)) = Var (x, Nothing)
substExp s (Con c) = Con c
substExp s (Lit l) = Lit l
substExp s (Unop op e) = Unop op $ substExp s e
substExp s (Conj e1 e2) = Conj (substExp s e1) (substExp s e2)
substExp s (Disj me1 e1 me2 e2) = Disj (substExp s <$> me1) (substExp s e1)
(substExp s <$> me2) (substExp s e2)
substExp s (Binop e1 op e2) = Binop (substExp s e1) op (substExp s e2)
substExp s (App e1 e2) = App (substExp s e1) (substExp s e2)
substExp s (If e1 e2 e3) = If (substExp s e1) (substExp s e2) (substExp s e3)
substExp s (Case e alts) = Case (substExp s e) (map (substAlt s) alts)
substExp s (Fun vars e) = Fun vars (substExp s e)
substExp s (Fresh x t e1 e2) = Fresh x t (substExp s e1) (substExp s e2)
substExp s (Inst e x) = Inst (substExp s e) x
substExp s (TRACE x e) = TRACE x (substExp s e)
substExp s (Collect e1 e2) = Collect (substExp s e1) (substExp s e2)
substAlt s (Outer.AST.Alt loc weight pat e) = Outer.AST.Alt loc weight pat (substExp s e)
substDcl :: Substitution -> Decl -> Decl
substDcl s (FunDecl loc f args e mt) = FunDecl loc f args (substExp s e) (subst s <$> mt)
substDcl s (InstanceDecl loc cid ty ctrs binds) =
InstanceDecl loc cid ty ctrs (map (\(a,b,e,mt) -> (a,b, substExp s e, subst s <$> mt)) binds)
substDcl s d = d
typeInference :: Prg -> Either Message (Prg, OTcEnv)
typeInference p =
case runTc initOTcEnv (inferTyDecls p >>= (\p' -> (p',) <$> getTc)) of
Left err -> Left err
Right ((p', tcEnv), c) -> do
s <- solve c
let p'' = map (substDcl s) p'
let TcEnv varEnv' conEnv' conIxs tyConEnv' = tcEnv
return $ (p'', TcEnv
{ varEnv = generalizeMap $ substEnv s varEnv'
, conEnv = generalizeMap conEnv'
, conIndices = conIxs
, tyConEnv = generalizeMap' tyConEnv' })
where
generalizeVar (Flexible v) = v
generalizeVar (Rigid v) = v
generalizeMap = Map.map (\(Forall vs ty) ->
Forall (Set.map generalizeVar vs)
(generalizeVar <$> ty))
generalizeMap' = Map.map (over _1 $ map generalizeVar)
-- | Builtin OTcEnv
initOTcEnv :: OTcEnv'
initOTcEnv = TcEnv Map.empty cE cIxs tcE where
list_tyvar = Rigid "@@0"
list_quant = Forall (Set.singleton list_tyvar)
list_type = TcCon list_tycon_name 1 [TcVar list_tyvar]
bool_type = Forall Set.empty (TcCon "Bool" 0 [])
unit_type = Forall Set.empty (TcCon "Unit" 0 [])
-- Tuple types
mkTuple n =
let vars = tuple_vars n
tcVars = TcVar `map` vars
in
( tuple_con_name n
, tuple_quant vars . foldr TcFun (tuple_type n tcVars) $ tcVars)
tuple_vars n = [ Rigid $ "@@" ++ show i | i <- [1 .. n] ]
tuple_quant = Forall . Set.fromList
tuple_type n tcVars = TcCon (tuple_tycon_name n) n tcVars
max_arity = 9
cE = Map.fromList $
[("Nil" , list_quant list_type)
,("Cons", list_quant (TcFun (TcVar list_tyvar)
(TcFun list_type list_type)))
,("True" , bool_type)
,("False", bool_type)
,("()", unit_type)
] ++ [ mkTuple i | i <- [2 .. max_arity] ]
tcE = Map.fromList $
[("List", ([list_tyvar], ["Nil" , "Cons" ]))
,("Bool", ([], ["True", "False"]))
,("Int", ([], [])) -- TODO: Should be indicated as built-in type
,("Unit", ([], ["()"]))
] ++ [ (tuple_tycon_name i, (tuple_vars i, [tuple_con_name i]))
| i <- [2 .. max_arity] ]
cIxs = Map.fromList $
[("Nil", cIx ([] :: [()])), ("Cons", cIx [()])
,("False", cIx False), ("True", cIx True)
,("()", cIx ())
] ++ [ (tuple_con_name i, 1) | i <- [2 .. max_arity] ]
cIx :: Data a => a -> ConIndex
cIx = constrIndex . toConstr
oBuiltIn :: BuiltIn ConId TyConId TyVarId
oBuiltIn = BuiltIn
{ biInt = "Int"
, biList = "List"
, biListArg = "@@0"
, biListCons = "Cons"
, biListNil = "Nil"
, biUnit = "()"
}
removeClassBindings :: Prg -> OTcEnv -> OTcEnv
removeClassBindings prg (TcEnv ve ce ci tce) = TcEnv ve' ce ci tce
where ve' = foldr handleDecl ve prg
handleDecl (ClassDecl _ _ _ binds) ve =
foldr (\(fid, _) acc -> Map.delete fid acc) ve binds
handleDecl _ ve = ve
|
QuickChick/Luck
|
luck/src/Outer/Types.hs
|
mit
| 20,882
| 0
| 21
| 5,313
| 8,003
| 4,037
| 3,966
| 446
| 4
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.SVGStyleElement
(js_setDisabled, setDisabled, js_getDisabled, getDisabled,
js_setType, setType, js_getType, getType, js_setMedia, setMedia,
js_getMedia, getMedia, js_setTitle, setTitle, js_getTitle,
getTitle, SVGStyleElement, castToSVGStyleElement,
gTypeSVGStyleElement)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"disabled\"] = $2;"
js_setDisabled :: SVGStyleElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGStyleElement.disabled Mozilla SVGStyleElement.disabled documentation>
setDisabled :: (MonadIO m) => SVGStyleElement -> Bool -> m ()
setDisabled self val = liftIO (js_setDisabled (self) val)
foreign import javascript unsafe "($1[\"disabled\"] ? 1 : 0)"
js_getDisabled :: SVGStyleElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGStyleElement.disabled Mozilla SVGStyleElement.disabled documentation>
getDisabled :: (MonadIO m) => SVGStyleElement -> m Bool
getDisabled self = liftIO (js_getDisabled (self))
foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType ::
SVGStyleElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGStyleElement.type Mozilla SVGStyleElement.type documentation>
setType ::
(MonadIO m, ToJSString val) => SVGStyleElement -> val -> m ()
setType self val = liftIO (js_setType (self) (toJSString val))
foreign import javascript unsafe "$1[\"type\"]" js_getType ::
SVGStyleElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGStyleElement.type Mozilla SVGStyleElement.type documentation>
getType ::
(MonadIO m, FromJSString result) => SVGStyleElement -> m result
getType self = liftIO (fromJSString <$> (js_getType (self)))
foreign import javascript unsafe "$1[\"media\"] = $2;" js_setMedia
:: SVGStyleElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGStyleElement.media Mozilla SVGStyleElement.media documentation>
setMedia ::
(MonadIO m, ToJSString val) => SVGStyleElement -> val -> m ()
setMedia self val = liftIO (js_setMedia (self) (toJSString val))
foreign import javascript unsafe "$1[\"media\"]" js_getMedia ::
SVGStyleElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGStyleElement.media Mozilla SVGStyleElement.media documentation>
getMedia ::
(MonadIO m, FromJSString result) => SVGStyleElement -> m result
getMedia self = liftIO (fromJSString <$> (js_getMedia (self)))
foreign import javascript unsafe "$1[\"title\"] = $2;" js_setTitle
:: SVGStyleElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGStyleElement.title Mozilla SVGStyleElement.title documentation>
setTitle ::
(MonadIO m, ToJSString val) => SVGStyleElement -> val -> m ()
setTitle self val = liftIO (js_setTitle (self) (toJSString val))
foreign import javascript unsafe "$1[\"title\"]" js_getTitle ::
SVGStyleElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGStyleElement.title Mozilla SVGStyleElement.title documentation>
getTitle ::
(MonadIO m, FromJSString result) => SVGStyleElement -> m result
getTitle self = liftIO (fromJSString <$> (js_getTitle (self)))
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/SVGStyleElement.hs
|
mit
| 4,181
| 56
| 10
| 602
| 981
| 556
| 425
| 59
| 1
|
module Main where
import Hanabi.Client
main :: IO ()
main = startClient
|
TimoFreiberg/hanabi
|
app/Main.hs
|
mit
| 74
| 0
| 6
| 14
| 24
| 14
| 10
| 4
| 1
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- | This module implements generation of fractals based on other noise modules.
module Graphics.Ninja.Noise.Fractal
( fBm
) where
import Graphics.Ninja.Noise.Types
-- | Fractal brownian motion
-- Input value range is assumed `[-1..1]`, in that case, the output value range also is `[-1..1]`
fBm :: (Num (d a), Fractional b) => Int -> d a -> d a -> b -> Noise (d a) b -> Noise (d a) b
fBm octaves frequency lacunarity persistence source = Noise go where
go x = let values = map (\ (f,a) -> a * noiseAt source (x * f)) $ zip freqs ampls
in sum values / expsum
-- frequencies and amplitutes of the octaves
freqs = take octaves $ iterate (* lacunarity) frequency
ampls = take octaves $ iterate (* persistence) 1
-- maximum value, needed for scaling
expsum = (persistence^octaves-1)/(persistence-1)
|
fatho/ninja
|
src/Graphics/Ninja/Noise/Fractal.hs
|
mit
| 960
| 0
| 18
| 209
| 260
| 139
| 121
| 13
| 1
|
-- Functions from http://learnyouahaskell.com/starting-out
doubleMe x = x*2
doubleUs x y = x*2 + y*2
-- Could also be doubleUs x y = doubleMe x + doubleMe y
-- a function that multiplies a number by 2 but only if
-- that number is smaller than or equal to 100
doubleSmallNumber x = if x > 100
then x
else doubleMe x -- elses in Haskell are mandatory
doubleSmallNumber' x = (if x > 100 then x else x*2) + 1
-- We usually use ' to either denote a strict version of
-- a function (one that isn't lazy) or a slightly modified
-- version of a function or a variable
-- Using list comprehension for functions
length' xs = sum [1 | _ <- xs] -- Modified version of length
-- _ means that we don't care what we'll draw from the list anyway
-- so instead of writing a variable name that we'll never use, we
-- just write _. This function replaces every element of a list
-- with 1 and then sums that up. This means that the resulting
-- sum will be the length of our list.
removeNonUppercase st = [ c | c <- st, c `elem` ['A'..'Z']]
--a function that takes a string and removes everything except
--uppercase letters from it.
--Using list comprehensions to solve the following question
--which right triangle that has integers for all sides and
--all sides equal to or smaller than 10 has a perimeter of 24?
-- All triangles that have sides equal or smaller than 10
triangles = [ (a,b,c) | a <- [1..10], b <- [1..10], c<- [1..10]]
-- Now make them to be right triangles (a^2 + b^2 = c^2)
-- Also let's force c to be the hypotenuse
rightTriangles = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2 ]
-- Finally, let's add the fact that the perimeter must be equal to 24
rightTriangles' = [ (a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c == 24 ]
-- The solution is [(6,8,10)]
|
jeiros/Haskell-Tutorial
|
functions_page1.hs
|
mit
| 1,847
| 4
| 12
| 395
| 407
| 231
| 176
| 11
| 2
|
{-
- Find the K'th element of a list. The first element in the list is number
- 1.
-}
elementAt :: [a] -> Int -> a
elementAt (x:xs) 1 = x
elementAt (x:xs) ind
| ind <= 0 = error "Invalid index."
| otherwise = elementAt xs (ind-1)
|
LucianU/99problems
|
P3.hs
|
mit
| 238
| 0
| 8
| 57
| 86
| 43
| 43
| 5
| 1
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
-- |A bridge between the JuicyPixels and colour packages
-- will result in a own module later on
module JuicySRGB where
import Prelude
import Control.Monad (liftM, ap)
import Codec.Picture
import Codec.Picture.Types
import Data.Word (Word8)
import qualified Data.Colour as C
import qualified Data.Colour.SRGB as SRGB
import qualified Data.Colour.SRGB.Linear as Linear
import qualified Data.Colour.RGBSpace as C
import Foreign.Storable ( Storable )
import Control.Monad.Primitive ( PrimMonad, PrimState )
import Data.Vector.Storable ((!))
import qualified Data.Vector.Storable as V
import qualified Data.Vector.Storable.Mutable as M
-- | lifts the PixelRGB8 to an PixelSRGB8
newtype PixelSRGB8 = PixelSRGB8 PixelRGB8
deriving ( Eq, Ord, Show )
instance Pixel PixelSRGB8 where
type PixelBaseComponent PixelSRGB8 = Word8
{-# INLINE pixelOpacity #-}
pixelOpacity = const maxBound
{-# INLINE mixWith #-}
mixWith f (PixelSRGB8 a) (PixelSRGB8 b) = PixelSRGB8 $ mixWith f a b
{-# INLINE componentCount #-}
componentCount _ = 3
{-# INLINE colorMap #-}
colorMap f (PixelSRGB8 a) = PixelSRGB8 $ colorMap f a
pixelAt image@(Image { imageData = arr }) x y = PixelSRGB8 $ PixelRGB8 (arr ! (baseIdx + 0))
(arr ! (baseIdx + 1))
(arr ! (baseIdx + 2))
where baseIdx = pixelBaseIndex image x y
readPixel image@(MutableImage { mutableImageData = arr }) x y = do
rv <- arr .!!!. baseIdx
gv <- arr .!!!. (baseIdx + 1)
bv <- arr .!!!. (baseIdx + 2)
return $ PixelSRGB8 $ PixelRGB8 rv gv bv
where baseIdx = mutablePixelBaseIndex image x y
writePixel image@(MutableImage { mutableImageData = arr }) x y (PixelSRGB8 (PixelRGB8 rv gv bv)) = do
let baseIdx = mutablePixelBaseIndex image x y
(arr .<-. (baseIdx + 0)) rv
(arr .<-. (baseIdx + 1)) gv
(arr .<-. (baseIdx + 2)) bv
unsafePixelAt v idx =
PixelSRGB8 $ PixelRGB8 (V.unsafeIndex v idx) (V.unsafeIndex v $ idx + 1) (V.unsafeIndex v $ idx + 2)
unsafeReadPixel vec idx =
mkPixelSRGB8 `liftM` M.unsafeRead vec idx
`ap` M.unsafeRead vec (idx + 1)
`ap` M.unsafeRead vec (idx + 2)
unsafeWritePixel v idx (PixelSRGB8 (PixelRGB8 r g b)) = do
M.unsafeWrite v idx r
M.unsafeWrite v (idx + 1) g
M.unsafeWrite v (idx + 2) b
-- |converts from the linear RGB space to the non-linear Standard-RGB (sRGB) color space
-- approxumates a gamma of about 1/2.2
-- see: http://hackage.haskell.org/package/colour-2.3.3/docs/src/Data-Colour-SRGB.html#sRGB24
instance ColorSpaceConvertible PixelRGB8 PixelSRGB8 where
{-# INLINE convertPixel #-}
convertPixel (PixelRGB8 r g b) = PixelSRGB8 . C.uncurryRGB PixelRGB8 . SRGB.toSRGB24 . asDouble $ linRGB24 r g b
where
asDouble :: C.Colour Double -> C.Colour Double
asDouble = id
instance ColorSpaceConvertible PixelSRGB8 PixelRGB8 where
{-# INLINE convertPixel #-}
-- sRGB24 transfers the sRGB color coordinates to the linear Colour type
-- toRGB simply exposes the true values of the color-channels
convertPixel (PixelSRGB8 (PixelRGB8 r g b)) = C.uncurryRGB PixelRGB8 . toLinearBounded . asDouble $ SRGB.sRGB24 r g b
where
asDouble :: C.Colour Double -> C.Colour Double
asDouble = id
-- |a description how to convert a `Colour` type to the concrete pixel
class (Pixel p, Floating a) => ColourPixel a p where
colourToPixel :: C.Colour a -> p
instance (Floating a, RealFrac a) => ColourPixel a PixelSRGB8 where
colourToPixel = PixelSRGB8 . C.uncurryRGB PixelRGB8 . SRGB.toSRGB24
instance (Floating a, RealFrac a) => ColourPixel a PixelRGB8 where
colourToPixel = C.uncurryRGB PixelRGB8 . toLinearBounded
instance (Floating a, RealFrac a) => ColourPixel a PixelRGBA8 where
colourToPixel = C.uncurryRGB (\r g b -> PixelRGBA8 r g b 1) . toLinearBounded
instance (Floating a, RealFrac a) => ColourPixel a Pixel8 where
colourToPixel c = computeLuma (colourToPixel c :: PixelRGB8)
-- just helpers
castToSRGB8 :: Image PixelRGB8 -> Image PixelSRGB8
castToSRGB8 = pixelMap PixelSRGB8
castToRGB8 :: Image PixelSRGB8 -> Image PixelRGB8
castToRGB8 = pixelMap (\(PixelSRGB8 pixelRGB) -> pixelRGB)
{-# INLINE (!!!) #-}
(!!!) :: (Storable e) => V.Vector e -> Int -> e
(!!!) = V.unsafeIndex
{-# INLINE (.!!!.) #-}
(.!!!.) :: (PrimMonad m, Storable a) => M.STVector (PrimState m) a -> Int -> m a
(.!!!.) = M.read -- unsafeRead
{-# INLINE (.<-.) #-}
(.<-.) :: (PrimMonad m, Storable a) => M.STVector (PrimState m) a -> Int -> a -> m ()
(.<-.) = M.write -- unsafeWrite
{-# INLINE mkPixelSRGB8 #-}
mkPixelSRGB8 :: Pixel8 -> Pixel8 -> Pixel8 -> PixelSRGB8
mkPixelSRGB8 r g b = PixelSRGB8 $ PixelRGB8 r g b
-- |lifts linear color coordiantes `r` `g` `b` into the Colour type (which is linear by definition)
-- the values are normalized with their maxBound
-- no transfer function is applied
{-# INLINE linRGB24 #-}
linRGB24 :: (Ord b, Floating b, Integral a, Bounded a) =>
a -> a -> a -> C.Colour b
linRGB24 r g b = C.uncurryRGB Linear.rgb $ fmap normalize $ Linear.RGB r g b
where
normalize x = fromIntegral x / m
m = fromIntegral $ maxBound `asTypeOf` r
{- Results are clamped and quantized, without transfer -}
-- |Return the approximate sRGB colour components in the range
-- [0..'maxBound'].
-- Out of range values are clamped.
toLinearBounded :: (RealFrac b, Floating b, Integral a, Bounded a) =>
C.Colour b -> Linear.RGB a
toLinearBounded c = fmap quant (Linear.toRGB c)
where
quant x' = quantize (m*x')
m = fromIntegral $ maxBound `asTypeOf` (quant undefined)
-- |'round's and then clamps @x@ between 0 and 'maxBound'.
-- from: http://hackage.haskell.org/package/colour-2.3.3/src/Data/Colour/Internal.hs
quantize :: (RealFrac a1, Integral a, Bounded a) => a1 -> a
quantize x | x <= fromIntegral l = l
| fromIntegral h <= x = h
| otherwise = round x
where
l = minBound
h = maxBound
|
MaxDaten/yage-contrib
|
src/JuicySRGB.hs
|
mit
| 6,435
| 0
| 12
| 1,558
| 1,783
| 950
| 833
| 110
| 1
|
module Render where
|
mfpi/q-inqu
|
tools/asp/Render.hs
|
mit
| 21
| 0
| 2
| 4
| 4
| 3
| 1
| 1
| 0
|
import Database.HDBC
import Database.HDBC.PostgreSQL
import Control.Monad
import Text.CSV
import DBGrader.Questions
import DBGrader.Types
import DBGrader.Config
import DBGrader.Students
main :: IO ()
main = do
-- Print header
printLine "name" -- Name of student.
"question" -- Question name (E.g. q1, q1, q3...).
"db" -- Database queried .
"matches" -- Did the students answer match the given solution.
"notes" -- Notes from the solution checker.
"flags" -- Where to input flags for grading.
"query" -- If this question involved defining a view, the view
-- definition will be put here.
"errors" -- Errors received while trying to find solution, usually
-- this means the database or view did not exist.
-- Print student solutions for every student.
mapM_ getStudentSolutions students
getStudentSolutions :: Student -> IO ()
getStudentSolutions s = catchSql (getStudentSolutions' s) $ catcherror (name s)
where
catcherror _ _ = putStrLn "\n" -- If we catch an error, just skip
getStudentSolutions' :: Student -> IO ()
getStudentSolutions' s = do
conn <- connectPostgreSQL $ connectInfoFromStudent s
mapM_ (getStudentGrade conn s) questions
printLine "" "" "" "" "" "" "" "" -- Add blank line between students
disconnect conn
-- Add a line to CSV output.
printLine :: String -> String -> String -> String -> String -> String -> String -> String -> IO ()
printLine name view db matches notes flags query errors =
putStrLn $ printCSV [[name, view, db, matches, notes, flags, query, errors]]
getStudentGrade :: Connection -> Student -> Question -> IO ()
getStudentGrade conn s q = case q of
-- Depending on the type of question extract information from database
-- and print results. To understand question types see Types.hs
ViewQuestion{} -> do
-- Prepare query to get view definition.
getViewDef <- prepare conn $ "select pg_get_viewdef('" ++ view q ++ "',true);"
-- Run query to get view definition
catchSql (executeSQL getViewDef) (catcherror s q conn "")
-- Fetch rows to get view definition
viewDef <- fetchAllRows getViewDef
-- If viewDef is null then an error occurred.
let def = if null viewDef
then "Error"
else fromSql $ (head . head) viewDef
-- Prepare query to check if answer matches solution
stmt <- prepare conn $ differenceBetweenQuerys (view q) (solution q)
-- Run query to check solution
(n,error) <- catchSql (executeSQL stmt) (catcherror s q conn def)
-- Fetch rows from query
results <- fetchAllRows stmt
-- Solution was correct if no rows were returned.
let correct = null results
if n==errorCode || def == "Error"
then printLine (name s) (nm q) (dbname s) "Error" "" "" "" error
else printLine (name s)
(view q)
(dbname s)
(show (correct && def/="Error" ))
""
""
def
"None"
TableQuestion{} -> do
-- Query to count number of rows in table
let qur = "SELECT COUNT(*) FROM " ++ schema q ++ "." ++ table q ++ ";"
-- Prepare query
stmt <- prepare conn qur
-- Run query
(n,error) <- catchSql (executeSQL stmt) (catcherror s q conn "")
-- Get rows from query, this should be a count of rows
results <- fetchAllRows stmt
if n == errorCode
then printLine (name s) (nm q) (dbname s) "Error" "" "" "" error
else let correct = if null results
then "Error"
else show $ fromSql ((head . head) results) >= rows q
in printLine (name s)
(nm q)
(dbname s)
correct
("Rows returned:" ++ fromSql ((head . head) results))
""
qur
""
QueryQuestion{} -> do
-- Prepare query
stmt <- prepare conn $ query q
-- Run query
(n,error) <- catchSql (executeSQL stmt) (catcherror s q conn "")
-- Get rows from query
results <- fetchAllRows stmt
if n == errorCode
then printLine (name s) (nm q) (dbname s) "Error" "" "" "" error
else let len = show $ length results
correct = show $ not $ null results
in printLine (name s)
(nm q)
(dbname s)
correct
("Rows returned:" ++ len)
""
(query q)
""
where
executeSQL sql = execute sql [] >>= \i -> return (i, "")
errorCode = 37707 -- This is an arbitrary int to denote an error
catcherror st qe con ans ex = do
rollback con -- Rollback connection
return (errorCode, show (seErrorMsg ex)) -- Return error code
-- Takes two sql queries and returns a new sql query that will return zero rows
-- if queries are equal. If the queries return different columns then running the
-- produced query will cause a error at runtime.
differenceBetweenQuerys :: SQLQuery -> SQLQuery -> SQLQuery
differenceBetweenQuerys query1 query2 = "(SELECT * FROM "
++ init query1 -- Remove ; from sql query
++ " EXCEPT SELECT * FROM ("
++ init query2
++ ") AS a) "
++ "UNION ALL"
++ " (SELECT * FROM ("
++ init query2
++ ") AS b EXCEPT SELECT * FROM "
++ init query1
++ ");"
|
GarrisonJ/DBGrader
|
GetStudentAnswers.hs
|
mit
| 6,523
| 0
| 22
| 2,747
| 1,320
| 664
| 656
| 105
| 8
|
{-# LANGUAGE OverloadedStrings #-}
module Network.Wai.Middleware.OAuth2 (login, callback, basicCallback, getJSON, OAuth2, appendQueryParam, QueryParams, CheckState, OAuth2Result, AccessToken) where
import Network.Wai
import Network.OAuth.OAuth2
import qualified Data.ByteString.Char8 as BSC8
import qualified Data.ByteString.Lazy as L
import Data.ByteString
import Control.Error
import Control.Monad.IO.Class (MonadIO(liftIO))
import Data.Monoid (mempty)
import Network.HTTP.Types (status200, status302, status400, status404)
import Data.Aeson.Types
import Network.HTTP.Conduit (Manager, newManager, conduitManagerSettings)
import Data.Either
--instance (MonadIO m) => MonadIO (EitherT m) where
-- liftIO = lift . liftIO
type CheckState = BSC8.ByteString -> Bool
redirect302 :: URI -> Response
redirect302 uri = responseLBS status302 [("Location", uri)] mempty
login :: OAuth2 -> QueryParams -> Response
login config param = redirect302 $ authorizationUrl config `appendQueryParam` param
basicCallback :: Manager -> OAuth2 -> CheckState -> (L.ByteString -> Application) -> ((OAuth2Result AccessToken) -> Application) -> Application
basicCallback mgr config authcheckstate failapp successapp req sendResponse = do
accessToken <- liftIO eAccessToken
either runFailApp runSuccessApp accessToken
where
eAccessToken :: IO (Either ByteString (OAuth2Result AccessToken))
eAccessToken = runEitherT (callback mgr config authcheckstate req)
runFailApp :: ByteString -> IO ResponseReceived
runFailApp = \x -> failapp (L.fromStrict x) req sendResponse
runSuccessApp :: OAuth2Result AccessToken -> IO ResponseReceived
runSuccessApp = \x -> successapp (x) req sendResponse
callback :: Manager -> OAuth2 -> CheckState -> Request -> EitherT ByteString IO (OAuth2Result AccessToken)
callback mgr config authcheckstate req = do
hoistEither checkState -- SECURITY -- check state NONCE to check callback request is valid
getAccessToken -- AccessToken can now be used to request user INFO
where
lookupQuery name = lookup name (queryString req)
getState :: Either ByteString ByteString
getState = note ("OhAuth sessionCallback getState" :: ByteString) $ do
mstate <- lookupQuery "state"
state <- mstate
return state
getCode :: Either ByteString ByteString
getCode = note "OhAuth sessionCallback getCode" $ do
mcode <- lookupQuery "code"
code <- mcode
return code
checkState :: Either ByteString ByteString
checkState = do
state <- getState
bool (Left "OhAuth sessionCallback checkState") (Right state) (authcheckstate state)
getAccessToken :: EitherT ByteString IO (OAuth2Result AccessToken)
getAccessToken = do
code <- hoistEither getCode
liftIO $ fetchAccessToken mgr config code
getJSON :: FromJSON a => Manager -> AccessToken -> URI -> IO (OAuth2Result a)
getJSON = authGetJSON
|
NerdGGuy/wai-middleware-oauth2
|
src/Network/Wai/Middleware/OAuth2.hs
|
mit
| 3,033
| 0
| 13
| 619
| 751
| 399
| 352
| 54
| 1
|
module Language.PiCalc.Analysis.PetriNet(module PetriNet) where
import Data.List(partition)
import Data.Map(Map)
import qualified Data.Map as Map
import Data.Set(Set)
import qualified Data.Set as Set
-- TODO: add places :: Set pl field for efficiency
newtype PN pl = PN {
-- rules :: [(Map pl TokenNum, Map pl TokenNum)]
rules :: [PNRule pl]
-- ^ each transition @([(pi,ni)..],[(pj,nj)..])@ takes ni token from place @pi@ and puts @nj@ tokens to place @pj@
-- each place must appear at most once in the two lists.
-- I could have chosen Map to represent these but I did not want to over-complicate things.
} deriving (Show, Eq, Ord)
type PNRule pl = ([(pl,TokenNum)] , [(pl,TokenNum)])
type Marking pl = Map pl TokenLim
type TokenNum = Int -- ^ Should be always positive!
data TokenLim = Tok TokenNum | OmegaTok
deriving (Eq, Ord, Show)
places :: Ord pl => PN pl -> Set pl
places pn = foldr Set.insert Set.empty $ concatMap extract $ rules pn
where extract (pre,post) = map fst $ pre ++ post
places' :: Ord a => PN a -> Set a
places' pn = Set.unions $ map extract $ rules pn
where extract (pre,post) = Set.fromList $ map fst $ pre ++ post
tokensIn :: Ord pl => pl -> Marking pl -> TokenLim
tokensIn pl m = Map.findWithDefault (Tok 0) pl m
addTokensTo :: Ord pl => (pl, TokenNum) -> Marking pl -> Marking pl
addTokensTo (pl, n) m = Map.insert pl (tokAdd n (tokensIn pl m)) m
remTokensFrom :: Ord pl => (pl, TokenNum) -> Marking pl -> Marking pl
remTokensFrom (pl, n) m = Map.insert pl (tokRem n (tokensIn pl m)) m
-- | Lift a unary operation on "TokenNum" to "TokenLim", with the invariant @tokLift op OmegaTok = OmegaTok@.
tokLift :: (TokenNum -> TokenNum) -> TokenLim -> TokenLim
tokLift _ OmegaTok = OmegaTok
tokLift op (Tok n) = Tok $ op n
tokAdd :: TokenNum -> TokenLim -> TokenLim
tokAdd n = tokLift (+ n)
tokRem :: TokenNum -> TokenLim -> TokenLim
tokRem n = tokLift (subtract n)
addRule :: [(pl, TokenNum)] -> [(pl, TokenNum)] -> PN pl -> PN pl
addRule pre post pn = pn{ rules = (pre, post):rules pn }
-- where
-- toMap = Map.fromListWith (+)
-- tag = Map.map (Tok . abs)
emptyPN :: PN pl
emptyPN = PN{ rules = [] }
emptyMarking :: Marking pl
emptyMarking = Map.empty
partitionEnabled :: Ord pl => PN pl -> Marking pl -> ([PNRule pl], [PNRule pl])
partitionEnabled pn m = partition (isEnabled m) $ rules pn
enabledRules :: Ord pl => PN pl -> Marking pl -> [PNRule pl]
enabledRules pn m = filter (isEnabled m) $ rules pn
isEnabled :: Ord pl => Marking pl -> PNRule pl -> Bool
isEnabled m (pre, _) = validMarking $ remTokens pre m
-- all enoughTok pre
enoughTok :: Ord pl => (pl, TokenNum) -> Marking pl -> Bool
enoughTok (pl, n) m = tokensIn pl m >= (Tok n)
succMarkings :: Ord pl => PN pl -> Marking pl -> [Marking pl]
succMarkings pn m = map fire $ enabledRules pn m
where
fire (pre, post) = addTokens post $ remTokens pre m
remTokens :: Ord pl => [(pl, TokenNum)] -> Marking pl -> Marking pl
remTokens pre m = foldr remTokensFrom m pre
addTokens :: Ord pl => [(pl, TokenNum)] -> Marking pl -> Marking pl
addTokens pre m = foldr addTokensTo m pre
validMarking :: Marking pl -> Bool
validMarking m = all (>= Tok 0) $ Map.elems m
-- limDiff OmegaTok OmegaTok = Tok 0
-- limDiff OmegaTok _ = OmegaTok
-- limDiff (Tok n) (Tok m) = Tok $ n-m
-- | Partial order on markings:
-- * @Nothing@ means incomparable
-- * @Just c@ means comparison results in @c@ (@EQ@, @LT@ or @GT@)
compareMarkings :: Ord pl => Marking pl -> Marking pl -> Maybe Ordering
compareMarkings m1 m2 = foldr join (Just EQ) $ map cmp $ Map.toList m1
where
cmp (pl, n) = compare n (tokensIn pl m2)
join _ Nothing = Nothing
join EQ x = x
join LT (Just GT) = Nothing
join LT _ = Just LT
join GT (Just LT) = Nothing
join GT _ = Just GT
{--
TODO: make karpMiller parametric on a function
PN pl -> Marking pl -> PN pl
that can update the transitions at each step wrt the new marking.
When the transitions are known beforehand one can just supply
(\_ _ -> p) but you can now also support generating them on-the-fly
--}
karpMiller :: Ord pl => PN pl -> Marking pl -> [Marking pl]
karpMiller pn m = explore [m]
where
explore ms@(m:_) = m : concat [ explore (m' : ms) | s <- succMarkings pn m, m' <- accellerate s ms ]
accellerate m [] = [m] -- it is a new state
accellerate m (m':ms) =
case compareMarkings m m' of
Just GT -> [widenMarking m m'] -- continue with widened state
Just EQ -> [] -- already seen: nothing to explore
_ -> accellerate m ms -- look for comparable states in rest of path
widenMarking :: Ord pl => Marking pl -> Marking pl -> Marking pl
widenMarking m1 m2 = Map.unionWith widen m1 m2
where
widen x y
| x > y = OmegaTok
| otherwise = x
isUnbounded :: Ord pl => PN pl -> Marking pl -> pl -> Bool
isUnbounded pn m pl = any (\x -> tokensIn pl x == OmegaTok) $ karpMiller pn m
isCoverable :: Ord pl => PN pl -> Marking pl -> Marking pl -> Bool
isCoverable pn m0 m = any (covers m) $ karpMiller pn m0
where covers m m' =
case compareMarkings m m' of
Just EQ -> True
Just LT -> True
_ -> False
showMarking m = concat ["[" ++ show p ++ " " ++ showTok n ++ "] " | (p,n) <- Map.toList m]
where showTok OmegaTok = "ω"
showTok (Tok n) = show n
|
bordaigorl/jamesbound
|
src/Language/PiCalc/Analysis/PetriNet.hs
|
gpl-2.0
| 5,505
| 0
| 12
| 1,387
| 1,940
| 987
| 953
| 91
| 6
|
data MonF a = MEmpty | MAppend a a
|
hmemcpy/milewski-ctfp-pdf
|
src/content/3.8/code/haskell/snippet02.hs
|
gpl-3.0
| 34
| 0
| 6
| 8
| 16
| 9
| 7
| 1
| 0
|
{-|
Copyright : (c) Nathan Bloomfield, 2017
License : GPL-3
Maintainer : nbloomf@gmail.com
Stability : experimental
This module provides a filter for Hakyll which expands WordPress-style shortcodes. To use it, include the line @>>= applyShortcodes allServices@ in your compiler.
-}
module Hakyll.Shortcode (
ShortcodeService(..),
expandShortcodes,
applyShortcodes,
allServices
) where
import Hakyll.Shortcode.Service.GeoGebra
import Hakyll.Shortcode.Service.Gravatar
import Hakyll.Shortcode.Service.YouTube
import Hakyll.Shortcode.Service.Example
-- | A simple sum type representing the available shortcodes.
data ShortcodeService
= GeoGebra
| Gravatar
| YouTube
| Example
deriving Eq
-- Expand shortcodes of the provided type.
expandShortcodesFor :: ShortcodeService -> String -> String
expandShortcodesFor x = case x of
GeoGebra -> expandGeoGebraShortcodes
Gravatar -> expandGravatarShortcodes
YouTube -> expandYouTubeShortcodes
Example -> expandExampleShortcodes
-- | Expand shortcodes of each of the provided types.
expandShortcodes :: [ShortcodeService] -> String -> String
expandShortcodes = foldr1 (.) . map expandShortcodesFor
-- | Monadic version of 'expandShortcodes', for use with Hakyll.
applyShortcodes :: (Monad m, Functor f)
=> [ShortcodeService] -> f String -> m (f String)
applyShortcodes svc text =
return $ (fmap $ expandShortcodes svc) text
-- | A list of all the available shortcodes (for convenience).
allServices :: [ShortcodeService]
allServices =
[ GeoGebra
, Gravatar
, YouTube
]
|
nbloomf/hakyll-shortcode
|
src/Hakyll/Shortcode.hs
|
gpl-3.0
| 1,564
| 0
| 10
| 252
| 251
| 146
| 105
| 32
| 4
|
{-# LANGUAGE RankNTypes #-}
-- |
-- Module : Aura.Utils
-- Copyright : (c) Colin Woodbury, 2012 - 2020
-- License : GPL3
-- Maintainer: Colin Woodbury <colin@fosskers.ca>
--
-- Utility functions specific to Aura.
module Aura.Utils
( -- * Strings
Pattern(..)
, searchLines
-- * Network
, urlContents
-- * Semigroupoids
, foldMap1
, fold1
-- * Errors
, hush
, note
-- * Compactable
, fmapEither
, traverseEither
-- * These
, These(..)
, these
-- * Directory
, edit
-- * Lens
, Traversal'
-- * Misc.
, maybe'
, groupsOf
, nes
, partNonEmpty
) where
import Network.HTTP.Client
import Network.HTTP.Types.Status (statusCode)
import RIO
import qualified RIO.ByteString.Lazy as BL
import qualified RIO.List as L
import qualified RIO.NonEmpty as NEL
import qualified RIO.Set as S
import qualified RIO.Text as T
import System.Process.Typed (proc, runProcess)
---
---------
-- STRING
---------
-- | For regex-like find-and-replace in some `Text`.
data Pattern = Pattern { _pattern :: !Text, _target :: !Text }
-- | Find lines which contain some given `Text`.
searchLines :: Text -> [Text] -> [Text]
searchLines pat = filter (T.isInfixOf pat)
----------
-- NETWORK
----------
-- | Assumes the given URL is correctly formatted.
urlContents :: Manager -> String -> IO (Maybe ByteString)
urlContents m url = f <$> httpLbs (parseRequest_ url) m
where
f :: Response BL.ByteString -> Maybe ByteString
f res | statusCode (responseStatus res) == 200 = Just . BL.toStrict $ responseBody res
| otherwise = Nothing
--------------
-- DIRECTORIES
--------------
-- | Edit some file in-place with the user's specified editor.
edit :: FilePath -> FilePath -> IO ()
edit editor p = void . runProcess $ proc editor [p]
-------
-- MISC
-------
-- | `maybe` with the function at the end.
maybe' :: b -> Maybe a -> (a -> b) -> b
maybe' zero m f = maybe zero f m
-- | Borrowed from Compactable.
fmapEither :: (a -> Either b c) -> [a] -> ([b], [c])
fmapEither f = foldl' (deal f) ([],[])
where
deal :: (a -> Either b c) -> ([b], [c]) -> a -> ([b], [c])
deal g ~(bs, cs) a = case g a of
Left b -> (b:bs, cs)
Right c -> (bs, c:cs)
-- | Borrowed from Compactable.
traverseEither :: Applicative f => (a -> f (Either b c)) -> [a] -> f ([b], [c])
traverseEither f = fmap partitionEithers . traverse f
-- | Break a list into groups of @n@ elements. The last item in the result is
-- not guaranteed to have the same length as the others.
groupsOf :: Int -> [a] -> [[a]]
groupsOf n as
| n <= 0 = []
| otherwise = go as
where
go [] = []
go bs = xs : go rest
where
(xs, rest) = L.splitAt n bs
nes :: Set a -> Maybe (NonEmpty a)
nes = NEL.nonEmpty . S.toList
hush :: Either a b -> Maybe b
hush = either (const Nothing) Just
note :: a -> Maybe b -> Either a b
note a = maybe (Left a) Right
-- | Borrowed from semigroupoids.
foldMap1 :: Semigroup m => (a -> m) -> NonEmpty a -> m
foldMap1 f (a :| []) = f a
foldMap1 f (a :| b : bs) = f a <> foldMap1 f (b :| bs)
-- | Borrowed from semigroupoids.
fold1 :: Semigroup m => NonEmpty m -> m
fold1 = foldMap1 id
-- | Partition a `NonEmpty` based on some function.
partNonEmpty :: (a -> These b c) -> NonEmpty a -> These (NonEmpty b) (NonEmpty c)
partNonEmpty f = foldMap1 (bimap pure pure . f)
--------------------------------------------------------------------------------
-- Lens
-- | Simple Traversals compatible with both lens and microlens.
type Traversal' s a = forall f. Applicative f => (a -> f a) -> s -> f s
--------------------------------------------------------------------------------
-- These
data These a b = This a | That b | These a b
instance (Semigroup a, Semigroup b) => Semigroup (These a b) where
This x <> This y = This (x <> y)
This x <> These z y = These (x <> z) y
This x <> That y = These x y
That x <> That y = That (x <> y)
That x <> This y = These y x
That x <> These y z = These y (x <> z)
These w x <> This y = These (w <> y) x
These w x <> That y = These w (x <> y)
These w x <> These y z = These (w <> y) (x <> z)
instance Bifunctor These where
bimap f _ (This x) = This (f x)
bimap _ g (That y) = That (g y)
bimap f g (These x y) = These (f x) (g y)
these :: (a -> t) -> (b -> t) -> (a -> b -> t) -> These a b -> t
these f _ _ (This a) = f a
these _ g _ (That b) = g b
these _ _ h (These a b) = h a b
|
aurapm/aura
|
aura/lib/Aura/Utils.hs
|
gpl-3.0
| 4,489
| 0
| 13
| 1,106
| 1,698
| 895
| 803
| 93
| 2
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.ServiceManagement.Services.Enable
-- 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)
--
-- Enable a managed service for a project with default setting. Operation
-- google.rpc.Status errors may contain a google.rpc.PreconditionFailure
-- error detail.
--
-- /See:/ <https://cloud.google.com/service-management/ Google Service Management API Reference> for @servicemanagement.services.enable@.
module Network.Google.Resource.ServiceManagement.Services.Enable
(
-- * REST Resource
ServicesEnableResource
-- * Creating a Request
, servicesEnable
, ServicesEnable
-- * Request Lenses
, seXgafv
, seUploadProtocol
, sePp
, seAccessToken
, seUploadType
, sePayload
, seBearerToken
, seServiceName
, seCallback
) where
import Network.Google.Prelude
import Network.Google.ServiceManagement.Types
-- | A resource alias for @servicemanagement.services.enable@ method which the
-- 'ServicesEnable' request conforms to.
type ServicesEnableResource =
"v1" :>
"services" :>
CaptureMode "serviceName" "enable" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] EnableServiceRequest :>
Post '[JSON] Operation
-- | Enable a managed service for a project with default setting. Operation
-- google.rpc.Status errors may contain a google.rpc.PreconditionFailure
-- error detail.
--
-- /See:/ 'servicesEnable' smart constructor.
data ServicesEnable = ServicesEnable'
{ _seXgafv :: !(Maybe Xgafv)
, _seUploadProtocol :: !(Maybe Text)
, _sePp :: !Bool
, _seAccessToken :: !(Maybe Text)
, _seUploadType :: !(Maybe Text)
, _sePayload :: !EnableServiceRequest
, _seBearerToken :: !(Maybe Text)
, _seServiceName :: !Text
, _seCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'ServicesEnable' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'seXgafv'
--
-- * 'seUploadProtocol'
--
-- * 'sePp'
--
-- * 'seAccessToken'
--
-- * 'seUploadType'
--
-- * 'sePayload'
--
-- * 'seBearerToken'
--
-- * 'seServiceName'
--
-- * 'seCallback'
servicesEnable
:: EnableServiceRequest -- ^ 'sePayload'
-> Text -- ^ 'seServiceName'
-> ServicesEnable
servicesEnable pSePayload_ pSeServiceName_ =
ServicesEnable'
{ _seXgafv = Nothing
, _seUploadProtocol = Nothing
, _sePp = True
, _seAccessToken = Nothing
, _seUploadType = Nothing
, _sePayload = pSePayload_
, _seBearerToken = Nothing
, _seServiceName = pSeServiceName_
, _seCallback = Nothing
}
-- | V1 error format.
seXgafv :: Lens' ServicesEnable (Maybe Xgafv)
seXgafv = lens _seXgafv (\ s a -> s{_seXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
seUploadProtocol :: Lens' ServicesEnable (Maybe Text)
seUploadProtocol
= lens _seUploadProtocol
(\ s a -> s{_seUploadProtocol = a})
-- | Pretty-print response.
sePp :: Lens' ServicesEnable Bool
sePp = lens _sePp (\ s a -> s{_sePp = a})
-- | OAuth access token.
seAccessToken :: Lens' ServicesEnable (Maybe Text)
seAccessToken
= lens _seAccessToken
(\ s a -> s{_seAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
seUploadType :: Lens' ServicesEnable (Maybe Text)
seUploadType
= lens _seUploadType (\ s a -> s{_seUploadType = a})
-- | Multipart request metadata.
sePayload :: Lens' ServicesEnable EnableServiceRequest
sePayload
= lens _sePayload (\ s a -> s{_sePayload = a})
-- | OAuth bearer token.
seBearerToken :: Lens' ServicesEnable (Maybe Text)
seBearerToken
= lens _seBearerToken
(\ s a -> s{_seBearerToken = a})
-- | Name of the service to enable. Specifying an unknown service name will
-- cause the request to fail.
seServiceName :: Lens' ServicesEnable Text
seServiceName
= lens _seServiceName
(\ s a -> s{_seServiceName = a})
-- | JSONP
seCallback :: Lens' ServicesEnable (Maybe Text)
seCallback
= lens _seCallback (\ s a -> s{_seCallback = a})
instance GoogleRequest ServicesEnable where
type Rs ServicesEnable = Operation
type Scopes ServicesEnable =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/service.management"]
requestClient ServicesEnable'{..}
= go _seServiceName _seXgafv _seUploadProtocol
(Just _sePp)
_seAccessToken
_seUploadType
_seBearerToken
_seCallback
(Just AltJSON)
_sePayload
serviceManagementService
where go
= buildClient (Proxy :: Proxy ServicesEnableResource)
mempty
|
rueshyna/gogol
|
gogol-servicemanagement/gen/Network/Google/Resource/ServiceManagement/Services/Enable.hs
|
mpl-2.0
| 5,934
| 0
| 19
| 1,473
| 942
| 548
| 394
| 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.CloudPrivateCatalogProducer.Catalogs.Products.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 a specific Product resource.
--
-- /See:/ <https://cloud.google.com/private-catalog/ Cloud Private Catalog Producer API Reference> for @cloudprivatecatalogproducer.catalogs.products.patch@.
module Network.Google.Resource.CloudPrivateCatalogProducer.Catalogs.Products.Patch
(
-- * REST Resource
CatalogsProductsPatchResource
-- * Creating a Request
, catalogsProductsPatch
, CatalogsProductsPatch
-- * Request Lenses
, cppXgafv
, cppUploadProtocol
, cppUpdateMask
, cppAccessToken
, cppUploadType
, cppPayload
, cppName
, cppCallback
) where
import Network.Google.CloudPrivateCatalogProducer.Types
import Network.Google.Prelude
-- | A resource alias for @cloudprivatecatalogproducer.catalogs.products.patch@ method which the
-- 'CatalogsProductsPatch' request conforms to.
type CatalogsProductsPatchResource =
"v1beta1" :>
Capture "name" 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]
GoogleCloudPrivatecatalogproducerV1beta1Product
:>
Patch '[JSON]
GoogleCloudPrivatecatalogproducerV1beta1Product
-- | Updates a specific Product resource.
--
-- /See:/ 'catalogsProductsPatch' smart constructor.
data CatalogsProductsPatch =
CatalogsProductsPatch'
{ _cppXgafv :: !(Maybe Xgafv)
, _cppUploadProtocol :: !(Maybe Text)
, _cppUpdateMask :: !(Maybe GFieldMask)
, _cppAccessToken :: !(Maybe Text)
, _cppUploadType :: !(Maybe Text)
, _cppPayload :: !GoogleCloudPrivatecatalogproducerV1beta1Product
, _cppName :: !Text
, _cppCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CatalogsProductsPatch' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cppXgafv'
--
-- * 'cppUploadProtocol'
--
-- * 'cppUpdateMask'
--
-- * 'cppAccessToken'
--
-- * 'cppUploadType'
--
-- * 'cppPayload'
--
-- * 'cppName'
--
-- * 'cppCallback'
catalogsProductsPatch
:: GoogleCloudPrivatecatalogproducerV1beta1Product -- ^ 'cppPayload'
-> Text -- ^ 'cppName'
-> CatalogsProductsPatch
catalogsProductsPatch pCppPayload_ pCppName_ =
CatalogsProductsPatch'
{ _cppXgafv = Nothing
, _cppUploadProtocol = Nothing
, _cppUpdateMask = Nothing
, _cppAccessToken = Nothing
, _cppUploadType = Nothing
, _cppPayload = pCppPayload_
, _cppName = pCppName_
, _cppCallback = Nothing
}
-- | V1 error format.
cppXgafv :: Lens' CatalogsProductsPatch (Maybe Xgafv)
cppXgafv = lens _cppXgafv (\ s a -> s{_cppXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
cppUploadProtocol :: Lens' CatalogsProductsPatch (Maybe Text)
cppUploadProtocol
= lens _cppUploadProtocol
(\ s a -> s{_cppUploadProtocol = a})
-- | Field mask that controls which fields of the product should be updated.
cppUpdateMask :: Lens' CatalogsProductsPatch (Maybe GFieldMask)
cppUpdateMask
= lens _cppUpdateMask
(\ s a -> s{_cppUpdateMask = a})
-- | OAuth access token.
cppAccessToken :: Lens' CatalogsProductsPatch (Maybe Text)
cppAccessToken
= lens _cppAccessToken
(\ s a -> s{_cppAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
cppUploadType :: Lens' CatalogsProductsPatch (Maybe Text)
cppUploadType
= lens _cppUploadType
(\ s a -> s{_cppUploadType = a})
-- | Multipart request metadata.
cppPayload :: Lens' CatalogsProductsPatch GoogleCloudPrivatecatalogproducerV1beta1Product
cppPayload
= lens _cppPayload (\ s a -> s{_cppPayload = a})
-- | Required. The resource name of the product in the format
-- \`catalogs\/{catalog_id}\/products\/a-z*[a-z0-9]\'. A unique identifier
-- for the product under a catalog, which cannot be changed after the
-- product is created. The final segment of the name must between 1 and 256
-- characters in length.
cppName :: Lens' CatalogsProductsPatch Text
cppName = lens _cppName (\ s a -> s{_cppName = a})
-- | JSONP
cppCallback :: Lens' CatalogsProductsPatch (Maybe Text)
cppCallback
= lens _cppCallback (\ s a -> s{_cppCallback = a})
instance GoogleRequest CatalogsProductsPatch where
type Rs CatalogsProductsPatch =
GoogleCloudPrivatecatalogproducerV1beta1Product
type Scopes CatalogsProductsPatch =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient CatalogsProductsPatch'{..}
= go _cppName _cppXgafv _cppUploadProtocol
_cppUpdateMask
_cppAccessToken
_cppUploadType
_cppCallback
(Just AltJSON)
_cppPayload
cloudPrivateCatalogProducerService
where go
= buildClient
(Proxy :: Proxy CatalogsProductsPatchResource)
mempty
|
brendanhay/gogol
|
gogol-cloudprivatecatalogproducer/gen/Network/Google/Resource/CloudPrivateCatalogProducer/Catalogs/Products/Patch.hs
|
mpl-2.0
| 6,077
| 0
| 17
| 1,389
| 859
| 501
| 358
| 127
| 1
|
{-# LANGUAGE OverloadedStrings #-}
import Data.Monoid ((<>))
import Data.Binary(encode, decode)
import Data.Binary.Get (runGet, getWord16be, getWord32le)
import Data.Binary.Put (runPut, putWord16be, putWord32le)
import Data.IP (fromHostAddress, fromHostAddress6)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Char8 as B8
import Conduit
import Data.Conduit.Network
import Control.Concurrent.Async (race_)
import Network.Socket (SockAddr(..))
initialize :: ConduitM ByteString ByteString IO (ByteString, Int)
initialize = do
Just _init <- await
yield "\x05\x00" -- no auth
Just (proto, more) <- (B.splitAt 4 <$>) <$> await
let typ = B.index proto 3
let (host, rest) =
case typ of
-- domain
3 -> let len = fromIntegral $ B.head more
in B.splitAt len (B.tail more)
-- IPv4
1 -> let (ip, rst) = B.splitAt 4 more
addr = fromHostAddress . runGet getWord32le . L.fromStrict $ ip
in (B8.pack . show $ addr, rst)
-- IPv6
4 -> let (ip, rst) = B.splitAt 16 more
addr = fromHostAddress6 . decode . L.fromStrict $ ip
in (B8.pack . show $ addr, rst)
let port = fromIntegral . runGet getWord16be . L.fromStrict $ B.take 2 rest
return (host, port)
main :: IO ()
main =
runTCPServer (serverSettings 8000 "*") $ \client -> do
(clientSource, (remoteHost, remotePort)) <-
appSource client $$+ initialize `fuseUpstream` appSink client
runTCPClient (clientSettings remotePort remoteHost) $ \remote -> do
let (typ, hostBs, port) =
case appSockAddr remote of
SockAddrInet portNum host ->
("\x01", runPut (putWord32le host), portNum)
SockAddrInet6 portNum _ host _ ->
("\x04", encode host, portNum)
let msg = "\x05\x00\x00" <> typ <> hostBs
<> runPut (putWord16be . fromInteger $ toInteger port)
-- answer the remote host & port
clientSource $$++ yield (L.toStrict msg) =$ appSink client
-- tunnel between client and remote
race_ (clientSource $$+- appSink remote)
(appSource remote $$ appSink client)
|
scturtle/fun.hs
|
mylifesocks.hs
|
unlicense
| 2,306
| 0
| 22
| 615
| 746
| 395
| 351
| 49
| 3
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.