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 FlexibleContexts #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
module Score.Render (
printScorePage, Orientation(..), RenderingOptions(..), renderingOptionsOrientation
) where
import Control.Lens hiding ((<|))
import Control.Monad.State.Strict
import qualified Data.Foldable as F
import Data.List.NonEmpty (NonEmpty((:|)), (<|))
import Score.Render.Music
import qualified Data.List.NonEmpty as NE
import qualified Data.Music.Lilypond as L hiding (F)
import Data.Ratio
import Data.Semigroup ((<>))
import Score.Render.RenderedNote
import Data.VectorSpace
import Score.Types
import Text.Pretty
import Data.String.QQ (s)
data RenderingOptions =
RenderingOptions {_renderingOptionsOrientation :: Orientation}
deriving (Eq,Show)
data Orientation = Portrait | Landscape deriving (Eq, Show)
makeLenses ''RenderingOptions
-- | State that needs to be managed while we render
-- * note modifications are stored here, they are picked up on one note
-- and apply to the next note
-- * bar count. used to apply a line break after every N
data RenderState =
RenderState {_renderStateNoteMods :: [NoteMod]
,_renderStateBarsPerLine :: Int
,_renderStateBarCount :: Int}
deriving (Eq, Show)
makeLenses ''RenderState
-- TODO:
-- * prettier fonts - http://lilypond.1069038.n5.nabble.com/Change-font-of-titles-composer-etc-td25870.html
-- * pretty note font lilyjazz http://lilypondblog.org/2016/01/arnold/#more-4291
-- * tweak note styles to look like this: http://drummingmad.com/what-are-unisons/
-- * staff height bigger
printScorePage :: RenderingOptions -> [Score] -> String
printScorePage ro scores =
engraverPrefix <>
renderOrientation (_renderingOptionsOrientation ro) <> "\n" <>
(runPrinter . pretty . slashBlock "book" $
slashBlock "paper" [L.Field "print-all-headers" (L.toLiteralValue "##t")] :
slashBlock "header" [L.Field "tagline" (L.toValue "")] :
fmap renderScore scores)
engraverPrefix :: String
engraverPrefix = [s|
startGraceMusic = {
\override NoteHead.font-size = -5
}
stopGraceMusic = {
\revert NoteHead.font-size
}
|]
renderOrientation :: Orientation -> String
renderOrientation o' = "#(set-default-paper-size \"a4" <> o <> "\")"
where o =
case o' of
Portrait -> "portrait"
Landscape -> "landscape"
renderScore :: Score -> L.Music
renderScore (Score details signature barsPerLine ps) =
let content =
flip evalState (RenderState [] barsPerLine 0) $
do
bs <- traverse renderPart ps
pure $! beginScore signature (F.toList bs)
styles = [L.Slash1 "layout", L.Sequential [
L.Field "indent" (L.toLiteralValue "#0")
,slashBlock "context" [
L.Slash1 "Score",
L.Slash1 "omit BarNumber",
L.Override "GraceSpacing.spacing-increment" (L.toValue (0::Double)),
-- This should be used to give us bar lines at the start, however we
-- only end up with a dot:
L.Override "SystemStartBar.collapse-height" (L.toValue (1::Int)),
L.Field "proportionalNotationDuration" (L.toLiteralValue "#(ly:make-moment 1/16)")
]
]]
header = slashBlock "header" (renderDetails details <> [L.Field "tagline" (L.toValue "")])
in slashBlock "score" (content ++ [header] ++ styles)
renderDetails :: Details -> [L.Music]
renderDetails ds = [
L.Field "title" $ L.toValue (ds ^. detailsTitle)
, L.Field "composer" $ L.toValue (ds ^. detailsComposer)
, L.Field "piece" $ L.toValue (ds ^. detailsGenre)
] <> maybe [] (pure . L.Field "opus" . L.toValue) (ds ^. detailsBand)
mark :: [L.Music]
mark =
[L.Set "Score.markFormatter" (L.toLiteralValue "#format-mark-box-numbers")
,L.Raw "\\mark \\default"]
renderPart :: Part -> State RenderState L.Music
renderPart p =
do let (anacrusis, rest) = case p ^. partBars of
a@(PartialBar _):xs -> ([a], xs)
xs -> ([], xs)
ana <- renderBars anacrusis
beams <- renderBars rest
let thisPart =
L.Sequential (ana <> mark <> F.toList beams)
r =
fmap (L.Sequential . F.toList . join) .
traverse renderBar .
F.toList
case p ^. partRepeat of
NoRepeat -> pure thisPart
Repeat ->
pure (L.Repeat False 2 thisPart Nothing)
Return firstTime secondTime ->
do
-- we want to pass the same mods into the first and second time, I think
ft <- restoring (r firstTime)
st <- r secondTime
pure (L.Repeat False 2 thisPart (Just (ft,st)))
renderBars :: [Bar] -> State RenderState [L.Music]
renderBars = fmap join . traverse renderBar
renderBar :: Bar -> State RenderState [L.Music]
renderBar (SignatureChange x) = pure (renderSignature x)
renderBar (PartialBar b) = renderAnacrusis b <&> (<> [L.Raw "|", L.Slash1 "noBreak"])
renderBar (Bar bs) =
do let Sum barLength = bs ^. _Duration . to Sum
-- render barLength / min-note-dur hidden spacing notes
_ys = (round $ barLength / (1 % 32)) :: Int
barsPerLine <- use renderStateBarsPerLine
v <- renderManyBeameds bs
-- let v' = L.Sequential (L.Slash1 "oneVoice" :v) `ggg` L.Sequential [L.Repeat True _ys (L.Sequential [L.Slash1 "hideNotes", L.Raw "c''32" ]) Nothing]
let v' = v
-- ggg a b = L.simultaneous b a
newCount <- renderStateBarCount <+= 1
return $
if newCount `mod` barsPerLine == 0
then v' <> [L.Raw "|", L.Slash1 "break"]
else v' <> [L.Raw "|", L.Slash1 "noBreak"]
renderAnacrusis :: Beamed -> State RenderState [L.Music]
renderAnacrusis a =
do let duration = sumOf _Duration a
bs <- renderManyBeameds (pure a)
pure [ L.Partial (round $ 1/duration) (L.Sequential $ F.toList bs) ]
beginScore :: Signature -> [L.Music] -> [L.Music]
beginScore signature i =
[L.New "Staff"
Nothing
(slashBlock
"with"
[override "StaffSymbol.line-count" (1 :: Int)
,override "Stem.direction" (-1 :: Int)
-- TODO play with beam thickness
-- ,L.Override "Beam.beam-thickness" (L.toValue (0.4 :: Double))
,override "StemTremolo.beam-thickness" (0.3 :: Double)
,override "StemTremolo.slope" (0.35 :: Double)
])
,
L.Sequential
([
L.Slash1 "hide Staff.Clef",
L.Clef L.Percussion,
L.Slash1 "tiny"] <>
spannerStyles <>
[beamPositions] <>
renderSignature signature <>
i)
]
where -- turn ottava brackets (octave switchers) into Unison marks
spannerStyles = [
override "DynamicLineSpanner.direction" (1::Int)
,override "Staff.OttavaBracket.thickness" (2::Int)
,overrideL "Staff.OttavaBracket.color" "#(x11-color 'OrangeRed)"
,overrideL "Staff.OttavaBracket.edge-height" "#'(1.2 . 1.2)"
,overrideL "Staff.OttavaBracket.bracket-flare" "#'(0 . 0)"
,override "Staff.OttavaBracket.dash-fraction" (1.0::Double)
,overrideL "Staff.OttavaBracket.shorten-pair" "#'(-0.4 . -0.4)"
,override "Staff.OttavaBracket.staff-padding" (3.0::Double)
,override "Staff.OttavaBracket.minimum-length" (1.0::Double)
]
setMomentAndStructure :: Integer -> [Integer] -> [L.Music]
setMomentAndStructure moment momentGroups =
let mm = "#(ly:make-moment 1/" <> show moment <> ")"
structure = unwords (map show momentGroups)
in literalSet "baseMoment" mm <>
literalSet "beatStructure" ("#'(" <> structure <> ")")
literalSet :: Applicative f => String -> String -> f L.Music
literalSet k v = pure (L.Set k (L.toLiteralValue v))
renderSignature :: Signature -> [L.Music]
renderSignature sig@(Signature n m) =
literalSet "strictBeatBeaming" "##t" <>
literalSet "subdivideBeams" "##t" <>
momentAndStructure <>
[L.Time n m]
where
momentAndStructure = case sig of
Signature 2 4 -> setMomentAndStructure 8 [2,2,2,2]
Signature 2 2 -> setMomentAndStructure 8 [2,2,2,2]
Signature 3 4 -> setMomentAndStructure 8 [2, 2, 2]
Signature 4 4 -> setMomentAndStructure 1 [4,4,4,4]
-- TODO what does the 6 here even mean.
Signature 6 8 -> setMomentAndStructure 6 [3, 3]
Signature 9 8 -> setMomentAndStructure 6 [3, 3, 3]
Signature 12 8 -> setMomentAndStructure 6 [3, 3, 3, 3]
_ -> error "Unknown signature"
renderManyBeameds :: [Beamed] -> State RenderState [L.Music]
renderManyBeameds bs =
(join . fmap F.toList) <$> traverse f bs
where f b = do notes <- resolveMods b
return $! renderBeamed notes
resolveMods :: MonadState RenderState f => Beamed -> f (NonEmpty Note)
resolveMods (Beamed b) =
forOf (traverse . _NoteHead) b $ \nh ->
do mods <- use renderStateNoteMods
let v = applyMods mods nh
renderStateNoteMods .= (nh^.noteHeadMods)
return (v & noteHeadMods .~ [])
renderBeamed :: NonEmpty Note -> NonEmpty L.Music
renderBeamed =
buildMusic
. addBeams
. (>>= renderNote)
addBeams :: Traversable t => t RenderedNote -> t RenderedNote
addBeams rn =
let numNotes = lengthOf visitNotes rn
visitNotes = traverse . _NoteMusic
in if numNotes > 1
then rn & taking 1 visitNotes %~ L.beginBeam
& dropping (numNotes - 1) visitNotes %~ L.endBeam
else rn
buildMusic :: NonEmpty RenderedNote -> NonEmpty L.Music
buildMusic rns = rns >>= f
where f (NoteMusic l) = pure l
f (GraceMusic l) = l
f (OtherMusic l) = l
f (Tupleted n d more) =
pure $
L.Tuplet n d (L.Sequential . F.toList . buildMusic $ more)
renderNote :: Note -> NE.NonEmpty RenderedNote
renderNote (Note h) = renderNoteHead h
renderNote (Rest n) = pure (renderRest n)
renderNote (Tuplet r h) =
let notes = renderNote =<< h
tupletGroup = Tupleted (fromInteger $ numerator r) (fromInteger $ denominator r)
mkTuplet ns =
case ns of
GraceMusic o :| (x:xs) -> GraceMusic o <| mkTuplet (x:|xs)
_ -> pure $ tupletGroup ns
in mkTuplet notes
renderRest :: Duration -> RenderedNote
renderRest n = OtherMusic (pure $ L.Rest (Just $ L.Duration n) [])
restoring :: State a b -> State a b
restoring ma =
do x <- get
v <- ma
put x
return v
|
nkpart/score-writer
|
src/Score/Render.hs
|
bsd-3-clause
| 11,085 | 0 | 17 | 3,182 | 3,042 | 1,572 | 1,470 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
-- | Module contains all stuff to migrate from AcidState to Postgres.
module Guide.Database.Import
(
loadIntoPostgres
) where
import Imports
import Data.Acid (EventResult, EventState, QueryEvent, query)
import Hasql.Transaction (Transaction)
import Hasql.Transaction.Sessions (Mode (..))
import Data.Generics.Uniplate.Operations (Biplate, transformBi)
import Guide.Database.Connection
import Guide.Database.Queries.Insert
import Guide.Database.Queries.Select
import Guide.Database.Schema
import Guide.Database.Types
import Guide.State
import Guide.Types.Core
import Guide.Uid
import Guide.Config
import Guide.Logger
-- | Load categories and deleted categories from acid state to postgres
-- and check if they are equal.
--
-- NOTE: It loads categories and categoriesDeleted fields of GlobalState only.
loadIntoPostgres :: Config -> IO ()
loadIntoPostgres config@Config{..} = withLogger config $ \logger -> do
withDB (pure ()) $ \db -> do
globalState <- dbQuery logger db GetGlobalState
postgresLoader logger globalState
postgresLoader :: Logger -> GlobalState -> IO ()
postgresLoader logger globalState = do
-- Postgres should be started and 'guide' base created.
setupDatabase
-- Upload to Postgres
conn <- connect
runTransactionExceptT conn Write $ insertCategories globalState
-- Download from Postgres
(catPostgres, catDeletedPostgres)
<- runTransactionExceptT conn Read getCategories
-- Check identity of available categories
let checkedCat =
sortOn categoryUid catPostgres ==
sortOn categoryUid (categories globalState)
-- Check identity of deleted categories
let checkedCatDeleted =
sortOn categoryUid catDeletedPostgres ==
sortOn categoryUid (categoriesDeleted globalState)
let checked = checkedCat && checkedCatDeleted
logDebugIO logger $ format "AcidState == Postgres: {}" checked
unless checked $ exitFailure
where
-- Insert all categories from AcidState either deleted or not.
-- Categories be normilised before insertion. See 'normalizeUTC'.
insertCategories :: GlobalState -> ExceptT DatabaseError Transaction ()
insertCategories GlobalState{..} = do
mapM_ (insertCategoryWhole (#deleted False) . normalizeUTC)
categories
mapM_ (insertCategoryWhole (#deleted True) . normalizeUTC)
categoriesDeleted
----------------------------------------------------------------------------
-- Helpers
----------------------------------------------------------------------------
-- | Read something from the database.
dbQuery :: (EventState event ~ GlobalState, QueryEvent event, Show event)
=> Logger -> DB -> event -> IO (EventResult event)
dbQuery logger db x = do
logDebugIO logger $ "dbQuery: " +|| x ||+ ""
liftIO $ query db x
-- | Format recursivly all UTCTime fields of Category to Postgres way.
normalizeUTC :: Biplate Category UTCTime => Category -> Category
normalizeUTC = transformBi cutUTCTime
-- | Truncate pico up to 6 digits.
-- | Haskell UTCTime '2019-08-22 09:03:45.736488657 UTC' becomes
-- | Postgres timestamptz '2019-08-22 09:03:45.736488 UTC'.
cutUTCTime :: UTCTime -> UTCTime
cutUTCTime UTCTime{..} = UTCTime{utctDay, utctDayTime = utctDayTimeCut}
where
utctDayTimeCut = picosecondsToDiffTime pico12Cut
pico12 = diffTimeToPicoseconds utctDayTime
pico12Cut = truncate ((fromInteger pico12 / 1000000) :: Double) * 1000000
----------------------------------------------------------------------------
-- Insert helpers
----------------------------------------------------------------------------
-- | Insert category at whole (with items and traits).
insertCategoryWhole
:: "deleted" :! Bool
-> Category
-> ExceptT DatabaseError Transaction ()
insertCategoryWhole (arg #deleted -> deleted) category@Category{..} = do
insertCategoryByRow category (#deleted deleted)
insertItemsOfCategory category
mapM_ insertTraitsOfItem categoryItems
mapM_ insertTraitsOfItem categoryItemsDeleted
-- | Insert to postgres all items of Category.
insertItemsOfCategory :: Category -> ExceptT DatabaseError Transaction ()
insertItemsOfCategory Category{..} = do
mapM_ (insertItemByRow categoryUid (#deleted False)) categoryItems
mapM_ (insertItemByRow categoryUid (#deleted True)) categoryItemsDeleted
-- | Insert to postgres all traits of Item.
insertTraitsOfItem :: Item -> ExceptT DatabaseError Transaction ()
insertTraitsOfItem Item{..} = do
mapM_ (insertTraitByRow itemUid (#deleted False) TraitTypePro) itemPros
mapM_ (insertTraitByRow itemUid (#deleted True) TraitTypePro) itemProsDeleted
mapM_ (insertTraitByRow itemUid (#deleted False) TraitTypeCon) itemCons
mapM_ (insertTraitByRow itemUid (#deleted True) TraitTypeCon) itemConsDeleted
-- | Insert category passing 'Category'.
insertCategoryByRow
:: Category
-> "deleted" :! Bool
-> ExceptT DatabaseError Transaction ()
insertCategoryByRow category (arg #deleted -> deleted) = do
let categoryRow = categoryToRowCategory category (#deleted deleted)
insertCategoryWithCategoryRow categoryRow
-- | Insert item passing 'Item'.
insertItemByRow
:: Uid Category
-> "deleted" :! Bool
-> Item
-> ExceptT DatabaseError Transaction ()
insertItemByRow catId (arg #deleted -> deleted) item = do
let itemRow = itemToRowItem catId (#deleted deleted) item
insertItemWithItemRow itemRow
-- | Insert trait passing 'Trait'.
insertTraitByRow
:: Uid Item
-> "deleted" :! Bool
-> TraitType
-> Trait
-> ExceptT DatabaseError Transaction ()
insertTraitByRow itemId (arg #deleted -> deleted) traitType trait = do
let traitRow = traitToTraitRow itemId (#deleted deleted) traitType trait
insertTraitWithTraitRow traitRow
----------------------------------------------------------------------------
-- Get helpers
----------------------------------------------------------------------------
-- | Get all categories and categoriesDeleted.
getCategories :: ExceptT DatabaseError Transaction ([Category], [Category])
getCategories = do
categoryRowsAll <- selectCategoryRows
let (categoryRowsDeleted, categoryRows) =
partition categoryRowDeleted categoryRowsAll
categories <- traverse getCategoryByRow categoryRows
categoriesDeleted <- traverse getCategoryByRow categoryRowsDeleted
pure (categories, categoriesDeleted)
-- | Get category by CategoryRow
getCategoryByRow :: CategoryRow -> ExceptT DatabaseError Transaction Category
getCategoryByRow categoryRow@CategoryRow{..} = do
itemRows <- selectItemRowsByCategory categoryRowUid
items <- traverse getItemByRow itemRows
itemRowsDeleted <- selectDeletedItemRowsByCategory categoryRowUid
itemsDeleted <- traverse getItemByRow itemRowsDeleted
pure $ categoryRowToCategory (#items items)
(#itemsDeleted itemsDeleted) categoryRow
-- | Get Item by ItemRow
getItemByRow :: ItemRow -> ExceptT DatabaseError Transaction Item
getItemByRow itemRow@ItemRow{..} = do
proTraitRows <- selectTraitRowsByItem itemRowUid TraitTypePro
let proTraits = map traitRowToTrait proTraitRows
proDeletedTraitRows <- selectDeletedTraitRowsByItem itemRowUid TraitTypePro
let proDeletedTraits = map traitRowToTrait proDeletedTraitRows
conTraitRows <- selectTraitRowsByItem itemRowUid TraitTypeCon
let conTraits = map traitRowToTrait conTraitRows
conDeletedTraitRows <- selectDeletedTraitRowsByItem itemRowUid TraitTypeCon
let conDeletedTraits = map traitRowToTrait conDeletedTraitRows
pure $ itemRowToItem
(#proTraits proTraits)
(#proDeletedTraits proDeletedTraits)
(#conTraits conTraits)
(#conDeletedTraits conDeletedTraits)
itemRow
|
aelve/guide
|
back/src/Guide/Database/Import.hs
|
bsd-3-clause
| 7,693 | 0 | 14 | 1,187 | 1,623 | 808 | 815 | -1 | -1 |
module Chapter20 where
import Data.Monoid ((<>))
data Constant a b = Constant a
instance Foldable (Constant a) where
foldMap _ _ = mempty
data Two a b = Two a b
instance Foldable (Two a) where
foldMap f (Two _ x) = f x
data Three a b c = Three a b c
instance Foldable (Three a b) where
foldMap f (Three _ _ x) = f x
data Three' a b = Three' a b b
instance Foldable (Three' a) where
foldMap f (Three' _ x y) = f x <> f y
data Four' a b = Four' a b b b
instance Foldable (Four' a) where
foldMap f (Four' _ x y z) = f x <> f y <> f z
filterF :: (Applicative f, Foldable t, Monoid (f a)) => (a -> Bool) -> t a -> f a
filterF p = foldMap (\x -> if p x then pure x else mempty)
|
taojang/haskell-programming-book-exercise
|
src/ch20/Chapter20.hs
|
bsd-3-clause
| 691 | 0 | 9 | 178 | 369 | 193 | 176 | 19 | 2 |
module OpCodes where
import Control.Applicative (pure)
import Data.Word (Word8, Word16)
import Data.Bits
import qualified Data.Vector as V ((//), (!), slice, toList, fromList, update)
import Lens.Micro
import Lens.Micro.Mtl (view)
import CPU
import Stack
import Registers
import Display (clearDisplay)
import Data.Char (digitToInt)
import Stack (getSP)
data BitwiseOp =
OR
| XOR
| AND
| ADD
| SUB
| SHR
| SUBN
| SHL
deriving (Eq)
handleOpCode :: CPU -> Word16 -> CPU
handleOpCode cpu code =
case operation code of
0x0 -> case byte code of
0xE0 -> cpu & clearDisplay
& increasePC
0xEE -> subReturn cpu
_ -> jump cpu $ addr code
0x1 -> jump cpu $ addr code
0x2 -> call cpu $ addr code
0x3 -> skip cpu (==) (getRegister (view registers cpu) (vx code)) (Just $ byte code)
0x4 -> skip cpu (/=) (getRegister (view registers cpu) (vx code)) (Just $ byte code)
0x5 -> skip cpu (==) (getRegister (view registers cpu) (vx code)) (getRegister (view registers cpu) (vy code))
0x6 -> load cpu (vx code) (byte code)
0x7 -> add cpu (vx code) (byte code)
0x8 -> case nibble code of
0x0 -> load cpu (vx code) ((view registers cpu) V.! (fromIntegral (vy code)))
0x1 -> load cpu (vx code) (bitwise OR cpu code)
0x2 -> load cpu (vx code) (bitwise AND cpu code)
0x3 -> load cpu (vx code) (bitwise XOR cpu code)
0x4 -> load cpu (vx code) (bitwise ADD cpu code)
0x5 -> load cpu (vx code) (bitwise SUB cpu code)
0x6 -> load cpu (vx code) (bitwise SHR cpu code)
0x7 -> load cpu (vx code) (bitwise SUBN cpu code)
0xE -> load cpu (vx code) (bitwise SHL cpu code)
0x9 -> skip cpu (/=) (getRegister (view registers cpu) (vx code)) (getRegister (view registers cpu) (vy code))
0xA -> setI cpu $ addr code
0xB -> jump cpu (maybeIntegral (getRegister (view registers cpu) 0) + (addr code))
0xC -> cpu & set message "Need random"
& increasePC -- RND vx byte
0xD -> cpu & set message "Need graphics"
& increasePC -- DRW vx vy nibble
0xE -> case byte code of
0x9E -> skipKey cpu (==) (getRegister (view registers cpu) (vx code))
0xA1 -> skipKey cpu (/=) (getRegister (view registers cpu) (vx code))
0xF -> case byte code of
0x07 -> load cpu (vx code) (fromIntegral (view delayTimer cpu))
0x0A -> undefined -- LD Vx, K (keyboard)
0x15 -> cpu & delayTimer .~ (regVal cpu (vx code))
& increasePC
0x18 -> cpu & soundTimer .~ (regVal cpu (vx code))
& increasePC
0x1E -> setI cpu ((fromIntegral (regVal cpu (vx code) )) + (view i cpu))
0x29 -> setI cpu (fromIntegral (regVal cpu (vx code)) * 5)
0x33 -> loadBCD cpu (regVal cpu (vx code)) (fromIntegral $ view i cpu)
0x55 -> regsToMem cpu (fromIntegral (view i cpu)) (vx code)
0x65 -> memToRegs cpu (fromIntegral (view i cpu)) (vx code)
jump :: CPU -> Word16 -> CPU
jump cpu val = cpu & pc .~ val
& increasePC
call :: CPU -> Word16 -> CPU
call cpu val = jump (addToStack cpu val) val
load :: CPU -> Word8 -> Word8 -> CPU
load cpu vx byte = cpu & registers %~ (V.// [(fromIntegral vx, byte)])
& increasePC
add :: CPU -> Word8 -> Word8 -> CPU
add cpu vx byte =
cpu & registers %~
(V.// [(fromIntegral vx,
(maybeIntegral $ getRegister (view registers cpu) vx)
+ byte)
]
)
& increasePC
skip :: CPU -> (Word8 -> Word8 -> Bool) -> Maybe Word8 -> Maybe Word8 -> CPU
skip cpu f Nothing _ = cpu
skip cpu f _ Nothing = cpu
skip cpu f (Just b) (Just b') =
if f b b'
then increasePC cpu
else cpu
skipKey :: CPU -> (Bool -> Bool -> Bool) -> Maybe Word8 -> CPU
skipKey cpu f Nothing = increasePC cpu
skipKey cpu f (Just vx) =
if f key True
then cpu & increasePC & increasePC
else cpu & increasePC
where
key = (view input cpu) V.! (fromIntegral vx)
operation :: Word16 -> Word16
operation x = (x .&. 0xF000) `shiftR` 12
addr :: Word16 -> Word16
addr x = x .&. 0x0FFF
vx :: Word16 -> Word8
vx x = fromIntegral $ (x .&. 0x0F00) `shiftR` 8
vy :: Word16 -> Word8
vy x = fromIntegral $ (x .&. 0x00F0) `shiftR` 4
byte :: Word16 -> Word8
byte x = fromIntegral $ x .&. 0x00FF
nibble :: Word16 -> Word16
nibble x = x .&. 0x000F
word8to16 :: Word8 -> Word8 -> Word16
word8to16 h l = shift (fromIntegral h) 8 .|. fromIntegral l
bitwise :: BitwiseOp -> CPU -> Word16 -> Word8
bitwise OR cpu code = (regVal cpu (vx code)) .|. (regVal cpu (vy code))
bitwise AND cpu code = (regVal cpu (vx code)) .&. (regVal cpu (vy code))
bitwise XOR cpu code = (regVal cpu (vx code)) `xor` (regVal cpu (vy code))
bitwise ADD cpu code = undefined
bitwise SUB cpu code = undefined
bitwise SHR cpu code = undefined
bitwise SUBN cpu code = undefined
bitwise SHL cpu code = undefined
regVal :: CPU -> Word8 -> Word8
regVal cpu i = (view registers cpu) V.! (fromIntegral i)
regsToMem :: CPU -> Int -> Word8 -> CPU
regsToMem cpu i vx = cpu & over memory (`V.update` V.fromList (zip [i..] regs))
& increasePC
where regs = V.toList $ V.slice 0 (fromIntegral vx) (view registers cpu)
memToRegs :: CPU -> Int -> Word8 -> CPU
memToRegs cpu i vx = cpu & over registers (`V.update` V.fromList (zip [0..(fromIntegral vx)] mems))
& increasePC
where mems = V.toList $ V.slice i (fromIntegral vx) (view memory cpu)
loadBCD :: CPU -> Word8 -> Int -> CPU
loadBCD cpu vx i = cpu & over memory (`V.update` V.fromList (zip [i,i+1,i+2] bcd))
where
bcd = map (\x -> fromIntegral $ digitToInt x) (show $ fromIntegral vx)
subReturn :: CPU -> CPU
subReturn cpu = cpu & set pc (view stack cpu V.! getSP cpu)
& over sp (\x -> x-1)
& increasePC
draw :: CPU -> Word8 -> Word8 -> Word8 -> CPU
draw cpu vx vy nib = undefined
|
nmohoric/chip8
|
src/OpCodes.hs
|
bsd-3-clause
| 6,363 | 0 | 19 | 2,026 | 2,641 | 1,355 | 1,286 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, NoImplicitPrelude, NamedFieldPuns #-}
import BasePrelude hiding ((\\), finally, read)
import qualified Control.Concurrent as C
import qualified Control.Concurrent.Chan as Ch
import Control.Concurrent.Suspend (sDelay)
import Control.Concurrent.Timer (repeatedTimer, stopTimer, TimerIO)
import Control.Monad.Catch (finally)
import Control.Monad.Trans
import Control.Monad.Trans.Maybe
import qualified Data.Aeson as A
import Data.Map (Map)
import qualified Data.Map as M
import Data.Text (Text)
import qualified Data.Text as T
import Data.UnixTime (UnixTime, getUnixTime, secondsToUnixDiffTime, diffUnixTime)
import Network.WebSockets (Connection)
import qualified Network.WebSockets as WS
import System.IO
import System.IO.Streams.Attoparsec (ParseException)
import System.Random (getStdRandom, randomR)
type Email = Text
type Location = (Float, Float)
data Player = Player Email deriving (Eq, Ord, Show)
data Move = Move Location deriving (Show)
data Pong = Pong Bool
type DB = Map Player (Location, UnixTime, Connection)
data World = World DB
newtype Scoreboard = Scoreboard (Map Player Float)
newtype King = King Location
data Registration = Registration Player Location deriving (Show)
instance A.FromJSON Registration where
parseJSON (A.Object o) = Registration <$> (Player <$> o A..: "email") <*> ((,) <$> o A..: "x" <*> o A..: "y")
parseJSON _ = error "Invalid player"
instance A.FromJSON Move where
parseJSON (A.Object o) = Move <$> ((,) <$> o A..: "x" <*> o A..: "y")
parseJSON _ = error "Invalid move"
instance A.FromJSON Pong where
parseJSON (A.Object o) = Pong <$> o A..: "pong"
parseJSON _ = error "Invalid pong"
instance A.ToJSON World where
toJSON (World db) =
A.object [("world", A.toJSON tuples)]
where
tuples =
[(email, loc) | (Player email, (loc, _, _)) <- M.toList db]
instance A.ToJSON King where
toJSON (King loc) =
A.object [("king", A.toJSON loc)]
instance A.ToJSON Scoreboard where
toJSON (Scoreboard scores) =
A.object [("scoreboard", A.toJSON tuples)]
where
tuples = [(email, score) | (Player email, score) <- M.toList scores]
read :: MVar a -> IO a
read = C.readMVar
modify :: MVar a -> (a -> IO a) -> IO a
modify m f = C.modifyMVar m $ \x -> do
y <- f x
return (y, y)
ping :: Connection -> IO ()
ping conn = WS.sendTextData conn ("{\"ping\": true}" :: Text)
heartbeat :: Int64 -> DB -> IO DB
heartbeat wait db =
M.fromList <$> heartbeatFilterM (M.toList db)
where
delta =
secondsToUnixDiffTime wait
heartbeatFilterM =
filterM $ \(player, (_, lastPongTime, conn)) -> do
now <- getUnixTime
if diffUnixTime now lastPongTime > delta then do
putStrLn ("+ GCing " <> show player)
WS.sendClose conn ("pong better" :: Text)
return False
else do
ping conn
return True
broadcast :: (A.ToJSON a) => DB -> a -> IO ()
broadcast db obj =
forM_ (M.toList db) unicast
where
unicast (_, (_, _, conn)) =
WS.sendTextData conn (A.encode obj)
king :: DB -> IO Location
king db = do
x <- randomFloat
y <- randomFloat
let location = (x, y) :: Location
putStrLn ("+ King moving to: " <> show location)
broadcast db (King location)
return (x, y)
where
randomFloat = ((/ 1024) . fromIntegral) <$> getStdRandom limits
limits = randomR (0, 1024 :: Int)
scoring :: Location -> DB -> Map Player Float -> IO (Map Player Float)
scoring hill db scores = do
broadcast db (Scoreboard scores)
return scores'
where
scores' =
M.mapWithKey (\player (loc, _, _) -> score player + score' loc) db
score player =
fromMaybe 0 (M.lookup player scores)
score' loc =
if distance loc > 0.01 then 1 / distance loc else 100
distance loc =
let (x0, y0) = loc
(x1, y1) = hill in
sqrt ((x1 - x0) ^ two + (y1 - y0) ^ two)
two = 2 :: Int -- :(
dataflow :: (Registration
-> Connection
-> IO (Move -> IO (), Pong -> IO (), IO ()))
-> WS.PendingConnection -> IO ()
dataflow onConnect pending = do
conn <- WS.acceptRequest pending
initial <- WS.receiveData conn
case A.decode initial of
Nothing ->
putStrLn ("Invalid registration: " <> show initial)
Just registration -> do
(onMove, onPong, onDisconnect) <- onConnect registration conn
(void . (`finally` onDisconnect) . runMaybeT . forever) $ do
message <- lift $ WS.receiveData conn
case A.decode message of
Just move ->
lift $ onMove move
Nothing ->
case A.decode message of
Just pong ->
lift $ onPong pong
Nothing -> do
lift $ putStrLn ("Unrecognized: " <> show message)
unforever
putStrLn "+ Finally over"
return ()
where
-- forever in the IO monad loops forever, as you might suspect,
-- without giving us a way to break out. forever in the
-- MaybeT IO monad, however, is quite delightful.
unforever = mzero
makeTimers :: MVar DB ->
Chan (Player, Connection) ->
Chan (Player, Connection) ->
IO [TimerIO]
makeTimers state didConnect didMove = do
king0 <- read state >>= king
kingState <- C.newMVar king0
let kingIO =
join (king <$> read state)
kingTimer <-
makeTimer (void . modify kingState $ const kingIO) secondsPerKing
_ <- forkIO $ do
connects <- Ch.getChanContents didConnect
(`mapM_` connects) $ \(_, conn) -> do
loc <- read kingState
WS.sendTextData conn (A.encode (King loc))
putStrLn "+ King up"
heartbeatTimer <-
makeTimer (void . modify state $ heartbeat maxSecondsBeforeGC) secondsPerHeartbeat
putStrLn "+ Heartbeat up"
_ <- forkIO $ do
moves <- Ch.getChanContents didMove
(`mapM_` moves) $ \(_, _) -> do
db <- read state
broadcast db (World db)
putStrLn "+ Broadcast up"
scoringState <- C.newMVar M.empty
let scoringIO scores =
join (scoring <$> read kingState <*> read state <*> pure scores)
scoringTimer <-
makeTimer (void (modify scoringState scoringIO)) secondsPerScoring
putStrLn "+ Scoring up"
return [ heartbeatTimer
, kingTimer
, scoringTimer
]
where
makeTimer io secs = repeatedTimer io (sDelay secs)
secondsPerHeartbeat = 20
secondsPerKing = 5
secondsPerScoring = 1
maxSecondsBeforeGC = secondsPerHeartbeat * 2
mainWithState :: MVar DB ->
Chan (Player, Connection) ->
Chan (Player, Connection) ->
IO ()
mainWithState state didConnect didMove = do
timers <- makeTimers state didConnect didMove
finally server (forM_ timers stopTimer)
where
server =
runServer (dataflow application)
application registration@(Registration player home) conn = do
putStrLn ("+ Connecting " <> show registration)
onConnect
Ch.writeChan didConnect (player, conn)
return (onMove, onPong, void onDisconnect)
where
drug now (Just (loc, _, _)) =
Just (loc, now, conn)
drug now (Nothing) =
Just (home, now, conn)
renew = modify state $ \db -> do
now <- getUnixTime
return (M.alter (drug now) player db)
onConnect =
read state >>= \db -> do
case (player, M.lookup player db) of
(Player email, Just _) -> error ("This email address is already taken: " <> T.unpack email)
(_, Nothing) -> return ()
db' <- renew
WS.sendTextData conn (A.encode (World db'))
onMove (Move to) = do
_ <- modify state $ \db -> do
putStrLn ("+ Move from " <> show player <> ": " <> show to)
now <- getUnixTime
return (M.insert player (to, now, conn) db)
Ch.writeChan didMove (player, conn)
onDisconnect = modify state $ \db -> do
putStrLn ("+ Disconnecting " <> show player)
let db' = M.delete player db
Ch.writeChan didMove (player, conn)
return db'
onPong _ =
void renew
runServer :: (WS.PendingConnection -> IO ()) -> IO ()
runServer server = do
putStrLn ("+ Server up @" <> ip <> ":" <> show port)
WS.runServer ip port (handle connectionExceptions .
handle parseExceptions .
server)
where
ip = "0.0.0.0"
port = 9160
connectionExceptions :: WS.ConnectionException -> IO ()
connectionExceptions _ =
-- Our finally handler is sufficient.
return ()
parseExceptions :: ParseException -> IO ()
parseExceptions _ =
throw WS.ConnectionClosed
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
state <- C.newMVar M.empty
didConnect <- Ch.newChan
didMove <- Ch.newChan
mainWithState state didConnect didMove
|
trello/staunton
|
server/Main.hs
|
bsd-3-clause
| 9,030 | 0 | 27 | 2,522 | 3,124 | 1,586 | 1,538 | 233 | 4 |
module Main where
import Control.Exception (Handler(..), ErrorCall(..))
import qualified Control.Exception as E
import qualified System.Console.GetOpt as O
import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.IO (hPutStr, hPutStrLn, stdout, stderr, hSetEncoding, utf8)
import Language.Haskell.GhcMod
----------------------------------------------------------------
main :: IO ()
main = flip E.catches handlers $ do
-- #if __GLASGOW_HASKELL__ >= 611
hSetEncoding stdout utf8
-- #endif
getArgs >>= evaluateRequest >>= putStrLn
where
handlers = [Handler (handleThenExit handler1), Handler (handleThenExit handler2)]
handleThenExit handler e = handler e >> exitFailure
handler1 :: ErrorCall -> IO ()
handler1 = print -- for debug
handler2 :: GHCModError -> IO ()
handler2 SafeList = printUsage
handler2 (TooManyArguments cmd) = do
hPutStrLn stderr $ "\"" ++ cmd ++ "\": Too many arguments"
printUsage
handler2 (NoSuchCommand cmd) = do
hPutStrLn stderr $ "\"" ++ cmd ++ "\" not supported"
printUsage
handler2 (CmdArg errs) = do
mapM_ (hPutStr stderr) errs
printUsage
handler2 (FileNotExist file) = do
hPutStrLn stderr $ "\"" ++ file ++ "\" not found"
printUsage
printUsage = hPutStrLn stderr $ '\n' : O.usageInfo usage argspec
|
darthdeus/ghc-mod-ng
|
src/GHCMod.hs
|
bsd-3-clause
| 1,378 | 0 | 12 | 294 | 390 | 205 | 185 | 31 | 5 |
/*Owner & Copyrights: Vance King Saxbe. A.*//* Copyright (c) <2014> Author Vance King Saxbe. A, and contributors Power Dominion Enterprise, Precieux Consulting and other contributors. Modelled, Architected and designed by Vance King Saxbe. A. with the geeks from GoldSax Consulting and GoldSax Technologies email @[email protected]. Development teams from Power Dominion Enterprise, Precieux Consulting. Project sponsored by GoldSax Foundation, GoldSax Group and executed by GoldSax Manager.*/module GoldSaxMachineModule7.APriori.Types where
import Data.Set (Set)
import qualified Data.Set as S
data Client = GovOrg { clientName :: String }
| Company { clientName :: String, person :: Person, duty :: String }
| Individual { person :: Person }
deriving (Show, Eq, Ord)
data ClientKind = KindGovOrg | KindCompany | KindIndividual
deriving (Show, Eq, Ord)
data Person = Person { firstName :: String, lastName :: String, gender :: Gender }
deriving (Show, Eq, Ord)
data Gender = Male | Female | UnknownGender
deriving (Show, Eq, Ord)
data Product = Product { productId :: Integer, productType :: ProductType }
deriving (Show, Eq, Ord)
data ProductType = TimeMachine | TravelGuide | Tool | Trip
deriving (Show, Eq, Ord)
data Purchase = Purchase { client :: Client, products :: [Product] }
deriving (Show, Eq, Ord)
data PurchaseInfo = InfoClientKind ClientKind
| InfoClientDuty String
| InfoClientGender Gender
| InfoPurchasedProduct Integer
| InfoPurchasedProductType ProductType
deriving (Show, Eq, Ord)
clientToPurchaseInfo :: Client -> Set PurchaseInfo
clientToPurchaseInfo GovOrg { } =
S.singleton $ InfoClientKind KindGovOrg
clientToPurchaseInfo Company { duty = d } =
S.fromList [ InfoClientKind KindCompany, InfoClientDuty d ]
clientToPurchaseInfo Individual { person = Person { gender = UnknownGender } } =
S.singleton $ InfoClientKind KindIndividual
clientToPurchaseInfo Individual { person = Person { gender = g } } =
S.fromList [ InfoClientKind KindIndividual, InfoClientGender g ]
productsToPurchaseInfo :: [Product] -> Set PurchaseInfo
productsToPurchaseInfo = foldr
(\(Product i t) pinfos -> S.insert (InfoPurchasedProduct i) $
S.insert (InfoPurchasedProductType t) pinfos)
S.empty
purchaseToTransaction :: Purchase -> Transaction
purchaseToTransaction (Purchase c p) =
Transaction $ clientToPurchaseInfo c `S.union` productsToPurchaseInfo p
newtype Transaction = Transaction (Set PurchaseInfo) deriving (Eq, Ord)
newtype FrequentSet = FrequentSet (Set PurchaseInfo) deriving (Eq, Ord)
data AssocRule = AssocRule (Set PurchaseInfo) (Set PurchaseInfo) deriving (Eq, Ord)
instance Show AssocRule where
show (AssocRule a b) = show a ++ " => " ++ show b
setSupport :: [Transaction] -> FrequentSet -> Double
setSupport transactions (FrequentSet sElts) =
let total = length transactions
supp = length (filter (\(Transaction tElts) -> sElts `S.isSubsetOf` tElts) transactions)
in fromIntegral supp / fromIntegral total
ruleConfidence :: [Transaction] -> AssocRule -> Double
ruleConfidence transactions (AssocRule a b) =
setSupport transactions (FrequentSet $ a `S.union` b) / setSupport transactions (FrequentSet a)
/*email to provide support at [email protected], [email protected], For donations please write to [email protected]*/
|
VanceKingSaxbeA/GoldSaxMachineStore
|
GoldSaxMachineModule7/src/GoldSaxMachineModule7/APriori/Types.hs
|
mit
| 3,729 | 23 | 16 | 864 | 1,127 | 601 | 526 | 55 | 1 |
module Test.Pos.Launcher.Gen where
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import Universum
import Ntp.Client (NtpConfiguration (NtpConfiguration))
import Pos.Configuration (NodeConfiguration (NodeConfiguration))
import Pos.Crypto (ProtocolMagic)
import Pos.Launcher.Configuration (Configuration (Configuration),
ThrottleSettings (ThrottleSettings),
WalletConfiguration (WalletConfiguration))
import Test.Pos.Chain.Block.Gen (genBlockConfiguration)
import Test.Pos.Chain.Delegation.Gen (genDlgConfiguration)
import Test.Pos.Chain.Genesis.Gen (genStaticConfig)
import Test.Pos.Chain.Ssc.Gen (genSscConfiguration)
import Test.Pos.Chain.Txp.Gen (genTxValidationRulesConfig,
genTxpConfiguration)
import Test.Pos.Chain.Update.Gen (genUpdateConfiguration)
import Test.Pos.Crypto.Gen (genRequiresNetworkMagic)
genConfiguration :: ProtocolMagic -> Gen Configuration
genConfiguration pm = Configuration <$> genStaticConfig pm <*> genNtpConfiguration <*> genUpdateConfiguration <*> genSscConfiguration <*> genDlgConfiguration <*> genTxpConfiguration <*> genBlockConfiguration <*> genNode <*> genWallet <*> genRequiresNetworkMagic <*> genTxValidationRulesConfig
genNtpConfiguration :: Gen NtpConfiguration
genNtpConfiguration = NtpConfiguration <$> Gen.list (Range.constant 1 4) genString <*> Gen.integral (Range.constant 1 1000) <*> Gen.integral (Range.constant 1 1000)
genString :: Gen String
genString = Gen.string (Range.constant 1 10) Gen.alphaNum
genNode :: Gen NodeConfiguration
genNode = NodeConfiguration <$> Gen.int Range.constantBounded
<*> Gen.int Range.constantBounded
<*> Gen.int Range.constantBounded
<*> Gen.int Range.constantBounded
<*> Gen.bool
<*> Gen.bool
<*> Gen.bool
genWallet :: Gen WalletConfiguration
genWallet = WalletConfiguration <$> Gen.maybe genThrottleSettings
genThrottleSettings :: Gen ThrottleSettings
genThrottleSettings = ThrottleSettings <$> genWord64 <*> genWord64 <*> genWord64
genWord64 :: Gen Word64
genWord64 = Gen.word64 $ Range.constant 0 1000
|
input-output-hk/pos-haskell-prototype
|
lib/test/Test/Pos/Launcher/Gen.hs
|
mit
| 2,402 | 0 | 16 | 555 | 509 | 287 | 222 | 39 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module ClientRepo (getClients, saveClient, deleteClient) where
import Client
import DBConnection
import Database.MySQL.Simple
getClients :: IO [Client]
getClients = do
conn <- connectDB
clients <- query_ conn "SELECT * FROM clients"
return clients
saveClient :: Client -> IO Client
saveClient client = do
conn <- connectDB
_ <- execute conn "INSERT INTO clients \
\(name,address,city,state,zip,country,email,contact,phone,created_at,updated_at) values \
\(?,?,?,?,?,?,?,?,?,?,?)" client
results <- query_ conn "SELECT LAST_INSERT_ID()"
let [Only clientId] = results
return client { Client.id = clientId }
deleteClient :: Int -> IO ()
deleteClient clientId = do
conn <- connectDB
_ <- execute conn "DELETE FROM clients WHERE id=?" [clientId]
return ()
|
botandrose/eboshi_api_shootout
|
haskell_scotty/ClientRepo.hs
|
mit
| 821 | 0 | 11 | 140 | 208 | 102 | 106 | 23 | 1 |
{- Main.hs; Mun Hon Cheong ([email protected]) 2005
Main module
-}
module Main where
import TextureFonts
import Graphics.UI.GLUT
import Graphics.Rendering.OpenGL
import Data.IORef
import Data.Maybe
import Control.Monad
import qualified HGL as HGL
import AFRP
import AFRPInternals
import AFRPForceable
import Game
import Parser
import Object
import BSP
import Camera
import System.Exit (ExitCode(..), exitWith)
import Matrix
import MD3
import Data.HashTable
import Frustum
import Data.List (find)
import Textures
import MapCfg
import Render
msInterval :: Int
msInterval = 16
clkRes :: Double
clkRes = 1000
data Input
= KBMInput { key :: Key,
keyState :: KeyState,
modifiers :: Modifiers,
pos :: Position}
| MouseMove { pos :: Position }
deriving Show
type OGLInput = Maybe Input
type WinInput = Event HGL.Event
main :: IO ()
main = do
(progName,names) <-getArgsAndInitialize
case names of
[] -> printUsage progName
[name] -> do createAWindow "FRAG" name
mainLoop
_ -> printUsage progName
printUsage :: String -> IO ()
printUsage n = do putStrLn $ "Usage: " ++ n ++ " <level>"
putStrLn $ "Example: " ++ n ++ " leveleg"
createAWindow :: String -> String -> IO ()
createAWindow windowName level = do
initialDisplayMode $= [WithDepthBuffer, DoubleBuffered, RGBAMode]
drawBuffer $= BackBuffers
initialWindowSize $= (Size 640 480)
createWindow windowName
clear [ColorBuffer]
viewport $= ((Position 0 0), Size 640 480)
matrixMode $= Projection
loadIdentity
perspective 70.0 (640/480) 10.0 4000.0
matrixMode $= Modelview 0
loadIdentity
depthFunc $= Just Less
texture Texture2D $= Enabled
cullFace $= Just Front
cursor $= None
--load our level objects from the *.cfg file
iobjs <- readMapCfg (level ++ ".cfg")
let cam = initCamera (80::Int,61::Int,60::Int) (80::Int,611::Int,59::Int) (0::Int,1::Int,0::Int)
camRef <- newIORef(cam)
--read the BSP files and player models specified in the *.med files
(mapRef,modls) <- readMapMedia (level ++ ".med")
listModels <- toList modls
animList <- mapM getAnims listModels
--complete the objects
let objs = toCompleteObjects animList iobjs
--build the fonts
(tex,base)<- buildFonts
numbase <- buildBigNums
--create a hashmap for textures
texs <- fromList hashString []
--create the crosshair
crosshair <- getAndCreateTexture "crosshaira"
insert texs "crosshair" crosshair
--set up the variables needed by our callbacks and game loop
tme <- get elapsedTime
lasttime <- newIORef(tme)
lastDTime <- newIORef(tme)
lastDTime2 <- newIORef(tme)
fpsc1 <- newIORef(0,0)
fps1 <- newIORef(0,0,0)
newIORef(0::Int)
_ <- newIORef(tme)
--hold new keyboard input
newInput <- newIORef(Nothing)
inpState <- newIORef (False)
--hold the new mouse input
newMouseInput <- newIORef(Nothing)
--lock the mouse or not
lck <- newIORef(True)
(_, _) <- getWinInput
(lasttime, (newInput,newMouseInput)) inpState True tme
hasReact <- newIORef(False)
mp <- readIORef mapRef
let gd = GameData {
gamemap = mapRef,
models = modls,
textures = texs,
camera = camRef,
lastDrawTime = lastDTime,
lastDrawTime2 = lastDTime2,
hasReacted = hasReact,
fonts = (tex,base),
nbase = numbase,
lock = lck,
fpsc = fpsc1,
fpss = fps1,
nems = ((length objs)-1)
}
rh <-
reactInit
(initr lasttime (newInput,newMouseInput) inpState)
(actuate gd)
(repeatedly (0.016) () &&&(parseWinInput >>> game mp objs))
--set up the callbacks
displayCallback $= display
keyboardMouseCallback $= Just (keyboardMouse newInput newMouseInput lck)
motionCallback $= Just (dragMotion newMouseInput)
passiveMotionCallback $= Just (mouseMotion newMouseInput)
idleCallback $=
Just (idle lasttime (newInput,newMouseInput)
hasReact (tex,base) inpState rh)
where getAnims (x,y) = do
us <- readIORef (upperState y)
ls <- readIORef (lowerState y)
return (x,us,ls)
-------------------------------------------------------------------------------
-- functions to connect Haskell and Yampa
actuate :: GameData -> ReactHandle a b ->
Bool -> (Event (), [ObsObjState]) -> IO Bool
actuate gd _ _ (e, noos) = do
when (force (noos) `seq` isEvent e)
(render gd noos)
return False
initr :: IORef(Int) -> (IORef(OGLInput),IORef(OGLInput)) ->
(IORef(Bool)) -> IO (WinInput,WinInput)
initr lasttime newInput inpState = do
tme <- get elapsedTime
writeIORef lasttime 1
(_, inp) <- getWinInput (lasttime, newInput) inpState True tme
case inp of
Just i -> return i
Nothing -> return (noEvent,noEvent)
-------------------------------------------------------------------------------
-- graphics
render :: GameData -> [ObsObjState] -> IO()
render gd oos = do
-- get the last time we drew the screen
lastime <- readIORef (lastDrawTime gd)
-- the current time
tme <- get elapsedTime
l <- readIORef (lock gd)
-- if the last time is at least greater than 0.016
-- seconds and the mouse is locked reset the position
-- to the middle of the screen
case ((realToFrac ((tme - lastime) :: Int)) / (1000))
>= (1/60) && l == True of
True -> do
pointerPosition $= (Position 320 240)
writeIORef (lastDrawTime gd) tme
_ -> return ()
_ <- readIORef (lastDrawTime2 gd)
_ <- readIORef (hasReacted gd)
--case (((realToFrac (time - lastTime2))/1000) <= (1/60)) of
case (True) of
True -> do
-- initial setup
clear [ ColorBuffer, DepthBuffer ]
loadIdentity
--find the camera and set our view
let playerState = findCam oos
case (cood playerState) of
[] -> return ()
_ -> print (getPos (cood playerState))
let cam = setCam $ playerState
writeIORef (camera gd) cam
cameraLook cam
--render the map
renderBSP (gamemap gd) (cpos cam)
--render the objects
mp <- readIORef (gamemap gd)
frust <- getFrustum
mapM_ (renderObjects (camera gd) (models gd) frust mp) oos
--render the gun
renderGun cam (models gd)
--set up orthographics mode so we can draw the fonts
renderHud gd playerState (length oos) tme
writeIORef (lastDrawTime2 gd) tme
writeIORef (hasReacted gd) False
swapBuffers
_ -> do
writeIORef (lastDrawTime2 gd) tme
return()
getPos :: [(Double,Double,Double)] -> [(Int,Int,Int)]
getPos coords = map ints l
where
l = map (vectorAdd (0,90,0)) coords
ints (x,y,z)= (truncate x,truncate y,truncate z)
findCam :: [ObsObjState] -> ObsObjState
findCam states = fromJust $ find (\x -> (isCamera x)) states
setCam :: ObsObjState -> Camera
setCam (OOSCamera {oldCam = cam, newCam = _}) = cam
-------------------------------------------------------------------------------
--callbacks
display :: (Monad t) => t ()
display = return ()
keyboardMouse ::
IORef(OGLInput) -> IORef(OGLInput) -> IORef(Bool) -> KeyboardMouseCallback
keyboardMouse _ _ lck (Char 'z') _ _ _ = do
readIORef lck
writeIORef lck (False)
keyboardMouse _ _ lck (Char 'x') _ _ _ = do
_ <- readIORef lck
writeIORef lck (True)
keyboardMouse _ _ _ (Char '\27') _ _ _ = exitWith ExitSuccess
keyboardMouse _ newMouse _ newKey@(MouseButton _)
newKeyState newModifiers newPosition = do
writeIORef newMouse (Just KBMInput{
key = newKey,
keyState = newKeyState,
modifiers = newModifiers,
pos = newPosition})
keyboardMouse newInput _ _ newKey
newKeyState newModifiers newPosition = do
writeIORef newInput (Just KBMInput{
key = newKey,
keyState = newKeyState,
modifiers = newModifiers,
pos = newPosition})
mouseMotion :: IORef(OGLInput) -> MotionCallback
mouseMotion newInput newCursorPos = do
lst <- readIORef newInput
case lst of
(Just inp) -> writeIORef newInput (Just inp)
_ -> writeIORef newInput (Just MouseMove {pos=newCursorPos})
dragMotion :: IORef(OGLInput) -> MotionCallback
dragMotion newInput newCursorPos = do
lst <- readIORef newInput
case lst of
(Just inp) -> writeIORef newInput (Just inp)
_ -> writeIORef newInput (Just MouseMove {pos=newCursorPos})
idle :: IORef(Int) -> (IORef(OGLInput),IORef(OGLInput)) ->IORef(Bool) ->
(Maybe TextureObject,DisplayList) -> (IORef(Bool)) ->
ReactHandle (WinInput,WinInput) (Event (), ([Object.ObsObjState])) -> IO()
idle lasttime newInput hasreacted _ inputState rh = do
lTime <- readIORef lasttime
currenttime <- get elapsedTime
case (currenttime - lTime >= 16) of
True -> do
(dt, input) <-
getWinInput (lasttime,newInput) inputState True currenttime
react rh (dt,input)
writeIORef hasreacted True
writeIORef lasttime currenttime
return ()
_ -> return ()
-------------------------------------------------------------------------------
-- input handling
-- mimic HGL so the parser from Space Invaders can be used
getWinInput ::
(IORef(Int),(IORef(OGLInput),IORef(OGLInput))) ->
(IORef(Bool)) -> Bool -> Int-> IO(DTime,(Maybe (WinInput,WinInput)))
getWinInput (lasttime, (newInput,newMouseInput)) inpState _ currenttime = do
lTime <- readIORef lasttime
newIn <- readIORef newInput
newMouseIn <- readIORef newMouseInput
writeIORef newInput Nothing
writeIORef newMouseInput Nothing
-- we try to get rid of redundant events
hasReset <- readIORef inpState
mmin <-
case (coalesce newIn, coalesce newMouseIn,hasReset) of
(NoEvent, NoEvent,_) -> return Nothing
(NoEvent, Event HGL.MouseMove {HGL.pt =HGL.Point (320,240)},False)-> do
writeIORef inpState False
return Nothing
(NoEvent, Event HGL.MouseMove {HGL.pt =HGL.Point (320,240)},True) -> do
writeIORef inpState False
return $ Just (coalesce newIn,coalesce newMouseIn)
(NoEvent, Event HGL.MouseMove {HGL.pt = _ },True) -> do
writeIORef inpState True
return $ Just (coalesce newIn,coalesce newMouseIn)
(NoEvent, Event HGL.MouseMove {HGL.pt = _ },False) -> do
writeIORef inpState True
return $ Just (coalesce newIn,coalesce newMouseIn)
(Event _, Event HGL.MouseMove {HGL.pt =HGL.Point (320,240)},False)-> do
writeIORef inpState False
return $ Just (coalesce newIn,noEvent)
(Event _, Event HGL.MouseMove {HGL.pt =HGL.Point (320,240)},True) -> do
writeIORef inpState False
return $ Just (coalesce newIn,coalesce newMouseIn)
(Event _, Event HGL.MouseMove {HGL.pt = _},True) -> do
writeIORef inpState True
return $ Just (coalesce newIn,coalesce newMouseIn)
(Event _, Event HGL.MouseMove {HGL.pt = _},False) -> do
writeIORef inpState True
return $ Just (coalesce newIn,coalesce newMouseIn)
(_,_,_) -> do
writeIORef inpState True
return $ Just (coalesce newIn,coalesce newMouseIn)
return ((fromIntegral (currenttime-lTime))/clkRes, mmin)
coalesce :: OGLInput -> WinInput
coalesce Nothing = NoEvent
coalesce (Just KBMInput {key = (MouseButton button),
keyState = ks,
pos = p}) =
(Event HGL.Button {
HGL.pt = (pos2Point p),
HGL.isLeft = (isMBLeft (MouseButton button)),
HGL.isDown = (isKeyDown ks)})
coalesce (Just KBMInput {key = (Char a),
keyState = ks}) =
(Event HGL.Char {HGL.char = a,
HGL.isDown = (isKeyDown ks)})
coalesce (Just MouseMove {pos= p}) =
(Event HGL.MouseMove { HGL.pt = pos2Point p })
coalesce _ = NoEvent
pos2Point :: Position -> HGL.Point
pos2Point (Position a b) = HGL.Point (fromIntegral a, fromIntegral b)
isMBLeft :: Key -> Bool
isMBLeft (MouseButton LeftButton) = True
isMBLeft _ = False
isKeyDown :: KeyState -> Bool
isKeyDown Down = True
isKeyDown _ = False
filter :: Eq a => a -> a -> Maybe(a)
filter a b =
if (a == b) then
Just(a)
else
Nothing
|
snowmantw/Frag
|
src/Main.hs
|
gpl-2.0
| 14,090 | 0 | 19 | 4,797 | 4,188 | 2,142 | 2,046 | 305 | 10 |
{-# 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.OpsWorks.DescribeCommands
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- 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 <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Describes the results of specified commands.
--
-- You must specify at least one of the parameters.
--
-- Required Permissions: To use this action, an IAM user must have a Show,
-- Deploy, or Manage permissions level for the stack, or an attached policy that
-- explicitly grants permissions. For more information on user permissions, see <http://docs.aws.amazon.com/opsworks/latest/userguide/opsworks-security-users.html Managing User Permissions>.
--
-- <http://docs.aws.amazon.com/opsworks/latest/APIReference/API_DescribeCommands.html>
module Network.AWS.OpsWorks.DescribeCommands
(
-- * Request
DescribeCommands
-- ** Request constructor
, describeCommands
-- ** Request lenses
, dcCommandIds
, dcDeploymentId
, dcInstanceId
-- * Response
, DescribeCommandsResponse
-- ** Response constructor
, describeCommandsResponse
-- ** Response lenses
, dcrCommands
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.OpsWorks.Types
import qualified GHC.Exts
data DescribeCommands = DescribeCommands
{ _dcCommandIds :: List "CommandIds" Text
, _dcDeploymentId :: Maybe Text
, _dcInstanceId :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'DescribeCommands' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dcCommandIds' @::@ ['Text']
--
-- * 'dcDeploymentId' @::@ 'Maybe' 'Text'
--
-- * 'dcInstanceId' @::@ 'Maybe' 'Text'
--
describeCommands :: DescribeCommands
describeCommands = DescribeCommands
{ _dcDeploymentId = Nothing
, _dcInstanceId = Nothing
, _dcCommandIds = mempty
}
-- | An array of command IDs. If you include this parameter, 'DescribeCommands'
-- returns a description of the specified commands. Otherwise, it returns a
-- description of every command.
dcCommandIds :: Lens' DescribeCommands [Text]
dcCommandIds = lens _dcCommandIds (\s a -> s { _dcCommandIds = a }) . _List
-- | The deployment ID. If you include this parameter, 'DescribeCommands' returns a
-- description of the commands associated with the specified deployment.
dcDeploymentId :: Lens' DescribeCommands (Maybe Text)
dcDeploymentId = lens _dcDeploymentId (\s a -> s { _dcDeploymentId = a })
-- | The instance ID. If you include this parameter, 'DescribeCommands' returns a
-- description of the commands associated with the specified instance.
dcInstanceId :: Lens' DescribeCommands (Maybe Text)
dcInstanceId = lens _dcInstanceId (\s a -> s { _dcInstanceId = a })
newtype DescribeCommandsResponse = DescribeCommandsResponse
{ _dcrCommands :: List "Commands" Command
} deriving (Eq, Read, Show, Monoid, Semigroup)
instance GHC.Exts.IsList DescribeCommandsResponse where
type Item DescribeCommandsResponse = Command
fromList = DescribeCommandsResponse . GHC.Exts.fromList
toList = GHC.Exts.toList . _dcrCommands
-- | 'DescribeCommandsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dcrCommands' @::@ ['Command']
--
describeCommandsResponse :: DescribeCommandsResponse
describeCommandsResponse = DescribeCommandsResponse
{ _dcrCommands = mempty
}
-- | An array of 'Command' objects that describe each of the specified commands.
dcrCommands :: Lens' DescribeCommandsResponse [Command]
dcrCommands = lens _dcrCommands (\s a -> s { _dcrCommands = a }) . _List
instance ToPath DescribeCommands where
toPath = const "/"
instance ToQuery DescribeCommands where
toQuery = const mempty
instance ToHeaders DescribeCommands
instance ToJSON DescribeCommands where
toJSON DescribeCommands{..} = object
[ "DeploymentId" .= _dcDeploymentId
, "InstanceId" .= _dcInstanceId
, "CommandIds" .= _dcCommandIds
]
instance AWSRequest DescribeCommands where
type Sv DescribeCommands = OpsWorks
type Rs DescribeCommands = DescribeCommandsResponse
request = post "DescribeCommands"
response = jsonResponse
instance FromJSON DescribeCommandsResponse where
parseJSON = withObject "DescribeCommandsResponse" $ \o -> DescribeCommandsResponse
<$> o .:? "Commands" .!= mempty
|
romanb/amazonka
|
amazonka-opsworks/gen/Network/AWS/OpsWorks/DescribeCommands.hs
|
mpl-2.0
| 5,248 | 0 | 10 | 1,031 | 660 | 398 | 262 | 71 | 1 |
{-
Copyright 2012-2013 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Plush.Run.ExecuteType (
ExecuteType(..),
execType,
)
where
import Control.Applicative ((<*>))
import Data.Functor
import Data.Monoid
import Plush.Run.Command
import Plush.Run.Expansion
import Plush.Run.Posix
import Plush.Run.ShellExec
import Plush.Types
data ExecuteType = ExecuteForeground | ExecuteMidground | ExecuteBackground
deriving (Eq, Ord, Bounded)
instance Monoid ExecuteType where
mempty = ExecuteForeground
mappend = min
mconcat [] = mempty
mconcat es = minimum es
execType :: (PosixLike m) => CommandList -> ShellExec m ExecuteType
execType = typeCommandList
where
typeCommandList cl = mconcat <$> mapM typeCommandItem cl
typeCommandItem (ao, Sequential) = typeAndOr ao
typeCommandItem (_, Background) = return ExecuteBackground
typeAndOr ao = mconcat <$> mapM (\(_, (_, p)) -> typePipe p) ao
typePipe p = mconcat <$> mapM typeCommand p
typeCommand (Simple cmd) = typeSimple cmd
typeCommand (Compound cmd _) = case cmd of
BraceGroup cmdlist -> typeCommandList cmdlist
-- Things in the subshell can't change the state of this shell.
Subshell {} -> return ExecuteMidground
ForLoop _ _ cmdlist -> typeCommandList cmdlist
CaseConditional _ items -> minimum <$>
mapM (maybe (return mempty) typeCommandList . snd) items
IfConditional conds mElse -> minimum <$>
mapM typeCommandList
(maybe id (:) mElse $ concatMap (\(c,d)->[c,d]) conds)
WhileLoop condition body ->
min <$> typeCommandList condition <*> typeCommandList body
UntilLoop condition body ->
min <$> typeCommandList condition <*> typeCommandList body
typeCommand (Function {}) = return ExecuteForeground
typeSimple (SimpleCommand [] _ _) = return ExecuteForeground
typeSimple (SimpleCommand ws _ _) =
expandPassive ws >>= typeFields . map quoteRemoval
typeFields [] = return ExecuteForeground
typeFields (cmd:_) = do
(fc, _, _) <- commandSearch cmd
return $ typeFound fc
typeFound SpecialCommand = ExecuteForeground
typeFound DirectCommand = ExecuteForeground
typeFound (BuiltInCommand _) = ExecuteMidground
typeFound FunctionCall = ExecuteForeground
-- TODO: analyze function bodies to see if they can be midgrounded
typeFound (ExecutableCommand _) = ExecuteMidground
typeFound UnknownCommand = ExecuteForeground
|
mzero/plush
|
src/Plush/Run/ExecuteType.hs
|
apache-2.0
| 3,043 | 0 | 17 | 654 | 696 | 360 | 336 | 53 | 17 |
module Ivory.Artifact.Transformer
( Transformer()
, emptyTransformer
, transform
, transformErr
, runTransformer
) where
newtype Transformer a =
Transformer
{ unTransformer :: a -> Either String a
}
emptyTransformer :: Transformer a
emptyTransformer = Transformer Right
transform :: (a -> a) -> Transformer a -> Transformer a
transform f (Transformer t) = Transformer $ \a -> do
a' <- t a
return (f a')
transformErr :: (a -> Either String a) -> Transformer a -> Transformer a
transformErr f (Transformer t) = Transformer $ \a -> do
a' <- t a
f a'
runTransformer :: Transformer a -> a -> Either String a
runTransformer = unTransformer
|
GaloisInc/ivory
|
ivory-artifact/src/Ivory/Artifact/Transformer.hs
|
bsd-3-clause
| 672 | 0 | 11 | 144 | 237 | 122 | 115 | 23 | 1 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module HaskellPrelude (module M, ifThenElse) where
import "base" Prelude as M
import "base" Data.String as M
ifThenElse a b c = if a then b else c
|
Ye-Yong-Chi/codeworld
|
codeworld-base/src/HaskellPrelude.hs
|
apache-2.0
| 817 | 0 | 5 | 153 | 50 | 34 | 16 | 6 | 2 |
{-# LANGUAGE TemplateHaskell, ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for the SlotMap.
-}
{-
Copyright (C) 2014 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.SlotMap
( testSlotMap
, genSlotLimit
, genTestKey
, overfullKeys
) where
import Prelude ()
import Ganeti.Prelude hiding (all)
import Control.Monad
import Data.Foldable (all)
import qualified Data.Map as Map
import Data.Map (Map, member, keys, keysSet)
import Data.Set (Set, size, union)
import qualified Data.Set as Set
import Test.HUnit
import Test.QuickCheck
import Test.Ganeti.TestCommon
import Test.Ganeti.TestHelper
import Test.Ganeti.Types ()
import Ganeti.SlotMap
{-# ANN module "HLint: ignore Use camelCase" #-}
-- | Generates a number typical for the limit of a `Slot`.
-- Useful for constructing resource bounds when not directly constructing
-- the relevant `Slot`s.
genSlotLimit :: Gen Int
genSlotLimit = frequency [ (9, choose (1, 5))
, (1, choose (1, 100))
] -- Don't create huge slot limits.
instance Arbitrary Slot where
arbitrary = do
limit <- genSlotLimit
occ <- choose (0, limit * 2)
return $ Slot occ limit
-- | Generates a number typical for the occupied count of a `Slot`.
-- Useful for constructing `CountMap`s.
genSlotCount :: Gen Int
genSlotCount = slotOccupied <$> arbitrary
-- | Takes a slot and resamples its `slotOccupied` count to fit the limit.
resampleFittingSlot :: Slot -> Gen Slot
resampleFittingSlot (Slot _ limit) = do
occ <- choose (0, limit)
return $ Slot occ limit
-- | What we use as key for testing `SlotMap`s.
type TestKey = String
-- | Generates short strings used as `SlotMap` keys.
--
-- We limit ourselves to a small set of key strings with high probability to
-- increase the chance that `SlotMap`s actually have more than one slot taken.
genTestKey :: Gen TestKey
genTestKey = frequency [ (9, elements ["a", "b", "c", "d", "e"])
, (1, genPrintableAsciiString)
]
-- | Generates small lists.
listSizeGen :: Gen Int
listSizeGen = frequency [ (9, choose (1, 5))
, (1, choose (1, 100))
]
-- | Generates a `SlotMap` given a generator for the keys (see `genTestKey`).
genSlotMap :: (Ord a) => Gen a -> Gen (SlotMap a)
genSlotMap keyGen = do
n <- listSizeGen -- don't create huge `SlotMap`s
Map.fromList <$> vectorOf n ((,) <$> keyGen <*> arbitrary)
-- | Generates a `CountMap` given a generator for the keys (see `genTestKey`).
genCountMap :: (Ord a) => Gen a -> Gen (CountMap a)
genCountMap keyGen = do
n <- listSizeGen -- don't create huge `CountMap`s
Map.fromList <$> vectorOf n ((,) <$> keyGen <*> genSlotCount)
-- | Tells which keys of a `SlotMap` are overfull.
overfullKeys :: (Ord a) => SlotMap a -> Set a
overfullKeys sm =
Set.fromList [ a | (a, Slot occ limit) <- Map.toList sm, occ > limit ]
-- | Generates a `SlotMap` for which all slots are within their limits.
genFittingSlotMap :: (Ord a) => Gen a -> Gen (SlotMap a)
genFittingSlotMap keyGen = do
-- Generate a SlotMap, then resample all slots to be fitting.
slotMap <- traverse resampleFittingSlot =<< genSlotMap keyGen
when (isOverfull slotMap) $ error "BUG: FittingSlotMap Gen is wrong"
return slotMap
-- * Test cases
case_isOverfull :: Assertion
case_isOverfull = do
assertBool "overfull"
. isOverfull $ Map.fromList [("buck", Slot 3 2)]
assertBool "not overfull"
. not . isOverfull $ Map.fromList [("buck", Slot 2 2)]
assertBool "empty"
. not . isOverfull $ (Map.fromList [] :: SlotMap TestKey)
case_occupySlots_examples :: Assertion
case_occupySlots_examples = do
let a n = ("a", Slot n 2)
let b n = ("b", Slot n 4)
let sm = Map.fromList [a 1, b 2]
cm = Map.fromList [("a", 1), ("b", 1), ("c", 5)]
assertEqual "fitting occupySlots"
(sm `occupySlots` cm)
(Map.fromList [a 2, b 3, ("c", Slot 5 0)])
-- | Union of the keys of two maps.
keyUnion :: (Ord a) => Map a b -> Map a c -> Set a
keyUnion a b = keysSet a `union` keysSet b
-- | Tests properties of `SlotMap`s being filled up.
prop_occupySlots :: Property
prop_occupySlots =
forAll arbitrary $ \(sm :: SlotMap Int, cm :: CountMap Int) ->
let smOcc = sm `occupySlots` cm
in conjoin
[ counterexample "input keys are preserved" $
all (`member` smOcc) (keyUnion sm cm)
, counterexample "all keys must come from the input keys" $
all (`Set.member` keyUnion sm cm) (keys smOcc)
]
-- | Tests for whether there's still space for a job given its rate
-- limits.
case_hasSlotsFor_examples :: Assertion
case_hasSlotsFor_examples = do
let a n = ("a", Slot n 2)
let b n = ("b", Slot n 4)
let c n = ("c", Slot n 8)
let sm = Map.fromList [a 1, b 2]
assertBool "fits" $
sm `hasSlotsFor` Map.fromList [("a", 1), ("b", 1)]
assertBool "doesn't fit"
. not $ sm `hasSlotsFor` Map.fromList [("a", 1), ("b", 3)]
let smOverfull = Map.fromList [a 1, b 2, c 10]
assertBool "fits (untouched keys overfull)" $
isOverfull smOverfull
&& smOverfull `hasSlotsFor` Map.fromList [("a", 1), ("b", 1)]
assertBool "empty fitting" $
Map.empty `hasSlotsFor` (Map.empty :: CountMap TestKey)
assertBool "empty not fitting"
. not $ Map.empty `hasSlotsFor` Map.fromList [("a", 1), ("b", 100)]
assertBool "empty not fitting"
. not $ Map.empty `hasSlotsFor` Map.fromList [("a", 1)]
-- | Tests properties of `hasSlotsFor` on `SlotMap`s that are known to
-- respect their limits.
prop_hasSlotsFor_fitting :: Property
prop_hasSlotsFor_fitting =
forAll (genFittingSlotMap genTestKey) $ \sm ->
forAll (genCountMap genTestKey) $ \cm ->
sm `hasSlotsFor` cm ==? not (isOverfull $ sm `occupySlots` cm)
-- | Tests properties of `hasSlotsFor`, irrespective of whether the
-- input `SlotMap`s respect their limits or not.
prop_hasSlotsFor :: Property
prop_hasSlotsFor =
let -- Generates `SlotMap`s for combining.
genMaps = resize 10 $ do -- We don't need very large SlotMaps.
sm1 <- genSlotMap genTestKey
-- We need to make sm2 smaller to make `hasSlots` below more
-- likely (otherwise the LHS of ==> is always false).
sm2 <- sized $ \n -> resize (n `div` 3) (genSlotMap genTestKey)
-- We also want to test (sm1, sm1); we have to make it more
-- likely for it to ever happen.
frequency [ (1, return (sm1, sm1))
, (9, return (sm1, sm2)) ]
in forAll genMaps $ \(sm1, sm2) ->
let fits = sm1 `hasSlotsFor` toCountMap sm2
smOcc = sm1 `occupySlots` toCountMap sm2
oldOverfullBucks = overfullKeys sm1
newOverfullBucks = overfullKeys smOcc
in conjoin
[ counterexample "if there's enough extra space, then the new\
\ overfull keys must be as before" $
fits ==> (newOverfullBucks ==? oldOverfullBucks)
-- Note that the other way around does not hold:
-- (newOverfullBucks == oldOverfullBucks) ==> fits
, counterexample "joining SlotMaps must not change the number of\
\ overfull keys (but may change their slot\
\ counts"
. property $ size newOverfullBucks >= size oldOverfullBucks
]
testSuite "SlotMap"
[ 'case_isOverfull
, 'case_occupySlots_examples
, 'prop_occupySlots
, 'case_hasSlotsFor_examples
, 'prop_hasSlotsFor_fitting
, 'prop_hasSlotsFor
]
|
andir/ganeti
|
test/hs/Test/Ganeti/SlotMap.hs
|
bsd-2-clause
| 8,912 | 0 | 17 | 2,123 | 1,946 | 1,050 | 896 | 138 | 1 |
{-# LANGUAGE TypeFamilies, Rank2Types, ImpredicativeTypes, DataKinds #-}
module Tests.Lazy where
import Prelude hiding (Real)
import Language.Hakaru.Lazy hiding (disintegrate)
import Language.Hakaru.Compose
import Language.Hakaru.Any (Any(Any, unAny))
import Language.Hakaru.Syntax (Hakaru(..), Base(..),
ununit, max_, liftM, liftM2, bind_,
swap_, bern, fst_, not_, equal_, weight,
Mochastic(..), Lambda(..), Integrate(..),
Order_(..))
import Language.Hakaru.PrettyPrint (PrettyPrint, runPrettyPrint, leftMode)
import Language.Hakaru.Simplify (Simplifiable, closeLoop, simplify)
import Language.Hakaru.Expect (Expect(Expect), Expect', normalize, total)
import Language.Hakaru.Maple (Maple)
import Language.Hakaru.Inference
import Tests.TestTools
import qualified Tests.Models as RT
-- import qualified Examples.EasierRoadmap as RM
import Data.Typeable (Typeable)
import Test.HUnit
import qualified Data.List as L
import Text.PrettyPrint
recover :: (Typeable a) => PrettyPrint a -> IO (Any a)
recover hakaru = closeLoop ("Any (" ++ leftMode (runPrettyPrint hakaru) ++ ")")
simp :: (Simplifiable a) => Any a -> IO (Any a)
simp = simplify . unAny
testS' :: (Simplifiable a) => Any a -> Assertion
testS' t = testS (unAny t)
testL
:: (Backward a a, Typeable a, Typeable b,
Simplifiable a, Simplifiable b, Simplifiable env)
=> Cond PrettyPrint env (HMeasure (HPair a b))
-> [(Maple env, Maple a, Any (HMeasure b))]
-> Assertion
testL f slices = do
ds <- mapM recover (runDisintegrate f)
assertResult ds
mapM_ testS' ds
mapM_ (\(env,a,t') ->
testSS [(app (app (unAny d) env) a) | d <- ds] (unAny t')) slices
exists :: PrettyPrint a -> [PrettyPrint a] -> Assertion
exists t ts' = assertBool "no correct disintegration" $
elem (result t) (map result ts')
disp = print . runPrettyPrint
disintegrate :: (Mochastic repr, Backward a a, Lambda repr) =>
(forall s t. Lazy s (Compose [] t repr) (HMeasure (HPair a b)))
-> repr (HFun a (HMeasure b))
disintegrate m = head (runDisintegrate (\u -> ununit u $ m)) `app` unit
runExpect :: (Lambda repr, Base repr) =>
Expect repr (HMeasure HProb) -> repr HProb
runExpect (Expect m) = unpair m (\ m1 m2 -> m2 `app` lam id)
nonDefault
:: (Backward a a)
=> String
-> Cond PrettyPrint env (HMeasure (HPair a b))
-> Assertion
nonDefault s = assertBool "not calling non-default implementation" . any id .
map (L.isInfixOf s . leftMode . runPrettyPrint) . runDisintegrate
justRun :: Test -> IO ()
justRun t = runTestTT t >> return ()
main :: IO ()
main = -- justRun nonDefaultTests
disp (disintegrate burgalarm)
-- | TODO: understand why the following fail to use non-default uniform
-- prog1s, prog2s, prog3s, (const culpepper), t3, t4, t9, marsaglia
nonDefaultTests :: Test
nonDefaultTests = test [ nonDefault "uniform" borelishSub
, nonDefault "uniform" borelishDiv
, nonDefault "uniform" density1
, nonDefault "uniform" density2
, nonDefault "uniform" t1
, nonDefault "uniform" t2
, nonDefault "uniform" t5
, nonDefault "uniform" t6
, nonDefault "uniform" t7
, nonDefault "uniform" t8
, nonDefault "sqrt_" fwdSqrt_
, nonDefault "sqrt" fwdSqrt
, nonDefault "**" fwdPow
, nonDefault "pow_" fwdPow_
, nonDefault "logBase" fwdLogBase
]
-- 2015-04-09
--------------------------------------------------------------------------------
important :: Test
important = test
[ "zeroAddInt" ~: testL zeroAddInt [(unit, 0, Any $ dirac 3)]
, "zeroAddReal" ~: testL zeroAddReal [(unit, 0, Any $ dirac 3)]
-- , "easierRoadmapProg1" ~: testL easierRoadmapProg1 []
]
--------------------------------------------------------------------------------
allTests :: Test
allTests = test
[ -- "easierRoadmapProg1" ~: testL easierRoadmapProg1 []
"normalFB1" ~: testL normalFB1 []
, "normalFB2" ~: testL normalFB2 []
, "zeroDiv" ~: testL zeroDiv [(unit, 0, Any $ dirac 0)]
, "zeroAddInt" ~: testL zeroAddInt [(unit, 0, Any $ dirac 3)]
, "zeroPlusSnd" ~: testL zeroPlusSnd []
, "prog1s" ~: testL prog1s []
, "prog2s" ~: testL prog2s []
, "prog3s" ~: testL prog3s []
, "pair1fst" ~: testL pair1fst []
, "pair1fstSwap" ~: testL pair1fstSwap []
, "borelishSub" ~: testL borelishSub [(unit, 0, Any uniform_0_1)]
, "borelishDiv" ~: testL borelishDiv
[(unit, 1, Any
(superpose [(1/2, liftM fromProb (beta 2 1))]))]
, "culpepper" ~: testL (const culpepper)
[(unit, 0, Any
(superpose [(fromRational (1/8), dirac true)
,(fromRational (1/8), dirac false)]))]
, "beta" ~: testL testBetaConj
[(unit, true, Any
(superpose [(fromRational (1/2), beta 2 1)]))]
, "betaNorm" ~: testSS [testBetaConjNorm] (beta 2 1)
, "testGibbsPropUnif" ~: testS testGibbsPropUnif
, "testGibbs0" ~: testSS [testGibbsProp0]
(lam $ \x ->
normal (x * fromRational (1/2))
(sqrt_ 2 * fromRational (1/2)))
, "testGibbs1" ~: testSS [testGibbsProp1]
(lam $ \x ->
normal (fst_ x) 1 `bind` \y ->
dirac (pair (fst_ x) y))
-- , "testGibbs2" ~: testSS [testGibbsProp2]
-- (lam $ \x ->
-- normal ((snd_ x) * fromRational (1/2))
-- (sqrt_ 2 * fromRational (1/2))
-- `bind` \y ->
-- dirac (pair y (snd_ x)))
, "density1" ~: testL density1 []
, "density2" ~: testL density2 []
-- , "density3" ~: testL density3 []
, "t0" ~: testL t0
[(unit, 1, Any
(superpose
[( recip (sqrt_ pi_) *
exp_ (1 * 1 * fromRational (-1/4)) *
fromRational (1/2)
, normal
(1 * fromRational (1/2))
((sqrt_ 2) * fromRational (1/2)) )]))]
, "t1" ~: testL t1 []
, "t2" ~: testL t2 []
, "t3" ~: testL t3 []
, "t4" ~: testL t4 []
, "t5" ~: testL t5 []
, "t6" ~: testL t6 []
, "t7" ~: testL t7 []
, "t8" ~: testL t8 []
, "t9" ~: testL t9 []
, "t10" ~: testL t10 []
, "marsaglia" ~: testL marsaglia [] -- needs heavy disintegration
]
burgalarm
:: (Mochastic repr)
=> repr (HMeasure (HPair HBool HBool))
burgalarm = bern 0.0001 `bind` \burglary ->
bern (if_ burglary 0.95 0.01) `bind` \alarm ->
dirac (pair alarm burglary)
burgCond :: (Mochastic repr, Lambda repr)
=> repr (HFun HBool (HMeasure HBool))
burgCond = disintegrate burgalarm
burgSimpl = simplify $ disintegrate burgalarm
-- burgObs b = simplify (d `app` unit `app` b)
-- where d:_ = runDisintegrate burgalarm
normalFB1
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HUnit))
normalFB1 = \u -> ununit u $
normal_0_1 `bind` \x ->
normal x 1 `bind` \y ->
dirac (pair ((y + y) + x) unit)
normalFB2
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HUnit))
normalFB2 = \u -> ununit u $
normal_0_1 `bind` \x ->
normal x 1 `bind` \y ->
dirac (pair (y + x) unit)
-- easierRoadmapProg1
-- :: (Mochastic repr)
-- => Cond repr HUnit
-- (HMeasure (HPair (HPair HReal HReal) (HPair HProb HProb)))
-- easierRoadmapProg1 = \u -> ununit u $ RM.easierRoadmapProg1
zeroDiv
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HReal))
zeroDiv = \u -> ununit u $
normal_0_1 `bind` \x ->
dirac (pair x (0 / x))
cushing :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
cushing = \u -> ununit u $
uniform_0_1 `bind` \x ->
if_ (not_ (equal_ x (1/2)))
(uniform 0 x)
(uniform x 1) `bind` \y ->
dirac (pair y x)
cushingObs n = simplify (d `app` unit `app` n)
where d:_ = runDisintegrate cushing
cushingSimpl = mapM simplify (runDisintegrate cushing)
cobb :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
cobb = \u -> ununit u $
uniform_0_1 `bind` \x ->
uniform (-x) x `bind` \y ->
dirac (pair y x)
cobbSimpl = mapM simplify (runDisintegrate cobb)
cobbObs n = simplify (d `app` unit `app` n)
where d:_ = runDisintegrate cobb
cobb0 :: (Mochastic repr, Lambda repr, Integrate repr)
=> Expect repr (HMeasure HProb)
cobb0 = uniform_0_1 `bind` \x0 ->
weight (recip (unsafeProb x0) * (1/2)) $
dirac (unsafeProb x0)
expectCobb0 :: Doc
expectCobb0 = runPrettyPrint (runExpect cobb0)
totalCobb0 :: Doc
totalCobb0 = runPrettyPrint (total cobb0)
thenSimpl1 = simplify $ dirac (total cobb0)
thenSimpl2 = simplify $ dirac (runExpect cobb0)
thenSimpl3 = simplify $ normalize cobb0
zeroAddInt
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HInt HInt))
zeroAddInt = \u -> ununit u $
counting `bind` \x ->
dirac (pair (0+x) 3)
zeroAddReal
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HReal))
zeroAddReal = \u -> ununit u $
lebesgue `bind` \x ->
dirac (pair (0+x) 3)
zeroPlusSnd
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HUnit HReal))
zeroPlusSnd = \u -> ununit u $
normal_0_1 `bind` \x ->
dirac (pair unit (0 + x))
-- Jacques on 2014-11-18: "From an email of Oleg's, could someone please
-- translate the following 3 programs into new Hakaru?" The 3 programs below
-- are equivalent.
prog1s, prog2s, prog3s
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HBool))
prog1s = \u -> ununit u $
bern 0.5 `bind` \c ->
if_ c normal_0_1 (uniform 10 20) `bind` \x ->
dirac (pair x c)
prog2s = \u -> ununit u $
bern 0.5 `bind` \c ->
if_ c normal_0_1
(dirac 10 `bind` \d ->
uniform d 20) `bind` \x ->
dirac (pair x c)
prog3s = \u -> ununit u $
bern 0.5 `bind` \c ->
if_ c normal_0_1
(dirac false `bind` \e ->
uniform (10 + if_ e 1 0) 20) `bind` \x ->
dirac (pair x c)
pair1fst
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HBool HProb))
pair1fst = \u -> ununit u $
beta 1 1 `bind` \bias ->
bern bias `bind` \coin ->
dirac (pair coin bias)
pair1fstSwap
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HProb HBool))
pair1fstSwap = \u -> ununit u $
liftM swap_ $
beta 1 1 `bind` \bias ->
bern bias `bind` \coin ->
dirac (pair coin bias)
borelishSub
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HReal))
borelishSub = const (borelish (-))
borelishDiv
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HReal))
borelishDiv = const (borelish (/))
borelish
:: (Mochastic repr)
=> (repr HReal -> repr HReal -> repr a)
-> repr (HMeasure (HPair a HReal))
borelish comp =
uniform_0_1 `bind` \x ->
uniform_0_1 `bind` \y ->
dirac (pair (comp x y) x)
culpepper :: (Mochastic repr) => repr (HMeasure (HPair HReal HBool))
culpepper = bern 0.5 `bind` \a ->
if_ a (uniform (-2) 2) (liftM (2*) (uniform (-1) 1)) `bind` \b ->
dirac (pair b a)
-- | testBetaConj is like RT.t4, but we condition on the coin coming up true,
-- so a different sampling procedure for the bias is called for.
testBetaConj
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HBool HProb))
testBetaConj = \u -> ununit u $ liftM swap_ RT.t4
-- | This is a test of normalizing post disintegration
testBetaConjNorm
:: (Mochastic repr, Integrate repr, Lambda repr)
=> repr (HMeasure HProb)
testBetaConjNorm = normalize (app (app d unit) true)
where d:_ = runDisintegrate testBetaConj
testGibbsPropUnif
:: (Lambda repr, Mochastic repr, Integrate repr)
=> repr (HFun HReal (HMeasure HReal))
testGibbsPropUnif = lam $ \x -> normalize (app (app d unit) (Expect x))
where d:_ = runDisintegrate (const (liftM swap_ RT.unif2))
testGibbsProp0
:: (Lambda repr, Mochastic repr, Integrate repr)
=> repr (HFun HReal (HMeasure HReal))
testGibbsProp0 = lam $ \x -> normalize (app (app d unit) (Expect x))
where d:_ = runDisintegrate t0
testGibbsProp1
:: (Lambda repr, Mochastic repr, Integrate repr)
=> repr (HFun (HPair HReal HReal) (HMeasure (HPair HReal HReal)))
testGibbsProp1 = lam (gibbsProposal norm)
onSnd
:: (Mochastic repr, Mochastic repr1, Lambda repr)
=> (repr1 (HMeasure (HPair b1 a1))
-> repr (HPair b2 a2)
-> repr (HMeasure (HPair a b)))
-> repr1 (HMeasure (HPair a1 b1))
-> repr (HFun (HPair a2 b2) (HMeasure (HPair b a)))
onSnd tr f = lam (liftM swap_ . tr (liftM swap_ f) . swap_)
-- testGibbsProp2
-- :: (Lambda repr, Mochastic repr, Integrate repr)
-- => repr (HFun (HPair HReal HReal) (HMeasure (HPair HReal HReal)))
-- testGibbsProp2 = lam (liftM swap_ . gibbsProposal (liftM swap_ norm) . swap_)
-- testGibbsProp2 = onSnd gibbsProposal norm
density1
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HUnit))
density1 = \u -> ununit u $
liftM (`pair` unit) $
uniform_0_1 `bind` \x ->
uniform_0_1 `bind` \y ->
dirac (x + exp (-y))
density2
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HUnit))
density2 = \u -> ununit u $
liftM (`pair` unit) $
liftM2 (*) uniform_0_1 $
liftM2 (+) uniform_0_1 uniform_0_1
-- density3
-- :: (Mochastic repr)
-- => Cond repr HUnit (HMeasure (HPair HReal HUnit))
-- density3 = \u -> ununit u $
-- liftM (`pair` unit) $
-- mix [(7, liftM (\x -> x - 1/2 + 0) uniform_0_1),
-- (3, liftM (\x -> (x - 1/2) * 10) uniform_0_1)]
norm :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
norm = \u -> ununit u $ RT.norm
t0 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
t0 = \u -> ununit u $
normal_0_1 `bind` \x ->
normal x 1 `bind` \y ->
dirac (pair y x)
t1 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
t1 = \u -> ununit u $
uniform_0_1 `bind` \x ->
uniform_0_1 `bind` \y ->
dirac (pair (exp x) (y + x))
t2 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
t2 = \u -> ununit u $
uniform_0_1 `bind` \x ->
uniform_0_1 `bind` \y ->
dirac (pair (y + x) (exp x))
t3 :: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal (HPair HReal HReal)))
t3 = \u -> ununit u $
uniform_0_1 `bind` \x ->
uniform_0_1 `bind` \y ->
dirac (pair (max_ x y) (pair x y))
t4 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
t4 = \u -> ununit u $
uniform_0_1 `bind` \x ->
dirac (pair (exp x) (-x))
t5 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HUnit))
t5 = \u -> ununit u $
liftM (`pair` unit) $
let m = superpose (replicate 2 (1, uniform_0_1))
in let add = liftM2 (+)
in add (add m m) m
t6 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
t6 = \u -> ununit u $
uniform_0_1 `bind` \x ->
uniform_0_1 `bind` \y ->
dirac (pair (x+y) (x-y))
t7 :: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal (HMeasure HReal)))
t7 = \u -> ununit u $
uniform_0_1 `bind` \y ->
uniform_0_1 `bind` \x ->
dirac (pair (x+y) (uniform_0_1 `bind_` dirac y))
t8 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
t8 = \u -> ununit u $
dirac (uniform_0_1 `bind` \x -> dirac (1+x)) `bind` \m ->
m `bind` \x ->
m `bind` \y ->
dirac (pair x y)
t9 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HReal))
t9 = \u -> ununit u $
(uniform_0_1 `bind` \x -> dirac (dirac (1+x))) `bind` \m ->
m `bind` \x ->
m `bind` \y ->
dirac (pair x y)
t10 :: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair (HPair HReal HReal) HReal))
t10 = \u -> ununit u $
normal_0_1 `bind` \x ->
plate (vector 10 (\i -> normal x (unsafeProb (fromInt i) + 1))) `bind` \ys ->
dirac (pair (pair (index ys 3) (index ys 4)) x)
marsaglia
:: (Mochastic repr)
=> repr HUnit
-> repr (HMeasure (HPair HReal HUnit))
marsaglia _ =
uniform (-1) 1 `bind` \x ->
uniform (-1) 1 `bind` \y ->
let s = x ** 2 + y ** 2 in
if_ (s `less_` 1)
(dirac (pair (x * sqrt (-2 * log s / s)) unit))
(superpose [])
-- | Show that uniform should not always evaluate its arguments
-- Here disintegrate goes forward on x before going backward on x,
-- causing the failure of the non-default implementation of uniform
-- (which evaluates the lower bound x)
t11 :: (Mochastic repr) => Cond repr HUnit (HMeasure (HPair HReal HUnit))
t11 = \u -> ununit u $
uniform_0_1 `bind` \x ->
uniform x 1 `bind` \y ->
dirac (pair (x + (y + y)) unit)
bwdSqrt_
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HProb HReal))
bwdSqrt_ = \u -> ununit u $
uniform 0 10 `bind` \x ->
dirac (pair (sqrt_ (unsafeProb x)) x)
fwdSqrt_
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HProb))
fwdSqrt_ = \u -> ununit u $
uniform 0 10 `bind` \x ->
dirac (pair x (sqrt_ (unsafeProb x)))
bwdSqrt
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HReal))
bwdSqrt = \u -> ununit u $
uniform 0 10 `bind` \x ->
dirac (pair (sqrt x) x)
fwdSqrt
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HReal))
fwdSqrt = \u -> ununit u $
uniform 0 10 `bind` \x ->
dirac (pair x (sqrt x))
bwdLogBase
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HUnit))
bwdLogBase = \u -> ununit u $
uniform 2 4 `bind` \x ->
uniform 5 7 `bind` \y ->
dirac (pair (logBase x y) unit)
fwdLogBase
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HUnit HReal))
fwdLogBase = \u -> ununit u $
uniform 2 4 `bind` \x ->
uniform 5 7 `bind` \y ->
dirac (pair unit (logBase x y))
bwdPow
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HReal HUnit))
bwdPow = \u -> ununit u $
uniform 2 4 `bind` \x ->
uniform 5 7 `bind` \y ->
dirac (pair (x ** y) unit)
fwdPow
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HUnit HReal))
fwdPow = \u -> ununit u $
uniform 2 4 `bind` \x ->
uniform 5 7 `bind` \y ->
dirac (pair unit (x ** y))
bwdPow_
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HProb HUnit))
bwdPow_ = \u -> ununit u $
uniform 2 4 `bind` \x ->
uniform 5 7 `bind` \y ->
dirac (pair (pow_ (unsafeProb x) y) unit)
fwdPow_
:: (Mochastic repr)
=> Cond repr HUnit (HMeasure (HPair HUnit HProb))
fwdPow_ = \u -> ununit u $
uniform 2 4 `bind` \x ->
uniform 5 7 `bind` \y ->
dirac (pair unit (pow_ (unsafeProb x) y))
|
zaxtax/hakaru
|
haskell/Tests/Lazy.hs
|
bsd-3-clause
| 19,965 | 0 | 24 | 5,974 | 7,476 | 3,972 | 3,504 | 461 | 1 |
{-# language LambdaCase, ViewPatterns, RecordWildCards, OverloadedStrings #-}
module GameEngine.Graphics.GameCharacter where
import Control.Monad
import Data.Char
import Data.List
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as Map
import qualified Data.HashMap.Strict as HashMap
import Data.ByteString.Char8 (ByteString,unpack)
import qualified Data.ByteString.Lazy as LB
import qualified Data.Vector as V
import Text.Printf
import Data.Vect
import Data.Vect.Float.Util.Quaternion
import LambdaCube.GL
import LambdaCube.Linear
import GameEngine.Data.GameCharacter
import GameEngine.Data.MD3
import GameEngine.Loader.MD3
import GameEngine.Loader.GameCharacter
import GameEngine.Loader.Zip
import GameEngine.Graphics.MD3
import GameEngine.Graphics.Frustum
import GameEngine.Utils
{-
character:
skin: default, blue, red -- SKIN
name: anarki
resources:
md3 models: head, upper, lower -- BODYPART
skin: BODYPART_SKIN.skin
animation: animation.cfg
loaded resources:
- we can not reuse/share geometry data because we mutate it's content with current animation frame
FIXME: improve lambdacube-gl API to support update object's stream input
GPUCharacter -- not possible yet
Character
skinMap :: Map String String
head :: GPUMD3
upper :: GPUMD3
lower :: GPUMD3
CharacterInstance
Character
head :: MD3Instance
upper :: MD3Instance
lower :: MD3Instance
setupCharacterInstance
set animation frames
snap part: lower, upper, head
set body part rotation: upper, head
optional: snap weapon to hand
-}
data CharacterInstance
= CharacterInstance
{ characterinstanceCharacter :: Character
, characterinstanceHeadModel :: MD3Instance
, characterinstanceUpperModel :: MD3Instance
, characterinstanceLowerModel :: MD3Instance
}
addCharacterInstance :: Map String Entry -> GLStorage -> String -> String -> IO CharacterInstance
addCharacterInstance pk3 storage name skin = do
let skinName part = printf "models/players/%s/%s_%s.skin" name part skin
modelName part = printf "models/players/%s/%s.md3" name part
animationName = printf "models/players/%s/animation.cfg" name
getEntry n = readEntry =<< case Map.lookup n pk3 of
Nothing -> fail $ printf "file not found: %s" n
Just a -> return a
loadInstance :: String -> IO MD3Instance
loadInstance part = do
model <- readMD3 . LB.fromStrict <$> getEntry (modelName part)
skin <- readMD3Skin <$> getEntry (skinName part)
addMD3 storage model skin ["worldMat","entityRGB","entityAlpha"]
character <- parseCharacter animationName . unpack <$> getEntry animationName >>= \case
Left message -> fail message
Right a -> return a
headInstance <- loadInstance "head"
upperInstance <- loadInstance "upper"
lowerInstance <- loadInstance "lower"
return $ CharacterInstance
{ characterinstanceCharacter = character
, characterinstanceHeadModel = headInstance
, characterinstanceUpperModel = upperInstance
, characterinstanceLowerModel = lowerInstance
}
sampleCharacterAnimation = V.fromList $
[ (TORSO_GESTURE,LEGS_IDLE)
, (TORSO_ATTACK,LEGS_IDLE)
, (TORSO_ATTACK2,LEGS_IDLE)
, (TORSO_DROP,LEGS_IDLE)
, (TORSO_RAISE,LEGS_IDLE)
, (TORSO_STAND,LEGS_IDLE)
, (TORSO_STAND2,LEGS_IDLE)
, (TORSO_GETFLAG,LEGS_IDLE)
, (TORSO_GUARDBASE,LEGS_IDLE)
, (TORSO_PATROL,LEGS_IDLE)
, (TORSO_FOLLOWME,LEGS_IDLE)
, (TORSO_AFFIRMATIVE,LEGS_IDLE)
, (TORSO_NEGATIVE,LEGS_IDLE)
, (TORSO_STAND,LEGS_WALKCR)
, (TORSO_STAND,LEGS_WALK)
, (TORSO_STAND,LEGS_RUN)
, (TORSO_STAND,LEGS_BACK)
, (TORSO_STAND,LEGS_SWIM)
, (TORSO_STAND,LEGS_JUMP)
, (TORSO_STAND,LEGS_LAND)
, (TORSO_STAND,LEGS_JUMPB)
, (TORSO_STAND,LEGS_LANDB)
, (TORSO_STAND,LEGS_IDLE)
, (TORSO_STAND,LEGS_IDLECR)
, (TORSO_STAND,LEGS_TURN)
, (TORSO_STAND,LEGS_BACKCR)
, (TORSO_STAND,LEGS_BACKWALK)
] ++ zip bothAnim bothAnim where bothAnim = [BOTH_DEATH1, BOTH_DEAD1, BOTH_DEATH2, BOTH_DEAD2, BOTH_DEATH3, BOTH_DEAD3]
-- TODO: design proper interface
setupGameCharacter :: CharacterInstance -> Float -> Frustum -> Vec3 -> UnitQuaternion -> Float -> Vec4 -> IO ()
setupGameCharacter CharacterInstance{..} time cameraFrustum position orientation scale rgba = do
let t100 = floor $ time / 4
(torsoAnimType,legAnimType) = sampleCharacterAnimation V.! (t100 `mod` V.length sampleCharacterAnimation)
-- torso = upper
-- transform torso to legs
-- transform head to torso (and legs)
t = floor $ time * 15
Character{..} = characterinstanceCharacter
legAnim = animationMap HashMap.! legAnimType
legFrame = aFirstFrame legAnim + t `mod` aNumFrames legAnim
torsoAnim = animationMap HashMap.! torsoAnimType
torsoFrame = aFirstFrame torsoAnim + t `mod` aNumFrames torsoAnim
rgb = trim rgba
alpha = _4 rgba
worldMat = toWorldMatrix position orientation scale
lcMat :: Proj4 -> M44F
lcMat m = mat4ToM44F . fromProjective $ m .*. rotationEuler (Vec3 (time/5) 0 0) .*. worldMat
tagToProj4 :: Tag -> Proj4
tagToProj4 Tag{..} = translateAfter4 tgOrigin (orthogonal . toOrthoUnsafe $ tgRotationMat)
getTagProj4 :: MD3Instance -> Int -> ByteString -> Proj4
getTagProj4 MD3Instance{..} frame name = case mdTags md3instanceModel V.!? frame >>= HashMap.lookup name of
Nothing -> idmtx
Just tag -> tagToProj4 tag
lowerMat = one :: Proj4
upperMat = getTagProj4 characterinstanceLowerModel legFrame "tag_torso"
headMat = getTagProj4 characterinstanceUpperModel torsoFrame "tag_head" .*. upperMat
--p = trim . _4 $ fromProjective mat
setup m obj = do
--let finalMat = mat4ToM44F . fromProjective $ getTagProj4 characterinstanceUpperModel torsoFrame "tag_head" .*. getTagProj4 characterinstanceLowerModel legFrame "tag_torso" .*. one .*. worldMat
uniformM44F "worldMat" (objectUniformSetter obj) $ lcMat m
uniformV3F "entityRGB" (objectUniformSetter obj) $ vec3ToV3F rgb
uniformFloat "entityAlpha" (objectUniformSetter obj) alpha
enableObject obj $ pointInFrustum position cameraFrustum
--cullObject obj p
-- snap body parts
forM_ (md3instanceObject characterinstanceHeadModel) $ setup headMat
forM_ (md3instanceObject characterinstanceUpperModel) $ setup upperMat
forM_ (md3instanceObject characterinstanceLowerModel) $ setup lowerMat
-- set animation frame geometry
--setMD3Frame hLC frame
setMD3Frame characterinstanceUpperModel torsoFrame
setMD3Frame characterinstanceLowerModel legFrame
|
csabahruska/quake3
|
game-engine/GameEngine/Graphics/GameCharacter.hs
|
bsd-3-clause
| 6,788 | 0 | 16 | 1,378 | 1,422 | 776 | 646 | 118 | 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="fr-FR">
<title>Retest Add-On</title>
<maps>
<homeID>retest</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>
|
kingthorin/zap-extensions
|
addOns/retest/src/main/javahelp/org/zaproxy/addon/retest/resources/help_fr_FR/helpset_fr_FR.hs
|
apache-2.0
| 961 | 77 | 67 | 156 | 411 | 208 | 203 | -1 | -1 |
module Dwarf (
dwarfGen
) where
import CLabel
import CmmExpr ( GlobalReg(..) )
import Config ( cProjectName, cProjectVersion )
import CoreSyn ( Tickish(..) )
import Debug
import DynFlags
import FastString
import Module
import Outputable
import Platform
import Unique
import UniqSupply
import Dwarf.Constants
import Dwarf.Types
import Data.Maybe
import Data.List ( sortBy )
import Data.Ord ( comparing )
import qualified Data.Map as Map
import System.FilePath
import System.Directory ( getCurrentDirectory )
import qualified Compiler.Hoopl as H
-- | Generate DWARF/debug information
dwarfGen :: DynFlags -> ModLocation -> UniqSupply -> [DebugBlock]
-> IO (SDoc, UniqSupply)
dwarfGen _ _ us [] = return (empty, us)
dwarfGen df modLoc us blocks = do
-- Convert debug data structures to DWARF info records
-- We strip out block information, as it is not currently useful for
-- anything. In future we might want to only do this for -g1.
let procs = debugSplitProcs blocks
stripBlocks dbg = dbg { dblBlocks = [] }
compPath <- getCurrentDirectory
let lowLabel = dblCLabel $ head procs
highLabel = mkAsmTempEndLabel $ dblCLabel $ last procs
dwarfUnit = DwarfCompileUnit
{ dwChildren = map (procToDwarf df) (map stripBlocks procs)
, dwName = fromMaybe "" (ml_hs_file modLoc)
, dwCompDir = addTrailingPathSeparator compPath
, dwProducer = cProjectName ++ " " ++ cProjectVersion
, dwLowLabel = lowLabel
, dwHighLabel = highLabel
, dwLineLabel = dwarfLineLabel
}
-- Check whether we have any source code information, so we do not
-- end up writing a pointer to an empty .debug_line section
-- (dsymutil on Mac Os gets confused by this).
let haveSrcIn blk = isJust (dblSourceTick blk) && isJust (dblPosition blk)
|| any haveSrcIn (dblBlocks blk)
haveSrc = any haveSrcIn procs
-- .debug_abbrev section: Declare the format we're using
let abbrevSct = pprAbbrevDecls haveSrc
-- .debug_info section: Information records on procedures and blocks
let -- unique to identify start and end compilation unit .debug_inf
(unitU, us') = takeUniqFromSupply us
infoSct = vcat [ ptext dwarfInfoLabel <> colon
, dwarfInfoSection
, compileUnitHeader unitU
, pprDwarfInfo haveSrc dwarfUnit
, compileUnitFooter unitU
]
-- .debug_line section: Generated mainly by the assembler, but we
-- need to label it
let lineSct = dwarfLineSection $$
ptext dwarfLineLabel <> colon
-- .debug_frame section: Information about the layout of the GHC stack
let (framesU, us'') = takeUniqFromSupply us'
frameSct = dwarfFrameSection $$
ptext dwarfFrameLabel <> colon $$
pprDwarfFrame (debugFrame framesU procs)
-- .aranges section: Information about the bounds of compilation units
let aranges = dwarfARangesSection $$
pprDwarfARange (DwarfARange lowLabel highLabel unitU)
return (infoSct $$ abbrevSct $$ lineSct $$ frameSct $$ aranges, us'')
-- | Header for a compilation unit, establishing global format
-- parameters
compileUnitHeader :: Unique -> SDoc
compileUnitHeader unitU = sdocWithPlatform $ \plat ->
let cuLabel = mkAsmTempLabel unitU -- sits right before initialLength field
length = ppr (mkAsmTempEndLabel cuLabel) <> char '-' <> ppr cuLabel
<> ptext (sLit "-4") -- length of initialLength field
in vcat [ ppr cuLabel <> colon
, ptext (sLit "\t.long ") <> length -- compilation unit size
, pprHalf 3 -- DWARF version
, sectionOffset (ptext dwarfAbbrevLabel) (ptext dwarfAbbrevLabel)
-- abbrevs offset
, ptext (sLit "\t.byte ") <> ppr (platformWordSize plat) -- word size
]
-- | Compilation unit footer, mainly establishing size of debug sections
compileUnitFooter :: Unique -> SDoc
compileUnitFooter unitU =
let cuEndLabel = mkAsmTempEndLabel $ mkAsmTempLabel unitU
in ppr cuEndLabel <> colon
-- | Splits the blocks by procedures. In the result all nested blocks
-- will come from the same procedure as the top-level block.
debugSplitProcs :: [DebugBlock] -> [DebugBlock]
debugSplitProcs b = concat $ H.mapElems $ mergeMaps $ map split b
where mergeMaps = foldr (H.mapUnionWithKey (const (++))) H.mapEmpty
split :: DebugBlock -> H.LabelMap [DebugBlock]
split blk = H.mapInsert prc [blk {dblBlocks = own_blks}] nested
where prc = dblProcedure blk
own_blks = fromMaybe [] $ H.mapLookup prc nested
nested = mergeMaps $ map split $ dblBlocks blk
-- Note that we are rebuilding the tree here, so tick scopes
-- might change. We could fix that - but we actually only care
-- about dblSourceTick in the result, so this is okay.
-- | Generate DWARF info for a procedure debug block
procToDwarf :: DynFlags -> DebugBlock -> DwarfInfo
procToDwarf df prc
= DwarfSubprogram { dwChildren = foldr blockToDwarf [] $ dblBlocks prc
, dwName = case dblSourceTick prc of
Just s@SourceNote{} -> sourceName s
_otherwise -> showSDocDump df $ ppr $ dblLabel prc
, dwLabel = dblCLabel prc
}
-- | Generate DWARF info for a block
blockToDwarf :: DebugBlock -> [DwarfInfo] -> [DwarfInfo]
blockToDwarf blk dws
| isJust (dblPosition blk) = dw : dws
| otherwise = nested ++ dws -- block was optimized out, flatten
where nested = foldr blockToDwarf [] $ dblBlocks blk
dw = DwarfBlock { dwChildren = nested
, dwLabel = dblCLabel blk
, dwMarker = mkAsmTempLabel (dblLabel blk)
}
-- | Generates the data for the debug frame section, which encodes the
-- desired stack unwind behaviour for the debugger
debugFrame :: Unique -> [DebugBlock] -> DwarfFrame
debugFrame u procs
= DwarfFrame { dwCieLabel = mkAsmTempLabel u
, dwCieInit = initUws
, dwCieProcs = map (procToFrame initUws) procs
}
where initUws = Map.fromList [(Sp, UwReg Sp 0)]
-- | Generates unwind information for a procedure debug block
procToFrame :: UnwindTable -> DebugBlock -> DwarfFrameProc
procToFrame initUws blk
= DwarfFrameProc { dwFdeProc = dblCLabel blk
, dwFdeHasInfo = dblHasInfoTbl blk
, dwFdeBlocks = map (uncurry blockToFrame) blockUws
}
where blockUws :: [(DebugBlock, UnwindTable)]
blockUws = map snd $ sortBy (comparing fst) $ flatten initUws blk
flatten uws0 b@DebugBlock{ dblPosition=pos, dblUnwind=uws,
dblBlocks=blocks }
| Just p <- pos = (p, (b, uws')):nested
| otherwise = nested -- block was optimized out
where uws' = uws `Map.union` uws0
nested = concatMap (flatten uws') blocks
blockToFrame :: DebugBlock -> UnwindTable -> DwarfFrameBlock
blockToFrame blk uws
= DwarfFrameBlock { dwFdeBlock = mkAsmTempLabel $ dblLabel blk
, dwFdeBlkHasInfo = dblHasInfoTbl blk
, dwFdeUnwind = uws
}
|
acowley/ghc
|
compiler/nativeGen/Dwarf.hs
|
bsd-3-clause
| 7,485 | 0 | 16 | 2,162 | 1,601 | 853 | 748 | 121 | 2 |
{- |
Module : Language.Egison.MList
Licence : MIT
This module provides definition and utility functions for monadic list.
-}
module Language.Egison.MList
( MList (..)
, fromList
, fromSeq
, fromMList
, msingleton
, mfoldr
, mappend
, mconcat
, mmap
, mfor
, mAny
) where
import Data.Sequence (Seq)
import Prelude hiding (mappend, mconcat)
data MList m a = MNil | MCons a (m (MList m a))
instance Show a => Show (MList m a) where
show MNil = "MNil"
show (MCons x _) = "(MCons " ++ show x ++ " ...)"
fromList :: Monad m => [a] -> MList m a
fromList = foldr f MNil
where f x xs = MCons x $ return xs
fromSeq :: Monad m => Seq a -> MList m a
fromSeq = foldr f MNil
where f x xs = MCons x $ return xs
fromMList :: Monad m => MList m a -> m [a]
fromMList = mfoldr f $ return []
where f x xs = (x:) <$> xs
msingleton :: Monad m => a -> MList m a
msingleton = flip MCons $ return MNil
mfoldr :: Monad m => (a -> m b -> m b) -> m b -> MList m a -> m b
mfoldr _ init MNil = init
mfoldr f init (MCons x xs) = f x (xs >>= mfoldr f init)
mappend :: Monad m => MList m a -> m (MList m a) -> m (MList m a)
mappend xs ys = mfoldr ((return .) . MCons) ys xs
mconcat :: Monad m => MList m (MList m a) -> m (MList m a)
mconcat = mfoldr mappend $ return MNil
mmap :: Monad m => (a -> m b) -> MList m a -> m (MList m b)
mmap f = mfoldr g $ return MNil
where g x xs = flip MCons xs <$> f x
mfor :: Monad m => MList m a -> (a -> m b) -> m (MList m b)
mfor = flip mmap
mAny :: Monad m => (a -> m Bool) -> MList m a -> m Bool
mAny _ MNil = return False
mAny p (MCons x xs) = do
b <- p x
if b
then return True
else do xs' <- xs
mAny p xs'
|
egison/egison
|
hs-src/Language/Egison/MList.hs
|
mit
| 1,733 | 0 | 10 | 505 | 850 | 421 | 429 | 49 | 2 |
{-# Language TypeSynonymInstances, FlexibleInstances, GeneralizedNewtypeDeriving,
MultiParamTypeClasses, UndecidableInstances, DeriveDataTypeable,
TypeFamilies, TupleSections #-}
{- |
Module : Language.Egison.Types
Copyright : Satoshi Egi
Licence : MIT
This module contains type definitions of Egison Data.
-}
module Language.Egison.Types
(
-- * Egison expressions
EgisonTopExpr (..)
, EgisonExpr (..)
, EgisonPattern (..)
, InnerExpr (..)
, BindingExpr (..)
, MatchClause (..)
, MatcherInfo (..)
, LoopRange (..)
, PrimitivePatPattern (..)
, PrimitiveDataPattern (..)
-- * Egison values
, EgisonValue (..)
, Matcher (..)
, PrimitiveFunc (..)
, EgisonData (..)
, showTSV
, addInteger
, subInteger
, mulInteger
, addInteger'
, subInteger'
, mulInteger'
, reduceFraction
-- * Internal data
, Object (..)
, ObjectRef (..)
, WHNFData (..)
, Intermediate (..)
, Inner (..)
, EgisonWHNF (..)
-- * Environment
, Env (..)
, Var (..)
, Binding (..)
, nullEnv
, extendEnv
, refVar
-- * Pattern matching
, Match
, PMMode (..)
, pmMode
, MatchingState (..)
, MatchingTree (..)
, PatternBinding (..)
, LoopPatContext (..)
-- * Errors
, EgisonError (..)
, liftError
-- * Monads
, EgisonM (..)
, runEgisonM
, liftEgisonM
, fromEgisonM
, FreshT (..)
, Fresh (..)
, MonadFresh (..)
, runFreshT
, MatchM (..)
, matchFail
, MList (..)
, fromList
, fromSeq
, fromMList
, msingleton
, mfoldr
, mappend
, mconcat
, mmap
, mfor
) where
import Prelude hiding (foldr, mappend, mconcat)
import Control.Exception
import Data.Typeable
import Control.Applicative
import Control.Monad.Error
import Control.Monad.State
import Control.Monad.Reader (ReaderT)
import Control.Monad.Writer (WriterT)
import Control.Monad.Identity
import Control.Monad.Trans.Maybe
import Data.Monoid (Monoid)
import qualified Data.Array as Array
import qualified Data.Sequence as Sq
import Data.Sequence (Seq)
import Data.Foldable (foldr, toList)
import Data.IORef
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.List (intercalate)
import Data.Text (Text)
import qualified Data.Text as T
import System.IO
import Data.Ratio
import Numeric
import System.IO.Unsafe (unsafePerformIO)
--
-- Expressions
--
data EgisonTopExpr =
Define String EgisonExpr
| Test EgisonExpr
| Execute EgisonExpr
-- temporary : we will replace load to import and export
| LoadFile String
| Load String
deriving (Show)
data EgisonExpr =
CharExpr Char
| StringExpr Text
| BoolExpr Bool
| NumberExpr (Integer, Integer) (Integer, Integer)
| FloatExpr Double Double
| VarExpr String
| IndexedExpr EgisonExpr [EgisonExpr]
| InductiveDataExpr String [EgisonExpr]
| TupleExpr [EgisonExpr]
| CollectionExpr [InnerExpr]
| ArrayExpr [EgisonExpr]
| HashExpr [(EgisonExpr, EgisonExpr)]
| LambdaExpr [String] EgisonExpr
| MemoizedLambdaExpr [String] EgisonExpr
| MemoizeExpr [(EgisonExpr, EgisonExpr, EgisonExpr)] EgisonExpr
| PatternFunctionExpr [String] EgisonPattern
| IfExpr EgisonExpr EgisonExpr EgisonExpr
| LetRecExpr [BindingExpr] EgisonExpr
| LetExpr [BindingExpr] EgisonExpr
| LetStarExpr [BindingExpr] EgisonExpr
| MatchExpr EgisonExpr EgisonExpr [MatchClause]
| MatchAllExpr EgisonExpr EgisonExpr MatchClause
| MatchLambdaExpr EgisonExpr [MatchClause]
| MatchAllLambdaExpr EgisonExpr MatchClause
| NextMatchExpr EgisonExpr EgisonExpr [MatchClause]
| NextMatchAllExpr EgisonExpr EgisonExpr MatchClause
| NextMatchLambdaExpr EgisonExpr [MatchClause]
| NextMatchAllLambdaExpr EgisonExpr MatchClause
| MatcherBFSExpr MatcherInfo
| MatcherDFSExpr MatcherInfo
| DoExpr [BindingExpr] EgisonExpr
| IoExpr EgisonExpr
| SeqExpr EgisonExpr EgisonExpr
| ContExpr
| ApplyExpr EgisonExpr EgisonExpr
| PartialExpr Integer EgisonExpr
| PartialVarExpr Integer
| RecVarExpr
| AlgebraicDataMatcherExpr [(String, [EgisonExpr])]
| GenerateArrayExpr [String] EgisonExpr EgisonExpr
| ArraySizeExpr EgisonExpr
| ArrayRefExpr EgisonExpr EgisonExpr
| SomethingExpr
| UndefinedExpr
deriving (Show)
data InnerExpr =
ElementExpr EgisonExpr
| SubCollectionExpr EgisonExpr
deriving (Show)
type BindingExpr = ([String], EgisonExpr)
type MatchClause = (EgisonPattern, EgisonExpr)
type MatcherInfo = [(PrimitivePatPattern, EgisonExpr, [(PrimitiveDataPattern, EgisonExpr)])]
data EgisonPattern =
WildCard
| PatVar String
| ValuePat EgisonExpr
| RegexPat EgisonExpr
| PredPat EgisonExpr
| IndexedPat EgisonPattern [EgisonExpr]
| LetPat [BindingExpr] EgisonPattern
| NotPat EgisonPattern
| AndPat [EgisonPattern]
| OrPat [EgisonPattern]
| OrderedOrPat [EgisonPattern]
| TuplePat [EgisonPattern]
| InductivePat String [EgisonPattern]
| LoopPat String LoopRange EgisonPattern EgisonPattern
| ContPat
| ApplyPat EgisonExpr [EgisonPattern]
| VarPat String
deriving (Show)
data LoopRange = LoopRange EgisonExpr EgisonExpr EgisonPattern
deriving (Show)
data PrimitivePatPattern =
PPWildCard
| PPPatVar
| PPValuePat String
| PPInductivePat String [PrimitivePatPattern]
deriving (Show)
data PrimitiveDataPattern =
PDWildCard
| PDPatVar String
| PDInductivePat String [PrimitiveDataPattern]
| PDEmptyPat
| PDConsPat PrimitiveDataPattern PrimitiveDataPattern
| PDSnocPat PrimitiveDataPattern PrimitiveDataPattern
| PDConstantPat EgisonExpr
deriving (Show)
--
-- Values
--
data EgisonValue =
World
| Char Char
| String Text
| Bool Bool
| Number (Integer, Integer) (Integer, Integer)
| Float Double Double
| InductiveData String [EgisonValue]
| Tuple [EgisonValue]
| Collection (Seq EgisonValue)
| Array (Array.Array Integer EgisonValue)
| IntHash (HashMap Integer EgisonValue)
| CharHash (HashMap Char EgisonValue)
| StrHash (HashMap Text EgisonValue)
| UserMatcher Env PMMode MatcherInfo
| Func Env [String] EgisonExpr
| MemoizedFunc ObjectRef (IORef (HashMap [Integer] ObjectRef)) Env [String] EgisonExpr
| PatternFunc Env [String] EgisonPattern
| PrimitiveFunc PrimitiveFunc
| IOFunc (EgisonM WHNFData)
| Port Handle
| Something
| Undefined
| EOF
type Matcher = EgisonValue
type PrimitiveFunc = WHNFData -> EgisonM WHNFData
instance Show EgisonValue where
show (Char c) = "'" ++ [c] ++ "'"
show (String str) = "\"" ++ T.unpack str ++ "\""
show (Bool True) = "#t"
show (Bool False) = "#f"
show (Number (x,y) (1,0)) = showComplex x y
show (Number (x,y) (x',y')) = showComplex x y ++ "/" ++ showComplex x' y'
show (Float x y) = showComplexFloat x y
show (InductiveData name []) = "<" ++ name ++ ">"
show (InductiveData name vals) = "<" ++ name ++ " " ++ unwords (map show vals) ++ ">"
show (Tuple vals) = "[" ++ unwords (map show vals) ++ "]"
show (Collection vals) = if Sq.null vals
then "{}"
else "{" ++ unwords (map show (toList vals)) ++ "}"
show (Array vals) = "[|" ++ unwords (map show $ Array.elems vals) ++ "|]"
show (IntHash hash) = "{|" ++ unwords (map (\(key, val) -> "[" ++ show key ++ " " ++ show val ++ "]") $ HashMap.toList hash) ++ "|}"
show (CharHash hash) = "{|" ++ unwords (map (\(key, val) -> "[" ++ show key ++ " " ++ show val ++ "]") $ HashMap.toList hash) ++ "|}"
show (StrHash hash) = "{|" ++ unwords (map (\(key, val) -> "[\"" ++ T.unpack key ++ "\" " ++ show val ++ "]") $ HashMap.toList hash) ++ "|}"
show (UserMatcher _ BFSMode _) = "#<matcher-bfs>"
show (UserMatcher _ DFSMode _) = "#<matcher-dfs>"
show (Func _ names _) = "(lambda [" ++ unwords names ++ "] ...)"
show (MemoizedFunc _ _ _ names _) = "(memoized-lambda [" ++ unwords names ++ "] ...)"
show (PatternFunc _ _ _) = "#<pattern-function>"
show (PrimitiveFunc _) = "#<primitive-function>"
show (IOFunc _) = "#<io-function>"
show (Port _) = "#<port>"
show Something = "something"
show Undefined = "undefined"
show World = "#<world>"
show EOF = "#<eof>"
addInteger :: EgisonValue -> EgisonValue -> EgisonValue
addInteger (Number (x,y) (1,0)) (Number (x',y') (1,0)) = Number ((x+x'),(y+y')) (1,0)
subInteger :: EgisonValue -> EgisonValue -> EgisonValue
subInteger (Number (x,y) (1,0)) (Number (x',y') (1,0)) = Number ((x-x'),(y-y')) (1,0)
mulInteger :: EgisonValue -> EgisonValue -> EgisonValue
mulInteger (Number (x,y) (1,0)) (Number (x',y') (1,0)) = Number ((x*x'-y*y'),(x*y'+x'*y)) (1,0)
addInteger' :: (Integer, Integer) -> (Integer, Integer) -> (Integer, Integer)
addInteger' (x,y) (x',y') = ((x+x'),(y+y'))
subInteger' :: (Integer, Integer) -> (Integer, Integer) -> (Integer, Integer)
subInteger' (x,y) (x',y') = ((x-x'),(y-y'))
mulInteger' :: (Integer, Integer) -> (Integer, Integer) -> (Integer, Integer)
mulInteger' (x,y) (x',y') = ((x*x'-y*y'),(x*y'+x'*y))
showComplex :: (Num a, Eq a, Ord a, Show a) => a -> a -> String
showComplex x 0 = show x
showComplex 0 y = show y ++ "i"
showComplex x y = show x ++ (if y > 0 then "+" else "") ++ show y ++ "i"
showComplexFloat :: Double -> Double -> String
showComplexFloat x 0.0 = showFFloat Nothing x ""
showComplexFloat 0.0 y = showFFloat Nothing y "i"
showComplexFloat x y = (showFFloat Nothing x "") ++ (if y > 0 then "+" else "") ++ (showFFloat Nothing y "i")
reduceFraction :: EgisonValue -> EgisonValue
reduceFraction (Number (x,y) (x',y'))
| x' < 0 = let m = negate (foldl gcd x [y, x', y']) in
Number (x `quot` m, y `quot` m) (x' `quot` m, y' `quot` m)
| x' > 0 = let m = foldl gcd x [y, x', y'] in
Number (x `quot` m, y `quot` m) (x' `quot` m, y' `quot` m)
| x' == 0 && y' < 0 = let m = negate (foldl gcd x [y, x', y']) in
Number (x `quot` m, y `quot` m) (x' `quot` m, y' `quot` m)
| x' == 0 && y' > 0 = let m = foldl gcd x [y, x', y'] in
Number (x `quot` m, y `quot` m) (x' `quot` m, y' `quot` m)
| x' == 0 && y' == 0 = Number (1,0) (0,0)
showTSV :: EgisonValue -> String
showTSV (Tuple (val:vals)) = foldl (\r x -> r ++ "\t" ++ x) (show val) (map showTSV vals)
showTSV (Collection vals) = intercalate "\t" (map showTSV (toList vals))
showTSV val = show val
instance Eq EgisonValue where
(Char c) == (Char c') = c == c'
(String str) == (String str') = str == str'
(Bool b) == (Bool b') = b == b'
(Number (x1,y1) (x1',y1')) == (Number (x2,y2) (x2',y2')) = (x1 == x2) && (y1 == y2) && (x1' == x2') && (y1' == y2')
(Float x y) == (Float x' y') = (x == x') && (y == y')
(InductiveData name vals) == (InductiveData name' vals') = (name == name') && (vals == vals')
(Tuple vals) == (Tuple vals') = vals == vals'
(Collection vals) == (Collection vals') = vals == vals'
(Array vals) == (Array vals') = vals == vals'
(IntHash vals) == (IntHash vals') = vals == vals'
(CharHash vals) == (CharHash vals') = vals == vals'
(StrHash vals) == (StrHash vals') = vals == vals'
_ == _ = False
--
-- Egison data and Haskell data
--
class EgisonData a where
toEgison :: a -> EgisonValue
fromEgison :: EgisonValue -> EgisonM a
instance EgisonData Char where
toEgison c = Char c
fromEgison = liftError . fromCharValue
instance EgisonData Text where
toEgison str = String str
fromEgison = liftError . fromStringValue
instance EgisonData Bool where
toEgison b = Bool b
fromEgison = liftError . fromBoolValue
instance EgisonData Integer where
toEgison i = Number (i, 0) (1, 0)
fromEgison = liftError . fromIntegerValue
instance EgisonData Rational where
toEgison r = Number ((numerator r), 0) ((denominator r), 0)
fromEgison = liftError . fromRationalValue
instance EgisonData Double where
toEgison f = Float f 0
fromEgison = liftError . fromFloatValue
instance EgisonData Handle where
toEgison h = Port h
fromEgison = liftError . fromPortValue
instance (EgisonData a) => EgisonData [a] where
toEgison xs = Collection $ Sq.fromList (map toEgison xs)
fromEgison (Collection seq) = mapM fromEgison (toList seq)
fromEgison val = liftError $ throwError $ TypeMismatch "collection" (Value val)
instance EgisonData () where
toEgison () = Tuple []
fromEgison (Tuple []) = return ()
fromEgison val = liftError $ throwError $ TypeMismatch "zero element tuple" (Value val)
instance (EgisonData a, EgisonData b) => EgisonData (a, b) where
toEgison (x, y) = Tuple [toEgison x, toEgison y]
fromEgison (Tuple (x:y:[])) = (liftM2 (,)) (fromEgison x) (fromEgison y)
fromEgison val = liftError $ throwError $ TypeMismatch "two elements tuple" (Value val)
instance (EgisonData a, EgisonData b, EgisonData c) => EgisonData (a, b, c) where
toEgison (x, y, z) = Tuple [toEgison x, toEgison y, toEgison z]
fromEgison (Tuple (x:y:z:[])) = do
x' <- fromEgison x
y' <- fromEgison y
z' <- fromEgison z
return (x', y', z')
fromEgison val = liftError $ throwError $ TypeMismatch "two elements tuple" (Value val)
instance (EgisonData a, EgisonData b, EgisonData c, EgisonData d) => EgisonData (a, b, c, d) where
toEgison (x, y, z, w) = Tuple [toEgison x, toEgison y, toEgison z, toEgison w]
fromEgison (Tuple (x:y:z:w:[])) = do
x' <- fromEgison x
y' <- fromEgison y
z' <- fromEgison z
w' <- fromEgison w
return (x', y', z', w')
fromEgison val = liftError $ throwError $ TypeMismatch "two elements tuple" (Value val)
fromCharValue :: EgisonValue -> Either EgisonError Char
fromCharValue (Char c) = return c
fromCharValue val = throwError $ TypeMismatch "char" (Value val)
fromStringValue :: EgisonValue -> Either EgisonError Text
fromStringValue (String str) = return str
fromStringValue val = throwError $ TypeMismatch "string" (Value val)
fromBoolValue :: EgisonValue -> Either EgisonError Bool
fromBoolValue (Bool b) = return b
fromBoolValue val = throwError $ TypeMismatch "bool" (Value val)
fromIntegerValue :: EgisonValue -> Either EgisonError Integer
fromIntegerValue (Number (x, 0) (1, 0)) = return x
fromIntegerValue val = throwError $ TypeMismatch "integer" (Value val)
fromRationalValue :: EgisonValue -> Either EgisonError Rational
fromRationalValue (Number (x, 0) (y, 0)) = return (x % y)
fromRationalValue val = throwError $ TypeMismatch "rational" (Value val)
fromFloatValue :: EgisonValue -> Either EgisonError Double
fromFloatValue (Float f 0) = return f
fromFloatValue val = throwError $ TypeMismatch "float" (Value val)
fromPortValue :: EgisonValue -> Either EgisonError Handle
fromPortValue (Port h) = return h
fromPortValue val = throwError $ TypeMismatch "port" (Value val)
--
-- Internal Data
--
-- |For memoization
type ObjectRef = IORef Object
data Object =
Thunk (EgisonM WHNFData)
| WHNF WHNFData
data WHNFData =
Intermediate Intermediate
| Value EgisonValue
data Intermediate =
IInductiveData String [ObjectRef]
| ITuple [ObjectRef]
| ICollection (IORef (Seq Inner))
| IArray (Array.Array Integer ObjectRef)
| IIntHash (HashMap Integer ObjectRef)
| ICharHash (HashMap Char ObjectRef)
| IStrHash (HashMap Text ObjectRef)
data Inner =
IElement ObjectRef
| ISubCollection ObjectRef
instance Show WHNFData where
show (Value val) = show val
show (Intermediate (IInductiveData name _)) = "<" ++ name ++ " ...>"
show (Intermediate (ITuple _)) = "[...]"
show (Intermediate (ICollection _)) = "{...}"
show (Intermediate (IArray _)) = "[|...|]"
show (Intermediate (IIntHash _)) = "{|...|}"
show (Intermediate (ICharHash _)) = "{|...|}"
show (Intermediate (IStrHash _)) = "{|...|}"
instance Show Object where
show (Thunk _) = "#<thunk>"
show (WHNF whnf) = show whnf
instance Show ObjectRef where
show _ = "#<ref>"
--
-- Extract data from WHNF
--
class (EgisonData a) => EgisonWHNF a where
toWHNF :: a -> WHNFData
fromWHNF :: WHNFData -> EgisonM a
toWHNF = Value . toEgison
instance EgisonWHNF Char where
fromWHNF = liftError . fromCharWHNF
instance EgisonWHNF Text where
fromWHNF = liftError . fromStringWHNF
instance EgisonWHNF Bool where
fromWHNF = liftError . fromBoolWHNF
instance EgisonWHNF Integer where
fromWHNF = liftError . fromIntegerWHNF
instance EgisonWHNF Rational where
fromWHNF = liftError . fromRationalWHNF
instance EgisonWHNF Double where
fromWHNF = liftError . fromFloatWHNF
instance EgisonWHNF Handle where
fromWHNF = liftError . fromPortWHNF
fromCharWHNF :: WHNFData -> Either EgisonError Char
fromCharWHNF (Value (Char c)) = return c
fromCharWHNF whnf = throwError $ TypeMismatch "char" whnf
fromStringWHNF :: WHNFData -> Either EgisonError Text
fromStringWHNF (Value (String str)) = return str
fromStringWHNF whnf = throwError $ TypeMismatch "string" whnf
fromBoolWHNF :: WHNFData -> Either EgisonError Bool
fromBoolWHNF (Value (Bool b)) = return b
fromBoolWHNF whnf = throwError $ TypeMismatch "bool" whnf
fromIntegerWHNF :: WHNFData -> Either EgisonError Integer
fromIntegerWHNF (Value (Number (x, 0) (1, 0))) = return x
fromIntegerWHNF whnf = throwError $ TypeMismatch "integer" whnf
fromRationalWHNF :: WHNFData -> Either EgisonError Rational
fromRationalWHNF (Value (Number (x, 0) (y, 0))) = return (x % y)
fromRationalWHNF whnf = throwError $ TypeMismatch "rational" whnf
fromFloatWHNF :: WHNFData -> Either EgisonError Double
fromFloatWHNF (Value (Float f 0)) = return f
fromFloatWHNF whnf = throwError $ TypeMismatch "float" whnf
fromPortWHNF :: WHNFData -> Either EgisonError Handle
fromPortWHNF (Value (Port h)) = return h
fromPortWHNF whnf = throwError $ TypeMismatch "port" whnf
class (EgisonWHNF a) => EgisonObject a where
toObject :: a -> Object
toObject = WHNF . toWHNF
--
-- Environment
--
type Env = [HashMap Var ObjectRef]
type Var = String
type Binding = (Var, ObjectRef)
nullEnv :: Env
nullEnv = []
extendEnv :: Env -> [Binding] -> Env
extendEnv env = (: env) . HashMap.fromList
refVar :: Env -> Var -> EgisonM ObjectRef
refVar env var = maybe (throwError $ UnboundVariable var) return
(msum $ map (HashMap.lookup var) env)
--
-- Pattern Match
--
type Match = [Binding]
data PMMode = BFSMode | DFSMode
deriving (Show)
pmMode :: Matcher -> PMMode
pmMode (UserMatcher _ mode _) = mode
pmMode (Tuple _) = DFSMode
pmMode Something = DFSMode
data MatchingState = MState Env [LoopPatContext] [Binding] [MatchingTree]
deriving (Show)
data MatchingTree =
MAtom EgisonPattern ObjectRef Matcher
| MNode [PatternBinding] MatchingState
deriving (Show)
type PatternBinding = (Var, EgisonPattern)
data LoopPatContext = LoopPatContext Binding ObjectRef EgisonPattern EgisonPattern EgisonPattern
deriving (Show)
--
-- Errors
--
data EgisonError =
UnboundVariable Var
| TypeMismatch String WHNFData
| ArgumentsNumWithNames [String] Int Int
| ArgumentsNumPrimitive Int Int
| ArgumentsNum Int Int
| NotImplemented String
| Assertion String
| Match String
| Parser String
| Desugar String
| EgisonBug String
| Default String
deriving Typeable
instance Show EgisonError where
show (Parser err) = "Parse error at: " ++ err
show (UnboundVariable var) = "Unbound variable: " ++ var
show (TypeMismatch expected found) = "Expected " ++ expected ++
", but found: " ++ show found
show (ArgumentsNumWithNames names expected got) = "Wrong number of arguments: " ++ show names ++ ": expected " ++
show expected ++ ", but got " ++ show got
show (ArgumentsNumPrimitive expected got) = "Wrong number of arguments for a primitive function: expected " ++
show expected ++ ", but got " ++ show got
show (ArgumentsNum expected got) = "Wrong number of arguments: expected " ++
show expected ++ ", but got " ++ show got
show (NotImplemented message) = "Not implemented: " ++ message
show (Assertion message) = "Assertion failed: " ++ message
show (Desugar message) = "Error: " ++ message
show (EgisonBug message) = "Egison Error: " ++ message
show (Default message) = "Error: " ++ message
instance Exception EgisonError
instance Error EgisonError where
noMsg = Default "An error has occurred"
strMsg = Default
liftError :: (MonadError e m) => Either e a -> m a
liftError = either throwError return
--
-- Monads
--
newtype EgisonM a = EgisonM {
unEgisonM :: ErrorT EgisonError (FreshT IO) a
} deriving (Functor, Applicative, Monad, MonadIO, MonadError EgisonError, MonadFresh)
runEgisonM :: EgisonM a -> FreshT IO (Either EgisonError a)
runEgisonM = runErrorT . unEgisonM
liftEgisonM :: Fresh (Either EgisonError a) -> EgisonM a
liftEgisonM m = EgisonM $ ErrorT $ FreshT $ do
s <- get
(a, s') <- return $ runFresh s m
put s'
return $ either throwError return $ a
fromEgisonM :: EgisonM a -> IO (Either EgisonError a)
fromEgisonM = modifyCounter . runEgisonM
counter :: IORef Int
counter = unsafePerformIO (newIORef 0)
readCounter :: IO Int
readCounter = readIORef counter
updateCounter :: Int -> IO ()
updateCounter = writeIORef counter
modifyCounter :: FreshT IO a -> IO a
modifyCounter m = do
seed <- readCounter
(result, seed) <- runFreshT seed m
updateCounter seed
return result
newtype FreshT m a = FreshT { unFreshT :: StateT Int m a }
deriving (Functor, Applicative, Monad, MonadState Int, MonadTrans)
type Fresh = FreshT Identity
class (Applicative m, Monad m) => MonadFresh m where
fresh :: m String
instance (Applicative m, Monad m) => MonadFresh (FreshT m) where
fresh = FreshT $ do counter <- get; modify (+ 1)
return $ "$_" ++ show counter
instance (MonadError e m) => MonadError e (FreshT m) where
throwError = lift . throwError
catchError m h = FreshT $ catchError (unFreshT m) (unFreshT . h)
instance (MonadState s m) => MonadState s (FreshT m) where
get = lift $ get
put s = lift $ put s
instance (MonadFresh m) => MonadFresh (StateT s m) where
fresh = lift $ fresh
instance (MonadFresh m, Error e) => MonadFresh (ErrorT e m) where
fresh = lift $ fresh
instance (MonadFresh m, Monoid e) => MonadFresh (ReaderT e m) where
fresh = lift $ fresh
instance (MonadFresh m, Monoid e) => MonadFresh (WriterT e m) where
fresh = lift $ fresh
instance MonadIO (FreshT IO) where
liftIO = lift
runFreshT :: Monad m => Int -> FreshT m a -> m (a, Int)
runFreshT seed = flip (runStateT . unFreshT) seed
runFresh :: Int -> Fresh a -> (a, Int)
runFresh seed m = runIdentity $ flip runStateT seed $ unFreshT m
type MatchM = MaybeT EgisonM
matchFail :: MatchM a
matchFail = MaybeT $ return Nothing
data MList m a = MNil | MCons a (m (MList m a))
instance Show (MList m a) where
show MNil = "MNil"
show (MCons _ _) = "(MCons ... ...)"
fromList :: Monad m => [a] -> MList m a
fromList = foldr f MNil
where f x xs = MCons x $ return xs
fromSeq :: Monad m => Seq a -> MList m a
fromSeq = foldr f MNil
where f x xs = MCons x $ return xs
fromMList :: Monad m => MList m a -> m [a]
fromMList = mfoldr f $ return []
where f x xs = xs >>= return . (x:)
msingleton :: Monad m => a -> MList m a
msingleton = flip MCons $ return MNil
mfoldr :: Monad m => (a -> m b -> m b) -> m b -> MList m a -> m b
mfoldr f init MNil = init
mfoldr f init (MCons x xs) = f x (xs >>= mfoldr f init)
mappend :: Monad m => MList m a -> m (MList m a) -> m (MList m a)
mappend xs ys = mfoldr ((return .) . MCons) ys xs
mconcat :: Monad m => MList m (MList m a) -> m (MList m a)
mconcat = mfoldr mappend $ return MNil
mmap :: Monad m => (a -> m b) -> MList m a -> m (MList m b)
mmap f = mfoldr g $ return MNil
where g x xs = f x >>= return . flip MCons xs
mfor :: Monad m => MList m a -> (a -> m b) -> m (MList m b)
mfor = flip mmap
|
beni55/egison
|
hs-src/Language/Egison/Types.hs
|
mit
| 23,935 | 0 | 19 | 5,086 | 8,785 | 4,703 | 4,082 | 587 | 2 |
module GUBS.Solve.SCC (sccDecompose, sccDecomposeWith, chainWith) where
import qualified Text.PrettyPrint.ANSI.Leijen as PP
import GUBS.Algebra
import qualified GUBS.ConstraintSystem as CS
import GUBS.Solve.Simplify (partiallyInterpret)
import GUBS.Solve.Strategy
sccDecompose :: (Eq f, Monad m) => Processor f c v m -> Processor f c v m
sccDecompose = sccDecomposeWith CS.sccs
sccDecomposeWith :: Monad m => (CS.ConstraintSystem f v -> [CS.ConstraintSystem f v]) -> Processor f c v m -> Processor f c v m
sccDecomposeWith f p cs =
case f cs of
[] -> return NoProgress
(scc:sccs) -> do
logMsg ("SCC: " ++ show (length sccs + 1) ++ " SCCs")
toResult sccs <$> p scc
where
toResult sccs (Progress []) = Progress (concat sccs)
toResult _ _ = NoProgress
-- @chainWith f p cs@ behaves similar to @try (exhaustive (sccDecomposeWith f p cs))@; but decomposition is applied
-- only once.
chainWith :: (Ord f, Ord v, Monad m, Integral c) => (CS.ConstraintSystem f v -> [[CS.TermConstraint f v]]) -> Processor f c v m -> Processor f c v m
chainWith f p cs = go (f cs) where
go [] = return $ Progress []
go (s:ss) = do
logMsg ("Component: " ++ show (length ss + 1) ++ " Components")
q <- p s
case q of
Progress [] -> go ss
_ -> return $ Progress (concat $ s:ss)
|
mzini/gubs
|
src/GUBS/Solve/SCC.hs
|
mit
| 1,392 | 0 | 17 | 361 | 526 | 267 | 259 | 26 | 3 |
module Main where
import Evaluator
import Parser
import System.Environment
import Text.ParserCombinators.Parsec
import TypeChecker
main :: IO ()
main = do
filename <- getArgs
arg <- case filename of
[] -> getContents
fn:_ -> readFile fn
case parse program "pascal-like-interpreter" arg of
(Left err) -> print err
(Right res) -> do
tt <- goTC res
case fst tt of
(Left e) -> putStrLn e
(Right _) -> do
co <- checkOut res
case fst co of
(Left e) -> putStrLn e
(Right _) -> return ()
|
minib00m/jpp
|
src/Main.hs
|
mit
| 642 | 0 | 21 | 247 | 218 | 105 | 113 | 23 | 5 |
#!/usr/bin/env runhaskell
import Text.Printf
maxIterations = 200
epsilon = 1e-6
f :: Double -> Double
f x = x * exp x + x ^^ 3 + 1
bisect :: (Double -> Double) -> Double -> Double -> Int -> IO ()
bisect g a b i = do
let m = (a + b) / 2
fa = g a
fm = g m
dx = (b - a) / 2
printf "%d %.3f %.3f %.3f %.3f %.3f %.3f\n" i a b m fa fm dx
if dx < epsilon || i > maxIterations
then return ()
else if fa * fm > 0 then bisect g m b (i+1) else bisect g a m (i+1)
main :: IO ()
main = do
putStr "a: "
a <- fmap read getLine :: IO Double
putStr "b: "
b <- fmap read getLine :: IO Double
putStrLn "i a b m f(a) f(m) |Δx/2|"
bisect f a b 0
|
ergenekonyigit/Numerical-Analysis-Examples
|
Haskell/BisectionMethod.hs
|
mit
| 746 | 0 | 12 | 279 | 329 | 162 | 167 | 23 | 3 |
module Parser.Internal.AST where
import Control.Monad.Reader
import Data.List (partition)
import qualified Data.Map as M
import Parser.Internal.CST
type EnvMap = M.Map String [String]
buildGlobalEnv :: [Directive] -> EnvMap
buildGlobalEnv ds = foldl mapper M.empty $ filter (\d -> null $ nested d) ds
where mapper :: M.Map String [String] -> Directive -> M.Map String [String]
mapper m d = case M.lookup (name d) m of
{-
If we have seen this directive before
lookup how we should deal with this second
declaration.
-}
Just pargs -> directiveMapper d m pargs
{-
If we have not seen this directive
yet just add it.
-}
Nothing -> M.insert (name d) (args d) m
directiveMapper :: Directive -> EnvMap -> [String] -> EnvMap
directiveMapper d m pargs =
case M.lookup (name d) directiveMap of
Just f -> f d m pargs
Nothing -> m
directiveMap :: M.Map String (Directive -> EnvMap -> [String] -> EnvMap)
directiveMap = M.fromList [
("ServerRoot", \d m _ -> M.insert (name d) (args d) m),
("ServerAdmin", \d m _ -> M.insert (name d) (args d) m),
("Listen", \d m pargs -> M.insert (name d) (pargs ++ args d) m),
("LoadModule", \d m pargs -> M.insert (name d) (pargs ++ args d) m)
]
|
wayofthepie/httpd-conf-parser
|
src/Parser/Internal/AST.hs
|
mit
| 1,760 | 0 | 12 | 795 | 486 | 257 | 229 | 23 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Utils.Geo where
import Data.Aeson as Json (decode)
import Data.Aeson.TH
import qualified Network.HTTP.Client as HTTP
data Telize =
Telize { country_code :: String }
$(deriveJSON defaultOptions ''Telize)
-- TODO: 1) define time-out 2) define exception handling
findCountryCode :: String -> IO String
findCountryCode ip =
do httpRequest <- HTTP.parseUrl "http://www.telize.com/geoip/2.240.222.127" -- ++ ip
-- for testing purposes use a static ip
response <- HTTP.withManager HTTP.defaultManagerSettings $ HTTP.httpLbs httpRequest
let telize = Json.decode $ HTTP.responseBody response :: Maybe Telize
case telize of
Just t -> return $ country_code t
Nothing -> return ""
|
stefanodacchille/itson
|
src/backend/Utils/Geo.hs
|
mit
| 753 | 0 | 12 | 140 | 179 | 93 | 86 | 16 | 2 |
mnr = tail [0,1,2,3,4,5,6,7] :: [Integer] {- Matrikelnummer -}
name = "Mustermann Max" :: String {- Name -}
t1 = ("p1", (drop 9.show)mnr, (take 3.zip name.tail)name)
t2 = (\a b c d -> ( (b.a)d, (a.b)d )) {- Nur allgemeinster Typ -}
t3 = t2 (take 3) reverse (drop 3) mnr
t4 = (drop 4 [[i-1] | i<-mnr], take 3 [i | i<-mnr, i>4])
t5 = take 4 [[i|j<-[i..5]] | i<-mnr]
tls _ = (tail.reverse.tail.tail)
t6 = (tls 1 mnr, take 5 [(i,j)| i <- tls 2 mnr, j <- tls 3 mnr, j<i])
p o (b:m) (a:l) n = o a b : p o l m n
p _ _ _ n = n
t7 = p (+) (reverse mnr) mnr [12]
|
Szuuuken/funk-prog-pruefungs-vorbereitung
|
pruefung-2019-01-17/Aufgabe01.hs
|
mit
| 561 | 4 | 10 | 132 | 415 | 223 | 192 | 12 | 1 |
module Web.PushBullet (
Connection(..),
Response(..),
defaultResponse,
runPushBullet,
getDevices,
pushNoteToAll,
pushNoteToDevice
) where
import Web.PushBullet.Types
import Web.PushBullet.Core
import Web.PushBullet.Device
import Web.PushBullet.Push
|
tlunter/PushBullet
|
src/Web/PushBullet.hs
|
mit
| 278 | 0 | 5 | 49 | 61 | 41 | 20 | 12 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiParamTypeClasses #-}
import Test.HUnit hiding (Test)
import Test.Hspec
import Yesod.Core
import Yesod.Form
import Yesod.Test
import Yesod.Test.CssQuery
import Yesod.Test.TransversingCSS
import Text.XML
import Data.Text (Text, pack)
import Data.Monoid ((<>))
import Control.Applicative
import Network.Wai (pathInfo)
import Data.Maybe (fromMaybe)
import Data.ByteString.Lazy.Char8 ()
import qualified Data.Map as Map
import qualified Text.HTML.DOM as HD
parseQuery_ = either error id . parseQuery
findBySelector_ x = either error id . findBySelector x
parseHtml_ = HD.parseLBS
main :: IO ()
main = hspec $ do
describe "CSS selector parsing" $ do
it "elements" $ parseQuery_ "strong" @?= [[DeepChildren [ByTagName "strong"]]]
it "child elements" $ parseQuery_ "strong > i" @?= [[DeepChildren [ByTagName "strong"], DirectChildren [ByTagName "i"]]]
it "comma" $ parseQuery_ "strong.bar, #foo" @?= [[DeepChildren [ByTagName "strong", ByClass "bar"]], [DeepChildren [ById "foo"]]]
describe "find by selector" $ do
it "XHTML" $
let html = "<html><head><title>foo</title></head><body><p>Hello World</p></body></html>"
query = "body > p"
in findBySelector_ html query @?= ["<p>Hello World</p>"]
it "HTML" $
let html = "<html><head><title>foo</title></head><body><br><p>Hello World</p></body></html>"
query = "body > p"
in findBySelector_ html query @?= ["<p>Hello World</p>"]
let query = "form.foo input[name=_token][type=hidden][value]"
html = "<input name='_token' type='hidden' value='foo'><form class='foo'><input name='_token' type='hidden' value='bar'></form>"
expected = "<input name=\"_token\" type=\"hidden\" value=\"bar\" />"
in it query $ findBySelector_ html (pack query) @?= [expected]
it "descendents and children" $
let html = "<html><p><b><i><u>hello</u></i></b></p></html>"
query = "p > b u"
in findBySelector_ html query @?= ["<u>hello</u>"]
it "hyphenated classes" $
let html = "<html><p class='foo-bar'><b><i><u>hello</u></i></b></p></html>"
query = "p.foo-bar u"
in findBySelector_ html query @?= ["<u>hello</u>"]
it "descendents" $
let html = "<html><p><b><i>hello</i></b></p></html>"
query = "p i"
in findBySelector_ html query @?= ["<i>hello</i>"]
describe "HTML parsing" $ do
it "XHTML" $
let html = "<html><head><title>foo</title></head><body><p>Hello World</p></body></html>"
doc = Document (Prologue [] Nothing []) root []
root = Element "html" Map.empty
[ NodeElement $ Element "head" Map.empty
[ NodeElement $ Element "title" Map.empty
[NodeContent "foo"]
]
, NodeElement $ Element "body" Map.empty
[ NodeElement $ Element "p" Map.empty
[NodeContent "Hello World"]
]
]
in parseHtml_ html @?= doc
it "HTML" $
let html = "<html><head><title>foo</title></head><body><br><p>Hello World</p></body></html>"
doc = Document (Prologue [] Nothing []) root []
root = Element "html" Map.empty
[ NodeElement $ Element "head" Map.empty
[ NodeElement $ Element "title" Map.empty
[NodeContent "foo"]
]
, NodeElement $ Element "body" Map.empty
[ NodeElement $ Element "br" Map.empty []
, NodeElement $ Element "p" Map.empty
[NodeContent "Hello World"]
]
]
in parseHtml_ html @?= doc
describe "basic usage" $ yesodSpec app $ do
ydescribe "tests1" $ do
yit "tests1a" $ do
get ("/" :: Text)
statusIs 200
bodyEquals "Hello world!"
yit "tests1b" $ do
get ("/foo" :: Text)
statusIs 404
ydescribe "tests2" $ do
yit "type-safe URLs" $ do
get $ LiteAppRoute []
statusIs 200
yit "type-safe URLs with query-string" $ do
get (LiteAppRoute [], [("foo", "bar")])
statusIs 200
bodyEquals "foo=bar"
yit "post params" $ do
post ("/post" :: Text)
statusIs 500
request $ do
setMethod "POST"
setUrl $ LiteAppRoute ["post"]
addPostParam "foo" "foobarbaz"
statusIs 200
bodyEquals "foobarbaz"
yit "labels" $ do
get ("/form" :: Text)
statusIs 200
request $ do
setMethod "POST"
setUrl ("/form" :: Text)
byLabel "Some Label" "12345"
fileByLabel "Some File" "test/main.hs" "text/plain"
addNonce
statusIs 200
bodyEquals "12345"
yit "finding html" $ do
get ("/html" :: Text)
statusIs 200
htmlCount "p" 2
htmlAllContain "p" "Hello"
htmlAnyContain "p" "World"
htmlAnyContain "p" "Moon"
htmlNoneContain "p" "Sun"
ydescribe "utf8 paths" $ do
yit "from path" $ do
get ("/dynamic1/שלום" :: Text)
statusIs 200
bodyEquals "שלום"
yit "from path, type-safe URL" $ do
get $ LiteAppRoute ["dynamic1", "שלום"]
statusIs 200
printBody
bodyEquals "שלום"
yit "from WAI" $ do
get ("/dynamic2/שלום" :: Text)
statusIs 200
bodyEquals "שלום"
ydescribe "labels" $ do
yit "can click checkbox" $ do
get ("/labels" :: Text)
request $ do
setMethod "POST"
setUrl ("/labels" :: Text)
byLabel "Foo Bar" "yes"
describe "cookies" $ yesodSpec cookieApp $ do
yit "should send the cookie #730" $ do
get ("/" :: Text)
statusIs 200
post ("/cookie/foo" :: Text)
statusIs 303
get ("/" :: Text)
statusIs 200
printBody
bodyContains "Foo"
instance RenderMessage LiteApp FormMessage where
renderMessage _ _ = defaultFormMessage
app :: LiteApp
app = liteApp $ do
dispatchTo $ do
mfoo <- lookupGetParam "foo"
case mfoo of
Nothing -> return "Hello world!"
Just foo -> return $ "foo=" <> foo
onStatic "dynamic1" $ withDynamic $ \d -> dispatchTo $ return (d :: Text)
onStatic "dynamic2" $ onStatic "שלום" $ dispatchTo $ do
req <- waiRequest
return $ pathInfo req !! 1
onStatic "post" $ dispatchTo $ do
mfoo <- lookupPostParam "foo"
case mfoo of
Nothing -> error "No foo"
Just foo -> return foo
onStatic "form" $ dispatchTo $ do
((mfoo, widget), _) <- runFormPost
$ renderDivs
$ (,)
<$> areq textField "Some Label" Nothing
<*> areq fileField "Some File" Nothing
case mfoo of
FormSuccess (foo, _) -> return $ toHtml foo
_ -> defaultLayout widget
onStatic "html" $ dispatchTo $
return ("<html><head><title>Hello</title></head><body><p>Hello World</p><p>Hello Moon</p></body></html>" :: Text)
onStatic "labels" $ dispatchTo $
return ("<html><label><input type='checkbox' name='fooname' id='foobar'>Foo Bar</label></html>" :: Text)
cookieApp :: LiteApp
cookieApp = liteApp $ do
dispatchTo $ fromMaybe "no message available" <$> getMessage
onStatic "cookie" $ do
onStatic "foo" $ dispatchTo $ do
setMessage "Foo"
redirect ("/cookie/home" :: Text)
return ()
|
wujf/yesod
|
yesod-test/test/main.hs
|
mit
| 8,577 | 0 | 24 | 3,219 | 2,013 | 939 | 1,074 | 193 | 4 |
-- | This module contains resolution routines for acts.
module Game.Cosanostra.Resolver
( DepGraph
, depGraph
, depOrder
, resolve
) where
import Game.Cosanostra.Action
import Game.Cosanostra.Effect
import Game.Cosanostra.Resolver.Action
import Game.Cosanostra.Resolver.Effect
import Game.Cosanostra.Lenses
import Game.Cosanostra.Types
import Control.Lens hiding (rewrite)
import Control.Monad
import Control.Monad.Cont
import Control.Monad.Reader
import Control.Monad.State
import Data.Foldable
import Data.Function
import qualified Data.Graph.Inductive.Graph as G
import qualified Data.Graph.Inductive.Query.DFS as G
import Data.Graph.Inductive.PatriciaTree
import Data.List
import qualified Data.Map.Strict as M
import Data.Maybe
import qualified Data.Set as S
import Data.Tuple
-- | The type for the dependency graph created.
type DepGraph = Gr Act Effect
affected :: Players -> Actions -> Turn -> Phase -> Act -> Act -> [Effect]
affected players actions turn phase dependent act =
[effect
| (holder, effects) <- M.toList dependentEffects
, sourceAffected aType effects holder act ||
targetsAffected aType effects holder act
, effect <- effects
]
where
Just traits = actions ^. at (act ^. actAction)
aType = traits ^. actionTraitsType
dependentEffects =
M.map (filter isEffectActive)
(appliesEffects' dependent (playerKeys players) actions)
isEffectActive effect =
not (act ^. actUnaffectable) &&
checkConstraint players (act ^. actSource) turn phase
(effect ^. effectConstraint)
sourceAffected :: ActionType -> [Effect] -> Player -> Act -> Bool
sourceAffected actionType effects holder act =
((act ^. actSource) == holder) &&
(not $ null $ snd $ rewriteOnSource effects actionType act)
targetsAffected :: ActionType -> [Effect] -> Player -> Act -> Bool
targetsAffected actionType effects holder act =
any (targetAffected actionType effects holder act)
[0..length (act ^. actTargets) - 1]
targetAffected :: ActionType -> [Effect] -> Player -> Act -> Index [Player] -> Bool
targetAffected actionType effects holder act i =
((act ^?! actTargets . ix i) == holder) &&
(not $ null $ snd $ rewriteOnTarget effects actionType act i)
appliesEffects' :: Act -> [Player] -> Actions -> M.Map Player [Effect]
appliesEffects' act players actions =
appliesEffects (traits ^. actionTraitsType) act players
where
Just traits = actions ^. at (act ^. actAction)
-- | Computes a dependency graph strictly from acts. This doesn't take into
-- account things like rewriting and additional effect acts.
depGraph :: Players -> Actions -> Turn -> Phase -> [Act] -> DepGraph
depGraph players actions turn phase acts =
G.mkGraph nodes edges
where
nodes = zip [0..] acts
actIndices = M.fromList (map swap nodes)
edge dependent act effect = ( actIndices M.! dependent
, actIndices M.! act
, effect
)
edges = [edge dependent act effect
| dependent <- acts
, act <- acts
, act /= dependent
, effect <- affected players actions turn phase dependent act
]
-- | Finds a consistent ordering for the dependency graph.
--
-- Due to the possible presence of cycles in the graph, this does not just
-- naively topsort the graph. Instead it:
--
-- 1. Generates the condensation of the graph; that is, the graph of the graph's
-- strongly connected components.
--
-- 2. The condensation is guaranteed to not have cycles, so we topsort it to
-- get an ordering of components.
--
-- 3. For each component, we take the act with the highest emergency precedence
-- and return that first.
--
-- 4. We recurse by removing the node we've returned and repeating the process.
depOrder :: Actions -> DepGraph -> [Act]
depOrder actions g = do
guard $ not (G.isEmpty g)
scc <- G.topsort' (G.condensation g)
let g' = G.subgraph scc g
let (n, l) = minimumBy compareNodes (G.labNodes g')
l:depOrder actions (G.delNode n g')
where
compareNodes = compare `on` (^. _2 . actAction . to (actionTraits actions) .
actionTraitsType . to emergencyPrecedence)
type Seen = M.Map (ActTrace, Slot) (S.Set EffectTrace)
data Slot = Source
| Target (Index [Player])
deriving (Eq, Ord, Show)
-- | Rewrites a single item from the head. Returns 'Nothing' if we don't need
-- to re-resolve; otherwise returns the cause of a rewrite.
--
-- Note that we don't handle causality here, i.e. an action that is later
-- deleted but initially caused a rewrite with new actions will retain the new
-- actions, even though the action that added the new actions is now deleted.
-- This can be handled later by checking that act traces with rewrite origins
-- have the act that caused the rewrite present in the final list of actions.
rewrite1 :: Actions -> Turn -> Phase -> Players -> Act -> State Seen (Maybe ([Act], Player, [Effect]))
rewrite1 actions turn phase players act = (`runContT` return) $ callCC $ \exit -> do
let abort = exit . Just
seen <- get
forM_ (tails $ filter (checkEffect Source seen) $
source ^. to (playerEffects players source turn phase)) $ \effects -> do
let (acts', used) = rewriteOnSource effects aType act
forM_ used $ \effect ->
modify $ markSeen Source aTrace (effect ^. effectTrace)
when (not $ null used) $ abort (acts', source, used)
forM_ (zip [0..] targets) $ \(i, target) ->
forM_ (tails $ filter (checkEffect (Target i) seen) $
target ^. to (playerEffects players source turn phase)) $ \effects -> do
let (acts', used) = rewriteOnTarget effects aType act i
forM_ used $ \effect ->
modify $ markSeen (Target i) aTrace (effect ^. effectTrace)
when (not $ null used) $ abort (acts', source, used)
return Nothing
where
source = act ^. actSource
targets = act ^. actTargets
aType = actionTraits actions (act ^. actAction) ^. actionTraitsType
aTrace = act ^. actTrace
checkEffect slot seen effect =
not (isSeen slot aTrace (effect ^. effectTrace) seen)
rewrite :: Seen -> Actions -> Turn -> Phase -> [Act] -> Players -> [Act] -> Reader ([Act], Players) ([Act], Players)
rewrite seen actions turn phase (act:acts) players acc = case rewriting of
Just (pending, holder, used) -> do
(allActs, originalPlayers) <- ask
-- Note: weird things may happen if there is a vengeful roleblocker,
-- but that's an insane role and we ignore that here.
return $ resolve' seen' actions turn phase
(pending ++ delete act allActs)
(foldr (flip (\players' -> playerUseEffect players' holder))
originalPlayers
used)
Nothing -> do
let players' = playerUnionEffects
players
(appliesEffects' act (playerKeys players) actions)
rewrite seen' actions turn phase acts players' (act:acc)
where
(rewriting, seen') = runState (rewrite1 actions turn phase players act) seen
rewrite _ _ _ _ [] players acc = return (reverse acc, players)
resolve' :: Seen -> Actions -> Turn -> Phase -> [Act] -> Players -> ([Act], Players)
resolve' seen actions turn phase acts players =
runReader (rewrite seen actions turn phase guess players []) (acts, players)
where
guess = depOrder actions (depGraph players actions turn phase acts)
-- | Resolve unordered acts into a list of acts and map of player effects.
--
-- This effectively solves the entire game state, so you can call this without
-- any assumptions about the input data (well, effects must not have 0 uses
-- left, but that's about it).
resolve :: Actions -> Turn -> Phase -> [Act] -> Players -> ([Act], Players)
resolve = resolve' M.empty
isSeen :: Slot -> ActTrace -> EffectTrace -> Seen -> Bool
isSeen slot aTrace eTrace seen =
eTrace `S.member` fromMaybe S.empty (seen ^. at (aTrace, slot)) ||
dependentIsSeen
where
dependentIsSeen = case aTrace of
fromRewrite@ActFromRewrite{} ->
isSeen slot (fromRewrite ^?! actTraceDependentTrace) eTrace seen
_ -> False
markSeen :: Slot -> ActTrace -> EffectTrace -> Seen -> Seen
markSeen slot aTrace eTrace =
M.insertWith S.union (aTrace, slot) (S.singleton eTrace)
|
rfw/cosanostra
|
src/Game/Cosanostra/Resolver.hs
|
mit
| 8,585 | 0 | 21 | 2,125 | 2,354 | 1,252 | 1,102 | -1 | -1 |
module Tests where
import Control.Monad (liftM2)
import Distribution.TestSuite
import qualified IntegrationTests
import qualified ResponseParserTests
tests :: IO [Test]
tests = ResponseParserTests.tests
`concatM` IntegrationTests.tests
concatM :: Monad m => m [a] -> m [a] -> m [a]
concatM = liftM2 (++)
|
timbodeit/qpx-api
|
test/Tests.hs
|
mit
| 339 | 0 | 9 | 75 | 101 | 58 | 43 | 10 | 1 |
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Y2017.M09.D26.Exercise where
import qualified Codec.Compression.GZip as GZ
import Data.Aeson
import Data.Aeson.Encode.Pretty
import Data.ByteString.Lazy.Char8 (ByteString)
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Map (Map)
import qualified Data.Map as Map
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToRow
import Database.PostgreSQL.Simple.ToField
import Network.HTTP.Conduit
-- below imports available via 1HaskellADay git repository
import Store.SQL.Connection (connectInfo)
import Store.SQL.Util.Inserts (inserter)
import Y2017.M09.D22.Exercise (scanArticles, dir, arts, rawText, articleTextById)
import Y2017.M09.D25.Exercise (parseArticle, metadata, Article, srcId)
{--
So, I wrote a whole exercise for today, which you will see as tomorrow's
exercise, instead, because then I realized that it was too much for one day
without some introduction.
So, today's Haskell problem: a name, by any other name, would smell as sweet.
A datum from Friday's exercise is "Person":
>>> articles <- scanArticles . GZ.decompress <$> BL.readFile (dir ++ arts)
>>> Just art3 = parseArticle 3 (rawText $ head articles)
>>> Map.lookup "People" (metadata art3)
Just "Cuomo, Mario M"
This is an example where the article is about just one person. As you scan the
articles you will see some that are about more than one person and the names
will be in various formats.
Today we will not worry about formats of name(s) in the Person field.
Because today we're simply going to store the names.
Say you have a staging table in PostgreSQL called name_stg with the following
structure:
--}
data RawNames = Raw { fromArticle :: Int, text :: String }
deriving (Eq, Ord, Show)
-- with our handy insert statement:
insertRawNamesStmt :: Query
insertRawNamesStmt = [sql|INSERT INTO name_stg (article_id,names) VALUES (?,?)|]
-- from the above, derive the below:
instance ToRow RawNames where
toRow rn = undefined
{--
Okay, great, and you can use the inserter from before to construct the
procedure that inserts RawNames values into PostgreSQL database.
Before we do that, we have to convert articles scanned to a list of raw names
values. And before we do that, let's create a function that pipelines the whole
process of extracting articles from the archive and reifying those articles
to the Y2017.M09.D25.Article type.
--}
type Compressed = ByteString
-- reminder to me that this is a compressed archive
extractArticles :: Compressed -> [Article]
extractArticles gz = undefined
-- then let's grab the line that has the raw names listed from each article
art2RawNames :: Article -> Maybe RawNames
art2RawNames art = undefined
-- and with that transformation function, we can insert raw names from articles
insertAllRawNames :: Connection -> [RawNames] -> IO ()
insertAllRawNames conn = undefined
-- How many rows did you insert? [low key: your answer should be '11']
-- [... or should it?]
-- Now: how many names did you insert?
-- We will address that question tomorrow when we get into some simple name
-- parsers.
{-- BONUS -----------------------------------------------------------------
Output your RawNames values as JSON.
--}
instance ToJSON RawNames where
toJSON rn = undefined
-- BONUS-BONUS ------------------------------------------------------------
-- prettily.
|
geophf/1HaskellADay
|
exercises/HAD/Y2017/M09/D26/Exercise.hs
|
mit
| 3,439 | 0 | 8 | 531 | 344 | 221 | 123 | 33 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Control.Timeout.Tests (tests) where
import Control.Exception (SomeException, try)
import Data.Maybe (isJust, isNothing)
import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (Arbitrary(..), Property, Positive(..), NonNegative(..),
suchThat, once, within, testProperty)
import Test.QuickCheck.Monadic (monadicIO, run, assert)
import Control.Timeout (timeout, sleep)
-- | Interval that lesser than 1000 microseconds, that guarantied by
-- 'Arbitrary' instance implementation.
newtype SmallInterval = SmallInterval NominalDiffTime
deriving (Show)
instance Arbitrary SmallInterval where
arbitrary = fmap (SmallInterval . getPositive) $ suchThat arbitrary (< Positive 1000)
instance Arbitrary NominalDiffTime where
arbitrary = fmap fromInteger arbitrary
-- | Timeout works with exceptions mechanism, so we need to check is
-- ordinary exceptions works.
testOtherException :: Property
testOtherException = monadicIO $ do
res <- run $ try $ timeout 1 $ error "testOtherException"
assert $ case res of
Right _ -> False
Left (_ :: SomeException) -> True
-- | Test is 'timeout' works.
testTimedOut :: Property
testTimedOut = monadicIO $ do
res <- run $ timeout 0.1 $ sleep 0.2
assert $ isNothing res
-- | Test is 'timeout' works even in negative case.
testNotTimedOut :: Property
testNotTimedOut = monadicIO $ do
res <- run $ timeout 0.2 $ sleep 0.1
assert $ isJust res
-- | Test is timeout fires immediately for negative and zero value.
testNotPoisitiveTimeout :: NonNegative NominalDiffTime -> Property
testNotPoisitiveTimeout (NonNegative t') = let t = negate t' in monadicIO $ do
res <- run $ do
now <- getCurrentTime
timeout t $ sleep 0.1
new <- getCurrentTime
return $ diffUTCTime new now
assert $ res < 0.01
-- | Test is forked timeout thread killed properly.
testKillThreadKilled :: Property
testKillThreadKilled = monadicIO $ do
run $ timeout 0.1 $ return ()
run $ sleep 0.2
assert True
-- | Test is 'sleep' actually sleep.
testSleep :: SmallInterval -> Property
testSleep (SmallInterval interval) = monadicIO $ do
res <- run $ do
now <- getCurrentTime
sleep t
new <- getCurrentTime
return $ diffUTCTime new now
assert $ res > t
where
t = interval / 1000
tests :: TestTree
tests = testGroup "Control.Timeout.Tests"
[ testProperty "timeout pass exceptions" $ once $ testOtherException
, testProperty "timed out" $ once testTimedOut
, testProperty "not timed out" $ once testNotTimedOut
, testProperty "not positive timeout" $ testNotPoisitiveTimeout
, testProperty "kill thread killed" $ once testKillThreadKilled
, testProperty "sleep" testSleep
]
|
lambda-llama/timeout
|
tests/Control/Timeout/Tests.hs
|
mit
| 2,942 | 0 | 15 | 612 | 722 | 373 | 349 | 61 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-launchroleconstraint.html
module Stratosphere.Resources.ServiceCatalogLaunchRoleConstraint where
import Stratosphere.ResourceImports
-- | Full data type definition for ServiceCatalogLaunchRoleConstraint. See
-- 'serviceCatalogLaunchRoleConstraint' for a more convenient constructor.
data ServiceCatalogLaunchRoleConstraint =
ServiceCatalogLaunchRoleConstraint
{ _serviceCatalogLaunchRoleConstraintAcceptLanguage :: Maybe (Val Text)
, _serviceCatalogLaunchRoleConstraintDescription :: Maybe (Val Text)
, _serviceCatalogLaunchRoleConstraintPortfolioId :: Val Text
, _serviceCatalogLaunchRoleConstraintProductId :: Val Text
, _serviceCatalogLaunchRoleConstraintRoleArn :: Val Text
} deriving (Show, Eq)
instance ToResourceProperties ServiceCatalogLaunchRoleConstraint where
toResourceProperties ServiceCatalogLaunchRoleConstraint{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::ServiceCatalog::LaunchRoleConstraint"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("AcceptLanguage",) . toJSON) _serviceCatalogLaunchRoleConstraintAcceptLanguage
, fmap (("Description",) . toJSON) _serviceCatalogLaunchRoleConstraintDescription
, (Just . ("PortfolioId",) . toJSON) _serviceCatalogLaunchRoleConstraintPortfolioId
, (Just . ("ProductId",) . toJSON) _serviceCatalogLaunchRoleConstraintProductId
, (Just . ("RoleArn",) . toJSON) _serviceCatalogLaunchRoleConstraintRoleArn
]
}
-- | Constructor for 'ServiceCatalogLaunchRoleConstraint' containing required
-- fields as arguments.
serviceCatalogLaunchRoleConstraint
:: Val Text -- ^ 'sclrcPortfolioId'
-> Val Text -- ^ 'sclrcProductId'
-> Val Text -- ^ 'sclrcRoleArn'
-> ServiceCatalogLaunchRoleConstraint
serviceCatalogLaunchRoleConstraint portfolioIdarg productIdarg roleArnarg =
ServiceCatalogLaunchRoleConstraint
{ _serviceCatalogLaunchRoleConstraintAcceptLanguage = Nothing
, _serviceCatalogLaunchRoleConstraintDescription = Nothing
, _serviceCatalogLaunchRoleConstraintPortfolioId = portfolioIdarg
, _serviceCatalogLaunchRoleConstraintProductId = productIdarg
, _serviceCatalogLaunchRoleConstraintRoleArn = roleArnarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-launchroleconstraint.html#cfn-servicecatalog-launchroleconstraint-acceptlanguage
sclrcAcceptLanguage :: Lens' ServiceCatalogLaunchRoleConstraint (Maybe (Val Text))
sclrcAcceptLanguage = lens _serviceCatalogLaunchRoleConstraintAcceptLanguage (\s a -> s { _serviceCatalogLaunchRoleConstraintAcceptLanguage = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-launchroleconstraint.html#cfn-servicecatalog-launchroleconstraint-description
sclrcDescription :: Lens' ServiceCatalogLaunchRoleConstraint (Maybe (Val Text))
sclrcDescription = lens _serviceCatalogLaunchRoleConstraintDescription (\s a -> s { _serviceCatalogLaunchRoleConstraintDescription = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-launchroleconstraint.html#cfn-servicecatalog-launchroleconstraint-portfolioid
sclrcPortfolioId :: Lens' ServiceCatalogLaunchRoleConstraint (Val Text)
sclrcPortfolioId = lens _serviceCatalogLaunchRoleConstraintPortfolioId (\s a -> s { _serviceCatalogLaunchRoleConstraintPortfolioId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-launchroleconstraint.html#cfn-servicecatalog-launchroleconstraint-productid
sclrcProductId :: Lens' ServiceCatalogLaunchRoleConstraint (Val Text)
sclrcProductId = lens _serviceCatalogLaunchRoleConstraintProductId (\s a -> s { _serviceCatalogLaunchRoleConstraintProductId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-launchroleconstraint.html#cfn-servicecatalog-launchroleconstraint-rolearn
sclrcRoleArn :: Lens' ServiceCatalogLaunchRoleConstraint (Val Text)
sclrcRoleArn = lens _serviceCatalogLaunchRoleConstraintRoleArn (\s a -> s { _serviceCatalogLaunchRoleConstraintRoleArn = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/Resources/ServiceCatalogLaunchRoleConstraint.hs
|
mit
| 4,355 | 0 | 15 | 421 | 552 | 313 | 239 | 47 | 1 |
{-# LANGUAGE MultiParamTypeClasses, DeriveDataTypeable #-}
module Type.Poly.Check where
import Type.Poly.Data
import Type.Poly.Tree
import Type.Poly.Infer
import Autolib.Reporter.Type
import Autolib.ToDoc
import Autolib.Size
import Autolib.TES.Identifier
import Inter.Types
import qualified Challenger as C
import Data.Typeable
import qualified Tree as T
data TypePolyCheck = TypePolyCheck deriving ( Eq, Ord, Show, Read, Typeable )
instance OrderScore TypePolyCheck where
scoringOrder _ = Increasing
instance C.Partial TypePolyCheck TI Expression where
describe p i = vcat
[ text "Gesucht ist ein Ausdruck vom Typ"
<+> protect (toDoc (target i))
, text "in der Signatur"
, nest 4 $ protect $ toDoc (signature i)
]
initial p i = read "f(a(),M.<Foo>g(b()))"
total p i b = do
inform $ vcat [ text "Die Baumstruktur des Ausdrucks"
, nest 4 $ protect $ toDoc b
, text "ist"
]
peng b
t <- infer (signature i) b
assert ( t == target i )
$ text "ist das der geforderte Typ?"
instance C.Measure TypePolyCheck TI Expression where
measure p i b = fromIntegral $ size b
make :: Make
make = direct TypePolyCheck $
TI { target = read "boolean"
, signature = read "static int a(); static <T>boolean eq (T a, T b);"
}
|
Erdwolf/autotool-bonn
|
src/Type/Poly/Check.hs
|
gpl-2.0
| 1,389 | 3 | 15 | 380 | 371 | 195 | 176 | 37 | 1 |
import Data.Time
import Data.Time.Clock.POSIX
import Data.List
import Data.Maybe
import System.Locale (defaultTimeLocale)
data Entry = Entry {
abbrev :: String,
date :: String
} deriving (Show,Eq)
secondsFrom :: POSIXTime -> POSIXTime -> Double
secondsFrom startPt endPt =
a - b
where
a = ptToDouble endPt
b = ptToDouble startPt
ptToDouble :: POSIXTime -> Double
ptToDouble t = fromRational (toRational t)
-- ... 'T minus 3', 'T minus 2', 'T minus 1', 'Liftoff', 'T plus 1', ...
plusMinus sDouble
| sDouble >= 0.0 = "+" -- T plus n, event in past
| otherwise = "-" -- T minus n, event in future
secsToDaysHoursMinsSecs :: Double -> String
secsToDaysHoursMinsSecs sDouble =
plusMinus sDouble ++ " " ++ dStr ++ hStr ++ minStr where
dStr = if d /= 0 then (show d) ++ " d " else ""
hStr = if h /= 0 then (show h) ++ " h " else ""
minStr = if min /= 0 then (show min) ++ " min" else ""
sInt = round (abs sDouble)
(d,hLeft) = divMod sInt 86400
(h,minLeft) = divMod hLeft 3600
(min,s) = divMod minLeft 60
earlierFst (Entry abbrev1 date1) (Entry abbrev2 date2) =
date1 `compare` date2
ptEntry pt =
Entry {
abbrev = abbrev,
date = date
} where
abbrev = "NOW"
date = formatTime defaultTimeLocale "%Y-%m-%d %H:%M" (
utcToLocalTime utc (posixSecondsToUTCTime pt))
createEntry :: String -> Entry
createEntry str =
Entry {
abbrev = abbrev,
date = date
} where
abbrev = take 2 str
date = drop 3 str
readSeasons = do
-- You may want to use the full path when compiled:
content <- readFile "seasons-utc-list.txt"
let fileLines = lines content
entries = map createEntry fileLines
sortedEntries = sortBy earlierFst entries
return sortedEntries
timeParsed :: String -> UTCTime
timeParsed line =
fromJust t where
t = parseTime defaultTimeLocale "%Y-%m-%d %H:%M" line
idx now entries =
fromJust e where
e = elemIndex now testEntries
testEntries = insertBy earlierFst now entries
entriesAround pt r entries =
take (2*r) dropList
where
dropList = drop (i-r) entries
i = idx (ptEntry pt) entries
countersAround currentPt entries =
[(fDiffShow x) ++ " " ++ (abbrev x) | x <- around]
where
fDiffShow = diffShow . diffSecs . datePt . date
around = entriesAround currentPt 1 entries
datePt = utcTimeToPOSIXSeconds . timeParsed
diffSecs = \datePt -> secondsFrom datePt currentPt
diffShow = secsToDaysHoursMinsSecs
newLine = do
putStrLn ""
main = do
pt <- getPOSIXTime
entries <- readSeasons
--mapM_ (putStrLn . show) entries
--newLine
--putStrLn (show (ptEntry pt))
--newLine
--putStrLn (show (idx (ptEntry pt) entries))
--newLine
--mapM_ (putStrLn . show) (entriesAround pt 2 entries)
--newLine
mapM_ putStrLn (countersAround pt entries)
|
jsavatgy/season-count
|
seasons-count-read-from-file.hs
|
gpl-2.0
| 2,864 | 8 | 11 | 690 | 835 | 436 | 399 | 76 | 4 |
module HEP.Automation.MadGraph.Dataset.Set20110315set3 where
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.Cluster
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Dataset.Common
my_ssetup :: ScriptSetup
my_ssetup = SS {
scriptbase = "/Users/iankim/mac/workspace/ttbar/mc_script/"
, mg5base = "/Users/iankim/mac/montecarlo/MG_ME_V4.4.44/MadGraph5_v0_6_1/"
, workbase = "/Users/iankim/mac/workspace/ttbar/mc/"
}
processTTBar0or1jet :: [Char]
processTTBar0or1jet =
"\ngenerate P P > t t~ QED=99 @1 \nadd process P P > t t~ J QED=99 @2 \n"
psetup_six_ttbar01j :: ProcessSetup
psetup_six_ttbar01j = PS {
mversion = MadGraph5
, model = Six
, process = processTTBar0or1jet
, processBrief = "ttbar01j"
, workname = "315Six1J"
}
my_csetup :: ClusterSetup
my_csetup = CS { cluster = Parallel 3 }
sixparamset :: [Param]
sixparamset = [ SixParam mass g
| mass <- [700.0, 800.0 ]
, g <- [0.6, 0.8 .. 4.0 ] ]
psetuplist :: [ProcessSetup]
psetuplist = [ psetup_six_ttbar01j ]
sets :: [Int]
sets = [1]
sixtasklist :: [WorkSetup]
sixtasklist = [ WS my_ssetup (psetup_six_ttbar01j)
(rsetupGen p MLM NoUserCutDef NoPGS 20000 num)
my_csetup
| p <- sixparamset , num <- sets ]
totaltasklist :: [WorkSetup]
totaltasklist = sixtasklist
|
wavewave/madgraph-auto-dataset
|
src/HEP/Automation/MadGraph/Dataset/Set20110315set3.hs
|
gpl-3.0
| 1,536 | 0 | 8 | 366 | 315 | 194 | 121 | 39 | 1 |
module Exp2FA
( grammar2etnfa
)
where
import Set
import FiniteMap
import Grammar
import TA
import FAtypes
import Stuff
import Options
import Ids
------------------------------------------------------------------------
grammar2etnfa :: (Show a, Ord a) => Opts -> Grammar a -> ETNFA a
grammar2etnfa opts (start, rules) =
let
all = unionManySets ( unitSet start
: [ mkSet (v : stargs t) | (v, Right t) <- rules ]
++ [ mkSet (v : [w]) | (v, Left w ) <- rules ] )
moves = addListToFM_C unionSet emptyFM
[ (v, unitSet t) | (v, Right t) <- rules ]
eps = addListToFM_C unionSet emptyFM
[ (v, unitSet w) | (v, Left w) <- rules ]
cons = mkSet [ stcon t | (v, Right t) <- rules ]
e = ETNFA cons all (unitSet start) moves eps
in
-- trace ("\ngrammar2etnfa.e = " ++ show e) $
e
|
jwaldmann/rx
|
src/Exp2FA.hs
|
gpl-3.0
| 806 | 6 | 17 | 184 | 320 | 172 | 148 | 23 | 1 |
-- http://graybeardprogrammer.com/?p=1
-- In haskell this time.
data Operation a = Add | Subtract | Multiply | Divide | Push a
test_ops = [ Push 4, Push 3, Subtract, Push 1, Add, Push 5, Multiply ]
process state op =
let act = case op of
Add -> bin (+)
Subtract -> bin (-)
Multiply -> bin (*)
Divide -> bin (/)
Push a -> (:) a
where bin op (a2:a1:rest) = (op a1 a2) : rest
in act state
main = print $ show $ foldl process [] test_ops
|
jmesmon/trifles
|
vssm.hs
|
gpl-3.0
| 466 | 2 | 12 | 122 | 208 | 111 | 97 | 12 | 5 |
module BarterParams
( BarterParams -- note only export data-constructor, not the accessors
, mkBarterParams
, getNumGoods
, getConsumeArray
, getMaxTries
, getEquiPrice
, isCheckEfficiency
, getProduceGoodPriceFactor
, isEquiInitialPrices
, getAgentsPerGood
, isVarySupply
, getPriceUnitGood
, getStdDevGood
, getReproducePeriod
, getTotalAgents
, getReplacementRate
, getMutationDelta
, getMutationRate
) where
data BarterParams = BarterParams
{ agentsPerGood :: Int
, reproducePeriod :: Int
, replacementRate :: Double
, mutationRate :: Double
, mutationDelta :: Double
, consume :: [Double]
, maxTries :: Int
, producerShiftRate :: Double
, varySupply :: Bool
, checkEfficiency :: Bool
, equiInitialPrices :: Bool
, stdDevGood :: Int
, produceGoodPriceFactor :: Double
, updateFrequency :: Int
, skipChartFrames :: Int
, shouldQuit :: Bool
, seed :: Int
, equiPrice :: [Double]
} deriving Show
mkBarterParams :: BarterParams
mkBarterParams = BarterParams
{ agentsPerGood = 100
, reproducePeriod = 10
, replacementRate = 0.05
, mutationRate = 0.1
, mutationDelta = 0.95
, consume = consumeVector
, maxTries = 5
, producerShiftRate = 0.01
, varySupply = False
, checkEfficiency = False
, equiInitialPrices = False
, stdDevGood = 0
, produceGoodPriceFactor = 0.8
, updateFrequency = 2
, skipChartFrames = 100
, shouldQuit = False
, seed = 0
, equiPrice = eqPrice
}
where
consumeVector = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
eqPrice = calcEquiPrice consumeVector
calcEquiPrice :: [Double] -> [Double]
calcEquiPrice consumeVector
= map (cpug /) consumeVector
where
pug = length consumeVector - 1
cpug = consumeVector !! pug
getNumGoods :: BarterParams -> Int
getNumGoods = length . consume
getConsumeArray :: BarterParams -> [Double]
getConsumeArray = consume
getMaxTries :: BarterParams -> Int
getMaxTries = maxTries
getEquiPrice :: BarterParams -> [Double]
getEquiPrice = equiPrice
isCheckEfficiency :: BarterParams -> Bool
isCheckEfficiency = checkEfficiency
getProduceGoodPriceFactor :: BarterParams -> Double
getProduceGoodPriceFactor = produceGoodPriceFactor
isEquiInitialPrices :: BarterParams -> Bool
isEquiInitialPrices = equiInitialPrices
getAgentsPerGood :: BarterParams -> Int
getAgentsPerGood = agentsPerGood
isVarySupply :: BarterParams -> Bool
isVarySupply = varySupply
getPriceUnitGood :: BarterParams -> Int
getPriceUnitGood = (+(-1)) . length . consume
getStdDevGood :: BarterParams -> Int
getStdDevGood = stdDevGood
getReproducePeriod :: BarterParams -> Int
getReproducePeriod = reproducePeriod
-- it should be possible to write it point-free with arrows?
getTotalAgents :: BarterParams -> Int
getTotalAgents params = agentsPerGood params * getNumGoods params
getReplacementRate :: BarterParams -> Double
getReplacementRate = replacementRate
getMutationDelta :: BarterParams -> Double
getMutationDelta = mutationDelta
getMutationRate :: BarterParams -> Double
getMutationRate = mutationRate
|
thalerjonathan/phd
|
thesis/code/barter/haskell/src/BarterParams.hs
|
gpl-3.0
| 3,452 | 0 | 9 | 943 | 660 | 403 | 257 | 98 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module Language.Mulang.Interpreter (
defaultContext,
dereference,
dereference',
eval,
eval',
evalExpr,
evalRaising,
nullRef,
ExecutionContext(..),
Value(..)
) where
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.List (find, intercalate, genericLength)
import Control.Monad (forM, (>=>))
import Control.Monad.State.Class
import Control.Monad.Loops
import Control.Monad.State.Strict
import Control.Monad.Cont
import Data.Fixed (mod')
import qualified Language.Mulang.Ast as M
import qualified Language.Mulang.Ast.Operator as O
import Language.Mulang.Ast.Operator (opposite)
import Language.Mulang.Interpreter.Internals
eval' :: ExecutionContext -> Executable Reference -> IO (Reference, ExecutionContext)
eval' ctx ref = runStateT (runContT ref return) ctx
eval :: ExecutionContext -> M.Expression -> IO (Reference, ExecutionContext)
eval ctx expr = eval' ctx (evalExpr expr)
evalRaising :: ExecutionContext -> M.Expression -> Executable (Reference, Maybe Reference)
evalRaising context expr = do
resultRef <- callCC $ \raiseCallback -> do
put (context { currentRaiseCallback = raiseCallback })
evalExpr expr
return nullRef
lastException <- gets currentException
return (resultRef, lastException)
evalExpressionsWith :: [M.Expression] -> ([Value] -> Executable Reference) -> Executable Reference
evalExpressionsWith expressions f = do
params <- forM expressions evalExprValue
f params
evalExpressionsWith' :: [M.Expression] -> ([(Reference, Value)] -> Executable Reference) -> Executable Reference
evalExpressionsWith' expressions f = do
refs <- forM expressions evalExpr
values <- forM refs dereference
f $ zip refs values
evalExprValue :: M.Expression -> Executable Value
evalExprValue = evalExpr >=> dereference
evalExpr :: M.Expression -> Executable Reference
evalExpr (M.Sequence expressions) = last <$> forM expressions evalExpr
evalExpr (M.Lambda params body) = do
executionFrames <- gets scopes
createRef $
MuFunction executionFrames [M.Equation params (M.UnguardedBody body)]
evalExpr (M.Subroutine name body) = do
executionFrames <- gets scopes
let function = MuFunction executionFrames body
ref <- createRef function
unless (null name) (setLocalVariable name ref) -- if function has no name we avoid registering it
return ref
evalExpr (M.Print expression) = do
parameter <- evalExprValue expression
liftIO $ print parameter
return nullRef
evalExpr (M.Assert negated (M.Truth expression)) =
evalExpressionsWith [expression] f
where f [MuBool result]
| result /= negated = return nullRef
| otherwise = raiseString $ "Expected " ++ (show . not $ negated) ++ " but got: " ++ show result
evalExpr (M.Assert negated (M.Equality expected actual)) =
evalExpressionsWith [expected, actual] f
where f [v1, v2]
| muEquals v1 v2 /= negated = return nullRef
| otherwise = raiseString $ "Expected " ++ show v1 ++ " but got: " ++ show v2
evalExpr (M.Application (M.Primitive O.GreatherOrEqualThan) expressions) = evalBinaryNumeric expressions (>=) createBool
evalExpr (M.Application (M.Primitive O.Modulo) expressions) = evalBinaryNumeric expressions (mod') createNumber
evalExpr (M.Application (M.Primitive O.GreatherThan) expressions) = evalBinaryNumeric expressions (>) createBool
evalExpr (M.Application (M.Primitive O.Or) expressions) = evalBinaryBoolean expressions (||)
evalExpr (M.Application (M.Primitive O.And) expressions) = evalBinaryBoolean expressions (&&)
evalExpr (M.Application (M.Primitive O.Negation) expressions) =
evalExpressionsWith expressions f
where f [MuBool b] = createBool $ not b
f params = raiseTypeError "expected one boolean" params
evalExpr (M.Application (M.Primitive O.Push) expressions) =
evalExpressionsWith' expressions f
where f [(lr, MuList xs), (vr, _)] = updateRef lr (MuList (xs ++ [vr])) >> return vr
f params = raiseTypeError "{Push} expected a list" (map snd params)
evalExpr (M.Application (M.Primitive O.Size) expressions) =
evalExpressionsWith expressions f
where f [MuList xs] = createNumber $ genericLength xs
f [MuString s] = createNumber $ genericLength s
f params = raiseTypeError "{Size} expected a list or string" params
evalExpr (M.Application (M.Primitive O.GetAt) expressions) =
evalExpressionsWith expressions f
where f [MuObject m, MuString s] | Just ref <- Map.lookup s m = return ref
| otherwise = raiseString ("key error: " ++ s)
f params = raiseTypeError "expected an object" params
evalExpr (M.Application (M.Primitive O.SetAt) expressions) =
evalExpressionsWith' expressions f
where f [(or, MuObject _), (_, MuString s), (vr, _)] = modifyRef or (setObjectAt s vr) >> return vr
f params = raiseTypeError "expected an object" (map snd params)
evalExpr (M.Application (M.Primitive O.Multiply) expressions) = evalBinaryNumeric expressions (*) createNumber
evalExpr (M.Application (M.Primitive O.Like) expressions) = do
params <- forM expressions evalExpr
let [r1, r2] = params
muValuesEqual r1 r2
evalExpr (M.Application (M.Primitive [email protected]) expressions) = do
evalExpr $ M.Application (M.Primitive O.Negation) [M.Application (M.Primitive (opposite op)) expressions]
evalExpr (M.Application (M.Primitive O.LessOrEqualThan) expressions) = evalBinaryNumeric expressions (<=) createBool
evalExpr (M.Application (M.Primitive O.LessThan) expressions) = evalBinaryNumeric expressions (<) createBool
evalExpr (M.Application (M.Primitive O.Plus) expressions) = evalBinaryNumeric expressions (+) createNumber
evalExpr (M.Application (M.Primitive O.Minus) expressions) = evalBinaryNumeric expressions (-) createNumber
evalExpr (M.MuList expressions) = do
refs <- forM expressions evalExpr
createRef $ MuList refs
evalExpr (M.MuDict expression) = evalObject expression
evalExpr (M.MuObject expression) = evalObject expression
evalExpr (M.Object name expression) = evalExpr (M.Variable name (M.MuObject expression))
evalExpr (M.FieldAssignment e1 k e2) = evalExpr (M.Application (M.Primitive O.SetAt) [e1, M.MuString k, e2])
evalExpr (M.FieldReference expression k) = evalExpr (M.Application (M.Primitive O.GetAt) [expression, M.MuString k])
evalExpr (M.New klass expressions) = do
(MuFunction locals ([M.SimpleEquation params body])) <- evalExprValue klass
objReference <- createObject Map.empty
thisContext <- createObject $ Map.singleton "this" objReference
paramsContext <- evalParams params expressions
runFunction (thisContext:paramsContext:locals) body
return objReference
evalExpr (M.Application function expressions) = do
(MuFunction locals ([M.SimpleEquation params body])) <- evalExprValue function
paramsContext <- evalParams params expressions
returnValue <- runFunction (paramsContext:locals) (body)
return returnValue
evalExpr (M.If cond thenBranch elseBranch) = do
v <- evalCondition cond
if v then evalExpr thenBranch else evalExpr elseBranch
evalExpr (M.MuNumber n) = createNumber n
evalExpr (M.MuNil) = return nullRef
evalExpr (M.MuBool b) = createBool b
evalExpr (M.MuString s) = createRef $ MuString s
evalExpr (M.Return e) = do
ref <- evalExpr e
currentReturn <- gets (currentReturnCallback)
currentReturn ref
return ref -- Unreachable
evalExpr (M.Variable name expr) = do
r <- evalExpr expr
setLocalVariable name r
return r
evalExpr (M.While cond expr) = do
whileM (evalCondition cond) (evalExpr expr)
return nullRef
evalExpr (M.For [M.Generator (M.LValuePattern name) iterable] body) = do
(MuList elementRefs) <- evalExprValue iterable
forM elementRefs (\r -> do
setLocalVariable name r
evalExpr body)
return nullRef
evalExpr (M.ForLoop beforeExpr cond afterExpr expr) = do
evalExpr beforeExpr
whileM (evalCondition cond) $ do
evalExpr expr
evalExpr afterExpr
return nullRef
evalExpr (M.Assignment name expr) = do
valueRef <- evalExpr expr
frameRef <- findFrameForName' name
case frameRef of
Just ref -> modifyRef ref (setObjectAt name valueRef)
Nothing -> setLocalVariable name valueRef
return valueRef
evalExpr (M.Try expr [( M.VariablePattern exName, catchExpr)] finallyExpr) = do
context <- get
(resultRef, lastException) <- evalRaising context expr
modify' (\c ->
c { currentReturnCallback = currentReturnCallback context
, currentRaiseCallback = currentRaiseCallback context
, currentException = Nothing
})
case lastException of
Nothing -> return resultRef
Just ref -> do
setLocalVariable exName ref
evalExpr catchExpr
evalExpr finallyExpr
evalExpr (M.Raise expr) = raiseInternal =<< evalExpr expr
evalExpr (M.Reference name) = findReferenceForName name
evalExpr (M.None) = return nullRef
evalExpr e = raiseString $ "Unkown expression: " ++ show e
evalObject :: M.Expression -> Executable Reference
evalObject M.None = createObject (Map.empty)
evalObject (M.Sequence es) = do
arrowRefs <- forM es evalArrow
createObject $ Map.fromList arrowRefs
evalObject e = do
(s, vRef) <- evalArrow e
createObject $ Map.singleton s vRef
evalArrow :: M.Expression -> Executable (String, Reference)
evalArrow (M.LValue n v) = evalArrow (M.Arrow (M.MuString n) v)
evalArrow (M.Arrow k v) = do
(MuString s) <- evalExprValue k
vRef <- evalExpr v
return (s, vRef)
evalArrow e = raiseString ("malformed object arrow: " ++ show e)
-- TODO make this evaluation non strict on both parameters
evalBinaryBoolean :: [M.Expression] -> (Bool -> Bool -> Bool) -> Executable Reference
evalBinaryBoolean expressions op = evalExpressionsWith expressions f
where f [MuBool b1, MuBool b2] = createBool $ op b1 b2
f params = raiseTypeError "expected two booleans" params
evalBinaryNumeric :: [M.Expression] -> (Double -> Double -> a) -> (a -> Executable Reference) -> Executable Reference
evalBinaryNumeric expressions op pack = evalExpressionsWith expressions f
where f [MuNumber n1, MuNumber n2] = pack $ op n1 n2
f params = raiseTypeError "expected two numbers" params
evalCondition :: M.Expression -> Executable Bool
evalCondition cond = evalExprValue cond >>= muBool
where
muBool (MuBool value) = return value
muBool v = raiseTypeError "expected boolean" [v]
evalParams :: [M.Pattern] -> [M.Expression] -> Executable Reference
evalParams params arguments = do
evaluatedParams <- forM arguments evalExpr
let localsAfterParameters = Map.fromList $ zip (getParamNames params) (evaluatedParams ++ repeat nullRef)
createObject localsAfterParameters
raiseInternal :: Reference -> Executable b
raiseInternal exceptionRef = do
raiseCallback <- gets currentRaiseCallback
modify' (\c -> c {currentException = Just exceptionRef})
raiseCallback exceptionRef
raiseString "Unreachable" -- the callback above should never allow this to execute
raiseString :: String -> Executable a
raiseString s = do
raiseInternal =<< (createRef $ MuString s)
raiseTypeError :: String -> [Value] ->Executable a
raiseTypeError message values = raiseString $ "Type error: " ++ message ++ " but got " ++ (intercalate ", " . map debug $ values)
muValuesEqual r1 r2
| r1 == r2 = createRef $ MuBool True
| otherwise = do
v1 <- dereference r1
v2 <- dereference r2
createBool $ muEquals v1 v2
muEquals (MuBool b1) (MuBool b2) = b1 == b2
muEquals (MuNumber n1) (MuNumber n2) = n1 == n2
muEquals (MuString s1) (MuString s2) = s1 == s2
muEquals MuNull MuNull = True
muEquals _ _ = False
getParamNames :: [M.Pattern] -> [String]
getParamNames = fmap getParamName
where
getParamName (M.LValuePattern n) = n
getParamName other = error $ "Unsupported pattern " ++ (show other)
runFunction :: [Reference] -> M.Expression -> Executable Reference
runFunction functionEnv body = do
context <- get
returnValue <- callCC $ \(returnCallback) -> do
put (context { scopes = functionEnv, currentReturnCallback = returnCallback })
evalExpr body
return nullRef
modify' (\c -> c { scopes = scopes context
, currentReturnCallback = currentReturnCallback context
, currentRaiseCallback = currentRaiseCallback context
, currentException = currentException context
})
return returnValue
findFrameForName :: String -> Executable Reference
findFrameForName name = do
maybe (raiseString $ "Reference not found for name '" ++ name ++ "'") return
=<< findFrameForName' name
findFrameForName' :: String -> Executable (Maybe Reference)
findFrameForName' name = do
framesRefs <- gets scopes
frames :: [(Reference, Map String Reference)] <- forM framesRefs $ \ref -> do
dereference ref >>= \value -> case value of
(MuObject context) -> return (ref, context)
v -> error $ "Finding '" ++ name ++ "' the frame I got a non object " ++ show v
return $ fmap fst . find (Map.member name . snd) $ frames
findReferenceForName :: String -> Executable Reference
findReferenceForName name = do
ref <- findFrameForName name
(MuObject context) <- dereference ref
return $ context Map.! name
nullRef = Reference 0
createBool = createRef . MuBool
createNumber = createRef . MuNumber
createObject = createRef . MuObject
setLocalVariable :: String -> Reference -> Executable ()
setLocalVariable name ref = do
frame <- currentFrame
modifyRef frame (setObjectAt name ref)
where
currentFrame :: Executable Reference
currentFrame = gets (head . scopes)
setObjectAt :: String -> Reference -> Value -> Value
setObjectAt k r (MuObject map) = MuObject $ Map.insert k r map
setObjectAt k _r v = error $ "Tried adding " ++ k ++ " to a non object: " ++ show v
|
mumuki/mulang
|
src/Language/Mulang/Interpreter.hs
|
gpl-3.0
| 14,142 | 0 | 20 | 2,827 | 4,739 | 2,324 | 2,415 | 287 | 10 |
module STH.Lib.RegExpr where
data CharClass
= Alpha
| AlNum
| Punct
| Digit
deriving (Eq, Show)
data RegEx
= Literal Char
| Range Char Char
| AnyChar
| OneOf CharClass
| Choice [RegEx]
| Sequence [RegEx]
| Kleene RegEx
deriving (Eq, Show)
|
nbloomf/st-haskell
|
src/STH/Lib/RegExpr.hs
|
gpl-3.0
| 278 | 0 | 7 | 81 | 90 | 54 | 36 | 16 | 0 |
{-#LANGUAGE GADTs, ConstraintKinds, RankNTypes, FlexibleContexts, PatternSynonyms, TypeSynonymInstances, FlexibleInstances, MultiParamTypeClasses #-}
module Carnap.Languages.PureFirstOrder.Logic.Rules where
import Data.List (intercalate)
import Data.Typeable (Typeable)
import Data.Maybe (catMaybes)
import Control.Lens (toListOf,preview, Prism')
import Text.Parsec
import Carnap.Core.Data.Util
import Carnap.Core.Unification.Unification (applySub,occurs,FirstOrder, Equation, pureBNF)
import Carnap.Core.Data.Classes
import Carnap.Core.Data.Types
import Carnap.Core.Data.Optics
import Carnap.Languages.PurePropositional.Logic.Rules (exchange, replace)
import Carnap.Languages.PureFirstOrder.Syntax
import Carnap.Languages.PureFirstOrder.Parser
import Carnap.Languages.PureFirstOrder.Util
import Carnap.Languages.PurePropositional.Util
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.ClassicalSequent.Parser
import Carnap.Languages.Util.LanguageClasses
import Carnap.Languages.Util.GenericConstructors
import Carnap.Calculi.NaturalDeduction.Syntax (DeductionLine(..),depth,assertion,discharged,justificationOf,inScope, isAssumptionLine)
--------------------------------------------------------
--1. FirstOrder Sequent Calculus
--------------------------------------------------------
type FOLSequentCalc = ClassicalSequentOver PureLexiconFOL
type OpenFOLSequentCalc a = ClassicalSequentOver (PureFirstOrderLexWith a)
--we write the Copula schema at this level since we may want other schemata
--for sequent languages that contain things like quantifiers
instance CopulaSchema FOLSequentCalc where
appSchema q@(Fx _) (LLam f) e = case ( qtype q >>= preview _all >>= \x -> (,) <$> Just x <*> castTo (seqVar x)
, qtype q >>= preview _some >>= \x -> (,) <$> Just x <*> castTo (seqVar x)
) of
(Just (x,v), _) -> schematize (All x) (show (f v) : e)
(_, Just (x,v)) -> schematize (Some x) (show (f v) : e)
_ -> schematize q (show (LLam f) : e)
appSchema x y e = schematize x (show y : e)
lamSchema = defaultLamSchema
instance Eq (FOLSequentCalc a) where
(==) = (=*)
seqVar :: StandardVarLanguage (FixLang lex (Term Int)) => String -> FixLang lex (Term Int)
seqVar = var
tau :: IndexedSchemeConstantLanguage (FixLang lex (Term Int)) => FixLang lex (Term Int)
tau = taun 1
tau' :: IndexedSchemeConstantLanguage (FixLang lex (Term Int)) => FixLang lex (Term Int)
tau' = taun 2
tau'' :: IndexedSchemeConstantLanguage (FixLang lex (Term Int)) => FixLang lex (Term Int)
tau'' = taun 3
phi :: (Typeable b, PolyadicSchematicPredicateLanguage (FixLang lex) (Term Int) (Form b))
=> Int -> (FixLang lex) (Term Int) -> (FixLang lex) (Form b)
phi n x = pphin n AOne :!$: x
phi' :: PolyadicSchematicPredicateLanguage (FixLang lex) (Term Int) (Form Bool)
=> Int -> (FixLang lex) (Term Int) -> (FixLang lex) (Form Bool)
phi' n x = pphin n AOne :!$: x
theta :: SchematicPolyadicFunctionLanguage (FixLang lex) (Term Int) (Term Int)
=> (FixLang lex) (Term Int) -> (FixLang lex) (Term Int)
theta x = spfn 1 AOne :!$: x
eigenConstraint ::
( PrismStandardVar (ClassicalSequentLexOver lex) Int
, PrismIndexedConstant (ClassicalSequentLexOver lex) Int
, PrismPolyadicSchematicFunction (ClassicalSequentLexOver lex) Int Int
, Schematizable (lex (ClassicalSequentOver lex))
, FirstOrderLex (lex (ClassicalSequentOver lex))
, CopulaSchema (ClassicalSequentOver lex)
, PrismSubstitutionalVariable (ClassicalSequentLexOver lex)
) => ClassicalSequentOver lex (Term Int)
-> ClassicalSequentOver lex (Succedent (Form Bool))
-> ClassicalSequentOver lex (Antecedent (Form Bool))
-> [Equation (ClassicalSequentOver lex)]
-> Maybe String
eigenConstraint c suc ant sub
| (applySub sub c) `occurs` (applySub sub ant) = Just $ "The term " ++ show (applySub sub c) ++ " appears not to be fresh. "
++ "Check the dependencies of this inference for occurances of " ++ show (applySub sub c) ++ "."
| (applySub sub c) `occurs` (applySub sub suc) = Just $ "The term " ++ show (applySub sub c) ++ " appears not to be fresh. "
++ "Check the dependencies of this inference for occurances of " ++ show (applySub sub c) ++ "."
| otherwise = case (applySub sub c) of
_ | not . null $ preview _sfuncIdx' (applySub sub c) -> Nothing
| not . null $ preview _constIdx (applySub sub c) -> Nothing
| not . null $ preview _varLabel (applySub sub c) -> Nothing
_ -> Just $ "The term " ++ show (pureBNF $ applySub sub c) ++ " is not a constant or variable"
where _sfuncIdx' :: PrismPolyadicSchematicFunction (ClassicalSequentLexOver lex) Int Int
=> Prism' (ClassicalSequentOver lex (Term Int)) (Int, Arity (Term Int) (Term Int) (Term Int))
_sfuncIdx' = _sfuncIdx
tautologicalConstraint prems conc sub = case prems' of
[] | isValid (propForm conc') -> Nothing
(p':ps') | isValid (propForm $ foldr (./\.) p' ps' .=>. conc') -> Nothing
[] | otherwise -> Just $ show conc' ++ " is not truth-functional validity"
_ | otherwise -> Just $ show conc' ++ " is not a truth functional consequence of " ++ intercalate ", " (map show prems')
where prems' = map (applySub sub) prems
conc' = applySub sub conc
totallyFreshConstraint n ded t v sub
| any (\x -> v `occurs`x) relevantLines = Just $ show v ++ " appears not to be fresh on line " ++ show n
| tau' /= (liftToSequent v) = Just "the flagged variable isn't the one used for instantiation."
| otherwise = Nothing
where relevantLines = catMaybes . map assertion $ (take (n - 1) ded)
tau' = applySub sub t
notAssumedConstraint n ded t sub
| any (\x -> tau' `occurs` (liftToSequent x)) relevantLines = Just $ show tau' ++ " appears not to be fresh in its occurence on line " ++ show n
| otherwise = Nothing
where relevantLines = catMaybes . map assertion . filter isAssumptionLine . scopeFilter . take (n - 1) $ ded
scopeFilter l = map fst . filter (inScope . snd) $ zip l [1 ..]
inScope m = (>= (depth $ ded !! (m - 1))) . minimum . map depth . drop (m - 1) . take n $ ded
tau' = applySub sub t
flaggedVariableConstraint n ded suc getFlag sub =
case targetlinenos of
[x] | x < min n (length ded) -> checkFlag (ded !! (x - 1))
_ -> Just "wrong number of lines discharged"
where targetlinenos = discharged (ded !! (n - 1))
scope = inScope (ded !! (n - 1))
forms = catMaybes . map (\n -> liftToSequent <$> assertion (ded !! (n - 1))) $ scope
suc' = applySub sub suc
checkFlag x = case justificationOf x of
Just rs -> case getFlag (head rs) of
Left s -> Just s
Right v'| any (\x -> v' `occurs` x) forms -> Just $ "The term " ++ show v' ++ " occurs in one of the dependencies " ++ show forms
| v' `occurs` suc' -> Just $ "The term " ++ show v' ++ " occurs in the conclusion " ++ show suc'
| otherwise -> Nothing
_ -> Just "the line cited has no justification"
globalOldConstraint cs (Left ded) lineno sub =
if all (\c -> any (\x -> c `occurs`x) relevantLines) cs'
then Nothing
else Just $ "a constant in " ++ show cs' ++ " appears not to be old, but this rule needs old constants"
where cs' = map (applySub sub) cs
relevantLines = catMaybes . map (fmap liftLang . assertion) $
((oldRelevant [] $ take (lineno - 1) ded) ++ fromsp)
--some extra lines that we need to add if we're putting this
--constraint on a subproof-closing rule
fromsp = case ded !! (lineno - 1) of
ShowWithLine _ d _ _ ->
case takeWhile (\x -> depth x > d) . drop lineno $ ded of
sp@(h:t) -> filter (witnessAt (depth h)) sp
[] -> []
_ -> []
oldRelevant accum [] = accum
oldRelevant [] (d:ded) = oldRelevant [d] ded
oldRelevant (a:accum) (d:ded) = if depth d < depth a
then let accum' = filter (witnessAt (depth d)) accum in
oldRelevant (d:accum') ded
else oldRelevant (d:a:accum) ded
witnessAt ldepth (ShowWithLine _ sdepth _ _) = sdepth < ldepth
witnessAt ldepth l = depth l <= ldepth
globalNewConstraint cs ded lineno sub =
case checkNew of
Nothing -> Just $ "a constant in " ++ show cs' ++ " appears not to be new, but this rule needs new constants"
Just s -> Nothing
where cs' = map (applySub sub) cs
checkNew = mapM (\c -> globalOldConstraint [c] ded lineno sub) cs
montagueNewExistentialConstraint cs ded lineno sub =
if any (\x -> any (occursIn x) relevantForms) cs'
then Just $ "a variable in " ++ show cs' ++ " occurs before this line. This rule requires a variable not occuring (free or bound) on any earlier line"
else Nothing
where cs' = map (fromSequent . applySub sub) cs
relevantLines = take (lineno - 1) ded
relevantForms = catMaybes $ map assertion relevantLines
occursIn x y = occurs x y
|| boundVarOf x y
|| any (boundVarOf x) (toListOf formsOf y)
montagueNewUniversalConstraint cs ded lineno sub =
case relevantForms of
[] -> Just "No show line found for this rule. But this rule requires a preceeding show line. Remeber to align opening and closing lines of subproofs."
x:xs | boundVarOf c' x -> if any (occurs c') xs
then Just $ "The variable " ++ show c' ++ " occurs freely somewhere before the show line of this rule"
else Nothing
_ -> Just $ "The variable " ++ show c' ++ " is not bound in the show line of this rule."
where c' = fromSequent $ applySub sub (head cs)
relevantLines = dropWhile (not . isShow) $ reverse $ take lineno ded
--XXX: for now we ignore the complication of making sure these
--are *available* lines.
relevantForms = catMaybes $ map assertion relevantLines
isShow (ShowLine _ d) = d == depth (ded !! (lineno - 1))
isShow _ = False
-------------------------
-- 1.1. Common Rules --
-------------------------
type FirstOrderConstraints lex b =
( Typeable b
, BooleanLanguage (ClassicalSequentOver lex (Form b))
, IndexedSchemeConstantLanguage (ClassicalSequentOver lex (Term Int))
, IndexedSchemePropLanguage (ClassicalSequentOver lex (Form b))
, QuantLanguage (ClassicalSequentOver lex (Form b)) (ClassicalSequentOver lex (Term Int))
, PolyadicSchematicPredicateLanguage (ClassicalSequentOver lex) (Term Int) (Form b)
)
type FirstOrderRule lex b = FirstOrderConstraints lex b => SequentRule lex (Form b)
type FirstOrderEqRule lex b =
( FirstOrderConstraints lex b
, EqLanguage (ClassicalSequentOver lex) (Term Int) (Form b)
) => SequentRule lex (Form b)
eqReflexivity :: FirstOrderEqRule lex b
eqReflexivity = [] ∴ Top :|-: SS (tau `equals` tau)
eqSymmetry :: FirstOrderEqRule lex b
eqSymmetry = [GammaV 1 :|-: SS (tau `equals` tau')] ∴ GammaV 1 :|-: SS (tau' `equals` tau)
eqTransitivity :: FirstOrderEqRule lex b
eqTransitivity = [GammaV 1 :|-: SS (tau `equals` tau')
, GammaV 1 :|-: SS (tau' `equals` tau'')
] ∴ GammaV 1 :|-: SS (tau `equals` tau'')
eqNegSymmetry :: FirstOrderEqRule lex b
eqNegSymmetry = [GammaV 1 :|-: SS (lneg $ tau `equals` tau')] ∴ GammaV 1 :|-: SS (lneg $ tau' `equals` tau)
universalGeneralization :: FirstOrderRule lex b
universalGeneralization = [ GammaV 1 :|-: SS (phi 1 (taun 1))]
∴ GammaV 1 :|-: SS (lall "v" (phi 1))
universalInstantiation :: FirstOrderRule lex b
universalInstantiation = [ GammaV 1 :|-: SS (lall "v" (phi 1))]
∴ GammaV 1 :|-: SS (phi 1 (taun 1))
existentialGeneralization :: FirstOrderRule lex b
existentialGeneralization = [ GammaV 1 :|-: SS (phi 1 (taun 1))]
∴ GammaV 1 :|-: SS (lsome "v" (phi 1))
existentialInstantiation :: FirstOrderRule lex b
existentialInstantiation = [ GammaV 1 :|-: SS (lsome "v" (phi 1))]
∴ GammaV 1 :|-: SS (phi 1 (taun 1))
existentialAssumption :: FirstOrderRule lex b
existentialAssumption = [ GammaV 1 :|-: SS (lsome "v" (phi 1))]
∴ GammaV 1 :+: SA (phi 1 (taun 1)) :|-: SS (phi 1 (taun 1))
existentialAssumptionDischarge :: FirstOrderRule lex b
existentialAssumptionDischarge = [ GammaV 1 :+: SA (phi 1 (taun 1)) :|-: SS (phi 1 (taun 1))
, GammaV 2 :+: SA (phi 1 (taun 1)) :|-: SS (phin 1) ]
∴ GammaV 2 :|-: SS (phin 1)
weakExistentialDerivation :: FirstOrderRule lex b
weakExistentialDerivation = [ GammaV 1 :|-: SS (phin 1)
, GammaV 2 :|-: SS (lsome "v" $ phi 1)
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (phin 1)
parameterExistentialDerivation :: FixLang (ClassicalSequentLexOver lex) (Term Int) -> FirstOrderRule lex b
parameterExistentialDerivation t = [ GammaV 1 :+: SA (phi 1 t) :|-: SS (phin 1)
, GammaV 2 :|-: SS (lsome "v" $ phi 1)
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (phin 1)
negatedExistentialInstantiation :: FirstOrderRule lex b
negatedExistentialInstantiation = [ GammaV 1 :|-: SS (lneg $ lsome "v" (phi 1))]
∴ GammaV 1 :|-: SS (lneg $ phi 1 (taun 1))
negatedUniversalInstantiation :: FirstOrderRule lex b
negatedUniversalInstantiation = [ GammaV 1 :|-: SS (lneg $ lall "v" (phi 1))]
∴ GammaV 1 :|-: SS (lneg $ phi 1 (taun 1))
conditionalExistentialDerivation :: FirstOrderRule lex b
conditionalExistentialDerivation = [ GammaV 1 :|-: SS (lsome "v" (phi 1))
, GammaV 2 :|-: SS (phi 1 (taun 1) .→. phin 1)
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (phin 1)
------------------------------------
-- 1.2. Rules with Variations --
------------------------------------
type FirstOrderRuleVariants lex b = FirstOrderConstraints lex b => [SequentRule lex (Form b)]
type FirstOrderEqRuleVariants lex b =
( FirstOrderConstraints lex b
, EqLanguage (ClassicalSequentOver lex) (Term Int) (Form b)
, SchematicPolyadicFunctionLanguage (ClassicalSequentOver lex) (Term Int) (Term Int)
) => [SequentRule lex (Form b)]
leibnizLawVariations :: FirstOrderEqRuleVariants lex b
leibnizLawVariations = [
[ GammaV 1 :|-: SS (phi 1 tau)
, GammaV 2 :|-: SS (tau `equals` tau')
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (phi 1 tau')
,
[ GammaV 1 :|-: SS (phi 1 tau')
, GammaV 2 :|-: SS (tau `equals` tau')
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (phi 1 tau)
]
antiLeibnizLawVariations :: FirstOrderEqRuleVariants lex b
antiLeibnizLawVariations = [
[ GammaV 1 :|-: SS (phi 1 tau)
, GammaV 2 :|-: SS (lneg $ phi 1 tau')
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (lneg $ tau `equals` tau')
,
[ GammaV 1 :|-: SS (phi 1 tau)
, GammaV 2 :|-: SS (lneg $ phi 1 tau')
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (lneg $ tau' `equals` tau)
]
euclidsLawVariations :: FirstOrderEqRuleVariants lex b
euclidsLawVariations = [
[ GammaV 2 :|-: SS (tau `equals` tau')
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (theta tau `equals` theta tau')
,
[ GammaV 2 :|-: SS (tau `equals` tau')
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (theta tau' `equals` theta tau)
]
existentialDerivation :: FirstOrderRuleVariants lex b
existentialDerivation = [
[ GammaV 1 :+: SA (phi 1 tau) :|-: SS (phin 1)
, GammaV 2 :|-: SS (lsome "v" $ phi 1)
, SA (phi 1 tau) :|-: SS (phi 1 tau)
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (phin 1)
,
[ GammaV 1 :|-: SS (phin 1)
, SA (phi 1 tau) :|-: SS (phi 1 tau)
, GammaV 2 :|-: SS (lsome "v" $ phi 1)
] ∴ GammaV 1 :+: GammaV 2 :|-: SS (phin 1)
]
quantifierNegation :: FirstOrderRuleVariants lex b
quantifierNegation = exchange (lneg $ lsome "v" $ phi 1) (lall "v" $ lneg . phi 1)
++ exchange (lsome "v" $ lneg . phi 1) (lneg $ lall "v" $ phi 1)
++ exchange (lneg $ lsome "v" $ lneg . phi 1) (lall "v" $ phi 1)
++ exchange (lsome "v" $ phi 1) (lneg $ lall "v" $ lneg . phi 1)
quantifierNegationReplace :: IndexedPropContextSchemeLanguage (ClassicalSequentOver lex (Form b)) => FirstOrderRuleVariants lex b
quantifierNegationReplace = replace (lneg $ lsome "v" $ phi 1) (lall "v" $ lneg . phi 1)
++ replace (lsome "v" $ lneg . phi 1) (lneg $ lall "v" $ phi 1)
|
opentower/carnap
|
Carnap/src/Carnap/Languages/PureFirstOrder/Logic/Rules.hs
|
gpl-3.0
| 18,518 | 1 | 19 | 5,992 | 5,976 | 3,005 | 2,971 | 266 | 8 |
{-# 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.Compute.InstanceGroupManagers.SetInstanceTemplate
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Specifies the instance template to use when creating new instances in
-- this group. The templates for existing instances in the group do not
-- change unless you run recreateInstances, run applyUpdatesToInstances, or
-- set the group\'s updatePolicy.type to PROACTIVE.
--
-- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.instanceGroupManagers.setInstanceTemplate@.
module Network.Google.Resource.Compute.InstanceGroupManagers.SetInstanceTemplate
(
-- * REST Resource
InstanceGroupManagersSetInstanceTemplateResource
-- * Creating a Request
, instanceGroupManagersSetInstanceTemplate
, InstanceGroupManagersSetInstanceTemplate
-- * Request Lenses
, igmsitRequestId
, igmsitProject
, igmsitInstanceGroupManager
, igmsitZone
, igmsitPayload
) where
import Network.Google.Compute.Types
import Network.Google.Prelude
-- | A resource alias for @compute.instanceGroupManagers.setInstanceTemplate@ method which the
-- 'InstanceGroupManagersSetInstanceTemplate' request conforms to.
type InstanceGroupManagersSetInstanceTemplateResource
=
"compute" :>
"v1" :>
"projects" :>
Capture "project" Text :>
"zones" :>
Capture "zone" Text :>
"instanceGroupManagers" :>
Capture "instanceGroupManager" Text :>
"setInstanceTemplate" :>
QueryParam "requestId" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON]
InstanceGroupManagersSetInstanceTemplateRequest
:> Post '[JSON] Operation
-- | Specifies the instance template to use when creating new instances in
-- this group. The templates for existing instances in the group do not
-- change unless you run recreateInstances, run applyUpdatesToInstances, or
-- set the group\'s updatePolicy.type to PROACTIVE.
--
-- /See:/ 'instanceGroupManagersSetInstanceTemplate' smart constructor.
data InstanceGroupManagersSetInstanceTemplate =
InstanceGroupManagersSetInstanceTemplate'
{ _igmsitRequestId :: !(Maybe Text)
, _igmsitProject :: !Text
, _igmsitInstanceGroupManager :: !Text
, _igmsitZone :: !Text
, _igmsitPayload :: !InstanceGroupManagersSetInstanceTemplateRequest
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstanceGroupManagersSetInstanceTemplate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'igmsitRequestId'
--
-- * 'igmsitProject'
--
-- * 'igmsitInstanceGroupManager'
--
-- * 'igmsitZone'
--
-- * 'igmsitPayload'
instanceGroupManagersSetInstanceTemplate
:: Text -- ^ 'igmsitProject'
-> Text -- ^ 'igmsitInstanceGroupManager'
-> Text -- ^ 'igmsitZone'
-> InstanceGroupManagersSetInstanceTemplateRequest -- ^ 'igmsitPayload'
-> InstanceGroupManagersSetInstanceTemplate
instanceGroupManagersSetInstanceTemplate pIgmsitProject_ pIgmsitInstanceGroupManager_ pIgmsitZone_ pIgmsitPayload_ =
InstanceGroupManagersSetInstanceTemplate'
{ _igmsitRequestId = Nothing
, _igmsitProject = pIgmsitProject_
, _igmsitInstanceGroupManager = pIgmsitInstanceGroupManager_
, _igmsitZone = pIgmsitZone_
, _igmsitPayload = pIgmsitPayload_
}
-- | An optional request ID to identify requests. Specify a unique request ID
-- so that if you must retry your request, the server will know to ignore
-- the request if it has already been completed. For example, consider a
-- situation where you make an initial request and the request times out.
-- If you make the request again with the same request ID, the server can
-- check if original operation with the same request ID was received, and
-- if so, will ignore the second request. This prevents clients from
-- accidentally creating duplicate commitments. The request ID must be a
-- valid UUID with the exception that zero UUID is not supported
-- (00000000-0000-0000-0000-000000000000).
igmsitRequestId :: Lens' InstanceGroupManagersSetInstanceTemplate (Maybe Text)
igmsitRequestId
= lens _igmsitRequestId
(\ s a -> s{_igmsitRequestId = a})
-- | Project ID for this request.
igmsitProject :: Lens' InstanceGroupManagersSetInstanceTemplate Text
igmsitProject
= lens _igmsitProject
(\ s a -> s{_igmsitProject = a})
-- | The name of the managed instance group.
igmsitInstanceGroupManager :: Lens' InstanceGroupManagersSetInstanceTemplate Text
igmsitInstanceGroupManager
= lens _igmsitInstanceGroupManager
(\ s a -> s{_igmsitInstanceGroupManager = a})
-- | The name of the zone where the managed instance group is located.
igmsitZone :: Lens' InstanceGroupManagersSetInstanceTemplate Text
igmsitZone
= lens _igmsitZone (\ s a -> s{_igmsitZone = a})
-- | Multipart request metadata.
igmsitPayload :: Lens' InstanceGroupManagersSetInstanceTemplate InstanceGroupManagersSetInstanceTemplateRequest
igmsitPayload
= lens _igmsitPayload
(\ s a -> s{_igmsitPayload = a})
instance GoogleRequest
InstanceGroupManagersSetInstanceTemplate
where
type Rs InstanceGroupManagersSetInstanceTemplate =
Operation
type Scopes InstanceGroupManagersSetInstanceTemplate
=
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/compute"]
requestClient
InstanceGroupManagersSetInstanceTemplate'{..}
= go _igmsitProject _igmsitZone
_igmsitInstanceGroupManager
_igmsitRequestId
(Just AltJSON)
_igmsitPayload
computeService
where go
= buildClient
(Proxy ::
Proxy
InstanceGroupManagersSetInstanceTemplateResource)
mempty
|
brendanhay/gogol
|
gogol-compute/gen/Network/Google/Resource/Compute/InstanceGroupManagers/SetInstanceTemplate.hs
|
mpl-2.0
| 6,809 | 0 | 19 | 1,482 | 642 | 384 | 258 | 110 | 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.FirebaseDynamicLinks.ReopenAttribution
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Get iOS reopen attribution for app universal link open deeplinking.
--
-- /See:/ <https://firebase.google.com/docs/dynamic-links/ Firebase Dynamic Links API Reference> for @firebasedynamiclinks.reopenAttribution@.
module Network.Google.Resource.FirebaseDynamicLinks.ReopenAttribution
(
-- * REST Resource
ReopenAttributionResource
-- * Creating a Request
, reopenAttribution
, ReopenAttribution
-- * Request Lenses
, raXgafv
, raUploadProtocol
, raAccessToken
, raUploadType
, raPayload
, raCallback
) where
import Network.Google.FirebaseDynamicLinks.Types
import Network.Google.Prelude
-- | A resource alias for @firebasedynamiclinks.reopenAttribution@ method which the
-- 'ReopenAttribution' request conforms to.
type ReopenAttributionResource =
"v1" :>
"reopenAttribution" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] GetIosReopenAttributionRequest :>
Post '[JSON] GetIosReopenAttributionResponse
-- | Get iOS reopen attribution for app universal link open deeplinking.
--
-- /See:/ 'reopenAttribution' smart constructor.
data ReopenAttribution =
ReopenAttribution'
{ _raXgafv :: !(Maybe Xgafv)
, _raUploadProtocol :: !(Maybe Text)
, _raAccessToken :: !(Maybe Text)
, _raUploadType :: !(Maybe Text)
, _raPayload :: !GetIosReopenAttributionRequest
, _raCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ReopenAttribution' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'raXgafv'
--
-- * 'raUploadProtocol'
--
-- * 'raAccessToken'
--
-- * 'raUploadType'
--
-- * 'raPayload'
--
-- * 'raCallback'
reopenAttribution
:: GetIosReopenAttributionRequest -- ^ 'raPayload'
-> ReopenAttribution
reopenAttribution pRaPayload_ =
ReopenAttribution'
{ _raXgafv = Nothing
, _raUploadProtocol = Nothing
, _raAccessToken = Nothing
, _raUploadType = Nothing
, _raPayload = pRaPayload_
, _raCallback = Nothing
}
-- | V1 error format.
raXgafv :: Lens' ReopenAttribution (Maybe Xgafv)
raXgafv = lens _raXgafv (\ s a -> s{_raXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
raUploadProtocol :: Lens' ReopenAttribution (Maybe Text)
raUploadProtocol
= lens _raUploadProtocol
(\ s a -> s{_raUploadProtocol = a})
-- | OAuth access token.
raAccessToken :: Lens' ReopenAttribution (Maybe Text)
raAccessToken
= lens _raAccessToken
(\ s a -> s{_raAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
raUploadType :: Lens' ReopenAttribution (Maybe Text)
raUploadType
= lens _raUploadType (\ s a -> s{_raUploadType = a})
-- | Multipart request metadata.
raPayload :: Lens' ReopenAttribution GetIosReopenAttributionRequest
raPayload
= lens _raPayload (\ s a -> s{_raPayload = a})
-- | JSONP
raCallback :: Lens' ReopenAttribution (Maybe Text)
raCallback
= lens _raCallback (\ s a -> s{_raCallback = a})
instance GoogleRequest ReopenAttribution where
type Rs ReopenAttribution =
GetIosReopenAttributionResponse
type Scopes ReopenAttribution =
'["https://www.googleapis.com/auth/firebase"]
requestClient ReopenAttribution'{..}
= go _raXgafv _raUploadProtocol _raAccessToken
_raUploadType
_raCallback
(Just AltJSON)
_raPayload
firebaseDynamicLinksService
where go
= buildClient
(Proxy :: Proxy ReopenAttributionResource)
mempty
|
brendanhay/gogol
|
gogol-firebase-dynamiclinks/gen/Network/Google/Resource/FirebaseDynamicLinks/ReopenAttribution.hs
|
mpl-2.0
| 4,746 | 0 | 16 | 1,085 | 702 | 409 | 293 | 103 | 1 |
{-# LANGUAGE CPP, FlexibleInstances, TypeSynonymInstances #-}
--
-- Copyright (c) 2005-2022 Stefan Wehr - http://www.stefanwehr.de
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
--
{- |
This module defines the 'Pretty' type class. The assert functions
from 'Test.Framework.HUnitWrapper' use the pretty-printing functionality
provided by this type class so as to provide nicely formatted
error messages.
Additionally, this module re-exports the standard Haskell pretty-printing module
'Text.PrettyPrint'
-}
module Test.Framework.Pretty (
Pretty(..), (<=>),
module Text.PrettyPrint
)
where
#if MIN_VERSION_base(4,11,0)
-- Text.PrettyPrint exports (<>) conflicting with newer Prelude.
import Text.PrettyPrint hiding ((<>))
#else
import Text.PrettyPrint
#endif
-- | A type class for pretty-printable things.
-- Minimal complete definition: @pretty@.
class Pretty a where
-- | Pretty-print a single value.
pretty :: a -> Doc
-- | Pretty-print a list of things.
prettyList :: [a] -> Doc
prettyList l =
char '[' <> vcat (punctuate comma (map pretty l)) <> char ']'
-- | Pretty-print a single value as a 'String'.
showPretty :: a -> String
showPretty = render . pretty
{-
instance Pretty String where
pretty = text
-}
instance Pretty Char where
pretty = char
prettyList s = text s
instance Pretty a => Pretty [a] where
pretty = prettyList
instance Pretty Int where
pretty = int
instance Pretty Bool where
pretty = text . show
-- | Utility function for inserting a @=@ between two 'Doc' values.
(<=>) :: Doc -> Doc -> Doc
d1 <=> d2 = d1 <+> equals <+> d2
|
skogsbaer/HTF
|
Test/Framework/Pretty.hs
|
lgpl-2.1
| 2,320 | 0 | 13 | 448 | 270 | 161 | 109 | 23 | 1 |
{-# language DeriveFunctor, DeriveFoldable, DeriveTraversable #-}
module StoryMode.Types where
import Data.Binary
import Data.Initial
-- | Versioned!
-- Saves the state of an episode.
-- 1. How many batteries were put in the battery terminal.
-- (How many batteries are collected in total will be calculated by the
-- highscores.)
-- (Which stage is available (intro, body, outro) should be calculated by the highscores.)
data EpisodeScore
= EpisodeScore_0 {
usedBatteryTerminal :: Bool,
batteriesInTerminal :: Integer
}
deriving Show
instance Initial EpisodeScore where
initial = EpisodeScore_0 False 0
instance Binary EpisodeScore where
put (EpisodeScore_0 ubt batts) = do
putWord8 0
put ubt
put batts
get = do
0 <- getWord8
EpisodeScore_0 <$> get <*> get
data EpisodeUID
= Episode_1
deriving (Show, Eq, Ord)
instance Binary EpisodeUID where
put Episode_1 = putWord8 1
get = do
1 <- getWord8
return Episode_1
data Episode a = Episode {
euid :: EpisodeUID,
intro :: a,
body :: [a],
outro :: a,
happyEnd :: a
}
deriving (Show, Functor, Foldable, Traversable)
|
nikki-and-the-robots/nikki
|
src/StoryMode/Types.hs
|
lgpl-3.0
| 1,223 | 0 | 9 | 329 | 251 | 137 | 114 | 34 | 0 |
{-
Created : by NICTA.
Last Modified : 2014 Jul 15 (Tue) 04:43:38 by Harold Carr.
-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- + Complete the 10 exercises below by filling out the function bodies.
-- Replace the function bodies (error "todo") with an appropriate solution.
-- + These exercises may be done in any order, however:
-- Exercises are generally increasing in difficulty, though some people may find later exercise easier.
-- + Bonus for using the provided functions or for using one exercise solution to help solve another.
-- + Approach with your best available intuition; just dive in and do what you can!
module Course.List where
import Course.Core
import Course.Optional
import qualified Numeric as N
import qualified Prelude as P
import qualified System.Environment as E
import qualified Test.HUnit as T
import qualified Test.HUnit.Util as U
-- $setup
-- >>> import Test.QuickCheck
-- >>> import Course.Core(even, id, const)
-- >>> import qualified Prelude as P(fmap, foldr)
-- >>> instance Arbitrary a => Arbitrary (List a) where arbitrary = P.fmap (P.foldr (:.) Nil) arbitrary
-- BEGIN Helper functions and data types
-- The custom list type
data List t =
Nil
| t :. List t
deriving (Eq, Ord)
-- Right-associative
infixr 5 :.
instance Show t => Show (List t) where
show = show . foldRight (:) []
-- The list of integers from zero to infinity.
infinity ::
List Integer
infinity = infinityFrom 0
-- HC : open up so I can use below.
infinityFrom :: Num t => t -> List t
infinityFrom x = x :. infinityFrom (x+1)
-- functions over List that you may consider using
foldRight :: (a -> b -> b) -> b -> List a -> b
foldRight _ b Nil = b
foldRight f b (h :. t) = f h (foldRight f b t)
-- HC: this is a strict foldLeft (via `seq`).
foldLeft :: (b -> a -> b) -> b -> List a -> b
foldLeft _ b Nil = b
foldLeft f b (h :. t) = let b' = f b h in b' `seq` foldLeft f b' t
-- END Helper functions and data types
-- | Returns the head of the list or the given default.
--
-- >>> headOr 3 (1 :. 2 :. Nil)
-- 1
--
-- >>> headOr 3 Nil
-- 3
--
-- prop> x `headOr` infinity == 0
--
-- prop> x `headOr` Nil == x
headOr ::
a
-> List a
-> a
headOr = foldRight const
-- HC
-- headOr a Nil = a
-- headOr _ (h:._) = h
tho1 :: [T.Test]
tho1 = U.tt "tho1"
[ headOr (-1) infinity
, foldRight const (-1) infinity -- def of headOr
, const 0 (foldRight const ((-1)::Int) (infinityFrom (0+1))) -- def of foldRight non-Nil case
]
0 -- def of const
tho2 :: [T.Test]
tho2 = U.tt "tho2"
[ headOr (-1) Nil
, foldRight const (-1) Nil -- def of headOr
]
((-1)::Int) -- def of foldRight Nil case
-- | The product of the elements of a list.
--
-- >>> product (1 :. 2 :. 3 :. Nil)
-- 6
--
-- >>> product (1 :. 2 :. 3 :. 4 :. Nil)
-- 24
product ::
List Int
-> Int
product = foldRight (*) 1
productC :: List Int -> Int
productC = foldLeft (*) 1
tp1 :: [T.Test]
tp1 = U.tt "tp1"
[ product (2:. 3:.Nil)
, foldRight (*) 1 (2:. 3:.Nil) -- def of product
, (*) 2 (foldRight (*) 1 (3:.Nil)) -- def of foldRight non-Nil
, (*) 2 ((*) 3 (foldRight (*) 1 Nil)) -- "
, (*) 2 ((*) 3 1) -- def of foldRight Nil
]
6 -- def of (*)
tp2 :: [T.Test]
tp2 = U.tt "tp2"
[ productC (2:.3:.Nil)
, (*) 1 (2::Int) `seq` foldLeft (*) ((*) 1 2) (3:.Nil)
, foldLeft (*) 1 (2:. 3:.Nil)
, (2::Int) `seq` foldLeft (*) 2 (3:.Nil)
, 2 `seq` (*) 2 3 `seq` foldLeft (*) ((*) 2 3) Nil
, 2 `seq` 6 `seq` foldLeft (*) 6 Nil
, 2 `seq` 6 `seq` 6 -- http://www.haskell.org/haskellwiki/Seq
]
6
-- | Sum the elements of the list.
--
-- >>> sum (1 :. 2 :. 3 :. Nil)
-- 6
--
-- >>> sum (1 :. 2 :. 3 :. 4 :. Nil)
-- 10
--
-- prop> foldLeft (-) (sum x) x == 0
sum ::
List Int
-> Int
sum = foldRight (+) 0
sumC :: List Int -> Int
sumC = foldLeft (+) 0
-- | Return the length of the list.
--
-- >>> length (1 :. 2 :. 3 :. Nil)
-- 3
--
-- prop> sum (map (const 1) x) == length x
length ::
List a
-> Int
length = foldLeft (const . succ) 0
-- HC: length = foldRight (\_ acc -> acc + 1) 0
tlc :: [T.Test]
tlc = U.tt "tlc"
[ length (10:. 20:.Nil)
, foldLeft (const . succ) 0 (10:. 20:.Nil)
, (const . succ) 0 10 `seq` foldLeft (const . succ) ((const . succ) 0 10) (20:.Nil)
, 1 `seq` foldLeft (const . succ) 1 (20:.Nil)
, 1 `seq` (const . succ) 1 20 `seq` foldLeft (const . succ) ((const . succ) 1 20) Nil
, 1 `seq` 2 `seq` foldLeft (const . succ) 2 Nil
, 1 `seq` 2 `seq` 2
]
2
-- | Map the given function on each element of the list.
--
-- >>> map (+10) (1 :. 2 :. 3 :. Nil)
-- [11,12,13]
--
-- prop> headOr x (map (+1) infinity) == 1
--
-- prop> map id x == x
map ::
(a -> b)
-> List a
-> List b
map f = foldRight (\x acc -> f x :. acc) Nil
-- | Return elements satisfying the given predicate.
--
-- >>> filter even (1 :. 2 :. 3 :. 4 :. 5 :. Nil)
-- [2,4]
--
-- prop> headOr x (filter (const True) infinity) == 0
--
-- prop> filter (const True) x == x
--
-- prop> filter (const False) x == Nil
filter ::
(a -> Bool)
-> List a
-> List a
filter f = foldRight (\a -> if f a then (a:.) else id) Nil -- anon return partially applied cons or id - then applied to acc in foldRight
-- HC:
-- filter f =
-- foldRight (\a acc -> if f a then a:.acc else acc) Nil
-- | Append two lists to a new list.
--
-- >>> (1 :. 2 :. 3 :. Nil) ++ (4 :. 5 :. 6 :. Nil)
-- [1,2,3,4,5,6]
--
-- prop> headOr x (Nil ++ infinity) == 0
--
-- prop> headOr x (y ++ infinity) == headOr 0 y
--
-- prop> (x ++ y) ++ z == x ++ (y ++ z)
--
-- prop> x ++ Nil == x
(++) ::
List a
-> List a
-> List a
(++) = flip (foldRight (:.))
-- HC: (++) xsl xsr = foldRight (:.) xsr xsl
infixr 5 ++
-- | Flatten a list of lists to a list.
--
-- >>> flatten ((1 :. 2 :. 3 :. Nil) :. (4 :. 5 :. 6 :. Nil) :. (7 :. 8 :. 9 :. Nil) :. Nil)
-- [1,2,3,4,5,6,7,8,9]
--
-- prop> headOr x (flatten (infinity :. y :. Nil)) == 0
--
-- prop> headOr x (flatten (y :. infinity :. Nil)) == headOr 0 y
--
-- prop> sum (map length x) == length (flatten x)
flatten ::
List (List a)
-> List a
flatten = foldRight (++) Nil
-- HC: this layout is not completely accurate, but it does give some insight.
tft :: [T.Test]
tft = U.tt "tft"
[ flatten ((1 :. Nil) :. (6 :. Nil) :. Nil)
, foldRight (++) Nil ((1 :. Nil) :. (6 :. Nil) :. Nil)
, (++) (1 :. Nil) (foldRight (++) Nil ((6 :. Nil) :. Nil))
, foldRight (:.) (foldRight (++) Nil ((6 :. Nil) :. Nil)) (1 :. Nil)
, foldRight (:.) ((++) (6 :. Nil) (foldRight (++) Nil Nil)) (1 :. Nil)
, foldRight (:.) (foldRight (:.) (foldRight (++) Nil Nil) (6 :. Nil)) (1 :. Nil)
, foldRight (:.) (foldRight (:.) Nil (6 :. Nil)) (1 :. Nil)
, foldRight (:.) (6 :. Nil) (1 :. Nil)
]
(1:.6:.Nil)
-- | Map a function then flatten to a list.
--
-- >>> flatMap (\x -> x :. x + 1 :. x + 2 :. Nil) (1 :. 2 :. 3 :. Nil)
-- [1,2,3,2,3,4,3,4,5]
--
-- prop> headOr x (flatMap id (infinity :. y :. Nil)) == 0
--
-- prop> headOr x (flatMap id (y :. infinity :. Nil)) == headOr 0 y
--
-- prop> flatMap id (x :: List (List Int)) == flatten x
-- HC:
-- This walks the initial list only once.
-- But it repeatedly traverses/appends intermediate results.
flatMap ::
(a -> List b)
-> List a
-> List b
flatMap g = foldRight (\x acc -> g x ++ acc) Nil
-- HC:
-- This walks the initial list once to map and then the result list once to flatten.
-- When flattening result list it repeatedly traverses/appends intermediate results.
flatMapC :: (a -> List b) -> List a -> List b
flatMapC f = flatten . map f
testFun :: Num t => t -> List t
testFun x = x :. x * 10 :. Nil
tfm :: [T.Test]
tfm = U.tt "tfm"
[ flatMap testFun (1 :. 11 :. Nil)
, foldRight (\x acc -> testFun x ++ acc) Nil (1 :. 11 :. Nil)
, testFun 1 ++ foldRight (\x acc -> testFun x ++ acc) Nil (11 :. Nil)
, (++) (testFun 1) (foldRight (\x acc -> testFun x ++ acc) Nil (11 :. Nil))
, foldRight (:.) (foldRight (\x acc -> testFun x ++ acc) Nil (11 :. Nil)) (testFun 1)
, foldRight (:.) (foldRight (\x acc -> testFun x ++ acc) Nil (11 :. Nil)) (1:.10:.Nil)
-- ...
]
(1:.10:.11:.110:.Nil)
-- | Flatten a list of lists to a list (again).
-- HOWEVER, this time use the /flatMap/ function that you just wrote.
--
-- prop> let types = x :: List (List Int) in flatten x == flattenAgain x
flattenAgain ::
List (List a)
-> List a
flattenAgain = flatMap id
-- | Convert a list of optional values to an optional list of values.
--
-- * If the list contains all `Full` values,
-- then return `Full` list of values.
--
-- * If the list contains one or more `Empty` values,
-- then return `Empty`.
--
-- * The only time `Empty` is returned is
-- when the list contains one or more `Empty` values.
--
-- >>> seqOptional (Full 1 :. Full 10 :. Nil)
-- Full [1,10]
--
-- >>> seqOptional Nil
-- Full []
--
-- >>> seqOptional (Full 1 :. Full 10 :. Empty :. Nil)
-- Empty
--
-- >>> seqOptional (Empty :. map Full infinity)
-- Empty
seqOptional ::
List (Optional a)
-> Optional (List a)
seqOptional = seqOptional' Nil
where
seqOptional' _ (Empty :. _) = Empty
seqOptional' acc Nil = Full (reverse acc) -- TODO: avoid reverse
seqOptional' acc (Full x :. t) = seqOptional' (x :. acc) t
seqOptionalCannotHandleInfinity :: List (Optional a) -> Optional (List a)
seqOptionalCannotHandleInfinity xs =
let filtered = filter onlyFull xs
onlyFull Empty = False
onlyFull (Full _) = True
in if length filtered /= length xs -- cannot handle infinite lists
then Empty
else Full $ foldRight (\(Full x) acc -> x :. acc) Nil filtered
seqOptionalC :: List (Optional a) -> Optional (List a)
seqOptionalC = foldRight (twiceOptional (:.)) (Full Nil) -- TODO: understand better
tsq :: [T.Test]
tsq = U.tt "tsq"
[ seqOptionalC (Full 1 :. Full 10 :. Nil)
, foldRight (twiceOptional (:.)) (Full Nil) (Full 1 :. Full 10 :. Nil)
, (twiceOptional (:.)) (Full 1) (foldRight (twiceOptional (:.)) (Full Nil) (Full 10 :. Nil))
, bindOptional (\aa -> mapOptional ((:.) aa) (foldRight (twiceOptional (:.)) (Full Nil) (Full 10 :. Nil))) (Full 1)
-- ...
]
(Full (1:.10:.Nil))
-- | Find the first element in the list matching the predicate.
--
-- >>> find even (1 :. 3 :. 5 :. Nil)
-- Empty
--
-- >>> find even Nil
-- Empty
--
-- >>> find even (1 :. 2 :. 3 :. 5 :. Nil)
-- Full 2
--
-- >>> find even (1 :. 2 :. 3 :. 4 :. 5 :. Nil)
-- Full 2
--
-- >>> find (const True) infinity
-- Full 0
find ::
(a -> Bool)
-> List a
-> Optional a
find _ Nil = Empty
find p (h:.t) = if p h then Full h else find p t -- stop on the first one that satisfies predicate
findC :: (a -> Bool) -> List a -> Optional a
findC p x =
case filter p x of -- since pattern match drives evaluations
Nil -> Empty -- this also stops on first one that satisfies predicate
h:._ -> Full h
-- | Determine if the length of the given list is greater than 4.
--
-- >>> lengthGT4 (1 :. 3 :. 5 :. Nil)
-- False
--
-- >>> lengthGT4 Nil
-- False
--
-- >>> lengthGT4 (1 :. 2 :. 3 :. 4 :. 5 :. Nil)
-- True
--
-- >>> lengthGT4 infinity
-- True
lengthGT4 ::
List a
-> Bool
lengthGT4 = lengthGT4' 0
where
lengthGT4' n Nil = gt4 n
lengthGT4' n (_:.xs) = gt4 n || lengthGT4' (n + 1) xs
gt4 = (>4)
lengthGT4C :: List a -> Bool
lengthGT4C (_:._:._:._:._:._) = True
lengthGT4C _ = False
-- | Reverse a list.
--
-- >>> reverse Nil
-- []
--
-- >>> take 1 (reverse largeList)
-- [50000]
--
-- prop> let types = x :: List Int in reverse x ++ reverse y == reverse (y ++ x)
--
-- prop> let types = x :: Int in reverse (x :. Nil) == x :. Nil
reverse ::
List a
-> List a
reverse = reverse' Nil
where
reverse' acc Nil = acc
reverse' acc (h:.t) = reverse' (h:.acc) t -- this version only creates what is used
reverseC :: List a -> List a
reverseC = foldLeft (flip (:.)) Nil -- this version creates unused (partial) copies of the result
trv :: [T.Test]
trv = U.tt "trv"
[ reverseC (1:.2:.Nil)
, (flip (:.)) Nil 1 `seq` (foldLeft (flip (:.)) ((flip (:.)) Nil 1) (2:.Nil))
, (1 :. Nil) `seq` (foldLeft (flip (:.)) (1 :. Nil) (2:.Nil))
, (1 :. Nil) `seq` (flip (:.)) (1 :. Nil) 2 `seq` (foldLeft (flip (:.)) ((flip (:.)) (1 :. Nil) 2) Nil)
, (1 :. Nil) `seq` (2 :. 1 :. Nil) `seq` (foldLeft (flip (:.)) (2 :. 1 :. Nil) Nil)
, (1 :. Nil) `seq` (2 :. 1 :. Nil) `seq` (2 :. 1 :. Nil)
]
(2:.1:.Nil)
-- | Produce an infinite `List` that seeds with the given value at its head,
-- then runs the given function for subsequent elements
--
-- >>> let (x:.y:.z:.w:._) = produce (+1) 0 in [x,y,z,w]
-- [0,1,2,3]
--
-- >>> let (x:.y:.z:.w:._) = produce (*2) 1 in [x,y,z,w]
-- [1,2,4,8]
produce ::
(a -> a)
-> a
-> List a
produce f a = a:.produce f (f a)
-- | Do anything other than reverse a list.
-- Is it even possible?
--
-- >>> notReverse Nil
-- []
--
-- prop> let types = x :: List Int in notReverse x ++ notReverse y == notReverse (y ++ x)
--
-- prop> let types = x :: Int in notReverse (x :. Nil) == x :. Nil
notReverse ::
List a
-> List a
notReverse l@(_:.Nil) = l -- unnecessary: this is the same thing as the next line for single item lists
notReverse xs = reverse xs
notReverseC :: List a -> List a
notReverseC = reverse -- impossible
largeList ::
List Int
largeList =
listh [1..50000]
hlist ::
List a
-> [a]
hlist =
foldRight (:) []
listh ::
[a]
-> List a
listh =
P.foldr (:.) Nil
putStr ::
Chars
-> IO ()
putStr =
P.putStr . hlist
putStrLn ::
Chars
-> IO ()
putStrLn =
P.putStrLn . hlist
readFile ::
Filename
-> IO Chars
readFile =
P.fmap listh . P.readFile . hlist
writeFile ::
Filename
-> Chars
-> IO ()
writeFile n s =
P.writeFile (hlist n) (hlist s)
getLine ::
IO Chars
getLine =
P.fmap listh P.getLine
getArgs ::
IO (List Chars)
getArgs =
P.fmap (listh . P.fmap listh) E.getArgs
isPrefixOf ::
Eq a =>
List a
-> List a
-> Bool
isPrefixOf Nil _ =
True
isPrefixOf _ Nil =
False
isPrefixOf (x:.xs) (y:.ys) =
x == y && isPrefixOf xs ys
isEmpty ::
List a
-> Bool
isEmpty Nil =
True
isEmpty (_:._) =
False
span ::
(a -> Bool)
-> List a
-> (List a, List a)
span p x =
(takeWhile p x, dropWhile p x)
break ::
(a -> Bool)
-> List a
-> (List a, List a)
break p =
span (not . p)
dropWhile ::
(a -> Bool)
-> List a
-> List a
dropWhile _ Nil =
Nil
dropWhile p xs@(x:.xs') =
if p x
then
dropWhile p xs'
else
xs
takeWhile ::
(a -> Bool)
-> List a
-> List a
takeWhile _ Nil =
Nil
takeWhile p (x:.xs) =
if p x
then
x :. takeWhile p xs
else
Nil
zip ::
List a
-> List b
-> List (a, b)
zip =
zipWith (,)
zipWith ::
(a -> b -> c)
-> List a
-> List b
-> List c
zipWith f (a:.as) (b:.bs) =
f a b :. zipWith f as bs
zipWith _ _ _ =
Nil
unfoldr ::
(a -> Optional (b, a))
-> a
-> List b
unfoldr f b =
case f b of
Full (a, z) -> a :. unfoldr f z
Empty -> Nil
lines ::
Chars
-> List Chars
lines =
listh . P.fmap listh . P.lines . hlist
unlines ::
List Chars
-> Chars
unlines =
listh . P.unlines . hlist . map hlist
words ::
Chars
-> List Chars
words =
listh . P.fmap listh . P.words . hlist
unwords ::
List Chars
-> Chars
unwords =
listh . P.unwords . hlist . map hlist
listOptional ::
(a -> Optional b)
-> List a
-> List b
listOptional _ Nil =
Nil
listOptional f (h:.t) =
let r = listOptional f t
in case f h of
Empty -> r
Full q -> q :. r
any ::
(a -> Bool)
-> List a
-> Bool
any p =
foldRight ((||) . p) False
all ::
(a -> Bool)
-> List a
-> Bool
all p =
foldRight ((&&) . p) True
or ::
List Bool
-> Bool
or =
any id
and ::
List Bool
-> Bool
and =
all id
elem ::
Eq a =>
a
-> List a
-> Bool
elem x =
any (== x)
notElem ::
Eq a =>
a
-> List a
-> Bool
notElem x =
all (/= x)
permutations
:: List a -> List (List a)
permutations xs0 =
let perms Nil _ =
Nil
perms (t:.ts) is =
let interleave' _ Nil r =
(ts, r)
interleave' f (y:.ys) r =
let (us,zs) = interleave' (f . (y:.)) ys r
in (y:.us, f (t:.y:.us):.zs)
in foldRight (\xs -> snd . interleave' id xs) (perms ts (t:.is)) (permutations is)
in xs0 :. perms xs0 Nil
intersectBy ::
(a -> b -> Bool)
-> List a
-> List b
-> List a
intersectBy e xs ys =
filter (\x -> any (e x) ys) xs
take ::
(Num n, Ord n) =>
n
-> List a
-> List a
take n _ | n <= 0 =
Nil
take _ Nil =
Nil
take n (x:.xs) =
x :. take (n - 1) xs
drop ::
(Num n, Ord n) =>
n
-> List a
-> List a
drop n xs | n <= 0 =
xs
drop _ Nil =
Nil
drop n (_:.xs) =
drop (n-1) xs
repeat ::
a
-> List a
repeat x =
x :. repeat x
replicate ::
(Num n, Ord n) =>
n
-> a
-> List a
replicate n x =
take n (repeat x)
reads ::
P.Read a =>
Chars
-> Optional (a, Chars)
reads s =
case P.reads (hlist s) of
[] -> Empty
((a, q):_) -> Full (a, listh q)
read ::
P.Read a =>
Chars
-> Optional a
read =
mapOptional fst . reads
readHexs ::
(Eq a, Num a) =>
Chars
-> Optional (a, Chars)
readHexs s =
case N.readHex (hlist s) of
[] -> Empty
((a, q):_) -> Full (a, listh q)
readHex ::
(Eq a, Num a) =>
Chars
-> Optional a
readHex =
mapOptional fst . readHexs
readFloats ::
(RealFrac a) =>
Chars
-> Optional (a, Chars)
readFloats s =
case N.readSigned N.readFloat (hlist s) of
[] -> Empty
((a, q):_) -> Full (a, listh q)
readFloat ::
(RealFrac a) =>
Chars
-> Optional a
readFloat =
mapOptional fst . readFloats
instance IsString (List Char) where
fromString =
listh
type Chars =
List Char
type Filename =
Chars
strconcat ::
[Chars]
-> P.String
strconcat =
P.concatMap hlist
stringconcat ::
[P.String]
-> P.String
stringconcat =
P.concat
show' ::
Show a =>
a
-> List Char
show' =
listh . show
instance P.Monad List where
(>>=) =
flip flatMap
return =
(:. Nil)
testList :: IO T.Counts
testList =
T.runTestTT P.$ T.TestList P.$ tho1 P.++ tho2 P.++ tp1 P.++ tp2 P.++ tlc P.++ tfm P.++ tft P.++ tsq P.++ trv
-- End of file.
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/course/2013-11-nicta/src/Course/List.hs
|
unlicense
| 19,983 | 0 | 20 | 6,474 | 6,332 | 3,448 | 2,884 | 527 | 3 |
{-# LANGUAGE NoImplicitPrelude #-}
hello = "hello"
|
gelisam/hawk
|
tests/preludes/noImplicitPrelude/prelude.hs
|
apache-2.0
| 51 | 0 | 4 | 7 | 7 | 4 | 3 | 2 | 1 |
module Emulator.Video.TileMode where
import Emulator.Memory
import Emulator.Types
import Emulator.Video.Palette
import Emulator.Video.Util
import Emulator.Video.VideoController
import Utilities.Parser.TemplateHaskell
import Data.Array.IArray
import Data.Bits
type ScreenEntry = (Address, Bool, Bool, Address)
type TileMap = Array Address Byte
tileModes :: AddressIO m => LCDControl -> m [ScreenObj]
tileModes cnt = do
palette <- readRange (0x05000000, 0x050001FF)
case bgMode cnt of
0 -> mode0 palette cnt
1 -> mode1 palette cnt
_ -> mode2 palette cnt
mode0 :: AddressSpace m => Palette -> LCDControl -> m [ScreenObj]
mode0 palette cnt = do
bg0Data <- readTextBG 0x04000008 0x04000010 0x04000012
bg1Data <- readTextBG 0x0400000A 0x04000014 0x04000016
bg2Data <- readTextBG 0x0400000C 0x04000018 0x0400001A
bg3Data <- readTextBG 0x0400000E 0x0400001C 0x0400001E
-- let bg0 = if screenDispBG0 cnt then textBG bg0Data palette 0 else Hidden
-- let bg1 = if screenDispBG1 cnt then textBG bg1Data palette 1 else Hidden
-- let bg2 = if screenDispBG2 cnt then textBG bg2Data palette 2 else Hidden
-- let bg3 = if screenDispBG3 cnt then textBG bg3Data palette 3 else Hidden
let bg0 = if screenDispBG0 cnt then textBG bg0Data palette 0 else textBG bg0Data palette 0
let bg1 = if screenDispBG1 cnt then textBG bg1Data palette 1 else textBG bg1Data palette 1
let bg2 = if screenDispBG2 cnt then textBG bg2Data palette 2 else textBG bg2Data palette 2
let bg3 = if screenDispBG3 cnt then textBG bg3Data palette 3 else textBG bg3Data palette 3
return [bg0, bg1, bg2, bg3]
mode1 :: AddressIO m => Palette -> LCDControl -> m [ScreenObj]
mode1 palette cnt = do
bg0Data <- readTextBG 0x04000008 0x04000010 0x04000012
bg1Data <- readTextBG 0x0400000A 0x04000014 0x04000016
bg2Data <- readAffineBG 0x0400000C 0x04000028 0x04000020
let bg0 = if screenDispBG0 cnt then textBG bg0Data palette 0 else Hidden
let bg1 = if screenDispBG1 cnt then textBG bg1Data palette 1 else Hidden
let bg2 = if screenDispBG2 cnt then affineBG bg2Data palette 2 else Hidden
return [bg0, bg1, bg2]
mode2 :: AddressIO m => Palette -> LCDControl -> m [ScreenObj]
mode2 palette cnt = do
bg2Data <- readAffineBG 0x0400000C 0x04000028 0x04000020
bg3Data <- readAffineBG 0x0400000E 0x04000038 0x04000030
let bg2 = if screenDispBG2 cnt then affineBG bg2Data palette 2 else Hidden
let bg3 = if screenDispBG3 cnt then affineBG bg3Data palette 3 else Hidden
return [bg2, bg3]
readTextBG :: AddressSpace m => Address -> Address -> Address -> m (BGControl, TileOffset, ([TileMap], TileSet))
readTextBG bgCNTAddr xOffAddr yOffAddr = do
bg <- recordBGControl bgCNTAddr
xHWord <- readAddressHalfWord xOffAddr
yHWord <- readAddressHalfWord yOffAddr
let xOff = negate (fromIntegral $ $(bitmask 8 0) xHWord)
let yOff = negate (fromIntegral $ $(bitmask 8 0) yHWord)
tileSet <- readCharBlocks (characterBaseBlock bg) (colorsPalettes bg)
tileMapSets <- getTextTileMaps (screenSize bg) (screenBaseBlock bg)
return (bg, (xOff, yOff), (tileMapSets, tileSet))
getTextTileMaps :: AddressSpace m => Int -> TileMapBaseAddress -> m [TileMap]
getTextTileMaps 0 tileMapAddr = do
tileMap0 <- readTileMap tileMapAddr
return [tileMap0]
getTextTileMaps 3 tileMapAddr = do
tileMap0 <- readTileMap tileMapAddr
tileMap1 <- readTileMap (tileMapAddr + 0x00000800)
tileMap2 <- readTileMap (tileMapAddr + 0x00001000)
tileMap3 <- readTileMap (tileMapAddr + 0x00001800)
return [tileMap0, tileMap1, tileMap2, tileMap3]
getTextTileMaps _ tileMapAddr = do
tileMap0 <- readTileMap tileMapAddr
tileMap1 <- readTileMap (tileMapAddr + 0x00000800)
return [tileMap0, tileMap1]
-- -- Text Mode
textBG :: (BGControl, TileOffset, ([TileMap], TileSet)) -> Palette -> Layer -> ScreenObj
textBG (bg, offset, mapSet) palette layer = BG bgTiles priority layer
where
bgTiles = getTextBGTiles (screenSize bg) (colorsPalettes bg) offset palette mapSet (screenBaseBlock bg) (characterBaseBlock bg)
priority = bgPriority bg
affineBG :: (BGControl, AffineRefPoints, AffineParameters, (Int, Int), TileMap, TileSet, Centre) -> Palette -> Layer -> ScreenObj
affineBG (bg, refPoint, param, size, tileMap, tileSet, centre) pal layer = BG affineBgTiles priority layer
where
bgTiles = concat $ mapTileSet size (colorsPalettes bg) tileMap tileSet refPoint pal (screenBaseBlock bg) (characterBaseBlock bg)
priority = bgPriority bg
affineBgTiles = transformCoords bgTiles centre param
getTextBGTiles :: Int -> PaletteFormat -> TileOffset -> Palette -> ([TileMap], TileSet) -> TileMapBaseAddress -> TileSetBaseAddress -> [Tile]
getTextBGTiles 0 palFormat offSet pal (maps, tileSet) tileMapAddr tileSetAddr = bgTiles
where
bgTiles = concat $ mapTileSet (32, 32) palFormat (maps!!0) tileSet offSet pal tileMapAddr tileSetAddr
getTextBGTiles 1 palFormat (x, y) pal (maps, tileSet) tileMapAddr tileSetAddr = bgTiles0 ++ bgTiles1
where
bgTiles0 = concat $ mapTileSet (32, 32) palFormat (maps!!0) tileSet (x, y) pal tileMapAddr tileSetAddr
bgTiles1 = concat $ mapTileSet (32, 32) palFormat (maps!!1) tileSet (x+32, y) pal tileMapAddr tileSetAddr
getTextBGTiles 2 palFormat (x, y) pal (maps, tileSet) tileMapAddr tileSetAddr = bgTiles0 ++ bgTiles1
where
bgTiles0 = concat $ mapTileSet (32, 32) palFormat (maps!!0) tileSet (x, y) pal tileMapAddr tileSetAddr
bgTiles1 = concat $ mapTileSet (32, 32) palFormat (maps!!1) tileSet (x, y+32) pal tileMapAddr tileSetAddr
getTextBGTiles _ palFormat (x, y) pal (maps, tileSet) tileMapAddr tileSetAddr = bgTiles0 ++ bgTiles1 ++ bgTiles2 ++ bgTiles3
where
bgTiles0 = concat $ mapTileSet (32, 32) palFormat (maps!!0) tileSet (x, y) pal tileMapAddr tileSetAddr
bgTiles1 = concat $ mapTileSet (32, 32) palFormat (maps!!1) tileSet (x+32, y) pal tileMapAddr tileSetAddr
bgTiles2 = concat $ mapTileSet (32, 32) palFormat (maps!!2) tileSet (x, y+32) pal tileMapAddr tileSetAddr
bgTiles3 = concat $ mapTileSet (32, 32) palFormat (maps!!3) tileSet (x+32, y+32) pal tileMapAddr tileSetAddr
readTileMap :: AddressSpace m => Address -> m (TileMap)
readTileMap addr = readRange (addr, addr + 0x000007FF)
readCharBlocks :: AddressSpace m => Address -> PaletteFormat -> m TileSet
readCharBlocks addr False = readRange (addr, addr + 0x00007FFF)
readCharBlocks addr True = readRange (addr, addr + 0x0000FFFF)
-- Draw 32x32 tiles at a time
mapTileSet :: (Int, Int) -> PaletteFormat -> TileMap -> TileSet -> TileOffset -> Palette -> TileMapBaseAddress -> TileSetBaseAddress -> [[Tile]]
mapTileSet (0, _) _ _ _ _ _ _ _ = []
mapTileSet (rows, cols) palFormat tileMap tileSet bgOffset@(xOff, yOff) palette baseAddr setBaseAddr = row:mapTileSet (rows-1, cols) palFormat tileMap tileSet (xOff, yOff + 8) palette (baseAddr + tileMapRowWidth) setBaseAddr
where
row = mapRow cols baseAddr palFormat tileMapRow tileSet bgOffset palette setBaseAddr
tileMapRow = ixmap (baseAddr, baseAddr + (tileMapRowWidth - 0x00000001)) (id) tileMap :: TileMap
tileMapRowWidth = (fromIntegral cols) * 0x00000002
-- Need to recurse using int instead
mapRow :: Int -> Address -> PaletteFormat -> TileMap -> TileSet -> TileOffset -> Palette -> TileSetBaseAddress -> [Tile]
mapRow 0 _ _ _ _ _ _ _ = []
mapRow column mapIndex palFormat tileMapRow tileSet (xOff, yOff) palette setBaseAddr =
Tile pixData tileCoords:mapRow (column-1) (mapIndex + 0x00000002) palFormat tileMapRow tileSet (xOff + 8, yOff) palette setBaseAddr
where
pixData = pixelData palFormat palette tile palBank
tile = getTile palFormat tileIdx tileSet
upperByte = (tileMapRow!(mapIndex + 0x00000001))
lowerByte = (tileMapRow!mapIndex)
(tileIdx, _hFlip, _vFlip, palBank) = parseScreenEntry lowerByte upperByte palFormat setBaseAddr
tileCoords = ((xOff, yOff), (xOff+8, yOff), (xOff, yOff+8), (xOff+8, yOff+8))
-- NEED TO SORT HFLIP AND VFLIP WHEN GRAPHICS RUN
-- a is the lower byte, b is the upper
parseScreenEntry :: Byte -> Byte -> PaletteFormat -> TileSetBaseAddress -> ScreenEntry
parseScreenEntry a b palFormat setBaseAddr = (tileIdx, hFlip, vFlip, palBank)
where
hword = bytesToHalfWord a b
tileIdx = setBaseAddr + convIntToAddr (fromIntegral $ $(bitmask 9 0) hword :: Int) palFormat
hFlip = (testBit hword 10)
vFlip = (testBit hword 11)
palBank = convIntToAddr (fromIntegral $ $(bitmask 15 12) hword :: Int) False
readAffineBG :: AddressSpace m => Address -> Address -> Address -> m (BGControl, AffineRefPoints, AffineParameters, (Int, Int), TileMap, TileSet, Centre)
readAffineBG bgCNTAddr refBaseAddr paramBaseAddr = do
bg <- recordBGControl bgCNTAddr
xWord <- readAddressWord refBaseAddr
yWord <- (readAddressWord (refBaseAddr + 0x00000004))
paramMem <- readRange (paramBaseAddr, paramBaseAddr + 0x00000007)
let refPoint@(x, y) = (referencePoint xWord, referencePoint yWord)
let params = affineParameters paramBaseAddr (paramBaseAddr + 0x00000002) (paramBaseAddr + 0x00000004) (paramBaseAddr + 0x00000006) paramMem
let size@(w, h) = affineBGSize (screenSize bg)
let centre = (x + (fromIntegral w * 4), y + (((fromIntegral h * 4))))
tileSet <- readCharBlocks (characterBaseBlock bg) (colorsPalettes bg)
let mapSize = fromIntegral ((w * h * 2) - 1) :: Address
tileMap <- readRange ((screenBaseBlock bg), (screenBaseBlock bg) + mapSize)
return (bg, refPoint, params, size, tileMap, tileSet, centre)
-- Returns number of tiles to be drawn
affineBGSize :: Int -> (Int, Int)
affineBGSize n
| n == 0 = (16, 16)
| n == 1 = (32, 32)
| n == 2 = (64, 64)
| otherwise = (128, 128)
|
intolerable/GroupProject
|
src/Emulator/Video/TileMode.hs
|
bsd-2-clause
| 9,592 | 0 | 16 | 1,619 | 3,303 | 1,726 | 1,577 | -1 | -1 |
{-# LANGUAGE RecordWildCards #-}
-- | Baseline word-segmentation functions.
module NLP.Concraft.DAG.Segmentation
( PathTyp (..)
, pickPath
, findPath
-- * Frequencies
, computeFreqs
, FreqConf (..)
-- * Ambiguity-related stats
, computeAmbiStats
, AmbiCfg (..)
, AmbiStats (..)
) where
import Control.Monad (guard)
-- import qualified Control.Monad.State.Strict as State
import qualified Data.Foldable as F
import qualified Data.MemoCombinators as Memo
import qualified Data.Set as S
import qualified Data.Map.Strict as M
import qualified Data.List as L
import qualified Data.Text as T
import Data.Ord (comparing)
import Data.DAG (DAG)
import qualified Data.DAG as DAG
-- import qualified Data.Tagset.Positional as P
import qualified NLP.Concraft.DAG.Morphosyntax as X
import qualified NLP.Concraft.DAG.Morphosyntax.Ambiguous as Ambi
------------------------------------
-- Shortest-path segmentation
------------------------------------
-- | Configuration related to frequency-based path picking.
data FreqConf = FreqConf
{ pickFreqMap :: M.Map T.Text (Int, Int)
-- ^ A map which assigns (chosen, not chosen) counts to the invidiaul
-- orthographic forms (see `computeFreqs`).
, smoothingParam :: Double
-- ^ A naive smoothing related parameter, which should be adddd to each
-- count in `pickFreqMap`.
-- , orth :: DAG.EdgeID -> T.Text
-- -- ^ Orthographic form of a given edge
}
-- | Which path type to search: shortest (`Min`) or longest (`Max`)
data PathTyp
= Min
| Max
| Freq FreqConf
-- | Select the shortest-path (or longest, depending on `PathTyp`) in the given
-- DAG and remove all the edges which are not on this path.
pickPath
:: (X.Word b)
=> PathTyp
-> DAG a b
-> DAG a b
pickPath pathTyp dag =
let
dag' = DAG.filterDAG (findPath pathTyp dag) dag
in
if DAG.isOK dag'
then dag'
else error "Segmentation.pickPath: the resulting DAG not correct"
-- | Retrieve the edges which belong to the shortest/longest (depending on the
-- argument function: `minimum` or `maximum`) path in the given DAG.
findPath
:: (X.Word b)
=> PathTyp
-> DAG a b
-> S.Set DAG.EdgeID
findPath pathTyp dag
= S.fromList . pickNode . map fst
-- Below, we take the node with the smallest (reverse) or highest (no reverse)
-- distance to a target node, depending on the path type (`Min` or `Max`).
. reverseOrNot
. L.sortBy (comparing snd)
$ sourceNodes
where
sourceNodes = do
nodeID <- DAG.dagNodes dag
guard . null $ DAG.ingoingEdges nodeID dag
return (nodeID, dist nodeID)
reverseOrNot = case pathTyp of
Max -> reverse
_ -> id
forward nodeID
| null (DAG.outgoingEdges nodeID dag) = []
| otherwise = pick $ do
nextEdgeID <- DAG.outgoingEdges nodeID dag
let nextNodeID = DAG.endsWith nextEdgeID dag
-- guard $ dist nodeID == dist nextNodeID + 1
guard $ dist nodeID == dist nextNodeID + arcLen nextEdgeID
-- return nextNodeID
return nextEdgeID
pickNode ids = case ids of
nodeID : _ -> forward nodeID
[] -> error "Segmentation.pickPath: no node to pick!?"
pick ids = case ids of
edgeID : _ -> edgeID : forward (DAG.endsWith edgeID dag)
[] -> error "Segmentation.pickPath: nothing to pick!?"
dist = computeDist pathTyp dag
-- distance between two nodes connected by an arc
arcLen =
case pathTyp of
Freq conf -> computeArcLen conf dag
_ -> const 1
------------------------------------
-- Distance from target nodes
------------------------------------
-- | Compute the minimal/maximal distance (depending on the argument function)
-- from each node to a target node.
computeDist
:: (X.Word b)
=> PathTyp
-> DAG a b
-> DAG.NodeID
-> Double
computeDist pathTyp dag =
dist
where
minMax = case pathTyp of
Max -> maximum
_ -> minimum
dist =
Memo.wrap DAG.NodeID DAG.unNodeID Memo.integral dist'
dist' nodeID
| null (DAG.outgoingEdges nodeID dag) = 0
| otherwise = minMax $ do
nextEdgeID <- DAG.outgoingEdges nodeID dag
let nextNodeID = DAG.endsWith nextEdgeID dag
-- return $ dist nextNodeID + 1
return $ dist nextNodeID + arcLen nextEdgeID
arcLen =
case pathTyp of
Freq conf -> computeArcLen conf dag
_ -> const 1
------------------------------------
-- Frequency-based segmentation
------------------------------------
-- | Compute chosen/not-chosen counts of the individual orthographic forms in
-- the DAGs. Only the ambiguous segments are taken into account.
computeFreqs :: (X.Word w) => [X.Sent w t] -> M.Map T.Text (Int, Int)
computeFreqs dags = M.fromListWith addBoth $ do
dag <- dags
let ambiDAG = Ambi.identifyAmbiguousSegments dag
edgeID <- DAG.dagEdges dag
guard $ DAG.edgeLabel edgeID ambiDAG == True
let seg = DAG.edgeLabel edgeID dag
orth = edgeOrth seg
edgeWeight = sum . M.elems . X.unWMap . X.tags $ seg
eps = 1e-9
return $
if edgeWeight > eps
then (orth, (1, 0))
else (orth, (0, 1))
where
addBoth (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
computeArcLen
:: (X.Word b)
=> FreqConf
-> DAG a b
-> DAG.EdgeID
-> Double
computeArcLen FreqConf{..} dag edgeID =
(\x -> -x) . log $
case M.lookup (edgeOrth $ DAG.edgeLabel edgeID dag) pickFreqMap of
Just (chosen, notChosen) ->
(fromIntegral chosen + smoothingParam) /
(fromIntegral (chosen + notChosen) + smoothingParam*2)
Nothing -> 0.5 -- smoothingParam / (smoothingParam*2)
-- | Retrieve the orthographic representation of a given segment for the purpose
-- of frequency-based segmentation.
edgeOrth :: X.Word w => w -> T.Text
edgeOrth = T.toLower . T.strip . X.orth
------------------------------------
-- Frequency-based segmentation
--
-- How this can work?
--
-- For each segment (i.e, a particular orthographic form) we would like to find
-- a simple measure of how likely it is to use it in a segmentation.
--
-- # Solution 1
--
-- A simple way would be to determine the probability as follows:
--
-- p(orth) = chosen(orth) / possible(orth)
--
-- where `chosen(orth)` is the number of *chosen* (disamb) edges in the training
-- dataset whose orthographic form is `orth`, and `possible(orth)` is the total
-- number of edges in train with the `orth` orthographic form.
--
-- Now, the problem is that we would need to use smoothing to account for forms
-- not in the training dataset:
--
-- p(orth) = chosen(orth) + 1 / possible(orth) + 2
--
-- The reason to add 2 in the denominator is that it can be rewritten as:
--
-- p(orth) = chosen(orth) + 1 / chosen(orth) + 1 + not-chosen(orth) + 1
--
-- So the default probability is 1/2. Not too bad?
--
-- # Solution 2
--
-- An alternative would be to decide, for a given segment, whether it should be
-- taken or not. For example, if a given segment (i.e., orthographic form) is
-- chosen in more than a half of situations where it can actually be chosen,
-- then it should belong to the path. Otherwise, it should not.
--
-- Then we have to choose how to represent the fact that the edge should be
-- taken (i.e. should belong to a path). One way to do that is to say that, if
-- the form is chosen, its weight is 0; otherwise, its weight is 1. This does
-- not account for the length of edges, so another solution would be to say that
-- if the edge/form is chosen, then its weight is 0; otherwise, it is equal to
-- its length. Then again, the length of an edge can be computed in several
-- manners, e.g., as the string length of the orthographic form, or as the
-- number of segments which can be used inside. But the latter is not always
-- possible to compute.
--
-- # Choice
--
-- For now, solution 1 seems more principled. So we need to compute a map from
-- orthographic forms to pairs of (chosen, not chosen) counts on the basis of
-- the training dataset. Afterwards, we use "naive" smoothing
-- (http://ivan-titov.org/teaching/nlmi-15/lecture-4.pdf) and transform the
-- resulting probability with `(-) . log`. This gives as a positive value
-- assigned to each segment, and we need to find the path with the lowest
-- weigth.
------------------------------------
------------------------------------
-- Ambiguity stats
------------------------------------
-- | Numbers of tokens.
data AmbiCfg = AmbiCfg
{ onlyChosen :: Bool
-- ^ Only take the chosen tokens into account
} deriving (Show, Eq, Ord)
-- | Numbers of tokens.
data AmbiStats = AmbiStats
{ ambi :: !Int
-- ^ Ambiguous tokens
, total :: !Int
-- ^ All tokens
} deriving (Show, Eq, Ord)
-- | Initial statistics.
zeroAmbiStats :: AmbiStats
zeroAmbiStats = AmbiStats 0 0
addAmbiStats :: AmbiStats -> AmbiStats -> AmbiStats
addAmbiStats x y = AmbiStats
{ ambi = ambi x + ambi y
, total = total x + total y
}
-- | Compute:
-- * the number of tokens participating in ambiguities
-- * the total number of tokens
computeAmbiStats
:: (X.Word w)
=> AmbiCfg
-> [X.Sent w t]
-> AmbiStats
computeAmbiStats cfg sents =
F.foldl' addAmbiStats zeroAmbiStats
[ ambiStats cfg sent
| sent <- sents ]
ambiStats
:: (X.Word w)
=> AmbiCfg
-> X.Sent w t
-> AmbiStats
ambiStats AmbiCfg{..} dag
= F.foldl' addAmbiStats zeroAmbiStats
. DAG.mapE gather
$ DAG.zipE dag ambiDag
where
ambiDag = Ambi.identifyAmbiguousSegments dag
gather _edgeID (seg, isAmbi)
| isAmbi && prob >= eps =
AmbiStats {ambi = 1, total = 1}
| prob >= eps =
AmbiStats {ambi = 0, total = 1}
| otherwise =
AmbiStats {ambi = 0, total = 0}
where
-- isChosen = (prob >= eps) || (not onlyChosen)
prob = sum . M.elems . X.unWMap $ X.tags seg
eps = 0.5
|
kawu/concraft
|
src/NLP/Concraft/DAG/Segmentation.hs
|
bsd-2-clause
| 9,854 | 0 | 15 | 2,238 | 1,861 | 1,022 | 839 | 173 | 5 |
{-# LANGUAGE BangPatterns #-}
-- | Replace a string by another string
--
-- Tested in this benchmark:
--
-- * Search and replace of a pattern in a text
--
module Benchmarks.Replace
( benchmark
, initEnv
) where
import Criterion (Benchmark, bgroup, bench, nf)
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Search as BL
import qualified Data.ByteString.Search as B
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Lazy as TL
import qualified Data.Text.Lazy.Encoding as TL
import qualified Data.Text.Lazy.IO as TL
type Env = (T.Text, B.ByteString, TL.Text, BL.ByteString)
initEnv :: FilePath -> IO Env
initEnv fp = do
tl <- TL.readFile fp
bl <- BL.readFile fp
let !t = TL.toStrict tl
!b = T.encodeUtf8 t
return (t, b, tl, bl)
benchmark :: String -> String -> Env -> Benchmark
benchmark pat sub ~(t, b, tl, bl) =
bgroup "Replace" [
bench "Text" $ nf (T.length . T.replace tpat tsub) t
, bench "ByteString" $ nf (BL.length . B.replace bpat bsub) b
, bench "LazyText" $ nf (TL.length . TL.replace tlpat tlsub) tl
, bench "LazyByteString" $ nf (BL.length . BL.replace blpat blsub) bl
]
where
tpat = T.pack pat
tsub = T.pack sub
tlpat = TL.pack pat
tlsub = TL.pack sub
bpat = T.encodeUtf8 tpat
bsub = T.encodeUtf8 tsub
blpat = B.concat $ BL.toChunks $ TL.encodeUtf8 tlpat
blsub = B.concat $ BL.toChunks $ TL.encodeUtf8 tlsub
|
bgamari/text
|
benchmarks/haskell/Benchmarks/Replace.hs
|
bsd-2-clause
| 1,590 | 0 | 12 | 376 | 514 | 287 | 227 | 37 | 1 |
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, NoMonomorphismRestriction, GADTs #-}
module Render.Alerts where
import Application
import Data.Text
import Heist
import Snap.Snaplet
import Snap.Snaplet.Session
import Control.Monad.Trans
import qualified Heist.Compiled as C
getSessionValues :: [Text] -> AppHandler [(Text, Text)]
getSessionValues =
Prelude.foldl
(\out level -> do
v <- out
s <- with sess $ getFromSession level
_ <- with sess $ deleteFromSession level
return $ case s of Just sv -> v ++ [(level, sv)]
Nothing -> v)
(return [])
alertRuntime :: RuntimeSplice AppHandler [(Text, Text)]
alertRuntime = lift $ getSessionValues ["danger", "info"]
splicesFromAlert :: Splices (RuntimeSplice AppHandler (Text, Text) -> C.Splice AppHandler)
splicesFromAlert = do "level" ## C.pureSplice $ C.textSplice fst
"msg" ## C.pureSplice $ C.textSplice snd
renderAlerts :: RuntimeSplice AppHandler [(Text, Text)] -> C.Splice AppHandler
renderAlerts = C.manyWithSplices C.runChildren splicesFromAlert
|
rjohnsondev/haskellshop
|
src/Render/Alerts.hs
|
bsd-2-clause
| 1,174 | 0 | 16 | 299 | 328 | 174 | 154 | 26 | 2 |
-- |
module Main
where
import Test.QuickCheck
import Test.QuickCheck.Monadic (assert, monadicIO, pick, pre, run)
import Control.Monad (filterM,mapM)
import qualified System.Directory as D
import System.Exit (exitFailure,exitSuccess)
import qualified System.FilePath as F
import qualified System.Environment as E
import Data.List as L
import qualified Data.Set as Set
import qualified Data.Rewriting.Problem.Xml as X
import qualified Data.Rewriting.Problem.Parse as W
import qualified Data.Rewriting.Problem.Type as T
getFilenames :: FilePath -> IO [FilePath]
getFilenames fpxml = do
allDir <- D.getDirectoryContents fpxml
let allFDir = map (F.combine fpxml) (filter (`notElem` [".",".."]) allDir )
xmlfns <- filterM D.doesFileExist allFDir
subdirs <- filterM D.doesDirectoryExist allFDir
subfiless <- mapM getFilenames subdirs -- infinite recursion with symbolic links possible
let files = xmlfns ++ concat subfiless
return files
getFileTuples :: FilePath -> FilePath -> IO [(FilePath,FilePath)]
getFileTuples fpxml fptrs = do
xmlfns <- getFilenames fpxml
let trsfns = map ((flip F.replaceExtension "trs") . (fptrs ++) . drop (length fpxml)) xmlfns
return $ zip xmlfns trsfns
checkStartTerms p1 p2 = let
st1 = T.startTerms p1
st2 = T.startTerms p2
in st1 == st2
checkRules p1 p2 = let
rp1 = T.rules p1
rp2 = T.rules p2
wr1 = T.weakRules rp1
wr2 = T.weakRules rp2
sr1 = T.strictRules rp1
sr2 = T.strictRules rp2
in (null (wr1 \\ wr2)) &&
(null (sr1 \\ sr2)) &&
(null (wr2 \\ wr1)) &&
(null (sr2 \\ sr1))
checkStrategy p1 p2 = let
s1 = T.strategy p1
s2 = T.strategy p2
in s1 == s2
checkVaraibles p1 p2 = let
v1 = Set.fromList $ T.variables p1
v2 = Set.fromList $ T.variables p2
in v1 == v2
checkSymbols p1 p2 = let
s1 = Set.fromList $ T.symbols p1
s2 = Set.fromList $ T.symbols p2
in s1 == s2
prop_sameSystem :: (FilePath,FilePath) -> Property
prop_sameSystem ft = monadicIO $ do
--run $ appendFile "tested" $ show ft ++ "\n"
p1 <- run $ X.xmlFileToProblem (fst ft)
p2 <- run $ W.parseFileIO (snd ft)
assert $ and [ checkRules p1 p2
-- , checkStartTerms p1 p2 -- removed since Information not available in WST-format
, checkStrategy p1 p2
, checkVaraibles p1 p2
, checkSymbols p1 p2]
prop_allSameSystem :: [(FilePath,FilePath)] -> Property
prop_allSameSystem fts = forAll (elements fts) prop_sameSystem
main :: IO ()
main = do
args <- E.getArgs
let qcArgs = stdArgs { maxSuccess = read (args !! 0)}
fts <- getFileTuples (args !! 1) (args !! 2)
result <- quickCheckWithResult qcArgs (prop_allSameSystem fts)
case result of
Success {} -> exitSuccess
_ -> exitFailure
|
ComputationWithBoundedResources/term-rewriting-xml
|
testsuite/Main.hs
|
bsd-3-clause
| 2,745 | 0 | 16 | 583 | 967 | 504 | 463 | 73 | 2 |
{-# LANGUAGE FlexibleInstances #-}
module Data.List.TypeLevel.Constraint where
import GHC.Exts (Constraint)
-- | A constraint on each element of a type-level list.
type family ListAll (ts :: [k]) (c :: k -> Constraint) :: Constraint where
ListAll '[] c = ()
ListAll (t ': ts) c = (c t, ListAll ts c)
class (ca x, cb x) => (ca :&: cb) x
instance (ca x, cb x) => (ca :&: cb) x
type family RequireEquality (a :: k) (b :: k) (c :: j) :: j where
RequireEquality a a c = c
|
andrewthad/vinyl-vectors
|
src/Data/List/TypeLevel/Constraint.hs
|
bsd-3-clause
| 488 | 3 | 9 | 113 | 205 | 116 | 89 | -1 | -1 |
module Data.Profunctor.Product.Class where
import Data.Profunctor (Profunctor)
-- | 'ProductProfunctor' is a generalization of 'Applicative'.
--
-- It has the usual 'Applicative' "output" (covariant) parameter on
-- the right. Additionally it has an "input" (contravariant) type
-- parameter on the left.
--
-- You will find it easier to see the similarity between
-- 'ProductProfunctor' and 'Applicative' if you look at @purePP@,
-- @***$@, and @****@, which correspond to @pure@, @<$>@, and @<*>@
-- respectively.
--
-- It's easy to make instances of 'ProductProfunctor'. Just make
-- instances
--
-- @
-- instance Profunctor MyProductProfunctor where
-- ...
--
-- instance Applicative (MyProductProfunctor a) where
-- ...
-- @
--
-- and then write
--
-- @
-- instance ProductProfunctor Writer where
-- empty = defaultEmpty
-- (***!) = defaultProfunctorProduct
-- @
class Profunctor p => ProductProfunctor p where
empty :: p () ()
(***!) :: p a b -> p a' b' -> p (a, a') (b, b')
|
karamaan/product-profunctors
|
Data/Profunctor/Product/Class.hs
|
bsd-3-clause
| 1,006 | 0 | 10 | 183 | 119 | 78 | 41 | 5 | 0 |
import Data.Foldable as F
import Data.Functor.Identity
import qualified Data.Vector.Storable as V
import Control.Applicative
import Data.Functor.Product
import Linear
import Control.Lens
import ModelFit.Types
import ModelFit.Fit
import ModelFit.Model
import ModelFit.Models.Fcs
sources pts = runGlobalFitM $ do
diff1 <- globalParam 2.3 :: GlobalFitM Double Double Double (FitExprM Double Double)
diff2 <- globalParam 3.2
aspect <- globalParam 10
a <- expr $ Diff3DP <$> diff1 <*> fixed 1 <*> aspect <*> param 1
b <- expr $ Diff3DP <$> diff2 <*> fixed 1 <*> aspect <*> param 1
fit pts $ liftOp (*) <$> fmap diff3DModel (hoist a)
<*> fmap diff3DModel (hoist b)
return (a, b)
main = do
let genParams1 = defaultParams & (diffTime .~ 10)
. (concentration .~ 2)
genParams2 = defaultParams & (diffTime .~ 30)
. (concentration .~ 2)
m = liftOp (*) (diff3DModel genParams1) (diff3DModel genParams2)
((unpackA, unpackB), curves, p0) = sources points
points = V.fromList [ let x = 2**i in Point x (m x) 1
| i <- [1, 1.1..10]
]
let Right fit = leastSquares curves p0
print $ evalParam unpackA p0
print $ evalParam unpackB fit
|
bgamari/model-fit
|
Main.hs
|
bsd-3-clause
| 1,356 | 0 | 16 | 421 | 460 | 234 | 226 | -1 | -1 |
{-# OPTIONS -fglasgow-exts -XOverlappingInstances -XUndecidableInstances -XOverloadedStrings #-}
module Main where
import System.Mem.StableName
import System.IO.Unsafe
import Data.RefSerialize
import Data.Monoid
import Data.ByteString.Lazy.Char8(unpack)
-- we use a default instance for show and read instances
instance (Show a, Read a )=> Serialize a where
showp= showpText
readp= readpText
main= do
let x = (5 :: Int)
let xss = [[x,x],[x,x]]
let str= rShow xss
putStrLn $ unpack str
putStrLn "read the output back"
let y = rRead str :: [[Int]]
print y
print $ y==xss
|
agocorona/RefSerialize
|
demo.hs
|
bsd-3-clause
| 613 | 0 | 11 | 125 | 186 | 101 | 85 | 19 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving
, RankNTypes
#-}
module Control.Monad.GraphT where
import Data.Maybe
import Data.Foldable
import Data.Traversable
import Control.Applicative
import Control.Monad.State hiding (mapM_, mapM, forM)
import Control.Monad.Cont hiding (mapM_, mapM, forM)
import qualified Control.Monad.ContextT as ContextT
import Prelude hiding (elem, and, concat, mapM, mapM_, foldr)
newtype GraphT s f m a = GraphT { unGraphT :: ContextT.ContextT s (f (GraphRef s f)) m a }
deriving (Monad, MonadFix, MonadTrans, Applicative, Alternative, Functor, MonadPlus, MonadCont, MonadIO)
newtype GraphRef s f = GraphRef { unGraphRef :: ContextT.ContextRef s (f (GraphRef s f)) }
runGraphT :: (Monad m) => (forall s. GraphT s f m a) -> m a
runGraphT m = unsafeRunGraphT m
unsafeRunGraphT :: (Monad m) => GraphT s f m a -> m a
unsafeRunGraphT m = ContextT.unsafeRunContextT $ unGraphT m
mapGraphT :: (forall s'. m (a, s') -> n (b, s')) -> GraphT s f m a -> GraphT s f n b
mapGraphT f (GraphT m) = GraphT $ ContextT.mapContextT f m
newRef :: (Monad m) => f (GraphRef s f) -> GraphT s f m (GraphRef s f)
newRef a = liftM GraphRef $ GraphT $ ContextT.newRef a
readRef :: (Monad m) => GraphRef s f -> GraphT s f m (f (GraphRef s f))
readRef (GraphRef ref) = GraphT $ ContextT.readRef ref
writeRef :: (Monad m) => GraphRef s f -> f (GraphRef s f) -> GraphT s f m ()
writeRef (GraphRef ref) a = GraphT $ ContextT.writeRef ref a
subsRef :: (Monad m) => GraphRef s f -> GraphRef s f -> GraphT s f m ()
subsRef (GraphRef a) (GraphRef b) = GraphT $ ContextT.subsRef a b
subsRefs :: (Monad m) => [GraphRef s f] -> GraphRef s f -> GraphT s f m ()
subsRefs xs (GraphRef ref) = GraphT $ ContextT.subsRefs (fmap unGraphRef xs) ref
refEq :: (Monad m) => GraphRef s f -> GraphRef s f -> GraphT s f m Bool
refEq (GraphRef a) (GraphRef b) = GraphT $ ContextT.refEq a b
unsafeCastRef :: (Functor f) => (f (GraphRef s' g) -> g (GraphRef s' g)) -> GraphRef s f -> GraphRef s' g
unsafeCastRef f (GraphRef (ContextT.UnsafeContextRef ref a)) = GraphRef $ ContextT.UnsafeContextRef ref (f (fmap (unsafeCastRef f) a))
forkContext :: (Monad m, Functor f, Foldable t, Functor t) => t (GraphRef s f) -> (forall s'. t (GraphRef s' f) -> GraphT s' f m b) -> GraphT s f m b
forkContext refs f = forkMappedContext refs id f
oneOf :: (Monad m) => [GraphT s f m (Maybe a)] -> GraphT s f m (Maybe a)
oneOf ms = GraphT $ ContextT.UnsafeContextT $ StateT $ \context -> do
let onlyOne (Nothing, _) a = a
onlyOne a (Nothing, _) = a
onlyOne _ _ = (Nothing, context)
return . foldr onlyOne (Nothing, context) =<< mapM (flip runStateT context . ContextT.unsafeUnContextT . unGraphT) ms
-- #TODO check to see if the f needs to be polymorphic (I think it might need to be.. maybe not)
--forkMappedContext :: (Monad m, Functor f, Foldable t, Functor t) => t (GraphRef s f) -> (f (GraphRef s' g) -> g (GraphRef s' g)) -> (forall s'. t (GraphRef s' g) -> GraphT s' g m b) -> GraphT s f m b
forkMappedContext :: (Monad m, Functor f, Foldable t, Functor t) => t (GraphRef s f) -> (forall a. f a -> g a) -> (forall s'. t (GraphRef s' g) -> GraphT s' g m b) -> GraphT s f m b
forkMappedContext refs f g = do
GraphT $ mapM_ ContextT.unsafeLookupRef (fmap unGraphRef refs) -- force ref commit
context <- GraphT $ ContextT.UnsafeContextT $ get
GraphT $ ContextT.UnsafeContextT $ lift $ evalStateT (ContextT.unsafeUnContextT $ unGraphT $ g $ fmap (unsafeCastRef f) refs) (fmap (f . fmap (unsafeCastRef f)) context)
refElem :: (Monad m, Foldable g) => GraphRef s f -> g (GraphRef s f) -> GraphT s f m Bool
refElem ref t = refElem' $ toList t
where
refElem' [] = return False
refElem' (x:xs) = do
yep <- refEq ref x
case yep of
True -> return True
False -> refElem' xs
lookupRef :: (Monad m) => GraphRef s f -> [(GraphRef s f, a)] -> GraphT s f m (Maybe a)
lookupRef _ [] = return Nothing
lookupRef ref ((x,y):xys) = do
yep <- refEq ref x
case yep of
True -> return $ Just y
False -> lookupRef ref xys
copySubGraph :: (MonadFix m, Traversable f, Functor f) => GraphRef s f -> GraphT s f m (GraphRef s f)
copySubGraph ref = do
relevantNodes <- reachable ref
lookupNew <- mfix $ \lookupNew -> do
newNodes <- forM relevantNodes $ \x -> do
newValue <- readRef x
newRef =<< mapM lookupNew newValue
let lookupNew' a = liftM fromJust $ lookupRef a $ zip relevantNodes newNodes
return lookupNew'
lookupNew ref
--
-- Check to see if a is reachable from b. Will return false if a == b unless there is a cycle
reachableFrom :: (Foldable f, Monad m) => GraphRef s f -> GraphRef s f -> GraphT s f m Bool
reachableFrom a b = refElem a =<< liftM concat . mapM reachable =<< return . toList =<< readRef b
-- The returned list always includes the original reference
reachable :: (Foldable f, Monad m) => GraphRef s f -> GraphT s f m [GraphRef s f]
reachable ref = reachable' [] ref
reachable' :: (Monad m, Foldable f) => [GraphRef s f] -> GraphRef s f -> GraphT s f m [GraphRef s f]
reachable' xs ref= do
alreadyFound <- refElem ref xs
case alreadyFound of
True -> return []
False -> do
x <- readRef ref
xs' <- liftM concat $ mapM (reachable' (ref:xs)) $ toList x
return (ref:xs')
graphEq :: (Functor f, Eq (f ()), Foldable f, Monad m) => GraphRef s f -> GraphRef s f -> GraphT s f m Bool
graphEq aRef' bRef' = forkContext [aRef', bRef'] $ \[a', b'] -> let
graphEq' aRef bRef = do
eq <- refEq aRef bRef
case eq of
True -> return True
False -> do
a <- readRef aRef
b <- readRef bRef
case headEq a b of
False -> return False
True -> do
subsRef aRef bRef
liftM and $ zipWithM graphEq' (toList a) (toList b)
unitize x = fmap (const ()) x
headEq a b = unitize a == unitize b
in graphEq' a' b'
|
jvranish/ContextT
|
src/Control/Monad/GraphT.hs
|
bsd-3-clause
| 5,979 | 0 | 26 | 1,426 | 2,530 | 1,257 | 1,273 | 102 | 3 |
{-# LANGUAGE PartialTypeSignatures #-}
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-}
{-# LANGUAGE CPP #-}
-- #define DEBUG
{-|
Module : AERN2.Poly.Cheb.DCT
Description : Interpolation using Discrete cosine transform
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : portable
Interpolation using Discrete cosine transform
-}
module AERN2.Poly.Cheb.DCT
(
lift1_DCT, lift2_DCT
)
where
#ifdef DEBUG
import Debug.Trace (trace)
#define maybeTrace trace
#define maybeTraceIO putStrLn
#else
#define maybeTrace (\ (_ :: String) t -> t)
#define maybeTraceIO (\ (_ :: String) -> return ())
#endif
import MixedTypesNumPrelude
import qualified Prelude as P
-- import Text.Printf
import qualified Data.List as List
-- import Test.Hspec
-- import Test.QuickCheck
import Math.NumberTheory.Logarithms (integerLog2)
import AERN2.Normalize
import AERN2.MP
import AERN2.Real
-- import AERN2.Interval
-- import AERN2.RealFun.Operations
-- import AERN2.RealFun.UnaryBallFun
import AERN2.Poly.Basics
import AERN2.Poly.Cheb.Type
import AERN2.Poly.Cheb.Maximum
{-|
DCT-approximate the result of applying the given binary function @f@
pointwise to the given polynomials @p1@ and @p2@.
-}
lift2_DCT ::
-- (PolyCoeffBall c, CanNormalize (ChPoly c), CanSetPrecision c) =>
-- _ =>
(c ~ MPBall) =>
(Degree -> Degree -> Degree)
{-^ detemining a degree bound for the result from the degrees of @p1@ and @p2@ -} ->
(c -> c -> c) {-^ the function @f@ to apply pointwise to @p1@ and @p2@ -} ->
ChPoly c {-^ @p1@ -} -> ChPoly c {-^ @p2@ -} -> ChPoly c
lift2_DCT getDegree op pA pB
| domA /= domB = error "lift2_DCT: combining functions with incompatible domains"
| otherwise =
maybeTrace
(
"lift2_DCT:"
++ "\n cN = " ++ show cN
++ "\n workingPrec = " ++ show workingPrec
-- ++ "\n aT = " ++ show aT
-- ++ "\n bT = " ++ show bT
-- ++ "\n cT = " ++ show cT
-- ++ "\n c = " ++ show c
) $
result
where
dA = terms_degree $ chPoly_terms pA
dB = terms_degree $ chPoly_terms pB
resultDegree = getDegree dA dB
cNexponent = 1 + (integerLog2 $ max 1 (resultDegree + 1))
cN = 2 ^! cNexponent
-- prc = (getPrecision pA) `max` (getPrecision pB)
workingPrec = (prec $ 100 + cN) + (getPrecision pA) + (getPrecision pB)
(ChPoly domA (Poly termsA) acGA _) = raisePrecisionIfBelow workingPrec pA
(ChPoly domB (Poly termsB) acGB _) = raisePrecisionIfBelow workingPrec pB
aT = coeffs2gridvalues cN termsA
bT = coeffs2gridvalues cN termsB
cT = zipWith op aT bT -- op on the cN+1 values of the polynomials on the grid
(c0Double : c) = map (* (2 /! cN)) (tDCT_I_nlogn cT) -- interpolate the values using a polynomial
result =
setAccuracyGuide acG $
normalize $
reduceDegree resultDegree $
ChPoly domA (Poly $ terms_fromList $ zip [0..] (c0Double /! 2 : c)) (acG + cN)
(chPolyBounds_forChPoly result)
acG = (max acGA acGB)
-- terms_fromList [(0, mpBall 1)] -- dummy for debugging exceptions
{-|
DCT-approximate the result of applying the given function @f@
pointwise to the given polynomial @p@.
-}
lift1_DCT ::
-- (Field c, CanMulBy c CauchyReal, CanNormalize (ChPoly c), CanSetPrecision c, Show c) =>
-- _ =>
(c ~ MPBall) =>
(Degree -> Degree) {-^ detemining a degree bound for the result from the degree of @p@ -} ->
(c -> c) {-^ the function @f@ to apply pointwise to @p@ -} ->
ChPoly c {-^ @p@ -} ->
ChPoly c
lift1_DCT getDegree op p =
maybeTrace
(
"lift1_DCT:"
++ "\n cN = " ++ show cN
++ "\n dA = " ++ show dA
++ "\n aT = " ++ show aT
++ "\n cT = " ++ show cT
++ "\n c0Double = " ++ show c0Double
++ "\n c = " ++ show c
) $
result
where
result =
normalize $
ChPoly dom (Poly terms) acG (chPolyBounds_forChPoly result)
terms =
terms_fromList $ zip [0..] (c0Double /! 2 : c)
-- terms_fromList [(0, mpBall 1)] -- dummy for debugging exceptions
(c0Double : c) = map (* (2 /! cN)) (tDCT_I_nlogn cT) -- interpolate the values using a polynomial
-- op on the cN+1 values of the polynomials on the grid:
cT = map op aT
aT = coeffs2gridvalues cN termsA
cN = 2 ^! (1 + (integerLog2 $ max 1 (getDegree dA + 1)))
workingPrec = (prec $ 100 + cN) + (getPrecision p)
(ChPoly dom (Poly termsA) acG _) = raisePrecisionIfBelow workingPrec p
dA = terms_degree termsA
{-|
Compute the values of the polynomial termsA on a grid.
-}
coeffs2gridvalues ::
-- (Field c, CanMulBy c CauchyReal) =>
-- _ =>
(c ~ MPBall) =>
Integer -> Terms c -> [c]
coeffs2gridvalues cN terms =
tDCT_I_nlogn coeffs
where
-- convert from sparse to dense representation:
coeffs = pad0 $ map (terms_lookupCoeffDoubleConstTerm terms) [0..(terms_degree terms)]
pad0 list = take (cN + 1) $ list ++ (repeat (convertExactly 0))
{-|
DCT-I computed directly from its definition in
[BT97, page 18, display (6.1)].
This is quite inefficient for large N.
It is to be used only for N<8 and as a reference in tests.
-}
tDCT_I_reference ::
-- (Field c, CanMulBy c CauchyReal) =>
-- _ =>
(c ~ MPBall) =>
[c] {-^ @a@ a vector of validated real numbers -} ->
[c] {-^ @a~@ a vector of validated real numbers -}
tDCT_I_reference a =
[sum [ (eps cN k) * (a !! k) * cos ( ((mu * k) * pi) /! cN)
| k <- [0..cN]
]
| mu <- [0..cN]
]
where
cN = (length a) - 1
{-| An auxiliary family of constants, frequently used in Chebyshev-basis expansions. -}
eps :: Integer -> Integer -> Rational
eps n k
| k == 0 = 0.5
| k == n = 0.5
| otherwise = 1.0
{-|
DCT-I computed by splitting N and via DCT-III as described in
[BT97, page 18, Proposition 6.1].
Precondition: (length a) = 1+2^{t+1} where t > 1
-}
tDCT_I_nlogn ::
-- (Field c, CanMulBy c CauchyReal) =>
-- _ =>
(c ~ MPBall) =>
[c] {-^ @a@ a vector of validated real numbers -} ->
[c] {-^ @a~@ a vector of validated real numbers -}
tDCT_I_nlogn a
| cN < 8 = tDCT_I_reference a
| otherwise = map aTilde [0..cN]
where
aTilde i
| even i = fTilde !! (floor (i/!2))
| otherwise = gTilde !! (floor ((i - 1)/!2))
fTilde = tDCT_I_nlogn f
gTilde = tDCT_III_nlogn g
f = [ (a !! ell) + (a !! (cN - ell)) | ell <- [0..cN1]]
g = [ (a !! ell) - (a !! (cN - ell)) | ell <- [0..cN1-1]]
cN = (length a) - 1
cN1 = floor (cN /! 2)
{-|
DCT-III computed directly from its definition in
[BT97, page 18, display (6.2)].
This is quite inefficient. It is to be used only as a reference in tests.
-}
_tDCT_III_reference ::
-- (Field c, CanMulBy c CauchyReal) =>
-- _ =>
(c ~ MPBall) =>
[c] {-^ g a vector of validated real numbers -} ->
[c] {-^ g~ a vector of validated real numbers -}
_tDCT_III_reference g =
[sum [ (eps cN1 k) * (g !! k) * cos ( (((2*j+1)*k) * pi) /! cN)
| k <- [0..(cN1-1)]
]
| j <- [0..(cN1-1)]
]
where
cN = cN1 * 2
cN1 = (length g)
{-|
DCT-III computed via SDCT-III. The reduction is described on page 20.
Precondition: (length g) is a power of 2
-}
tDCT_III_nlogn ::
-- (Field c, CanMulBy c CauchyReal) =>
-- _ =>
(c ~ MPBall) =>
[c] {-^ g a vector of validated real numbers -} ->
[c] {-^ g~ a vector of validated real numbers -}
tDCT_III_nlogn g =
h2g $ tSDCT_III_nlogn $ map g2h $ zip [0..] g
where
g2h (i,gi) = (eps cN1 i) * gi
h2g h = map get_g [0..cN1-1]
where
get_g i
| even i = h !! (floor (i/!2 :: Rational))
| otherwise = h !! (floor $ (2*cN1 - i - 1)/!2)
cN1 = (length g)
{-|
Simplified DCT-III computed directly from its definition in
[BT97, page 20, display (6.3)].
This is quite inefficient. It is to be used only as a reference in tests.
-}
_tSDCT_III_reference ::
-- (Field c, CanMulBy c CauchyReal) =>
-- _ =>
(c ~ MPBall) =>
[c] {-^ h a vector of validated real numbers -} ->
[c] {-^ h~ a vector of validated real numbers -}
_tSDCT_III_reference h =
[sum [ (h !! ell) * cos ( (((4*j+1)*ell) * pi) /! cN)
| ell <- [0..(cN1-1)]
]
| j <- [0..(cN1-1)]
]
where
cN = cN1 * 2
cN1 = (length h)
{-|
Simplified DCT-III computed as described in
[BT97, page 21, Algorithm 1].
Changed many occurrences of N1 with N1-1 because the indices were out of range.
This is part of a trial and error process.
Precondition: length h is a power of 2
-}
tSDCT_III_nlogn ::
-- (Field c, CanMulBy c CauchyReal) =>
-- _ =>
(c ~ MPBall) =>
[c] {-^ h a vector of validated real numbers -} ->
[c] {-^ h~ a vector of validated real numbers -}
tSDCT_III_nlogn (h :: [c]) =
map (\ (_,[a],_) -> a) $
List.sortBy (\ (i,_,_) (j,_,_) -> P.compare i j) $
splitUntilSingletons $ [(0, h, 1)]
where
splitUntilSingletons :: [(Integer, [c], Integer)] -> [(Integer, [c], Integer)]
splitUntilSingletons groups
| allSingletons = groups
| otherwise =
splitUntilSingletons $
concat $ map splitGroup groups
where
allSingletons = and $ map isSingleton groups
isSingleton (_, [_], _) = True
isSingleton _ = False
splitGroup :: (Integer, [c], Integer) -> [(Integer, [c], Integer)]
splitGroup (c_Itau_minus_1, hItau_minus_1, two_pow_tau_minus_1) =
[subgroup 0, subgroup 1]
where
subgroup bit_iTauMinus1 =
(c_Itau_minus_1 + bit_iTauMinus1 * two_pow_tau_minus_1,
map hItau [0..c_Ntau_plus_1-1],
2 * two_pow_tau_minus_1)
where
hItau 0 =
(hItau_minus_1 !! 0)
+
(minusOnePow bit_iTauMinus1) * (hItau_minus_1 !! (c_Ntau_plus_1)) * gamma
hItau n =
(hItau_minus_1 !! n)
-
(hItau_minus_1 !! (c_Ntau - n))
+
((2 * (minusOnePow bit_iTauMinus1)) * (hItau_minus_1 !! (c_Ntau_plus_1+n)) * gamma)
gamma =
cos $ (((4 * c_Itau_minus_1) + 1) * pi) /! (4*two_pow_tau_minus_1)
c_Ntau = length hItau_minus_1
c_Ntau_plus_1
| even c_Ntau = floor (c_Ntau/!2)
| otherwise = error "tSDCT_III_nlogn: precondition violated: (length h) has to be a power of 2"
minusOnePow :: Integer -> Integer
minusOnePow 0 = 1
minusOnePow 1 = -1
minusOnePow _ = error "tSDCT_III_nlogn: minusOnePow called with a value other than 0,1"
|
michalkonecny/aern2
|
aern2-fun-univariate/src/AERN2/Poly/Cheb/DCT.hs
|
bsd-3-clause
| 10,728 | 0 | 19 | 2,982 | 2,663 | 1,447 | 1,216 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_HADDOCK hide #-}
-- |
-- Module : Data.Array.Accelerate.Array.Memory.Table
-- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller
-- [2009..2014] Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Robert Clifton-Everest <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Accelerate backends often need to copy arrays to a remote memory before they
-- can be used in computation. This module provides an automated method for
-- doing so. Keeping track of arrays in a `MemoryTable` ensures that any memory
-- allocated for them will be freed when GHC's garbage collector collects the
-- host array.
--
module Data.Array.Accelerate.Array.Memory.Table (
-- Tables for host/device memory associations
MemoryTable, new, lookup, malloc, free, freeStable, insertUnmanaged, reclaim,
StableArray, makeStableArray,
-- Weak pointers of arrays
makeWeakArrayData
) where
import Data.Array.Storable.Internals ( StorableArray(..) )
import Data.Functor
import Data.Maybe ( isJust )
import Data.Proxy
import Data.Typeable ( Typeable, gcast )
import Control.Monad.IO.Class ( MonadIO, liftIO )
import Control.Concurrent ( yield )
import Control.Concurrent.MVar ( MVar, newMVar, withMVar, modifyMVar_, mkWeakMVar )
import System.Mem ( performGC )
import System.Mem.Weak ( Weak, deRefWeak )
import Foreign.Storable ( sizeOf )
import Prelude hiding ( lookup )
import GHC.Exts ( Ptr(..) )
import GHC.ForeignPtr ( ForeignPtr(..), ForeignPtrContents(..) )
import GHC.IORef ( IORef(..) )
import GHC.STRef ( STRef(..) )
import GHC.Base ( mkWeak#, mkWeakNoFinalizer#, IO(..) )
import GHC.Weak ( Weak(..) )
import qualified Data.HashTable.IO as HT
import Data.Array.Accelerate.Error ( internalError )
import Data.Array.Accelerate.Array.Data ( ArrayData, GArrayData(..),
ArrayPtrs, ArrayElt, arrayElt, ArrayEltR(..),
UniqueArray, storableFromUnique, getUniqueId )
import Data.Array.Accelerate.Array.Memory ( RemoteMemory, RemotePointer, PrimElt )
import Data.Array.Accelerate.Array.Memory.Nursery ( Nursery(..) )
import Data.Array.Accelerate.Lifetime
import qualified Data.Array.Accelerate.Array.Memory as M
import qualified Data.Array.Accelerate.Array.Memory.Nursery as N
import qualified Data.Array.Accelerate.Debug as D
-- We use an MVar to the hash table, so that several threads may safely access
-- it concurrently. This includes the finalisation threads that remove entries
-- from the table.
--
-- It is important that we can garbage collect old entries from the table when
-- the key is no longer reachable in the heap. Hence the value part of each
-- table entry is a (Weak val), where the stable name 'key' is the key for the
-- memo table, and the 'val' is the value of this table entry. When the key
-- becomes unreachable, a finaliser will fire and remove this entry from the
-- hash buckets, and further attempts to dereference the weak pointer will
-- return Nothing. References from 'val' to the key are ignored (see the
-- semantics of weak pointers in the documentation).
--
type HashTable key val = HT.BasicHashTable key val
type MT p = MVar ( HashTable StableArray (RemoteArray p) )
data MemoryTable p = MemoryTable {-# UNPACK #-} !(MT p)
{-# UNPACK #-} !(Weak (MT p))
{-# UNPACK #-} !(Nursery p)
(forall a. p a -> IO ())
-- | An untyped reference to an array, similar to a stablename.
--
type StableArray = Int
data RemoteArray p where
RemoteArray :: Typeable e
=> {-# UNPACK #-} !(Weak ()) -- Keep track of host array liveness.
-> p e -- The actual remote pointer
-> Int -- The array size in bytes
-> RemoteArray p
-- |Create a new memory table from host to remote arrays.
--
-- The function supplied should be the `free` for the remote pointers being
-- stored. This function will be called by the GC, which typically runs on a
-- different thread. Unlike the `free` in `RemoteMemory`, this function cannot
-- depend on any state.
--
new :: (RemoteMemory m, MonadIO m) => (forall a. RemotePointer m a -> IO ()) -> m (MemoryTable (RemotePointer m))
new free = do
message "initialise memory table"
tbl <- liftIO $ HT.new
ref <- liftIO $ newMVar tbl
nrs <- N.new free
weak <- liftIO $ mkWeakMVar ref (return ())
return $! MemoryTable ref weak nrs free
-- | Look for the remote pointer corresponding to a given host-side array.
--
lookup :: (PrimElt a b) => MemoryTable p -> ArrayData a -> IO (Maybe (p b))
lookup (MemoryTable !ref _ _ _) !arr = do
sa <- makeStableArray arr
mw <- withMVar ref (`HT.lookup` sa)
case mw of
Nothing -> trace ("lookup/not found: " ++ show sa) $ return Nothing
Just (RemoteArray w p _) -> do
mv <- deRefWeak w
case mv of
Just _ | Just p' <- gcast p -> trace ("lookup/found: " ++ show sa) $ return (Just p')
| otherwise -> $internalError "lookup" $ "type mismatch"
-- Note: [Weak pointer weirdness]
--
-- After the lookup is successful, there might conceivably be no further
-- references to 'arr'. If that is so, and a garbage collection
-- intervenes, the weak pointer might get tombstoned before 'deRefWeak'
-- gets to it. In that case we throw an error (below). However, because
-- we have used 'arr' in the continuation, this ensures that 'arr' is
-- reachable in the continuation of 'deRefWeak' and thus 'deRefWeak'
-- always succeeds. This sort of weirdness, typical of the world of weak
-- pointers, is why we can not reuse the stable name 'sa' computed
-- above in the error message.
--
Nothing ->
makeStableArray arr >>= \x -> $internalError "lookup" $ "dead weak pair: " ++ show x
-- | Allocate a new device array to be associated with the given host-side array.
-- This may not always use the `malloc` provided by the `RemoteMemory` instance.
-- In order to reduce the number of raw allocations, previously allocated remote
-- arrays will be re-used. In the event that the remote memory is exhausted,
-- 'Nothing' is returned.
--
malloc :: forall a b m. (PrimElt a b, RemoteMemory m, MonadIO m)
=> MemoryTable (RemotePointer m)
-> ArrayData a
-> Int
-> m (Maybe (RemotePointer m b))
malloc mt@(MemoryTable _ _ !nursery _) !ad !n = do
-- Note: [Allocation sizes]
--
-- Instead of allocating the exact number of elements requested, we round up to
-- a fixed chunk size; currently set at 128 elements. This means there is a
-- greater chance the nursery will get a hit, and moreover that we can search
-- the nursery for an exact size.
--
-- TLM: I believe the CUDA API allocates in chunks, of size 4MB.
--
chunk <- M.chunkSize
let -- next highest multiple of f from x
multiple x f = (x + (f-1)) `div` f
!n' = chunk * multiple n chunk
!bytes = n' * sizeOf (undefined :: b)
--
message ("malloc: " ++ showBytes bytes)
mp <-
attempt "malloc/nursery" (liftIO $ fmap (M.castPtr (Proxy :: Proxy m)) <$> N.malloc bytes nursery)
`orElse` attempt "malloc/new" (do
M.malloc n')
`orElse` (do
message "malloc/remote-malloc-failed (cleaning)"
clean mt
liftIO $ fmap (M.castPtr (Proxy :: Proxy m)) <$> N.malloc bytes nursery)
`orElse` (do
message "malloc/remote-malloc-failed (purging)"
purge mt
M.malloc n')
`orElse` (do
message "malloc/remote-malloc-failed (non-recoverable)"
return Nothing)
case mp of
Nothing -> return Nothing
Just p' -> do
insert mt ad p' bytes
return (Just p')
where
orElse :: m (Maybe x) -> m (Maybe x) -> m (Maybe x)
orElse ra rb = do
ma <- ra
case ma of
Nothing -> rb
Just a -> return (Just a)
attempt :: String -> m (Maybe x) -> m (Maybe x)
attempt msg next = do
ma <- next
case ma of
Nothing -> return Nothing
Just a -> trace msg (return (Just a))
-- | Deallocate the device array associated with the given host-side array.
-- Typically this should only be called in very specific circumstances.
--
free :: (RemoteMemory m, PrimElt a b) => proxy m -> MemoryTable (RemotePointer m) -> ArrayData a -> IO ()
free proxy mt !arr = do
sa <- makeStableArray arr
freeStable proxy mt sa
-- | Deallocate the device array associated with the given StableArray. This
-- is useful for other memory managers built on top of the memory table.
--
freeStable :: RemoteMemory m => proxy m -> MemoryTable (RemotePointer m) -> StableArray -> IO ()
freeStable proxy (MemoryTable !ref _ (Nursery !nrs _) _) !sa = withMVar ref $ \mt -> do
mw <- mt `HT.lookup` sa
case mw of
Nothing -> message ("free/already-removed: " ++ show sa)
Just (RemoteArray _ !p !bytes) -> trace ("free/evict: " ++ show sa ++ " of " ++ showBytes bytes) $ do
N.stash proxy bytes nrs p
mt `HT.delete` sa
-- Record an association between a host-side array and a new device memory area.
-- The device memory will be freed when the host array is garbage collected.
--
insert :: forall m a b. (PrimElt a b, RemoteMemory m, MonadIO m)
=> MemoryTable (RemotePointer m)
-> ArrayData a
-> RemotePointer m b
-> Int
-> m ()
insert mt@(MemoryTable !ref _ _ _) !arr !ptr !bytes = do
key <- makeStableArray arr
weak <- liftIO $ makeWeakArrayData arr () (Just $ freeStable (Proxy :: Proxy m) mt key)
message $ "insert: " ++ show key
liftIO $ withMVar ref $ \tbl -> HT.insert tbl key (RemoteArray weak ptr bytes)
-- |Record an association between a host-side array and a remote memory area
-- that was not allocated by accelerate. The remote memory will NOT be re-used
-- once the host-side array is garbage collected.
--
-- This typically only has use for backends that provide an FFI.
--
insertUnmanaged :: (PrimElt a b, MonadIO m) => MemoryTable p -> ArrayData a -> p b -> m ()
insertUnmanaged (MemoryTable !ref !weak_ref _ _) !arr !ptr = do
key <- makeStableArray arr
weak <- liftIO $ makeWeakArrayData arr () (Just $ remoteFinalizer weak_ref key)
message $ "insertUnmanaged: " ++ show key
liftIO $ withMVar ref $ \tbl -> HT.insert tbl key (RemoteArray weak ptr 0)
-- Removing entries
-- ----------------
-- |Initiate garbage collection and mark any arrays that no longer have host-side
-- equivalents as reusable.
--
clean :: forall m. (RemoteMemory m, MonadIO m) => MemoryTable (RemotePointer m) -> m ()
clean mt@(MemoryTable _ weak_ref nrs _) = management "clean" nrs . liftIO $ do
-- Unforunately there is no real way to force a GC then wait for it to finsh.
-- Calling performGC then yielding works moderately well in single-threaded
-- cases, but tends to fall down otherwise. Either way, given that finalizers
-- are often significantly delayed, it is worth our while traversing the table
-- and explicitly freeing any dead entires.
--
performGC
yield
mr <- deRefWeak weak_ref
case mr of
Nothing -> return ()
Just ref -> do
rs <- withMVar ref $ HT.foldM removable [] -- collect arrays that can be removed
mapM_ (freeStable (Proxy :: Proxy m) mt) rs -- remove them all
where
removable rs (sa, RemoteArray w _ _) = do
alive <- isJust <$> deRefWeak w
if alive then return rs else return (sa:rs)
-- |Call `free` on all arrays that are not currently associated with host-side
-- arrays.
--
purge :: (RemoteMemory m, MonadIO m) => MemoryTable (RemotePointer m) -> m ()
purge (MemoryTable _ _ nursery@(Nursery nrs _) free) = management "purge" nursery . liftIO $
modifyMVar_ nrs (\(tbl,_) -> N.flush free tbl >> return (tbl, 0))
-- |Initiate garbage collection and `free` any remote arrays that no longer
-- have matching host-side equivalents.
--
reclaim :: forall m. (RemoteMemory m, MonadIO m) => MemoryTable (RemotePointer m) -> m ()
reclaim mt = clean mt >> purge mt
remoteFinalizer :: Weak (MT p) -> StableArray -> IO ()
remoteFinalizer !weak_ref !key = do
mr <- deRefWeak weak_ref
case mr of
Nothing -> message ("finalise/dead table: " ++ show key)
Just ref -> trace ("finalise: " ++ show key) $ withMVar ref (`HT.delete` key)
-- Miscellaneous
-- -------------
-- | Make a new StableArray.
{-# INLINE makeStableArray #-}
makeStableArray :: (MonadIO m, Typeable a, Typeable e, ArrayPtrs a ~ Ptr e, ArrayElt a) => ArrayData a -> m StableArray
makeStableArray !ad = liftIO $ id arrayElt ad
where
id :: ArrayEltR e -> ArrayData e -> IO Int
id ArrayEltRint (AD_Int ua) = getUniqueId ua
id ArrayEltRint8 (AD_Int8 ua) = getUniqueId ua
id ArrayEltRint16 (AD_Int16 ua) = getUniqueId ua
id ArrayEltRint32 (AD_Int32 ua) = getUniqueId ua
id ArrayEltRint64 (AD_Int64 ua) = getUniqueId ua
id ArrayEltRword (AD_Word ua) = getUniqueId ua
id ArrayEltRword8 (AD_Word8 ua) = getUniqueId ua
id ArrayEltRword16 (AD_Word16 ua) = getUniqueId ua
id ArrayEltRword32 (AD_Word32 ua) = getUniqueId ua
id ArrayEltRword64 (AD_Word64 ua) = getUniqueId ua
id ArrayEltRcshort (AD_CShort ua) = getUniqueId ua
id ArrayEltRcushort (AD_CUShort ua) = getUniqueId ua
id ArrayEltRcint (AD_CInt ua) = getUniqueId ua
id ArrayEltRcuint (AD_CUInt ua) = getUniqueId ua
id ArrayEltRclong (AD_CLong ua) = getUniqueId ua
id ArrayEltRculong (AD_CULong ua) = getUniqueId ua
id ArrayEltRcllong (AD_CLLong ua) = getUniqueId ua
id ArrayEltRcullong (AD_CULLong ua) = getUniqueId ua
id ArrayEltRfloat (AD_Float ua) = getUniqueId ua
id ArrayEltRdouble (AD_Double ua) = getUniqueId ua
id ArrayEltRcfloat (AD_CFloat ua) = getUniqueId ua
id ArrayEltRcdouble (AD_CDouble ua) = getUniqueId ua
id ArrayEltRbool (AD_Bool ua) = getUniqueId ua
id ArrayEltRchar (AD_Char ua) = getUniqueId ua
id ArrayEltRcchar (AD_CChar ua) = getUniqueId ua
id ArrayEltRcschar (AD_CSChar ua) = getUniqueId ua
id ArrayEltRcuchar (AD_CUChar ua) = getUniqueId ua
id _ _ = error "I do have a cause, though. It is obscenity. I'm for it."
-- Weak arrays
-- ----------------------
-- |Make a weak pointer using an array as a key. Unlike the stanard `mkWeak`,
-- this guarantees finalisers won't fire early.
makeWeakArrayData :: forall a e c. (ArrayElt e, ArrayPtrs e ~ Ptr a) => ArrayData e -> c -> Maybe (IO ()) -> IO (Weak c)
makeWeakArrayData ad c f = mw arrayElt ad
where
mw :: ArrayEltR e -> ArrayData e -> IO (Weak c)
mw ArrayEltRint (AD_Int ua) = mkWeak' ua c f
mw ArrayEltRint8 (AD_Int8 ua) = mkWeak' ua c f
mw ArrayEltRint16 (AD_Int16 ua) = mkWeak' ua c f
mw ArrayEltRint32 (AD_Int32 ua) = mkWeak' ua c f
mw ArrayEltRint64 (AD_Int64 ua) = mkWeak' ua c f
mw ArrayEltRword (AD_Word ua) = mkWeak' ua c f
mw ArrayEltRword8 (AD_Word8 ua) = mkWeak' ua c f
mw ArrayEltRword16 (AD_Word16 ua) = mkWeak' ua c f
mw ArrayEltRword32 (AD_Word32 ua) = mkWeak' ua c f
mw ArrayEltRword64 (AD_Word64 ua) = mkWeak' ua c f
mw ArrayEltRcshort (AD_CShort ua) = mkWeak' ua c f
mw ArrayEltRcushort (AD_CUShort ua) = mkWeak' ua c f
mw ArrayEltRcint (AD_CInt ua) = mkWeak' ua c f
mw ArrayEltRcuint (AD_CUInt ua) = mkWeak' ua c f
mw ArrayEltRclong (AD_CLong ua) = mkWeak' ua c f
mw ArrayEltRculong (AD_CULong ua) = mkWeak' ua c f
mw ArrayEltRcllong (AD_CLLong ua) = mkWeak' ua c f
mw ArrayEltRcullong (AD_CULLong ua) = mkWeak' ua c f
mw ArrayEltRfloat (AD_Float ua) = mkWeak' ua c f
mw ArrayEltRdouble (AD_Double ua) = mkWeak' ua c f
mw ArrayEltRcfloat (AD_CFloat ua) = mkWeak' ua c f
mw ArrayEltRcdouble (AD_CDouble ua) = mkWeak' ua c f
mw ArrayEltRbool (AD_Bool ua) = mkWeak' ua c f
mw ArrayEltRchar (AD_Char ua) = mkWeak' ua c f
mw ArrayEltRcchar (AD_CChar ua) = mkWeak' ua c f
mw ArrayEltRcschar (AD_CSChar ua) = mkWeak' ua c f
mw ArrayEltRcuchar (AD_CUChar ua) = mkWeak' ua c f
mw _ _ = error "Base eight is just like base ten really — if you're missing two fingers."
mkWeak' :: UniqueArray i a -> c -> Maybe (IO ()) -> IO (Weak c)
mkWeak' ua k Nothing = mkWeak (storableFromUnique ua) k
mkWeak' ua k (Just f) = do
addFinalizer (storableFromUnique ua) f
mkWeak (storableFromUnique ua) k
-- Debug
-- -----
{-# INLINE showBytes #-}
showBytes :: Integral n => n -> String
showBytes x = D.showFFloatSIBase (Just 0) 1024 (fromIntegral x :: Double) "B"
{-# INLINE trace #-}
trace :: MonadIO m => String -> m a -> m a
trace msg next = message msg >> next
{-# INLINE message #-}
message :: MonadIO m => String -> m ()
message msg = liftIO $ D.traceIO D.dump_gc ("gc: " ++ msg)
{-# INLINE management #-}
management :: (RemoteMemory m, MonadIO m) => String -> Nursery p -> m a -> m a
management msg nrs next = do
before <- M.availableMem
before_nrs <- liftIO $ N.size nrs
total <- M.totalMem
r <- next
D.when D.dump_gc $ do
after <- M.availableMem
after_nrs <- liftIO $ N.size nrs
message $ msg ++ " (freed: " ++ showBytes (after - before)
++ ", stashed: " ++ showBytes (before_nrs - after_nrs)
++ ", remaining: " ++ showBytes after
++ " of " ++ showBytes total ++ ")"
return r
|
rrnewton/accelerate
|
Data/Array/Accelerate/Array/Memory/Table.hs
|
bsd-3-clause
| 19,085 | 0 | 20 | 5,424 | 4,784 | 2,431 | 2,353 | 267 | 29 |
{-# LANGUAGE
TemplateHaskell
, TypeOperators
, MultiParamTypeClasses
, GeneralizedNewtypeDeriving
#-}
module Heap.Alloc where
import Control.Applicative
import Control.Monad.Lazy
import Control.Monad.Reader
import Control.Monad.State
import Data.Record.Label
import Data.Word
import System.IO.Binary
import Heap.Block
import Heap.Read hiding (Heap, run)
import System.IO
import qualified Data.IntMap as I
import qualified Heap.Read as R
type AllocationMap = I.IntMap [Int]
data FileHeap =
FileHeap
{ _allocMap :: AllocationMap
, _heapSize :: Int
, _file :: Handle
} deriving Show
$(mkLabels [''FileHeap])
newtype Heap a = Heap { run' :: StateT FileHeap R.Heap a }
deriving
( Functor
, Applicative
, Monad
, MonadIO
, MonadState FileHeap
, MonadReader Handle
)
instance LiftLazy R.Heap Heap where
liftLazy = Heap . lift
file :: FileHeap :-> Handle
heapSize :: FileHeap :-> Size
allocMap :: FileHeap :-> I.IntMap [Int]
-- Exported functions.
run :: Handle -> Heap a -> R.Heap a
run h c = evalStateT
(run' (readAllocationMap 0 >> c))
(FileHeap I.empty 0 h)
allocate :: Size -> Heap Block
allocate i =
findFreeBlock i >>= maybe
(allocateAtEnd i) -- No free block found, allocate at end of heap.
(reuseFreeBlock i) -- Free block with sufficient size found, use this block.
free :: Offset -> Heap ()
free o =
do t <- getM heapSize
h <- ask
s <- liftIO $
do hSeek h AbsoluteSeek (fromIntegral o)
write8 h (0::Int)
read32 h
if t /= o + headerSize + s
then mkFree o s
else
do shrink (headerSize + s)
liftIO (hSetFileSize h (fromIntegral o))
-- Helper functions.
grow :: Size -> Heap ()
grow s = modM heapSize (+s)
shrink :: Size -> Heap ()
shrink s = modM heapSize (-s+)
findFreeBlock :: Size -> Heap (Maybe (Offset, Size))
findFreeBlock i = f <$> getM allocMap
where f = fmap (swp . fmap head . fst) . I.minViewWithKey . snd . I.split (i - 1)
swp (a, b) = (b, a)
reuseFreeBlock :: Size -> (Size, Size) -> Heap Block
reuseFreeBlock i (o, s) =
do unFree s
if s > headerSize + i + headerSize + splitThreshold
then splitAndUse i o s
else return (Block o s Nothing)
unFree :: Int -> Heap ()
unFree s = modM allocMap (I.update f s)
where f (_:x:xs) = Just (x:xs)
f _ = Nothing
mkFree :: Offset -> Size -> Heap ()
mkFree o = modM allocMap . I.alter (Just . maybe [o] (o:))
splitAndUse :: Size -> Offset -> Size -> Heap Block
splitAndUse i o s =
do let o' = o + headerSize + i
s' = s - headerSize - i
splitter o' s'
mkFree o' s'
return (Block o i Nothing)
splitter :: Offset -> Size -> Heap ()
splitter o s =
do h <- ask
liftIO $
do hSeek h AbsoluteSeek (fromIntegral o)
write8 h (0x00 :: Word8)
write32 h s
allocateAtEnd :: Size -> Heap Block
allocateAtEnd i =
do e <- getM heapSize
grow (headerSize + i)
return (Block e i Nothing)
readAllocationMap :: Offset -> Heap ()
readAllocationMap o =
do i <- Heap . lift $ readHeader o
case i of
Just (f, s) ->
do when (not f) (mkFree o s)
grow (headerSize + s)
readAllocationMap (o + headerSize + s)
Nothing -> return ()
|
sebastiaanvisser/islay
|
src/Heap/Alloc.hs
|
bsd-3-clause
| 3,307 | 0 | 15 | 895 | 1,270 | 646 | 624 | 108 | 2 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE UnboxedTuples #-}
module Data.IntPSQ.Internal
( -- * Type
Nat
, Key
, Mask
, IntPSQ (..)
-- * Query
, null
, size
, member
, lookup
, findMin
-- * Construction
, empty
, singleton
-- * Insertion
, insert
-- * Delete/update
, delete
, deleteMin
, alter
, alterMin
-- * Lists
, fromList
, toList
, keys
-- * Views
, insertView
, deleteView
, minView
-- * Traversal
, map
, fold'
-- * Unsafe manipulation
, unsafeInsertNew
, unsafeInsertIncreasePriority
, unsafeInsertIncreasePriorityView
, unsafeInsertWithIncreasePriority
, unsafeInsertWithIncreasePriorityView
, unsafeLookupIncreasePriority
-- * Testing
, valid
, hasBadNils
, hasDuplicateKeys
, hasMinHeapProperty
, validMask
) where
import Control.DeepSeq (NFData(rnf))
import Control.Applicative ((<$>), (<*>))
import Data.BitUtil
import Data.Bits
import Data.List (foldl')
import Data.Maybe (isJust)
import Data.Word (Word)
import Data.Foldable (Foldable (foldr))
import qualified Data.List as List
import Prelude hiding (lookup, map, filter, foldr, foldl, null)
-- TODO (SM): get rid of bang patterns
{-
-- Use macros to define strictness of functions.
-- STRICT_x_OF_y denotes an y-ary function strict in the x-th parameter.
-- We do not use BangPatterns, because they are not in any standard and we
-- want the compilers to be compiled by as many compilers as possible.
#define STRICT_1_OF_2(fn) fn arg _ | arg `seq` False = undefined
-}
------------------------------------------------------------------------------
-- Types
------------------------------------------------------------------------------
-- A "Nat" is a natural machine word (an unsigned Int)
type Nat = Word
type Key = Int
-- | We store masks as the index of the bit that determines the branching.
type Mask = Int
-- | A priority search queue with @Int@ keys and priorities of type @p@ and
-- values of type @v@. It is strict in keys, priorities and values.
data IntPSQ p v
= Bin {-# UNPACK #-} !Key !p !v {-# UNPACK #-} !Mask !(IntPSQ p v) !(IntPSQ p v)
| Tip {-# UNPACK #-} !Key !p !v
| Nil
deriving (Show)
instance (NFData p, NFData v) => NFData (IntPSQ p v) where
rnf (Bin _k p v _m l r) = rnf p `seq` rnf v `seq` rnf l `seq` rnf r
rnf (Tip _k p v) = rnf p `seq` rnf v
rnf Nil = ()
instance (Ord p, Eq v) => Eq (IntPSQ p v) where
x == y = case (minView x, minView y) of
(Nothing , Nothing ) -> True
(Just (xk, xp, xv, x'), (Just (yk, yp, yv, y'))) ->
xk == yk && xp == yp && xv == yv && x' == y'
(Just _ , Nothing ) -> False
(Nothing , Just _ ) -> False
instance Foldable (IntPSQ p) where
foldr _ z Nil = z
foldr f z (Tip _ _ v) = f v z
foldr f z (Bin _ _ v _ l r) = f v z''
where
z' = foldr f z l
z'' = foldr f z' r
instance Functor (IntPSQ p) where
fmap f = map (\_ _ v -> f v)
-- bit twiddling
----------------
{-# INLINE natFromInt #-}
natFromInt :: Key -> Nat
natFromInt = fromIntegral
{-# INLINE intFromNat #-}
intFromNat :: Nat -> Key
intFromNat = fromIntegral
{-# INLINE zero #-}
zero :: Key -> Mask -> Bool
zero i m
= (natFromInt i) .&. (natFromInt m) == 0
{-# INLINE nomatch #-}
nomatch :: Key -> Key -> Mask -> Bool
nomatch k1 k2 m =
natFromInt k1 .&. m' /= natFromInt k2 .&. m'
where
m' = maskW (natFromInt m)
{-# INLINE maskW #-}
maskW :: Nat -> Nat
maskW m = complement (m-1) `xor` m
{-# INLINE branchMask #-}
branchMask :: Key -> Key -> Mask
branchMask k1 k2 =
intFromNat (highestBitMask (natFromInt k1 `xor` natFromInt k2))
------------------------------------------------------------------------------
-- Query
------------------------------------------------------------------------------
-- | /O(1)/ True if the queue is empty.
null :: IntPSQ p v -> Bool
null Nil = True
null _ = False
-- | /O(n)/ The number of elements stored in the queue.
size :: IntPSQ p v -> Int
size Nil = 0
size (Tip _ _ _) = 1
size (Bin _ _ _ _ l r) = 1 + size l + size r
-- TODO (SM): benchmark this against a tail-recursive variant
-- | /O(min(n,W))/ Check if a key is present in the the queue.
member :: Int -> IntPSQ p v -> Bool
member k = isJust . lookup k
-- | /O(min(n,W))/ The priority and value of a given key, or 'Nothing' if the
-- key is not bound.
lookup :: Int -> IntPSQ p v -> Maybe (p, v)
lookup k = go
where
go t = case t of
Nil -> Nothing
Tip k' p' x'
| k == k' -> Just (p', x')
| otherwise -> Nothing
Bin k' p' x' m l r
| nomatch k k' m -> Nothing
| k == k' -> Just (p', x')
| zero k m -> go l
| otherwise -> go r
-- | /O(1)/ The element with the lowest priority.
findMin :: Ord p => IntPSQ p v -> Maybe (Int, p, v)
findMin t = case t of
Nil -> Nothing
Tip k p x -> Just (k, p, x)
Bin k p x _ _ _ -> Just (k, p, x)
------------------------------------------------------------------------------
--- Construction
------------------------------------------------------------------------------
-- | /O(1)/ The empty queue.
empty :: IntPSQ p v
empty = Nil
-- | /O(1)/ Build a queue with one element.
singleton :: Ord p => Int -> p -> v -> IntPSQ p v
singleton = Tip
------------------------------------------------------------------------------
-- Insertion
------------------------------------------------------------------------------
-- | /O(min(n,W))/ Insert a new key, priority and value into the queue. If the key
-- is already present in the queue, the associated priority and value are
-- replaced with the supplied priority and value.
insert :: Ord p => Int -> p -> v -> IntPSQ p v -> IntPSQ p v
insert k p x t0 = unsafeInsertNew k p x (delete k t0)
-- | Internal function to insert a key that is *not* present in the priority
-- queue.
{-# INLINABLE unsafeInsertNew #-}
unsafeInsertNew :: Ord p => Key -> p -> v -> IntPSQ p v -> IntPSQ p v
unsafeInsertNew k p x = go
where
go t = case t of
Nil -> Tip k p x
Tip k' p' x'
| (p, k) < (p', k') -> link k p x k' t Nil
| otherwise -> link k' p' x' k (Tip k p x) Nil
Bin k' p' x' m l r
| nomatch k k' m ->
if (p, k) < (p', k')
then link k p x k' t Nil
else link k' p' x' k (Tip k p x) (merge m l r)
| otherwise ->
if (p, k) < (p', k')
then
if zero k' m
then Bin k p x m (unsafeInsertNew k' p' x' l) r
else Bin k p x m l (unsafeInsertNew k' p' x' r)
else
if zero k m
then Bin k' p' x' m (unsafeInsertNew k p x l) r
else Bin k' p' x' m l (unsafeInsertNew k p x r)
-- | Link
link :: Key -> p -> v -> Key -> IntPSQ p v -> IntPSQ p v -> IntPSQ p v
link k p x k' k't otherTree
| zero m k' = Bin k p x m k't otherTree
| otherwise = Bin k p x m otherTree k't
where
m = branchMask k k'
------------------------------------------------------------------------------
-- Delete/Alter
------------------------------------------------------------------------------
-- | /O(min(n,W))/ Delete a key and its priority and value from the queue. When
-- the key is not a member of the queue, the original queue is returned.
{-# INLINABLE delete #-}
delete :: Ord p => Int -> IntPSQ p v -> IntPSQ p v
delete k = go
where
go t = case t of
Nil -> Nil
Tip k' _ _
| k == k' -> Nil
| otherwise -> t
Bin k' p' x' m l r
| nomatch k k' m -> t
| k == k' -> merge m l r
| zero k m -> binShrinkL k' p' x' m (go l) r
| otherwise -> binShrinkR k' p' x' m l (go r)
-- | /O(min(n,W))/ Delete the binding with the least priority, and return the
-- rest of the queue stripped of that binding. In case the queue is empty, the
-- empty queue is returned again.
{-# INLINE deleteMin #-}
deleteMin :: Ord p => IntPSQ p v -> IntPSQ p v
deleteMin t = case minView t of
Nothing -> t
Just (_, _, _, t') -> t'
-- | /O(min(n,W))/ The expression @alter f k queue@ alters the value @x@ at @k@,
-- or absence thereof. 'alter' can be used to insert, delete, or update a value
-- in a queue. It also allows you to calculate an additional value @b@.
{-# INLINE alter #-}
alter
:: Ord p
=> (Maybe (p, v) -> (b, Maybe (p, v)))
-> Int
-> IntPSQ p v
-> (b, IntPSQ p v)
alter f = \k t0 ->
let (t, mbX) = case deleteView k t0 of
Nothing -> (t0, Nothing)
Just (p, v, t0') -> (t0', Just (p, v))
in case f mbX of
(b, mbX') ->
(b, maybe t (\(p, v) -> unsafeInsertNew k p v t) mbX')
-- | /O(min(n,W))/ A variant of 'alter' which works on the element with the
-- minimum priority. Unlike 'alter', this variant also allows you to change the
-- key of the element.
{-# INLINE alterMin #-}
alterMin :: Ord p
=> (Maybe (Int, p, v) -> (b, Maybe (Int, p, v)))
-> IntPSQ p v
-> (b, IntPSQ p v)
alterMin f t = case t of
Nil -> case f Nothing of
(b, Nothing) -> (b, Nil)
(b, Just (k', p', x')) -> (b, Tip k' p' x')
Tip k p x -> case f (Just (k, p, x)) of
(b, Nothing) -> (b, Nil)
(b, Just (k', p', x')) -> (b, Tip k' p' x')
Bin k p x m l r -> case f (Just (k, p, x)) of
(b, Nothing) -> (b, merge m l r)
(b, Just (k', p', x'))
| k /= k' -> (b, insert k' p' x' (merge m l r))
| p' <= p -> (b, Bin k p' x' m l r)
| otherwise -> (b, unsafeInsertNew k p' x' (merge m l r))
-- | Smart constructor for a 'Bin' node whose left subtree could have become
-- 'Nil'.
{-# INLINE binShrinkL #-}
binShrinkL :: Key -> p -> v -> Mask -> IntPSQ p v -> IntPSQ p v -> IntPSQ p v
binShrinkL k p x m Nil r = case r of Nil -> Tip k p x; _ -> Bin k p x m Nil r
binShrinkL k p x m l r = Bin k p x m l r
-- | Smart constructor for a 'Bin' node whose right subtree could have become
-- 'Nil'.
{-# INLINE binShrinkR #-}
binShrinkR :: Key -> p -> v -> Mask -> IntPSQ p v -> IntPSQ p v -> IntPSQ p v
binShrinkR k p x m l Nil = case l of Nil -> Tip k p x; _ -> Bin k p x m l Nil
binShrinkR k p x m l r = Bin k p x m l r
------------------------------------------------------------------------------
-- Lists
------------------------------------------------------------------------------
-- | /O(n*min(n,W))/ Build a queue from a list of (key, priority, value) tuples.
-- If the list contains more than one priority and value for the same key, the
-- last priority and value for the key is retained.
{-# INLINABLE fromList #-}
fromList :: Ord p => [(Int, p, v)] -> IntPSQ p v
fromList = foldl' (\im (k, p, x) -> insert k p x im) empty
-- | /O(n)/ Convert a queue to a list of (key, priority, value) tuples. The
-- order of the list is not specified.
toList :: IntPSQ p v -> [(Int, p, v)]
toList =
go []
where
go acc Nil = acc
go acc (Tip k' p' x') = (k', p', x') : acc
go acc (Bin k' p' x' _m l r) = (k', p', x') : go (go acc r) l
-- | /O(n)/ Obtain the list of present keys in the queue.
keys :: IntPSQ p v -> [Int]
keys t = [k | (k, _, _) <- toList t]
-- TODO (jaspervdj): More efficient implementations possible
------------------------------------------------------------------------------
-- Views
------------------------------------------------------------------------------
-- | /O(min(n,W))/ Insert a new key, priority and value into the queue. If the key
-- is already present in the queue, then the evicted priority and value can be
-- found the first element of the returned tuple.
insertView :: Ord p => Int -> p -> v -> IntPSQ p v -> (Maybe (p, v), IntPSQ p v)
insertView k p x t0 = case deleteView k t0 of
Nothing -> (Nothing, unsafeInsertNew k p x t0)
Just (p', v', t) -> (Just (p', v'), unsafeInsertNew k p x t)
-- | /O(min(n,W))/ Delete a key and its priority and value from the queue. If
-- the key was present, the associated priority and value are returned in
-- addition to the updated queue.
{-# INLINABLE deleteView #-}
deleteView :: Ord p => Int -> IntPSQ p v -> Maybe (p, v, IntPSQ p v)
deleteView k t0 =
case delFrom t0 of
(# _, Nothing #) -> Nothing
(# t, Just (p, x) #) -> Just (p, x, t)
where
delFrom t = case t of
Nil -> (# Nil, Nothing #)
Tip k' p' x'
| k == k' -> (# Nil, Just (p', x') #)
| otherwise -> (# t, Nothing #)
Bin k' p' x' m l r
| nomatch k k' m -> (# t, Nothing #)
| k == k' -> let t' = merge m l r
in t' `seq` (# t', Just (p', x') #)
| zero k m -> case delFrom l of
(# l', mbPX #) -> let t' = binShrinkL k' p' x' m l' r
in t' `seq` (# t', mbPX #)
| otherwise -> case delFrom r of
(# r', mbPX #) -> let t' = binShrinkR k' p' x' m l r'
in t' `seq` (# t', mbPX #)
-- | /O(min(n,W))/ Retrieve the binding with the least priority, and the
-- rest of the queue stripped of that binding.
{-# INLINE minView #-}
minView :: Ord p => IntPSQ p v -> Maybe (Int, p, v, IntPSQ p v)
minView t = case t of
Nil -> Nothing
Tip k p x -> Just (k, p, x, Nil)
Bin k p x m l r -> Just (k, p, x, merge m l r)
------------------------------------------------------------------------------
-- Traversal
------------------------------------------------------------------------------
-- | /O(n)/ Modify every value in the queue.
{-# INLINABLE map #-}
map :: (Int -> p -> v -> w) -> IntPSQ p v -> IntPSQ p w
map f =
go
where
go t = case t of
Nil -> Nil
Tip k p x -> Tip k p (f k p x)
Bin k p x m l r -> Bin k p (f k p x) m (go l) (go r)
-- | /O(n)/ Strict fold over every key, priority and value in the queue. The order
-- in which the fold is performed is not specified.
{-# INLINABLE fold' #-}
fold' :: (Int -> p -> v -> a -> a) -> a -> IntPSQ p v -> a
fold' f = go
where
go !acc Nil = acc
go !acc (Tip k' p' x') = f k' p' x' acc
go !acc (Bin k' p' x' _m l r) =
let !acc1 = f k' p' x' acc
!acc2 = go acc1 l
!acc3 = go acc2 r
in acc3
-- | Internal function that merges two *disjoint* 'IntPSQ's that share the
-- same prefix mask.
{-# INLINABLE merge #-}
merge :: Ord p => Mask -> IntPSQ p v -> IntPSQ p v -> IntPSQ p v
merge m l r = case l of
Nil -> r
Tip lk lp lx ->
case r of
Nil -> l
Tip rk rp rx
| (lp, lk) < (rp, rk) -> Bin lk lp lx m Nil r
| otherwise -> Bin rk rp rx m l Nil
Bin rk rp rx rm rl rr
| (lp, lk) < (rp, rk) -> Bin lk lp lx m Nil r
| otherwise -> Bin rk rp rx m l (merge rm rl rr)
Bin lk lp lx lm ll lr ->
case r of
Nil -> l
Tip rk rp rx
| (lp, lk) < (rp, rk) -> Bin lk lp lx m (merge lm ll lr) r
| otherwise -> Bin rk rp rx m l Nil
Bin rk rp rx rm rl rr
| (lp, lk) < (rp, rk) -> Bin lk lp lx m (merge lm ll lr) r
| otherwise -> Bin rk rp rx m l (merge rm rl rr)
------------------------------------------------------------------------------
-- Improved insert performance for special cases
------------------------------------------------------------------------------
-- TODO (SM): Make benchmarks run again, integrate this function with insert
-- and test how benchmarks times change.
-- | Internal function to insert a key with priority larger than the
-- maximal priority in the heap. This is always the case when using the PSQ
-- as the basis to implement a LRU cache, which associates a
-- access-tick-number with every element.
{-# INLINE unsafeInsertIncreasePriority #-}
unsafeInsertIncreasePriority
:: Ord p => Key -> p -> v -> IntPSQ p v -> IntPSQ p v
unsafeInsertIncreasePriority =
unsafeInsertWithIncreasePriority (\newP newX _ _ -> (newP, newX))
{-# INLINE unsafeInsertIncreasePriorityView #-}
unsafeInsertIncreasePriorityView
:: Ord p => Key -> p -> v -> IntPSQ p v -> (Maybe (p, v), IntPSQ p v)
unsafeInsertIncreasePriorityView =
unsafeInsertWithIncreasePriorityView (\newP newX _ _ -> (newP, newX))
-- | This name is not chosen well anymore. This function:
--
-- - Either inserts a value at a new key with a prio higher than the max of the
-- entire PSQ.
-- - Or, overrides the value at the key with a prio strictly higher than the
-- original prio at that key (but not necessarily the max of the entire PSQ).
{-# INLINABLE unsafeInsertWithIncreasePriority #-}
unsafeInsertWithIncreasePriority
:: Ord p
=> (p -> v -> p -> v -> (p, v))
-> Key -> p -> v -> IntPSQ p v -> IntPSQ p v
unsafeInsertWithIncreasePriority f k p x t0 =
-- TODO (jaspervdj): Maybe help inliner a bit here, check core.
go t0
where
go t = case t of
Nil -> Tip k p x
Tip k' p' x'
| k == k' -> case f p x p' x' of (!fp, !fx) -> Tip k fp fx
| otherwise -> link k' p' x' k (Tip k p x) Nil
Bin k' p' x' m l r
| nomatch k k' m -> link k' p' x' k (Tip k p x) (merge m l r)
| k == k' -> case f p x p' x' of
(!fp, !fx)
| zero k m -> merge m (unsafeInsertNew k fp fx l) r
| otherwise -> merge m l (unsafeInsertNew k fp fx r)
| zero k m -> Bin k' p' x' m (go l) r
| otherwise -> Bin k' p' x' m l (go r)
{-# INLINABLE unsafeInsertWithIncreasePriorityView #-}
unsafeInsertWithIncreasePriorityView
:: Ord p
=> (p -> v -> p -> v -> (p, v))
-> Key -> p -> v -> IntPSQ p v -> (Maybe (p, v), IntPSQ p v)
unsafeInsertWithIncreasePriorityView f k p x t0 =
-- TODO (jaspervdj): Maybe help inliner a bit here, check core.
case go t0 of
(# t, mbPX #) -> (mbPX, t)
where
go t = case t of
Nil -> (# Tip k p x, Nothing #)
Tip k' p' x'
| k == k' -> case f p x p' x' of
(!fp, !fx) -> (# Tip k fp fx, Just (p', x') #)
| otherwise -> (# link k' p' x' k (Tip k p x) Nil, Nothing #)
Bin k' p' x' m l r
| nomatch k k' m ->
let t' = merge m l r
in t' `seq`
let t'' = link k' p' x' k (Tip k p x) t'
in t'' `seq` (# t'', Nothing #)
| k == k' -> case f p x p' x' of
(!fp, !fx)
| zero k m ->
let t' = merge m (unsafeInsertNew k fp fx l) r
in t' `seq` (# t', Just (p', x') #)
| otherwise ->
let t' = merge m l (unsafeInsertNew k fp fx r)
in t' `seq` (# t', Just (p', x') #)
| zero k m -> case go l of
(# l', mbPX #) -> l' `seq` (# Bin k' p' x' m l' r, mbPX #)
| otherwise -> case go r of
(# r', mbPX #) -> r' `seq` (# Bin k' p' x' m l r', mbPX #)
-- | This can NOT be used to delete elements.
{-# INLINABLE unsafeLookupIncreasePriority #-}
unsafeLookupIncreasePriority
:: Ord p
=> (p -> v -> (Maybe b, p, v))
-> Key
-> IntPSQ p v
-> (Maybe b, IntPSQ p v)
unsafeLookupIncreasePriority f k t0 =
-- TODO (jaspervdj): Maybe help inliner a bit here, check core.
case go t0 of
(# t, mbB #) -> (mbB, t)
where
go t = case t of
Nil -> (# Nil, Nothing #)
Tip k' p' x'
| k == k' -> case f p' x' of
(!fb, !fp, !fx) -> (# Tip k fp fx, fb #)
| otherwise -> (# t, Nothing #)
Bin k' p' x' m l r
| nomatch k k' m -> (# t, Nothing #)
| k == k' -> case f p' x' of
(!fb, !fp, !fx)
| zero k m ->
let t' = merge m (unsafeInsertNew k fp fx l) r
in t' `seq` (# t', fb #)
| otherwise ->
let t' = merge m l (unsafeInsertNew k fp fx r)
in t' `seq` (# t', fb #)
| zero k m -> case go l of
(# l', mbB #) -> l' `seq` (# Bin k' p' x' m l' r, mbB #)
| otherwise -> case go r of
(# r', mbB #) -> r' `seq` (# Bin k' p' x' m l r', mbB #)
------------------------------------------------------------------------------
-- Validity checks for the datastructure invariants
------------------------------------------------------------------------------
-- | /O(n^2)/ Internal function to check if the 'IntPSQ' is valid, i.e. if all
-- invariants hold. This should always be the case.
valid :: Ord p => IntPSQ p v -> Bool
valid psq =
not (hasBadNils psq) &&
not (hasDuplicateKeys psq) &&
hasMinHeapProperty psq &&
validMask psq
hasBadNils :: IntPSQ p v -> Bool
hasBadNils psq = case psq of
Nil -> False
Tip _ _ _ -> False
Bin _ _ _ _ Nil Nil -> True
Bin _ _ _ _ l r -> hasBadNils l || hasBadNils r
hasDuplicateKeys :: IntPSQ p v -> Bool
hasDuplicateKeys psq =
any ((> 1) . length) (List.group . List.sort $ collectKeys [] psq)
where
collectKeys :: [Int] -> IntPSQ p v -> [Int]
collectKeys ks Nil = ks
collectKeys ks (Tip k _ _) = k : ks
collectKeys ks (Bin k _ _ _ l r) =
let ks' = collectKeys (k : ks) l
in collectKeys ks' r
hasMinHeapProperty :: Ord p => IntPSQ p v -> Bool
hasMinHeapProperty psq = case psq of
Nil -> True
Tip _ _ _ -> True
Bin _ p _ _ l r -> go p l && go p r
where
go :: Ord p => p -> IntPSQ p v -> Bool
go _ Nil = True
go parentPrio (Tip _ prio _) = parentPrio <= prio
go parentPrio (Bin _ prio _ _ l r) =
parentPrio <= prio && go prio l && go prio r
data Side = L | R
validMask :: IntPSQ p v -> Bool
validMask Nil = True
validMask (Tip _ _ _) = True
validMask (Bin _ _ _ m left right ) =
maskOk m left right && go m L left && go m R right
where
go :: Mask -> Side -> IntPSQ p v -> Bool
go parentMask side psq = case psq of
Nil -> True
Tip k _ _ -> checkMaskAndSideMatchKey parentMask side k
Bin k _ _ mask l r ->
checkMaskAndSideMatchKey parentMask side k &&
maskOk mask l r &&
go mask L l &&
go mask R r
checkMaskAndSideMatchKey parentMask side key =
case side of
L -> parentMask .&. key == 0
R -> parentMask .&. key == parentMask
maskOk :: Mask -> IntPSQ p v -> IntPSQ p v -> Bool
maskOk mask l r = case xor <$> childKey l <*> childKey r of
Nothing -> True
Just xoredKeys ->
fromIntegral mask == highestBitMask (fromIntegral xoredKeys)
childKey Nil = Nothing
childKey (Tip k _ _) = Just k
childKey (Bin k _ _ _ _ _) = Just k
|
phadej/psqueues
|
src/Data/IntPSQ/Internal.hs
|
bsd-3-clause
| 23,961 | 0 | 21 | 8,058 | 7,699 | 3,945 | 3,754 | 449 | 7 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-}
module DockerHub.Config
( load
, Config(..)
) where
{-
@Issue(
"Check if we could limit what is imported from Text.Internal, Yaml and Generics"
type="improvement"
priority="low"
)
-}
import qualified Data.ByteString.Char8 as BS (readFile)
import Data.Maybe (fromJust)
import Data.Text.Internal
import Data.Yaml
import DockerHub.Data (Repository)
import GHC.Generics
-- Public API/types.
-- Data type that holds information about a DockerHub account.
data Config = Config { repositories :: [Repository] } deriving (Show, Generic)
-- Load a configuration file and convert it to a Config value.
{-
@Issue(
"Add support for other file types too"
type="improvement"
priority="low"
)
-}
load :: FilePath -> IO (Config)
load filepath = do
ymlData <- BS.readFile filepath
let config = Data.Yaml.decode ymlData :: Maybe Config
return $ fromJust config
-- Functions/types for internal use.
-- Conversion from and to JSON.
instance FromJSON Config
instance ToJSON Config
|
krystalcode/docker-hub
|
src/DockerHub/Config.hs
|
bsd-3-clause
| 1,082 | 0 | 11 | 215 | 185 | 106 | 79 | 18 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.CS.Corpus
( corpus ) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {locale = makeLocale CS Nothing}, testOptions, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (NumeralValue 0)
[ "0"
, "nula"
]
, examples (NumeralValue 1)
[ "1"
, "jeden"
, "jedna"
, "jedno"
]
, examples (NumeralValue 2)
[ "dva"
, "dvĕ"
]
, examples (NumeralValue 3)
[ "tři"
]
, examples (NumeralValue 4)
[ "čtyři"
]
]
|
facebookincubator/duckling
|
Duckling/Numeral/CS/Corpus.hs
|
bsd-3-clause
| 1,034 | 0 | 9 | 338 | 197 | 117 | 80 | 28 | 1 |
{-
Copyright (c) 2010, 2012 Lukas Mai
2013, 2014 Jonathan Fischoff, João Cristóvão
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the author nor the names of his contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY LUKAS MAI AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Data.Default.Generics (
-- | This module defines a class for types with a default value. Instances are
-- provided for '()', 'S.Set', 'M.Map', 'Int', 'Integer', 'Float', 'Double',
-- and many others (see below).
Default(..)
) where
import Data.Int
import Data.Word
import Data.Fixed
import Foreign.C.Types
import Data.Monoid
import Data.Ratio
import Data.Complex
import qualified Data.Set as S
import qualified Data.Map as M
import Data.IntMap (IntMap)
import Data.IntSet (IntSet)
import Data.Sequence (Seq)
import Data.Tree (Tree(..))
import Data.DList (DList)
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BSL
import qualified Data.HashMap.Lazy as HSL
import qualified Data.Vector as V
import qualified Data.Vector.Storable as VS
import qualified Data.Vector.Unboxed as VU
import qualified Data.Vector.Primitive as VP
-- Strict only in functions, data structure is the same
{-import qualified Data.HashMap.Strict as HSS-}
import qualified Data.HashSet as HSet
import System.Locale
import System.IO
import GHC.Generics
import Data.Time.Calendar
import Data.Time.Clock
import Data.Time.LocalTime
-- | A class for types with a default value.
class Default a where
-- | The default value for this type.
def :: a
default def :: (Generic a, GDefault (Rep a)) => a
def = to gDef
instance Default Bool where def = False
instance Default Int where def = 0
instance Default Int8 where def = 0
instance Default Int16 where def = 0
instance Default Int32 where def = 0
instance Default Int64 where def = 0
instance Default Word where def = 0
instance Default Word8 where def = 0
instance Default Word16 where def = 0
instance Default Word32 where def = 0
instance Default Word64 where def = 0
instance Default Integer where def = 0
instance Default Float where def = 0
instance Default Double where def = 0
instance (Integral a) => Default (Ratio a) where def = 0
instance (Default a, RealFloat a) => Default (Complex a) where def = def :+ def
-- C Interface
instance Default CChar where def = 0
instance Default CSChar where def = 0
instance Default CUChar where def = 0
instance Default CShort where def = 0
instance Default CUShort where def = 0
instance Default CInt where def = 0
instance Default CUInt where def = 0
instance Default CLong where def = 0
instance Default CULong where def = 0
-- instance Default CPtrdiff where def = 0 -- this just seems wrong
instance Default CSize where def = 0
instance Default CWchar where def = 0
instance Default CLLong where def = 0
instance Default CULLong where def = 0
instance Default CFloat where def = 0
instance Default CDouble where def = 0
instance Default (Fixed E0) where def = 0
instance Default (Fixed E1) where def = 0
instance Default (Fixed E2) where def = 0
instance Default (Fixed E3) where def = 0
instance Default (Fixed E6) where def = 0
instance Default (Fixed E9) where def = 0
instance Default (Fixed E12)where def = 0
-- System.IO
-- should these be here?
instance Default IOMode where def = ReadMode
instance Default TextEncoding where def = utf8
instance Default Newline where def = LF
instance Default NewlineMode where def = universalNewlineMode
-- maybe, either, function, IO
instance Default (Maybe a) where def = Nothing
instance (Default a) => Default (Either a b) where def = Left def
instance (Default r) => Default (e -> r) where def = const def
instance (Default a) => Default (IO a) where def = return def
-- monoids
instance Default () where def = mempty
instance Default [a] where def = mempty
instance Default Ordering where def = mempty
instance Default Any where def = mempty
instance Default All where def = mempty
instance Default (First a) where def = mempty
instance Default (Last a) where def = mempty
instance (Num a) => Default (Sum a) where def = mempty
instance (Num a) => Default (Product a) where def = mempty
instance Default (Endo a) where def = mempty
instance (Default a) => Default (Dual a) where def = Dual def
instance (Default a, Default b) => Default (a, b) where def = (def, def)
instance (Default a, Default b, Default c) => Default (a, b, c) where def = (def, def, def)
instance (Default a, Default b, Default c, Default d) => Default (a, b, c, d) where def = (def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e) => Default (a, b, c, d, e) where def = (def, def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e, Default f) => Default (a, b, c, d, e, f) where def = (def, def, def, def, def, def)
instance (Default a, Default b, Default c, Default d, Default e, Default f, Default g) => Default (a, b, c, d, e, f, g) where def = (def, def, def, def, def, def, def)
-- containers
instance Default (S.Set v) where def = S.empty
instance Default (M.Map k v) where def = M.empty
instance Default (IntMap v) where def = mempty
instance Default IntSet where def = mempty
instance Default (Seq a) where def = mempty
instance (Default a) => Default (Tree a) where def = Node def def
-- unordered-containers
instance Default (HSL.HashMap k v) where def = HSL.empty
instance Default (HSet.HashSet v) where def = HSet.empty
-- difference lists
instance Default (DList a) where def = mempty
-- vectors
instance Default (V.Vector v) where def = V.empty
instance (VS.Storable v) => Default (VS.Vector v) where def = VS.empty
instance (VU.Unbox v) => Default (VU.Vector v) where def = VU.empty
instance (VP.Prim v) => Default (VP.Vector v) where def = VP.empty
instance Default T.Text where def = T.empty
instance Default TL.Text where def = TL.empty
instance Default BS.ByteString where def = BS.empty
instance Default BSL.ByteString where def = BSL.empty
instance Default TimeLocale where def = defaultTimeLocale
-- Data.Time.Calendar
instance Default Day where def = ModifiedJulianDay 0
-- Data.Time.Clock
instance Default UniversalTime where def = ModJulianDate 0
instance Default DiffTime where def = secondsToDiffTime 0
instance Default UTCTime where def = UTCTime def def
instance Default NominalDiffTime where def = diffUTCTime def def
-- Data.Time.LocalTime
instance Default TimeZone where def = utc
instance Default TimeOfDay where def = midnight
instance Default LocalTime where def = utcToLocalTime utc def
instance Default ZonedTime where def = utcToZonedTime utc def
-- Generic Default for default implementation
class GDefault f where
gDef :: f a
instance GDefault U1 where
gDef = U1
instance (Datatype d, GDefault a) => GDefault (D1 d a) where
gDef = M1 gDef
instance (Constructor c, GDefault a) => GDefault (C1 c a) where
gDef = M1 gDef
instance (Selector s, GDefault a) => GDefault (S1 s a) where
gDef = M1 gDef
instance (Default a) => GDefault (K1 i a) where
gDef = K1 def
instance (GDefault a, GDefault b) => GDefault (a :*: b) where
gDef = gDef :*: gDef
instance (HasRec a, GDefault a, GDefault b) => GDefault (a :+: b) where
gDef = if hasRec' (gDef :: a p) then R1 gDef else L1 gDef
--------------------------------------------------------------------------------
-- | We use 'HasRec' to check for recursion in the structure. This is used
-- to avoid selecting a recursive branch in the sum case for 'Empty'.
class HasRec a where
hasRec' :: a x -> Bool
hasRec' _ = False
instance HasRec V1
instance HasRec U1
instance (HasRec a) => HasRec (M1 i j a) where
hasRec' (M1 x) = (hasRec' x)
instance (HasRec a, HasRec b)
=> HasRec (a :+: b) where
hasRec' (L1 x) = hasRec' x
hasRec' (R1 x) = hasRec' x
instance (HasRec a, HasRec b)
=> HasRec (a :*: b) where
hasRec' (a :*: b) = hasRec' a || hasRec' b
instance HasRec (Rec0 b) where
hasRec' (K1 _) = True
|
jcristovao/data-default-generics
|
src/Data/Default/Generics.hs
|
bsd-3-clause
| 9,797 | 0 | 11 | 1,930 | 2,776 | 1,531 | 1,245 | 167 | 0 |
{-# LANGUAGE ViewPatterns, ScopedTypeVariables, TemplateHaskell #-}
import Control.Concurrent.STM
import Control.Concurrent
import Control.Monad
import Control.Exception
import Sound.OSC
import qualified Data.Map as M
import Control.Lens
import Control.Lens.TH
import Data.List
import Data.Ord
import System.Random
import Control.Monad.Random
import Control.Arrow
import Data.Traversable
import System.Console.Haskeline
import TestAlsa
import Board
import Interface
type Controls = M.Map Int Int
readValue :: Int -> Double -> Double -> Controls -> Double
readValue i f s = (+s) . (*f) . (/128) . fromIntegral . M.findWithDefault 0 i
type TrackId = Int
data Displace = Displace {
_shiftTime :: Time ,
_expandTime :: Time
}deriving (Show,Read)
displace :: Displace -> E a -> E a
displace (Displace dt ro) = over timet ((+dt) . (*ro)) where
readDisplace n m = Displace
(readValue (0 + n) 4 0 m)
(readValue (8 + n) 2 0 m)
data Repeat = Repeat {
_repeatSubd :: Int,
_repeatCount :: Int
} deriving (Show,Read)
repea :: Repeat -> Int -> Int -> E a -> E a
repea (Repeat (fromIntegral -> n) (fromIntegral -> s)) (fromIntegral -> i) (fromIntegral -> k) = over timet (+ (1/(n + 1)*(i + k / (s + 1))))
readRepeat n m = Repeat
(floor (readValue (16 + n) 128 0 m))
(floor (readValue (24 + n) 128 0 m))
data R = R Int Int Int Int Int Int Time deriving (Read, Show)
randomness :: Int -> R -> [E N]
randomness c (R seed n p dp v dv dt) = flip evalRand (mkStdGen seed) . replicateM n $ do
p <- getRandomR (p,p + dp)
v <- getRandomR (v,v + dv)
t <- getRandomR(0,1)
dt <- getRandomR (0,dt)
return $ E (N c p v dt) t
readRandomness n m = R
(floor (readValue (32 + n) 128 0 m))
(floor (readValue (40 + n) 128 0 m))
(floor (readValue (48 + n) 128 0 m))
(floor (readValue (56 + n) 128 0 m))
(floor (readValue (64 + n) 128 0 m))
(floor (readValue (72 + n) 128 0 m))
(readValue (80 + n) 1 0 m)
data Track = Track {
_displacer :: Displace,
_repeater :: Repeat ,
_randomnesser :: R,
_sections :: M.Map Int Bool
} deriving (Show,Read)
makeLenses ''Track
events :: Int -> Track -> [E N]
events c (Track d r@(Repeat n s) ra se) = [0..n] >>= \i -> [0..s] >>= f i where
es = randomness c ra
l = length es
es' i k = case se M.! (i * (s + 1) + k) of
True -> take ((l `div` (n + 1) `div` (s + 1)) + 1) es
_ -> []
f i k = map (repea r i k . displace d ) (es' i k)
fromControls :: Channell -> Int -> Track
fromControls (Channell m cs) i = Track (readDisplace i m) (readRepeat i m ) (readRandomness i m) (cs M.! i)
-- listen to notes and substitute the nearest event
boarder :: Channell -> Board N
boarder c = [0 ..7] >>= (events `ap` (fromControls c))
data L = P | T | Q deriving Read
main = do
board <- newTVarIO []
forkIO $ sequp board
change <- newTChanIO
forkIO . forever . atomically $ do
c <- readTChan change
writeTVar board $ boarder c >>= convert
gui change
|
paolino/medibox
|
Seq2.hs
|
bsd-3-clause
| 3,077 | 0 | 17 | 794 | 1,436 | 759 | 677 | 85 | 2 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
module Data.Arib.PSI.PAT.Internal where
import Control.Applicative
import Control.Monad
import Data.Typeable
import Data.Bits
import Data.Binary.Get
import Data.Tagged
import Data.Arib.PSI.Internal.Common
data PAT
= PAT
{ patPsiHeader :: {-#UNPACK#-}!PSIHeader
, programPidMap :: ![(Int, Int)]
} deriving (Show, Eq, Typeable)
instance HasPSIHeader PAT where
header = header . patPsiHeader
{-# INLINE header #-}
pat :: PSITag PAT
pat = Tagged (== 0)
instance PSI PAT where
getPSI _ = {-# SCC "pat" #-} runPsi getF
where
getF h = PAT h . flip ($) [] <$> foldM (\f _ -> do
genre <- getWord16be
pid <- fromIntegral . (0x1FFF .&.) <$> getWord16be
return $ if genre == 0
then f
else f . (:) (fromIntegral genre, pid)
) id [1 .. ((sectionLength h - 9) `quot` 4)]
{-# INLINE getPSI #-}
|
philopon/arib
|
src/Data/Arib/PSI/PAT/Internal.hs
|
bsd-3-clause
| 1,176 | 0 | 19 | 314 | 297 | 171 | 126 | 37 | 1 |
{-# LANGUAGE CPP, GADTs, PackageImports #-}
module Main where
import Control.DeepSeq
import Control.Exception (evaluate)
import Control.Monad.Trans (liftIO)
import Criterion.Config
import Criterion.Main
import Data.Bits ((.&.))
import Data.Hashable (Hashable)
import qualified Data.ByteString as BS
import qualified "hashmap" Data.HashMap as IHM
import qualified Data.HashMap.Strict as HM
import qualified Data.IntMap as IM
import qualified Data.Map as M
import Data.List (foldl')
import Data.Maybe (fromMaybe)
import Prelude hiding (lookup)
import qualified Util.ByteString as UBS
import qualified Util.Int as UI
import qualified Util.String as US
#if !MIN_VERSION_bytestring(0,10,0)
instance NFData BS.ByteString
#endif
data B where
B :: NFData a => a -> B
instance NFData B where
rnf (B b) = rnf b
main :: IO ()
main = do
let hm = HM.fromList elems :: HM.HashMap String Int
hmbs = HM.fromList elemsBS :: HM.HashMap BS.ByteString Int
hmi = HM.fromList elemsI :: HM.HashMap Int Int
hmi2 = HM.fromList elemsI2 :: HM.HashMap Int Int
m = M.fromList elems :: M.Map String Int
mbs = M.fromList elemsBS :: M.Map BS.ByteString Int
im = IM.fromList elemsI :: IM.IntMap Int
ihm = IHM.fromList elems :: IHM.Map String Int
ihmbs = IHM.fromList elemsBS :: IHM.Map BS.ByteString Int
defaultMainWith defaultConfig
(liftIO . evaluate $ rnf [B m, B mbs, B hm, B hmbs, B hmi, B im])
[
-- * Comparison to other data structures
-- ** Map
bgroup "Map"
[ bgroup "lookup"
[ bench "String" $ whnf (lookupM keys) m
, bench "ByteString" $ whnf (lookupM keysBS) mbs
]
, bgroup "lookup-miss"
[ bench "String" $ whnf (lookupM keys') m
, bench "ByteString" $ whnf (lookupM keysBS') mbs
]
, bgroup "insert"
[ bench "String" $ whnf (insertM elems) M.empty
, bench "ByteStringString" $ whnf (insertM elemsBS) M.empty
]
, bgroup "insert-dup"
[ bench "String" $ whnf (insertM elems) m
, bench "ByteStringString" $ whnf (insertM elemsBS) mbs
]
, bgroup "delete"
[ bench "String" $ whnf (deleteM keys) m
, bench "ByteString" $ whnf (deleteM keysBS) mbs
]
, bgroup "delete-miss"
[ bench "String" $ whnf (deleteM keys') m
, bench "ByteString" $ whnf (deleteM keysBS') mbs
]
, bgroup "size"
[ bench "String" $ whnf M.size m
, bench "ByteString" $ whnf M.size mbs
]
, bgroup "fromList"
[ bench "String" $ whnf M.fromList elems
, bench "ByteString" $ whnf M.fromList elemsBS
]
]
-- ** Map from the hashmap package
, bgroup "hashmap/Map"
[ bgroup "lookup"
[ bench "String" $ whnf (lookupIHM keys) ihm
, bench "ByteString" $ whnf (lookupIHM keysBS) ihmbs
]
, bgroup "lookup-miss"
[ bench "String" $ whnf (lookupIHM keys') ihm
, bench "ByteString" $ whnf (lookupIHM keysBS') ihmbs
]
, bgroup "insert"
[ bench "String" $ whnf (insertIHM elems) IHM.empty
, bench "ByteStringString" $ whnf (insertIHM elemsBS) IHM.empty
]
, bgroup "insert-dup"
[ bench "String" $ whnf (insertIHM elems) ihm
, bench "ByteStringString" $ whnf (insertIHM elemsBS) ihmbs
]
, bgroup "delete"
[ bench "String" $ whnf (deleteIHM keys) ihm
, bench "ByteString" $ whnf (deleteIHM keysBS) ihmbs
]
, bgroup "delete-miss"
[ bench "String" $ whnf (deleteIHM keys') ihm
, bench "ByteString" $ whnf (deleteIHM keysBS') ihmbs
]
, bgroup "size"
[ bench "String" $ whnf IHM.size ihm
, bench "ByteString" $ whnf IHM.size ihmbs
]
, bgroup "fromList"
[ bench "String" $ whnf IHM.fromList elems
, bench "ByteString" $ whnf IHM.fromList elemsBS
]
]
-- ** IntMap
, bgroup "IntMap"
[ bench "lookup" $ whnf (lookupIM keysI) im
, bench "lookup-miss" $ whnf (lookupIM keysI') im
, bench "insert" $ whnf (insertIM elemsI) IM.empty
, bench "insert-dup" $ whnf (insertIM elemsI) im
, bench "delete" $ whnf (deleteIM keysI) im
, bench "delete-miss" $ whnf (deleteIM keysI') im
, bench "size" $ whnf IM.size im
, bench "fromList" $ whnf IM.fromList elemsI
]
, bgroup "HashMap"
[ -- * Basic interface
bgroup "lookup"
[ bench "String" $ whnf (lookup keys) hm
, bench "ByteString" $ whnf (lookup keysBS) hmbs
, bench "Int" $ whnf (lookup keysI) hmi
]
, bgroup "lookup-miss"
[ bench "String" $ whnf (lookup keys') hm
, bench "ByteString" $ whnf (lookup keysBS') hmbs
, bench "Int" $ whnf (lookup keysI') hmi
]
, bgroup "insert"
[ bench "String" $ whnf (insert elems) HM.empty
, bench "ByteString" $ whnf (insert elemsBS) HM.empty
, bench "Int" $ whnf (insert elemsI) HM.empty
]
, bgroup "insert-dup"
[ bench "String" $ whnf (insert elems) hm
, bench "ByteString" $ whnf (insert elemsBS) hmbs
, bench "Int" $ whnf (insert elemsI) hmi
]
, bgroup "delete"
[ bench "String" $ whnf (delete keys) hm
, bench "ByteString" $ whnf (delete keysBS) hmbs
, bench "Int" $ whnf (delete keysI) hmi
]
, bgroup "delete-miss"
[ bench "String" $ whnf (delete keys') hm
, bench "ByteString" $ whnf (delete keysBS') hmbs
, bench "Int" $ whnf (delete keysI') hmi
]
-- Combine
, bench "union" $ whnf (HM.union hmi) hmi2
-- Transformations
, bench "map" $ whnf (HM.map (\ v -> v + 1)) hmi
-- * Difference and intersection
, bench "difference" $ whnf (HM.difference hmi) hmi2
, bench "intersection" $ whnf (HM.intersection hmi) hmi2
-- Folds
, bench "foldl'" $ whnf (HM.foldl' (+) 0) hmi
, bench "foldr" $ nf (HM.foldr (:) []) hmi
-- Filter
, bench "filter" $ whnf (HM.filter (\ v -> v .&. 1 == 0)) hmi
, bench "filterWithKey" $ whnf (HM.filterWithKey (\ k _ -> k .&. 1 == 0)) hmi
-- Size
, bgroup "size"
[ bench "String" $ whnf HM.size hm
, bench "ByteString" $ whnf HM.size hmbs
, bench "Int" $ whnf HM.size hmi
]
-- fromList
, bgroup "fromList"
[ bgroup "long"
[ bench "String" $ whnf HM.fromList elems
, bench "ByteString" $ whnf HM.fromList elemsBS
, bench "Int" $ whnf HM.fromList elemsI
]
, bgroup "short"
[ bench "String" $ whnf HM.fromList elemsDup
, bench "ByteString" $ whnf HM.fromList elemsDupBS
, bench "Int" $ whnf HM.fromList elemsDupI
]
]
-- fromListWith
, bgroup "fromListWith"
[ bgroup "long"
[ bench "String" $ whnf (HM.fromListWith (+)) elems
, bench "ByteString" $ whnf (HM.fromListWith (+)) elemsBS
, bench "Int" $ whnf (HM.fromListWith (+)) elemsI
]
, bgroup "short"
[ bench "String" $ whnf (HM.fromListWith (+)) elemsDup
, bench "ByteString" $ whnf (HM.fromListWith (+)) elemsDupBS
, bench "Int" $ whnf (HM.fromListWith (+)) elemsDupI
]
]
]
]
where
n :: Int
n = 2^(12 :: Int)
elems = zip keys [1..n]
keys = US.rnd 8 n
elemsBS = zip keysBS [1..n]
keysBS = UBS.rnd 8 n
elemsI = zip keysI [1..n]
keysI = UI.rnd (n+n) n
elemsI2 = zip [n `div` 2..n + (n `div` 2)] [1..n] -- for union
keys' = US.rnd' 8 n
keysBS' = UBS.rnd' 8 n
keysI' = UI.rnd' (n+n) n
keysDup = US.rnd 2 n
keysDupBS = UBS.rnd 2 n
keysDupI = UI.rnd (n`div`4) n
elemsDup = zip keysDup [1..n]
elemsDupBS = zip keysDupBS [1..n]
elemsDupI = zip keysDupI [1..n]
------------------------------------------------------------------------
-- * HashMap
lookup :: (Eq k, Hashable k) => [k] -> HM.HashMap k Int -> Int
lookup xs m = foldl' (\z k -> fromMaybe z (HM.lookup k m)) 0 xs
{-# SPECIALIZE lookup :: [Int] -> HM.HashMap Int Int -> Int #-}
{-# SPECIALIZE lookup :: [String] -> HM.HashMap String Int -> Int #-}
{-# SPECIALIZE lookup :: [BS.ByteString] -> HM.HashMap BS.ByteString Int
-> Int #-}
insert :: (Eq k, Hashable k) => [(k, Int)] -> HM.HashMap k Int
-> HM.HashMap k Int
insert xs m0 = foldl' (\m (k, v) -> HM.insert k v m) m0 xs
{-# SPECIALIZE insert :: [(Int, Int)] -> HM.HashMap Int Int
-> HM.HashMap Int Int #-}
{-# SPECIALIZE insert :: [(String, Int)] -> HM.HashMap String Int
-> HM.HashMap String Int #-}
{-# SPECIALIZE insert :: [(BS.ByteString, Int)] -> HM.HashMap BS.ByteString Int
-> HM.HashMap BS.ByteString Int #-}
delete :: (Eq k, Hashable k) => [k] -> HM.HashMap k Int -> HM.HashMap k Int
delete xs m0 = foldl' (\m k -> HM.delete k m) m0 xs
{-# SPECIALIZE delete :: [Int] -> HM.HashMap Int Int -> HM.HashMap Int Int #-}
{-# SPECIALIZE delete :: [String] -> HM.HashMap String Int
-> HM.HashMap String Int #-}
{-# SPECIALIZE delete :: [BS.ByteString] -> HM.HashMap BS.ByteString Int
-> HM.HashMap BS.ByteString Int #-}
------------------------------------------------------------------------
-- * Map
lookupM :: Ord k => [k] -> M.Map k Int -> Int
lookupM xs m = foldl' (\z k -> fromMaybe z (M.lookup k m)) 0 xs
{-# SPECIALIZE lookupM :: [String] -> M.Map String Int -> Int #-}
{-# SPECIALIZE lookupM :: [BS.ByteString] -> M.Map BS.ByteString Int -> Int #-}
insertM :: Ord k => [(k, Int)] -> M.Map k Int -> M.Map k Int
insertM xs m0 = foldl' (\m (k, v) -> M.insert k v m) m0 xs
{-# SPECIALIZE insertM :: [(String, Int)] -> M.Map String Int
-> M.Map String Int #-}
{-# SPECIALIZE insertM :: [(BS.ByteString, Int)] -> M.Map BS.ByteString Int
-> M.Map BS.ByteString Int #-}
deleteM :: Ord k => [k] -> M.Map k Int -> M.Map k Int
deleteM xs m0 = foldl' (\m k -> M.delete k m) m0 xs
{-# SPECIALIZE deleteM :: [String] -> M.Map String Int -> M.Map String Int #-}
{-# SPECIALIZE deleteM :: [BS.ByteString] -> M.Map BS.ByteString Int
-> M.Map BS.ByteString Int #-}
------------------------------------------------------------------------
-- * Map from the hashmap package
lookupIHM :: (Eq k, Hashable k, Ord k) => [k] -> IHM.Map k Int -> Int
lookupIHM xs m = foldl' (\z k -> fromMaybe z (IHM.lookup k m)) 0 xs
{-# SPECIALIZE lookupIHM :: [String] -> IHM.Map String Int -> Int #-}
{-# SPECIALIZE lookupIHM :: [BS.ByteString] -> IHM.Map BS.ByteString Int
-> Int #-}
insertIHM :: (Eq k, Hashable k, Ord k) => [(k, Int)] -> IHM.Map k Int
-> IHM.Map k Int
insertIHM xs m0 = foldl' (\m (k, v) -> IHM.insert k v m) m0 xs
{-# SPECIALIZE insertIHM :: [(String, Int)] -> IHM.Map String Int
-> IHM.Map String Int #-}
{-# SPECIALIZE insertIHM :: [(BS.ByteString, Int)] -> IHM.Map BS.ByteString Int
-> IHM.Map BS.ByteString Int #-}
deleteIHM :: (Eq k, Hashable k, Ord k) => [k] -> IHM.Map k Int -> IHM.Map k Int
deleteIHM xs m0 = foldl' (\m k -> IHM.delete k m) m0 xs
{-# SPECIALIZE deleteIHM :: [String] -> IHM.Map String Int
-> IHM.Map String Int #-}
{-# SPECIALIZE deleteIHM :: [BS.ByteString] -> IHM.Map BS.ByteString Int
-> IHM.Map BS.ByteString Int #-}
------------------------------------------------------------------------
-- * IntMap
lookupIM :: [Int] -> IM.IntMap Int -> Int
lookupIM xs m = foldl' (\z k -> fromMaybe z (IM.lookup k m)) 0 xs
insertIM :: [(Int, Int)] -> IM.IntMap Int -> IM.IntMap Int
insertIM xs m0 = foldl' (\m (k, v) -> IM.insert k v m) m0 xs
deleteIM :: [Int] -> IM.IntMap Int -> IM.IntMap Int
deleteIM xs m0 = foldl' (\m k -> IM.delete k m) m0 xs
|
athanclark/lh-bug
|
deps/unordered-containers/benchmarks/Benchmarks.hs
|
bsd-3-clause
| 12,760 | 0 | 19 | 4,207 | 3,750 | 1,918 | 1,832 | 233 | 1 |
-- Copyright (c) 2015, Travis Bemann
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- o Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
--
-- o Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- o Neither the name of the copyright holder nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
{-# LANGUAGE OverloadedStrings #-}
module Network.IRC.Client.Amphibian.Commands
(cmd_PASS,
cmd_NICK,
cmd_USER,
cmd_OPER,
cmd_MODE,
cmd_QUIT,
cmd_ERROR,
cmd_SQUIT,
cmd_JOIN,
cmd_PART,
cmd_PRIVMSG,
cmd_NOTICE,
cmd_NAMES,
cmd_PING,
cmd_PONG,
rpl_WELCOME,
rpl_YOURHOST,
rpl_CREATED,
rpl_MYINFO,
rpl_BOUNCE,
rpl_USERHOST,
rpl_ISON,
rpl_AWAY,
rpl_UNAWAY,
rpl_NOAWAY,
rpl_WHOISUSER,
rpl_WHOISSERVER,
rpl_WHOISOPERATOR,
rpl_WHOISIDLE,
rpl_ENDOFWHOIS,
rpl_WHOISCHANNELS,
rpl_WHOWASUSER,
rpl_ENDOFWHOWAS,
rpl_LISTSTART,
rpl_LIST,
rpl_LISTEND,
rpl_UNIQOPIS,
rpl_CHANNELMODEIS,
rpl_NOTOPIC,
rpl_TOPIC,
rpl_TOPICWHOTIME,
rpl_INVITING,
rpl_SUMMONING,
rpl_INVITELIST,
rpl_ENDOFINVITELIST,
rpl_EXCEPTLIST,
rpl_ENDOFEXCEPTLIST,
rpl_VERSION,
rpl_WHOREPLY,
rpl_ENDOFWHO,
rpl_NAMREPLY,
rpl_ENDOFNAMES,
rpl_LINKS,
rpl_ENDOFLINKS,
rpl_BANLIST,
rpl_ENDOFBANLIST,
rpl_INFO,
rpl_ENDOFINFO,
rpl_MOTDSTART,
rpl_MOTD,
rpl_ENDOFMOTD,
rpl_YOUREOPER,
rpl_REHASHING,
rpl_YOURESERVICE,
rpl_TIME,
rpl_USERSTART,
rpl_USERS,
rpl_ENDOFUSERS,
rpl_NOUSERS,
rpl_TRACELINK,
rpl_TRACECONNECTING,
rpl_TRACEHANDSHAKE,
rpl_TRACEUNKNOWN,
rpl_TRACEOPERATOR,
rpl_TRACEUSER,
rpl_TRACESERVER,
rpl_TRACESERVICE,
rpl_TRACENEWTYPE,
rpl_TRACECLASS,
rpl_TRACERECONNECT,
rpl_TRACELOG,
rpl_TRACEEND,
rpl_STATSLINKINFO,
rpl_STATSCOMMANDS,
rpl_ENDOFSTATS,
rpl_STATSUPTIME,
rpl_STATSOLINE,
rpl_UMODEIS,
rpl_SERVLIST,
rpl_SERVLISTEND,
rpl_LUSERCLIENT,
rpl_LUSEROP,
rpl_LUSERUNKNOWN,
rpl_LUSERCHANNELS,
rpl_LUSERME,
rpl_ADMINME,
rpl_ADMINLOC1,
rpl_ADMINLOC2,
rpl_ADMINEMAIL,
rpl_TRYAGAIN,
err_NOSUCHNICK,
err_NOSUCHSERVER,
err_NOSUCHCHANNEL,
err_CANNOTSENDTOCHAN,
err_TOOMANYCHANNELS,
err_WASNOSUCHNICK,
err_TOOMANYTARGETS,
err_NOSUCHSERVICE,
err_NOORIGIN,
err_NORECIPIENT,
err_NOTEXTTOSEND,
err_NOTOPLEVEL,
err_WILDTOPLEVEL,
err_BADMASK,
err_UNKNOWNCOMMAND,
err_NOMOTD,
err_NOADMININFO,
err_FILEERROR,
err_NONICKNAMEGIVEN,
err_ERRONEUSNICKNAME,
err_NICKNAMEINUSE,
err_NICKCOLLISION,
err_UNAVAILRESOURCE,
err_USERNOTINCHANNEL,
err_NOTONCHANNEL,
err_USERONCHANNEL,
err_NOLOGIN,
err_SUMMONDISABLED,
err_USERSDISABLED,
err_NOTREGISTERED,
err_NEEDMOREPARAMS,
err_ALREADYREGISTERED,
err_NOPERMFORHOST,
err_PASSWDMISMATCH,
err_YOUREBANNEDCREEP,
err_YOUWILLBEBANNED,
err_KEYSET,
err_CHANNELISFULL,
err_UNKNOWNMODE,
err_INVITEONLYCHAN,
err_BANNEDFROMCHAN,
err_BADCHANNELKEY,
err_BADCHANMASK,
err_NOCHANMODES,
err_BANLISTFULL,
err_NOPRIVILEGES,
err_CHANOPRIVSNEEDED,
err_CANTKILLSERVER,
err_RESTRICTED,
err_UNIQOPPRIVSNEEDED,
err_NOOPERHOST,
err_UMODEUNKNOWNFLAG,
err_USERSDONTMATCH,
rpl_SERVICEINFO,
rpl_ENDOFSERVICES,
rpl_SERVICE,
rpl_NONE,
rpl_WHOISCHANOP,
rpl_KILLDONE,
rpl_CLOSING,
rpl_CLOSEEND,
rpl_INFOSTART,
rpl_MYPORTIS,
rpl_STATSCLINE,
rpl_STATSNLINE,
rpl_STATSILINE,
rpl_STATSKLINE,
rpl_STATSQLINE,
rpl_STATSYLINE,
rpl_STATSIAUTH,
rpl_STATSVLINE,
rpl_STATSLLINE,
rpl_STATSUPTIME,
rpl_STATSOLINE,
rpl_STATSHLINE,
rpl_STATSSLINE,
rpl_STATSPING,
rpl_STATSBLINE,
rpl_STATSGLINE,
rpl_STATSXLINE,
rpl_STATSDEFINE,
rpl_STATSULINE,
rpl_STATSDEBUG,
rpl_STATSDLINE,
rpl_STATSCONN,
err_NOSERVICEHOST,
err_OTHER,
ctcp_ACTION,
ctcp_FINGER,
ctcp_VERSION,
ctcp_SOURCE,
ctcp_USERINFO,
ctcp_CLIENTINFO,
ctcp_ERRMSG,
ctcp_PING,
ctcp_TIME)
where
import Network.IRC.Client.Amphibian.Types
import qualified Data.ByteString as B
cmd_PASS :: MessageCommand
cmd_PASS = "PASS"
cmd_NICK :: MessageCommand
cmd_NICK = "NICK"
cmd_USER :: MessageCommand
cmd_USER = "USER"
cmd_OPER :: MessageCommand
cmd_OPER = "OPER"
cmd_MODE :: MessageCommand
cmd_MODE = "MODE"
cmd_QUIT :: MessageCommand
cmd_QUIT = "QUIT"
cmd_ERROR :: MessageCommand
cmd_ERROR = "ERROR"
cmd_SQUIT :: MessageCommand
cmd_SQUIT = "SQUIT"
cmd_JOIN :: MessageCommand
cmd_JOIN = "JOIN"
cmd_PART :: MessageCommand
cmd_PART = "PART"
cmd_PRIVMSG :: MessageCommand
cmd_PRIVMSG = "PRIVMSG"
cmd_NOTICE :: MessageCommand
cmd_NOTICE = "NOTICE"
cmd_NAMES :: MessageCommand
cmd_NAMES = "NAMES"
cmd_PING :: MessageCommand
cmd_PING = "PING"
cmd_PONG :: MessageCommand
cmd_PONG = "PONG"
rpl_WELCOME :: MessageCommand
rpl_WELCOME = "001"
rpl_YOURHOST :: MessageCommand
rpl_YOURHOST = "002"
rpl_CREATED :: MessageCommand
rpl_CREATED = "003"
rpl_MYINFO :: MessageCommand
rpl_MYINFO = "004"
rpl_BOUNCE :: MessageCommand
rpl_BOUNCE = "005"
rpl_USERHOST :: MessageCommand
rpl_USERHOST = "302"
rpl_ISON :: MessageCommand
rpl_ISON = "303"
rpl_AWAY :: MessageCommand
rpl_AWAY = "301"
rpl_UNAWAY :: MessageCommand
rpl_UNAWAY = "305"
rpl_NOAWAY :: MessageCommand
rpl_NOAWAY = "306"
rpl_WHOISUSER :: MessageCommand
rpl_WHOISUSER = "311"
rpl_WHOISSERVER :: MessageCommand
rpl_WHOISSERVER = "312"
rpl_WHOISOPERATOR :: MessageCommand
rpl_WHOISOPERATOR = "313"
rpl_WHOISIDLE :: MessageCommand
rpl_WHOISIDLE = "317"
rpl_ENDOFWHOIS :: MessageCommand
rpl_ENDOFWHOIS = "318"
rpl_WHOISCHANNELS :: MessageCommand
rpl_WHOISCHANNELS = "319"
rpl_WHOWASUSER :: MessageCommand
rpl_WHOWASUSER = "314"
rpl_ENDOFWHOWAS :: MessageCommand
rpl_ENDOFWHOWAS = "369"
rpl_LISTSTART :: MessageCommand
rpl_LISTSTART = "321"
rpl_LIST :: MessageCommand
rpl_LIST = "322"
rpl_LISTEND :: MessageCommand
rpl_LISTEND = "323"
rpl_UNIQOPIS :: MessageCommand
rpl_UNIQOPIS = "325"
rpl_CHANNELMODEIS :: MessageCommand
rpl_CHANNELMODEIS = "324"
rpl_NOTOPIC :: MessageCommand
rpl_NOTOPIC = "331"
rpl_TOPIC :: MessageCommand
rpl_TOPIC = "332"
rpl_TOPICWHOTIME :: MessageCommand
rpl_TOPICWHOTIME = "333"
rpl_INVITING :: MessageCommand
rpl_INVITING = "341"
rpl_SUMMONING :: MessageCommand
rpl_SUMMONING = "342"
rpl_INVITELIST :: MessageCommand
rpl_INVITELIST = "346"
rpl_ENDOFINVITELIST :: MessageCommand
rpl_ENDOFINVITELIST = "347"
rpl_EXCEPTLIST :: MessageCommand
rpl_EXCEPTLIST = "348"
rpl_ENDOFEXCEPTLIST :: MessageCommand
rpl_ENDOFEXCEPTLIST = "349"
rpl_VERSION :: MessageCommand
rpl_VERSION = "351"
rpl_WHOREPLY :: MessageCommand
rpl_WHOREPLY = "352"
rpl_ENDOFWHO :: MessageCommand
rpl_ENDOFWHO = "315"
rpl_NAMREPLY :: MessageCommand
rpl_NAMREPLY = "353"
rpl_ENDOFNAMES :: MessageCommand
rpl_ENDOFNAMES = "366"
rpl_LINKS :: MessageCommand
rpl_LINKS = "364"
rpl_ENDOFLINKS :: MessageCommand
rpl_ENDOFLINKS = "365"
rpl_BANLIST :: MessageCommand
rpl_BANLIST = "367"
rpl_ENDOFBANLIST :: MessageCommand
rpl_ENDOFBANLIST = "368"
rpl_INFO :: MessageCommand
rpl_INFO = "371"
rpl_ENDOFINFO :: MessageCommand
rpl_ENDOFINFO = "374"
rpl_MOTDSTART :: MessageCommand
rpl_MOTDSTART = "375"
rpl_MOTD :: MessageCommand
rpl_MOTD = "372"
rpl_ENDOFMOTD :: MessageCommand
rpl_ENDOFMOTD = "376"
rpl_YOUREOPER :: MessageCommand
rpl_YOUREOPER = "381"
rpl_REHASHING :: MessageCommand
rpl_REHASHING = "382"
rpl_YOURESERVICE :: MessageCommand
rpl_YOURESERVICE = "383"
rpl_TIME :: MessageCommand
rpl_TIME = "391"
rpl_USERSSTART :: MessageCommand
rpl_USERSSTART = "392"
rpl_USERS :: MessageCommand
rpl_USERS = "393"
rpl_ENDOFUSERS :: MessageCommand
rpl_ENDOFUSERS = "394"
rpl_NOUSERS :: MessageCommand
rpl_NOUSERS = "395"
rpl_TRACELINK :: MessageCommand
rpl_TRACELINK = "200"
rpl_TRACECONNECTING :: MessageCommand
rpl_TRACECONNECTING = "201"
rpl_TRACEHANDSHAKE :: MessageCommand
rpl_TRACEHANDSHAKE = "202"
rpl_TRACEUNKNOWN :: MessageCommand
rpl_TRACEUNKNOWN = "203"
rpl_TRACEOPERATOR :: MessageCommand
rpl_TRACEOPERATOR = "204"
rpl_TRACEUSER :: MessageCommand
rpl_TRACEUSER = "205"
rpl_TRACESERVER :: MessageCommand
rpl_TRACESERVER = "206"
rpl_TRACESERVICE :: MessageCommand
rpl_TRACESERVICE = "207"
rpl_TRACENEWTYPE :: MessageCommand
rpl_TRACENEWTYPE = "208"
rpl_TRACECLASS :: MessageCommand
rpl_TRACECLASS = "209"
rpl_TRACERECONNECT :: MessageCommand
rpl_TRACERECONNECT = "210"
rpl_TRACELOG :: MessageCommand
rpl_TRACELOG = "261"
rpl_TRACEEND :: MessageCommand
rpl_TRACEEND = "262"
rpl_STATSLINKINFO :: MessageCommand
rpl_STATSLINKINFO = "211"
rpl_STATSCOMMANDS :: MessageCommand
rpl_STATSCOMMANDS = "212"
rpl_ENDOFSTATS :: MessageCommand
rpl_ENDOFSTATS = "219"
rpl_STATSUPTIME :: MessageCommand
rpl_STATSUPTIME = "242"
rpl_STATSOLINE :: MessageCommand
rpl_STATSOLINE = "243"
rpl_UMODEIS :: MessageCommand
rpl_UMODEIS = "221"
rpl_SERVLIST :: MessageCommand
rpl_SERVLIST = "234"
rpl_SERVLISTEND :: MessageCommand
rpl_SERVLISTEND = "235"
rpl_LUSERCLIENT :: MessageCommand
rpl_LUSERCLIENT = "251"
rpl_LUSEROP :: MessageCommand
rpl_LUSEROP = "252"
rpl_LUSERUNKNOWN :: MessageCommand
rpl_LUSERUNKNOWN = "253"
rpl_LUSERCHANNELS :: MessageCommand
rpl_LUSERCHANNELS = "254"
rpl_LUSERME :: MessageCommand
rpl_LUSERME = "255"
rpl_ADMINME :: MessageCommand
rpl_ADMINME = "256"
rpl_ADMINLOC1 :: MessageCommand
rpl_ADMINLOC1 = "257"
rpl_ADMINLOC2 :: MessageCommand
rpl_ADMINLOC2 = "258"
rpl_ADMINEMAIL :: MessageCommand
rpl_ADMINEMAIL = "259"
rpl_TRYAGAIN :: MessageCOmmand
rpl_TRYAGAIN = "263"
err_NOSUCHNICK :: MessageCommand
err_NOSUCHNICK = "401"
err_NOSUCHSERVER :: MessageCommand
err_NOSUCHSERVER = "402"
err_NOSUCHCHANNEL :: MessageCommand
err_NOSUCHCHANNEL = "403"
err_CANNOTSENDTOCHAN :: MessageCommand
err_CANNOTSENDTOCHAN = "404"
err_TOOMANYCHANNELS :: MessageCommand
err_TOOMANYCHANNELS = "405"
err_WASNOSUCHNICK :: MessageCommand
err_WASNOSUCHNICK = "406"
err_TOOMANYTARGETS :: MessageCommand
err_TOOMANYTARGETS = "407"
err_NOSUCHSERVICE :: MessageCommand
err_NOSUCHSERVICE = "408"
err_NOORIGIN :: MessageCommand
err_NOORIGIN = "409"
err_NORECIPIENT :: MessageCommand
err_NORECIPIENT = "411"
err_NOTEXTTOSEND :: MessageCommand
err_NOTEXTTOSEND = "412"
err_NOTOPLEVEL :: MessageCommand
err_NOTOPLEVEL = "413"
err_WILDTOPLEVEL :: MessageCommand
err_WILDTOPLEVEL = "414"
err_BADMASK :: MessageCommand
err_BADMASK = "415"
err_UNKNOWNCOMMAND :: MessageCommand
err_UNKNOWNCOMMAND = "421"
err_NOMOTD :: MessageCommand
err_NOMOTD = "422"
err_NOADMININFO :: MessageCommand
err_NOADMININFO = "423"
err_FILEERROR :: MessageCommand
err_FILEERROR = "424"
err_NONICKNAMEGIVEN :: MessageCommand
err_NONICKNAMEGIVEN = "431"
err_ERRONEUSNICKNAME :: MessageCommand
err_ERRONEUSNICKNAME = "432"
err_NICKNAMEINUSE :: MessageCommand
err_NICKNAMEINUSE = "433"
err_NICKCOLLISION :: MessageCommand
err_NICKCOLLISION = "436"
err_UNAVAILRESOURCE :: MessageCommand
err_UNAVAILRESOURCE = "437"
err_USERNOTINCHANNEL :: MessageCommand
err_USERNOTINCHANNEL = "441"
err_NOTONCHANNEL :: MessageCommand
err_NOTONCHANNEL = "442"
err_USERONCHANNEL :: MessageCommand
err_USERONCHANNEL = "443"
err_NOLOGIN :: MessageCommand
err_NOLOGIN = "444"
err_SUMMONDISABLED :: MessageCommand
err_SUMMONDISABLED = "445"
err_USERSDISABLED :: MessageCommand
err_USERSDISABLED = "446"
err_NOTREGISTERED :: MessageCommand
err_NOTREGISTERED = "451"
err_NEEDMOREPARAMS :: MessageCommand
err_NEEDMOREPARAMS = "461"
err_ALREADYREGISTERED :: MessageCommand
err_ALREADYREGISTERED = "462"
err_NOPERMFORHOST :: MessageCommand
err_NOPERMFORHOST = "463"
err_PASSWDMISMATCH :: MessageCommand
err_PASSWDMISMATCH = "464"
err_YOUREBANNEDCREEP :: MessageCommand
err_YOUREBANNEDCREEP = "465"
err_YOUWILLBEBANNED :: MessageCommand
err_YOUWILLBEBANNED = "466"
err_KEYSET :: MessageCommand
err_KEYSET = "467"
err_CHANNELISFULL :: MessageCommand
err_CHANNELISFULL = "471"
err_UNKNOWNMODE :: MessageCommand
err_UNKNOWNMODE = "472"
err_INVITEONLYCHAN :: MessageCommand
err_INVITEONLYCHAN = "473"
err_BANNEDFROMCHAN :: MessageCommand
err_BANNEDFROMCHAN = "474"
err_BADCHANNELKEY :: MessageCommand
err_BADCHANNELKEY = "475"
err_BADCHANMASK :: MessageCommand
err_BADCHANMASK = "476"
err_NOCHANMODES :: MessageCommand
err_NOCHANMODES = "477"
err_BANLISTFULL :: MessageCommand
err_BANLISTFULL = "478"
err_NOPRIVILEGES :: MessageCommand
err_NOPRIVILEGES = "481"
err_CHANOPRIVSNEEDED :: MessageCommand
err_CHANOPRIVSNEEDED = "482"
err_CANTKILLSERVER :: MessageCommand
err_CANTKILLSERVER = "483"
err_RESTRICTED :: MessageCommand
err_RESTRICTED = "484"
err_UNIQOPPRIVSNEEDED :: MessageCommand
err_UNIQOPPRIVSNEEDED = "485"
err_NOOPERHOST :: MessageCommand
err_NOOPERHOST = "491"
err_UMODEUNKNOWNFLAG :: MessageCommand
err_UMODEUNKNOWNFLAG = "501"
err_USERSDONTMATCH :: MessageCommand
err_USERSDONTMATCH = "502"
-- Nonstandard reply and error codes
rpl_SERVICEINFO :: MessageCommand
rpl_SERVICEINFO = "231"
rpl_ENDOFSERVICES :: MessageCommand
rpl_ENDOFSERVICES = "232"
rpl_SERVICE :: MessageCommand
rpl_SERVICE = "233"
rpl_NONE :: MessageCommand
rpl_NONE = "300"
rpl_WHOISCHANOP :: MessageCommand
rpl_WHOISCHANOP = "316"
rpl_KILLDONE :: MessageCommand
rpl_KILLDONE = "361"
rpl_CLOSING :: MessageCommand
rpl_CLOSING = "362"
rpl_CLOSEEND :: MessageCommand
rpl_CLOSEEND = "363"
rpl_INFOSTART :: MessageCommand
rpl_INFOSTART = "373"
rpl_MYPORTIS :: MessageCommand
rpl_MYPORTIS = "384"
rpl_STATSCLINE :: MessageCommand
rpl_STATSCLINE = "213"
rpl_STATSNLINE :: MessageCommand
rpl_STATSNLINE = "214"
rpl_STATSILINE :: MessageCommand
rpl_STATSILINE = "215"
rpl_STATSKLINE :: MessageCommand
rpl_STATSKLINE = "216"
rpl_STATSQLINE :: MessageCommand
rpl_STATSQLINE = "217"
rpl_STATSYLINE :: MessageCommand
rpl_STATSYLINE = "218"
rpl_STATSIAUTH :: MessageCommand
rpl_STATSIAUTH = "239"
rpl_STATSVLINE :: MessageCommand
rpl_STATSVLINE = "240"
rpl_STATSLLINE :: MessageCommand
rpl_STATSLLINE = "241"
rpl_STATSUPTIME :: MessageCommand
rpl_STATSUPTIME = "242"
rpl_STATSOLINE :: MessageCommand
rpl_STATSOLINE = "243"
rpl_STATSHLINE :: MessageCommand
rpl_STATSHLINE = "244"
rpl_STATSSLINE :: MessageCommand
rpl_STATSSLINE = "245"
rpl_STATSPING :: MessageCommand
rpl_STATSPING = "246"
rpl_STATSBLINE :: MessageCommand
rpl_STATSBLINE = "247"
rpl_STATSGLINE :: MessageCommand
rpl_STATSGLINE = "247"
rpl_STATSXLINE :: MessageCommand
rpl_STATSXLINE = "247"
rpl_STATSDEFINE :: MessageCommand
rpl_STATSDEFINE = "248"
rpl_STATSULINE :: MessageCommand
rpl_STATSULINE = "248"
rpl_STATSDEBUG :: MessageCommand
rpl_STATSDEBUG = "249"
rpl_STATSDLINE :: MessageCommand
rpl_STATSDLINE = "250"
rpl_STATSCONN :: MessageCommand
rpl_STATSCONN = "250"
err_NOSERVICEHOST :: MessageCommand
err_NOSERVICEHOST = "492"
err_OTHER :: MessageCommand
err_OTHER = "500"
-- CTCP requests/replies
ctcp_ACTION :: CtcpCommand
ctcp_ACTION = "ACTION"
ctcp_FINGER :: CtcpCommand
ctcp_FINGER = "FINGER"
ctcp_VERSION :: CtcpCommand
ctcp_VERSION = "VERSION"
ctcp_SOURCE :: CtcpCommand
ctcp_SOURCE = "SOURCE"
ctcp_USERINFO :: CtcpCommand
ctcp_USERINFO = "USERINFO"
ctcp_CLIENTINFO :: CtcpCommand
ctcp_CLIENTINFO = "CLIENTINFO"
ctcp_ERRMSG :: CtcpCommand
ctcp_ERRMSG = "ERRMSG"
ctcp_PING :: CtcpCommand
ctcp_PING = "PING"
ctcp_TIME :: CtcpCommand
ctcp_TIME = "TIME"
|
tabemann/amphibian
|
src_old/Network/IRC/Client/Amphibian/Commands.hs
|
bsd-3-clause
| 17,556 | 0 | 4 | 3,444 | 2,605 | 1,618 | 987 | 592 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Logic.Books where
import Database.Persist.MySQL
import Servant
import Control.Monad.Trans.Either
import Control.Monad.IO.Class
import Data.Text hiding (replace, length, any, concat, map, filter)
import Data.Char
import Data.Maybe
import Data.Word
import Auth.DbAuth
import Db.Common
import Json.Book (Book(..))
import qualified Json.Book as JsonBook
import qualified Db.Book as DbBook
import Json.User (User(..))
import qualified Json.User as JsonUser
import qualified Convert.BookConverter as C
createBook :: ConnectionPool -> String -> Maybe Text -> Book -> EitherT ServantErr IO ()
createBook _ _ Nothing _ = return ()
createBook pool salt (Just authHeader) book =
withUser pool authHeader salt $ \user -> do
query pool $ insert (C.toRecord book {user_id = JsonUser.id user} :: DbBook.Book)
return ()
bookBelongsToUser :: MonadIO m => ConnectionPool -> User -> Int -> m Bool
bookBelongsToUser _ (User {JsonUser.id = Nothing}) _ = return False -- No user id
bookBelongsToUser pool (User {JsonUser.id = _id}) _bid = do
books <- query pool $ selectList [DbBook.BookUser_id ==. _id, DbBook.BookId ==. toKey _bid] []
return $ length books == 1
updateBook :: ConnectionPool -> String -> Maybe Text -> Book -> EitherT ServantErr IO ()
updateBook _ _ Nothing _ = return ()
updateBook pool salt (Just authHeader) book =
withUser pool authHeader salt $ \user ->
case book of
Book {JsonBook.id = Nothing} -> left $ err400 { errBody = "No id specified!" }
Book {JsonBook.id = Just _id} -> do
belongs <- bookBelongsToUser pool user _id
if belongs
then do
query pool $ replace (toKey _id :: Key DbBook.Book)
(C.toRecord book {user_id = JsonUser.id user} :: DbBook.Book)
return ()
else return ()
deleteBook :: ConnectionPool -> String -> Maybe Text -> Int -> EitherT ServantErr IO ()
deleteBook _ _ Nothing _ = return ()
deleteBook pool salt (Just authHeader) _id =
withUser pool authHeader salt $ \user -> do
belongs <- bookBelongsToUser pool user _id
if belongs
then do
query pool $ delete (toKey _id :: Key DbBook.Book)
return ()
else return ()
showBook :: ConnectionPool -> Int -> EitherT ServantErr IO (Maybe Book)
showBook pool id = do
book <- query pool $ selectFirst [DbBook.BookId ==. (toKey id :: Key DbBook.Book)] []
return $ maybeBook book
where maybeBook Nothing = Nothing
maybeBook (Just b) = C.toJson b
selectBooks :: ConnectionPool -> Maybe String -> Maybe String -> Maybe Word16 -> Maybe Word16 -> EitherT ServantErr IO [Book]
selectBooks _ Nothing _ _ _= return []
selectBooks _ _ Nothing _ _ = return []
selectBooks _ _ _ Nothing _ = return []
selectBooks _ _ _ _ Nothing = return []
selectBooks pool (Just field) (Just searchStr) (Just offset) (Just limit) = do
let entityField = case field of
"title" -> DbBook.BookTitle
"author" -> DbBook.BookAuthor
"content" -> DbBook.BookContent
if any (not . isAlphaNum) searchStr
then return []
else do
books <- query pool $ selectList [Filter entityField (Left $ concat ["%", searchStr, "%"]) (BackendSpecificFilter "like")]
[OffsetBy $ fromIntegral offset, LimitTo $ fromIntegral limit]
return $ map (\(Just b) -> b) $ filter isJust $ map C.toJson books
|
dbushenko/biblio
|
src/Logic/Books.hs
|
bsd-3-clause
| 3,762 | 0 | 22 | 1,040 | 1,276 | 647 | 629 | 78 | 4 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ConstraintKinds #-}
-- | Loading targets.
module GHC.Server.Controller.Load where
import GHC.Compat
import GHC.Server.Defaults
import GHC.Server.Duplex
import GHC.Server.Logging
import GHC.Server.Model.Ghc
import GHC.Server.Model.Info
import GHC.Server.Types
import Control.Arrow
import Control.Concurrent.STM
import Control.Monad
import Control.Monad.Logger
import Control.Monad.Reader
import Data.Map (Map)
import qualified Data.Map as M
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
-- | Load a module.
loadTarget :: Text -> Producer Msg (SuccessFlag,Integer)
loadTarget filepath =
withGhc (do df <- getSessionDynFlags
warnings <- liftIO (atomically (newTVar (0,0)))
(result,loaded) <- withMessages (recordMessage warnings)
doLoad
case result of
Succeeded ->
do var <- getModuleInfosVar
void (forkGhc (runLogging (collectInfo var loaded)))
_ -> return ()
count <- liftIO (atomically (readTVar warnings))
return (result,snd count))
where recordMessage warnings df sev sp doc =
do send (Msg sev sp (T.pack (showSDoc df doc)))
case sev of
SevWarning ->
liftIO (atomically
(modifyTVar' warnings
(second (+ 1))))
SevError ->
liftIO (atomically
(modifyTVar' warnings
(first (+ 1))))
_ -> return ()
doLoad =
do target <- guessTarget (T.unpack filepath)
Nothing
setTargets [target]
result <- load LoadAllTargets
loaded <- getModuleGraph >>= filterM isLoaded . map ms_mod_name
mapM parseImportDecl (necessaryImports <> loadedImports loaded) >>=
setContext
return (result,loaded)
-- | Collect type info data for the loaded modules.
collectInfo :: (GhcMonad m,MonadLogger m)
=> TVar (Map ModuleName ModInfo) -> [ModuleName] -> m ()
collectInfo var loaded =
do ($(logDebug)
("Collecting module data for " <>
T.pack (show (length loaded)) <>
" modules ..."))
forM_ loaded
(\name ->
do info <- getModInfo name
io (atomically
(modifyTVar var
(M.insert name info))))
$(logDebug) ("Done collecting module data.")
|
chrisdone/ghc-server
|
src/GHC/Server/Controller/Load.hs
|
bsd-3-clause
| 2,909 | 0 | 20 | 1,133 | 714 | 369 | 345 | 70 | 4 |
{-# LANGUAGE CPP, OverloadedStrings #-}
module MOO.Builtins (builtinFunctions, callBuiltin, verifyBuiltins) where
import Control.Applicative ((<$>))
import Control.Monad (foldM)
import Data.HashMap.Lazy (HashMap)
import Data.List (transpose, inits)
import Data.Maybe (fromMaybe)
import Data.Monoid ((<>))
import qualified Data.HashMap.Lazy as HM
import MOO.Builtins.Common
import MOO.Database
import MOO.Object
import MOO.Task
import MOO.Types
import MOO.Builtins.Extra as Extra
import MOO.Builtins.Misc as Misc
import MOO.Builtins.Network as Network
import MOO.Builtins.Objects as Objects
import MOO.Builtins.Tasks as Tasks
import MOO.Builtins.Values as Values
-- | A 'HashMap' of all built-in functions, keyed by name
builtinFunctions :: HashMap Id Builtin
builtinFunctions =
HM.fromList $ map assoc $ Extra.builtins ++ Misc.builtins ++
Values.builtins ++ Objects.builtins ++ Network.builtins ++ Tasks.builtins
where assoc builtin = (builtinName builtin, builtin)
-- | Call the named built-in function with the given arguments, checking first
-- for the appropriate number and types of arguments. Raise 'E_INVARG' if the
-- built-in function is unknown.
callBuiltin :: Id -> [Value] -> MOO Value
callBuiltin func args = do
isProtected <- ($ func) <$> serverOption protectFunction
case (func `HM.lookup` builtinFunctions, isProtected) of
(Just builtin, False) -> call builtin
(Just builtin, True) -> do
this <- frame initialThis
if this == Obj systemObject then call builtin
else callSystemVerb ("bf_" <> fromId func) args >>=
maybe (checkWizard >> call builtin) return
(Nothing, _) -> let name = fromId func
message = "Unknown built-in function: " <> name
in raiseException (Err E_INVARG) message (Str name)
where call :: Builtin -> MOO Value
call builtin = checkArgs builtin args >> builtinFunction builtin args
checkArgs :: Builtin -> [Value] -> MOO ()
checkArgs Builtin { builtinMinArgs = min
, builtinMaxArgs = max
, builtinArgTypes = types
} args
| nargs < min || maybe False (nargs >) max = raise E_ARGS
| otherwise = checkTypes types args
where nargs = length args :: Int
checkTypes :: [Type] -> [Value] -> MOO ()
checkTypes (t:ts) (v:vs)
| typeMismatch t (typeOf v) = raise E_TYPE
| otherwise = checkTypes ts vs
checkTypes _ _ = return ()
typeMismatch :: Type -> Type -> Bool
typeMismatch a b | a == b = False
typeMismatch TAny _ = False
typeMismatch TNum TInt = False
typeMismatch TNum TFlt = False
typeMismatch _ _ = True
-- | Perform internal consistency verification of all the built-in functions,
-- checking that each implementation actually accepts the claimed argument
-- types. Note that an inconsistency may cause the program to abort.
--
-- Assuming the program doesn't abort, this generates either a string
-- describing an inconsistency, or an integer giving the total number of
-- (verified) built-in functions.
verifyBuiltins :: Either String Int
verifyBuiltins = foldM accum 0 $ HM.elems builtinFunctions
where accum :: Int -> Builtin -> Either String Int
accum a b = valid b >>= Right . (+ a)
valid :: Builtin -> Either String Int
valid Builtin { builtinName = name
, builtinMinArgs = min
, builtinMaxArgs = max
, builtinArgTypes = types
, builtinFunction = func
}
| min < 0 = invalid "arg min < 0"
| maybe False (< min) max = invalid "arg max < min"
| length types /= fromMaybe min max = invalid "incorrect # types"
| testArgs func min max types = ok
where invalid :: String -> Either String Int
invalid msg = Left $ "problem with built-in function " ++
fromId name ++ ": " ++ msg
ok = Right 1
testArgs :: ([Value] -> MOO Value) -> Int -> Maybe Int -> [Type] -> Bool
testArgs func min max types = all test argSpecs
where argSpecs = drop min $ inits $ map mkArgs augmentedTypes
augmentedTypes = maybe (types ++ [TAny]) (const types) max
test argSpec = all (\args -> func args `seq` True) $
enumerateArgs argSpec
enumerateArgs :: [[Value]] -> [[Value]]
enumerateArgs [a] = transpose [a]
enumerateArgs (a:as) = concatMap (combine a) (enumerateArgs as)
where combine ps rs = map (: rs) ps
enumerateArgs [] = [[]]
mkArgs :: Type -> [Value]
mkArgs TAny = mkArgs TNum ++ mkArgs TStr ++ mkArgs TObj ++
mkArgs TErr ++ mkArgs TLst
# ifdef MOO_WAIF
++ mkArgs TWaf
# endif
mkArgs TNum = mkArgs TInt ++ mkArgs TFlt
mkArgs TInt = [Int 0]
mkArgs TFlt = [Flt 0]
mkArgs TStr = [emptyString]
mkArgs TObj = [Obj 0]
mkArgs TErr = [Err E_NONE]
mkArgs TLst = [emptyList]
# ifdef MOO_WAIF
mkArgs TWaf = [Waf undefined]
# endif
|
verement/etamoo
|
src/MOO/Builtins.hs
|
bsd-3-clause
| 5,487 | 0 | 17 | 1,777 | 1,473 | 775 | 698 | 98 | 10 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Lib.ColorText
( ColorText(..), normalize, simple
, render, renderStr, stripColors
, withAttr
, intercalate, lines, putStrLn, singleton
) where
import Prelude.Compat hiding (putStrLn, lines)
import Data.Binary (Binary)
import Data.ByteString (ByteString)
import Data.Function (on)
import Data.String (IsString(..))
import GHC.Generics (Generic)
import Lib.AnsiConsoleUtils ()
import qualified Data.ByteString.Char8 as BS8
import qualified Data.List as List
import qualified System.Console.ANSI as Console
newtype ColorText = ColorText { colorTextPairs :: [([Console.SGR], ByteString)] }
deriving (Semigroup, Monoid, Show, Generic)
instance Binary ColorText
{-# INLINE onFirst #-}
onFirst :: (a -> a') -> (a, b) -> (a', b)
onFirst f (x, y) = (f x, y)
withAttr :: [Console.SGR] -> ColorText -> ColorText
withAttr sgrs (ColorText pairs) = ColorText $ (map . onFirst) (sgrs++) pairs
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn f = List.groupBy ((==) `on` f)
normalize :: ColorText -> ColorText
normalize = ColorText . map concatGroup . groupOn fst . filter (not . BS8.null . snd) . colorTextPairs
where
concatGroup items@((attrs, _):_) = (attrs, BS8.concat (map snd items))
concatGroup [] = error "groupOn yielded empty group!"
instance Eq ColorText where
(==) = (==) `on` (colorTextPairs . normalize)
simple :: ByteString -> ColorText
simple x = ColorText [([], x)]
instance IsString ColorText where
fromString = simple . fromString
putStrLn :: ColorText -> IO ()
putStrLn = BS8.putStrLn . render
renderStr :: ColorText -> String
renderStr = BS8.unpack . render
render :: ColorText -> ByteString
render = go [] . colorTextPairs
where
go [] [] = ""
go (_:_) [] = fromString (Console.setSGRCode [])
go curSgrs ((sgrs, x):rest) = colorCode <> x <> go sgrs rest
where
colorCode
| curSgrs /= sgrs = fromString (Console.setSGRCode sgrs)
| otherwise = ""
stripColors :: ColorText -> ByteString
stripColors = mconcat . map snd . colorTextPairs
intercalate :: Monoid m => m -> [m] -> m
intercalate x = mconcat . List.intersperse x
singleton :: [Console.SGR] -> ByteString -> ColorText
singleton attrs text = ColorText [(attrs, text)]
lines :: ColorText -> [ColorText]
lines (ColorText pairs) =
foldr combine [] linedPairs
where
-- For each attr, hold a list of lines with that attr:
linedPairs = (map . fmap) (BS8.split '\n') pairs
-- combine each (attrs, list of lines) with the rest of the ColorText
combine (_, []) restLines = restLines
combine (attrs, ls@(_:_)) (ColorText restLinePairs:restLines) =
map (singleton attrs) (init ls) ++
(ColorText ((attrs, last ls) : restLinePairs) : restLines)
combine (attrs, ls@(_:_)) [] = map (singleton attrs) ls
|
buildsome/buildsome
|
src/Lib/ColorText.hs
|
gpl-2.0
| 2,832 | 0 | 14 | 541 | 1,059 | 588 | 471 | 63 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module Internal.Num
( Number
, (+)
, (-)
, (*)
, (/)
, (^)
, (>)
, (>=)
, (<)
, (<=)
, max
, min
, negate
, abs
, absoluteValue
, signum
, truncation
, rounded
, ceiling
, floor
, quotient
, remainder
, pi
, exp
, sqrt
, squareRoot
, log
, logBase
, sin
, tan
, cos
, asin
, atan
, acos
, properFraction
, even
, odd
, gcd
, lcm
, sum
, product
, maximum
, minimum
, isInteger
, fromInteger
, fromRational
, fromInt
, toInt
, fromDouble
, toDouble
) where
import Numeric (showFFloatAlt)
import qualified "base" Prelude as P
import "base" Prelude (Bool(..), (.), (==), map)
import qualified Internal.Truth
import Internal.Truth (Truth, (&&), otherwise)
import GHC.Stack (HasCallStack, withFrozenCallStack)
{-|The type for numbers.
Numbers can be positive or negative, whole or fractional. For example, 5,
3.2, and -10 are all values of the type Number.
-}
newtype Number =
Number P.Double
deriving (P.RealFrac, P.Real, P.Floating, P.RealFloat, P.Eq)
{-# RULES
"equality/num" forall (x :: Number) . (Internal.Truth.==) x =
(P.==) x
#-}
{-# RULES
"equality/point" forall (x :: (Number, Number)) .
(Internal.Truth.==) x = (P.==) x
#-}
fromDouble :: HasCallStack => P.Double -> Number
fromDouble x
| P.isNaN x = P.error "Number is undefined."
| P.isInfinite x = P.error "Number is too large."
| otherwise = Number x
toDouble :: Number -> P.Double
toDouble (Number x) = x
fromInteger :: P.Integer -> Number
fromInteger = fromDouble . P.fromInteger
fromRational :: P.Rational -> Number
fromRational = fromDouble . P.fromRational
fromInt :: P.Int -> Number
fromInt = fromDouble . P.fromIntegral
toInt :: HasCallStack => Number -> P.Int
toInt n
| isInteger n = P.truncate (toDouble n)
| otherwise = P.error "Whole number is required."
instance P.Show Number where
show (Number x) = stripZeros (showFFloatAlt (P.Just 4) x "")
where
stripZeros =
P.reverse . P.dropWhile (== '.') . P.dropWhile (== '0') . P.reverse
instance P.Num Number where
fromInteger = fromInteger
(+) = (+)
(-) = (-)
(*) = (*)
negate (Number n) = Number (P.negate n)
abs = abs
signum = signum
instance P.Fractional Number where
fromRational x = Number (P.fromRational x)
(/) = (/)
instance P.Enum Number where
succ = fromDouble . P.succ . toDouble
pred = fromDouble . P.pred . toDouble
toEnum = fromDouble . P.toEnum
fromEnum = P.fromEnum . toDouble
enumFrom = map fromDouble . P.enumFrom . toDouble
enumFromThen (Number a) (Number b) = map fromDouble (P.enumFromThen a b)
enumFromTo (Number a) (Number b) = map fromDouble (P.enumFromTo a b)
enumFromThenTo (Number a) (Number b) (Number c) =
map fromDouble (P.enumFromThenTo a b c)
instance P.Ord Number where
compare (Number a) (Number b) = P.compare a b
{-| Tells whether a Number is an integer or not.
An integer is a whole number, such as 5, 0, or -10. Numbers with non-zero
decimals, like 5.3, are not integers.
-}
isInteger :: Number -> Truth
isInteger (Number x) = x == P.fromIntegral (P.truncate x)
infixr 8 ^
infixl 7 *, /
infixl 6 +, -
infix 4 <, <=, >=, >
{-| Adds two numbers. -}
(+) :: Number -> Number -> Number
Number a + Number b = fromDouble (a P.+ b)
{-| Subtracts two numbers. -}
(-) :: Number -> Number -> Number
Number a - Number b = fromDouble (a P.- b)
{-| Multiplies two numbers. -}
(*) :: Number -> Number -> Number
Number a * Number b = fromDouble (a P.* b)
{-| Divides two numbers. The second number should not be zero. -}
(/) :: HasCallStack => Number -> Number -> Number
Number a / Number b
| b == 0 = withFrozenCallStack (P.error "Cannot divide by zero.")
| otherwise = fromDouble (a P./ b)
{-| Raises a number to a power. -}
(^) :: HasCallStack => Number -> Number -> Number
Number a ^ Number b
| a P.< 0 && P.not (isInteger (Number b)) =
withFrozenCallStack
(P.error "Negative numbers cannot be raised to fractional powers.")
| a P.== 0 && b P.< 0 =
withFrozenCallStack
(P.error "Zero cannot be raised to negative powers.")
| otherwise = fromDouble (a P.** b)
{-| Tells whether one number is less than the other. -}
(<) :: Number -> Number -> Truth
Number a < Number b = a P.< b
{-| Tells whether one number is less than or equal to the other. -}
(<=) :: Number -> Number -> Truth
Number a <= Number b = a P.<= b
{-| Tells whether one number is greater than the other. -}
(>) :: Number -> Number -> Truth
Number a > Number b = a P.> b
{-| Tells whether one number is greater than or equal to the other. -}
(>=) :: Number -> Number -> Truth
Number a >= Number b = a P.>= b
{-| Gives the larger of two numbers. -}
max :: (Number, Number) -> Number
max (Number a, Number b) = fromDouble (P.max a b)
{-| Gives the smaller of two numbers. -}
min :: (Number, Number) -> Number
min (Number a, Number b) = fromDouble (P.min a b)
negate :: Number -> Number
negate = P.negate
{-| Gives the absolute value of a number.
If the number if positive or zero, the absolute value is the same as the
number. If the number is negative, the absolute value is the opposite of
the number.
-}
abs :: Number -> Number
abs = fromDouble . P.abs . toDouble
absoluteValue :: Number -> Number
absoluteValue = abs
{-| Gives the sign of a number.
If the number is negative, the signum is -1. If it's positive, the signum
is 1. If the number is 0, the signum is 0. In general, a number is equal
to its absolute value ('abs') times its sign ('signum').
-}
signum :: Number -> Number
signum = fromDouble . P.signum . toDouble
{-| Gives the number without its fractional part.
For example, truncate(4.2) is 4, while truncate(-4.7) is -4.
-}
truncation :: Number -> Number
truncation = fromInteger . P.truncate . toDouble
{-| Gives the number rounded to the nearest integer.
For example, round(4.2) is 4, while round(4.7) is 5.
-}
rounded :: Number -> Number
rounded = fromInteger . P.round . toDouble
{-| Gives the smallest integer that is greater than or equal to a number.
For example, ceiling(4) is 4, while ceiling(4.1) is 5. With negative
numbers, ceiling(-3.5) is -3, since -3 is greater than -3.5.
-}
ceiling :: Number -> Number
ceiling = fromInteger . P.ceiling . toDouble
{-| Gives the largest integer that is less than or equal to a number.
For example, floor(4) is 4, while floor(3.9) is 3. With negative
numbers, floor(-3.5) is -4, since -4 is less than -3.5.
-}
floor :: Number -> Number
floor = fromInteger . P.floor . toDouble
{-| Gives the integer part of the result when dividing two numbers.
For example, 3/2 is 1.5, but quotient(3, 2) is 1, which is the integer
part.
-}
quotient :: HasCallStack => (Number, Number) -> Number
quotient (_, 0) = withFrozenCallStack (P.error "Cannot divide by zero.")
quotient (a, b) = truncation (a / b)
{-| Gives the remainder when dividing two numbers.
For example, remainder(3,2) is 1, which is the remainder when dividing
3 by 2.
-}
remainder :: HasCallStack => (Number, Number) -> Number
remainder (a, 0) = withFrozenCallStack (P.error "Cannot divide by zero.")
remainder (a, b) = a - b * quotient (a, b)
{-| The constant pi, which is equal to the ratio between the circumference
and diameter of a circle.
pi is approximately 3.14.
-}
pi :: Number
pi = fromDouble 3.141592653589793
{-| Gives the exponential of a number. This is equal to the constant e,
raised to the power of the number.
The exp function increases faster and faster very quickly. For example,
if t is the current time in seconds, exp(t) will reach a million in about
14 seconds. It will reach a billion in around 21 seconds.
-}
exp :: Number -> Number
exp = fromDouble . P.exp . toDouble
{-| Gives the square root of a number. This is the positive number that, when
multiplied by itself, gives the original number back.
The sqrt always increases, but slows down. For example, if t is the
current time, sqrt(t) will reach 5 in 25 seconds. But it will take 100
seconds to reach 10, and 225 seconds (almost 4 minutes) to reach 15.
-}
sqrt :: HasCallStack => Number -> Number
sqrt (Number x)
| x P.< 0 =
withFrozenCallStack (P.error "Negative numbers have no square root.")
| otherwise = fromDouble (P.sqrt x)
squareRoot :: HasCallStack => Number -> Number
squareRoot = sqrt
{-| Gives the natural log of a number. This is the opposite of the exp
function.
Like sqrt, the log function always increases, but slows down. However,
it slows down much sooner than the sqrt function. If t is the current time
in seconds, it takes more than 2 minutes for log(t) to reach 5, and more
than 6 hours to reach 10!
-}
log :: HasCallStack => Number -> Number
log (Number x)
| x P.<= 0 =
withFrozenCallStack (P.error "Only positive numbers have logarithms.")
| otherwise = fromDouble (P.log x)
{-| Gives the logarithm of the first number, using the base of the second
number.
-}
logBase :: HasCallStack => (Number, Number) -> Number
logBase (Number x, Number b)
| x P.<= 0 =
withFrozenCallStack (P.error "Only positive numbers have logarithms.")
| b P.<= 0 =
withFrozenCallStack
(P.error "The base of a logarithm must be a positive number.")
| b P.== 1 =
withFrozenCallStack (P.error "A logarithm cannot have a base of 1.")
| otherwise = fromDouble (P.logBase b x)
{-| Converts an angle from degrees to radians. -}
toRadians :: Number -> Number
toRadians d = d / 180 * pi
{-| Converts an angle from radians to degrees. -}
fromRadians :: Number -> Number
fromRadians r = r / pi * 180
{-| Gives the sine of an angle, where the angle is measured in degrees. -}
sin :: Number -> Number
sin = fromDouble . P.sin . toDouble . toRadians
{-| Gives the tangent of an angle, where the angle is measured in degrees.
This is the slope of a line at that angle from horizontal.
-}
tan :: Number -> Number
tan = fromDouble . P.tan . toDouble . toRadians
{-| Gives the cosine of an angle, where the angle is measured in degrees. -}
cos :: Number -> Number
cos = fromDouble . P.cos . toDouble . toRadians
{-| Gives the inverse sine of a value, in degrees.
This is the unique angle between -90 and 90 that has the input as its sine.
-}
asin :: HasCallStack => Number -> Number
asin (Number x)
| x P.< -1 P.|| x P.> 1 =
withFrozenCallStack
(P.error
"The asin function is only defined for numbers from -1 to 1.")
| otherwise = fromRadians (fromDouble (P.asin x))
{-| Gives the inverse cosine of a value, in degrees.
This is the unique angle between 0 and 180 that has the input as its cosine.
-}
acos :: HasCallStack => Number -> Number
acos (Number x)
| x P.< -1 P.|| x P.> 1 =
withFrozenCallStack
(P.error
"The acos function is only defined for numbers from -1 to 1.")
| otherwise = fromRadians (fromDouble (P.acos x))
{-| Gives the inverse tangent of a value, in degrees.
This is the unique angle between -90 and 90 that has the input as its tangent.
-}
atan :: Number -> Number
atan = fromRadians . fromDouble . P.atan . toDouble
{-| Separates a number into its whole and fractional parts.
For example, properFraction(1.2) is (1, 0.2).
-}
properFraction :: Number -> (Number, Number)
properFraction (Number x) = (fromInteger w, fromDouble p)
where
(w, p) = P.properFraction x
{-| Tells if a number is even. -}
even :: Number -> Truth
even n
| isInteger n = P.even (toInt n)
| otherwise = False
{-| Tells if a number is odd. -}
odd :: Number -> Truth
odd n
| isInteger n = P.odd (toInt n)
| otherwise = False
{-| Gives the greatest common divisor of two numbers.
This is the largest number that divides each of the two parameters.
Both parameters must be integers.
-}
gcd :: HasCallStack => (Number, Number) -> Number
gcd (a, b) = withFrozenCallStack (fromInt (P.gcd (toInt a) (toInt b)))
{-| Gives the least common multiple of two numbers.
This is the smallest number that is divisible by both of the two
parameters. Both parameters must be integers.
-}
lcm :: HasCallStack => (Number, Number) -> Number
lcm (a, b) = withFrozenCallStack (fromInt (P.lcm (toInt a) (toInt b)))
{-| Gives the sum of a list of numbers. -}
sum :: [Number] -> Number
sum = fromDouble . P.sum . P.map toDouble
{-| Gives the product of a list of numbers. -}
product :: [Number] -> Number
product = fromDouble . P.product . P.map toDouble
{-| Gives the largest number from a list. -}
maximum :: [Number] -> Number
maximum = fromDouble . P.maximum . P.map toDouble
{-| Gives the smallest number from a list. -}
minimum :: [Number] -> Number
minimum = fromDouble . P.minimum . P.map toDouble
|
alphalambda/codeworld
|
codeworld-base/src/Internal/Num.hs
|
apache-2.0
| 13,772 | 2 | 13 | 3,182 | 3,089 | 1,641 | 1,448 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
module Database.DSH.SL.Opt.Rewrite.PruneEmpty(pruneEmpty) where
-- import Control.Monad
import Database.DSH.Common.Opt
import Database.DSH.Common.VectorLang
import Database.DSH.SL.Opt.Properties.Types
import Database.DSH.SL.Opt.Rewrite.Common
-- import Database.Algebra.Dag.Common
-- import Database.DSH.SL.Lang
pruneEmpty :: SLRewrite TExpr TExpr Bool
pruneEmpty = applyToAll inferBottomUp emptyRules
emptyRules :: SLRuleSet TExpr TExpr BottomUpProps
emptyRules = [ -- emptyAppendLeftR1
-- , emptyAppendLeftR2
-- , emptyAppendLeftR3
-- , emptyAppendRightR1
-- , emptyAppendRightR2
-- , emptyAppendRightR3
]
-- FIXME pruning data vectors (R1) alone is not sufficient when
-- dealing with natural keys. We need to treat R2 and R3 outputs as
-- well, because otherwise inner vectors will be re-keyed and no
-- longer be aligned with the outer vector.
-- isEmpty :: AlgNode -> SLMatch BottomUpProps Bool
-- isEmpty q = do
-- ps <- liftM emptyProp $ properties q
-- case ps of
-- VProp b -> return b
-- x -> error $ "PruneEmpty.isEmpty: non-vector input " ++ show x
-- {- If the left input is empty and the other is not, the resulting value vector
-- is simply the right input. -}
-- emptyAppendLeftR1 :: SLRule BottomUpProps
-- emptyAppendLeftR1 q =
-- $(dagPatMatch 'q "R1 ((q1) [Append | AppendS] (q2))"
-- [| do
-- predicate =<< ((&&) <$> (isEmpty $(v "q1")) <*> (not <$> isEmpty $(v "q2")))
-- return $ do
-- logRewrite "Empty.Append.Left.R1" q
-- replace q $(v "q2") |])
-- FIXME re-add rules when
{-
-- If the left input is empty, renaming will make the inner vector
-- empty as well.
emptyAppendLeftR2 :: SLRule BottomUpProps
emptyAppendLeftR2 q =
$(dagPatMatch 'q "(R2 ((q1) Append (q2))) PropRename (qv)"
[| do
predicate =<< ((&&) <$> (isEmpty $(v "q1")) <*> (not <$> isEmpty $(v "q2")))
VProp (ValueVector w) <- vectorTypeProp <$> properties $(v "qv")
return $ do
logRewrite "Empty.Append.Left.R2" q
void $ replaceWithNew q (NullaryOp $ Empty w) |])
-- If the left input is empty, the rename vector for the right inner
-- vectors is simply identity
emptyAppendLeftR3 :: SLRule BottomUpProps
emptyAppendLeftR3 q =
$(dagPatMatch 'q "(R3 ((q1) Append (q2))) PropRename (qv)"
[| do
predicate =<< ((&&) <$> (isEmpty $(v "q1")) <*> (not <$> isEmpty $(v "q2")))
return $ do
logRewrite "Empty.Append.Left.R3" q
replace q $(v "qv") |])
-}
-- emptyAppendRightR1 :: SLRule BottomUpProps
-- emptyAppendRightR1 q =
-- $(dagPatMatch 'q "R1 ((q1) [Append | AppendS] (q2))"
-- [| do
-- predicate =<< ((&&) <$> (isEmpty $(v "q2")) <*> (not <$> isEmpty $(v "q1")))
-- return $ do
-- logRewrite "Empty.Append.Right.R1" q
-- replace q $(v "q1") |])
{-
-- If the right input is empty, renaming will make the inner vector
-- empty as well.
emptyAppendRightR3 :: SLRule BottomUpProps
emptyAppendRightR3 q =
$(dagPatMatch 'q "(R3 ((q1) Append (q2))) PropRename (qv)"
[| do
predicate =<< ((&&) <$> (not <$> isEmpty $(v "q1")) <*> (isEmpty $(v "q2")))
VProp (ValueVector w) <- vectorTypeProp <$> properties $(v "qv")
return $ do
logRewrite "Empty.Append.Right.R3" q
void $ replaceWithNew q $ NullaryOp $ Empty w |])
-- If the right input is empty, the rename vector for the left inner
-- vectors is simply identity
emptyAppendRightR2 :: SLRule BottomUpProps
emptyAppendRightR2 q =
$(dagPatMatch 'q "(R2 ((q1) Append (q2))) PropRename (qv)"
[| do
predicate =<< ((&&) <$> (isEmpty $(v "q2")) <*> (not <$> isEmpty $(v "q1")))
return $ do
logRewrite "Empty.Append.Right.R2" q
void $ replace q $(v "qv") |])
-}
|
ulricha/dsh
|
src/Database/DSH/SL/Opt/Rewrite/PruneEmpty.hs
|
bsd-3-clause
| 3,973 | 0 | 5 | 998 | 129 | 97 | 32 | 10 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
-- Search for UndecidableInstances to see why this is needed
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.RWS.Class
-- Copyright : (c) Andy Gill 2001,
-- (c) Oregon Graduate Institute of Science and Technology, 2001
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (multi-param classes, functional dependencies)
--
-- Declaration of the MonadRWS class.
--
-- Inspired by the paper
-- /Functional Programming with Overloading and Higher-Order Polymorphism/,
-- Mark P Jones (<http://web.cecs.pdx.edu/~mpj/>)
-- Advanced School of Functional Programming, 1995.
-----------------------------------------------------------------------------
module Control.Monad.RWS.Class (
MonadRWS,
module Control.Monad.Reader.Class,
module Control.Monad.State.Class,
module Control.Monad.Writer.Class,
) where
import Control.Monad.Reader.Class
import Control.Monad.State.Class
import Control.Monad.Writer.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except(ExceptT)
import Control.Monad.Trans.Maybe(MaybeT)
import Control.Monad.Trans.Identity(IdentityT)
#if MIN_VERSION_transformers(0,5,6)
import qualified Control.Monad.Trans.RWS.CPS as CPS (RWST)
#endif
import qualified Control.Monad.Trans.RWS.Lazy as Lazy (RWST)
import qualified Control.Monad.Trans.RWS.Strict as Strict (RWST)
import Data.Monoid
class (Monoid w, MonadReader r m, MonadWriter w m, MonadState s m)
=> MonadRWS r w s m | m -> r, m -> w, m -> s
#if MIN_VERSION_transformers(0,5,6)
-- | @since 2.3
instance (Monoid w, Monad m) => MonadRWS r w s (CPS.RWST r w s m)
#endif
instance (Monoid w, Monad m) => MonadRWS r w s (Lazy.RWST r w s m)
instance (Monoid w, Monad m) => MonadRWS r w s (Strict.RWST r w s m)
---------------------------------------------------------------------------
-- Instances for other mtl transformers
--
-- All of these instances need UndecidableInstances,
-- because they do not satisfy the coverage condition.
-- | @since 2.2
instance MonadRWS r w s m => MonadRWS r w s (ExceptT e m)
instance MonadRWS r w s m => MonadRWS r w s (IdentityT m)
instance MonadRWS r w s m => MonadRWS r w s (MaybeT m)
|
ekmett/mtl
|
Control/Monad/RWS/Class.hs
|
bsd-3-clause
| 2,517 | 0 | 8 | 403 | 476 | 290 | 186 | -1 | -1 |
module Code.Huffman.Test
( isoptimalprefix
)
where
-- $Id$
import Code.Type
import Code.Huffman.LR
import Code.Huffman.Make
import Code.Measure
import Autolib.Util.Sort
import Autolib.FiniteMap
import Autolib.Reporter
import Autolib.ToDoc
isoptimalprefix :: ( ToDoc b, ToDoc a, Ord a, Eq b )
=> Frequency a
-> Code a b
-> Reporter ()
isoptimalprefix freq code = do
inform $ vcat
[ text "Ist"
, nest 4 $ toDoc code
, text "ein optimaler Präfix-Code für"
, nest 4 $ toDoc freq
, text "?"
]
let mcode = measure freq code
inform $ text "Der Code hat das Gesamtgewicht" <+> toDoc mcode
let huff = make freq
mhuff = measure freq huff
when ( mcode > mhuff ) $ reject
$ text "Das ist zu groß."
inform $ text "Das ist optimal."
|
Erdwolf/autotool-bonn
|
src/Code/Huffman/Test.hs
|
gpl-2.0
| 808 | 3 | 14 | 212 | 260 | 131 | 129 | 28 | 1 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Unicode
-- Copyright : (c) The University of Glasgow, 2003
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC extensions)
--
-- Implementations for the character predicates (isLower, isUpper, etc.)
-- and the conversions (toUpper, toLower). The implementation uses
-- libunicode on Unix systems if that is available.
--
-----------------------------------------------------------------------------
module GHC.Unicode (
isAscii, isLatin1, isControl,
isAsciiUpper, isAsciiLower,
isPrint, isSpace, isUpper,
isLower, isAlpha, isDigit,
isOctDigit, isHexDigit, isAlphaNum,
toUpper, toLower, toTitle,
wgencat
) where
import GHC.Base
import GHC.Char (chr)
import GHC.Real
import GHC.Num
-- | Selects the first 128 characters of the Unicode character set,
-- corresponding to the ASCII character set.
isAscii :: Char -> Bool
isAscii c = c < '\x80'
-- | Selects the first 256 characters of the Unicode character set,
-- corresponding to the ISO 8859-1 (Latin-1) character set.
isLatin1 :: Char -> Bool
isLatin1 c = c <= '\xff'
-- | Selects ASCII lower-case letters,
-- i.e. characters satisfying both 'isAscii' and 'isLower'.
isAsciiLower :: Char -> Bool
isAsciiLower c = c >= 'a' && c <= 'z'
-- | Selects ASCII upper-case letters,
-- i.e. characters satisfying both 'isAscii' and 'isUpper'.
isAsciiUpper :: Char -> Bool
isAsciiUpper c = c >= 'A' && c <= 'Z'
-- | Selects control characters, which are the non-printing characters of
-- the Latin-1 subset of Unicode.
isControl :: Char -> Bool
-- | Selects printable Unicode characters
-- (letters, numbers, marks, punctuation, symbols and spaces).
isPrint :: Char -> Bool
-- | Returns 'True' for any Unicode space character, and the control
-- characters @\\t@, @\\n@, @\\r@, @\\f@, @\\v@.
isSpace :: Char -> Bool
-- isSpace includes non-breaking space
-- The magic 0x377 isn't really that magical. As of 2014, all the codepoints
-- at or below 0x377 have been assigned, so we shouldn't have to worry about
-- any new spaces appearing below there. It would probably be best to
-- use branchless ||, but currently the eqLit transformation will undo that,
-- so we'll do it like this until there's a way around that.
isSpace c
| uc <= 0x377 = uc == 32 || uc - 0x9 <= 4 || uc == 0xa0
| otherwise = iswspace (ord c)
where
uc = fromIntegral (ord c) :: Word
-- | Selects upper-case or title-case alphabetic Unicode characters (letters).
-- Title case is used by a small number of letter ligatures like the
-- single-character form of /Lj/.
isUpper :: Char -> Bool
-- | Selects lower-case alphabetic Unicode characters (letters).
isLower :: Char -> Bool
-- | Selects alphabetic Unicode characters (lower-case, upper-case and
-- title-case letters, plus letters of caseless scripts and modifiers letters).
-- This function is equivalent to 'Data.Char.isLetter'.
isAlpha :: Char -> Bool
-- | Selects alphabetic or numeric digit Unicode characters.
--
-- Note that numeric digits outside the ASCII range are selected by this
-- function but not by 'isDigit'. Such digits may be part of identifiers
-- but are not used by the printer and reader to represent numbers.
isAlphaNum :: Char -> Bool
-- | Selects ASCII digits, i.e. @\'0\'@..@\'9\'@.
isDigit :: Char -> Bool
isDigit c = (fromIntegral (ord c - ord '0') :: Word) <= 9
-- We use an addition and an unsigned comparison instead of two signed
-- comparisons because it's usually faster and puts less strain on branch
-- prediction. It likely also enables some CSE when combined with functions
-- that follow up with an actual conversion.
-- | Selects ASCII octal digits, i.e. @\'0\'@..@\'7\'@.
isOctDigit :: Char -> Bool
isOctDigit c = (fromIntegral (ord c - ord '0') :: Word) <= 7
-- | Selects ASCII hexadecimal digits,
-- i.e. @\'0\'@..@\'9\'@, @\'a\'@..@\'f\'@, @\'A\'@..@\'F\'@.
isHexDigit :: Char -> Bool
isHexDigit c = isDigit c ||
(fromIntegral (ord c - ord 'A')::Word) <= 5 ||
(fromIntegral (ord c - ord 'a')::Word) <= 5
-- | Convert a letter to the corresponding upper-case letter, if any.
-- Any other character is returned unchanged.
toUpper :: Char -> Char
-- | Convert a letter to the corresponding lower-case letter, if any.
-- Any other character is returned unchanged.
toLower :: Char -> Char
-- | Convert a letter to the corresponding title-case or upper-case
-- letter, if any. (Title case differs from upper case only for a small
-- number of ligature letters.)
-- Any other character is returned unchanged.
toTitle :: Char -> Char
-- -----------------------------------------------------------------------------
-- Implementation with the supplied auto-generated Unicode character properties
-- table
-- Regardless of the O/S and Library, use the functions contained in WCsubst.c
isAlpha c = iswalpha (ord c)
isAlphaNum c = iswalnum (ord c)
isControl c = iswcntrl (ord c)
isPrint c = iswprint (ord c)
isUpper c = iswupper (ord c)
isLower c = iswlower (ord c)
toLower c = chr (towlower (ord c))
toUpper c = chr (towupper (ord c))
toTitle c = chr (towtitle (ord c))
-- TODO: Most of the following should be verified to see if compatible with GHC
foreign import java unsafe "@static java.lang.Character.isLetter"
iswalpha :: Int -> Bool
-- TODO: Inconsistent with GHC
foreign import java unsafe "@static java.lang.Character.isLetterOrDigit"
iswalnum :: Int -> Bool
foreign import java unsafe "@static java.lang.Character.isISOControl"
iswcntrl :: Int -> Bool
-- TODO: Inconsistent with GHC
foreign import java unsafe "@static java.lang.Character.isSpaceChar"
iswspace :: Int -> Bool
foreign import java unsafe "@static eta.base.Utils.isPrintableChar"
iswprint :: Int -> Bool
foreign import java unsafe "@static java.lang.Character.isLowerCase"
iswlower :: Int -> Bool
-- TODO: Inconsistent with GHC
foreign import java unsafe "@static java.lang.Character.isUpperCase"
iswupper :: Int -> Bool
foreign import java unsafe "@static java.lang.Character.toLowerCase"
towlower :: Int -> Int
foreign import java unsafe "@static java.lang.Character.toUpperCase"
towupper :: Int -> Int
foreign import java unsafe "@static java.lang.Character.toTitleCase"
towtitle :: Int -> Int
foreign import java unsafe "@static java.lang.Character.getType"
wgencat :: Int -> Int
|
alexander-at-github/eta
|
libraries/base/GHC/Unicode.hs
|
bsd-3-clause
| 6,983 | 24 | 14 | 1,538 | 985 | 545 | 440 | -1 | -1 |
{-# LANGUAGE DataKinds, KindSignatures, RankNTypes, StandaloneDeriving, GADTs, TypeOperators, FlexibleInstances, ViewPatterns #-}
import GHC.TypeLits
import Data.IORef
import System.IO.Unsafe (unsafePerformIO)
import Unsafe.Coerce (unsafeCoerce)
import Data.Type.Equality
-- stratified simply-typed first-order lambda calculus
-- in finally-tagless (typed) HOAS form
class LC (a :: Nat -> *) where
(&) :: a l -> a l -> a l
star :: a (2+l)
int :: a (1+l)
inh :: String -> a (1+l) -> a l
zero :: a l
inc :: a l
lam :: (a l -> a l) -> a l
as :: a l -> a (1+l) -> a l
lift :: a l -> a (1+l)
infixr `inh`
one, two, three :: LC a => a 0
one = inc & zero
two = twice inc & zero
three = inc & two
twice f = lam (\a -> f & (f & a))
twice' :: LC a => a 0
twice' = lam (\f -> twice f)
-- interpret these into Nat
data N (l :: Nat) = Z | S (N l) | F (N l -> N l)
instance Show (N l) where
show (F _) = "<func>"
show Z = "Z"
show (S n) = 'S' : show n
instance LC N where
zero = Z
inc = F S
F f & Z = f Z
F f & a@(S _) = f a
lam = F
as a _ = a
newtype Str (l :: Nat) = Str String deriving Show
unStr (Str a) = a
instance LC Str where
zero = Str "Z"
inc = Str "S"
lam f = Str $ "\a->" ++ unStr (f (Str "a"))
Str f & Str a = Str $ "(" ++ f ++ " & " ++ a ++ ")"
as (Str a) (Str t) = Str $ "(" ++ a ++ " :: " ++ show t ++ ")"
inh name (Str parent) = Str $ name ++ " `inh` " ++ parent
int = Str "Int"
star = Str "*"
data Norm :: Nat -> * where
Zero :: Norm l
Inc :: Norm l
Lam :: (Norm l -> Norm l) -> Norm l
App :: Norm l -> Norm l -> Norm l
StarN :: Norm (2+l)
IntN :: Norm (1+l)
InhN :: String -> Norm (1+l) -> Norm l
-- Lift :: Norm l -> Norm (1+l) -- not needed, we use unsafeCoerce
deriving instance Show (Norm l)
instance Show (Norm l -> Norm l) where
show _ = "<fn>"
instance LC Norm where
zero = Zero
inc = Inc
lam = Lam
Lam f & a = f a
l & a = l `App` a
v `as` _ = v
star = StarN
int = IntN
inh = InhN
lift = unsafeCoerce
--norm :: LC a => a l -> Norm l
--norm = id
unNorm :: LC a => Norm l -> a l
unNorm Zero = zero
unNorm Inc = inc
--unNorm (Lam f) = lam (\a -> unNorm $ f (norm a))
unNorm (f `App` a) = unNorm f & unNorm a
unNorm StarN = star
unNorm IntN = int
unNorm (name `InhN` ty) = name `inh` unNorm ty
-- interpret these into a primitive type universe
-- m >= n lev
data Univ :: Nat -> Nat -> Nat -> * where
Int :: Univ m m l
Arr :: Univ m n l -> Univ n o l -> Univ m o l
IntTy :: Univ m m (1+l)
Ty :: String -> Univ 0 0 (1+l) -> Univ m m l
Inh :: String -> Univ 0 0 (1+l) -> Univ m m l
Star :: Univ m m (2+l)
Unkn :: Ref l -> Univ m m l
deriving instance Show (Univ m n l)
instance Eq (Univ 0 0 l) where
Int == Int = True
Star == Star = True
IntTy == IntTy = True
l `Arr` r == l' `Arr` r' = coerce00 l == coerce00 l' && coerce00 r == coerce00 r'
where coerce00 :: Univ m n l -> Univ 0 0 l
coerce00 = unsafeCoerce
data Ref l = Ref (IORef (Maybe (Univ 0 0 l)))
instance Show (Ref l) where
show (Ref r) = "|" ++ show current ++ "|"
where current = unsafePerformIO $ readIORef r
instance Eq (Ref l) where
a == b = error "cannot compare Refs"
instance LC (Univ 0 0) where
--int = Int
zero = Int
inc = Int `Arr` Int
(Int `Arr` c) & Int = c
(Int `Arr` c) & Unkn r | f <- r `unifies` Int = f c
(Unkn r `Arr` c) & a | f <- r `unifies` a = f c
f & a = error $ '(' : show f ++ ") & (" ++ show a ++ ")"
lam f = let u = Unkn (Ref (unsafePerformIO $ newIORef Nothing)) in f u `seq` (u `Arr` f u)
as Int IntTy = Int
as IntTy Star = IntTy
as (Unkn r) IntTy | f <- r `unifies` Int = f (Unkn r)
--as (Unkn r) t@(name `Inh` _) | f <- r `unifies` t = f (Unkn r)
int = IntTy
inh = Inh
star = Star
unifies (Ref r) (Unkn _) = error "UNIMPL!"
unifies (Ref r) a = case current of
Just a' | a' == a -> id
Nothing -> unsafePerformIO $ (writeIORef r (Just a) >> return id)
Just other -> error $ "cannot unify: " ++ show a ++ " and " ++ show other
where current = unsafePerformIO $ readIORef r
-- possibly `fix` can help us avoiding two-hole contexts when unifying
class Defines a where
(.:=) :: a -> a -> a -- unify arguments
ar :: a -> a -> a -- form an arrow type
intt :: a -- the integer type
split :: (a -> a -> a) -> (a -> a) -- check/infer variant of `ar`
class Defines a => Startable a where
start :: (forall a . Defines a => a -> a) -> a -> a
data Uni where
Whatnot :: (forall a . Defines a => a -> a) -> x -> Uni
Intt :: Uni
Ar :: Uni -> Uni -> Uni
instance Show Uni where
show (Whatnot _ _) = "Whatnot"
show Intt = "Intt"
show (a `Ar` b) = "(" ++ show a ++ " `Ar` " ++ show b ++ ")"
instance Defines Uni where
Whatnot f _ .:= Whatnot g _ = fix' (g . f)
-- Whatnot f a .:= r@(Whatnot _ _) = r .:= fix' f
a .:= Whatnot _ _ = a
Whatnot _ _ .:= b = b
Intt .:= Intt = Intt
(a `Ar` b) .:= (a' `Ar` b') = (a .:= a') `Ar` (b .:= b')
a .:= b = error $ "cannot unify " ++ show (a,b)
ar = Ar
intt = Intt
split f e = e .:= f (Whatnot id e) (Whatnot id e)
--split f e = e .:= f (Whatnot (const $ error "tricky domain") e) (Whatnot (const $ error "tricky codomain") e)
instance Startable Uni where
start = Whatnot
infixr 5 `ar`
infixr 4 .:=
fix' :: Startable a => (forall a . Defines a => a -> a) -> a
fix' f = let x = f (start f x) in x
-- Relevant:
-- http://www.cse.chalmers.se/~emax/documents/axelsson2013using.pdf
--
instance Defines Int where
a .:= b = a `max` b
dom `ar` cod = error "heh"
instance Startable Int where
start f _ = 0
test, test2, test3, test4 :: Defines a => a -> a
test ex = ex .:= intt `ar` intt
test2 ex = (ex .:= intt `ar` intt) .:= intt
test3 ex = ex .:= ex
test4 = split (\ dom cod -> dom .:= cod `ar` cod)
{-
-- can we marry Defines and LC?
-- check ---+ +--- infer
-- v v
newtype D a (l :: Nat) = D (a -> a)
dc a = D $ \x -> x .:= a
unD (D x) = x
fix'' :: Startable a => D a l -> a
fix'' (D f) = fix' f
instance Defines a => LC (D a) where
zero = dc intt
inc = dc $ intt `ar` intt
--D f & D a =
-- lam f = D $ \a -> let i = intt in a .:= i `ar` (unD (f (dc i)) undefined) -- TODO
-- lam f = D $ split (\arg -> ) (id)
-}
-- Places in a lambda graph
-- how can this be injected into our HOAS?
data Place = Root | Lft Place | Rght Place | Def Place
class HOAS exp where
app :: KnownPlace p => exp (Lft p) -> exp (Rght p) -> exp p
lum :: KnownPlace p => (exp (Def p) -> exp (Def p)) -> exp p
use :: KnownPlace p => exp (Def p) -> exp use
tt1, tt2, tt3 :: (HOAS exp, KnownPlace p) => exp p
tt1 = lum (\a -> use a `app` use a) `app` lum id
tt2 = lum (\a -> lum id `app` use a) `app` lum id
tt3 = lum (\_ -> lum id)
class KnownPlace (p :: Place) where
place :: Pl p
data Pl :: Place -> * where
Root' :: Pl Root
Def' :: KnownPlace p => Pl (Def p)
Lft' :: KnownPlace p => Pl (Lft p)
Rght' :: KnownPlace p => Pl (Rght p)
instance KnownPlace Root where place = Root'
instance KnownPlace p => KnownPlace (Def p) where place = Def'
instance KnownPlace p => KnownPlace (Lft p) where place = Lft'
instance KnownPlace p => KnownPlace (Rght p) where place = Rght'
samePlace :: (KnownPlace p, KnownPlace p') => prox p -> prox' p' -> Maybe (p :~: p')
l `samePlace` r = placeOf l `samePlace'` placeOf r
where placeOf :: KnownPlace p => prox p -> Pl p
placeOf _ = place
samePlace' :: Pl p -> Pl p' -> Maybe (p :~: p')
Root' `samePlace'` Root' = return Refl
l@Def' `samePlace'` r@Def' = do Refl <- l `samePlace` r; return Refl
l@Lft' `samePlace'` r@Lft' = do Refl <- l `samePlace` r; return Refl
l@Rght' `samePlace'` r@Rght' = do Refl <- l `samePlace` r; return Refl
_ `samePlace'` _ = Nothing
class Defines' a where
(.~.) :: a -> a -> a -- unify arguments
aar :: a -> a -> a -- form an arrow type
iintt :: a -- the integer type
class Defines' a => Startable' a where
startt :: (forall a . Defines' a => a -> a) -> a -> a
data Uni' pla where
Whatnot' :: KnownPlace pl => (forall a . Defines' a => a -> a) -> x -> Uni' pl
IIntt :: Uni' pl
AAr :: Uni' pl' -> Uni' pl'' -> Uni' pl
instance Show (Uni' pl) where
show (Whatnot' _ _) = "Whatnot"
show IIntt = "IIntt"
show (a `AAr` b) = "(" ++ show a ++ " `AAr` " ++ show b ++ ")"
data SomePlace where
Some :: Uni' pl -> SomePlace
deriving instance Show SomePlace
instance Defines' SomePlace where
Some l@(Whatnot' f _) .~. Some r@(Whatnot' g _) | Just Refl <- l `samePlace` r = Some l
Some (Whatnot' f _) .~. Some (Whatnot' g _) = fixX' (g . f) -- FIXME: make the places congruent, but how? UNION?
a .~. Some (Whatnot' _ _) = a
Some (Whatnot' _ _) .~. b = b
l@(Some IIntt) .~. Some IIntt = l
--(a `Ar` b) .:= (a' `Ar` b') = (a .:= a') `Ar` (b .:= b')
a .~. b = error $ "cannot unify " ++ show (a,b)
--aar = AAr
iintt = Some IIntt
instance Startable' SomePlace where
startt f a = Some (Whatnot' f a :: Uni' Root)
fixX' :: Startable' a => (forall a . Defines' a => a -> a) -> a
fixX' f = let x = f (startt f x) in x
-- Zippers?
--data Zipper all part (l :: Nat) = Zipper part (part -> all)
data Zipper all (l :: Nat) = Zipper0 all | Zipper1 all (all -> all) | Zipper2 all (all -> all) all (all -> all)
allTogether (Zipper0 a) = a
allTogether (Zipper1 a a') = a' a
allTogether (Zipper2 a a' b b') = a' a & b' b
instance LC all => LC (Zipper (all l)) where
-- Zipper1 f f' & Zipper1 a a' = Zipper2 (f' f) (& a' a) (a' a) (f' f &)
(allTogether -> f) & (allTogether -> a) = Zipper2 f (& a) a (f &)
-- Zipper f f' & Zipper a a' = Zipper (f' f) (& undefined)
zero = Zipper0 zero
inc = Zipper0 inc
|
cartazio/omega
|
mosaic/finally-infer.hs
|
bsd-3-clause
| 9,753 | 2 | 15 | 2,690 | 4,262 | 2,191 | 2,071 | -1 | -1 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, TypeFamilies, MultiParamTypeClasses, ViewPatterns #-}
module YesodCoreTest.Json
( specs
, Widget
, resourcesApp
) where
import Yesod.Core
import Test.Hspec
import qualified Data.Map as Map
import Network.Wai.Test
import Data.Text (Text)
import Data.ByteString.Lazy (ByteString)
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
/has-multiple-pieces/#Int/#Int MultiplePiecesR GET
|]
instance Yesod App
getHomeR :: Handler RepPlain
getHomeR = do
val <- requireJsonBody
case Map.lookup ("foo" :: Text) val of
Nothing -> invalidArgs ["foo not found"]
Just foo -> return $ RepPlain $ toContent (foo :: Text)
getMultiplePiecesR :: Int -> Int -> Handler ()
getMultiplePiecesR _ _ = return ()
test :: String
-> ByteString
-> (SResponse -> Session ())
-> Spec
test name rbody f = it name $ do
app <- toWaiApp App
flip runSession app $ do
sres <- srequest SRequest
{ simpleRequest = defaultRequest
, simpleRequestBody = rbody
}
f sres
specs :: Spec
specs = describe "Yesod.Json" $ do
test "parses valid content" "{\"foo\":\"bar\"}" $ \sres -> do
assertStatus 200 sres
assertBody "bar" sres
test "400 for bad JSON" "{\"foo\":\"bar\"" $ \sres -> do
assertStatus 400 sres
test "400 for bad structure" "{\"foo2\":\"bar\"}" $ \sres -> do
assertStatus 400 sres
assertBodyContains "foo not found" sres
|
s9gf4ult/yesod
|
yesod-core/test/YesodCoreTest/Json.hs
|
mit
| 1,527 | 0 | 14 | 376 | 408 | 206 | 202 | 43 | 2 |
{-# LANGUAGE NoOverloadedStrings, TypeSynonymInstances, GADTs, CPP #-}
{- | Description : Wrapper around GHC API, exposing a single `evaluate` interface that runs
a statement, declaration, import, or directive.
This module exports all functions used for evaluation of IHaskell input.
-}
module IHaskell.Eval.Evaluate (
interpret,
evaluate,
flushWidgetMessages,
Interpreter,
liftIO,
typeCleaner,
formatType,
capturedIO,
) where
import IHaskellPrelude
import qualified Data.Text as T
import qualified Data.Text.Lazy as LT
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Char8 as CBS
import Control.Concurrent (forkIO, threadDelay)
import Prelude (putChar, head, tail, last, init, (!!))
import Data.List (findIndex, and, foldl1, nubBy)
import Text.Printf
import Data.Char as Char
import Data.Dynamic
import Data.Typeable
import qualified Data.Serialize as Serialize
import System.Directory
#if !MIN_VERSION_base(4,8,0)
import System.Posix.IO (createPipe)
#endif
import System.Posix.IO (fdToHandle)
import System.IO (hGetChar, hFlush)
import System.Random (getStdGen, randomRs)
import Unsafe.Coerce
import Control.Monad (guard)
import System.Process
import System.Exit
import Data.Maybe (fromJust)
import qualified Control.Monad.IO.Class as MonadIO (MonadIO, liftIO)
import qualified MonadUtils (MonadIO, liftIO)
import System.Environment (getEnv)
import qualified Data.Map as Map
import NameSet
import Name
import PprTyThing
import InteractiveEval
import DynFlags
import Type
import Exception (gtry)
import HscTypes
import HscMain
import qualified Linker
import TcType
import Unify
import InstEnv
#if MIN_VERSION_ghc(7, 8, 0)
import GhcMonad (liftIO, withSession)
#else
import GhcMonad (withSession)
#endif
import GHC hiding (Stmt, TypeSig)
import Exception hiding (evaluate)
import Outputable hiding ((<>))
import Packages
import Module hiding (Module)
import qualified Pretty
import FastString
import Bag
import ErrUtils (errMsgShortDoc, errMsgExtraInfo)
import IHaskell.Types
import IHaskell.IPython
import IHaskell.Eval.Parser
import IHaskell.Eval.Lint
import IHaskell.Display
import qualified IHaskell.Eval.Hoogle as Hoogle
import IHaskell.Eval.Util
import IHaskell.Eval.Widgets
import IHaskell.BrokenPackages
import qualified IHaskell.IPython.Message.UUID as UUID
import StringUtils (replace, split, strip, rstrip)
import Paths_ihaskell (version)
import Data.Version (versionBranch)
data ErrorOccurred = Success
| Failure
deriving (Show, Eq)
-- | Set GHC's verbosity for debugging
ghcVerbosity :: Maybe Int
ghcVerbosity = Nothing -- Just 5
ignoreTypePrefixes :: [String]
ignoreTypePrefixes = [ "GHC.Types"
, "GHC.Base"
, "GHC.Show"
, "System.IO"
, "GHC.Float"
, ":Interactive"
, "GHC.Num"
, "GHC.IO"
, "GHC.Integer.Type"
]
typeCleaner :: String -> String
typeCleaner = useStringType . foldl' (.) id (map (`replace` "") fullPrefixes)
where
fullPrefixes = map (++ ".") ignoreTypePrefixes
useStringType = replace "[Char]" "String"
-- MonadIO constraint necessary for GHC 7.6
write :: (MonadIO m, GhcMonad m) => KernelState -> String -> m ()
write state x = when (kernelDebug state) $ liftIO $ hPutStrLn stderr $ "DEBUG: " ++ x
type Interpreter = Ghc
#if MIN_VERSION_ghc(7, 8, 0)
-- GHC 7.8 exports a MonadIO instance for Ghc
#else
instance MonadIO.MonadIO Interpreter where
liftIO = MonadUtils.liftIO
#endif
requiredGlobalImports :: [String]
requiredGlobalImports =
[ "import qualified Prelude as IHaskellPrelude"
, "import qualified System.Directory as IHaskellDirectory"
, "import qualified System.Posix.IO as IHaskellIO"
, "import qualified System.IO as IHaskellSysIO"
, "import qualified Language.Haskell.TH as IHaskellTH"
]
ihaskellGlobalImports :: [String]
ihaskellGlobalImports =
[ "import IHaskell.Display()"
, "import qualified IHaskell.Display"
, "import qualified IHaskell.IPython.Stdin"
, "import qualified IHaskell.Eval.Widgets"
]
-- | Run an interpreting action. This is effectively runGhc with initialization and importing. First
-- argument indicates whether `stdin` is handled specially, which cannot be done in a testing
-- environment. The argument passed to the action indicates whether Haskell support libraries are
-- available.
interpret :: String -> Bool -> (Bool -> Interpreter a) -> IO a
interpret libdir allowedStdin action = runGhc (Just libdir) $ do
-- If we're in a sandbox, add the relevant package database
sandboxPackages <- liftIO getSandboxPackageConf
initGhci sandboxPackages
case ghcVerbosity of
Just verb -> do
dflags <- getSessionDynFlags
void $ setSessionDynFlags $ dflags { verbosity = verb }
Nothing -> return ()
hasSupportLibraries <- initializeImports
-- Close stdin so it can't be used. Otherwise it'll block the kernel forever.
dir <- liftIO getIHaskellDir
let cmd = printf "IHaskell.IPython.Stdin.fixStdin \"%s\"" dir
when (allowedStdin && hasSupportLibraries) $ void $
runStmt cmd RunToCompletion
initializeItVariable
-- Run the rest of the interpreter
action hasSupportLibraries
#if MIN_VERSION_ghc(7,10,2)
packageIdString' dflags pkg_key = fromMaybe "(unknown)" (packageKeyPackageIdString dflags pkg_key)
#elif MIN_VERSION_ghc(7,10,0)
packageIdString' dflags = packageKeyPackageIdString dflags
#else
packageIdString' dflags = packageIdString
#endif
-- | Initialize our GHC session with imports and a value for 'it'. Return whether the IHaskell
-- support libraries are available.
initializeImports :: Interpreter Bool
initializeImports = do
-- Load packages that start with ihaskell-*, aren't just IHaskell, and depend directly on the right
-- version of the ihaskell library. Also verify that the packages we load are not broken.
dflags <- getSessionDynFlags
broken <- liftIO getBrokenPackages
(dflags, _) <- liftIO $ initPackages dflags
let Just db = pkgDatabase dflags
packageNames = map (packageIdString' dflags . packageConfigId) db
initStr = "ihaskell-"
-- Name of the ihaskell package, e.g. "ihaskell-1.2.3.4"
iHaskellPkgName = initStr ++ intercalate "." (map show (versionBranch version))
dependsOnRight pkg = not $ null $ do
pkg <- db
depId <- depends pkg
dep <- filter ((== depId) . installedPackageId) db
let idString = packageIdString' dflags (packageConfigId dep)
guard (iHaskellPkgName `isPrefixOf` idString)
displayPkgs = [pkgName | pkgName <- packageNames
, Just (x:_) <- [stripPrefix initStr pkgName]
, pkgName `notElem` broken
, isAlpha x]
hasIHaskellPackage = not $ null $ filter (== iHaskellPkgName) packageNames
-- Generate import statements all Display modules.
let capitalize :: String -> String
capitalize (first:rest) = Char.toUpper first : rest
importFmt = "import IHaskell.Display.%s"
dropFirstAndLast :: [a] -> [a]
dropFirstAndLast = reverse . drop 1 . reverse . drop 1
toImportStmt :: String -> String
toImportStmt = printf importFmt . concatMap capitalize . dropFirstAndLast . split "-"
displayImports = map toImportStmt displayPkgs
-- Import implicit prelude.
importDecl <- parseImportDecl "import Prelude"
let implicitPrelude = importDecl { ideclImplicit = True }
-- Import modules.
imports <- mapM parseImportDecl $ requiredGlobalImports ++ if hasIHaskellPackage
then ihaskellGlobalImports ++ displayImports
else []
setContext $ map IIDecl $ implicitPrelude : imports
-- Set -fcontext-stack to 100 (default in ghc-7.10). ghc-7.8 uses 20, which is too small.
let contextStackFlag = printf "-fcontext-stack=%d" (100 :: Int)
void $ setFlags [contextStackFlag]
return hasIHaskellPackage
-- | Give a value for the `it` variable.
initializeItVariable :: Interpreter ()
initializeItVariable =
-- This is required due to the way we handle `it` in the wrapper statements - if it doesn't exist,
-- the first statement will fail.
void $ runStmt "let it = ()" RunToCompletion
-- | Publisher for IHaskell outputs. The first argument indicates whether this output is final
-- (true) or intermediate (false).
type Publisher = (EvaluationResult -> IO ())
-- | Output of a command evaluation.
data EvalOut =
EvalOut
{ evalStatus :: ErrorOccurred
, evalResult :: Display
, evalState :: KernelState
, evalPager :: String
, evalMsgs :: [WidgetMsg]
}
cleanString :: String -> String
cleanString x = if allBrackets
then clean
else str
where
str = strip x
l = lines str
allBrackets = all (fAny [isPrefixOf ">", null]) l
fAny fs x = any ($x) fs
clean = unlines $ map removeBracket l
removeBracket ('>':xs) = xs
removeBracket [] = []
-- should never happen:
removeBracket other = error $ "Expected bracket as first char, but got string: " ++ other
-- | Evaluate some IPython input code.
evaluate :: KernelState -- ^ The kernel state.
-> String -- ^ Haskell code or other interpreter commands.
-> Publisher -- ^ Function used to publish data outputs.
-> (KernelState -> [WidgetMsg] -> IO KernelState) -- ^ Function to handle widget messages
-> Interpreter KernelState
evaluate kernelState code output widgetHandler = do
cmds <- parseString (cleanString code)
let execCount = getExecutionCounter kernelState
-- Extract all parse errors.
let justError x@ParseError{} = Just x
justError _ = Nothing
errs = mapMaybe (justError . unloc) cmds
updated <- case errs of
-- Only run things if there are no parse errors.
[] -> do
when (getLintStatus kernelState /= LintOff) $ liftIO $ do
lintSuggestions <- lint cmds
unless (noResults lintSuggestions) $
output $ FinalResult lintSuggestions [] []
runUntilFailure kernelState (map unloc cmds ++ [storeItCommand execCount])
-- Print all parse errors.
errs -> do
forM_ errs $ \err -> do
out <- evalCommand output err kernelState
liftIO $ output $ FinalResult (evalResult out) [] []
return kernelState
return updated { getExecutionCounter = execCount + 1 }
where
noResults (Display res) = null res
noResults (ManyDisplay res) = all noResults res
runUntilFailure :: KernelState -> [CodeBlock] -> Interpreter KernelState
runUntilFailure state [] = return state
runUntilFailure state (cmd:rest) = do
evalOut <- evalCommand output cmd state
-- Get displayed channel outputs. Merge them with normal display outputs.
dispsMay <- if supportLibrariesAvailable state
then extractValue "IHaskell.Display.displayFromChan" >>= liftIO
else return Nothing
let result =
case dispsMay of
Nothing -> evalResult evalOut
Just disps -> evalResult evalOut <> disps
helpStr = evalPager evalOut
-- Output things only if they are non-empty.
let empty = noResults result && null helpStr
unless empty $
liftIO $ output $ FinalResult result [plain helpStr] []
let tempMsgs = evalMsgs evalOut
tempState = evalState evalOut { evalMsgs = [] }
-- Handle the widget messages
newState <- if supportLibrariesAvailable state
then flushWidgetMessages tempState tempMsgs widgetHandler
else return tempState
case evalStatus evalOut of
Success -> runUntilFailure newState rest
Failure -> return newState
storeItCommand execCount = Statement $ printf "let it%d = it" execCount
-- | Compile a string and extract a value from it. Effectively extract the result of an expression
-- from inside the notebook environment.
extractValue :: Typeable a => String -> Interpreter a
extractValue expr = do
compiled <- dynCompileExpr expr
case fromDynamic compiled of
Nothing -> error "Error casting types in Evaluate.hs"
Just result -> return result
flushWidgetMessages :: KernelState
-> [WidgetMsg]
-> (KernelState -> [WidgetMsg] -> IO KernelState)
-> Interpreter KernelState
flushWidgetMessages state evalMsgs widgetHandler = do
-- Capture all widget messages queued during code execution
messagesIO <- extractValue "IHaskell.Eval.Widgets.relayWidgetMessages"
messages <- liftIO messagesIO
-- Handle all the widget messages
let commMessages = evalMsgs ++ messages
liftIO $ widgetHandler state commMessages
safely :: KernelState -> Interpreter EvalOut -> Interpreter EvalOut
safely state = ghandle handler . ghandle sourceErrorHandler
where
handler :: SomeException -> Interpreter EvalOut
handler exception =
return
EvalOut
{ evalStatus = Failure
, evalResult = displayError $ show exception
, evalState = state
, evalPager = ""
, evalMsgs = []
}
sourceErrorHandler :: SourceError -> Interpreter EvalOut
sourceErrorHandler srcerr = do
let msgs = bagToList $ srcErrorMessages srcerr
errStrs <- forM msgs $ \msg -> do
shortStr <- doc $ errMsgShortDoc msg
contextStr <- doc $ errMsgExtraInfo msg
return $ unlines [shortStr, contextStr]
let fullErr = unlines errStrs
return
EvalOut
{ evalStatus = Failure
, evalResult = displayError fullErr
, evalState = state
, evalPager = ""
, evalMsgs = []
}
wrapExecution :: KernelState
-> Interpreter Display
-> Interpreter EvalOut
wrapExecution state exec = safely state $
exec >>= \res ->
return
EvalOut
{ evalStatus = Success
, evalResult = res
, evalState = state
, evalPager = ""
, evalMsgs = []
}
-- | Return the display data for this command, as well as whether it resulted in an error.
evalCommand :: Publisher -> CodeBlock -> KernelState -> Interpreter EvalOut
evalCommand _ (Import importStr) state = wrapExecution state $ do
write state $ "Import: " ++ importStr
evalImport importStr
-- Warn about `it` variable.
return $ if "Test.Hspec" `isInfixOf` importStr
then displayError $ "Warning: Hspec is unusable in IHaskell until the resolution of GHC bug #8639." ++
"\nThe variable `it` is shadowed and cannot be accessed, even in qualified form."
else mempty
evalCommand _ (Module contents) state = wrapExecution state $ do
write state $ "Module:\n" ++ contents
-- Write the module contents to a temporary file in our work directory
namePieces <- getModuleName contents
let directory = "./" ++ intercalate "/" (init namePieces) ++ "/"
filename = last namePieces ++ ".hs"
liftIO $ do
createDirectoryIfMissing True directory
writeFile (directory ++ filename) contents
-- Clear old modules of this name
let modName = intercalate "." namePieces
removeTarget $ TargetModule $ mkModuleName modName
removeTarget $ TargetFile filename Nothing
-- Remember which modules we've loaded before.
importedModules <- getContext
let
-- Get the dot-delimited pieces of the module name.
moduleNameOf :: InteractiveImport -> [String]
moduleNameOf (IIDecl decl) = split "." . moduleNameString . unLoc . ideclName $ decl
moduleNameOf (IIModule imp) = split "." . moduleNameString $ imp
-- Return whether this module prevents the loading of the one we're trying to load. If a module B
-- exist, we cannot load A.B. All modules must have unique last names (where A.B has last name B).
-- However, we *can* just reload a module.
preventsLoading mod =
let pieces = moduleNameOf mod
in last namePieces == last pieces && namePieces /= pieces
-- If we've loaded anything with the same last name, we can't use this. Otherwise, GHC tries to load
-- the original *.hs fails and then fails.
case find preventsLoading importedModules of
-- If something prevents loading this module, return an error.
Just previous -> do
let prevLoaded = intercalate "." (moduleNameOf previous)
return $ displayError $
printf "Can't load module %s because already loaded %s" modName prevLoaded
-- Since nothing prevents loading the module, compile and load it.
Nothing -> doLoadModule modName modName
-- | Directives set via `:set`.
evalCommand output (Directive SetDynFlag flagsStr) state = safely state $ do
write state $ "All Flags: " ++ flagsStr
-- Find which flags are IHaskell flags, and which are GHC flags
let flags = words flagsStr
-- Get the kernel state updater for any IHaskell flag; Nothing for things that aren't IHaskell
-- flags.
ihaskellFlagUpdater :: String -> Maybe (KernelState -> KernelState)
ihaskellFlagUpdater flag = getUpdateKernelState <$> find (elem flag . getSetName) kernelOpts
(ihaskellFlags, ghcFlags) = partition (isJust . ihaskellFlagUpdater) flags
write state $ "IHaskell Flags: " ++ unwords ihaskellFlags
write state $ "GHC Flags: " ++ unwords ghcFlags
if null flags
then do
flags <- getSessionDynFlags
return
EvalOut
{ evalStatus = Success
, evalResult = Display
[ plain $ showSDoc flags $ vcat
[ pprDynFlags False flags
, pprLanguages False flags
]
]
, evalState = state
, evalPager = ""
, evalMsgs = []
}
else do
-- Apply all IHaskell flag updaters to the state to get the new state
let state' = foldl' (.) id (map (fromJust . ihaskellFlagUpdater) ihaskellFlags) state
errs <- setFlags ghcFlags
let display =
case errs of
[] -> mempty
_ -> displayError $ intercalate "\n" errs
-- For -XNoImplicitPrelude, remove the Prelude import. For -XImplicitPrelude, add it back in.
if "-XNoImplicitPrelude" `elem` flags
then evalImport "import qualified Prelude as Prelude"
else when ("-XImplicitPrelude" `elem` flags) $ do
importDecl <- parseImportDecl "import Prelude"
let implicitPrelude = importDecl { ideclImplicit = True }
imports <- getContext
setContext $ IIDecl implicitPrelude : imports
return
EvalOut
{ evalStatus = Success
, evalResult = display
, evalState = state'
, evalPager = ""
, evalMsgs = []
}
evalCommand output (Directive SetExtension opts) state = do
write state $ "Extension: " ++ opts
let set = concatMap (" -X" ++) $ words opts
evalCommand output (Directive SetDynFlag set) state
evalCommand output (Directive LoadModule mods) state = wrapExecution state $ do
write state $ "Load Module: " ++ mods
let stripped@(firstChar:remainder) = mods
(modules, removeModule) =
case firstChar of
'+' -> (words remainder, False)
'-' -> (words remainder, True)
_ -> (words stripped, False)
forM_ modules $ \modl -> if removeModule
then removeImport modl
else evalImport $ "import " ++ modl
return mempty
evalCommand a (Directive SetOption opts) state = do
write state $ "Option: " ++ opts
let (existing, nonExisting) = partition optionExists $ words opts
if not $ null nonExisting
then let err = "No such options: " ++ intercalate ", " nonExisting
in return
EvalOut
{ evalStatus = Failure
, evalResult = displayError err
, evalState = state
, evalPager = ""
, evalMsgs = []
}
else let options = mapMaybe findOption $ words opts
updater = foldl' (.) id $ map getUpdateKernelState options
in return
EvalOut
{ evalStatus = Success
, evalResult = mempty
, evalState = updater state
, evalPager = ""
, evalMsgs = []
}
where
optionExists = isJust . findOption
findOption opt =
find (elem opt . getOptionName) kernelOpts
evalCommand _ (Directive GetType expr) state = wrapExecution state $ do
write state $ "Type: " ++ expr
formatType <$> ((expr ++ " :: ") ++) <$> getType expr
evalCommand _ (Directive GetKind expr) state = wrapExecution state $ do
write state $ "Kind: " ++ expr
(_, kind) <- GHC.typeKind False expr
flags <- getSessionDynFlags
let typeStr = showSDocUnqual flags $ ppr kind
return $ formatType $ expr ++ " :: " ++ typeStr
evalCommand _ (Directive LoadFile names) state = wrapExecution state $ do
write state $ "Load: " ++ names
displays <- forM (words names) $ \name -> do
let filename = if ".hs" `isSuffixOf` name
then name
else name ++ ".hs"
contents <- liftIO $ readFile filename
modName <- intercalate "." <$> getModuleName contents
doLoadModule filename modName
return (ManyDisplay displays)
evalCommand publish (Directive ShellCmd ('!':cmd)) state = wrapExecution state $
case words cmd of
"cd":dirs -> do
-- Get home so we can replace '~` with it.
homeEither <- liftIO (try $ getEnv "HOME" :: IO (Either SomeException String))
let home =
case homeEither of
Left _ -> "~"
Right val -> val
let directory = replace "~" home $ unwords dirs
exists <- liftIO $ doesDirectoryExist directory
if exists
then do
-- Set the directory in IHaskell native code, for future shell commands. This doesn't set it for
-- user code, though.
liftIO $ setCurrentDirectory directory
-- Set the directory for user code.
let cmd = printf "IHaskellDirectory.setCurrentDirectory \"%s\"" $
replace " " "\\ " $
replace "\"" "\\\"" directory
runStmt cmd RunToCompletion
return mempty
else return $ displayError $ printf "No such directory: '%s'" directory
cmd -> liftIO $ do
(pipe, handle) <- createPipe'
let initProcSpec = shell $ unwords cmd
procSpec = initProcSpec
{ std_in = Inherit
, std_out = UseHandle handle
, std_err = UseHandle handle
}
(_, _, _, process) <- createProcess procSpec
-- Accumulate output from the process.
outputAccum <- liftIO $ newMVar ""
-- Start a loop to publish intermediate results.
let
-- Compute how long to wait between reading pieces of the output. `threadDelay` takes an
-- argument of microseconds.
ms = 1000
delay = 100 * ms
-- Maximum size of the output (after which we truncate).
maxSize = 100 * 1000
incSize = 200
output str = publish $ IntermediateResult $ Display [plain str]
loop = do
-- Wait and then check if the computation is done.
threadDelay delay
-- Read next chunk and append to accumulator.
nextChunk <- readChars pipe "\n" incSize
modifyMVar_ outputAccum (return . (++ nextChunk))
-- Check if we're done.
exitCode <- getProcessExitCode process
let computationDone = isJust exitCode
when computationDone $ do
nextChunk <- readChars pipe "" maxSize
modifyMVar_ outputAccum (return . (++ nextChunk))
if not computationDone
then do
-- Write to frontend and repeat.
readMVar outputAccum >>= output
loop
else do
out <- readMVar outputAccum
case fromJust exitCode of
ExitSuccess -> return $ Display [plain out]
ExitFailure code -> do
let errMsg = "Process exited with error code " ++ show code
htmlErr = printf "<span class='err-msg'>%s</span>" errMsg
return $ Display
[ plain $ out ++ "\n" ++ errMsg
, html $ printf "<span class='mono'>%s</span>" out ++ htmlErr
]
loop
where
#if MIN_VERSION_base(4,8,0)
createPipe' = createPipe
#else
createPipe' = do
(readEnd, writeEnd) <- createPipe
handle <- fdToHandle writeEnd
pipe <- fdToHandle readEnd
return (pipe, handle)
#endif
-- This is taken largely from GHCi's info section in InteractiveUI.
evalCommand _ (Directive GetHelp _) state = do
write state "Help via :help or :?."
return
EvalOut
{ evalStatus = Success
, evalResult = Display [out]
, evalState = state
, evalPager = ""
, evalMsgs = []
}
where
out = plain $ intercalate "\n"
[ "The following commands are available:"
, " :extension <Extension> - Enable a GHC extension."
, " :extension No<Extension> - Disable a GHC extension."
, " :type <expression> - Print expression type."
, " :info <name> - Print all info for a name."
, " :hoogle <query> - Search for a query on Hoogle."
, " :doc <ident> - Get documentation for an identifier via Hogole."
, " :set -XFlag -Wall - Set an option (like ghci)."
, " :option <opt> - Set an option."
, " :option no-<opt> - Unset an option."
, " :?, :help - Show this help text."
, ""
, "Any prefix of the commands will also suffice, e.g. use :ty for :type."
, ""
, "Options:"
, " lint – enable or disable linting."
, " svg – use svg output (cannot be resized)."
, " show-types – show types of all bound names"
, " show-errors – display Show instance missing errors normally."
, " pager – use the pager to display results of :info, :doc, :hoogle, etc."
]
-- This is taken largely from GHCi's info section in InteractiveUI.
evalCommand _ (Directive GetInfo str) state = safely state $ do
write state $ "Info: " ++ str
-- Get all the info for all the names we're given.
strings <- getDescription str
-- TODO: Make pager work without html by porting to newer architecture
let output = unlines (map htmlify strings)
htmlify str =
printf
"<div style='background: rgb(247, 247, 247);'><form><textarea id='code'>%s</textarea></form></div>"
str
++ script
script =
"<script>CodeMirror.fromTextArea(document.getElementById('code'), {mode: 'haskell', readOnly: 'nocursor'});</script>"
return
EvalOut
{ evalStatus = Success
, evalResult = mempty
, evalState = state
, evalPager = output
, evalMsgs = []
}
evalCommand _ (Directive SearchHoogle query) state = safely state $ do
results <- liftIO $ Hoogle.search query
return $ hoogleResults state results
evalCommand _ (Directive GetDoc query) state = safely state $ do
results <- liftIO $ Hoogle.document query
return $ hoogleResults state results
evalCommand output (Statement stmt) state = wrapExecution state $ evalStatementOrIO output state
(CapturedStmt stmt)
evalCommand output (Expression expr) state = do
write state $ "Expression:\n" ++ expr
-- Try to use `display` to convert our type into the output Dislay If typechecking fails and there
-- is no appropriate typeclass instance, this will throw an exception and thus `attempt` will return
-- False, and we just resort to plaintext.
let displayExpr = printf "(IHaskell.Display.display (%s))" expr :: String
canRunDisplay <- attempt $ exprType displayExpr
-- Check if this is a widget.
let widgetExpr = printf "(IHaskell.Display.Widget (%s))" expr :: String
isWidget <- attempt $ exprType widgetExpr
-- Check if this is a template haskell declaration
let declExpr = printf "((id :: IHaskellTH.DecsQ -> IHaskellTH.DecsQ) (%s))" expr :: String
let anyExpr = printf "((id :: IHaskellPrelude.Int -> IHaskellPrelude.Int) (%s))" expr :: String
isTHDeclaration <- liftM2 (&&) (attempt $ exprType declExpr) (not <$> attempt (exprType anyExpr))
write state $ "Can Display: " ++ show canRunDisplay
write state $ "Is Widget: " ++ show isWidget
write state $ "Is Declaration: " ++ show isTHDeclaration
if isTHDeclaration
then
-- If it typechecks as a DecsQ, we do not want to display the DecsQ, we just want the
-- declaration made.
do
write state "Suppressing display for template haskell declaration"
GHC.runDecls expr
return
EvalOut
{ evalStatus = Success
, evalResult = mempty
, evalState = state
, evalPager = ""
, evalMsgs = []
}
else if canRunDisplay
then
-- Use the display. As a result, `it` is set to the output.
useDisplay displayExpr
else do
-- Evaluate this expression as though it's just a statement. The output is bound to 'it', so we can
-- then use it.
evalOut <- evalCommand output (Statement expr) state
let out = evalResult evalOut
showErr = isShowError out
-- If evaluation failed, return the failure. If it was successful, we may be able to use the
-- IHaskellDisplay typeclass.
return $ if not showErr || useShowErrors state
then evalOut
else postprocessShowError evalOut
where
-- Try to evaluate an action. Return True if it succeeds and False if it throws an exception. The
-- result of the action is discarded.
attempt :: Interpreter a -> Interpreter Bool
attempt action = gcatch (action >> return True) failure
where
failure :: SomeException -> Interpreter Bool
failure _ = return False
-- Check if the error is due to trying to print something that doesn't implement the Show typeclass.
isShowError (ManyDisplay _) = False
isShowError (Display errs) =
-- Note that we rely on this error message being 'type cleaned', so that `Show` is not displayed as
-- GHC.Show.Show. This is also very fragile!
"No instance for (Show" `isPrefixOf` msg &&
isInfixOf "print it" msg
where
msg = extractPlain errs
isSvg (DisplayData mime _) = mime == MimeSvg
removeSvg :: Display -> Display
removeSvg (Display disps) = Display $ filter (not . isSvg) disps
removeSvg (ManyDisplay disps) = ManyDisplay $ map removeSvg disps
useDisplay displayExpr = do
-- If there are instance matches, convert the object into a Display. We also serialize it into a
-- bytestring. We get the bytestring IO action as a dynamic and then convert back to a bytestring,
-- which we promptly unserialize. Note that attempting to do this without the serialization to
-- binary and back gives very strange errors - all the types match but it refuses to decode back
-- into a Display. Suppress output, so as not to mess up console. First, evaluate the expression in
-- such a way that we have access to `it`.
io <- isIO expr
let stmtTemplate = if io
then "it <- (%s)"
else "let { it = %s }"
evalOut <- evalCommand output (Statement $ printf stmtTemplate expr) state
case evalStatus evalOut of
Failure -> return evalOut
Success -> wrapExecution state $ do
-- Compile the display data into a bytestring.
let compileExpr = "fmap IHaskell.Display.serializeDisplay (IHaskell.Display.display it)"
displayedBytestring <- dynCompileExpr compileExpr
-- Convert from the bytestring into a display.
case fromDynamic displayedBytestring of
Nothing -> error "Expecting lazy Bytestring"
Just bytestringIO -> do
bytestring <- liftIO bytestringIO
case Serialize.decode bytestring of
Left err -> error err
Right display ->
return $
if useSvg state
then display :: Display
else removeSvg display
isIO expr = attempt $ exprType $ printf "((\\x -> x) :: IO a -> IO a) (%s)" expr
postprocessShowError :: EvalOut -> EvalOut
postprocessShowError evalOut = evalOut { evalResult = Display $ map postprocess disps }
where
Display disps = evalResult evalOut
text = extractPlain disps
postprocess (DisplayData MimeHtml _) = html $ printf
fmt
unshowableType
(formatErrorWithClass "err-msg collapse"
text)
script
where
fmt = "<div class='collapse-group'><span class='btn btn-default' href='#' id='unshowable'>Unshowable:<span class='show-type'>%s</span></span>%s</div><script>%s</script>"
script = unlines
[ "$('#unshowable').on('click', function(e) {"
, " e.preventDefault();"
, " var $this = $(this);"
, " var $collapse = $this.closest('.collapse-group').find('.err-msg');"
, " $collapse.collapse('toggle');"
, "});"
]
postprocess other = other
unshowableType = fromMaybe "" $ do
let pieces = words text
before = takeWhile (/= "arising") pieces
after = init $ unwords $ tail $ dropWhile (/= "(Show") before
firstChar <- headMay after
return $ if firstChar == '('
then init $ tail after
else after
evalCommand _ (Declaration decl) state = wrapExecution state $ do
write state $ "Declaration:\n" ++ decl
boundNames <- evalDeclarations decl
let nonDataNames = filter (not . isUpper . head) boundNames
-- Display the types of all bound names if the option is on. This is similar to GHCi :set +t.
if not $ useShowTypes state
then return mempty
else do
-- Get all the type strings.
dflags <- getSessionDynFlags
types <- forM nonDataNames $ \name -> do
theType <- showSDocUnqual dflags . ppr <$> exprType name
return $ name ++ " :: " ++ theType
return $ Display [html $ unlines $ map formatGetType types]
evalCommand _ (TypeSignature sig) state = wrapExecution state $
-- We purposefully treat this as a "success" because that way execution continues. Empty type
-- signatures are likely due to a parse error later on, and we want that to be displayed.
return $ displayError $ "The type signature " ++ sig ++ "\nlacks an accompanying binding."
evalCommand _ (ParseError loc err) state = do
write state "Parse Error."
return
EvalOut
{ evalStatus = Failure
, evalResult = displayError $ formatParseError loc err
, evalState = state
, evalPager = ""
, evalMsgs = []
}
evalCommand _ (Pragma (PragmaUnsupported pragmaType) pragmas) state = wrapExecution state $
return $ displayError $ "Pragmas of type " ++ pragmaType ++ "\nare not supported."
evalCommand output (Pragma PragmaLanguage pragmas) state = do
write state $ "Got LANGUAGE pragma " ++ show pragmas
evalCommand output (Directive SetExtension $ unwords pragmas) state
hoogleResults :: KernelState -> [Hoogle.HoogleResult] -> EvalOut
hoogleResults state results =
EvalOut
{ evalStatus = Success
, evalResult = mempty
, evalState = state
, evalPager = output
, evalMsgs = []
}
where
-- TODO: Make pager work with plaintext
fmt = Hoogle.HTML
output = unlines $ map (Hoogle.render fmt) results
doLoadModule :: String -> String -> Ghc Display
doLoadModule name modName = do
-- Remember which modules we've loaded before.
importedModules <- getContext
flip gcatch (unload importedModules) $ do
-- Compile loaded modules.
flags <- getSessionDynFlags
errRef <- liftIO $ newIORef []
setSessionDynFlags
flags
{ hscTarget = objTarget flags
, log_action = \dflags sev srcspan ppr msg -> modifyIORef' errRef (showSDoc flags msg :)
}
-- Load the new target.
target <- guessTarget name Nothing
oldTargets <- getTargets
-- Add a target, but make sure targets are unique!
addTarget target
getTargets >>= return . nubBy ((==) `on` targetId) >>= setTargets
result <- load LoadAllTargets
-- Reset the context, since loading things screws it up.
initializeItVariable
-- Reset targets if we failed.
case result of
Failed -> setTargets oldTargets
Succeeded{} -> return ()
-- Add imports
setContext $
case result of
Failed -> importedModules
Succeeded -> IIDecl (simpleImportDecl $ mkModuleName modName) : importedModules
-- Switch back to interpreted mode.
setSessionDynFlags flags
case result of
Succeeded -> return mempty
Failed -> do
errorStrs <- unlines <$> reverse <$> liftIO (readIORef errRef)
return $ displayError $ "Failed to load module " ++ modName ++ "\n" ++ errorStrs
where
unload :: [InteractiveImport] -> SomeException -> Ghc Display
unload imported exception = do
print $ show exception
-- Explicitly clear targets
setTargets []
load LoadAllTargets
-- Switch to interpreted mode!
flags <- getSessionDynFlags
setSessionDynFlags flags { hscTarget = HscInterpreted }
-- Return to old context, make sure we have `it`.
setContext imported
initializeItVariable
return $ displayError $ "Failed to load module " ++ modName ++ ": " ++ show exception
#if MIN_VERSION_ghc(7,8,0)
objTarget flags = defaultObjectTarget $ targetPlatform flags
#else
objTarget flags = defaultObjectTarget
#endif
keepingItVariable :: Interpreter a -> Interpreter a
keepingItVariable act = do
-- Generate the it variable temp name
gen <- liftIO getStdGen
let rand = take 20 $ randomRs ('0', '9') gen
var name = name ++ rand
goStmt s = runStmt s RunToCompletion
itVariable = var "it_var_temp_"
goStmt $ printf "let %s = it" itVariable
val <- act
goStmt $ printf "let it = %s" itVariable
act
data Captured a = CapturedStmt String
| CapturedIO (IO a)
capturedEval :: (String -> IO ()) -- ^ Function used to publish intermediate output.
-> Captured a -- ^ Statement to evaluate.
-> Interpreter (String, RunResult) -- ^ Return the output and result.
capturedEval output stmt = do
-- Generate random variable names to use so that we cannot accidentally override the variables by
-- using the right names in the terminal.
gen <- liftIO getStdGen
let
-- Variable names generation.
rand = take 20 $ randomRs ('0', '9') gen
var name = name ++ rand
-- Variables for the pipe input and outputs.
readVariable = var "file_read_var_"
writeVariable = var "file_write_var_"
-- Variable where to store old stdout.
oldVariable = var "old_var_"
-- Variable used to store true `it` value.
itVariable = var "it_var_"
voidpf str = printf $ str ++ " IHaskellPrelude.>> IHaskellPrelude.return ()"
-- Statements run before the thing we're evaluating.
initStmts =
[ printf "let %s = it" itVariable
, printf "(%s, %s) <- IHaskellIO.createPipe" readVariable writeVariable
, printf "%s <- IHaskellIO.dup IHaskellIO.stdOutput" oldVariable
, voidpf "IHaskellIO.dupTo %s IHaskellIO.stdOutput" writeVariable
, voidpf "IHaskellSysIO.hSetBuffering IHaskellSysIO.stdout IHaskellSysIO.NoBuffering"
, printf "let it = %s" itVariable
]
-- Statements run after evaluation.
postStmts =
[ printf "let %s = it" itVariable
, voidpf "IHaskellSysIO.hFlush IHaskellSysIO.stdout"
, voidpf "IHaskellIO.dupTo %s IHaskellIO.stdOutput" oldVariable
, voidpf "IHaskellIO.closeFd %s" writeVariable
, printf "let it = %s" itVariable
]
pipeExpr = printf "let %s = %s" (var "pipe_var_") readVariable
goStmt :: String -> Ghc RunResult
goStmt s = runStmt s RunToCompletion
runWithResult (CapturedStmt str) = goStmt str
runWithResult (CapturedIO io) = do
status <- gcatch (liftIO io >> return NoException) (return . AnyException)
return $
case status of
NoException -> RunOk []
AnyException e -> RunException e
-- Initialize evaluation context.
void $ forM initStmts goStmt
-- Get the pipe to read printed output from. This is effectively the source code of dynCompileExpr
-- from GHC API's InteractiveEval. However, instead of using a `Dynamic` as an intermediary, it just
-- directly reads the value. This is incredibly unsafe! However, for some reason the `getContext`
-- and `setContext` required by dynCompileExpr (to import and clear Data.Dynamic) cause issues with
-- data declarations being updated (e.g. it drops newer versions of data declarations for older ones
-- for unknown reasons). First, compile down to an HValue.
Just (_, hValues, _) <- withSession $ liftIO . flip hscStmt pipeExpr
-- Then convert the HValue into an executable bit, and read the value.
pipe <- liftIO $ do
fd <- head <$> unsafeCoerce hValues
fdToHandle fd
-- Keep track of whether execution has completed.
completed <- liftIO $ newMVar False
finishedReading <- liftIO newEmptyMVar
outputAccum <- liftIO $ newMVar ""
-- Start a loop to publish intermediate results.
let
-- Compute how long to wait between reading pieces of the output. `threadDelay` takes an
-- argument of microseconds.
ms = 1000
delay = 100 * ms
-- How much to read each time.
chunkSize = 100
-- Maximum size of the output (after which we truncate).
maxSize = 100 * 1000
loop = do
-- Wait and then check if the computation is done.
threadDelay delay
computationDone <- readMVar completed
if not computationDone
then do
-- Read next chunk and append to accumulator.
nextChunk <- readChars pipe "\n" 100
modifyMVar_ outputAccum (return . (++ nextChunk))
-- Write to frontend and repeat.
readMVar outputAccum >>= output
loop
else do
-- Read remainder of output and accumulate it.
nextChunk <- readChars pipe "" maxSize
modifyMVar_ outputAccum (return . (++ nextChunk))
-- We're done reading.
putMVar finishedReading True
liftIO $ forkIO loop
result <- gfinally (runWithResult stmt) $ do
-- Execution is done.
liftIO $ modifyMVar_ completed (const $ return True)
-- Finalize evaluation context.
void $ forM postStmts goStmt
-- Once context is finalized, reading can finish. Wait for reading to finish to that the output
-- accumulator is completely filled.
liftIO $ takeMVar finishedReading
printedOutput <- liftIO $ readMVar outputAccum
return (printedOutput, result)
data AnyException = NoException
| AnyException SomeException
capturedIO :: Publisher -> KernelState -> IO a -> Interpreter Display
capturedIO publish state action = do
let showError = return . displayError . show
handler e@SomeException{} = showError e
gcatch (evalStatementOrIO publish state (CapturedIO action)) handler
-- | Evaluate a @Captured@, and then publish the final result to the frontend. Returns the final
-- Display.
evalStatementOrIO :: Publisher -> KernelState -> Captured a -> Interpreter Display
evalStatementOrIO publish state cmd = do
let output str = publish . IntermediateResult $ Display [plain str]
case cmd of
CapturedStmt stmt ->
write state $ "Statement:\n" ++ stmt
CapturedIO io ->
write state "Evaluating Action"
(printed, result) <- capturedEval output cmd
case result of
RunOk names -> do
dflags <- getSessionDynFlags
let allNames = map (showPpr dflags) names
isItName name =
name == "it" ||
name == "it" ++ show (getExecutionCounter state)
nonItNames = filter (not . isItName) allNames
output = [plain printed | not . null $ strip printed]
write state $ "Names: " ++ show allNames
-- Display the types of all bound names if the option is on. This is similar to GHCi :set +t.
if not $ useShowTypes state
then return $ Display output
else do
-- Get all the type strings.
types <- forM nonItNames $ \name -> do
theType <- showSDocUnqual dflags . ppr <$> exprType name
return $ name ++ " :: " ++ theType
let joined = unlines types
htmled = unlines $ map formatGetType types
return $
case extractPlain output of
"" -> Display [html htmled]
-- Return plain and html versions. Previously there was only a plain version.
text -> Display [plain $ joined ++ "\n" ++ text, html $ htmled ++ mono text]
RunException exception -> throw exception
RunBreak{} -> error "Should not break."
-- Read from a file handle until we hit a delimiter or until we've read as many characters as
-- requested
readChars :: Handle -> String -> Int -> IO String
readChars handle delims 0 =
-- If we're done reading, return nothing.
return []
readChars handle delims nchars = do
-- Try reading a single character. It will throw an exception if the handle is already closed.
tryRead <- gtry $ hGetChar handle :: IO (Either SomeException Char)
case tryRead of
Right char ->
-- If this is a delimiter, stop reading.
if char `elem` delims
then return [char]
else do
next <- readChars handle delims (nchars - 1)
return $ char : next
-- An error occurs at the end of the stream, so just stop reading.
Left _ -> return []
formatError :: ErrMsg -> String
formatError = formatErrorWithClass "err-msg"
formatErrorWithClass :: String -> ErrMsg -> String
formatErrorWithClass cls =
printf "<span class='%s'>%s</span>" cls .
replace "\n" "<br/>" .
replace useDashV "" .
replace "Ghci" "IHaskell" .
replace "‘interactive:" "‘" .
fixDollarSigns .
rstrip .
typeCleaner
where
fixDollarSigns = replace "$" "<span>$</span>"
useDashV = "\nUse -v to see a list of the files searched for."
isShowError err =
"No instance for (Show" `isPrefixOf` err &&
isInfixOf " arising from a use of `print'" err
formatParseError :: StringLoc -> String -> ErrMsg
formatParseError (Loc line col) =
printf "Parse error (line %d, column %d): %s" line col
formatGetType :: String -> String
formatGetType = printf "<span class='get-type'>%s</span>"
formatType :: String -> Display
formatType typeStr = Display [plain typeStr, html $ formatGetType typeStr]
displayError :: ErrMsg -> Display
displayError msg = Display [plain . typeCleaner $ msg, html $ formatError msg]
mono :: String -> String
mono = printf "<span class='mono'>%s</span>"
|
artuuge/IHaskell
|
src/IHaskell/Eval/Evaluate.hs
|
mit
| 49,851 | 0 | 30 | 15,065 | 9,798 | 4,956 | 4,842 | 880 | 30 |
import A; import A hiding (C)
|
bitemyapp/apply-refact
|
tests/examples/Import6.hs
|
bsd-3-clause
| 29 | 0 | 5 | 5 | 14 | 9 | 5 | 1 | 0 |
{-# LANGUAGE DataKinds, KindSignatures #-}
module Example where
import Data.Typeable
import GHC.Exts
data Wat (a :: TYPE 'UnboxedSumRep) = Wat a
|
olsner/ghc
|
testsuite/tests/unboxedsums/sum_rr.hs
|
bsd-3-clause
| 148 | 0 | 7 | 24 | 36 | 22 | 14 | -1 | -1 |
{-# LANGUAGE CPP, DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : Language.Python.Common.Token
-- Copyright : (c) 2009 Bernie Pope
-- License : BSD-style
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : ghc
--
-- Lexical tokens for the Python lexer. Contains the superset of tokens from
-- version 2 and version 3 of Python (they are mostly the same).
-----------------------------------------------------------------------------
module Language.JavaScript.Parser.Token (
-- * The tokens
Token (..)
, CommentAnnotation(..)
-- * String conversion
, debugTokenString
-- * Classification
-- TokenClass (..),
) where
import Data.Data
import Language.JavaScript.Parser.SrcLocation
data CommentAnnotation = CommentA TokenPosn String
| WhiteSpace TokenPosn String
| NoComment
deriving (Eq,{-Ord,-}Show,Typeable,Data,Read)
-- | Lexical tokens.
-- Each may be annotated with any comment occuring between the prior token and this one
data Token
-- Comment
= CommentToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] } -- ^ Single line comment.
| WsToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] } -- ^ White space, for preservation.
-- Identifiers
| IdentifierToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] } -- ^ Identifier.
-- Javascript Literals
| DecimalToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
-- ^ Literal: Decimal
| HexIntegerToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
-- ^ Literal: Hexadecimal Integer
| OctalToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
-- ^ Literal: Octal Integer
| StringToken { token_span :: !TokenPosn, token_literal :: !String, token_delimiter :: !Char, token_comment :: ![CommentAnnotation] }
-- ^ Literal: string, delimited by either single or double quotes
| RegExToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
-- ^ Literal: Regular Expression
-- Keywords
| BreakToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| CaseToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| CatchToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| ConstToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| ContinueToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| DebuggerToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| DefaultToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| DeleteToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| DoToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| ElseToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| EnumToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| FalseToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| FinallyToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| ForToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| FunctionToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| IfToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| InToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| InstanceofToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| NewToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| NullToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| ReturnToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| SwitchToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| ThisToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| ThrowToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| TrueToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| TryToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| TypeofToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| VarToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| VoidToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| WhileToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| WithToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
-- Future reserved words
| FutureToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
-- Needed, not sure what they are though.
| GetToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| SetToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
-- Delimiters
-- Operators
| SemiColonToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| CommaToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| HookToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| ColonToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| OrToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| AndToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| BitwiseOrToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| BitwiseXorToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| BitwiseAndToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| StrictEqToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| EqToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| AssignToken { token_span :: !TokenPosn, token_literal :: !String, token_comment :: ![CommentAnnotation] }
| SimpleAssignToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| StrictNeToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| NeToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| LshToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| LeToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| LtToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| UrshToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| RshToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| GeToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| GtToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| IncrementToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| DecrementToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| PlusToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| MinusToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| MulToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| DivToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| ModToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| NotToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| BitwiseNotToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| DotToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| LeftBracketToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| RightBracketToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| LeftCurlyToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| RightCurlyToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| LeftParenToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| RightParenToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
| CondcommentEndToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] }
-- Special cases
| TailToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] } -- ^ Stuff between last JS and EOF
| EOFToken { token_span :: !TokenPosn, token_comment :: ![CommentAnnotation] } -- ^ End of file
deriving (Eq,{-Ord,-}Show,Typeable{-,Data-})
-- | Produce a string from a token containing detailed information. Mainly intended for debugging.
debugTokenString :: Token -> String
debugTokenString _token =
"blah"
{-
render (text (show $ toConstr token) <+> pretty (token_span token) <+>
if hasLiteral token then text (token_literal token) else empty)
-}
-- EOF
|
maoe/language-javascript
|
src/Language/JavaScript/Parser/Token.hs
|
bsd-3-clause
| 10,332 | 0 | 10 | 1,752 | 2,297 | 1,369 | 928 | 519 | 1 |
{-# LANGUAGE GADTs #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
-- Tests record selectors with unboxed fields for GADTs
module Main where
data T a where
T1 :: { w :: !(Int, Int), x :: a, y :: b } -> T (a,b)
T2 :: { w :: !(Int, Int), x :: a } -> T (a,b)
T3 :: { z :: Int } -> T Bool
-- T1 :: forall c a b. (c~(a,b)) => (Int,Int) -> a -> b -> T c
f xv yv = T1 { w = (0,0), x = xv, y = yv }
g :: T a -> T a
g (T1 {x=xv, y=yv}) = T2 { w = (0,0), x = xv }
-- h :: Num a => T a any -> a
h v = x v + 1
i v = let (x,y) = w v in x + y
main = do { let t1 = T1 { w = (0,0), y = "foo", x = 4 }
t2 = g t1
; print (h (f 8 undefined))
; print (h t2)
; print (i t1)
}
|
urbanslug/ghc
|
testsuite/tests/gadt/ubx-records.hs
|
bsd-3-clause
| 692 | 6 | 12 | 226 | 350 | 202 | 148 | 21 | 1 |
import Test.Hspec (hspec)
import Spec (spec)
main :: IO ()
main = hspec spec
|
AndreasPK/stack
|
src/test/Test.hs
|
bsd-3-clause
| 78 | 0 | 6 | 15 | 37 | 20 | 17 | 4 | 1 |
{-# LANGUAGE RankNTypes #-}
module ShouldCompile where
data Q = Q {f :: forall a. a -> a}
g1 = f
g2 x = f x
g3 x y = f x y
|
urbanslug/ghc
|
testsuite/tests/deSugar/should_compile/ds050.hs
|
bsd-3-clause
| 125 | 0 | 10 | 35 | 60 | 33 | 27 | 6 | 1 |
{-# htermination join :: IO (IO a) -> IO a #-}
import Monad
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Monad_join_4.hs
|
mit
| 60 | 0 | 3 | 13 | 5 | 3 | 2 | 1 | 0 |
module GHCJS.DOM.DedicatedWorkerGlobalScope (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/DedicatedWorkerGlobalScope.hs
|
mit
| 56 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
{-
This is my xmonad configuration file.
There are many like it, but this one is mine.
If you want to customize this file, the easiest workflow goes
something like this:
1. Make a small change.
2. Hit "super-q", which recompiles and restarts xmonad
3. If there is an error, undo your change and hit "super-q" again to
get to a stable place again.
4. Repeat
Author: David Brewer
Repository: https://github.com/davidbrewer/xmonad-ubuntu-conf
-}
import XMonad
import XMonad.Hooks.SetWMName
import XMonad.Layout.Grid
import XMonad.Layout.ResizableTile
import XMonad.Layout.IM
import XMonad.Layout.ThreeColumns
import XMonad.Layout.NoBorders
import XMonad.Layout.Circle
import XMonad.Layout.PerWorkspace (onWorkspace)
import XMonad.Layout.Fullscreen
import XMonad.Util.EZConfig
import XMonad.Util.Run
import XMonad.Hooks.DynamicLog
import XMonad.Actions.Plane
import XMonad.Hooks.ManageDocks
import XMonad.Hooks.UrgencyHook
import XMonad.Hooks.ICCCMFocus
import qualified XMonad.StackSet as W
import qualified Data.Map as M
import Data.Ratio ((%))
{-
Xmonad configuration variables. These settings control some of the
simpler parts of xmonad's behavior and are straightforward to tweak.
-}
myModMask = mod4Mask -- changes the mod key to "super"
myFocusedBorderColor = "#e6550d" -- color of focused border
myNormalBorderColor = "#cccccc" -- color of inactive border
myBorderWidth = 1 -- width of border around windows
myTerminal = "terminator" -- which terminal software to use
myIMRosterTitle = "Buddy List" -- title of roster on IM workspace
-- use "Buddy List" for Pidgin, but
-- "Contact List" for Empathy
{-
Xmobar configuration variables. These settings control the appearance
of text which xmonad is sending to xmobar via the DynamicLog hook.
-}
myTitleColor = "#eeeeee" -- color of window title
myTitleLength = 80 -- truncate window title to this length
myCurrentWSColor = "#e6744c" -- color of active workspace
myVisibleWSColor = "#c185a7" -- color of inactive workspace
myUrgentWSColor = "#cc0000" -- color of workspace with 'urgent' window
myCurrentWSLeft = "[" -- wrap active workspace with these
myCurrentWSRight = "]"
myVisibleWSLeft = "(" -- wrap inactive workspace with these
myVisibleWSRight = ")"
myUrgentWSLeft = "{" -- wrap urgent workspace with these
myUrgentWSRight = "}"
{-
Workspace configuration. Here you can change the names of your
workspaces. Note that they are organized in a grid corresponding
to the layout of the number pad.
I would recommend sticking with relatively brief workspace names
because they are displayed in the xmobar status bar, where space
can get tight. Also, the workspace labels are referred to elsewhere
in the configuration file, so when you change a label you will have
to find places which refer to it and make a change there as well.
This central organizational concept of this configuration is that
the workspaces correspond to keys on the number pad, and that they
are organized in a grid which also matches the layout of the number pad.
So, I don't recommend changing the number of workspaces unless you are
prepared to delve into the workspace navigation keybindings section
as well.
-}
myWorkspaces =
[
"7:Extr7", "8:Music", "9:NX",
"4:Term", "5:Dev", "6:Web",
"1:Extr1", "2:Todo", "3:Extr",
"0:RDC", "Extr1", "Extr2"
]
startupWorkspace = "5:Dev" -- which workspace do you want to be on after launch?
{-
Layout configuration. In this section we identify which xmonad
layouts we want to use. I have defined a list of default
layouts which are applied on every workspace, as well as
special layouts which get applied to specific workspaces.
Note that all layouts are wrapped within "avoidStruts". What this does
is make the layouts avoid the status bar area at the top of the screen.
Without this, they would overlap the bar. You can toggle this behavior
by hitting "super-b" (bound to ToggleStruts in the keyboard bindings
in the next section).
-}
-- Define group of default layouts used on most screens, in the
-- order they will appear.
-- "smartBorders" modifier makes it so the borders on windows only
-- appear if there is more than one visible window.
-- "avoidStruts" modifier makes it so that the layout provides
-- space for the status bar at the top of the screen.
defaultLayouts = smartBorders(avoidStruts(
-- ResizableTall layout has a large master window on the left,
-- and remaining windows tile on the right. By default each area
-- takes up half the screen, but you can resize using "super-h" and
-- "super-l".
ResizableTall 1 (3/100) (1/2) []
-- Mirrored variation of ResizableTall. In this layout, the large
-- master window is at the top, and remaining windows tile at the
-- bottom of the screen. Can be resized as described above.
||| Mirror (ResizableTall 1 (3/100) (1/2) [])
-- Full layout makes every window full screen. When you toggle the
-- active window, it will bring the active window to the front.
||| noBorders Full
-- ThreeColMid layout puts the large master window in the center
-- of the screen. As configured below, by default it takes of 3/4 of
-- the available space. Remaining windows tile to both the left and
-- right of the master window. You can resize using "super-h" and
-- "super-l".
-- ||| ThreeColMid 1 (3/100) (3/4)
-- Circle layout places the master window in the center of the screen.
-- Remaining windows appear in a circle around it
-- ||| Circle
-- Grid layout tries to equally distribute windows in the available
-- space, increasing the number of columns and rows as necessary.
-- Master window is at top left.
||| Grid))
-- Here we define some layouts which will be assigned to specific
-- workspaces based on the functionality of that workspace.
-- The chat layout uses the "IM" layout. We have a roster which takes
-- up 1/8 of the screen vertically, and the remaining space contains
-- chat windows which are tiled using the grid layout. The roster is
-- identified using the myIMRosterTitle variable, and by default is
-- configured for Pidgin, so if you're using something else you
-- will want to modify that variable.
chatLayout = avoidStruts(withIM (1%7) (Title myIMRosterTitle) Grid)
-- The GIMP layout uses the ThreeColMid layout. The traditional GIMP
-- floating panels approach is a bit of a challenge to handle with xmonad;
-- I find the best solution is to make the image you are working on the
-- master area, and then use this ThreeColMid layout to make the panels
-- tile to the left and right of the image. If you use GIMP 2.8, you
-- can use single-window mode and avoid this issue.
gimpLayout = smartBorders(avoidStruts(ThreeColMid 1 (3/100) (3/4)))
-- Here we combine our default layouts with our specific, workspace-locked
-- layouts.
myLayouts =
onWorkspace "7:Chat" chatLayout
$ onWorkspace "9:Pix" gimpLayout
$ defaultLayouts
{-
Custom keybindings. In this section we define a list of relatively
straightforward keybindings. This would be the clearest place to
add your own keybindings, or change the keys we have defined
for certain functions.
It can be difficult to find a good list of keycodes for use
in xmonad. I have found this page useful -- just look
for entries beginning with "xK":
http://xmonad.org/xmonad-docs/xmonad/doc-index-X.html
Note that in the example below, the last three entries refer
to nonstandard keys which do not have names assigned by
xmonad. That's because they are the volume and mute keys
on my laptop, a Lenovo W520.
If you have special keys on your keyboard which you
want to bind to specific actions, you can use the "xev"
command-line tool to determine the code for a specific key.
Launch the command, then type the key in question and watch
the output.
-}
myKeyBindings =
[
((myModMask, xK_b), sendMessage ToggleStruts)
, ((myModMask, xK_a), sendMessage MirrorShrink)
, ((myModMask, xK_z), sendMessage MirrorExpand)
, ((myModMask, xK_p), spawn "dmenu_run -b")
, ((myModMask .|. mod1Mask, xK_space), spawn "dmenu_run -b")
, ((myModMask, xK_u), focusUrgent)
, ((0, 0x1008FF12), spawn "amixer -q set Master toggle")
, ((0, 0x1008FF11), spawn "amixer -q set Master 10%-")
, ((0, 0x1008FF13), spawn "amixer -q set Master 10%+")
, ((myModMask .|. shiftMask, xK_g), spawn "google-chrome")
]
{-
Management hooks. You can use management hooks to enforce certain
behaviors when specific programs or windows are launched. This is
useful if you want certain windows to not be managed by xmonad,
or sent to a specific workspace, or otherwise handled in a special
way.
Each entry within the list of hooks defines a way to identify a
window (before the arrow), and then how that window should be treated
(after the arrow).
To figure out to identify your window, you will need to use a
command-line tool called "xprop". When you run xprop, your cursor
will temporarily change to crosshairs; click on the window you
want to identify. In the output that is printed in your terminal,
look for a couple of things:
- WM_CLASS(STRING): values in this list of strings can be compared
to "className" to match windows.
- WM_NAME(STRING): this value can be compared to "resource" to match
windows.
The className values tend to be generic, and might match any window or
dialog owned by a particular program. The resource values tend to be
more specific, and will be different for every dialog. Sometimes you
might want to compare both className and resource, to make sure you
are matching only a particular window which belongs to a specific
program.
Once you've pinpointed the window you want to manipulate, here are
a few examples of things you might do with that window:
- doIgnore: this tells xmonad to completely ignore the window. It will
not be tiled or floated. Useful for things like launchers and
trays.
- doFloat: this tells xmonad to float the window rather than tiling
it. Handy for things that pop up, take some input, and then go away,
such as dialogs, calculators, and so on.
- doF (W.shift "Workspace"): this tells xmonad that when this program
is launched it should be sent to a specific workspace. Useful
for keeping specific tasks on specific workspaces. In the example
below I have specific workspaces for chat, development, and
editing images.
-}
myManagementHooks :: [ManageHook]
myManagementHooks = [
resource =? "synapse" --> doIgnore
, resource =? "stalonetray" --> doIgnore
, className =? "rdesktop" --> doFloat
, (className =? "Komodo IDE") --> doF (W.shift "5:Dev")
, (className =? "Komodo IDE" <&&> resource =? "Komodo_find2") --> doFloat
, (className =? "Komodo IDE" <&&> resource =? "Komodo_gotofile") --> doFloat
, (className =? "Komodo IDE" <&&> resource =? "Toplevel") --> doFloat
, (className =? "Empathy") --> doF (W.shift "7:Chat")
, (className =? "Pidgin") --> doF (W.shift "7:Chat")
, (className =? "Gimp-2.8") --> doF (W.shift "9:Pix")
]
{-
Workspace navigation keybindings. This is probably the part of the
configuration I have spent the most time messing with, but understand
the least. Be very careful if messing with this section.
-}
-- We define two lists of keycodes for use in the rest of the
-- keyboard configuration. The first is the list of numpad keys,
-- in the order they occur on the keyboard (left to right and
-- top to bottom). The second is the list of number keys, in an
-- order corresponding to the numpad. We will use these to
-- make workspace navigation commands work the same whether you
-- use the numpad or the top-row number keys. And, we also
-- use them to figure out where to go when the user
-- uses the arrow keys.
numPadKeys =
[
xK_KP_Home, xK_KP_Up, xK_KP_Page_Up
, xK_KP_Left, xK_KP_Begin,xK_KP_Right
, xK_KP_End, xK_KP_Down, xK_KP_Page_Down
, xK_KP_Insert, xK_KP_Delete, xK_KP_Enter
]
numKeys =
[
xK_7, xK_8, xK_9
, xK_4, xK_5, xK_6
, xK_1, xK_2, xK_3
, xK_0, xK_minus, xK_equal
]
-- Here, some magic occurs that I once grokked but has since
-- fallen out of my head. Essentially what is happening is
-- that we are telling xmonad how to navigate workspaces,
-- how to send windows to different workspaces,
-- and what keys to use to change which monitor is focused.
myKeys = myKeyBindings ++
[
((m .|. myModMask, k), windows $ f i)
| (i, k) <- zip myWorkspaces numPadKeys
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]
] ++
[
((m .|. myModMask, k), windows $ f i)
| (i, k) <- zip myWorkspaces numKeys
, (f, m) <- [(W.greedyView, 0), (W.shift, shiftMask)]
] ++
M.toList (planeKeys myModMask (Lines 4) Finite) ++
[
((m .|. myModMask, key), screenWorkspace sc
>>= flip whenJust (windows . f))
| (key, sc) <- zip [xK_w, xK_e, xK_r] [1,0,2]
, (f, m) <- [(W.view, 0), (W.shift, shiftMask)]
]
{-
Here we actually stitch together all the configuration settings
and run xmonad. We also spawn an instance of xmobar and pipe
content into it via the logHook.
-}
main = do
xmproc <- spawnPipe "xmobar ~/.xmonad/xmobarrc"
xmonad $ withUrgencyHook NoUrgencyHook $ defaultConfig {
focusedBorderColor = myFocusedBorderColor
, normalBorderColor = myNormalBorderColor
, terminal = myTerminal
, borderWidth = myBorderWidth
, layoutHook = myLayouts
, workspaces = myWorkspaces
, modMask = myModMask
, handleEventHook = fullscreenEventHook
, startupHook = do
setWMName "LG3D"
windows $ W.greedyView startupWorkspace
spawn "~/.xmonad/startup-hook"
, manageHook = manageHook defaultConfig
<+> composeAll myManagementHooks
<+> manageDocks
, logHook = takeTopFocus <+> dynamicLogWithPP xmobarPP {
ppOutput = hPutStrLn xmproc
, ppTitle = xmobarColor myTitleColor "" . shorten myTitleLength
, ppCurrent = xmobarColor myCurrentWSColor ""
. wrap myCurrentWSLeft myCurrentWSRight
, ppVisible = xmobarColor myVisibleWSColor ""
. wrap myVisibleWSLeft myVisibleWSRight
, ppUrgent = xmobarColor myUrgentWSColor ""
. wrap myUrgentWSLeft myUrgentWSRight
}
}
`additionalKeys` myKeys
|
mchi/xmonad-ubuntu-conf
|
xmonad.hs
|
mit
| 14,560 | 0 | 16 | 3,065 | 1,563 | 934 | 629 | 136 | 1 |
module Main where
import Iptf (ipFromWeb, updateHosts)
import Iptf.Options (Options (..), getOptions)
main :: IO ()
main = do
opts <- getOptions
ip <- ipFromWeb $ url opts
case ip of
Left e -> putStrLn e
Right ip' -> updateHosts ip' (name opts) (path opts)
|
werbitt/ip-to-file
|
app/Main.hs
|
mit
| 301 | 0 | 12 | 89 | 115 | 59 | 56 | 10 | 2 |
{-# LANGUAGE ViewPatterns #-}
module Language.RobotC.Utils where
import Control.Monad.Trans.Writer
import Language.RobotC.Data.Program
robotC :: Stmt -> RobotC
robotC = tell . return
robotC1 :: (a -> Stmt) -> a -> RobotC
robotC1 f = robotC . f
robotC2 :: (a -> b -> Stmt) -> a -> b -> RobotC
robotC2 f = robotC1 . f
robotC3 :: (a -> b -> c -> Stmt) -> a -> b -> c -> RobotC
robotC3 f = robotC2 . f
robotC4 :: (a -> b -> c -> d -> Stmt) -> a -> b -> c -> d -> RobotC
robotC4 f = robotC3 . f
liftRobotC1 :: (Stmt -> Stmt) -> RobotC -> RobotC
liftRobotC1 f = robotC1 $ f . unRobotC
liftRobotC2 :: (Stmt -> Stmt -> Stmt) -> RobotC -> RobotC -> RobotC
liftRobotC2 f = robotC2 $ \x y -> f (unRobotC x) (unRobotC y)
unRobotC :: RobotC -> Stmt
unRobotC (execWriter -> [x]) = x
unRobotC (execWriter -> xs) = Block xs
call0v :: Ident -> RobotC
call0v = robotC1 Call0v
call1v :: Ident -> R a -> RobotC
call1v = robotC2 Call1v
call2v :: Ident -> R a -> R b -> RobotC
call2v = robotC3 Call2v
call3v :: Ident -> R a -> R b -> R c -> RobotC
call3v = robotC4 Call3v
|
qsctr/haskell-robotc
|
src/Language/RobotC/Utils.hs
|
mit
| 1,064 | 0 | 10 | 234 | 471 | 248 | 223 | 29 | 1 |
-- Numbers that are a power of their sum of digits
-- https://www.codewars.com/kata/55f4e56315a375c1ed000159
module Codewars.G964.Powersumdig(powerSumDigTerm) where
import Data.List(sort)
f x 0 = x
f x n = f (x + r) q
where (q, r) = n `divMod` 10
ps n = filter ((== n) . sod) . map (n ^) $ [2..20]
where sod = f 0
pos = sort . concat . filter (/= []) . map ps $ [2..120]
powerSumDigTerm :: Int -> Integer
powerSumDigTerm = (pos !!) . pred
|
gafiatulin/codewars
|
src/5 kyu/Powersumdig.hs
|
mit
| 453 | 0 | 10 | 97 | 188 | 105 | 83 | 10 | 1 |
module Raytrace (
-- * Types
Ray, Intersectable, Material(..), Object, Scene,
-- * Raytracing
traceRay, intersections,
-- * Intersectables
-- ** 3D objects
sphere, cylinderShell,
-- ** Polygons
polygon, regularPoly, triangle, parallelogram,
-- ** Other
plane,
-- * Lights
mkLight, lights, isLight,
-- * Colors
RTColor, rtcolor, (%+), (%%), (*%)
) where
import Control.Monad (guard)
import Raster.Color
import Vec3
type Ray a = (Vec3 a, Vec3 a) -- origin and direction
type Intersectable a = Ray a -> Maybe (a, Vec3 a, Bool)
-- The 'a' value is the factor by which the direction vector is scaled so
-- that adding it to the origin vector yields the closest point on the
-- object. The Vec3 is the unit vector normal to the surface at the point of
-- intersection. The Bool is True iff the ray hit the object from "inside."
data Material a = Material {
color :: RTColor a,
diffusion :: a,
specularity :: a,
reflection :: a,
refracRatio :: a, -- outer index of refraction to inner index of refraction
lightCenter :: Maybe (Vec3 a) -- center of a spherical light
} deriving (Eq, Ord, Read, Show)
type Object a = (Intersectable a, Material a)
type Scene a = [Object a]
-- Raytracing: ----------------------------------------------------------------
intersections :: RealFloat a => Scene a -> Ray a
-> [(a, Vec3 a, Bool, Material a)]
intersections scene ray = [(ð, n, s, matter) | (f, matter) <- scene,
Just (ð, n, s) <- [f ray]]
traceRay :: RealFloat a => Scene a -> Int -> Ray a -> RTColor a
traceRay _ d _ | d < 1 = black
traceRay scene d ray@(orig, dir) =
if null hits then black
else if isLight matter then white
else foldl (%+) black [
max 0 (diffusion matter) * max 0 (n <.> m) *% color matter %% c
%+ max 0 (specularity matter) * (max 0 q)^20 *% c
| (c, l) <- lights scene,
let m = normalize (l <-> p),
let q = dir' <.> (m <-> scale (2 * m <.> n) n),
all (\(x, _, _, t) -> isLight t || x >= magnitude (l <-> p))
(intersections scene (p <+> scale epsilon m, m))
] %+ max 0 (reflection matter)
*% traceRay scene (d-1) (p <+> scale epsilon r, r)
%% color matter
%+ (if index > 0 && sin2θ <= 1
then traceRay scene (d-1) (p <+> scale epsilon refr, refr)
else black)
where hits = intersections scene ray
(ð, n, s, matter) = minimum hits
p = orig <+> scale ð dir
dir' = normalize dir
r = dir' <-> scale (2 * cosθ) n
index = (if s then recip else id) (refracRatio matter)
--index = if s then 1 else refracRatio matter -- for Bikker compatibility
cosθ = dir' <.> n
sin2θ = index^2 * (1 - cosθ^2)
refr = scale index $ dir' <-> scale (cosθ + sqrt (1 - sin2θ)) n
-- Intersectables: ------------------------------------------------------------
sphere :: RealFloat a => Vec3 a -> a -> Intersectable a
sphere center r (orig, dir) = do
sol <- minST2 (>= 0) =<< quadratic (magn2 dir)
(2 * dir <.> (orig <-> center))
(magn2 (orig <-> center) - r*r)
wrapUp sol (orig<+>scale sol dir<->center) (magnitude (orig<->center) < r)
cylinderShell :: RealFloat a => Ray a -> a -> Intersectable a
-- hollow walls of a cylinder (sans bases); arguments: axis and radius
cylinderShell (axOrig, axDir) r (orig, dir) = case (a, b, c) of
(0, 0, 0) | alongAxis 0 -> finalize 0
(0, 0, 0) -> finalize =<< minST (>= 0) [((axOrig <-> orig) <.> axDir + i)
/ dir <.> axDir | i <- [0,1]]
(0, 0, _) -> Nothing
(0, _, _) -> let ð = -c/b in if alongAxis ð then finalize ð else Nothing
(_, _, _) -> quadratic a b c >>= minST2 alongAxis >>= finalize
where alef = component dir axDir
bet = component (orig <-> axOrig) axDir
a = alef <.> alef
b = 2 * alef <.> bet
c = bet <.> bet - r*r
alongAxis ð = ð >= 0 && 0 <= l && l <= 1
where l = projFactor (orig <+> scale ð dir <-> axOrig) axDir
finalize ð = wrapUp ð (component sol axDir) (magnitude bet < r)
where sol = orig <+> scale ð dir <-> axOrig
plane :: RealFloat a => Vec3 a -> a -> Intersectable a
-- arguments: normal vector, distance from origin along normal vector
plane n d (orig, dir) = if denom == 0 -- ray and plane are parallel
then if d' == d
then Just (0, normalize n, False)
else Nothing
else if ð >= 0 then wrapUp ð n revsign
else Nothing
where denom = dir <.> n
d' = projFactor orig n
ð = (scale d n <-> orig) <.> n / denom
revsign = if d == 0 then (d' < 0 || d' == 0 && denom > 0) else d' < d
-- |@polygon n d verts@ creates an 'Intersectable' for a (convex?) polygon
-- with vertices @verts@ lying in @plane n d@. It is assumed that the given
-- vertices actually lie in this plane and that each vertex is adjacent to its
-- neighbors in the list, cycling around at the ends.
polygon :: RealFloat a => Vec3 a -> a -> [Vec3 a] -> Intersectable a
polygon n d verts (orig, dir) = do
guard $ n /= Vec3 (0, 0, 0)
(ð, n', s) <- plane n d (orig, dir)
guard $ ingon n verts $ orig <+> scale ð dir
return (ð, n', s)
triangle :: RealFloat a => Vec3 a -> Vec3 a -> Vec3 a -> Intersectable a
triangle a b c = polygon n (projFactor b n) [a, b, c]
where n = cross (b <-> a) (b <-> c)
parallelogram :: RealFloat a => Vec3 a -> Vec3 a -> Vec3 a -> Intersectable a
-- arguments: a corner, vectors to vertices adjacent to that corner
parallelogram v e1 e2 = polygon n (projFactor v n)
[v, v <+> e1, v <+> e1 <+> e2, v <+> e2]
where n = cross e1 e2
regularPoly :: RealFloat a => Vec3 a -> Vec3 a -> Vec3 a -> Int
-> Intersectable a
regularPoly norm center rad n (orig, dir) = do
guard $ n >= 3
guard $ norm /= Vec3 (0, 0, 0)
guard $ norm <.> rad == 0
let apothem = magnitude rad * cos (pi / fromIntegral n) -- length of apothem
θ = 2 * pi / fromIntegral n
(ð, n', s) <- plane norm (projFactor center norm) (orig, dir)
let p = orig <+> scale ð dir <-> center
pr = magnitude p
pφ = abs $ angleTwixt p rad
pθ = until (< θ) (subtract θ) pφ
guard $ pr <= apothem
|| not (isNaN pφ) && not (isInfinite pφ) && pr * cos (pθ - θ/2) <= apothem
-- Due to floating-point roundoff, angleTwixt can sometimes end up trying to
-- take the arccosine of a number greater than 1, resulting in a NaN. The
-- isInfinite check is just for completeness. Try to figure out a better
-- way to deal with this problem.
return (ð, n', s)
-- Lights: --------------------------------------------------------------------
lights :: Scene a -> [(RTColor a, Vec3 a)]
lights sc = [(color m, c) | (_, m) <- sc, Just c <- [lightCenter m]]
isLight :: Material a -> Bool
isLight (Material {lightCenter = Just _}) = True
isLight _ = False
mkLight :: RealFloat a => Vec3 a -> a -> RTColor a -> Object a
mkLight loc rad colour = (sphere loc rad, Material colour 0 0 0 0 (Just loc))
-- RTColor: -------------------------------------------------------------------
newtype RTColor a = RTColor (a, a, a) deriving (Eq, Ord, Read, Show)
-- constructor not for export
instance (RealFrac a) => Color (RTColor a) where
black = RTColor (0, 0, 0)
white = RTColor (1, 1, 1)
getRGBA (RTColor (r, g, b)) = (unrt r, unrt g, unrt b, 255)
where unrt = round . (* 255) . max 0 . min 1
instance (RealFrac a) => GreyColor (RTColor a) where
fromGrey x = RTColor (tort x, tort x, tort x)
where tort = (/ 255) . fromIntegral
instance (RealFrac a) => RealColor (RTColor a) where
fromRGB r g b = RTColor (tort r, tort g, tort b)
where tort = (/ 255) . fromIntegral
rtcolor :: RealFrac a => a -> a -> a -> RTColor a
rtcolor r g b = RTColor (f r, f g, f b) where f = max 0 . min 1
-- Should these three be exported?
infixl 7 %%, *%
infixl 6 %+
(%+) :: Num a => RTColor a -> RTColor a -> RTColor a -- add RTColors
RTColor (r, g, b) %+ RTColor (x, y, z) = RTColor (r+x, g+y, b+z)
(%%) :: Num a => RTColor a -> RTColor a -> RTColor a -- multiply RTColors
RTColor (r, g, b) %% RTColor (x, y, z) = RTColor (r*x, g*y, b*z)
(*%) :: Num a => a -> RTColor a -> RTColor a -- scale an RTColor
c *% RTColor (r, g, b) = RTColor (c*r, c*g, c*b)
-- Unexported functions: ------------------------------------------------------
quadratic :: RealFloat a => a -> a -> a -> Maybe (a,a)
quadratic a b c = if disc < 0 then Nothing
else Just ((-b + sqrt disc)/2/a, (-b - sqrt disc)/2/a)
where disc = b*b - 4*a*c
epsilon :: Fractional a => a
epsilon = 0.0000001
minST :: Ord a => (a -> Bool) -> [a] -> Maybe a -- "minimum such that"
minST p xs = case filter p xs of [] -> Nothing; ys -> Just (minimum ys)
minST2 :: Ord a => (a -> Bool) -> (a, a) -> Maybe a
minST2 p (a, b) = minST p [a, b]
wrapUp :: Floating f => f -> Vec3 f -> Bool -> Maybe (f, Vec3 f, Bool)
--wrapUp ð n ins = Just (ð, scale ((-1) ^ fromEnum ins) (normalize n), ins)
wrapUp ð n ins = Just (ð, (if ins then scale (-1) else id) (normalize n), ins)
-- |Tests whether a given point is inside or on an edge of a polygon, assuming
-- that the given vertices all lie in the plane normal to the first vector and
-- that each vertex is adjacent to its neighbors in the list, cycling around
-- at the ends
ingon :: RealFloat a => Vec3 a -> [Vec3 a] -> Vec3 a -> Bool
-- Should this be merged into 'polygon'?
ingon _ [] _ = False
ingon n vs u = case head prods of (0, d) -> 0 <= d && d <= 1
(s, _) -> ingon' s (tail prods)
where prods = [(signum $ cross a b <.> n, projFactor b a)
| (x,y) <- pairNext vs, let a = x <-> y, let b = u <-> y]
ingon' _ ((0,d):_) = 0 <= d && d <= 1
ingon' s ((t,_):xs) = s == t && ingon' s xs
ingon' _ [] = True
-- @pairNext xs@ returns a list of all pairs of consecutive elements in @xs@,
-- with the last element paired with the first.
pairNext :: [a] -> [(a,a)]
pairNext [] = []
pairNext xs@(y:ys) = zip xs (ys ++ [y])
|
jwodder/hsgraphics
|
Raytrace.hs
|
mit
| 9,845 | 357 | 12 | 2,394 | 3,972 | 2,205 | 1,767 | 171 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module Main (main) where
import FRP.Yampa
import Game
import Input
import Rendering
import System.Random (newStdGen)
main :: IO ()
main = do
g <- newStdGen
animate "Flappy Haskell" (round winWidth) (round winHeight) $
parseWinInput >>> (game g &&& handleExit)
|
Rydgel/flappy-haskell
|
src/Main.hs
|
mit
| 357 | 0 | 11 | 105 | 96 | 52 | 44 | 12 | 1 |
module Compiler.Compiler where
import Language.Expr
compile :: Program -> String
compile (ProgEnd e) = compileExpr e ++ ";"
compile (ProgCont e p) = compileExpr e ++ ";" ++ compile p
compileExpr :: Expr -> String
compileExpr (BinOp Add e1 e2) = compileExpr e1 ++ ".__add__(" ++ compileExpr e2 ++ ")"
compileExpr (BinOp Sub e1 e2) = compileExpr e1 ++ ".__sub__(" ++ compileExpr e2 ++ ")"
compileExpr (BinOp Mul e1 e2) = compileExpr e1 ++ ".__mul__(" ++ compileExpr e2 ++ ")"
compileExpr (BinOp Div e1 e2) = compileExpr e1 ++ ".__div__(" ++ compileExpr e2 ++ ")"
compileExpr (Number x) = "IoNumber(" ++ x ++ ")"
|
dpzmick/io2js
|
src/Compiler/Compiler.hs
|
mit
| 613 | 0 | 8 | 107 | 246 | 120 | 126 | 11 | 1 |
--------------------------------------------------------------------------------
-- Module : Main
-- Maintainer : [email protected]
-- Stability : Experimental
-- Summary : Some common functions/datas used by a bunch of other modules.
--------------------------------------------------------------------------------
module Bot.Common where
import System.IO ( Handle )
import Text.Printf ( hPrintf, printf )
import System.Time ( ClockTime )
import Control.Monad.Reader
import Utils.Settings
-- | Define a data type that holds the bot state, which currently consists
-- of:
--
-- * A handle (socket)
-- * When the bot joined the channel (starttime)
-- * Configuration read from an external yaml file (settings)
data Bot = Bot { socket :: Handle
, starttime :: ClockTime
, settings :: Settings
}
type Net = ReaderT Bot IO
-- | Write stuff to the IRC server. Also writes a message to the console in which
-- the bot is running.
write :: String -> String -> Net ()
write s t = do
h <- asks socket
liftIO $ hPrintf h "%s %s\r\n" s t
liftIO $ printf "> %s %s\n" s t
splitString :: [Char] -> [[Char]]
splitString [] = []
splitString s = line : (splitString $ drop n s)
where n = length line + 1
line = splitHelp s
splitHelp :: [Char] -> [Char]
splitHelp s | (drop 400 s) == [] = (take 400 s)
splitHelp s =
if (head rem /= ' ')
then front ++ (takeWhile (/= ' ') rem)
else front
where front = take 400 s
rem = drop 400 s
|
madelgi/hs-bot
|
src/Bot/Common.hs
|
mit
| 1,663 | 0 | 10 | 492 | 361 | 199 | 162 | 28 | 2 |
module Data.Foldable.CompatSpec (main, spec) where
import Test.Hspec
import Data.Foldable.Compat
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "maximumBy" $ do
it "runs in constant space" $ do
maximumBy compare [1..10000] `shouldBe` (10000 :: Int)
|
haskell-compat/base-compat
|
base-compat-batteries/test/Data/Foldable/CompatSpec.hs
|
mit
| 303 | 0 | 15 | 78 | 99 | 54 | 45 | 10 | 1 |
module Main where
-- module under test
import Data.DTW
import Data.List
import Data.Functor
import Test.Framework
import Test.Framework.Providers.QuickCheck2
import Test.QuickCheck
import qualified Data.Vector.Unboxed as V
newtype SmallNonEmptySeq a = SmallNonEmptySeq { getSmallNonEmpty :: V.Vector a }
deriving (Show, Eq)
instance (V.Unbox a, Arbitrary a) => Arbitrary (SmallNonEmptySeq a) where
arbitrary = SmallNonEmptySeq . V.fromList <$> listOf arbitrary `suchThat` (\l -> length l > 2 && length l < 10)
newtype MediumNonEmptySeq a = MediumNonEmptySeq { getMediumNonEmpty :: V.Vector a }
deriving (Show, Eq)
instance (V.Unbox a, Arbitrary a) => Arbitrary (MediumNonEmptySeq a) where
arbitrary = MediumNonEmptySeq . V.fromList <$> listOf arbitrary `suchThat` (\l -> length l > 100 && length l < 1000)
dist :: Double -> Double -> Double
dist x y = abs (x-y)
-- | reduce a dataset to half its size by averaging neighbour values
-- together
reduceByHalf :: (V.Unbox a, Fractional a) => V.Vector a -> V.Vector a
reduceByHalf v | V.null v = V.empty
| V.length v == 1 = V.singleton (V.head v)
| even (V.length v) = split v
| otherwise = split v `V.snoc` V.last v
where split w = V.generate (V.length w `div` 2) (\i -> (w V.! (i*2+0)) + (w V.! (i*2+1)))
{-testDTWVSDTWNaive :: (SmallNonEmptySeq Double, SmallNonEmptySeq Double) -> Bool-}
{-testDTWVSDTWNaive (la,lb) = abs (dtwNaive dist sa sb - dtw dist sa sb) < 0.01-}
{- where sa = S.fromList $ getSmallNonEmpty la-}
{- sb = S.fromList $ getSmallNonEmpty lb-}
testDTWMemoVSDTWNaive :: (SmallNonEmptySeq Double, SmallNonEmptySeq Double) -> Bool
testDTWMemoVSDTWNaive (la,lb) = abs (dtwNaive dist sa sb - cost (dtwMemo dist sa sb)) < 0.01
where sa = getSmallNonEmpty la
sb = getSmallNonEmpty lb
testFastDTWvsDTWNaive :: (SmallNonEmptySeq Double, SmallNonEmptySeq Double) -> Bool
testFastDTWvsDTWNaive (la,lb) = abs (1 - (ca/l) / (cb/l)) < 0.1
where sa = getSmallNonEmpty la
sb = getSmallNonEmpty lb
l = fromIntegral $ V.length sa + V.length sb
ca = dtwNaive dist sa sb
cb = cost $ fastDtw dist reduceByHalf 2 sa sb
-- FIXME no real idea how to compare an optimal and an approximative
-- algorithm ... best bet below, but still failing tests
testFastDTWvsDTWMemoErr :: Int -> (MediumNonEmptySeq Double, MediumNonEmptySeq Double) -> Double
testFastDTWvsDTWMemoErr radius (la,lb) = err
where sa = getMediumNonEmpty la
sb = getMediumNonEmpty lb
optimal = cost (dtwMemo dist sa sb)
approx = cost (fastDtw dist reduceByHalf radius sa sb)
err = (approx - optimal) / optimal * 100
testFastDTWvsDTWMemo :: Int -> Double -> Property
testFastDTWvsDTWMemo radius goal = forAll (vector 25) go
where go xs = median < goal
where errs = map (testFastDTWvsDTWMemoErr radius) xs
median = sort errs !! (length errs `div` 2)
main :: IO ()
main = defaultMain
[ testProperty "dtwMemo ≡ dtwNaive" testDTWMemoVSDTWNaive
{-, testProperty "fastDtw ≅ dtwNaive" testFastDTWvsDTWNaive-}
, testProperty "fastDtw == dtwMemo (radius=5, maxError=5%)" (testFastDTWvsDTWMemo 5 5)
]
|
fhaust/dtw
|
test/MainTest.hs
|
mit
| 3,258 | 0 | 15 | 724 | 1,007 | 530 | 477 | 51 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.