code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Orville.PostgreSQL.Internal.Expr.TableDefinition
( CreateTableExpr,
createTableExpr,
PrimaryKeyExpr,
primaryKeyExpr,
AlterTableExpr,
alterTableExpr,
AlterTableAction,
addColumn,
dropColumn,
addConstraint,
dropConstraint,
alterColumnType,
alterColumnSetDefault,
alterColumnDropDefault,
UsingClause,
usingCast,
alterColumnNullability,
AlterNotNull,
setNotNull,
dropNotNull,
DropTableExpr,
dropTableExpr,
IfExists,
ifExists,
)
where
import Data.List.NonEmpty (NonEmpty)
import Data.Maybe (catMaybes, maybeToList)
import Orville.PostgreSQL.Internal.Expr.ColumnDefinition (ColumnDefinition, DataType)
import Orville.PostgreSQL.Internal.Expr.Name (ColumnName, ConstraintName, QualifiedTableName)
import Orville.PostgreSQL.Internal.Expr.TableConstraint (TableConstraint)
import qualified Orville.PostgreSQL.Internal.RawSql as RawSql
newtype CreateTableExpr
= CreateTableExpr RawSql.RawSql
deriving (RawSql.SqlExpression)
createTableExpr ::
QualifiedTableName ->
[ColumnDefinition] ->
Maybe PrimaryKeyExpr ->
[TableConstraint] ->
CreateTableExpr
createTableExpr tableName columnDefs mbPrimaryKey constraints =
let columnDefsSql =
map RawSql.toRawSql columnDefs
constraintsSql =
map RawSql.toRawSql constraints
tableElementsSql =
case mbPrimaryKey of
Nothing ->
columnDefsSql <> constraintsSql
Just primaryKey ->
RawSql.toRawSql primaryKey : (columnDefsSql <> constraintsSql)
in CreateTableExpr $
mconcat
[ RawSql.fromString "CREATE TABLE "
, RawSql.toRawSql tableName
, RawSql.space
, RawSql.leftParen
, RawSql.intercalate RawSql.comma tableElementsSql
, RawSql.rightParen
]
newtype PrimaryKeyExpr
= PrimaryKeyExpr RawSql.RawSql
deriving (RawSql.SqlExpression)
primaryKeyExpr :: NonEmpty ColumnName -> PrimaryKeyExpr
primaryKeyExpr columnNames =
PrimaryKeyExpr $
mconcat
[ RawSql.fromString "PRIMARY KEY "
, RawSql.leftParen
, RawSql.intercalate RawSql.comma columnNames
, RawSql.rightParen
]
newtype AlterTableExpr
= AlterTableExpr RawSql.RawSql
deriving (RawSql.SqlExpression)
alterTableExpr :: QualifiedTableName -> NonEmpty AlterTableAction -> AlterTableExpr
alterTableExpr tableName actions =
AlterTableExpr $
RawSql.fromString "ALTER TABLE "
<> RawSql.toRawSql tableName
<> RawSql.space
<> RawSql.intercalate RawSql.commaSpace actions
newtype AlterTableAction
= AlterTableAction RawSql.RawSql
deriving (RawSql.SqlExpression)
addColumn :: ColumnDefinition -> AlterTableAction
addColumn columnDef =
AlterTableAction $
RawSql.fromString "ADD COLUMN " <> RawSql.toRawSql columnDef
dropColumn :: ColumnName -> AlterTableAction
dropColumn columnName =
AlterTableAction $
RawSql.fromString "DROP COLUMN " <> RawSql.toRawSql columnName
addConstraint :: TableConstraint -> AlterTableAction
addConstraint constraint =
AlterTableAction $
RawSql.fromString "ADD " <> RawSql.toRawSql constraint
dropConstraint :: ConstraintName -> AlterTableAction
dropConstraint constraintName =
AlterTableAction $
RawSql.fromString "DROP CONSTRAINT " <> RawSql.toRawSql constraintName
alterColumnType ::
ColumnName ->
DataType ->
Maybe UsingClause ->
AlterTableAction
alterColumnType columnName dataType maybeUsingClause =
AlterTableAction $
RawSql.intercalate
RawSql.space
( RawSql.fromString "ALTER COLUMN" :
RawSql.toRawSql columnName :
RawSql.fromString "TYPE" :
RawSql.toRawSql dataType :
maybeToList (fmap RawSql.toRawSql maybeUsingClause)
)
newtype UsingClause
= UsingClause RawSql.RawSql
deriving (RawSql.SqlExpression)
usingCast :: ColumnName -> DataType -> UsingClause
usingCast columnName dataType =
UsingClause $
RawSql.fromString "USING "
<> RawSql.toRawSql columnName
<> RawSql.doubleColon
<> RawSql.toRawSql dataType
alterColumnNullability :: ColumnName -> AlterNotNull -> AlterTableAction
alterColumnNullability columnName alterNotNull =
AlterTableAction $
RawSql.intercalate
RawSql.space
[ RawSql.fromString "ALTER COLUMN"
, RawSql.toRawSql columnName
, RawSql.toRawSql alterNotNull
]
newtype AlterNotNull
= AlterNotNull RawSql.RawSql
deriving (RawSql.SqlExpression)
setNotNull :: AlterNotNull
setNotNull =
AlterNotNull $ RawSql.fromString "SET NOT NULL"
dropNotNull :: AlterNotNull
dropNotNull =
AlterNotNull $ RawSql.fromString "DROP NOT NULL"
alterColumnDropDefault :: ColumnName -> AlterTableAction
alterColumnDropDefault columnName =
AlterTableAction $
RawSql.intercalate
RawSql.space
[ RawSql.fromString "ALTER COLUMN"
, RawSql.toRawSql columnName
, RawSql.fromString "DROP DEFAULT"
]
alterColumnSetDefault ::
RawSql.SqlExpression valueExpression =>
ColumnName ->
valueExpression ->
AlterTableAction
alterColumnSetDefault columnName defaultValue =
AlterTableAction $
RawSql.intercalate
RawSql.space
[ RawSql.fromString "ALTER COLUMN"
, RawSql.toRawSql columnName
, RawSql.fromString "SET DEFAULT"
, RawSql.toRawSql defaultValue
]
newtype DropTableExpr
= DropTableExpr RawSql.RawSql
deriving (RawSql.SqlExpression)
dropTableExpr :: Maybe IfExists -> QualifiedTableName -> DropTableExpr
dropTableExpr maybeIfExists tableName =
DropTableExpr $
RawSql.intercalate
RawSql.space
( catMaybes
[ Just (RawSql.fromString "DROP TABLE")
, fmap RawSql.toRawSql maybeIfExists
, Just (RawSql.toRawSql tableName)
]
)
newtype IfExists
= IfExists RawSql.RawSql
deriving (RawSql.SqlExpression)
ifExists :: IfExists
ifExists =
IfExists $ RawSql.fromString "IF EXISTS"
|
flipstone/orville
|
orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/Expr/TableDefinition.hs
|
Haskell
|
mit
| 5,986
|
module Haskeroids.Initialize where
import Graphics.Rendering.OpenGL
import Graphics.UI.GLUT
import Haskeroids.Callbacks
-- | Set up the main application window
initializeWindow = do
_ <- getArgsAndInitialize
initialWindowSize $= Size 800 600
initialDisplayMode $= [DoubleBuffered]
createWindow "Haskeroids"
-- | Set up the initial OpenGL parameters
initializeOpenGL = do
-- Disable depth checking as we won't be needing it in 2D
depthMask $= Disabled
-- Nicer line drawing
lineSmooth $= Enabled
blend $= Enabled
blendFunc $= (SrcAlpha,OneMinusSrcAlpha)
lineWidth $= 2.0
-- Set up viewport
viewport $= (Position 0 0, Size 800 600)
-- Set up an orthogonal projection for 2D rendering
matrixMode $= Projection
loadIdentity
ortho 0 800 600 0 (-1) 1
matrixMode $= Modelview 0
loadIdentity
-- Set background color to dark bluish black
clearColor $= Color4 0.0 0.0 0.1 1.0
-- | Set up GLUT callbacks
initializeCallbacks = do
refs <- initCallbackRefs
keyboardMouseCallback $= Just (handleKeyboard refs)
displayCallback $= renderViewport refs
|
shangaslammi/haskeroids
|
Haskeroids/Initialize.hs
|
Haskell
|
mit
| 1,154
|
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Say (inEnglish)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "inEnglish" $ for_ cases test
where
test (n, expected) = it description assertion
where
description = show n
assertion = inEnglish n `shouldBe` expected
cases = [ ( 0, Just "zero" )
, ( 1, Just "one" )
, ( 14, Just "fourteen" )
, ( 20, Just "twenty" )
, ( 22, Just "twenty-two" )
, ( 100, Just "one hundred" )
, ( 123, Just "one hundred twenty-three" )
, ( 1000, Just "one thousand" )
, ( 1234, Just "one thousand two hundred thirty-four")
, ( 1000000, Just "one million" )
, ( 1000002, Just "one million two" )
, ( 1002345, Just "one million two thousand three \
\hundred forty-five" )
, ( 1000000000, Just "one billion" )
, ( 987654321123, Just "nine hundred eighty-seven billion \
\six hundred fifty-four million \
\three hundred twenty-one thousand \
\one hundred twenty-three" )
, ( -1, Nothing )
-- Even though the problem-specifications tests have this case,
-- we decide not to test it, to give freedom to go to trillions if desired.
-- , (1000000000000, Nothing )
]
-- 899023ec6526c664420a690eec2afcf3e62cb35b
|
exercism/xhaskell
|
exercises/practice/say/test/Tests.hs
|
Haskell
|
mit
| 2,217
|
module Lesson2.UCS.Enumerator where
import Control.Monad.Trans (MonadIO, liftIO)
import Data.Lens.Common (getL)
import Data.Enumerator (
Stream(..)
, Step(..)
, Iteratee(..)
, Enumerator
, (>>==)
, returnI
, continue
, yield
)
import Data.Hashable (Hashable(..))
import Data.Maybe (fromJust)
import qualified Data.Set as Set
import Navigation.Enumerator
import Lesson2.Types
import Lesson2.UCS.Types
-------------------------------------------------------------------------------
enumUCS :: (MonadIO m, Show a, Hashable a)
=> Node a
-> UCSGraph a
-> Enumerator (NavEvent (Node a)) m b
enumUCS zero g =
enumNavigation findCost
(return . (`getNodeNeighbours` g))
zero
where
findCost parent child =
return .
head .
Set.fold (processEdge parent child) [] $
getL graphEdges g
processEdge parent child e acc
| getEdgeSource e == parent &&
getEdgeSink e == child = fromJust (getEdgeCost e) : acc
| otherwise = acc
|
roman/ai-class-haskell
|
src/Lesson2/UCS/Enumerator.hs
|
Haskell
|
mit
| 1,056
|
import Primes
import Utils
lengthGreater3 :: [a] -> Bool
lengthGreater3 (a:b:c:d:xs) = True
lengthGreater3 _ = False
morethanFourFactors = lengthGreater3 . primeFactors
pairs = map (\n -> (n,morethanFourFactors n)) [2..]
firstFourTrue :: [(Integer, Bool)] -> Integer
firstFourTrue ((n1,b1):(n2,b2):(n3,b3):(n4,b4):xs)
| b1 && b2 && b3 && b4 = n1
| otherwise = firstFourTrue ((n2,b2):(n3,b3):(n4,b4):xs)
answer = firstFourTrue pairs
main = print answer
|
arekfu/project_euler
|
p0047/p0047.hs
|
Haskell
|
mit
| 475
|
{-# LANGUAGE OverloadedStrings, TemplateHaskell #-}
module Leankit.Types.Card where
import Control.Applicative ((<$>))
import Data.Aeson
import Data.Aeson.TH
import Data.List.Split
import Leankit.Types.TH
import Leankit.Types.Common
import Leankit.Types.AssignedUser (AssignedUser)
import Leankit.Types.CardContext (CardContext)
-- TODO clumsy, why do I need a separate data type??
newtype Tags = Tags [String] deriving (Eq, Show)
instance FromJSON Tags where
parseJSON Null = return $ Tags []
parseJSON v = toTags <$> parseJSON v where
toTags = Tags . splitOn ","
data Card = Card {
_id :: Int,
_version :: Maybe Int,
_typeId :: Maybe Int,
_typeName :: Maybe String,
_typeColorHex :: Maybe Color,
_typeIconPath :: Maybe String,
_title :: Maybe String,
_description :: Maybe String,
_tags :: Tags,
_dueDate :: Maybe Date,
_size :: Maybe Int,
_priority :: Maybe Int,
_priorityText :: Maybe String,
_color :: Maybe Color,
_laneId :: Maybe Int,
_parentCardId :: Maybe CardID,
_gravatarLink :: Maybe String,
_smallGravatarLink :: Maybe String,
_active :: Maybe Bool,
_index :: Maybe Int,
_taskBoardCompletionPercent :: Maybe Int,
_classOfServiceId :: Maybe Int,
_classOfServiceTitle :: Maybe String,
_classOfServiceColorHex :: Maybe Color,
_classOfServiceIconPath :: Maybe String,
_currentTaskBoardId :: Maybe BoardID,
_systemType :: Maybe String,
_currentContext :: Maybe String,
_cardContexts :: Maybe [CardContext], -- ?
_taskBoardTotalCards :: Maybe Int,
_taskBoardTotalSize :: Maybe Int,
_blockReason :: Maybe String,
_blockStateChangeDate :: Maybe String,
_assignedUsers :: [AssignedUser],
_assignedUserIds :: [UserID],
_externalCardID :: Maybe String,
_externalSystemName :: Maybe String,
_externalSystemUrl :: Maybe String,
_drillThroughBoardId :: Maybe BoardID,
_drillThroughCompletionPercent :: Maybe Int,
_drillThroughProgressComplete :: Maybe Int,
_drillThroughProgressTotal :: Maybe String,
_lastAttachment :: Maybe String,
_lastActivity :: Maybe DateTime,
_lastMove :: Maybe DateTime,
_lastComment :: Maybe String,
_commentsCount :: Maybe Int,
_dateArchived :: Maybe Date,
_attachmentsCount :: Maybe Int,
_countOfOldCards :: Maybe Int,
_hasDrillThroughBoard :: Maybe Bool,
_isBlocked :: Maybe Bool
} deriving (Eq, Show)
$(deriveFromJSON parseOptions ''Card)
|
dtorok/leankit-hsapi
|
Leankit/Types/Card.hs
|
Haskell
|
mit
| 3,555
|
{-# htermination elemFM :: (Ord a, Ord k) => (Either a k) -> FiniteMap (Either a k) b -> Bool #-}
import FiniteMap
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_elemFM_10.hs
|
Haskell
|
mit
| 115
|
module Test.Smoke.Spec.PathGenerator
( genAbsoluteFilePath,
genRelativeDir,
genRelativeFile,
genRelativeFilePath,
genNamedSegment,
)
where
import qualified Data.List as List
import Hedgehog
import qualified Hedgehog.Gen as Gen
import qualified Hedgehog.Range as Range
import qualified System.FilePath as FilePath
import Test.Smoke.Paths
import Test.Smoke.Spec.RootDirectory
data FilePathSegment
= Current
| Parent
| Named String
genRelativeDir :: Range Int -> Gen (RelativePath Dir)
genRelativeDir segmentRange = parseDir <$> genRelativeFilePath segmentRange
genRelativeFile :: Range Int -> Gen (RelativePath File)
genRelativeFile segmentRange = parseFile <$> genRelativeFilePath segmentRange
genAbsoluteFilePath :: Range Int -> Gen FilePath
genAbsoluteFilePath segmentRange =
FilePath.joinDrive rootDirectory <$> genRelativeFilePath segmentRange
genRelativeFilePath :: Range Int -> Gen FilePath
genRelativeFilePath segmentRange = do
segments <-
Gen.filter segmentsAreNotSubtractive $ Gen.list segmentRange genSegment
let joined =
List.intercalate [FilePath.pathSeparator] $ map segmentString segments
return $ dropWhile (== FilePath.pathSeparator) joined
genSegment :: Gen FilePathSegment
genSegment =
Gen.frequency
[ (2, Gen.constant Current),
(1, Gen.constant Parent),
(5, Named <$> genNamedSegment)
]
genNamedSegment :: Gen FilePath
genNamedSegment = do
name <- Gen.string (Range.linear 1 100) Gen.alphaNum
trailingSeparators <-
Gen.string (Range.linear 0 3) $ Gen.constant FilePath.pathSeparator
return $ name <> trailingSeparators
segmentsAreNotSubtractive :: [FilePathSegment] -> Bool
segmentsAreNotSubtractive = (>= 0) . countSegments
countSegment :: FilePathSegment -> Int
countSegment Current = 0
countSegment Parent = -1
countSegment (Named _) = 1
countSegments :: [FilePathSegment] -> Int
countSegments = sum . map countSegment
segmentString :: FilePathSegment -> String
segmentString Current = "."
segmentString Parent = ".."
segmentString (Named value) = value
|
SamirTalwar/Smoke
|
src/test/Test/Smoke/Spec/PathGenerator.hs
|
Haskell
|
mit
| 2,065
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-|
Module : Main
Description : Main module running the GMM
Copyright : (c) Julian Kopka Larsen, 2015
Stability : experimental
-}
module Main (
main
) where
import Control.Monad (forM, unless)
import Data.List (transpose, (\\))
import FileParsing
import GHC.Arr (range)
import Graphics.EasyPlot
import Numeric.LinearAlgebra
-- import Numeric.Statistics.PCA
import System.CPUTime
import System.Exit (exitFailure)
import System.IO (readFile)
import Text.Printf
import System.Random (mkStdGen)
import Debug.Trace
import MCMC
import Partition
import Math
import Distributions (lNormW, dlNormW,lnormalInvWishartSS)
list2Touple (a:b:_) = (a,b)
list2Touple _ = (0,0)
toTouples :: Num a => [[a]] -> [(a,a)]
toTouples = map list2Touple
--to2D = toTouples . toLists
plotClusters :: X -> Partition -> [Graph2D Double Double]
plotClusters x p = map toplot $ range (0,((k p)-1))
where toplot i = Data2D [Title "d"] [] (toTouples $ map toList $ select x p i)
qtr x = trace ("value: " ++ show x) x
data State = State (Partition,[Sstat]) deriving Show
instance Sampleable State X where
condMove x g (State (p,s)) = State (newPar, update)
where newPar = move g p
update = ss' x p s newPar
llikelihood _ (State (_,s)) = sum $ map (\(i,m,v) -> lnormalInvWishartSS i m v) s
llikDiff _ (State (_,s')) (State (_,s))
= f s' - f s
where f s = sum $ map (\(i,m,v) -> lnormalInvWishartSS i m v) s
ss :: X -> Partition -> [Sstat]
ss x part = zip3 csizes scatters means
where csizes = componentSizes part
scatters = map scatterMatrix xs
means = map meanv xs
xs = groups x part
ss' :: X -> Partition -> [Sstat] -> Partition -> [Sstat]
ss' x par s npar = map go $ zip3 (p par) s (p npar)
where go (c1, s, c2)
| c1 == c2 = s
| otherwise = updateSstat x c1 s c2
ssComponent :: X -> [Int] -> Sstat
ssComponent x []= (0, konst 0 (d,d), konst 0 d)
where d = dim $ head x
ssComponent x c = (length c, scatterMatrix xs, meanv xs)
where xs = group x c
updateSstat :: X -> [Int] -> Sstat -> [Int] -> Sstat
updateSstat x c1 s c2 = (s <-> removed) <+> added
where removed = (ssComponent x (c1\\c2))
added = (ssComponent x (c2\\c1))
gmmElement :: X -> Int -> Int -> Int -> Partition
gmmElement x seed k num = p
where State (p,_) = getElement gen x start num
gen = mkStdGen seed
start = State (startP, ss x startP)
startP = naiveFromNk n k
n = length x
time :: IO t -> IO t
time a = do
start <- getCPUTime
v <- a
end <- getCPUTime
let diff = (fromIntegral (end - start)) / (10^12)
printf "Computation time: %0.3f sec\n" (diff :: Double)
return v
-- Main
main = do
--contents <- readFile "../../Data/AccidentData.csv"
--contents <- readFile "../../Data/2Clusters.csv"
--contents <- readFile "../../Data/synthetic.6clust.csv"
contents <- readFile "../../Data/synth2c2d.csv"
let num_Components = 2
num_Samples = 4000
stdData = p2NormList contents
result = gmmElement stdData 1 num_Components
p a = plot X11 $ plotClusters stdData a
--Plot Data
putStrLn "Starting..."
time $ p (result num_Samples)
putStrLn "Done."
|
juliankopkalarsen/FpStats
|
GMM/src/Main.hs
|
Haskell
|
mit
| 3,730
|
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-import-lists #-}
{-# OPTIONS_GHC -fno-warn-implicit-prelude #-}
module Paths_robot_simulator (
version,
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
#if defined(VERSION_base)
#if MIN_VERSION_base(4,0,0)
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#else
catchIO :: IO a -> (Exception.Exception -> IO a) -> IO a
#endif
#else
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
#endif
catchIO = Exception.catch
version :: Version
version = Version [1,0,0,3] []
bindir, libdir, dynlibdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/bin"
libdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/lib/x86_64-osx-ghc-8.0.2/robot-simulator-1.0.0.3-KwygUXUpzGA9nJtpp5aRKY"
dynlibdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/lib/x86_64-osx-ghc-8.0.2"
datadir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/share/x86_64-osx-ghc-8.0.2/robot-simulator-1.0.0.3"
libexecdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/libexec"
sysconfdir = "/Users/c19/Documents/projects/exercism/haskell/haskell/robot-simulator/.stack-work/install/x86_64-osx/lts-8.21/8.0.2/etc"
getBinDir, getLibDir, getDynLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "robot_simulator_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "robot_simulator_libdir") (\_ -> return libdir)
getDynLibDir = catchIO (getEnv "robot_simulator_dynlibdir") (\_ -> return dynlibdir)
getDataDir = catchIO (getEnv "robot_simulator_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "robot_simulator_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "robot_simulator_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
|
c19/Exercism-Haskell
|
robot-simulator/.stack-work/dist/x86_64-osx/Cabal-1.24.2.0/build/autogen/Paths_robot_simulator.hs
|
Haskell
|
mit
| 2,476
|
module Nauva.CSS
( module X
) where
import Nauva.CSS.Helpers as X
import Nauva.CSS.Terms as X
import Nauva.CSS.Typeface as X
import Nauva.CSS.Types as X
|
wereHamster/nauva
|
pkg/hs/nauva-css/src/Nauva/CSS.hs
|
Haskell
|
mit
| 169
|
module Main where
import qualified Graphics.UI.SDL as SDL
import Reactive.Banana
import Reactive.Banana.Frameworks (actuate)
import Reactive.Banana.SDL
import Hage.Graphics
import Hage.Game.Arkanoid.EventNetwork
main :: IO ()
main = do
sdlES <- getSDLEventSource
gd <- initGraphics
network <- compile $ setupNetwork sdlES gd
actuate network
runCappedSDLPump 60 sdlES
SDL.quit
|
Hinidu/Arkanoid
|
src/Hage/Game/Arkanoid.hs
|
Haskell
|
mit
| 403
|
{-# LANGUAGE NoImplicitPrelude, PackageImports #-}
module Test where
import "base-compat-batteries" Data.Ratio.Compat
|
haskell-compat/base-compat
|
check/check-hs/Data.Ratio.Compat.check.hs
|
Haskell
|
mit
| 118
|
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
That line was so long
Phew
|
ke00n/alabno
|
backend/linter/testFiles/longLineFile.hs
|
Haskell
|
mit
| 156
|
-- Converts .lhs (literary Haskell files) to .hs (plain Haskell files)
-- Keeps only the statements which are normally compiled, plus blank lines.
-- To use:
-- ghc --make lhs2hs.hs
-- to get an executable file lhs2hs.
-- Then
-- lhs2hs filename
-- will open filename.lhs and save the converted file in filename.hs
-- by Scot Drysdale on 7/28/07, based on SOE program on p. 241
module Main where
import System.IO
import System.Environment -- to allow getArgs
-- Opens a file, given name and mode
openGivenFile :: String -> IOMode -> IO Handle
openGivenFile name mode
= do handle <- openFile name mode
return handle
main = do args <- getArgs
fromHandle <- openGivenFile (args !! 0 ++ ".lhs") ReadMode
toHandle <- openGivenFile (args !! 0 ++ ".hs") WriteMode
convertFile fromHandle toHandle
hClose fromHandle
hClose toHandle
-- Converts all the lines in a file
convertFile :: Handle -> Handle -> IO ()
convertFile fromHandle toHandle
= do line <- hGetLine fromHandle
case line of
('>' : ' ' : rest) -> hPutStrLn toHandle rest
('>' : rest) -> hPutStrLn toHandle rest
('\n' : rest) -> hPutStrLn toHandle line
('\r' : rest) -> hPutStrLn toHandle line
_ -> return ()
convertFile fromHandle toHandle
|
AlexMckey/FP101x-ItFP_Haskell
|
Sources/lhs2hs_.hs
|
Haskell
|
cc0-1.0
| 1,360
|
myLength :: [t] -> Int
myLength [] = 0
myLength (x:xs) = myLength xs + 1
|
alephnil/h99
|
04.hs
|
Haskell
|
apache-2.0
| 72
|
{-# LANGUAGE BangPatterns #-}
module Database.VCache.VRef
( VRef
, vref, deref
, vref', deref'
, unsafeVRefAddr
, unsafeVRefRefct
, vref_space
, CacheMode(..)
, vrefc, derefc
, withVRefBytes
, unsafeVRefEncoding
) where
import Control.Monad
import Data.IORef
import Data.Bits
import Data.Word
import Data.ByteString (ByteString)
import Foreign.Ptr
import Foreign.Storable
import System.IO.Unsafe
import Database.VCache.Types
import Database.VCache.Alloc
import Database.VCache.Read
-- | Construct a reference with the cache initially active, i.e.
-- such that immediate deref can access the value without reading
-- from the database. The given value will be placed in the cache
-- unless the same vref has already been constructed.
vref :: (VCacheable a) => VSpace -> a -> VRef a
vref = vrefc CacheMode1
{-# INLINE vref #-}
-- | Construct a VRef with an alternative cache control mode.
vrefc :: (VCacheable a) => CacheMode -> VSpace -> a -> VRef a
vrefc cm vc v = unsafePerformIO (newVRefIO vc v cm)
{-# INLINABLE vrefc #-}
-- | In some cases, developers can reasonably assume they won't need a
-- value in the near future. In these cases, use the vref' constructor
-- to allocate a VRef without caching the content.
vref' :: (VCacheable a) => VSpace -> a -> VRef a
vref' vc v = unsafePerformIO (newVRefIO' vc v)
{-# INLINABLE vref' #-}
readVRef :: VRef a -> IO (a, Int)
readVRef v = readAddrIO (vref_space v) (vref_addr v) (vref_parse v)
{-# INLINE readVRef #-}
-- | Dereference a VRef, obtaining its value. If the value is not in
-- cache, it will be read into the database then cached. Otherwise,
-- the value is read from cache and the cache is touched to restart
-- any expiration.
--
-- Assuming a valid VCacheable instance, this operation should return
-- an equivalent value as was used to construct the VRef.
deref :: VRef a -> a
deref = derefc CacheMode1
{-# INLINE deref #-}
-- | Dereference a VRef with an alternative cache control mode.
derefc :: CacheMode -> VRef a -> a
derefc cm v = unsafeDupablePerformIO $
unsafeInterleaveIO (readVRef v) >>= \ lazy_read_rw ->
join $ atomicModifyIORef (vref_cache v) $ \case
Cached r bf ->
let bf' = touchCache cm bf in
let c' = Cached r bf' in
(c', c' `seq` return r)
NotCached ->
let (r,w) = lazy_read_rw in
let c' = mkVRefCache r w cm in
let op = initVRefCache v >> return r in
(c', c' `seq` op)
{-# NOINLINE derefc #-}
-- | Dereference a VRef. This will read from the cache if the value
-- is available, but will not update the cache. If the value is not
-- cached, it will be read instead from the persistence layer.
--
-- This can be useful if you know you'll only dereference a value
-- once for a given task, or if the datatype involved is cheap to
-- parse (e.g. simple bytestrings) such that there isn't a strong
-- need to cache the parse result.
deref' :: VRef a -> a
deref' v = unsafePerformIO $
readIORef (vref_cache v) >>= \case
Cached r _ -> return r
NotCached -> fmap fst (readVRef v)
{-# INLINABLE deref' #-}
-- | Specialized, zero-copy access to a `VRef ByteString`. Access to
-- the given ByteString becomes invalid after returning. This operation
-- may also block the writer if it runs much longer than a single
-- writer batch (though, writer batches are frequently large enough
-- that this shouldn't be a problem if you're careful).
--
withVRefBytes :: VRef ByteString -> (Ptr Word8 -> Int -> IO a) -> IO a
withVRefBytes v action = unsafeVRefEncoding v $ \ p n ->
-- valid ByteString encoding: varNat, bytes, 0 (children)
readVarNat p 0 >>= \ (p', n') ->
let bOK = (p' `plusPtr` n') == (p `plusPtr` (n-1)) in
let eMsg = show v ++ " doesn't contain a ByteString" in
unless bOK (fail $ "withVRefBytes: " ++ eMsg) >>
action p' n'
readVarNat :: Ptr Word8 -> Int -> IO (Ptr Word8, Int)
readVarNat !p !n =
peek p >>= \ w8 ->
let p' = p `plusPtr` 1 in
let n' = (n `shiftL` 7) + fromIntegral (w8 .&. 0x7f) in
let bDone = (0 == (w8 .&. 0x80)) in
if bDone then return (p', n') else
readVarNat p' n'
-- | Zero-copy access to the raw encoding for any VRef. The given data
-- becomes invalid after returning. This is provided for mostly for
-- debugging purposes, i.e. so you can peek under the hood and see how
-- things are encoded or eyeball the encoding.
unsafeVRefEncoding :: VRef any -> (Ptr Word8 -> Int -> IO a) -> IO a
unsafeVRefEncoding v = withBytesIO (vref_space v) (vref_addr v)
{-# INLINE unsafeVRefEncoding #-}
-- | Each VRef has an numeric address in the VSpace. This address is
-- non-deterministic, and essentially independent of the arguments to
-- the vref constructor. This function is 'unsafe' in the sense that
-- it violates the illusion of purity. However, the VRef address will
-- be stable so long as the developer can guarantee it is reachable.
--
-- This function may be useful for memoization tables and similar.
--
-- The 'Show' instance for VRef will also show the address.
unsafeVRefAddr :: VRef a -> Address
unsafeVRefAddr = vref_addr
{-# INLINE unsafeVRefAddr #-}
-- | This function allows developers to access the reference count
-- for the VRef that is currently recorded in the database. This may
-- be useful for heuristic purposes. However, caveats are needed:
--
-- First, due to structure sharing, a VRef may share an address with
-- VRefs of other types having the same serialized form. Reference
-- counts are at the address level.
--
-- Second, because the VCache writer operates in a background thread,
-- the reference count returned here may be slightly out of date.
--
-- Third, it is possible that VCache will eventually use some other
-- form of garbage collection than reference counting. This function
-- should be considered an unstable element of the API.
unsafeVRefRefct :: VRef a -> IO Int
unsafeVRefRefct v = readRefctIO (vref_space v) (vref_addr v)
{-# INLINE unsafeVRefRefct #-}
|
dmbarbour/haskell-vcache
|
hsrc_lib/Database/VCache/VRef.hs
|
Haskell
|
bsd-2-clause
| 6,043
|
module RuntimeProcessManager (withRuntimeProcess) where
import JavaUtils (getClassPath)
import StringPrefixes (namespace)
import System.IO (Handle, hSetBuffering, BufferMode(..))
import System.Process
withRuntimeProcess :: String -> BufferMode -> ((Handle,Handle) -> IO a) -> Bool -> IO a
withRuntimeProcess class_name buffer_mode do_this loadPrelude
= do cp <- if loadPrelude then return "runtime/runtime.jar" else getClassPath
let p = (proc "java" ["-cp", cp, namespace ++ class_name, cp])
{std_in = CreatePipe, std_out = CreatePipe}
(Just inP, Just outP, _, proch) <- createProcess p
hSetBuffering inP buffer_mode
hSetBuffering outP buffer_mode
result <- do_this (inP, outP)
terminateProcess proch
return result
|
bixuanzju/fcore
|
lib/services/RuntimeProcessManager.hs
|
Haskell
|
bsd-2-clause
| 797
|
{- Copyright (c) 2008 David Roundy
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.
3. 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 THE AUTHORS ``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 AUTHORS 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 Distribution.Franchise.ListUtils
( stripPrefix, stripSuffix, endsWithOneOf, commaWords ) where
import Data.List ( isSuffixOf )
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
stripPrefix [] ys = Just ys
stripPrefix (x:xs) (y:ys) | x == y = stripPrefix xs ys
stripPrefix _ _ = Nothing
stripSuffix :: Eq a => [a] -> [a] -> Maybe [a]
stripSuffix x y = reverse `fmap` stripPrefix (reverse x) (reverse y)
-- | Checks if a string ends with any given suffix
endsWithOneOf :: [String] -- ^ List of strings to check
-> String -- ^ String to check against
-> Bool
endsWithOneOf xs y = any (`isSuffixOf` y) xs
commaWords :: [String] -> String
commaWords [] = ""
commaWords [x] = x
commaWords (x:xs) = x++", "++commaWords xs
|
droundy/franchise
|
Distribution/Franchise/ListUtils.hs
|
Haskell
|
bsd-3-clause
| 2,222
|
module HsImport.Types where
import qualified Language.Haskell.Exts as HS
type SrcLine = Int
type SrcColumn = Int
type SrcSpan = HS.SrcSpan
type SrcLoc = HS.SrcLoc
type Annotation = (HS.SrcSpanInfo, [HS.Comment])
type Decl = HS.Decl Annotation
type ImportDecl = HS.ImportDecl Annotation
type ImportSpec = HS.ImportSpec Annotation
type ImportSpecList = HS.ImportSpecList Annotation
type Name = HS.Name Annotation
type CName = HS.CName Annotation
type Module = HS.Module Annotation
type ModuleName = String
type ErrorMessage = String
data ParseResult = ParseResult
{ -- | the parse result
result :: HS.ParseResult Module
-- | if the source file isn't completely parsable, because e.g.
-- it contains incomplete Haskell code, then 'lastValidLine'
-- contains the last line till the source is parsable
, lastValidLine :: Maybe Int
}
firstSrcLine :: Annotation -> SrcLine
firstSrcLine = minimum . map HS.srcSpanStartLine . srcSpans
lastSrcLine :: Annotation -> SrcLine
lastSrcLine = maximum . map HS.srcSpanEndLine . srcSpans
firstSrcColumn :: Annotation -> SrcColumn
firstSrcColumn = minimum . map HS.srcSpanStartColumn . srcSpans
lastSrcColumn :: Annotation -> SrcColumn
lastSrcColumn = maximum . map HS.srcSpanEndColumn . srcSpans
srcSpan :: Annotation -> SrcSpan
srcSpan ann@(HS.SrcSpanInfo srcSpan _, _) =
srcSpan { HS.srcSpanStartLine = firstSrcLine ann
, HS.srcSpanStartColumn = firstSrcColumn ann
, HS.srcSpanEndLine = lastSrcLine ann
, HS.srcSpanEndColumn = lastSrcColumn ann
}
srcSpans :: Annotation -> [SrcSpan]
srcSpans (HS.SrcSpanInfo srcSpan _, comments) = srcSpan : commentSrcSpans
where
commentSrcSpans = map (\(HS.Comment _ srcSpan _) -> srcSpan) comments
noAnnotation :: Annotation
noAnnotation = (HS.noSrcSpan, [])
|
dan-t/hsimport
|
lib/HsImport/Types.hs
|
Haskell
|
bsd-3-clause
| 1,919
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Elm.Package.Description where
import Prelude hiding (read)
import Control.Applicative ((<$>))
import Control.Arrow (first)
import Control.Monad.Trans (MonadIO, liftIO)
import Control.Monad.Error.Class (MonadError, throwError)
import Control.Monad (when, mzero, forM)
import Data.Aeson
import Data.Aeson.Types (Parser)
import Data.Aeson.Encode.Pretty (encodePretty', defConfig, confCompare, keyOrder)
import qualified Data.ByteString.Lazy.Char8 as BS
import qualified Data.HashMap.Strict as Map
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Data.Text as T
import System.FilePath ((</>), (<.>))
import System.Directory (doesFileExist)
import qualified Elm.Compiler.Module as Module
import qualified Elm.Package as Package
import qualified Elm.Package.Constraint as C
import qualified Elm.Package.Paths as Path
import Elm.Utils ((|>))
data Description = Description
{ name :: Package.Name
, repo :: String
, version :: Package.Version
, elmVersion :: C.Constraint
, summary :: String
, license :: String
, sourceDirs :: [FilePath]
, exposed :: [Module.Name]
, natives :: Bool
, dependencies :: [(Package.Name, C.Constraint)]
}
defaultDescription :: Description
defaultDescription =
Description
{ name = Package.Name "USER" "PROJECT"
, repo = "https://github.com/USER/PROJECT.git"
, version = Package.initialVersion
, elmVersion = C.defaultElmVersion
, summary = "helpful summary of your project, less than 80 characters"
, license = "BSD3"
, sourceDirs = [ "." ]
, exposed = []
, natives = False
, dependencies = []
}
-- READ
read :: (MonadIO m, MonadError String m) => FilePath -> m Description
read path =
do json <- liftIO (BS.readFile path)
case eitherDecode json of
Left err ->
throwError $ "Error reading file " ++ path ++ ":\n " ++ err
Right ds ->
return ds
-- WRITE
write :: Description -> IO ()
write description =
BS.writeFile Path.description json
where
json = prettyJSON description
-- FIND MODULE FILE PATHS
locateExposedModules :: (MonadIO m, MonadError String m) => Description -> m [(Module.Name, FilePath)]
locateExposedModules desc =
mapM locate (exposed desc)
where
locate modul =
let path = Module.nameToPath modul <.> "elm"
dirs = sourceDirs desc
in
do possibleLocations <-
forM dirs $ \dir -> do
exists <- liftIO $ doesFileExist (dir </> path)
return (if exists then Just (dir </> path) else Nothing)
case Maybe.catMaybes possibleLocations of
[] ->
throwError $
unlines
[ "Could not find exposed module '" ++ Module.nameToString modul ++ "' when looking through"
, "the following source directories:"
, concatMap ("\n " ++) dirs
, ""
, "You may need to add a source directory to your " ++ Path.description ++ " file."
]
[location] ->
return (modul, location)
locations ->
throwError $
unlines
[ "I found more than one module named '" ++ Module.nameToString modul ++ "' in the"
, "following locations:"
, concatMap ("\n " ++) locations
, ""
, "Module names must be unique within your package."
]
-- JSON
prettyJSON :: Description -> BS.ByteString
prettyJSON description =
prettyAngles (encodePretty' config description)
where
config =
defConfig { confCompare = keyOrder (normalKeys ++ dependencyKeys) }
normalKeys =
[ "version"
, "summary"
, "repository"
, "license"
, "source-directories"
, "exposed-modules"
, "native-modules"
, "dependencies"
, "elm-version"
]
dependencyKeys =
dependencies description
|> map fst
|> List.sort
|> map (T.pack . Package.toString)
prettyAngles :: BS.ByteString -> BS.ByteString
prettyAngles string =
BS.concat $ replaceChunks string
where
replaceChunks str =
let (before, after) = BS.break (=='\\') str
in
case BS.take 6 after of
"\\u003e" -> before : ">" : replaceChunks (BS.drop 6 after)
"\\u003c" -> before : "<" : replaceChunks (BS.drop 6 after)
"" -> [before]
_ ->
before : "\\" : replaceChunks (BS.tail after)
instance ToJSON Description where
toJSON d =
object $
[ "repository" .= repo d
, "version" .= version d
, "summary" .= summary d
, "license" .= license d
, "source-directories" .= sourceDirs d
, "exposed-modules" .= exposed d
, "dependencies" .= jsonDeps (dependencies d)
, "elm-version" .= elmVersion d
] ++ if natives d then ["native-modules" .= True] else []
where
jsonDeps deps =
Map.fromList $ map (first (T.pack . Package.toString)) deps
instance FromJSON Description where
parseJSON (Object obj) =
do version <- get obj "version" "your project's version number"
elmVersion <- getElmVersion obj
summary <- get obj "summary" "a short summary of your project"
when (length summary >= 80) $
fail "'summary' must be less than 80 characters"
license <- get obj "license" "license information (BSD3 is recommended)"
repo <- get obj "repository" "a link to the project's GitHub repo"
name <- case repoToName repo of
Left err -> fail err
Right nm -> return nm
exposed <- get obj "exposed-modules" "a list of modules exposed to users"
sourceDirs <- get obj "source-directories" "the directories that hold source code"
deps <- getDependencies obj
natives <- maybe False id <$> obj .:? "native-modules"
return $ Description name repo version elmVersion summary license sourceDirs exposed natives deps
parseJSON _ = mzero
get :: FromJSON a => Object -> T.Text -> String -> Parser a
get obj field desc =
do maybe <- obj .:? field
case maybe of
Just value ->
return value
Nothing ->
fail $
"Missing field " ++ show field ++ ", " ++ desc ++ ".\n" ++
" Check out an example " ++ Path.description ++ " file here:\n" ++
" <https://raw.githubusercontent.com/evancz/elm-html/master/elm-package.json>"
getDependencies :: Object -> Parser [(Package.Name, C.Constraint)]
getDependencies obj =
do deps <- get obj "dependencies" "a listing of your project's dependencies"
forM (Map.toList deps) $ \(rawName, rawConstraint) ->
case (Package.fromString rawName, C.fromString rawConstraint) of
(Just name, Just constraint) ->
return (name, constraint)
(Nothing, _) ->
fail (Package.errorMsg rawName)
(_, Nothing) ->
fail (C.errorMessage rawConstraint)
getElmVersion :: Object -> Parser C.Constraint
getElmVersion obj =
do rawConstraint <- get obj "elm-version" elmVersionDescription
case C.fromString rawConstraint of
Just constraint ->
return constraint
Nothing ->
fail (C.errorMessage rawConstraint)
elmVersionDescription :: String
elmVersionDescription =
"acceptable versions of the Elm Platform (e.g. \""
++ C.toString C.defaultElmVersion ++ "\")"
repoToName :: String -> Either String Package.Name
repoToName repo =
if not (end `List.isSuffixOf` repo)
then Left msg
else
do path <- getPath
let raw = take (length path - length end) path
case Package.fromString raw of
Nothing -> Left msg
Just name -> Right name
where
getPath
| http `List.isPrefixOf` repo = Right $ drop (length http ) repo
| https `List.isPrefixOf` repo = Right $ drop (length https) repo
| otherwise = Left msg
http = "http://github.com/"
https = "https://github.com/"
end = ".git"
msg =
"the 'repository' field must point to a GitHub project for now, something\n\
\like <https://github.com/USER/PROJECT.git> where USER is your GitHub name\n\
\and PROJECT is the repo you want to upload."
|
laszlopandy/elm-package
|
src/Elm/Package/Description.hs
|
Haskell
|
bsd-3-clause
| 8,771
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-|
Module : Numeric.AERN.RealArithmetic.Basis.Double.Measures
Description : distance between Double numbers
Copyright : (c) Michal Konecny
License : BSD3
Maintainer : mikkonecny@gmail.com
Stability : experimental
Portability : portable
Distance between Double numbers.
This is a private module reexported publicly via its parent.
-}
module Numeric.AERN.RealArithmetic.Basis.Double.Measures where
import Numeric.AERN.RealArithmetic.Basis.Double.NumericOrder
import Numeric.AERN.RealArithmetic.Basis.Double.FieldOps
import qualified Numeric.AERN.RealArithmetic.RefinementOrderRounding as ArithInOut
import Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators
import Numeric.AERN.RealArithmetic.ExactOps
import Numeric.AERN.RealArithmetic.Measures
import Numeric.AERN.RealArithmetic.Interval.Double
import Numeric.AERN.Basics.Interval
instance HasDistance Double where
type Distance Double = DI
type DistanceEffortIndicator Double = ArithInOut.AddEffortIndicator DI
distanceDefaultEffort d = ArithInOut.addDefaultEffort (sampleDI :: DI)
distanceBetweenEff effort d1 d2 =
-- | d1 == 1/0 && d2 == 1/0 = zero
-- -- distance between two infinities is zero (beware: distance not continuous at infinities!)
-- | d1 == -1/0 && d2 == -1/0 = zero
-- | otherwise =
ArithInOut.absOut (d2I <-> d1I)
where
d1I = Interval d1 d1
d2I = Interval d2 d2
|
michalkonecny/aern
|
aern-double/src/Numeric/AERN/RealArithmetic/Basis/Double/Measures.hs
|
Haskell
|
bsd-3-clause
| 1,576
|
{- |
Module : <Onping.Tag.Report>
Description : <Executable for Onping Tag Report >
Copyright : (c) <Plow Technology 2014>
License : <MIT>
Maintainer : <lingpo.huang@plowtech.net>
Stability : unstable
Portability : portable
<Grab a company by its name and generate reports for all its sites , locations and tags.>
-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module Onping.Tag.Report where
-- General
import Data.Text (Text)
-- Database
import Plowtech.Persist.Settings
import Database.Persist
import Plowtech.Request.Haxl (PlowStateStore)
import qualified Plowtech.Request.Haxl as Haxl
import qualified Plowtech.Request.Haxl.Company as Haxl
import qualified Plowtech.Request.Haxl.Location as Haxl
import qualified Plowtech.Request.Haxl.OnpingTagCombined as Haxl
import qualified Plowtech.Request.Haxl.Site as Haxl
-- String Template
import Text.StringTemplate
data ReportStyle = HTML | CSV
-- Output Format
-- # Onping Register Report
-- ## Company: <company name>
-- ## Site: <site name>
-- ### Location: <location name> SlaveId: <locationSlaveId>
-- #### <location name> Parameter Tags
-- <table>
-- <tr>
-- <th>Tag Name</th> , <th>Slave Parameter Id </th>, <th>Parameter Tag ID</th>
-- <tr>
-- <tag name>, <slave_parameter_id>, <parameter tag Id>
-- fetchCompanies :: PlowStateStore -> Text -> IO [Company]
fetchCompanies :: PlowStateStore -> Text -> IO [Company]
fetchCompanies plowStateStore companyName' = do
companyEntities <- Haxl.runHaxlWithPlowState plowStateStore $ Haxl.getCompaniesByName [companyName']
return $ entityVal <$> companyEntities
fetchSites :: PlowStateStore -> Int -> IO [Site]
fetchSites plowStateStore companyId = do
siteEntities <- Haxl.runHaxlWithPlowState plowStateStore $ Haxl.getSitesByCompanyIdRefs [companyId]
return $ entityVal <$> siteEntities
fetchLocations :: PlowStateStore -> Int -> IO [Location]
fetchLocations plowStateStore siteId = do
locationEntities <- Haxl.runHaxlWithPlowState plowStateStore $ Haxl.getLocationsByAltKeys altkeys
return $ entityVal <$> locationEntities
where
altkeys = Haxl.LocationLookupId Nothing [] [siteId]
fetchOnpingTagCombineds :: PlowStateStore -> Int -> IO [OnpingTagCombined]
fetchOnpingTagCombineds plowStateStore locationId = do
otcEntities <- Haxl.runHaxlWithPlowState plowStateStore $ Haxl.getParametersByAltKeys altkeys
return otcEntities
where
altkeys = Haxl.ParameterLookupId [locationId] [] []
buildOTCSTemplate :: OnpingTagCombined -> String
buildOTCSTemplate otc = render otcSTemplate
where otcName = onpingTagCombinedDescription otc
otcSlaveParameterId = onpingTagCombinedSlave_parameter_id otc
otcParameterTagId = onpingTagCombinedParameter_tag_id otc
otcPID = onpingTagCombinedPid otc
baseTemplate = (newSTMP "<tr><td>$pid$</td><td>$tag_name$</td> <td>$slave_parameter_id$</td> <td>$parameter_tag_Id$</td></tr>") :: StringTemplate String
otcSTemplate = setAttribute "tag_name" otcName .
setAttribute "slave_parameter_id" otcSlaveParameterId .
setAttribute "parameter_tag_Id" otcParameterTagId .
setAttribute "pid" otcPID $ baseTemplate
buildTableSTemplate :: [OnpingTagCombined] -> String
buildTableSTemplate otcList = render tableSTemplate
where otcSTemplates = unlines $ buildOTCSTemplate <$> otcList
baseTemplate = (newSTMP "<table class='table table-condensed table-striped'> \n\
\<tr> \n\
\<th>Global Parameter Id </th> \n\
\<th>Tag Name</th> \n\
\<th>Slave Parameter Id </th> \n\
\<th>Parameter Tag ID</th> \n\
\</tr>\n\
\$otcSTemplate$\
\</table>") :: StringTemplate String
tableSTemplate = setAttribute "otcSTemplate" otcSTemplates $ baseTemplate
buildLocationTemplate :: PlowStateStore -> Location -> IO String
buildLocationTemplate plowStateStore l = do
otcList <- fetchOnpingTagCombineds plowStateStore (locationRefId l)
let tableTemplate = buildTableSTemplate otcList
locName = locationName l
locSlaveId = locationSlaveId l
baseTemplate = (newSTMP "\n### Location: $location_name$ SlaveId: $locationSlaveId$ \n\
\#### $location_name$ Parameter Tags \n\
\$tableTemplate$ \n") :: StringTemplate String
locationSTemplate = setAttribute "location_name" locName .
setAttribute "locationSlaveId" locSlaveId .
setAttribute "tableTemplate" tableTemplate $ baseTemplate
return $ render locationSTemplate
buildSiteTemplate :: PlowStateStore -> Site -> IO String
buildSiteTemplate plowStateStore s = do
locList <- fetchLocations plowStateStore (siteSiteIdRef s)
locationTemplates <- traverse (buildLocationTemplate plowStateStore ) locList
let sName = siteName s
baseTemplate = (newSTMP "\n## Site: $site_name$ \n\
\$location_template$ \n") :: StringTemplate String
siteSTemplate = setAttribute "site_name" sName .
setAttribute "location_template" (unlines locationTemplates) $ baseTemplate
return $ render siteSTemplate
buildCompanyTemplate :: PlowStateStore -> Text -> IO String
buildCompanyTemplate plowStateStore cName = do
companyList <- fetchCompanies plowStateStore cName
case companyList of
[] -> return "Error: There is no company records match the name given."
_ -> do
siteList <-fetchSites plowStateStore (companyCompanyIdRef . head $ companyList)
siteTemplates <- traverse (buildSiteTemplate plowStateStore ) siteList
let baseTemplate = (newSTMP "<head>\n\
\<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>\n\
\</head>\n\n\
\# Onping Register Report \n\n\
\## Company: $company_name$ \n\n\
\$site_template$ \n") :: StringTemplate String
companySTemplate = setAttribute "company_name" cName .
setAttribute "site_template" (unlines siteTemplates) $ baseTemplate
return $ render companySTemplate
-- --------------------------------------------------
buildOTCSTemplateCSV :: Text -> Text -> Text -> OnpingTagCombined -> String
buildOTCSTemplateCSV cName sName locName otc = render otcSTemplate
where otcName = onpingTagCombinedDescription otc
otcSlaveParameterId = onpingTagCombinedSlave_parameter_id otc
otcParameterTagId = onpingTagCombinedParameter_tag_id otc
otcPID = onpingTagCombinedPid otc
baseTemplate = (newSTMP "$company_name$ | $site_name$ | $location_name$ | $pid$ | $tag_name$ | $slave_parameter_id$ | $parameter_tag_Id$ \n") :: StringTemplate String
otcSTemplate = setAttribute "tag_name" otcName .
setAttribute "slave_parameter_id" otcSlaveParameterId .
setAttribute "parameter_tag_Id" otcParameterTagId .
setAttribute "company_name" cName.
setAttribute "site_name" sName.
setAttribute "location_name" locName.
setAttribute "pid" otcPID $ baseTemplate
buildTableSTemplateCSV :: Text -> Text -> Text -> [OnpingTagCombined] -> String
buildTableSTemplateCSV cName sName lName otcList = render tableSTemplate
where otcSTemplates = unlines $ buildOTCSTemplateCSV cName sName lName <$> otcList
baseTemplate = (newSTMP "$otcSTemplate$ \n") :: StringTemplate String
tableSTemplate = setAttribute "otcSTemplate" otcSTemplates $ baseTemplate
buildLocationTemplateCSV :: PlowStateStore -> Text -> Text -> Location -> IO String
buildLocationTemplateCSV plowStateStore cName sName l = do
let locName = locationName l
otcList <- fetchOnpingTagCombineds plowStateStore (locationRefId l)
let tableTemplate = buildTableSTemplateCSV cName sName locName otcList
baseTemplate = (newSTMP "$tableTemplate$ \n") :: StringTemplate String
locationSTemplate = setAttribute "tableTemplate" tableTemplate $ baseTemplate
return $ render locationSTemplate
buildSiteTemplateCSV :: PlowStateStore -> Text -> Site -> IO String
buildSiteTemplateCSV plowStateStore cName s = do
let sName = siteName s
locList <- fetchLocations plowStateStore (siteSiteIdRef s)
locationTemplates <- traverse (buildLocationTemplateCSV plowStateStore cName sName) locList
let
baseTemplate = (newSTMP "$location_template$") :: StringTemplate String
siteSTemplate = setAttribute "location_template" (unlines locationTemplates) $ baseTemplate
return $ render siteSTemplate
buildCompanyTemplateCSV :: PlowStateStore -> Text -> IO String
buildCompanyTemplateCSV plowStateStore cName = do
companyList <- fetchCompanies plowStateStore cName
case companyList of
[] -> return "Error: There is no company records match the name given."
_ -> do
siteList <-fetchSites plowStateStore (companyCompanyIdRef . head $ companyList)
siteTemplates <- traverse (buildSiteTemplateCSV plowStateStore cName) siteList
let baseTemplate = (newSTMP "Company Name | Site Name | Location Name | Global Parameter Id | Tag Name | Slave Parameter Id | Parameter Tag ID \n $site_template$ \n") :: StringTemplate String
companySTemplate = setAttribute "company_name" cName .
setAttribute "site_template" (unlines siteTemplates) $ baseTemplate
return $ render companySTemplate
|
plow-technologies/onping-tag-report
|
src/Onping/Tag/Report.hs
|
Haskell
|
bsd-3-clause
| 10,288
|
module AI.MDP.GridWorld
(
GridWorld
,GridVal
,GridAction(..)
-- Debug/Visualization Funcs
,showRewards
,showAbsorbs
,showTransition
-- common action results
,deterministicActions
,maybeActions
,maybeReverseActions
,scatterActions
,BlockedCells
,MoveCost
,gridWorld
,reward
,absorb
,initVals
,iterVals
) where
import Text.Printf
import qualified Data.Vector as V
import Data.Vector(Vector, (//), (!))
import AI.MDP
data GridWorld = GridWorld { g_width :: !Int
, g_height :: !Int
, g_blocked :: Vector Bool
, g_mdp :: MDP
} deriving (Show, Eq)
data GridVal = GridVal { gv_gw :: GridWorld
, gv_vals :: !Values
}
renderGrid f g gv@(GridVal gw vs) = vbar ++ concatMap mkRow [0..(height-1)]
where mkRow i = showRow (V.slice (width*i) width (V.zip bs (f gv))) ++ vbar
showRow = (++ "\n") . foldl (\s x -> s ++ buildVal x ++ "|") "|" . V.toList
buildVal (False, v) = take valCellWidth $ g v ++ repeat ' '
buildVal (True, _) = take valCellWidth $ repeat '#'
valCellWidth = 5
vbar = replicate (1 + (valCellWidth+1) * width) '=' ++ "\n"
width = g_width gw
height = g_height gw
bs = g_blocked gw
showRewards gv = putStr $ renderGrid (rewards . g_mdp . gv_gw) (printf "%3.1f") gv
showAbsorbs gv = putStr $ renderGrid (absState . g_mdp . gv_gw) (\x -> case x of { True -> "X"; False -> " "; }) gv
showTransition (x, y) a gv = putStr $ renderGrid getTrans (printf "%3.1f") gv
where getTrans = ((! i) . (! actionI a) . transitions . g_mdp . gv_gw)
gw = gv_gw gv
w = g_width gw
h = g_height gw
i = y*w + x
instance Show GridVal where
show = renderGrid gv_vals (printf "%3.1f")
data GridAction = MoveW | MoveE | MoveN | MoveS | MoveNE | MoveNW | MoveSE | MoveSW | MoveNone deriving (Show, Eq, Ord)
actionI :: GridAction -> Int
actionI MoveW = 0
actionI MoveE = 1
actionI MoveN = 2
actionI MoveS = 3
actionI MoveNE = 4
actionI MoveNW = 5
actionI MoveSE = 6
actionI MoveSW = 7
actionI MoveNone = 8
-- ^ Gives the allowed actions and the results of executing it along with their probabilities
type ActionResult = [(GridAction, Probability)]
type ActionResults = [ActionResult] -- ^ implicit understanding: action results are in order
checkActionResult :: ActionResults -> Bool
checkActionResult = all (\n -> abs (n-1) < 1E10) . map (sum . map snd)
deterministicActions :: ActionResults
deterministicActions = [[(MoveW, 1)]
,[(MoveE, 1)]
,[(MoveN, 1)]
,[(MoveS, 1)]
,[(MoveNE, 1)]
,[(MoveNW, 1)]
,[(MoveSE, 1)]
,[(MoveSW, 1)]]
maybeReverseActions :: Probability -> ActionResults
maybeReverseActions p = [[(MoveW, p), (MoveE, p2)]
,[(MoveE, p), (MoveW, p2)]
,[(MoveN, p), (MoveS, p2)]
,[(MoveS, p), (MoveN, p2)]
,[(MoveNE, p), (MoveSW, p2)]
,[(MoveNW, p), (MoveSE, p2)]
,[(MoveSE, p), (MoveNW, p2)]
,[(MoveSW, p), (MoveNE, p2)]]
where p2 = 1-p
maybeActions :: Probability -> ActionResults
maybeActions p = [[(MoveW, p), (MoveNone, p2)]
,[(MoveE, p), (MoveNone, p2)]
,[(MoveN, p), (MoveNone, p2)]
,[(MoveS, p), (MoveNone, p2)]
,[(MoveNE, p), (MoveNone, p2)]
,[(MoveNW, p), (MoveNone, p2)]
,[(MoveSE, p), (MoveNone, p2)]
,[(MoveSW, p), (MoveNone, p2)]]
where p2 = 1-p
scatterActions :: Probability -> ActionResults
scatterActions p = [[(MoveW, p), (MoveNW, p2), (MoveSW, p2)]
,[(MoveE, p), (MoveNE, p2), (MoveSE, p2)]
,[(MoveN, p), (MoveNE, p2), (MoveNW, p2)]
,[(MoveS, p), (MoveSE, p2), (MoveSW, p2)]
,[(MoveNE, p), (MoveE, p2), (MoveN, p2)]
,[(MoveNW, p), (MoveW, p2), (MoveN, p2)]
,[(MoveSE, p), (MoveE, p2), (MoveS, p2)]
,[(MoveSW, p), (MoveW, p2), (MoveS, p2)]]
where p2 = (1-p)/2
type BlockedCells = [(Int, Int)]
type MoveCost = Double
gridWorld :: (Int, Int) -> Discount -> MoveCost -> ActionResults -> BlockedCells -> GridWorld
gridWorld (w, h) gamma moveCost actionRes blockedCells = GridWorld w h bs mdp
where numStates = w * h
mdp = MDP ts rs as gamma
rs = V.replicate numStates moveCost
as = V.replicate numStates False
nullT = V.replicate numStates 0.0
ts = V.fromList $ map mkActTrans actionRes
bs = V.replicate numStates False // map (\(x,y) -> (x*w + y, True)) blockedCells
mkActTrans ar = V.generate numStates (makeTrans w h bs ar nullT)
makeTrans :: Int -> Int -> Vector Bool -> ActionResult -> Vector Probability -> State -> Vector Probability
makeTrans w h bs ar vs s = V.accum (+) vs (map (\(a,p) -> (getI w h bs s a, p)) ar)
getI :: Int -> Int -> Vector Bool -> State -> GridAction -> State
getI w _ bs i MoveN | i < w || bs ! (i-w) = i
| otherwise = i - w
getI w h bs i MoveS | i >= (w*(h-2)) || bs ! (i+w) = i
| otherwise = i + w
getI w _ bs i MoveW | (i `mod` w) == 0 || bs ! (i-1) = i
| otherwise = i - 1
getI w _ bs i MoveE | (i `mod` w) == (w-1) || bs ! (i+1) = i
| otherwise = i + 1
getI w h bs i MoveNE = getI w h bs (getI w h bs i MoveN) MoveE
getI w h bs i MoveNW = getI w h bs (getI w h bs i MoveN) MoveW
getI w h bs i MoveSE = getI w h bs (getI w h bs i MoveS) MoveE
getI w h bs i MoveSW = getI w h bs (getI w h bs i MoveS) MoveW
getI _ _ _ i MoveNone = i
reward :: (Int, Int) -> Reward -> GridWorld -> GridWorld
reward (x, y) r g = g { g_mdp = mdp' }
where mdp = g_mdp g
w = g_width g
mdp' = mdp { rewards = rewards mdp // [((y * w + x), r)] }
absorb :: (Int, Int) -> Reward -> GridWorld -> GridWorld
absorb (x, y) r g = g { g_mdp = mdp' }
where mdp = g_mdp g
w = g_width g
mdp' = mdp { rewards = rewards mdp // [((y * w + x), r)]
, absState = absState mdp // [((y * w + x), True)] }
initVals :: GridWorld -> GridVal
initVals gw = GridVal gw vs
where vs = V.replicate (w*h) 0.0
w = g_width gw
h = g_height gw
type NumIters = Int
iterVals :: NumIters -> GridVal -> GridVal
iterVals 0 gv = gv
iterVals n (GridVal gw vs) = iterVals (n-1) $ GridVal gw vs'
where vs' = V.fromList $ map iter_ [0..(V.length vs -1)]
mdp = g_mdp gw
iter_ i = let r = rewards mdp ! i
g = discount mdp
t = transitions mdp
isAbsorbing = absState mdp ! i
doAction ts = V.sum (V.zipWith (*) (ts ! i) vs)
in if isAbsorbing
then r
else r + g * V.maximum (V.map doAction t)
|
chetant/mdp
|
AI/MDP/GridWorld.hs
|
Haskell
|
bsd-3-clause
| 7,273
|
{-# LANGUAGE OverloadedStrings, DeriveDataTypeable , NoMonomorphismRestriction #-}
import MFlow.Wai.Blaze.Html.All hiding (footer, retry, push)
import qualified MFlow.Wai.Blaze.Html.All as MF(retry)
import Control.Monad.Trans
import Data.Monoid
import Control.Applicative
import Control.Concurrent
import Control.Workflow as WF hiding (step)
import Control.Workflow.Stat
import Control.Concurrent.STM
import Data.Typeable
import Data.TCache.DefaultPersistence
import Data.Persistent.Collection
import Data.ByteString.Lazy.Char8(pack,unpack)
import Data.Map as M (fromList)
import Data.List(isPrefixOf)
import Data.Maybe
import Debug.Trace
import System.IO.Unsafe
(!>) = flip trace
--comprar o reservar
--no está en stock
--reservar libro
--si está en stock pasado un tiempo quitar la reserva
--si está en stock y reservado, comprar
data Book= Book{btitle :: String, stock,reserved :: Int} deriving (Read,Show, Eq,Typeable)
instance Indexable Book where key= btitle
instance Serializable Book where
serialize= pack. show
deserialize= read . unpack
keyBook= "booktitle" :: String
rbook= getDBRef $ keyBook
stm= liftIO . atomically
reservetime= 120 -- 5* 24 * 60 * 60 -- five days waiting for reserve and five days reserved
data RouteOptions= Buy | Other | Reserve | NoReserve deriving (Typeable,Show)
main= do
enterStock 30 rbook
restartWorkflows $ M.fromList [("buyreserve", buyReserve reservetime)]
runNavigation "" . transientNav $ do
op <- page $ absLink Buy "buy or reserve the book" <++ br <|> wlink Other "Do other things"
case op of
Other -> page $ "doing other things" ++> wlink () "home"
Buy -> do
reserved <- stm (do
mr <- readDBRef rbook !> "RESERVING"
case mr of
Nothing -> return False
Just r ->
if reserved r > 0 then return True
else if stock r > 0 then reserveIt rbook >> return True
else return False)
`compensate` (stm (unreserveIt rbook) >> fail "" !> "JUST")
if reserved then do
page $ buyIt keyBook
return() !> "buyit forward"
else reserveOffline keyBook
absLink ref = wcached (show ref) 0 . wlink ref
buyIt keyBook= do
mh <- getHistory "buyreserve" keyBook
p "there is one book for you in stock "
++> case mh of
Nothing -> p "The book was in stock and reserved online right now"
Just hist ->
let histmarkup= mconcat[p << l | l <- hist]
in h2 "History of your reserve:"
<> histmarkup
++> wlink keyBook "buy?"
`waction` (\ key -> do
stm . buy $ getDBRef key
page $ "bought! " ++> wlink () "home"
delWF "buyreserve" key)
<|> (absLink Buy undefined >> return())
reserveOffline keyBook = do
v <- getState "buyreserve" (buyReserve reservetime) keyBook
case v of
Left AlreadyRunning -> lookReserve keyBook
Left err -> error $ show err
Right (name, f, stat) -> do
r <- page $ wlink Reserve "not in stock. Press to reserve it when available in\
\ the next five days. It will be reserved for five days "
<|> br
++> wlink NoReserve "no thanks, go to home"
case r of
Reserve -> do
liftIO $ forkIO $ runWF1 name (buyReserve reservetime keyBook) stat True
return ()
NoReserve -> return()
lookReserve keyBook= do
hist <- getHistory "buyreserve" keyBook `onNothing ` return ["No workflow log"]
let histmarkup= mconcat[p << l | l <- hist]
page $ do
mr <- stm $ readDBRef rbook
if mr== Nothing
|| fmap stock mr == Just 0
&& fmap reserved mr == Just 0
then
"Sorry, not available but you already demanded a reservation when the book\
\ enter in stock"
++> wlink () << p "press here to go home if the book has not arrived"
<++ p "you can refresh or enter this url to verify availability"
<> h2 "status of your request for reservation upto now:"
<> histmarkup
else
h2 "Good! things changed: the book arrived and was reserved"
++> buyIt keyBook
compensate :: Monad m => FlowM v m a -> FlowM v m a -> FlowM v m a
compensate doit undoit= do
back <- goingBack
case back of
False -> doit >>= breturn
True -> undoit
withTimeoutIO flag f = liftIO $ atomically $ (f >> return True)
`orElse` (waitUntilSTM flag >> return False)
buyReserve timereserve keyBook= runFlowOnce f undefined where
f :: FlowM Html (Workflow IO) ()
f= do
let rbook = getDBRef keyBook
lift . logWF $ "You requested the reserve for: "++ keyBook
t <- lift $ getTimeoutFlag timereserve -- $ 5 * 24 * 60 * 60
r <- compensate (step $ withTimeoutIO t (reserveAndMailIt rbook))
(do
lift $ logWF "Unreserving the book"
step $ liftIO . atomically $ unreserveIt rbook >> fail "")
-- liftIO $ atomically $ (reserveAndMailIt rbook >> return True)
-- `orElse` (waitUntilSTM t >> return False)
if not r
then do
lift $ logWF "reservation period ended, no stock available"
return ()
else do
lift $ logWF "The book entered in stock, reserved "
t <- lift $ getTimeoutFlag timereserve -- $ 5 * 24 *60 * 60
r <- step . liftIO $ atomically $ (waitUntilSTM t >> return False)
`orElse` (testBought rbook >> return True)
if r
then do
lift $ logWF "Book was bought at this time"
else do
lift $ logWF "Reserved for a time, but reserve period ended"
fail ""
-- now it is compensated above
-- step . liftIO $ atomically $ unreserveIt rbook
userMail= "user@mail.com"
mailQueue= "mailqueue"
reserveAndMailIt rbook= do
let qref = getQRef mailQueue
pushSTM qref ( userMail :: String
, "your book "++ keyObjDBRef rbook ++ " received" :: String
, "Hello, your book...." :: String)
reserveIt rbook
reserveIt rbook = do
mr <- readDBRef rbook !> "RESERVE"
case mr of
Nothing -> retry
Just (Book t s r) ->
if s >0 then writeDBRef rbook $ Book t (s-1) (r+1)
else retry
unreserveIt rbook= do
mr <- readDBRef rbook !> "UNRESERVE"
case mr of
Nothing -> error "unreserveIt: where is the book?"
Just (Book t s r) ->
if r >0 then writeDBRef rbook $ Book t (s+1) (r-1)
else return()
enterStock delay rbook= forkIO $ loop enter
where
loop f= f >> loop f
enter= do
threadDelay $ delay * 1000000
atomically $ do
Book _ n r <- readDBRef rbook `onNothing` return (Book keyBook 0 0)
writeDBRef rbook $ Book "booktitle" (n +1) r
!> "Added 1 more book to the stock"
buy rbook= do
mr <- readDBRef rbook
case mr of
Nothing -> error "Not in stock"
Just (Book t n n') ->
if n' > 0 !> show mr then writeDBRef rbook $ Book t n (n'-1)
!> "There is in Stock and reserved, BOUGHT"
else if n > 0 then
writeDBRef rbook $ Book t (n-1) 0
!> "No reserved, but stock available, BOUGHT"
else error "buy: neither stock nor reserve"
testBought rbook= do
mr <- readDBRef rbook
case mr of
Nothing -> retry !> ("testbought: the register does not exist: " ++ show rbook)
Just (Book t stock reserve) ->
case reserve of
0 -> return()
n -> retry
stopRestart delay timereserve th= do
threadDelay $ delay * 1000000
killThread th !> "workflow KILLED"
syncCache
atomically flushAll
restartWorkflows ( fromList [("buyreserve", buyReserve timereserve)] ) !> "workflow RESTARTED"
getHistory name x= liftIO $ do
let wfname= keyWF name x
let key= keyResource stat0{wfName=wfname}
atomically $ flushKey key
mh <- atomically . readDBRef . getDBRef $ key
case mh of
Nothing -> return Nothing
Just h -> return . Just
. catMaybes
. map eitherToMaybe
. map safeFromIDyn
$ versions h :: IO (Maybe [String])
where
eitherToMaybe (Right r)= Just r
eitherToMaybe (Left _) = Nothing
|
agocorona/MFlow
|
tests/workflow1.hs
|
Haskell
|
bsd-3-clause
| 8,659
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Network.Mail.Locutoria.State where
import Control.Applicative ((<$>), pure)
import Control.Lens hiding (Index)
import Data.Default (def)
import Data.List (elemIndex, find)
import Data.Maybe (catMaybes, isJust, listToMaybe)
import Data.Text (Text)
import Network.Mail.Locutoria.Index hiding (_conversations, conversations)
import qualified Network.Mail.Locutoria.Index as Index
import Network.Mail.Locutoria.Message
import Network.Mail.Locutoria.Notmuch (Database)
import Network.Mail.Locutoria.Channel
import Network.Mail.Locutoria.Conversation
import Network.Mail.Locutoria.View
data State = State
{ _stDatabase :: Database
, _stIndex :: Index
, _stHistory :: History
, _stRefreshing :: Bool
, _stScreenSize :: (Int, Int)
, _stStatus :: Status
}
deriving (Eq, Show)
type History = [View]
data Status = GenericError Text
| Refreshing
| Nominal
deriving (Eq, Show)
makeLenses ''State
mkState :: Database -> State
mkState db = State
{ _stDatabase = db
, _stIndex = def
, _stHistory = []
, _stRefreshing = False
, _stScreenSize = (80, 50)
, _stStatus = Nominal
}
stView :: Lens' State View
stView f st = case st^.stHistory of
v:vs -> (\v' -> st & stHistory .~ (v':vs)) <$> f v
[] -> (\v' -> st & stHistory .~ (v':[])) <$> f Root
pushView :: View -> State -> State
pushView v = stHistory %~ (v:)
popView :: State -> State
popView = stHistory %~ drop 1
replaceView :: View -> State -> State
replaceView v = pushView v . popView
stChannel :: Traversal' State Channel
stChannel = stView . viewChannel
stConversation :: Traversal' State Conversation
stConversation f st = case conv of
Nothing -> pure st
Just c -> updateConv <$> f c
where
conv = case st ^. stView of
ShowChannel _ Nothing -> listToMaybe (stConversations st)
v -> v ^? viewConversation
updateConv c = case st ^. stView of
ShowChannel chan Nothing -> st & stView .~ ShowChannel chan (Just c)
_ -> st & stView . viewConversation .~ c
stMessage :: Traversal' State Message
stMessage f st = case msg of
Nothing -> pure st
Just m -> updateMsg <$> f m
where
msg = case st ^. stView of
ShowConversation _ _ Nothing -> listToMaybe (stMessages st)
v -> v ^? viewMessage
updateMsg m = case st ^. stView of
ShowConversation chan conv Nothing -> st & stView .~ ShowConversation chan conv (Just m)
_ -> st & stView . viewMessage .~ m
stChannelGroups :: State -> [ChannelGroup]
stChannelGroups s =
[ ChannelGroup "Direct" [NoListChannel]
, ChannelGroup "Flagged" [FlaggedChannel]
, ChannelGroup "Lists" ls
]
where
ls = ListChannel <$> lists (s^.stIndex)
stChannels :: State -> [Channel]
stChannels st = catMaybes $ flattenChannelGroups (stChannelGroups st)
stConversations :: State -> [Conversation]
stConversations st = case st ^? stChannel of
Just chan -> filter (inChannel chan) (st^.stIndex.Index.conversations)
Nothing -> []
stMessages :: State -> [Message]
stMessages st = case st ^? stConversation of
Just conv -> conv^.convMessages
Nothing -> []
stChannelIndex :: Traversal' State Int
stChannelIndex f st = case (idx, chan) of
(_, Nothing) -> pure st
(Nothing, _) -> pure st
(Just i, _) -> update <$> f i
where
update i' = case clampedLookup isJust i i' cs of
Just (Just chan') -> st & stChannel .~ chan'
_ -> st
where
chan = st ^? stChannel
cs = flattenChannelGroups $ stChannelGroups st
idx = flip elemIndex cs . Just =<< chan
stConversationIndex :: Traversal' State Int
stConversationIndex f st = case idx of
Nothing -> pure st
Just i -> update . clamp cs <$> f i
where
cs = st^.to stConversations
idx = flip elemIndex cs =<< st ^? stConversation
update idx' = case find (const True) (drop idx' cs) of
Just conv -> st & stConversation .~ conv
Nothing -> st
stMessageIndex :: Traversal' State Int
stMessageIndex f st = case idx of
Nothing -> pure st
Just i -> update . clamp ms <$> f i
where
ms = stMessages st
idx = flip elemIndex ms =<< st ^? stMessage
update idx' = case find (const True) (drop idx' ms) of
Just msg -> st & stMessage .~ msg
Nothing -> st
clamp :: [a] -> Int -> Int
clamp xs i = if i >= 0 then i `min` end else length xs - i `max` 0
where
end = length xs - 1
clampedLookup :: (a -> Bool) -> Int -> Int -> [a] -> Maybe a
clampedLookup p oldIdx newIdx xs = find p xs'
where
idx = if newIdx >= 0 && newIdx < oldIdx
then 0 - (length xs - newIdx)
else newIdx
xs' = if idx >= 0
then drop idx xs
else drop (0 - idx - 1) (reverse xs)
|
hallettj/locutoria
|
Network/Mail/Locutoria/State.hs
|
Haskell
|
bsd-3-clause
| 4,908
|
module Base (
-- * General utilities
module Control.Applicative,
module Control.Monad.Extra,
module Data.List.Extra,
module Data.Maybe,
module Data.Semigroup,
module Hadrian.Utilities,
-- * Shake
module Development.Shake,
module Development.Shake.Classes,
module Development.Shake.FilePath,
module Development.Shake.Util,
-- * Basic data types
module Hadrian.Package,
module Stage,
module Way,
-- * Files
configH, ghcVersionH,
-- * Paths
hadrianPath, configPath, configFile, sourcePath, shakeFilesDir,
generatedDir, generatedPath,
stageBinPath, stageLibPath,
templateHscPath, ghcDeps,
relativePackageDbPath, packageDbPath, packageDbStamp, ghcSplitPath
) where
import Control.Applicative
import Control.Monad.Extra
import Control.Monad.Reader
import Data.List.Extra
import Data.Maybe
import Data.Semigroup
import Development.Shake hiding (parallel, unit, (*>), Normal)
import Development.Shake.Classes
import Development.Shake.FilePath
import Development.Shake.Util
import Hadrian.Utilities
import Hadrian.Package
import Stage
import Way
-- | Hadrian lives in the 'hadrianPath' directory of the GHC tree.
hadrianPath :: FilePath
hadrianPath = "hadrian"
-- TODO: Move this to build directory?
-- | Path to system configuration files, such as 'configFile'.
configPath :: FilePath
configPath = hadrianPath -/- "cfg"
-- | Path to the system configuration file generated by the @configure@ script.
configFile :: FilePath
configFile = configPath -/- "system.config"
-- | Path to source files of the build system, e.g. this file is located at
-- @sourcePath -/- "Base.hs"@. We use this to track some of the source files.
sourcePath :: FilePath
sourcePath = hadrianPath -/- "src"
-- TODO: Change @mk/config.h@ to @shake-build/cfg/config.h@.
-- | Path to the generated @mk/config.h@ file.
configH :: FilePath
configH = "mk/config.h"
ghcVersionH :: Action FilePath
ghcVersionH = generatedPath <&> (-/- "ghcversion.h")
-- | The directory in 'buildRoot' containing the Shake database and other
-- auxiliary files generated by Hadrian.
shakeFilesDir :: FilePath
shakeFilesDir = "hadrian"
-- | The directory in 'buildRoot' containing generated source files that are not
-- package-specific, e.g. @ghcplatform.h@.
generatedDir :: FilePath
generatedDir = "generated"
generatedPath :: Action FilePath
generatedPath = buildRoot <&> (-/- generatedDir)
-- | Path to the package database for the given stage of GHC,
-- relative to the build root.
relativePackageDbPath :: Stage -> FilePath
relativePackageDbPath stage = stageString stage -/- "lib" -/- "package.conf.d"
-- | Path to the package database used in a given 'Stage', including
-- the build root.
packageDbPath :: Stage -> Action FilePath
packageDbPath stage = buildRoot <&> (-/- relativePackageDbPath stage)
-- | We use a stamp file to track the existence of a package database.
packageDbStamp :: FilePath
packageDbStamp = ".stamp"
-- | @bin@ directory for the given 'Stage' (including the build root)
stageBinPath :: Stage -> Action FilePath
stageBinPath stage = buildRoot <&> (-/- stageString stage -/- "bin")
-- | @lib@ directory for the given 'Stage' (including the build root)
stageLibPath :: Stage -> Action FilePath
stageLibPath stage = buildRoot <&> (-/- stageString stage -/- "lib")
-- | Files the `ghc` binary depends on
ghcDeps :: Stage -> Action [FilePath]
ghcDeps stage = mapM (\f -> stageLibPath stage <&> (-/- f))
[ "ghc-usage.txt"
, "ghci-usage.txt"
, "llvm-targets"
, "llvm-passes"
, "platformConstants"
, "settings" ]
-- ref: utils/hsc2hs/ghc.mk
-- | Path to 'hsc2hs' template.
templateHscPath :: Stage -> Action FilePath
templateHscPath stage = stageLibPath stage <&> (-/- "template-hsc.h")
-- | @ghc-split@ is a Perl script used by GHC when run with @-split-objs@ flag.
-- It is generated in "Rules.Generate". This function returns the path relative
-- to the build root under which we will copy @ghc-split@.
ghcSplitPath :: Stage -> FilePath
ghcSplitPath stage = stageString stage -/- "bin" -/- "ghc-split"
|
bgamari/shaking-up-ghc
|
src/Base.hs
|
Haskell
|
bsd-3-clause
| 4,129
|
{-# LANGUAGE RecordWildCards #-}
module Plot.Gauss where
import Types
import PatternRecogn.Gauss.Utils
import PatternRecogn.Utils
import PatternRecogn.Lina as Lina
import PatternRecogn.Gauss.Types
import Graphics.Rendering.Chart.Easy as Chart hiding( Matrix, Vector )
import Graphics.Rendering.Chart.Backend.Diagrams as Chart
-- plot 1-dim data and estimated propability measure (gaussian)
plotProjected :: FilePath -> Vector -> Classes -> ErrT IO ()
plotProjected path dots params =
do
_ <- lift $ Chart.renderableToFile def path $ Chart.toRenderable diagram
return ()
where
diagram :: EC (Layout Double Double) ()
diagram =
do
layout_title .= path
Chart.plot $ points "data points" $
map (\x -> (x, 0)) $
Lina.toList dots
Chart.plot $ line "estimated distribution" $
concat $ map (\Class{..} -> gaussLine (vecToVal class_min) (matToVal class_cov)) $
params
vecToVal :: Vector -> R
vecToVal =
f
.
Lina.toList
where
f [x] = x
f _ = error "error converting to vector to scalar!"
matToVal :: Matrix -> R
matToVal =
f
.
Lina.toLists
where
f [[x]] = x
f _ = error "error converting to vector to scalar!"
gaussLine :: R -> R -> [[(R,R)]]
gaussLine center cov =
return $
map (\x -> (x, mahalanobis (scalar center) (scalar cov) (scalar x))) $
map (
\x -> (center - width / 2) + (x * width / count)
) $
[0..count]
where
count = 100 :: Num a => a
width = 30 * cov
plot :: FilePath -> Matrix -> Classes -> ErrT IO ()
plot path dots params =
do
_ <- lift $ Chart.renderableToFile def path $ Chart.toRenderable diagram
return ()
where
diagram :: EC (Layout Double Double) ()
diagram =
do
layout_title .= path
Chart.plot $ points "data points" $
map vecToTuple2 $
Lina.toRows dots
Chart.plot $
line "classes" $
map (
\Class{..} ->
map vecToTuple2 $
lineFromGauss class_min class_cov
)
params
lineFromGauss :: Vector -> Matrix -> [Vector]
lineFromGauss center cov =
toRows $
(+ asRow center) $ -- shift to center
(<> cov) $ -- multiply with covariance matrix
circleDots
where
circleDots =
cmap cos anglesMat
|||
cmap sin anglesMat
anglesMat =
((count :: Int)><1) angles
angles = (/(2*pi)) <$> ([0..(count-1)] :: [Double])
count :: Num a => a
count = 100
{-
vectorField :: String -> [((R,R),(R,R))] -> EC (Layout R R) (Plot R R)
vectorField title vectors =
fmap plotVectorField $ liftEC $
do
c <- takeColor
plot_vectors_values .= vectors
plot_vectors_style . vector_line_style . line_color .= c
plot_vectors_style . vector_head_style . point_color .= c
plot_vectors_title .= title
----plot_vectors_grid .= grid
-}
|
EsGeh/pattern-recognition
|
test/Plot/Gauss.hs
|
Haskell
|
bsd-3-clause
| 2,710
|
module Test.Database.Redis.CommandTests (
commandTests
) where
import Database.Redis
import Test.HUnit
import Test.Util
-- ---------------------------------------------------------------------------
-- Tests
--
commandTests :: Test
commandTests = TestLabel "command" $
TestList [ -- * Connection
testPing,
-- * String
testSet, testGet, testGetset, testMget, testSetnx, testMset,
testMsetnx, testIncr, testIncrby, testDecr, testDecrby
]
-- ---------------------------------------------------------------------------
-- Connection
--
-- @todo: is an AUTH test possible?
testPing :: Test
testPing = testWithConn "ping" $ \r -> do
res <- ping r
assertEqual "test that ping returned pong" (RedisString "PONG") res
-- ---------------------------------------------------------------------------
-- String
--
testGet :: Test
testGet = testWithConn "get" $ \r -> do
_ <- set r "mykey" "secret"
res <- get r "mykey"
assertEqual "test that get gets set value" (RedisString "secret") res
testSet :: Test
testSet = testWithConn "set" $ \r -> do
res <- set r "mykey" "secret"
assertBool "test successful set" res
testGetset :: Test
testGetset = testWithConn "getset" $ \r -> do
_ <- set r "mykey" "secret"
res <- getset r "mykey" "new"
assertEqual "test getset returns old value" (RedisString "secret") res
res' <- get r "mykey"
assertEqual "test getset set new value" (RedisString "new") res'
testMget :: Test
testMget = testWithConn "mget" $ \r -> do
_ <- set r "key1" "val1"
_ <- set r "key2" "val2"
_ <- set r "key3" "val3"
res <- mget r ["key1", "key2", "key3"]
assertEqual "test mget returns all values"
(RedisMulti [ RedisString "val1"
, RedisString "val2"
, RedisString "val3" ])
res
testSetnx :: Test
testSetnx = testWithConn "setnx" $ \r -> do
res <- setnx r "mykey" "secret"
assertBool "test set when key does not exist" res
res' <- setnx r "mykey" "secret"
assertBool "test failed set when key already exists" $ not res'
testMset :: Test
testMset = testWithConn "mset" $ \r -> do
mset r [ ("key1", "val1")
, ("key2", "val2")
, ("key3", "val3") ]
res <- mget r ["key1", "key2", "key3"]
assertEqual "test mset set all values"
(RedisMulti [ RedisString "val1"
, RedisString "val2"
, RedisString "val3" ])
res
testMsetnx :: Test
testMsetnx = testWithConn "mset" $ \r -> do
res <- msetnx r [ ("key1", "val1")
, ("key2", "val2")
, ("key3", "val3") ]
assertBool "test msetnx returned success" res
res' <- mget r ["key1", "key2", "key3"]
assertEqual "test msetnx set all values"
(RedisMulti [ RedisString "val1"
, RedisString "val2"
, RedisString "val3" ])
res'
res'' <- msetnx r [ ("key3", "val3")
, ("key4", "val4") ]
assertBool "test msetnx failed when at least one key exists" $ not res''
res''' <- exists r "key4"
assertBool "test msetnx sets no keys on failure" $ not res'''
testIncr :: Test
testIncr = testWithConn "incr" $ \r -> do
res <- incr r "counter"
assertEqual "test incr sets key that didn't exist" (RedisInteger 1) res
res' <- incr r "counter"
assertEqual "test increment" (RedisInteger 2) res'
testIncrby :: Test
testIncrby = testWithConn "incrby" $ \r -> do
res <- incrby r "counter" (iToParam 7)
assertEqual "test incrby sets key that didn't exist" (RedisInteger 7) res
res' <- incrby r "counter" (iToParam 2)
assertEqual "test increment by" (RedisInteger 9) res'
testDecr :: Test
testDecr = testWithConn "decr" $ \r -> do
_ <- set r "counter" (iToParam 10)
res <- decr r "counter"
assertEqual "test decrement" (RedisInteger 9) res
testDecrby :: Test
testDecrby = testWithConn "decrby" $ \r -> do
_ <- set r "counter" (iToParam 10)
res <- decrby r "counter" (iToParam 7)
assertEqual "test decrement by" (RedisInteger 3) res
|
brandur/redis-haskell
|
testsuite/tests/Test/Database/Redis/CommandTests.hs
|
Haskell
|
bsd-3-clause
| 4,277
|
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeOperators #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : Andrew Martin
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Andrew Martin <andrew.thaddeus@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- This module uses the "constraints" package to prove that if all of the
-- columns satisfy the 'HasDefaultVector' constraint, then a vector
-- parameterized over the record has an instance of the generic vector
-- typeclass.
-----------------------------------------------------------------------------
module Data.Vector.Vinyl.Default.Empty.Monomorphic.Implication where
import Data.Constraint
import Data.List.TypeLevel.Constraint (ListAll)
import Data.Vector.Vinyl.Default.Empty.Monomorphic.Internal
import Data.Vector.Vinyl.Default.Types (HasDefaultVector)
import Data.Vinyl.Core (Rec (..))
import Data.Vinyl.Functor (Identity (..))
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as GM
listAllVector :: Rec proxy rs
-> ListAll rs HasDefaultVector :- G.Vector Vector (Rec Identity rs)
listAllVector RNil = Sub Dict
listAllVector (_ :& rs) = Sub $ case listAllVector rs of
Sub Dict -> Dict
listAllMVector :: Rec proxy rs
-> ListAll rs HasDefaultVector :- GM.MVector MVector (Rec Identity rs)
listAllMVector RNil = Sub Dict
listAllMVector (_ :& rs) = Sub $ case listAllMVector rs of
Sub Dict -> Dict
-- listAllVectorBoth :: Rec proxy rs
-- -> ListAll rs HasDefaultVector :- (GM.MVector MVector (Rec Identity rs), G.Vector Vector (Rec Identity rs))
-- listAllVectorBoth RNil = Sub Dict
-- listAllVectorBoth (_ :& rs) = Sub $ case listAllVectorBoth rs of
-- Sub Dict -> Dict
|
andrewthad/vinyl-vectors
|
src/Data/Vector/Vinyl/Default/Empty/Monomorphic/Implication.hs
|
Haskell
|
bsd-3-clause
| 2,047
|
{-# LANGUAGE ScopedTypeVariables, RankNTypes #-}
-- | Simple lenses (from SPJ's talk about lenses) - playground
module Sky.Lens.SimpleLens where
import Data.Functor.Identity
import Control.Applicative (Const(Const,getConst))
data LensR s a = LensR { getR :: s -> a, setR :: a -> s -> s }
type Lens' s a = forall f. Functor f => (a -> f a) -> s -> f s
-- From Lens' to LensR
set :: forall s a. Lens' s a -> a -> s -> s
set lens v = runIdentity . lens (Identity . const v)
get :: Lens' s a -> s -> a
get lens = getConst . lens Const
lensToLensR :: Lens' s a -> LensR s a
lensToLensR lens = LensR (get lens) (set lens)
-- From LensR to Lens'
lensRToLens :: LensR s a -> Lens' s a
lensRToLens (LensR getter setter) m s = fmap (flip setter s) (m $ getter s)
-- lensRToLens :: forall f s a. Functor f => LensR s a -> (a -> f a) -> s -> f s
-- lensRtoLens = let
-- -- m :: a -> f a
-- -- s :: s
-- -- getter :: s -> a
-- -- setter :: a -> s -> s
-- modded :: f a
-- modded = m (getter s)
-- setA :: a -> s
-- setA = flip setter s
-- in fmap setA modded -- :: f s
-- Lens' utilities
over :: Lens' s a -> (a -> a) -> s -> s
over lens m = runIdentity . lens (Identity . m)
-- modify, returning the old state
overRet :: Lens' s a -> (a -> a) -> s -> (a, s)
overRet lens m =
-- via: f a = ((,) a)
lens $ \a -> (a, m a)
-- Example
data Person = Person { _name :: String, _salary :: Int }
deriving (Show, Eq)
name :: Lens' Person String
name m p = fmap (\x -> p { _name = x }) (m $ _name p)
personX :: Person
personX = Person "Hans Wurst" 10
-- name :: forall f. Functor f => (String -> f String) -> Person -> f Person
-- name m p = let
-- -- m :: String -> f String
-- -- p :: Person
-- modded :: f String
-- modded = m (_name p)
-- setName :: String -> Person
-- setName x = p { _name = x }
-- in fmap setName modded
data A = A ()
data B = B ()
data C = C ()
data D = D ()
data X = X ()
f :: A -> B
f (A ()) = B ()
|
xicesky/sky-haskell-playground
|
src/Sky/Lens/SimpleLens.hs
|
Haskell
|
bsd-3-clause
| 1,998
|
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE Safe #-}
module Data.MessagePack.Result where
import Control.Applicative (Alternative (..), Applicative (..),
(<$>), (<*>))
import Data.Foldable (Foldable)
import Data.Traversable (Traversable)
import Test.QuickCheck.Arbitrary (Arbitrary (..))
import qualified Test.QuickCheck.Gen as Gen
data Result a
= Success a
| Failure String
deriving (Read, Show, Eq, Functor, Traversable, Foldable)
instance Applicative Result where
pure = Success
Success f <*> x = fmap f x
Failure msg <*> _ = Failure msg
instance Alternative Result where
empty = Failure "empty alternative"
s@Success {} <|> _ = s
_ <|> r = r
instance Monad Result where
return = pure
fail = Failure
Success x >>= f = f x
Failure msg >>= _ = Failure msg
instance Arbitrary a => Arbitrary (Result a) where
arbitrary = Gen.oneof
[ Success <$> arbitrary
, Failure <$> arbitrary
]
|
SX91/msgpack-haskell
|
src/Data/MessagePack/Result.hs
|
Haskell
|
bsd-3-clause
| 1,153
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module HipChat.AddOn.Types.RoomEvent where
import Control.Lens.AsText (AsText)
import qualified Control.Lens.AsText as AsText
import Data.Aeson (FromJSON, ToJSON, parseJSON, toJSON)
data RoomEvent
= RoomArchived
| RoomCreated
| RoomDeleted
| RoomEnter
| RoomExit
| RoomFileUpload
| RoomMessage
| RoomNotification
| RoomTopicChange
| RoomUnarchived
deriving (Show, Eq)
instance AsText RoomEvent where
enc = \case
RoomArchived -> "room_archived"
RoomCreated -> "room_created"
RoomDeleted -> "room_deleted"
RoomEnter -> "room_enter"
RoomExit -> "room_exit"
RoomFileUpload -> "room_file_upload"
RoomMessage -> "room_message"
RoomNotification -> "room_notification"
RoomTopicChange -> "room_topic_change"
RoomUnarchived -> "room_unarchived"
dec = \case
"room_archived" -> Just RoomArchived
"room_created" -> Just RoomCreated
"room_deleted" -> Just RoomDeleted
"room_enter" -> Just RoomEnter
"room_exit" -> Just RoomExit
"room_file_upload" -> Just RoomFileUpload
"room_message" -> Just RoomMessage
"room_notification" -> Just RoomNotification
"room_topic_change" -> Just RoomTopicChange
"room_unarchived" -> Just RoomUnarchived
_ -> Nothing
instance ToJSON RoomEvent where
toJSON = AsText.toJSON
instance FromJSON RoomEvent where
parseJSON = AsText.parseJSON
|
mjhopkins/hipchat
|
src/HipChat/AddOn/Types/RoomEvent.hs
|
Haskell
|
bsd-3-clause
| 1,566
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Quantity.FR.Corpus
( corpus ) where
import Prelude
import Data.String
import Duckling.Lang
import Duckling.Quantity.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus = (testContext {lang = FR}, allExamples)
allExamples :: [Example]
allExamples = concat
[ examples (QuantityData Cup 2 (Just "café"))
[ "2 tasses de café"
]
, examples (QuantityData Cup 1 Nothing)
[ "une Tasse"
]
, examples (QuantityData Tablespoon 3 (Just "sucre"))
[ "3 Cuillères à soupe de sucre"
]
]
|
rfranek/duckling
|
Duckling/Quantity/FR/Corpus.hs
|
Haskell
|
bsd-3-clause
| 954
|
-- |A simple msgpack remote procedure call (rpc) system for
-- interacting with the MSF server.
module RPC.SimpleRPC (request) where
import MsgPack
import Data.Char
import Data.Maybe
import Network.HTTP (simpleHTTP)
import Network.HTTP.Base (Request (..), Response (..), RequestMethod (..))
import Network.HTTP.Headers (Header (..), HeaderName (..))
import Network.Stream (Result)
import Network.URI (URI(..),URIAuth(..))
import qualified Data.ByteString as BS
{-| request addr obj establishes a connection to the metasploit server
and then passes obj in a POST request, returning the Object formatted
response. -}
request :: URI -> Object -> IO Object
request uri obj =
simpleHTTP req >>= handleTransportErrors >>= handleApplicationErrors
where
req = Request {
rqURI = uri,
rqMethod = POST,
rqHeaders =
[ Header HdrUserAgent "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
, Header HdrContentType "binary/message-pack"
, Header HdrContentLength (show . BS.length $ body)
] ++ hostHdr,
rqBody = body
}
body = pack obj
hostHdr = fromMaybe [] $ do
auth <- uriAuthority uri
return [ Header HdrHost (uriRegName auth ++ uriPort auth) ]
handleTransportErrors :: Result (Response a) -> IO (Response a)
handleTransportErrors (Right a) = return a
handleTransportErrors (Left e) = error (show e)
handleApplicationErrors :: Response BS.ByteString -> IO Object
handleApplicationErrors response =
case rspCode response of
(2,_,_) -> case unpack (rspBody response) of
Right obj -> return obj
Left err -> fail ("Unable to unpack response: " ++ err)
(x,y,z) -> error (map intToDigit [x,y,z] ++ ' ' : (rspReason response))
|
GaloisInc/msf-haskell
|
src/RPC/SimpleRPC.hs
|
Haskell
|
bsd-3-clause
| 1,716
|
{-# LANGUAGE OverloadedStrings, QuasiQuotes #-}
module Transformations.Optimising.CaseCopyPropagationSpec where
import Transformations.Optimising.CaseCopyPropagation
import Transformations.Names (ExpChanges(..))
import Test.Hspec
import Grin.TH
import Test.Test hiding (newVar)
import Test.Assertions
import Grin.TypeEnv
import Data.Monoid
import Grin.Pretty
ctxs :: [TestExpContext]
ctxs =
[ emptyCtx
, lastBindR
, firstAlt
, middleAlt
-- , lastAlt
]
--spec :: Spec
--spec = pure ()
-- TODO: Check parsing.
spec :: Spec
spec = testExprContextIn ctxs $ \ctx -> do
it "Example from Figure 4.26" $ do
let teBefore = create $
(newVar "z'" int64_t) <>
(newVar "y'" int64_t) <>
(newVar "x'" int64_t)
let before = [expr|
m0 <- store (CNone)
u <- case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CInt z')
(CInt x') -> pure (CInt x')
pure m0
|]
let teAfter = extend teBefore $
newVar "v'" int64_t
let after = [expr|
m0 <- store (CNone)
u <- do
ccp.0 <- case v of
(Ffoo a) -> y' <- foo a
pure y'
(Fbar b) -> z' <- bar b
pure z'
(CInt x') -> pure x'
pure (CInt ccp.0)
pure m0
|]
-- TODO: Inspect type env
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
--(snd (ctx (teBefore, before))) `sameAs` (snd (ctx (teAfter, after)))
it "One node has no Int tagged value" $ do
let typeEnv = emptyTypeEnv
let teBefore = create $
(newVar "z'" float_t) <>
(newVar "y'" int64_t) <>
(newVar "x'" int64_t)
let before = [expr|
m0 <- store (CNone)
u <- do
case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CFloat z')
(CInt x') -> pure (CInt x')
pure m0
|]
let after = [expr|
m0 <- store (CNone)
u <- do
case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CFloat z')
(CInt x') -> pure (CInt x')
pure m0
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teBefore, after))), NoChange)
xit "Embedded good case" $ do
let teBefore = create $
(newVar "z'" int64_t) <>
(newVar "y'" int64_t) <>
(newVar "x'" int64_t) <>
(newVar "z1'" int64_t) <>
(newVar "y1'" int64_t) <>
(newVar "x1'" int64_t)
let before = [expr|
m0 <- store (CNone)
u <- case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CInt z')
(CInt x') -> u1 <- case v1 of
(Ffoo a1) -> y1' <- foo a1
pure (CInt y1')
(Fbar b1) -> z1' <- bar b1
pure (CInt z1')
(CInt x1') -> pure (CInt x1')
pure (CInt x')
pure m0
|]
let teAfter = extend teBefore $
newVar "v'" int64_t <>
newVar "v1'" int64_t
let after = [expr|
m0 <- store (CNone)
u <- case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CInt z')
(CInt x') -> u1 <- do
ccp.0 <- case v1 of
(Ffoo a1) -> y1' <- foo a1
pure y1'
(Fbar b1) -> z1' <- bar b1
pure z1'
(CInt x1') -> pure x1'
pure (CInt ccp.0)
pure (CInt x')
pure m0
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
it "Embedded bad case" $ do
let teBefore = create $
newVar "z'" int64_t <>
newVar "y'" int64_t <>
newVar "x'" int64_t <>
newVar "y1'" int64_t <>
newVar "z1'" float_t <>
newVar "x1'" int64_t
let before = [expr|
m0 <- store (CNone)
u <- case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CInt z')
(CInt x') -> u1 <- do
case v1 of
(Ffoo a1) -> y1' <- foo a1
pure (CInt y1')
(Fbar b1) -> z1' <- bar b1
pure (CFloat z1')
(CInt x1') -> pure (CInt x1')
pure (CInt x')
pure m0
|]
let teAfter = extend teBefore $
newVar "v'" int64_t
let after = [expr|
m0 <- store (CNone)
u <- do
ccp.0 <- case v of
(Ffoo a) -> y' <- foo a
pure y'
(Fbar b) -> z' <- bar b
pure z'
(CInt x') -> u1 <- do
case v1 of
(Ffoo a1) -> y1' <- foo a1
pure (CInt y1')
(Fbar b1) -> z1' <- bar b1
pure (CFloat z1')
(CInt x1') -> pure (CInt x1')
pure x'
pure (CInt ccp.0)
pure m0
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
it "Leave the outher, transform the inner" $ do
let teBefore = create $
newVar "z'" float_t <>
newVar "y'" int64_t <>
newVar "x'" int64_t <>
newVar "y1'" int64_t <>
newVar "z1'" int64_t <>
newVar "x1'" int64_t
let before = [expr|
m0 <- store (CNone)
u <- do
case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CFloat z')
(CInt x') -> u1 <- case v1 of
(Ffoo a1) -> y1' <- foo a1
pure (CInt y1')
(Fbar b1) -> z1' <- bar b1
pure (CInt z1')
(CInt x1') -> pure (CInt x1')
pure (CInt x')
pure m0
|]
let teAfter = extend teBefore $
newVar "v1'" int64_t
let after = [expr|
m0 <- store (CNone)
u <- do
case v of
(Ffoo a) -> y' <- foo a
pure (CInt y')
(Fbar b) -> z' <- bar b
pure (CFloat z')
(CInt x') -> u1 <- do
ccp.0 <- case v1 of
(Ffoo a1) -> y1' <- foo a1
pure y1'
(Fbar b1) -> z1' <- bar b1
pure z1'
(CInt x1') -> pure x1'
pure (CInt ccp.0)
pure (CInt x')
pure m0
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
xit "last expression is a case" $ do
let teBefore = create $
newVar "ax'" int64_t
let before =
[expr|
l2 <- eval l
case l2 of
(CNil) -> pure (CInt 0)
(CCons x xs) -> (CInt x') <- eval x
(CInt s') <- sum xs
ax' <- _prim_int_add x' s'
pure (CInt ax')
|]
let teAfter = extend teBefore $
newVar "l2'" int64_t
let after =
[expr|
l2 <- eval l
do ccp.0 <- case l2 of
(CNil) -> pure 0
(CCons x xs) -> (CInt x') <- eval x
(CInt s') <- sum xs
ax' <- _prim_int_add x' s'
pure ax'
pure (CInt ccp.0)
|]
(caseCopyPropagation (snd (ctx (teBefore, before)))) `sameAs` ((snd (ctx (teAfter, after))), NewNames)
runTests :: IO ()
runTests = hspec spec
|
andorp/grin
|
grin/test/Transformations/Optimising/CaseCopyPropagationSpec.hs
|
Haskell
|
bsd-3-clause
| 10,010
|
{-# LANGUAGE CPP, NamedFieldPuns, RecordWildCards #-}
-- | cabal-install CLI command: freeze
--
module Distribution.Client.CmdFreeze (
freezeCommand,
freezeAction,
) where
import Distribution.Client.ProjectPlanning
import Distribution.Client.ProjectConfig
( ProjectConfig(..), ProjectConfigShared(..)
, commandLineFlagsToProjectConfig, writeProjectLocalFreezeConfig
, findProjectRoot )
import Distribution.Client.Targets
( UserConstraint(..) )
import Distribution.Solver.Types.ConstraintSource
( ConstraintSource(..) )
import Distribution.Client.DistDirLayout
( defaultDistDirLayout, defaultCabalDirLayout )
import Distribution.Client.Config
( defaultCabalDir )
import qualified Distribution.Client.InstallPlan as InstallPlan
import Distribution.Package
( PackageName, packageName, packageVersion )
import Distribution.Version
( VersionRange, thisVersion, unionVersionRanges )
import Distribution.PackageDescription
( FlagAssignment )
import Distribution.Client.Setup
( GlobalFlags, ConfigFlags(..), ConfigExFlags, InstallFlags )
import Distribution.Simple.Setup
( HaddockFlags, fromFlagOrDefault )
import Distribution.Simple.Utils
( die, notice )
import Distribution.Verbosity
( normal )
import Data.Monoid as Monoid
import qualified Data.Map as Map
import Data.Map (Map)
import Control.Monad (unless)
import System.FilePath
import Distribution.Simple.Command
( CommandUI(..), usageAlternatives )
import Distribution.Simple.Utils
( wrapText )
import qualified Distribution.Client.Setup as Client
freezeCommand :: CommandUI (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
freezeCommand = Client.installCommand {
commandName = "new-freeze",
commandSynopsis = "Freezes a Nix-local build project",
commandUsage = usageAlternatives "new-freeze" [ "[FLAGS]" ],
commandDescription = Just $ \_ -> wrapText $
"Performs dependency solving on a Nix-local build project, and"
++ " then writes out the precise dependency configuration to cabal.project.freeze"
++ " so that the plan is always used in subsequent builds.",
commandNotes = Just $ \pname ->
"Examples:\n"
++ " " ++ pname ++ " new-freeze "
++ " Freeze the configuration of the current project\n"
}
-- | To a first approximation, the @freeze@ command runs the first phase of
-- the @build@ command where we bring the install plan up to date, and then
-- based on the install plan we write out a @cabal.project.freeze@ config file.
--
-- For more details on how this works, see the module
-- "Distribution.Client.ProjectOrchestration"
--
freezeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
freezeAction (configFlags, configExFlags, installFlags, haddockFlags)
extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'freeze' doesn't take any extra arguments: "
++ unwords extraArgs
cabalDir <- defaultCabalDir
let cabalDirLayout = defaultCabalDirLayout cabalDir
projectRootDir <- findProjectRoot
let distDirLayout = defaultDistDirLayout projectRootDir
let cliConfig = commandLineFlagsToProjectConfig
globalFlags configFlags configExFlags
installFlags haddockFlags
(_, elaboratedPlan, _, _) <-
rebuildInstallPlan verbosity
projectRootDir distDirLayout cabalDirLayout
cliConfig
let freezeConfig = projectFreezeConfig elaboratedPlan
writeProjectLocalFreezeConfig projectRootDir freezeConfig
notice verbosity $
"Wrote freeze file: " ++ projectRootDir </> "cabal.project.freeze"
where
verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
-- | Given the install plan, produce a config value with constraints that
-- freezes the versions of packages used in the plan.
--
projectFreezeConfig :: ElaboratedInstallPlan -> ProjectConfig
projectFreezeConfig elaboratedPlan =
Monoid.mempty {
projectConfigShared = Monoid.mempty {
projectConfigConstraints =
concat (Map.elems (projectFreezeConstraints elaboratedPlan))
}
}
-- | Given the install plan, produce solver constraints that will ensure the
-- solver picks the same solution again in future in different environments.
--
projectFreezeConstraints :: ElaboratedInstallPlan
-> Map PackageName [(UserConstraint, ConstraintSource)]
projectFreezeConstraints plan =
--
-- TODO: [required eventually] this is currently an underapproximation
-- since the constraints language is not expressive enough to specify the
-- precise solution. See https://github.com/haskell/cabal/issues/3502.
--
-- For the moment we deal with multiple versions in the solution by using
-- constraints that allow either version. Also, we do not include any
-- /version/ constraints for packages that are local to the project (e.g.
-- if the solution has two instances of Cabal, one from the local project
-- and one pulled in as a setup deps then we exclude all constraints on
-- Cabal, not just the constraint for the local instance since any
-- constraint would apply to both instances). We do however keep flag
-- constraints of local packages.
--
deleteLocalPackagesVersionConstraints
(Map.unionWith (++) versionConstraints flagConstraints)
where
versionConstraints :: Map PackageName [(UserConstraint, ConstraintSource)]
versionConstraints =
Map.mapWithKey
(\p v -> [(UserConstraintVersion p v, ConstraintSourceFreeze)])
versionRanges
versionRanges :: Map PackageName VersionRange
versionRanges =
Map.fromListWith unionVersionRanges $
[ (packageName pkg, thisVersion (packageVersion pkg))
| InstallPlan.PreExisting pkg <- InstallPlan.toList plan
]
++ [ (packageName pkg, thisVersion (packageVersion pkg))
| InstallPlan.Configured pkg <- InstallPlan.toList plan
]
flagConstraints :: Map PackageName [(UserConstraint, ConstraintSource)]
flagConstraints =
Map.mapWithKey
(\p f -> [(UserConstraintFlags p f, ConstraintSourceFreeze)])
flagAssignments
flagAssignments :: Map PackageName FlagAssignment
flagAssignments =
Map.fromList
[ (pkgname, flags)
| InstallPlan.Configured elab <- InstallPlan.toList plan
, let flags = elabFlagAssignment elab
pkgname = packageName elab
, not (null flags) ]
-- As described above, remove the version constraints on local packages,
-- but leave any flag constraints.
deleteLocalPackagesVersionConstraints
:: Map PackageName [(UserConstraint, ConstraintSource)]
-> Map PackageName [(UserConstraint, ConstraintSource)]
deleteLocalPackagesVersionConstraints =
#if MIN_VERSION_containers(0,5,0)
Map.mergeWithKey
(\_pkgname () constraints ->
case filter (not . isVersionConstraint . fst) constraints of
[] -> Nothing
constraints' -> Just constraints')
(const Map.empty) id
localPackages
#else
Map.mapMaybeWithKey
(\pkgname constraints ->
if pkgname `Map.member` localPackages
then case filter (not . isVersionConstraint . fst) constraints of
[] -> Nothing
constraints' -> Just constraints'
else Just constraints)
#endif
isVersionConstraint UserConstraintVersion{} = True
isVersionConstraint _ = False
localPackages :: Map PackageName ()
localPackages =
Map.fromList
[ (packageName elab, ())
| InstallPlan.Configured elab <- InstallPlan.toList plan
, elabLocalToProject elab
]
|
sopvop/cabal
|
cabal-install/Distribution/Client/CmdFreeze.hs
|
Haskell
|
bsd-3-clause
| 8,028
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE TypeApplications #-}
-- | typesafe printf in haskell
--
-- who needs idris lol
--
-- we didn't even need -XTypeInType :p
import GHC.TypeLits
import GHC.Types
import Data.Proxy
-- | Type level token
data Token = Var Type
| Const Symbol
type family Tokenize (s :: [Symbol]) :: ([Token]) where
Tokenize ("%i" ': xs) = Var Int ': Tokenize xs
Tokenize ("%s" ': xs) = Var String ': Tokenize xs
Tokenize (x ': xs) = Const x ': Tokenize xs
Tokenize ('[]) = '[]
-- | Arbitrarily sized products encoded in a GADT.
--
-- aka an HList.
--
data HList (k :: [Type]) where
Nil :: HList '[]
(:+) :: x -> HList xs -> HList (x ':xs)
-- | Now we need a way to generate a function
-- at both the term and type level
-- that grows as we recurse down
-- our typelevel list of tokens
class Parseable (s :: [Token]) where
type Needs s :: [Type]
printf'' :: Proxy s -> HList (Needs s) -> String
instance Parseable ('[]) where
type Needs '[] = '[]
printf'' _ x = ""
instance (KnownSymbol str, Parseable as) => Parseable (Const str ': as) where
type Needs (Const str ': as) = Needs as
printf'' _ x = symbolVal (Proxy :: Proxy str)
++ printf'' (Proxy :: Proxy as) x
instance {-# OVERLAPS #-} (Parseable as) => Parseable (Var String ': as) where
type Needs (Var String ': as) = (String ': (Needs as))
printf'' _ (x :+ xs) = x
++ printf'' (Proxy :: Proxy as) xs
instance (Show a, Parseable as) => Parseable (Var a ': as) where
type Needs (Var a ': as) = (a ': (Needs as))
printf'' _ (x :+ xs) = show x
++ printf'' (Proxy :: Proxy as) xs
-- | Uncurried version.
printf' :: forall l. (Parseable (Tokenize l)) => Proxy l -> HList (Needs (Tokenize l)) -> String
printf' _ = printf'' (Proxy :: Proxy (Tokenize l))
-- | Can we generalize currying for arbitrarily sized products?
--
-- Here's plain old currying:
curry' :: ((a, b) -> c) -> (a -> b -> c)
curry' f head = g
where
g tail = f (head, tail)
class Curryable k o where
type Curried k o
genCurry :: (HList k -> o) -> Curried k o
-- | base case
instance Curryable '[] o where
type Curried '[] o = o
genCurry f = f Nil
-- | inductive case
instance (Curryable as o) => Curryable (a ': as) o where
type Curried (a ': as) o = (a -> Curried as o)
genCurry f head = genCurry g
where
g tail = f (head :+ tail)
-- | Type-safe printf in Haskell!
printf :: forall l. (Parseable (Tokenize l), Curryable (Needs (Tokenize l)) String) => Curried (Needs (Tokenize l)) String
printf = genCurry (printf' (Proxy @l))
cool :: String
cool = printf @'["cool mayn"]
greet :: String -> String
greet = printf @'["hello ", "%s", "!"]
tellAge :: String -> Int -> String
tellAge = printf @'["%s", " is ", "%i", " years old."]
|
sleexyz/haskell-fun
|
TypeSafePrintF.hs
|
Haskell
|
bsd-3-clause
| 3,196
|
module Main where
import Test.Tasty
import Test.Tasty.HUnit
-- import qualified TicTacToeTest as TTTT
-- import qualified GameOfLifeTest as GOL
-- import qualified HearthstoneTest as HT
-- import qualified RomanNumeralTest as RN
import qualified PokerHandsTest as PH
import qualified PokerHoldEmTest as PHT
main :: IO ()
main = defaultMain (testGroup "new group" [
-- TTTT.tests2
--, GOL.tests2
--, HT.tests
--, RN.tests2
-- PH.tests2
PHT.tests2
])
|
steveshogren/haskell-katas
|
test/MainTest.hs
|
Haskell
|
bsd-3-clause
| 600
|
module Y2017.Day09 (answer1, answer2) where
import Data.Functor
import Data.Void
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.IO as T
import Text.Megaparsec
import Text.Megaparsec.Char
type Parser = Parsec Void Text
answer1, answer2 :: IO ()
answer1 = parseInput >>= print . streamSize
answer2 = parseInput >>= print . garbageSize
streamSize = go 1
where go n (Garbage _) = 0
go n (Group gs) = n + sum (fmap (go (n+1)) gs)
garbageSize (Garbage t) = T.length t
garbageSize (Group gs) = sum $ fmap garbageSize gs
data Stuff = Group [Stuff] | Garbage Text deriving Show
parseInput = parseStream <$> T.readFile "data/2017/day09.txt"
parseStream :: Text -> Stuff
parseStream s = case parse parseGroup "stream" s of
Left err -> error (show err)
Right x -> x
parseGroup = Group <$> between (char '{') (char '}') (parseStuff `sepBy` char ',')
parseStuff :: Parser Stuff
parseStuff = parseGroup <|> parseGarbage
parseGarbage = Garbage <$> between (char '<') (char '>') garbageContent
-- don't parse cancelled characters
garbageContent :: Parser Text
garbageContent = T.concat <$> many
( try (char '!' *> (T.singleton <$> asciiChar) $> T.pack "")
<|> (T.singleton <$> satisfy (/= '>'))
)
|
geekingfrog/advent-of-code
|
src/Y2017/Day09.hs
|
Haskell
|
bsd-3-clause
| 1,270
|
----------------------------------------------------------------------------
-- |
-- Module : Haskell.Language.Server.Tags.Types.Imports
-- Copyright : (c) Sergey Vinokurov 2018
-- License : BSD3-style (see LICENSE)
-- Maintainer : serg.foo@gmail.com
----------------------------------------------------------------------------
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module Haskell.Language.Server.Tags.Types.Imports
( ImportKey(..)
, ImportTarget(..)
, ImportSpec(..)
, importBringsUnqualifiedNames
, importBringsQualifiedNames
, importBringsNamesQualifiedWith
, ImportQualification(..)
, hasQualifier
, getQualifier
, ImportListSpec(..)
, ImportType(..)
, ImportList(..)
, EntryWithChildren(..)
, mkEntryWithoutChildren
, ChildrenVisibility(..)
) where
import Control.DeepSeq
import Data.Hashable
import Data.Map.Strict (Map)
import Data.Set (Set)
import Data.Store (Store)
import Data.Text.Prettyprint.Doc.Ext
import GHC.Generics (Generic)
import Data.KeyMap (KeyMap, HasKey(..))
import Data.SubkeyMap (HasSubkey(..))
import Data.SymbolMap (SymbolMap)
import qualified Data.SymbolMap as SM
import Data.Symbols
import qualified Haskell.Language.Lexer.FastTags as FastTags
-- | Handle for when particular module enters another module's scope.
data ImportKey = ImportKey
{ -- | Whether this import statement is annotated with {-# SOURCE #-} pragma.
-- This means that it refers to .hs-boot file, rather than vanilla .hs file.
ikImportTarget :: !ImportTarget
-- | Name of imported module
, ikModuleName :: !ModuleName
} deriving (Eq, Ord, Show, Generic)
instance Hashable ImportKey
instance NFData ImportKey
instance Store ImportKey
instance HasSubkey ImportKey where
type Subkey ImportKey = ModuleName
getSubkey = ikModuleName
instance Pretty ImportKey where
pretty ik =
"ImportKey" <+> pretty (ikImportTarget ik) <+> pretty (ikModuleName ik)
data ImportTarget = VanillaModule | HsBootModule
deriving (Eq, Ord, Show, Enum, Bounded, Generic)
instance Hashable ImportTarget
instance NFData ImportTarget
instance Store ImportTarget
instance Pretty ImportTarget where
pretty = ppGeneric
-- | Information about import statement
data ImportSpec = ImportSpec
{ ispecImportKey :: !ImportKey
, ispecQualification :: !ImportQualification
, ispecImportList :: !(ImportListSpec ImportList)
} deriving (Eq, Ord, Show, Generic)
instance NFData ImportSpec
instance Store ImportSpec
instance Pretty ImportSpec where
pretty = ppGeneric
-- NB See [Record fields visibility] why this function must not be
-- incorporated into main name resolution logic (i.e. the 'LoadModule' module).
importBringsUnqualifiedNames :: SymbolMap -> ImportSpec -> Maybe SymbolMap
importBringsUnqualifiedNames exportedNames ImportSpec{ispecQualification} =
case ispecQualification of
Qualified _ ->
case foldMap
(\(p, children) ->
-- [Record fields visibility]
-- Functions associated with a type will likely be names of
-- fields, which do come unqualified. But actual functions don't (!).
-- That's why this logic is not incorporated into main name resolution,
-- but only in search.
if resolvedSymbolType p == FastTags.Type
then filter ((== FastTags.Function) . resolvedSymbolType) children
else [])
(SM.childrenRelations exportedNames) of
[] -> Nothing
xs -> Just $ SM.fromList xs
Unqualified -> Just exportedNames
BothQualifiedAndUnqualified _ -> Just exportedNames
importBringsQualifiedNames :: ImportSpec -> Bool
importBringsQualifiedNames ImportSpec{ispecQualification} =
case ispecQualification of
Qualified _ -> True
Unqualified -> False
BothQualifiedAndUnqualified _ -> True
importBringsNamesQualifiedWith :: ImportSpec -> ImportQualifier -> Bool
importBringsNamesQualifiedWith ImportSpec{ispecQualification} q =
getQualifier ispecQualification == Just q
data ImportQualification =
-- | Qualified import, e.g.
--
-- import qualified X as Y
--
-- The ModuleName field would store "Y" in this case.
--
-- import qualified X - field would store "X"
Qualified !ImportQualifier
-- | Vanilla import, e.g.
--
-- import X
| Unqualified
-- | Vanilla import with explicit alias, e.g.
--
-- import X as Y
| BothQualifiedAndUnqualified !ImportQualifier
deriving (Eq, Ord, Show, Generic)
instance Hashable ImportQualification
instance NFData ImportQualification
instance Store ImportQualification
instance Pretty ImportQualification where
pretty = ppGeneric
hasQualifier :: ImportQualifier -> ImportQualification -> Bool
hasQualifier qual = maybe False (== qual) . getQualifier
getQualifier :: ImportQualification -> Maybe ImportQualifier
getQualifier (Qualified q) = Just q
getQualifier Unqualified = Nothing
getQualifier (BothQualifiedAndUnqualified q) = Just q
data ImportType =
-- | Explicit import list of an import statement, e.g.
--
-- import Foo (x, y, z(Baz))
-- import Bar ()
Imported
| -- | Hiding import list
--
-- import Foo hiding (x, y(Bar), z)
-- import Foo hiding ()
Hidden
deriving (Eq, Ord, Show, Generic)
instance Hashable ImportType
instance NFData ImportType
instance Store ImportType
instance Pretty ImportType where
pretty = ppGeneric
data ImportListSpec a =
NoImportList
-- | When we canot precisely analyse an import list it's
-- conservatively defaulted to "import all".
| AssumedWildcardImportList
| SpecificImports !a
deriving (Eq, Ord, Show, Generic, Functor, Foldable, Traversable)
instance NFData a => NFData (ImportListSpec a)
instance Store a => Store (ImportListSpec a)
instance Pretty a => Pretty (ImportListSpec a) where
pretty = ppGeneric
-- | User-provided import/hiding list.
data ImportList = ImportList
{ ilEntries :: !(KeyMap Set (EntryWithChildren () UnqualifiedSymbolName))
, ilImportType :: !ImportType
} deriving (Eq, Ord, Show, Generic)
instance NFData ImportList
instance Store ImportList
instance Pretty ImportList where
pretty ImportList{ilImportType, ilEntries} =
ppFoldableHeader ("Import list[" <> pretty ilImportType <> "]") ilEntries
data EntryWithChildren childAnn name = EntryWithChildren
{ entryName :: !name
, entryChildrenVisibility :: !(Maybe (ChildrenVisibility childAnn))
} deriving (Eq, Ord, Show, Generic, Functor, Foldable, Traversable)
instance (NFData a, NFData b) => NFData (EntryWithChildren a b)
instance (Store a, Store b) => Store (EntryWithChildren a b)
instance (Pretty ann, Pretty name) => Pretty (EntryWithChildren ann name) where
pretty = ppGeneric
mkEntryWithoutChildren :: a -> EntryWithChildren ann a
mkEntryWithoutChildren name = EntryWithChildren name Nothing
instance HasKey (EntryWithChildren ann UnqualifiedSymbolName) where
type Key (EntryWithChildren ann UnqualifiedSymbolName) = UnqualifiedSymbolName
{-# INLINE getKey #-}
getKey = entryName
instance HasKey (EntryWithChildren ann SymbolName) where
type Key (EntryWithChildren ann SymbolName) = SymbolName
{-# INLINE getKey #-}
getKey = entryName
data ChildrenVisibility ann =
-- | Wildcard import/export, e.g. Foo(..)
VisibleAllChildren
-- | Import/export with explicit list of children, e.g. Foo(Bar, Baz), Quux(foo, bar).
-- Set is always non-empty.
| VisibleSpecificChildren !(Map UnqualifiedSymbolName ann)
-- | Wildcard export with some things added in, so they'll be visible on
-- wildcard import, e.g.
-- ErrorCall(..,ErrorCall)
| VisibleAllChildrenPlusSome !(Map UnqualifiedSymbolName ann)
deriving (Eq, Ord, Show, Generic, Functor, Foldable, Traversable)
instance NFData a => NFData (ChildrenVisibility a)
instance Store a => Store (ChildrenVisibility a)
instance Pretty a => Pretty (ChildrenVisibility a) where
pretty = ppGeneric
|
sergv/tags-server
|
src/Haskell/Language/Server/Tags/Types/Imports.hs
|
Haskell
|
bsd-3-clause
| 8,319
|
-----------------------------------------------------------------------------
-- Pred: Predicates
--
-- Part of `Typing Haskell in Haskell', version of November 23, 2000
-- Copyright (c) Mark P Jones and the Oregon Graduate Institute
-- of Science and Technology, 1999-2000
--
-- This program is distributed as Free Software under the terms
-- in the file "License" that is included in the distribution
-- of this software, copies of which may be obtained from:
-- http://www.cse.ogi.edu/~mpj/thih/
--
-----------------------------------------------------------------------------
module Pred where
import Data.List(union,(\\))
import Control.Monad(msum)
import Id
import Kind
import Type
import Subst
import Unify
import PPrint
data Qual t = [Pred] :=> t
deriving Eq
instance PPrint t => PPrint (Qual t) where
pprint (ps :=> t) = (pprint ps <+> text ":=>") $$ nest 2 (parPprint t)
data Pred = IsIn Id Type
deriving Eq
instance PPrint Pred where
pprint (IsIn i t) = text "isIn1" <+> text ("c" ++ i) <+> parPprint t
instance Types t => Types (Qual t) where
apply s (ps :=> t) = apply s ps :=> apply s t
tv (ps :=> t) = tv ps `union` tv t
instance Types Pred where
apply s (IsIn i t) = IsIn i (apply s t)
tv (IsIn i t) = tv t
mguPred, matchPred :: Pred -> Pred -> Maybe Subst
mguPred = lift mgu
matchPred = lift match
lift m (IsIn i t) (IsIn i' t')
| i == i' = m t t'
| otherwise = fail "classes differ"
type Class = ([Id], [Inst])
type Inst = Qual Pred
-----------------------------------------------------------------------------
data ClassEnv = ClassEnv { classes :: Id -> Maybe Class,
defaults :: [Type] }
super :: ClassEnv -> Id -> [Id]
super ce i = case classes ce i of Just (is, its) -> is
insts :: ClassEnv -> Id -> [Inst]
insts ce i = case classes ce i of Just (is, its) -> its
defined :: Maybe a -> Bool
defined (Just x) = True
defined Nothing = False
modify :: ClassEnv -> Id -> Class -> ClassEnv
modify ce i c = ce{classes = \j -> if i==j then Just c
else classes ce j}
initialEnv :: ClassEnv
initialEnv = ClassEnv { classes = \i -> fail "class not defined",
defaults = [tInteger, tDouble] }
type EnvTransformer = ClassEnv -> Maybe ClassEnv
infixr 5 <:>
(<:>) :: EnvTransformer -> EnvTransformer -> EnvTransformer
(f <:> g) ce = do ce' <- f ce
g ce'
addClass :: Id -> [Id] -> EnvTransformer
addClass i is ce
| defined (classes ce i) = fail "class already defined"
| any (not . defined . classes ce) is = fail "superclass not defined"
| otherwise = return (modify ce i (is, []))
addPreludeClasses :: EnvTransformer
addPreludeClasses = addCoreClasses <:> addNumClasses
addCoreClasses :: EnvTransformer
addCoreClasses = addClass "Eq" []
<:> addClass "Ord" ["Eq"]
<:> addClass "Show" []
<:> addClass "Read" []
<:> addClass "Bounded" []
<:> addClass "Enum" []
<:> addClass "Functor" []
<:> addClass "Monad" []
addNumClasses :: EnvTransformer
addNumClasses = addClass "Num" ["Eq", "Show"]
<:> addClass "Real" ["Num", "Ord"]
<:> addClass "Fractional" ["Num"]
<:> addClass "Integral" ["Real", "Enum"]
<:> addClass "RealFrac" ["Real", "Fractional"]
<:> addClass "Floating" ["Fractional"]
<:> addClass "RealFloat" ["RealFrac", "Floating"]
addInst :: [Pred] -> Pred -> EnvTransformer
addInst ps p@(IsIn i _) ce
| not (defined (classes ce i)) = fail "no class for instance"
| any (overlap p) qs = fail "overlapping instance"
| otherwise = return (modify ce i c)
where its = insts ce i
qs = [ q | (_ :=> q) <- its ]
c = (super ce i, (ps:=>p) : its)
overlap :: Pred -> Pred -> Bool
overlap p q = defined (mguPred p q)
exampleInsts :: EnvTransformer
exampleInsts = addPreludeClasses
<:> addInst [] (IsIn "Ord" tUnit)
<:> addInst [] (IsIn "Ord" tChar)
<:> addInst [] (IsIn "Ord" tInt)
<:> addInst [IsIn "Ord" (TVar (Tyvar "a" Star)),
IsIn "Ord" (TVar (Tyvar "b" Star))]
(IsIn "Ord" (pair (TVar (Tyvar "a" Star))
(TVar (Tyvar "b" Star))))
-----------------------------------------------------------------------------
bySuper :: ClassEnv -> Pred -> [Pred]
bySuper ce p@(IsIn i t)
= p : concat [ bySuper ce (IsIn i' t) | i' <- super ce i ]
byInst :: ClassEnv -> Pred -> Maybe [Pred]
byInst ce p@(IsIn i t) = msum [ tryInst it | it <- insts ce i ]
where tryInst (ps :=> h) = do u <- matchPred h p
Just (map (apply u) ps)
entail :: ClassEnv -> [Pred] -> Pred -> Bool
entail ce ps p = any (p `elem`) (map (bySuper ce) ps) ||
case byInst ce p of
Nothing -> False
Just qs -> all (entail ce ps) qs
-----------------------------------------------------------------------------
inHnf :: Pred -> Bool
inHnf (IsIn c t) = hnf t
where hnf (TVar v) = True
hnf (TCon tc) = False
hnf (TAp t _) = hnf t
toHnfs :: Monad m => ClassEnv -> [Pred] -> m [Pred]
toHnfs ce ps = do pss <- mapM (toHnf ce) ps
return (concat pss)
toHnf :: Monad m => ClassEnv -> Pred -> m [Pred]
toHnf ce p | inHnf p = return [p]
| otherwise = case byInst ce p of
Nothing -> fail "context reduction"
Just ps -> toHnfs ce ps
simplify :: ClassEnv -> [Pred] -> [Pred]
simplify ce = loop []
where loop rs [] = rs
loop rs (p:ps) | entail ce (rs++ps) p = loop rs ps
| otherwise = loop (p:rs) ps
reduce :: Monad m => ClassEnv -> [Pred] -> m [Pred]
reduce ce ps = do qs <- toHnfs ce ps
return (simplify ce qs)
scEntail :: ClassEnv -> [Pred] -> Pred -> Bool
scEntail ce ps p = any (p `elem`) (map (bySuper ce) ps)
-----------------------------------------------------------------------------
|
elben/typing-haskell-in-haskell
|
Pred.hs
|
Haskell
|
bsd-3-clause
| 6,679
|
{-# LANGUAGE OverloadedStrings #-}
-- | Add <http://www.w3.org/TR/cors/ CORS> (cross-origin resource sharing)
-- headers to a Snap application. CORS headers can be added either conditionally
-- or unconditionally to the entire site, or you can apply CORS headers to a
-- single route.
module CORS
(
-- * Applying CORS to a specific response
applyCORS
-- * Option Specification
, CORSOptions(..)
, defaultOptions
-- ** Origin lists
, OriginList(..)
, OriginSet, mkOriginSet, origins
-- * Internals
, HashableURI(..), HashableMethod (..)
) where
import Control.Applicative
import Control.Monad (when)
import Data.CaseInsensitive (CI)
import Data.Foldable (for_)
import Data.Hashable (Hashable(..))
import Data.Maybe (fromMaybe)
import Data.Text.Encoding (decodeUtf8, encodeUtf8)
import Network.URI (URI (..), URIAuth (..), parseURI)
import qualified Data.Attoparsec.Combinator as Attoparsec
import qualified Data.Attoparsec.ByteString.Char8 as Attoparsec
import qualified Data.ByteString.Char8 as Char8
import qualified Data.CaseInsensitive as CI
import qualified Data.HashSet as HashSet
import qualified Data.Text as Text
import qualified Snap.Core as Snap
-- | A set of origins. RFC 6454 specifies that origins are a scheme, host and
-- port, so the 'OriginSet' wrapper around a 'HashSet.HashSet' ensures that each
-- 'URI' constists of nothing more than this.
newtype OriginSet = OriginSet { origins :: HashSet.HashSet HashableURI }
-- | Used to specify the contents of the @Access-Control-Allow-Origin@ header.
data OriginList
= Everywhere
-- ^ Allow any origin to access this resource. Corresponds to
-- @Access-Control-Allow-Origin: *@
| Nowhere
-- ^ Do not allow cross-origin requests
| Origins OriginSet
-- ^ Allow cross-origin requests from these origins.
-- | Specify the options to use when building CORS headers for a response. Most
-- of these options are 'Snap.Handler' actions to allow you to conditionally
-- determine the setting of each header.
data CORSOptions m = CORSOptions
{ corsAllowOrigin :: m OriginList
-- ^ Which origins are allowed to make cross-origin requests.
, corsAllowCredentials :: m Bool
-- ^ Whether or not to allow exposing the response when the omit credentials
-- flag is unset.
, corsExposeHeaders :: m (HashSet.HashSet (CI Char8.ByteString))
-- ^ A list of headers that are exposed to clients. This allows clients to
-- read the values of these headers, if the response includes them.
, corsAllowedMethods :: m (HashSet.HashSet HashableMethod)
-- ^ A list of request methods that are allowed.
, corsAllowedHeaders :: HashSet.HashSet String -> m (HashSet.HashSet String)
-- ^ An action to determine which of the request headers are allowed.
-- This action is supplied the parsed contents of
-- @Access-Control-Request-Headers@.
, corsMaxAge :: m (Maybe Int)
-- ^ Set the maximum number of seconds that a preflight authorization is
-- valid for.
}
-- | Liberal default options. Specifies that:
--
-- * All origins may make cross-origin requests
-- * @allow-credentials@ is true.
-- * No extra headers beyond simple headers are exposed.
-- * @GET@, @POST@, @PUT@, @DELETE@ and @HEAD@ are all allowed.
-- * All request headers are allowed.
--
-- All options are determined unconditionally.
defaultOptions :: Monad m => CORSOptions m
defaultOptions = CORSOptions
{ corsAllowOrigin = return Everywhere
, corsAllowCredentials = return True
, corsExposeHeaders = return HashSet.empty
, corsAllowedMethods =
return $ HashSet.fromList $ map HashableMethod
[ Snap.GET, Snap.POST, Snap.PUT, Snap.DELETE, Snap.HEAD ]
, corsAllowedHeaders = return
, corsMaxAge = return Nothing
}
-- | Apply CORS headers to a specific request. This is useful if you only have
-- a single action that needs CORS headers, and you don't want to pay for
-- conditional checks on every request.
--
-- You should note that 'applyCORS' needs to be used before you add any
-- 'Snap.method' combinators. For example, the following won't do what you want:
--
-- > method POST $ applyCORS defaultOptions $ myHandler
--
-- This fails to work as CORS requires an @OPTIONS@ request in the preflighting
-- stage, but this would get filtered out. Instead, use
--
-- > applyCORS defaultOptions $ method POST $ myHandler
applyCORS :: CORSOptions Snap.Snap -> Snap.Snap () -> Snap.Snap ()
applyCORS options m = do
mbRawOrigin <- getHeader "Origin"
case decodeOrigin =<< mbRawOrigin of
Nothing -> m
Just origin -> corsRequestFrom origin
where
corsRequestFrom origin = do
originList <- corsAllowOrigin options
if origin `inOriginList` originList
then Snap.method Snap.OPTIONS (preflightRequestFrom origin)
<|> handleRequestFrom origin
else m
preflightRequestFrom origin = do
maybeMethod <- fmap (parseMethod . Char8.unpack) <$>
getHeader "Access-Control-Request-Method"
case maybeMethod of
Nothing -> m
Just method -> do
allowedMethods <- corsAllowedMethods options
if method `HashSet.member` allowedMethods
then do
maybeHeaders <-
fromMaybe (Just HashSet.empty) . fmap splitHeaders
<$> getHeader "Access-Control-Request-Headers"
case maybeHeaders of
Nothing -> m
Just headers -> do
allowedHeaders <- corsAllowedHeaders options headers
if not $ HashSet.null $ headers `HashSet.difference` allowedHeaders
then m
else do
addAccessControlAllowOrigin origin
addAccessControlAllowCredentials
commaSepHeader
"Access-Control-Allow-Headers"
Char8.pack (HashSet.toList allowedHeaders)
commaSepHeader
"Access-Control-Allow-Methods"
(Char8.pack . show) (HashSet.toList allowedMethods)
mbMaxAge <- corsMaxAge options
for_ mbMaxAge addAccessControlMaxAge
else m
handleRequestFrom origin = do
addAccessControlAllowOrigin origin
addAccessControlAllowCredentials
exposeHeaders <- corsExposeHeaders options
when (not $ HashSet.null exposeHeaders) $
commaSepHeader
"Access-Control-Expose-Headers"
CI.original (HashSet.toList exposeHeaders)
m
addAccessControlAllowOrigin origin =
addHeader "Access-Control-Allow-Origin"
(encodeUtf8 $ Text.pack $ show origin)
addAccessControlMaxAge maxAge =
addHeader "Access-Control-Max-Age"
$ encodeUtf8 $ Text.pack $ show maxAge
addAccessControlAllowCredentials = do
allowCredentials <- corsAllowCredentials options
when (allowCredentials) $
addHeader "Access-Control-Allow-Credentials" "true"
decodeOrigin = fmap simplifyURI . parseURI . Text.unpack . decodeUtf8
addHeader k v = Snap.modifyResponse (Snap.addHeader k v)
commaSepHeader k f vs =
case vs of
[] -> return ()
_ -> addHeader k $ Char8.intercalate ", " (map f vs)
getHeader = Snap.getsRequest . Snap.getHeader
splitHeaders =
let spaces = Attoparsec.many' Attoparsec.space
headerC = Attoparsec.satisfy (not . (`elem` (" ," :: String)))
headerName = Attoparsec.many' headerC
header = spaces *> headerName <* spaces
parser = HashSet.fromList <$> header `Attoparsec.sepBy` (Attoparsec.char ',')
in either (const Nothing) Just . Attoparsec.parseOnly parser
mkOriginSet :: [URI] -> OriginSet
mkOriginSet = OriginSet . HashSet.fromList . map (HashableURI . simplifyURI)
simplifyURI :: URI -> URI
simplifyURI uri = uri { uriAuthority = fmap simplifyURIAuth (uriAuthority uri)
, uriPath = ""
, uriQuery = ""
, uriFragment = ""
}
where simplifyURIAuth auth = auth { uriUserInfo = "" }
--------------------------------------------------------------------------------
parseMethod :: String -> HashableMethod
parseMethod "GET" = HashableMethod Snap.GET
parseMethod "POST" = HashableMethod Snap.POST
parseMethod "HEAD" = HashableMethod Snap.HEAD
parseMethod "PUT" = HashableMethod Snap.PUT
parseMethod "DELETE" = HashableMethod Snap.DELETE
parseMethod "TRACE" = HashableMethod Snap.TRACE
parseMethod "OPTIONS" = HashableMethod Snap.OPTIONS
parseMethod "CONNECT" = HashableMethod Snap.CONNECT
parseMethod "PATCH" = HashableMethod Snap.PATCH
parseMethod s = HashableMethod $ Snap.Method (Char8.pack s)
--------------------------------------------------------------------------------
-- | A @newtype@ over 'URI' with a 'Hashable' instance.
newtype HashableURI = HashableURI URI
deriving (Eq)
instance Show HashableURI where
show (HashableURI u) = show u
instance Hashable HashableURI where
hashWithSalt s (HashableURI (URI scheme authority path query fragment)) =
s `hashWithSalt`
scheme `hashWithSalt`
fmap hashAuthority authority `hashWithSalt`
path `hashWithSalt`
query `hashWithSalt`
fragment
where
hashAuthority (URIAuth userInfo regName port) =
s `hashWithSalt`
userInfo `hashWithSalt`
regName `hashWithSalt`
port
inOriginList :: URI -> OriginList -> Bool
_ `inOriginList` Nowhere = False
_ `inOriginList` Everywhere = True
origin `inOriginList` (Origins (OriginSet xs)) =
HashableURI origin `HashSet.member` xs
--------------------------------------------------------------------------------
newtype HashableMethod = HashableMethod Snap.Method
deriving (Eq)
instance Hashable HashableMethod where
hashWithSalt s (HashableMethod Snap.GET) = s `hashWithSalt` (0 :: Int)
hashWithSalt s (HashableMethod Snap.HEAD) = s `hashWithSalt` (1 :: Int)
hashWithSalt s (HashableMethod Snap.POST) = s `hashWithSalt` (2 :: Int)
hashWithSalt s (HashableMethod Snap.PUT) = s `hashWithSalt` (3 :: Int)
hashWithSalt s (HashableMethod Snap.DELETE) = s `hashWithSalt` (4 :: Int)
hashWithSalt s (HashableMethod Snap.TRACE) = s `hashWithSalt` (5 :: Int)
hashWithSalt s (HashableMethod Snap.OPTIONS) = s `hashWithSalt` (6 :: Int)
hashWithSalt s (HashableMethod Snap.CONNECT) = s `hashWithSalt` (7 :: Int)
hashWithSalt s (HashableMethod Snap.PATCH) = s `hashWithSalt` (8 :: Int)
hashWithSalt s (HashableMethod (Snap.Method m)) =
s `hashWithSalt` (9 :: Int) `hashWithSalt` m
instance Show HashableMethod where
show (HashableMethod m) = show m
|
GaloisInc/verification-game
|
web-prover/src/CORS.hs
|
Haskell
|
bsd-3-clause
| 10,675
|
-- Min Zhang
-- March 2, 2016
-- LongestAlignment
-- BLAST algorithm
-- Find longest strech of matching
-- random generation sequences that match the probability
-- Not working yet
seq1 = [0, -1, -2, -1, -2, -1, -2, -1, 0, 1, 0, -1, -2, -3, -4]
value = fst
pos = snd
f [] (a, b, c, d) = (a, b, c, d)
f (x:xs) (min_, max_, minLoc, maxLoc)
| value x < min_ && minLoc <= maxLoc = f xs (value x, max_, pos x, pos x)
| value x < min_ = f xs (min_, max_, minLoc, maxLoc)
| value x > max_ && (pos x) - minLoc + 1 > len = f xs (min_, value x, minLoc, pos x)
| otherwise = f xs (min_, max_, minLoc, maxLoc)
where len = maxLoc - minLoc + 1
|
Min-/HaskellSandbox
|
src/LongestAlignment.hs
|
Haskell
|
bsd-3-clause
| 650
|
module ActorQueue where
import Control.Category
import Control.Lens
import qualified Data.Dequeue as DQ
import Prelude hiding (Either(..), id, (.))
import Entity
type ActorQueue = DQ.BankersDequeue EntityRef
dropFront :: ActorQueue -> ActorQueue
dropFront queue =
case DQ.popFront queue of
Nothing -> DQ.empty
Just (_ ,q) -> q
rotate :: ActorQueue -> ActorQueue
rotate queue = queueChoice
where
potentialQ = do
(exiting,queue') <- DQ.popFront queue
return $ DQ.pushBack queue' exiting
queueChoice =
case potentialQ of
Nothing -> queue
(Just q) -> q
actionPointsOfEntity :: Maybe Entity -> Maybe Int
actionPointsOfEntity eM = do
e <- eM
actor' <- e ^. actor
return $ actor' ^. actionPoints
enoughActionPoints :: Maybe Int -> Bool
enoughActionPoints p =
case p of
Nothing -> False
Just p' -> p' > 0
stillActive :: Maybe Entity -> Bool
stillActive = (enoughActionPoints <<< actionPointsOfEntity)
|
fros1y/umbral
|
src/ActorQueue.hs
|
Haskell
|
bsd-3-clause
| 1,010
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fplugin Brisk.Plugin #-}
{-# OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-}
module Scratch where
import Control.Distributed.Process
main :: Process ()
main = do me <- getSelfPid
spawnLocal $ send me ()
expect
|
abakst/brisk-prelude
|
examples/spawn01.hs
|
Haskell
|
bsd-3-clause
| 285
|
-- Quantities
-- Copyright (C) 2015-2016 Moritz Schulte <mtesseract@silverratio.net>
-- API is not necessarily stable.
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Quantities.Parser
( parseNumber
, parseFraction
, parseInt
, parseDecimal
, parseMixed
, parseQuantity
) where
import Data.Char
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import Formatting
import Numeric (readFloat, readSigned)
import Quantities.Types
import Quantities.Units
import Quantities.Util
import Text.Read
-------------
-- Parsers --
-------------
-- | Try to parse an Integer.
parseInt :: Text -> Either Text Integer
parseInt s =
let result = readMaybe (T.unpack s) :: Maybe Integer
in case result of
Nothing -> Left $ format ("Failed to parse integer `" % text % "'") s
Just x -> Right x
-- | Try to parse a fraction of the form "x/y" into a Rational.
parseFraction :: Text -> Either Text Rational
parseFraction s =
let result = readMaybe (T.unpack (T.replace "/" "%" s))
in case result of
Nothing -> Left $ format ("Failed to parse fraction `" % text % "'") s
Just x -> Right x
-- | Try to parse a decimal number.
parseDecimal :: Text -> Either Text Rational
parseDecimal s =
let result = readSigned readFloat (T.unpack s) :: [(Rational, String)]
in case result of
[(x, "")] -> Right x
_ -> Left $ format ("Failed to parse decimal number `" % text % "'") s
-- | Try to parse a mixed number, e.g. a number of the form "5 23/42".
parseMixed :: Text -> Either Text Rational
parseMixed s =
let components = T.words s
in case components of
[c0] ->
if contains '/' c0
then parseFraction c0
else fromInteger <$> parseInt c0
[c0, c1] -> do
i <- parseInt c0
frac <- parseFraction c1
case (i < 0, frac < 0) of
(False, False) -> Right $ fromInteger i + frac
(True, False) -> Right $ -1 * (fromInteger (abs i) + frac)
(False, True) -> Left errNoParse
(True, True) -> Left errNoParse
_ -> Left errNoParse
where errNoParse = "No Parse"
contains c t = (not . T.null . T.filter (== c)) t
-- | Try to parse a given number in string representation. First try
-- to parse it as a decimal number and if that fails, try to parse it
-- as a mixed number.
parseNumber :: Text -> Either Text Rational
parseNumber s' =
let s = T.strip s'
in eitherAlternative "Failed to parse number"
[parseDecimal s, parseMixed s]
-- | Parse a given quantity in its string representation, e.g. a
-- string of the form "0.7 l".
parseQuantity :: (Text -> Either Text Rational) -> Text -> Either Text Quantity
parseQuantity parser s = do
let (w0, w1) = splitAtUnit s
u = stringToUnit w1
num <- parser w0
return $ Quantity num u
where splitAtUnit t =
let num = T.takeWhile (not . isAlpha) t
u = T.drop (T.length num) t
in (num, u)
|
mtesseract/quantities
|
src/Quantities/Parser.hs
|
Haskell
|
bsd-3-clause
| 3,083
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE CPP #-}
module Common where
import Data.Proxy
import Servant.API
#if MIN_VERSION_servant(0,10,0)
import Servant.Utils.Links
#endif
import Miso
import Miso.String
data Model = Model { modelUri :: URI, modelMsg :: String }
deriving (Show, Eq)
data Action
= ServerMsg String
| NoOp
| ChangeURI URI
| HandleURI URI
deriving (Show, Eq)
home :: Model -> View Action
home (Model _ msg) =
div_ [] [div_ [] [h3_ [] [text "SSE (Server-sent events) Example"]], text $ ms msg]
-- There is only a single route in this example
type ClientRoutes = Home
type Home = View Action
handlers :: Model -> View Action
handlers = home
the404 :: View Action
the404 =
div_
[]
[ text "404: Page not found"
, a_ [onClick $ ChangeURI goHome] [text " - Go Home"]
]
goHome :: URI
goHome =
#if MIN_VERSION_servant(0,10,0)
linkURI (safeLink (Proxy :: Proxy ClientRoutes) (Proxy :: Proxy Home))
#else
safeLink (Proxy :: Proxy ClientRoutes) (Proxy :: Proxy Home)
#endif
|
dmjio/miso
|
examples/sse/shared/Common.hs
|
Haskell
|
bsd-3-clause
| 1,030
|
module Tests.Twitch.Path where
import Test.Hspec
tests :: Spec
tests = return ()
|
menelaos/twitch
|
tests/Tests/Twitch/Path.hs
|
Haskell
|
mit
| 81
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2013-15 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-----------------------------------------------------------------------------
module Succinct.Internal.Word4
( Word4(..)
, UM.MVector(MV_Word4)
, U.Vector(V_Word4)
, ny
, wds
, wd
) where
import Control.Monad
import Data.Bits
import Data.Vector.Generic as G
import Data.Vector.Generic.Mutable as GM
import Data.Vector.Primitive as P
import Data.Vector.Primitive.Mutable as PM
import Data.Vector.Unboxed as U
import Data.Vector.Unboxed.Mutable as UM
import Data.Word
newtype Word4 = Word4 Word8 deriving (Eq,Ord)
instance Show Word4 where
showsPrec d (Word4 n) = Prelude.showsPrec d n
instance Read Word4 where
readsPrec d r = [ (Word4 n, r') | (n,r') <- readsPrec d r, n <= 15 ]
instance Num Word4 where
Word4 n + Word4 m = Word4 $ (n + m) .&. 15
Word4 n - Word4 m = Word4 $ (n - m) .&. 15
Word4 n * Word4 m = Word4 $ (n * m) .&. 15
fromInteger n = Word4 (fromInteger n .&. 15)
abs n = n
signum (Word4 n) = Word4 $ signum n
instance Bits Word4 where
Word4 n .&. Word4 m = Word4 (n .&. m)
Word4 n .|. Word4 m = Word4 (n .|. m)
xor (Word4 n) (Word4 m) = Word4 (xor n m .&. 15)
complement (Word4 n) = Word4 (complement n .&. 15)
shift (Word4 n) i = Word4 (shift n i .&. 15)
shiftL (Word4 n) i = Word4 (shiftL n i .&. 15)
shiftR (Word4 n) i = Word4 (shiftR n i .&. 15)
unsafeShiftL (Word4 n) i = Word4 (unsafeShiftL n i .&. 15)
unsafeShiftR (Word4 n) i = Word4 (unsafeShiftR n i .&. 15)
rotate (Word4 n) i = Word4 $ (unsafeShiftL n (i .&. 3) .|. unsafeShiftR n (negate i .&. 3)) .&. 15
rotateL (Word4 n) i = Word4 $ (unsafeShiftL n (i .&. 3) .|. unsafeShiftR n (negate i .&. 3)) .&. 15
rotateR (Word4 n) i = Word4 $ (unsafeShiftL n (negate i .&. 3) .|. unsafeShiftR n (i .&. 3)) .&. 15
bit i = Word4 (bit i .&. 15)
setBit (Word4 n) i = Word4 (setBit n i .&. 15)
clearBit (Word4 n) i = Word4 (clearBit n i .&. 15)
complementBit (Word4 n) i = Word4 (complementBit n i .&. 15)
testBit (Word4 n) i = testBit n i
bitSize _ = 4
isSigned _ = False
popCount (Word4 n) = popCount n
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
bitSizeMaybe _ = Just 4
#endif
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ >= 707
instance FiniteBits Word4 where
finiteBitSize _ = 4
#endif
instance Real Word4 where
toRational (Word4 n) = toRational n
instance Integral Word4 where
quot (Word4 m) (Word4 n) = Word4 (quot m n .&. 15)
rem (Word4 m) (Word4 n) = Word4 (rem m n .&. 15)
div (Word4 m) (Word4 n) = Word4 (div m n .&. 15)
mod (Word4 m) (Word4 n) = Word4 (mod m n .&. 15)
quotRem (Word4 m) (Word4 n) = case quotRem m n of
(q, r) -> (Word4 $ q .&. 15, Word4 $ r .&. 15)
divMod (Word4 m) (Word4 n) = case divMod m n of
(q, r) -> (Word4 $ q .&. 15, Word4 $ r .&. 15)
toInteger (Word4 n) = toInteger n
instance Bounded Word4 where
minBound = Word4 0
maxBound = Word4 15
instance Enum Word4 where
succ (Word4 n)
| n == 15 = error "Prelude.Enum.succ{Word4}: tried to take `succ' of maxBound"
| otherwise = Word4 (n + 1)
pred (Word4 n)
| n == 0 = error "Prelude.Enum.pred{Word4}: tried to take `pred' of minBound"
| otherwise = Word4 (n - 1)
toEnum n
| n == n .&. 15 = Word4 (fromIntegral n)
| otherwise = error $ "Enum.toEnum{Word4}: tag (" Prelude.++ show n Prelude.++ ") is outside of bounds (0,15)"
fromEnum (Word4 n) = fromEnum n
instance UM.Unbox Word4
ny :: Int -> Int
ny x = x .&. 15
{-# INLINE ny #-}
wd :: Int -> Int
wd x = unsafeShiftR x 4
{-# INLINE wd #-}
wds :: Int -> Int
wds x = unsafeShiftR (x + 15) 4
{-# INLINE wds #-}
getWord4 :: Word64 -> Int -> Word4
getWord4 w n = Word4 $ fromIntegral (unsafeShiftR w (4*n) .&. 0xf)
{-# INLINE getWord4 #-}
setWord4 :: Word64 -> Int -> Word4 -> Word64
setWord4 w n (Word4 w4) = w .&. complement (unsafeShiftL 0xf n4) .|. unsafeShiftL (fromIntegral w4) n4
where !n4 = 4*n
{-# INLINE setWord4 #-}
data instance UM.MVector s Word4 = MV_Word4 {-# UNPACK #-} !Int !(PM.MVector s Word64)
tile :: Word4 -> Word64
tile (Word4 b) = b4
where !b0 = fromIntegral b
!b1 = b0 .|. unsafeShiftL b0 4
!b2 = b1 .|. unsafeShiftL b1 8
!b3 = b2 .|. unsafeShiftL b2 16
!b4 = b3 .|. unsafeShiftL b3 32
instance GM.MVector U.MVector Word4 where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicOverlaps #-}
{-# INLINE basicUnsafeNew #-}
{-# INLINE basicUnsafeReplicate #-}
{-# INLINE basicUnsafeRead #-}
{-# INLINE basicUnsafeWrite #-}
{-# INLINE basicClear #-}
{-# INLINE basicSet #-}
{-# INLINE basicUnsafeCopy #-}
{-# INLINE basicUnsafeGrow #-}
basicLength (MV_Word4 n _) = n
basicUnsafeSlice i n (MV_Word4 _ u) = MV_Word4 n $ GM.basicUnsafeSlice i (wds n) u
basicOverlaps (MV_Word4 _ v1) (MV_Word4 _ v2) = GM.basicOverlaps v1 v2
basicUnsafeNew n = do
v <- GM.basicUnsafeNew (wds n)
return $ MV_Word4 n v
basicUnsafeReplicate n w4 = do
v <- GM.basicUnsafeReplicate (wds n) (tile w4)
return $ MV_Word4 n v
basicUnsafeRead (MV_Word4 _ u) i = do
w <- GM.basicUnsafeRead u (wd i)
return $ getWord4 w (ny i)
basicUnsafeWrite (MV_Word4 _ u) i w4 = do
let wn = wd i
w <- GM.basicUnsafeRead u wn
GM.basicUnsafeWrite u wn (setWord4 w (ny i) w4)
basicClear (MV_Word4 _ u) = GM.basicClear u
basicSet (MV_Word4 _ u) w4 = GM.basicSet u (tile w4)
basicUnsafeCopy (MV_Word4 _ u1) (MV_Word4 _ u2) = GM.basicUnsafeCopy u1 u2
basicUnsafeMove (MV_Word4 _ u1) (MV_Word4 _ u2) = GM.basicUnsafeMove u1 u2
basicUnsafeGrow (MV_Word4 _ u) n = liftM (MV_Word4 n) (GM.basicUnsafeGrow u (wds n))
data instance U.Vector Word4 = V_Word4 {-# UNPACK #-} !Int !(P.Vector Word64)
instance G.Vector U.Vector Word4 where
{-# INLINE basicLength #-}
{-# INLINE basicUnsafeFreeze #-}
{-# INLINE basicUnsafeThaw #-}
{-# INLINE basicUnsafeSlice #-}
{-# INLINE basicUnsafeIndexM #-}
{-# INLINE elemseq #-}
basicLength (V_Word4 n _) = n
basicUnsafeFreeze (MV_Word4 n u) = liftM (V_Word4 n) (G.basicUnsafeFreeze u)
basicUnsafeThaw (V_Word4 n u) = liftM (MV_Word4 n) (G.basicUnsafeThaw u)
basicUnsafeSlice i n (V_Word4 _ u) = V_Word4 n (G.basicUnsafeSlice i (wds n) u)
basicUnsafeIndexM (V_Word4 _ u) i = do
w <- G.basicUnsafeIndexM u (wd i)
return $ getWord4 w (ny i)
basicUnsafeCopy (MV_Word4 _ mu) (V_Word4 _ u) = G.basicUnsafeCopy mu u
elemseq _ b z = b `seq` z
|
Gabriel439/succinct
|
src/Succinct/Internal/Word4.hs
|
Haskell
|
bsd-2-clause
| 6,818
|
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Marshal
-- Copyright : (c) The FFI task force 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Marshalling support
--
-----------------------------------------------------------------------------
module Foreign.Marshal
( module Foreign.Marshal.Alloc
, module Foreign.Marshal.Array
, module Foreign.Marshal.Error
, module Foreign.Marshal.Pool
, module Foreign.Marshal.Utils
) where
import Foreign.Marshal.Alloc
import Foreign.Marshal.Array
import Foreign.Marshal.Error
import Foreign.Marshal.Pool
import Foreign.Marshal.Utils
|
FranklinChen/hugs98-plus-Sep2006
|
packages/base/Foreign/Marshal.hs
|
Haskell
|
bsd-3-clause
| 852
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module ServerMonad (
ServerMonad, evalServerMonad, mkServerState,
getUser,
getProtocolVersion,
getLastReadyTime, setLastReadyTime,
getUserInfo,
getDirectory, getNotifierVar,
-- XXX Don't really belong here:
Directory(..), MessagerRequest(..),
getConfig,
NVar,
CHVar, ConfigHandlerRequest(..),
TimeMasterVar, getLocalTimeInTz,
baseDir,
Ppr(..), Who(..), ClientThread(..), CoreThread(..),
verbose, verbose', warn, warn',
) where
import Builder.Config
import Builder.Handlelike
import Builder.Utils
import Control.Applicative
import Control.Concurrent.MVar
import Control.Monad.State
import Data.Time.Format
import Data.Time.LocalTime
import Network.Socket
#if !MIN_VERSION_time(1,5,0)
import System.Locale
#endif
type NVar = MVar (User, BuildNum)
type CHVar = MVar ConfigHandlerRequest
type MessagerVar = MVar MessagerRequest
type TimeMasterVar = MVar (String, MVar LocalTime)
data ConfigHandlerRequest = ReloadConfig
| GiveMeConfig (MVar Config)
data MessagerRequest = Message Verbosity String
| Reopen
baseDir :: FilePath
baseDir = "data"
newtype ServerMonad a = ServerMonad (StateT ServerState IO a)
deriving (Functor, Applicative, Monad, MonadIO)
data ServerState = ServerState {
ss_handleOrSsl :: HandleOrSsl,
ss_user :: String,
ss_protocolVersion :: ProtocolVersion,
ss_directory :: Directory,
ss_last_ready_time :: TimeOfDay
}
mkServerState :: HandleOrSsl
-> User
-> ProtocolVersion
-> Directory
-> TimeOfDay
-> ServerState
mkServerState h u pv directory lrt
= ServerState {
ss_handleOrSsl = h,
ss_user = u,
ss_protocolVersion = pv,
ss_directory = directory,
ss_last_ready_time = lrt
}
evalServerMonad :: ServerMonad a -> ServerState -> IO a
evalServerMonad (ServerMonad m) cs = evalStateT m cs
getHandleOrSsl :: ServerMonad HandleOrSsl
getHandleOrSsl = do st <- ServerMonad get
return $ ss_handleOrSsl st
getUser :: ServerMonad String
getUser = do st <- ServerMonad get
return $ ss_user st
getProtocolVersion :: ServerMonad ProtocolVersion
getProtocolVersion = do st <- ServerMonad get
return $ ss_protocolVersion st
getLastReadyTime :: ServerMonad TimeOfDay
getLastReadyTime = do st <- ServerMonad get
return $ ss_last_ready_time st
setLastReadyTime :: TimeOfDay -> ServerMonad ()
setLastReadyTime tod = do st <- ServerMonad get
ServerMonad $ put $ st { ss_last_ready_time = tod }
getUserInfo :: ServerMonad (Maybe UserInfo)
getUserInfo = do st <- ServerMonad get
config <- liftIO $ getConfig (ss_directory st)
return $ lookup (ss_user st) $ config_clients config
getDirectory :: ServerMonad Directory
getDirectory = do st <- ServerMonad get
return $ ss_directory st
getNotifierVar :: ServerMonad NVar
getNotifierVar = liftM dir_notifierVar $ getDirectory
instance HandlelikeM ServerMonad where
hlPutStrLn str = do h <- getHandleOrSsl
liftIO $ hlPutStrLn' h str
hlGetLine = do h <- getHandleOrSsl
liftIO $ hlGetLine' h
hlGet n = do h <- getHandleOrSsl
liftIO $ hlGet' h n
data Directory = Directory {
dir_messagerVar :: MessagerVar,
dir_notifierVar :: NVar,
dir_configHandlerVar :: CHVar,
dir_timeMasterVar :: TimeMasterVar
}
getConfig :: Directory -> IO Config
getConfig directory
= do mv <- newEmptyMVar
putMVar (dir_configHandlerVar directory) (GiveMeConfig mv)
takeMVar mv
verbose :: String -> ServerMonad ()
verbose str = do directory <- getDirectory
u <- getUser
liftIO $ verbose' directory (ClientThread (User u)) str
warn :: String -> ServerMonad ()
warn str = do directory <- getDirectory
u <- getUser
liftIO $ warn' directory (ClientThread (User u)) str
verbose' :: Directory -> Who -> String -> IO ()
verbose' directory who str = message' directory Verbose who str
warn' :: Directory -> Who -> String -> IO ()
warn' directory who str = message' directory Normal who ("Warning: " ++ str)
message' :: Directory -> Verbosity -> Who -> String -> IO ()
message' directory verbosity who str
= do lt <- getLocalTimeInTz directory "UTC"
let fmt = "[%Y-%m-%d %H:%M:%S]"
t = formatTime defaultTimeLocale fmt lt
putMVar (dir_messagerVar directory)
(Message verbosity $ unwords [t, ppr who, str])
data Who = ClientThread ClientThread
| CoreThread CoreThread
| AddrThread SockAddr
data ClientThread = User User
| Unauthed SockAddr
data CoreThread = MessagerThread
| NotifierThread
| ConfigThread
| TimeThread
| MainThread
class Ppr a where
ppr :: a -> String
instance Ppr Who where
ppr (ClientThread ct) = "[" ++ ppr ct ++ "]"
ppr (CoreThread ct) = "[core:" ++ ppr ct ++ "]"
ppr (AddrThread sa) = "[addr:" ++ ppr sa ++ "]"
instance Ppr ClientThread where
ppr (User u) = "U:" ++ u
ppr (Unauthed a) = "unauthed:" ++ ppr a
instance Ppr CoreThread where
ppr MessagerThread = "Messager"
ppr NotifierThread = "Notifier"
ppr ConfigThread = "Config handler"
ppr TimeThread = "Time"
ppr MainThread = "Main"
instance Ppr SockAddr where
ppr = show
getLocalTimeInTz :: Directory -> String -> IO LocalTime
getLocalTimeInTz directory tz
= do mv <- newEmptyMVar
putMVar (dir_timeMasterVar directory) (tz, mv)
takeMVar mv
|
haskell/ghc-builder
|
server/ServerMonad.hs
|
Haskell
|
bsd-3-clause
| 6,274
|
module Syntax.Env where
import Syntax.Tree (Identifier)
import Data.Map as Map
-- Keeps track of declarations at this scope, and the scope above.
-- And the type of identifiers in the environment.
data Env a = Env {
-- Declarations in the scope above. These can be overwritten.
aboveScope :: Map Identifier a,
-- Declarations in the current scope. These cannot be overwritten.
used :: Map Identifier a
}
instance (Show a) => Show (Env a) where
show (Env a u) = "above: " ++ (show a) ++ ", used: " ++ (show u)
-- Returns the combination of both scopes to make for easier searching.
combinedScopes :: Env a -> Map Identifier a
-- used before above so conficts use the inner-most definiton.
combinedScopes (Env above used) = Map.union used above
empty :: Env a
empty = Env Map.empty Map.empty
-- State containing the list of used identifiers at the current scope.
fromList :: [(Identifier, a)] -> Env a
fromList usedIds = Env Map.empty (Map.fromList usedIds)
-- Adds a variable name to the current scope.
put :: Identifier -> a -> Env a -> Env a
put newId idType (Env above used) = Env above used' where
used' = Map.insert newId idType used
-- Returns whether a identifier can be used, i.e. if the identifier has been
-- declared in this scope or the scope above.
get :: Identifier -> Env a -> Maybe a
get i env = i `Map.lookup` (combinedScopes env)
-- Retrive the identifier from the environment and modify it. If the identifier
-- does not exist then the supplied env is returned.
modify :: Identifier -> (a -> a) -> Env a -> Env a
modify i f env = case get i env of
Nothing -> env
Just x -> put i (f x) env
-- Moves any used names into the scope above.
descendScope :: Env a -> Env a
descendScope env = Env (combinedScopes env) Map.empty
-- Returns whether a identifier has already been used to declare a variable/function.
-- i.e. if the name is in use at this scope.
isTaken :: Identifier -> Env a -> Bool
isTaken i (Env _ used) = i `Map.member` used
|
BakerSmithA/Turing
|
src/Syntax/Env.hs
|
Haskell
|
bsd-3-clause
| 1,997
|
-- |
-- Module : Console.Options
-- License : BSD-style
-- Maintainer : Vincent Hanquez <vincent@snarc.org>
-- Stability : experimental
-- Portability : Good
--
-- Options parsing using a simple DSL approach.
--
-- Using this API, your program should have the following shape:
--
-- >defaultMain $ do
-- > f1 <- flag ..
-- > f2 <- argument ..
-- > action $ \toParam ->
-- > something (toParam f1) (toParam f2) ..
--
-- You can also define subcommand using:
--
-- >defaultMain $ do
-- > subcommand "foo" $ do
-- > <..flags & parameters definitions...>
-- > action $ \toParam -> <..IO-action..>
-- > subcommand "bar" $ do
-- > <..flags & parameters definitions...>
-- > action $ \toParam -> <..IO-action..>
--
-- Example:
--
-- >main = defaultMain $ do
-- > programName "test-cli"
-- > programDescription "test CLI program"
-- > flagA <- flag $ FlagShort 'a' <> FlagLong "aaa"
-- > allArgs <- remainingArguments "FILE"
-- > action $ \toParam -> do
-- > putStrLn $ "using flag A : " ++ show (toParam flagA)
-- > putStrLn $ "args: " ++ show (toParam allArgs)
--
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TypeFamilies #-}
module Console.Options
(
-- * Running
defaultMain
, defaultMainWith
, parseOptions
, OptionRes(..)
, OptionDesc
-- * Description
, programName
, programVersion
, programDescription
, command
, FlagFrag(..)
, flag
, flagParam
, flagMany
-- , conflict
, argument
, remainingArguments
, action
, description
, Action
-- * Arguments
, ValueParser
, FlagParser(..)
, Flag
, FlagLevel
, FlagParam
, FlagMany
, Arg
, ArgRemaining
, Params
, paramsFlags
, getParams
) where
import Foundation (toList, toCount, fromList)
import Console.Options.Flags hiding (Flag)
import qualified Console.Options.Flags as F
import Console.Options.Nid
import Console.Options.Utils
import Console.Options.Monad
import Console.Options.Types
import Console.Display (justify, Justify(..))
import Control.Applicative
import Control.Monad
import Control.Monad.IO.Class
import Data.List
import Data.Maybe (fromMaybe)
import Data.Version
import Data.Functor.Identity
import System.Environment (getArgs, getProgName)
import System.Exit
----------------------------------------------------------------------
setDescription :: String -> Command r -> Command r
setDescription desc (Command hier _ opts act) = Command hier desc opts act
setAction :: Action r -> Command r -> Command r
setAction act (Command hier desc opts _) = Command hier desc opts (ActionWrapped act)
addOption :: FlagDesc -> Command r -> Command r
addOption opt (Command hier desc opts act) = Command hier desc (opt : opts) act
tweakOption :: Nid -> (FlagDesc -> FlagDesc) -> Command r -> Command r
tweakOption nid mapFlagDesc (Command hier desc opts act) =
Command hier desc (modifyNid opts) act
where
modifyNid [] = []
modifyNid (f:fs)
| flagNid f == nid = mapFlagDesc f : fs
| otherwise = f : modifyNid fs
addArg :: Argument -> Command r -> Command r
addArg arg = modifyHier $ \hier ->
case hier of
CommandLeaf l -> CommandLeaf (arg:l)
CommandTree {} -> hier -- ignore argument in a hierarchy.
----------------------------------------------------------------------
-- | A parser for a flag's value, either optional or required.
data FlagParser a =
FlagRequired (ValueParser a) -- ^ flag value parser with a required parameter.
| FlagOptional a (ValueParser a) -- ^ Optional flag value parser: Default value if not present to a
-- | A parser for a value. In case parsing failed Left should be returned.
type ValueParser a = String -> Either String a
-- | return value of the option parser. only needed when using 'parseOptions' directly
data OptionRes r =
OptionSuccess Params (Action r)
| OptionHelp
| OptionError String -- user cmdline error in the arguments
| OptionInvalid String -- API has been misused
-- | run parse options description on the action
--
-- to be able to specify the arguments manually (e.g. pre-handling),
-- you can use 'defaultMainWith'.
-- >defaultMain dsl = getArgs >>= defaultMainWith dsl
defaultMain :: OptionDesc (IO ()) () -> IO ()
defaultMain dsl = getArgs >>= defaultMainWith dsl
-- | same as 'defaultMain', but with the argument
defaultMainWith :: OptionDesc (IO ()) () -> [String] -> IO ()
defaultMainWith dsl args = do
progrName <- getProgName
let (programDesc, res) = parseOptions (programName progrName >> dsl) args
in case res of
OptionError s -> putStrLn s >> exitFailure
OptionHelp -> help (stMeta programDesc) (stCT programDesc) >> exitSuccess
OptionSuccess params r -> r (getParams params)
OptionInvalid s -> putStrLn s >> exitFailure
-- | This is only useful when you want to handle all the description parsing
-- manually and need to not automatically execute any action or help/error handling.
--
-- Used for testing the parser.
parseOptions :: OptionDesc r () -> [String] -> (ProgramDesc r, OptionRes r)
parseOptions dsl args =
let descState = gatherDesc dsl
in (descState, runOptions (stCT descState) args)
--helpSubcommand :: [String] -> IO ()
help :: ProgramMeta -> Command (IO ()) -> IO ()
help pmeta (Command hier _ commandOpts _) = do
tell (fromMaybe "<program>" (programMetaName pmeta) ++ " version " ++ fromMaybe "<undefined>" (programMetaVersion pmeta) ++ "\n")
tell "\n"
maybe (return ()) (\d -> tell d >> tell "\n\n") (programMetaDescription pmeta)
tell "Options:\n"
tell "\n"
mapM_ (tell . printOpt 0) commandOpts
case hier of
CommandTree subs -> do
tell "\n"
tell "Commands:\n"
let cmdLength = maximum (map (length . fst) subs) + 2
forM_ subs $ \(n, c) -> tell $ indent 2 (toList (justify JustifyRight (toCount cmdLength) (fromList n)) ++ getCommandDescription c ++ "\n")
tell "\n"
mapM_ (printSub 2) subs
CommandLeaf _ ->
return ()
where
tell = putStr
printSub iLevel (name, cmdOpt) = do
tell $ "\nCommand `" ++ name ++ "':\n\n"
tell $ indent iLevel "Options:\n\n"
mapM_ (tell . printOpt iLevel) (getCommandOptions cmdOpt)
case getCommandHier cmdOpt of
CommandTree subs -> do
tell $ indent iLevel "Commands:\n"
let cmdLength = maximum (map (length . fst) subs) + 2 + iLevel
forM_ subs $ \(n, c) -> tell $ indent (iLevel + 2) (toList (justify JustifyRight (toCount cmdLength) (fromList n)) ++ getCommandDescription c ++ "\n")
tell "\n"
mapM_ (printSub (iLevel + 2)) subs
CommandLeaf _ -> pure ()
--tell . indent 2 ""
printOpt iLevel fd =
let optShort = maybe (replicate 2 ' ') (\c -> "-" ++ [c]) $ flagShort ff
optLong = maybe (replicate 8 ' ') (\s -> "--" ++ s) $ flagLong ff
optDesc = maybe "" (" " ++) $ flagDescription ff
in indent (iLevel + 2) $ intercalate " " [optShort, optLong, optDesc] ++ "\n"
where
ff = flagFragments fd
runOptions :: Command r -- commands
-> [String] -- arguments
-> OptionRes r
runOptions ct allArgs
| "--help" `elem` allArgs = OptionHelp
| "-h" `elem` allArgs = OptionHelp
| otherwise = go [] ct allArgs
where
-- parse recursively using a Command structure
go :: [[F.Flag]] -> Command r -> [String] -> OptionRes r
go parsedOpts (Command hier _ commandOpts act) unparsedArgs =
case parseFlags commandOpts unparsedArgs of
(opts, unparsed, []) -> do
case hier of
-- if we have sub commands, then we pass the unparsed options
-- to their parsers
CommandTree subs -> do
case unparsed of
[] -> errorExpectingMode subs
(x:xs) -> case lookup x subs of
Nothing -> errorInvalidMode x subs
Just subTree -> go (opts:parsedOpts) subTree xs
-- no more subcommand (or none to start with)
CommandLeaf unnamedArgs ->
case validateUnnamedArgs (reverse unnamedArgs) unparsed of
Left err -> errorUnnamedArgument err
Right (pinnedArgs, remainingArgs) -> do
let flags = concat (opts:parsedOpts)
case act of
NoActionWrapped -> OptionInvalid "no action defined"
ActionWrapped a ->
let params = Params flags
pinnedArgs
remainingArgs
in OptionSuccess params a
(_, _, ers) -> do
OptionError $ mconcat $ map showOptionError ers
validateUnnamedArgs :: [Argument] -> [String] -> Either String ([String], [String])
validateUnnamedArgs argOpts l =
v [] argOpts >>= \(opts, _hasCatchall) -> do
let unnamedRequired = length opts
if length l < unnamedRequired
then Left "missing arguments"
else Right $ splitAt unnamedRequired l
where
v :: [Argument] -> [Argument] -> Either String ([Argument], Bool)
v acc [] = Right (reverse acc, False)
v acc (a@(Argument {}):as) = v (a:acc) as
v acc ((ArgumentCatchAll {}):[]) = Right (reverse acc, True)
v _ ((ArgumentCatchAll {}):_ ) = Left "arguments expected after remainingArguments"
showOptionError (FlagError opt i s) = do
let optName = (maybe "" (:[]) $ flagShort $ flagFragments opt) ++ " " ++ (maybe "" id $ flagLong $ flagFragments opt)
in ("error: " ++ show i ++ " option " ++ optName ++ " : " ++ s ++ "\n")
errorUnnamedArgument err =
OptionError $ mconcat
[ "error: " ++ err
, ""
]
errorExpectingMode subs =
OptionError $ mconcat (
[ "error: expecting one of the following mode:\n"
, "\n"
] ++ map (indent 4 . (++ "\n") . fst) subs)
errorInvalidMode got subs =
OptionError $ mconcat (
[ "error: invalid mode '" ++ got ++ "', expecting one of the following mode:\n"
, ""
] ++ map (indent 4 . (++ "\n") . fst) subs)
indent :: Int -> String -> String
indent n s = replicate n ' ' ++ s
-- | Set the program name
--
-- default is the result of base's `getProgName`
programName :: String -> OptionDesc r ()
programName s = modify $ \st -> st { stMeta = (stMeta st) { programMetaName = Just s } }
-- | Set the program version
programVersion :: Version -> OptionDesc r ()
programVersion s = modify $ \st -> st { stMeta = (stMeta st) { programMetaVersion = Just $ showVersion s } }
-- | Set the program description
programDescription :: String -> OptionDesc r ()
programDescription s = modify $ \st -> st { stMeta = (stMeta st) { programMetaDescription = Just s } }
-- | Set the description for a command
description :: String -> OptionDesc r ()
description doc = modify $ \st -> st { stCT = setDescription doc (stCT st) }
modifyHier :: (CommandHier r -> CommandHier r) -> Command r -> Command r
modifyHier f (Command hier desc opts act) = Command (f hier) desc opts act
modifyCT :: (Command r -> Command r) -> OptionDesc r ()
modifyCT f = modify $ \st -> st { stCT = f (stCT st) }
-- | Create a new sub command
command :: String -> OptionDesc r () -> OptionDesc r ()
command name sub = do
let subSt = gatherDesc sub
modifyCT (addCommand (stCT subSt))
--modify $ \st -> st { stCT = addCommand (stCT subSt) $ stCT st }
where addCommand subTree = modifyHier $ \hier ->
case hier of
CommandLeaf _ -> CommandTree [(name,subTree)]
CommandTree t -> CommandTree ((name, subTree) : t)
-- | Set the action to run in this command
action :: Action r -> OptionDesc r ()
action ioAct = modify $ \st -> st { stCT = setAction ioAct (stCT st) }
-- | Flag option either of the form -short or --long
--
-- for flag that doesn't have parameter, use 'flag'
flagParam :: FlagFrag -> FlagParser a -> OptionDesc r (FlagParam a)
flagParam frag fp = do
nid <- getNextID
let fragmentFlatten = flattenFragments frag
let opt = FlagDesc
{ flagFragments = fragmentFlatten
, flagNid = nid
, F.flagArg = argp
, flagArgValidate = validator
, flagArity = 1
}
modify $ \st -> st { stCT = addOption opt (stCT st) }
case mopt of
Just a -> return (FlagParamOpt nid a parser)
Nothing -> return (FlagParam nid parser)
where
(argp, parser, mopt, validator) = case fp of
FlagRequired p -> (FlagArgHave, toArg p, Nothing, isValid p)
FlagOptional a p -> (FlagArgMaybe, toArg p, Just a, isValid p)
toArg :: (String -> Either String a) -> String -> a
toArg p = either (error "internal error toArg") id . p
isValid f = either FlagArgInvalid (const FlagArgValid) . f
-- | Apply on a 'flagParam' to turn into a flag that can
-- be invoked multiples, creating a list of values
-- in the action.
flagMany :: OptionDesc r (FlagParam a) -> OptionDesc r (FlagMany a)
flagMany fp = do
f <- fp
let nid = case f of
FlagParamOpt n _ _ -> n
FlagParam n _ -> n
modify $ \st -> st { stCT = tweakOption nid (\fd -> fd { flagArity = maxBound }) (stCT st) }
return $ FlagMany f
-- | Flag option either of the form -short or --long
--
-- for flag that expect a value (optional or mandatory), uses 'flagArg'
flag :: FlagFrag -> OptionDesc r (Flag Bool)
flag frag = do
nid <- getNextID
let fragmentFlatten = flattenFragments frag
let opt = FlagDesc
{ flagFragments = fragmentFlatten
, flagNid = nid
, F.flagArg = FlagArgNone
, flagArgValidate = error ""
, flagArity = 0
}
modify $ \st -> st { stCT = addOption opt (stCT st) }
return (Flag nid)
-- | An unnamed positional argument
--
-- For now, argument in a point of tree that contains sub trees will be ignored.
-- TODO: record a warning or add a strict mode (for developping the CLI) and error.
argument :: String -> ValueParser a -> OptionDesc r (Arg a)
argument name fp = do
idx <- getNextIndex
let a = Argument { argumentName = name
, argumentDescription = ""
, argumentValidate = either Just (const Nothing) . fp
}
modifyCT $ addArg a
return (Arg idx (either (error "internal error") id . fp))
-- | All the remaining position arguments
--
-- This is useful for example for a program that takes an unbounded list of files
-- as parameters.
remainingArguments :: String -> OptionDesc r (ArgRemaining [String])
remainingArguments name = do
let a = ArgumentCatchAll { argumentName = name
, argumentDescription = ""
}
modifyCT $ addArg a
return ArgsRemaining
-- | give the ability to set options that are conflicting with each other
-- if option a is given with option b then an conflicting error happens
-- conflict :: Flag a -> Flag b -> OptionDesc r ()
-- conflict = undefined
|
NicolasDP/hs-cli
|
Console/Options.hs
|
Haskell
|
bsd-3-clause
| 16,457
|
module Countries where
import Data.Function (on)
import qualified Data.Set as S
import Text.Read
import qualified Text.Read.Lex as L
import Safe
data Country = Country {
countryCode :: String
, countryName :: String
}
instance Show Country where
show (Country c _) = c
showCountry :: Country -> String
showCountry (Country c n) = c ++ " - " ++ n
instance Read Country where
readPrec = parens
( do L.Ident s <- lexP
let i = S.intersection countries $ S.singleton $ Country s ""
case headMay $ S.toList i of
Nothing -> pfail
Just x -> return x
)
instance Eq Country where
(==) = (==) `on` countryCode
instance Ord Country where
compare = compare `on` countryCode
countries :: S.Set Country
countries = S.fromAscList
[ Country "AD" "Andorra"
, Country "AE" "United Arab Emirates"
, Country "AF" "Afghanistan"
, Country "AG" "Antigua and Barbuda"
, Country "AI" "Anguilla"
, Country "AL" "Albania"
, Country "AM" "Armenia"
, Country "AO" "Angola"
, Country "AQ" "Antarctica"
, Country "AR" "Argentina"
, Country "AS" "American Samoa"
, Country "AT" "Austria"
, Country "AU" "Australia"
, Country "AW" "Aruba"
, Country "AX" "Åland Islands"
, Country "AZ" "Azerbaijan"
, Country "BA" "Bosnia and Herzegovina"
, Country "BB" "Barbados"
, Country "BD" "Bangladesh"
, Country "BE" "Belgium"
, Country "BF" "Burkina Faso"
, Country "BG" "Bulgaria"
, Country "BH" "Bahrain"
, Country "BI" "Burundi"
, Country "BJ" "Benin"
, Country "BL" "Saint Barthélemy"
, Country "BM" "Bermuda"
, Country "BN" "Brunei Darussalam"
, Country "BO" "Bolivia (Plurinational State of)"
, Country "BR" "Brazil"
, Country "BS" "Bahamas"
, Country "BT" "Bhutan"
, Country "BV" "Bouvet Island"
, Country "BW" "Botswana"
, Country "BY" "Belarus"
, Country "BZ" "Belize"
, Country "CA" "Canada"
, Country "CC" "Cocos (Keeling) Islands"
, Country "CD" "Congo (Democratic Republic of the)"
, Country "CF" "Central African Republic"
, Country "CG" "Republic of the Congo"
, Country "CH" "Switzerland"
, Country "CI" "Côte d'Ivoire"
, Country "CK" "Cook Islands"
, Country "CL" "Chile"
, Country "CM" "Cameroon"
, Country "CN" "China"
, Country "CO" "Colombia"
, Country "CR" "Costa Rica"
, Country "CU" "Cuba"
, Country "CV" "Cabo Verde"
, Country "CX" "Christmas Island"
, Country "CY" "Cyprus"
, Country "CZ" "Czech Republic"
, Country "DJ" "Djibouti"
, Country "DE" "Germany"
, Country "DK" "Denmark"
, Country "DM" "Dominica"
, Country "DO" "Dominican Republic"
, Country "DZ" "Algeria"
, Country "EC" "Ecuador"
, Country "EE" "Estonia"
, Country "EG" "Egypt"
, Country "EH" "Western Sahara"
, Country "ER" "Eritrea"
, Country "ES" "Spain"
, Country "ET" "Ethiopia"
, Country "FI" "Finland"
, Country "FJ" "Fiji"
, Country "FK" "Falkland Islands (Malvinas)"
, Country "FM" "Micronesia (Federated States of)"
, Country "FO" "Faroe Islands"
, Country "FR" "France"
, Country "GA" "Gabon"
, Country "GB" "United Kingdom of Great Britain and Northern Ireland"
, Country "GD" "Grenada"
, Country "GE" "Georgia (country)"
, Country "GF" "French Guiana"
, Country "GG" "Guernsey"
, Country "GH" "Ghana"
, Country "GI" "Gibraltar"
, Country "GL" "Greenland"
, Country "GM" "Gambia"
, Country "GN" "Guinea"
, Country "GP" "Guadeloupe"
, Country "GQ" "Equatorial Guinea"
, Country "GR" "Greece"
, Country "GS" "South Georgia and the South Sandwich Islands"
, Country "GT" "Guatemala"
, Country "GU" "Guam"
, Country "GW" "Guinea-Bissau"
, Country "GY" "Guyana"
, Country "HK" "Hong Kong"
, Country "HM" "Heard Island and McDonald Islands"
, Country "HN" "Honduras"
, Country "HR" "Croatia"
, Country "HT" "Haiti"
, Country "HU" "Hungary"
, Country "ID" "Indonesia"
, Country "IE" "Republic of Ireland"
, Country "IL" "Israel"
, Country "IM" "Isle of Man"
, Country "IN" "India"
, Country "IO" "British Indian Ocean Territory"
, Country "IQ" "Iraq"
, Country "IR" "Iran (Islamic Republic of)"
, Country "IS" "Iceland"
, Country "IT" "Italy"
, Country "JE" "Jersey"
, Country "JM" "Jamaica"
, Country "JO" "Jordan"
, Country "JP" "Japan"
, Country "KE" "Kenya"
, Country "KG" "Kyrgyzstan"
, Country "KH" "Cambodia"
, Country "KI" "Kiribati"
, Country "KM" "Comoros"
, Country "KN" "Saint Kitts and Nevis"
, Country "KP" "North Korea"
, Country "KR" "Korea (Republic of)"
, Country "KW" "Kuwait"
, Country "KY" "Cayman Islands"
, Country "KZ" "Kazakhstan"
, Country "LA" "Lao People's Democratic Republic"
, Country "LB" "Lebanon"
, Country "LC" "Saint Lucia"
, Country "LI" "Liechtenstein"
, Country "LK" "Sri Lanka"
, Country "LR" "Liberia"
, Country "LS" "Lesotho"
, Country "LT" "Lithuania"
, Country "LU" "Luxembourg"
, Country "LV" "Latvia"
, Country "LY" "Libya"
, Country "MA" "Morocco"
, Country "MC" "Monaco"
, Country "MD" "Moldova (Republic of)"
, Country "ME" "Montenegro"
, Country "MG" "Madagascar"
, Country "MH" "Marshall Islands"
, Country "MK" "Republic of Macedonia"
, Country "ML" "Mali"
, Country "MM" "Myanmar"
, Country "MN" "Mongolia"
, Country "MO" "Macao"
, Country "MP" "Northern Mariana Islands"
, Country "MQ" "Martinique"
, Country "MR" "Mauritania"
, Country "MS" "Montserrat"
, Country "MT" "Malta"
, Country "MU" "Mauritius"
, Country "MV" "Maldives"
, Country "MW" "Malawi"
, Country "MX" "Mexico"
, Country "MY" "Malaysia"
, Country "MZ" "Mozambique"
, Country "NA" "Namibia"
, Country "NC" "New Caledonia"
, Country "NE" "Niger"
, Country "NF" "Norfolk Island"
, Country "NG" "Nigeria"
, Country "NI" "Nicaragua"
, Country "NL" "Netherlands"
, Country "NO" "Norway"
, Country "NP" "Nepal"
, Country "NR" "Nauru"
, Country "NU" "Niue"
, Country "NZ" "New Zealand"
, Country "OM" "Oman"
, Country "PA" "Panama"
, Country "PE" "Peru"
, Country "PF" "French Polynesia"
, Country "PG" "Papua New Guinea"
, Country "PH" "Philippines"
, Country "PK" "Pakistan"
, Country "PL" "Poland"
, Country "PM" "Saint Pierre and Miquelon"
, Country "PN" "Pitcairn"
, Country "PR" "Puerto Rico"
, Country "PS" "State of Palestine"
, Country "PT" "Portugal"
, Country "PW" "Palau"
, Country "PY" "Paraguay"
, Country "QA" "Qatar"
, Country "RE" "Réunion"
, Country "RO" "Romania"
, Country "RS" "Serbia"
, Country "RU" "Russian Federation"
, Country "RW" "Rwanda"
, Country "SA" "Saudi Arabia"
, Country "SB" "Solomon Islands"
, Country "SC" "Seychelles"
, Country "SD" "Sudan"
, Country "SE" "Sweden"
, Country "SG" "Singapore"
, Country "SH" "Saint Helena, Ascension and Tristan da Cunha"
, Country "SI" "Slovenia"
, Country "SJ" "Svalbard and Jan Mayen"
, Country "SK" "Slovakia"
, Country "SL" "Sierra Leone"
, Country "SM" "San Marino"
, Country "SN" "Senegal"
, Country "SO" "Somalia"
, Country "SR" "Suriname"
, Country "ST" "Sao Tome and Principe"
, Country "SV" "El Salvador"
, Country "SY" "Syrian Arab Republic"
, Country "SZ" "Swaziland"
, Country "TC" "Turks and Caicos Islands"
, Country "TD" "Chad"
, Country "TF" "French Southern Territories"
, Country "TG" "Togo"
, Country "TH" "Thailand"
, Country "TJ" "Tajikistan"
, Country "TK" "Tokelau"
, Country "TL" "Timor-Leste"
, Country "TM" "Turkmenistan"
, Country "TN" "Tunisia"
, Country "TO" "Tonga"
, Country "TR" "Turkey"
, Country "TT" "Trinidad and Tobago"
, Country "TV" "Tuvalu"
, Country "TW" "Taiwan"
, Country "TZ" "Tanzania, United Republic of"
, Country "UA" "Ukraine"
, Country "UG" "Uganda"
, Country "UM" "United States Minor Outlying Islands"
, Country "US" "United States of America"
, Country "UY" "Uruguay"
, Country "UZ" "Uzbekistan"
, Country "VA" "Vatican City State"
, Country "VC" "Saint Vincent and the Grenadines"
, Country "VE" "Venezuela (Bolivarian Republic of)"
, Country "VG" "British Virgin Islands"
, Country "VI" "United States Virgin Islands"
, Country "VN" "Viet Nam"
, Country "VU" "Vanuatu"
, Country "WF" "Wallis and Futuna"
, Country "WS" "Samoa"
, Country "YE" "Yemen"
, Country "YT" "Mayotte"
, Country "ZA" "South Africa"
, Country "ZM" "Zambia"
, Country "ZW" "Zimbabwe"
]
toFakeCountry :: [String] -> S.Set Country
toFakeCountry l = S.fromList $ map (flip Country "") l
|
MicheleCastrovilli/EuPhBot
|
Bots/MusicBot/Countries.hs
|
Haskell
|
bsd-3-clause
| 9,043
|
{- |
Module : Data.Convertible.Instances.Map
Copyright : Copyright (C) 2009-2011 John Goerzen
License : BSD3
Maintainer : John Goerzen <jgoerzen@complete.org>
Stability : provisional
Portability: portable
Instances to convert between Map and association list.
Copyright (C) 2009-2011 John Goerzen <jgoerzen@complete.org>
All rights reserved.
For license and copyright information, see the file LICENSE
-}
module Data.Convertible.Instances.Map()
where
import Data.Convertible.Base
import qualified Data.Map as Map
instance Ord k => Convertible [(k, a)] (Map.Map k a) where
safeConvert = return . Map.fromList
instance Convertible (Map.Map k a) [(k, a)] where
safeConvert = return . Map.toList
|
hdbc/convertible
|
Data/Convertible/Instances/Map.hs
|
Haskell
|
bsd-3-clause
| 737
|
-- Test purpose:
-- Ensure that not using -Wcompat does not enable its warnings
-- {-# OPTIONS_GHC -Wcompat #-}
-- {-# OPTIONS_GHC -Wno-compat #-}
module WCompatWarningsNotOn where
import qualified Data.Semigroup as Semi
monadFail :: Monad m => m a
monadFail = do
Just _ <- undefined
undefined
(<>) = undefined -- Semigroup warnings
-- -fwarn-noncanonical-monoid-instances
newtype S = S Int
instance Semi.Semigroup S where
(<>) = mappend
instance Monoid S where
S a `mappend` S b = S (a+b)
mempty = S 0
|
shlevy/ghc
|
testsuite/tests/wcompat-warnings/WCompatWarningsNotOn.hs
|
Haskell
|
bsd-3-clause
| 525
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
Bag: an unordered collection with duplicates
-}
{-# LANGUAGE ScopedTypeVariables, CPP #-}
module Bag (
Bag, -- abstract type
emptyBag, unitBag, unionBags, unionManyBags,
mapBag,
elemBag, lengthBag,
filterBag, partitionBag, partitionBagWith,
concatBag, catBagMaybes, foldBag, foldrBag, foldlBag,
isEmptyBag, isSingletonBag, consBag, snocBag, anyBag,
listToBag, bagToList, mapAccumBagL,
foldrBagM, foldlBagM, mapBagM, mapBagM_,
flatMapBagM, flatMapBagPairM,
mapAndUnzipBagM, mapAccumBagLM,
anyBagM, filterBagM
) where
import Outputable
import Util
import MonadUtils
import Control.Monad
import Data.Data
import Data.List ( partition, mapAccumL )
import qualified Data.Foldable as Foldable
infixr 3 `consBag`
infixl 3 `snocBag`
data Bag a
= EmptyBag
| UnitBag a
| TwoBags (Bag a) (Bag a) -- INVARIANT: neither branch is empty
| ListBag [a] -- INVARIANT: the list is non-empty
emptyBag :: Bag a
emptyBag = EmptyBag
unitBag :: a -> Bag a
unitBag = UnitBag
lengthBag :: Bag a -> Int
lengthBag EmptyBag = 0
lengthBag (UnitBag {}) = 1
lengthBag (TwoBags b1 b2) = lengthBag b1 + lengthBag b2
lengthBag (ListBag xs) = length xs
elemBag :: Eq a => a -> Bag a -> Bool
elemBag _ EmptyBag = False
elemBag x (UnitBag y) = x == y
elemBag x (TwoBags b1 b2) = x `elemBag` b1 || x `elemBag` b2
elemBag x (ListBag ys) = any (x ==) ys
unionManyBags :: [Bag a] -> Bag a
unionManyBags xs = foldr unionBags EmptyBag xs
-- This one is a bit stricter! The bag will get completely evaluated.
unionBags :: Bag a -> Bag a -> Bag a
unionBags EmptyBag b = b
unionBags b EmptyBag = b
unionBags b1 b2 = TwoBags b1 b2
consBag :: a -> Bag a -> Bag a
snocBag :: Bag a -> a -> Bag a
consBag elt bag = (unitBag elt) `unionBags` bag
snocBag bag elt = bag `unionBags` (unitBag elt)
isEmptyBag :: Bag a -> Bool
isEmptyBag EmptyBag = True
isEmptyBag _ = False -- NB invariants
isSingletonBag :: Bag a -> Bool
isSingletonBag EmptyBag = False
isSingletonBag (UnitBag _) = True
isSingletonBag (TwoBags _ _) = False -- Neither is empty
isSingletonBag (ListBag xs) = isSingleton xs
filterBag :: (a -> Bool) -> Bag a -> Bag a
filterBag _ EmptyBag = EmptyBag
filterBag pred b@(UnitBag val) = if pred val then b else EmptyBag
filterBag pred (TwoBags b1 b2) = sat1 `unionBags` sat2
where sat1 = filterBag pred b1
sat2 = filterBag pred b2
filterBag pred (ListBag vs) = listToBag (filter pred vs)
filterBagM :: Monad m => (a -> m Bool) -> Bag a -> m (Bag a)
filterBagM _ EmptyBag = return EmptyBag
filterBagM pred b@(UnitBag val) = do
flag <- pred val
if flag then return b
else return EmptyBag
filterBagM pred (TwoBags b1 b2) = do
sat1 <- filterBagM pred b1
sat2 <- filterBagM pred b2
return (sat1 `unionBags` sat2)
filterBagM pred (ListBag vs) = do
sat <- filterM pred vs
return (listToBag sat)
anyBag :: (a -> Bool) -> Bag a -> Bool
anyBag _ EmptyBag = False
anyBag p (UnitBag v) = p v
anyBag p (TwoBags b1 b2) = anyBag p b1 || anyBag p b2
anyBag p (ListBag xs) = any p xs
anyBagM :: Monad m => (a -> m Bool) -> Bag a -> m Bool
anyBagM _ EmptyBag = return False
anyBagM p (UnitBag v) = p v
anyBagM p (TwoBags b1 b2) = do flag <- anyBagM p b1
if flag then return True
else anyBagM p b2
anyBagM p (ListBag xs) = anyM p xs
concatBag :: Bag (Bag a) -> Bag a
concatBag bss = foldrBag add emptyBag bss
where
add bs rs = bs `unionBags` rs
catBagMaybes :: Bag (Maybe a) -> Bag a
catBagMaybes bs = foldrBag add emptyBag bs
where
add Nothing rs = rs
add (Just x) rs = x `consBag` rs
partitionBag :: (a -> Bool) -> Bag a -> (Bag a {- Satisfy predictate -},
Bag a {- Don't -})
partitionBag _ EmptyBag = (EmptyBag, EmptyBag)
partitionBag pred b@(UnitBag val)
= if pred val then (b, EmptyBag) else (EmptyBag, b)
partitionBag pred (TwoBags b1 b2)
= (sat1 `unionBags` sat2, fail1 `unionBags` fail2)
where (sat1, fail1) = partitionBag pred b1
(sat2, fail2) = partitionBag pred b2
partitionBag pred (ListBag vs) = (listToBag sats, listToBag fails)
where (sats, fails) = partition pred vs
partitionBagWith :: (a -> Either b c) -> Bag a
-> (Bag b {- Left -},
Bag c {- Right -})
partitionBagWith _ EmptyBag = (EmptyBag, EmptyBag)
partitionBagWith pred (UnitBag val)
= case pred val of
Left a -> (UnitBag a, EmptyBag)
Right b -> (EmptyBag, UnitBag b)
partitionBagWith pred (TwoBags b1 b2)
= (sat1 `unionBags` sat2, fail1 `unionBags` fail2)
where (sat1, fail1) = partitionBagWith pred b1
(sat2, fail2) = partitionBagWith pred b2
partitionBagWith pred (ListBag vs) = (listToBag sats, listToBag fails)
where (sats, fails) = partitionWith pred vs
foldBag :: (r -> r -> r) -- Replace TwoBags with this; should be associative
-> (a -> r) -- Replace UnitBag with this
-> r -- Replace EmptyBag with this
-> Bag a
-> r
{- Standard definition
foldBag t u e EmptyBag = e
foldBag t u e (UnitBag x) = u x
foldBag t u e (TwoBags b1 b2) = (foldBag t u e b1) `t` (foldBag t u e b2)
foldBag t u e (ListBag xs) = foldr (t.u) e xs
-}
-- More tail-recursive definition, exploiting associativity of "t"
foldBag _ _ e EmptyBag = e
foldBag t u e (UnitBag x) = u x `t` e
foldBag t u e (TwoBags b1 b2) = foldBag t u (foldBag t u e b2) b1
foldBag t u e (ListBag xs) = foldr (t.u) e xs
foldrBag :: (a -> r -> r) -> r
-> Bag a
-> r
foldrBag _ z EmptyBag = z
foldrBag k z (UnitBag x) = k x z
foldrBag k z (TwoBags b1 b2) = foldrBag k (foldrBag k z b2) b1
foldrBag k z (ListBag xs) = foldr k z xs
foldlBag :: (r -> a -> r) -> r
-> Bag a
-> r
foldlBag _ z EmptyBag = z
foldlBag k z (UnitBag x) = k z x
foldlBag k z (TwoBags b1 b2) = foldlBag k (foldlBag k z b1) b2
foldlBag k z (ListBag xs) = foldl k z xs
foldrBagM :: (Monad m) => (a -> b -> m b) -> b -> Bag a -> m b
foldrBagM _ z EmptyBag = return z
foldrBagM k z (UnitBag x) = k x z
foldrBagM k z (TwoBags b1 b2) = do { z' <- foldrBagM k z b2; foldrBagM k z' b1 }
foldrBagM k z (ListBag xs) = foldrM k z xs
foldlBagM :: (Monad m) => (b -> a -> m b) -> b -> Bag a -> m b
foldlBagM _ z EmptyBag = return z
foldlBagM k z (UnitBag x) = k z x
foldlBagM k z (TwoBags b1 b2) = do { z' <- foldlBagM k z b1; foldlBagM k z' b2 }
foldlBagM k z (ListBag xs) = foldlM k z xs
mapBag :: (a -> b) -> Bag a -> Bag b
mapBag _ EmptyBag = EmptyBag
mapBag f (UnitBag x) = UnitBag (f x)
mapBag f (TwoBags b1 b2) = TwoBags (mapBag f b1) (mapBag f b2)
mapBag f (ListBag xs) = ListBag (map f xs)
mapBagM :: Monad m => (a -> m b) -> Bag a -> m (Bag b)
mapBagM _ EmptyBag = return EmptyBag
mapBagM f (UnitBag x) = do r <- f x
return (UnitBag r)
mapBagM f (TwoBags b1 b2) = do r1 <- mapBagM f b1
r2 <- mapBagM f b2
return (TwoBags r1 r2)
mapBagM f (ListBag xs) = do rs <- mapM f xs
return (ListBag rs)
mapBagM_ :: Monad m => (a -> m b) -> Bag a -> m ()
mapBagM_ _ EmptyBag = return ()
mapBagM_ f (UnitBag x) = f x >> return ()
mapBagM_ f (TwoBags b1 b2) = mapBagM_ f b1 >> mapBagM_ f b2
mapBagM_ f (ListBag xs) = mapM_ f xs
flatMapBagM :: Monad m => (a -> m (Bag b)) -> Bag a -> m (Bag b)
flatMapBagM _ EmptyBag = return EmptyBag
flatMapBagM f (UnitBag x) = f x
flatMapBagM f (TwoBags b1 b2) = do r1 <- flatMapBagM f b1
r2 <- flatMapBagM f b2
return (r1 `unionBags` r2)
flatMapBagM f (ListBag xs) = foldrM k EmptyBag xs
where
k x b2 = do { b1 <- f x; return (b1 `unionBags` b2) }
flatMapBagPairM :: Monad m => (a -> m (Bag b, Bag c)) -> Bag a -> m (Bag b, Bag c)
flatMapBagPairM _ EmptyBag = return (EmptyBag, EmptyBag)
flatMapBagPairM f (UnitBag x) = f x
flatMapBagPairM f (TwoBags b1 b2) = do (r1,s1) <- flatMapBagPairM f b1
(r2,s2) <- flatMapBagPairM f b2
return (r1 `unionBags` r2, s1 `unionBags` s2)
flatMapBagPairM f (ListBag xs) = foldrM k (EmptyBag, EmptyBag) xs
where
k x (r2,s2) = do { (r1,s1) <- f x
; return (r1 `unionBags` r2, s1 `unionBags` s2) }
mapAndUnzipBagM :: Monad m => (a -> m (b,c)) -> Bag a -> m (Bag b, Bag c)
mapAndUnzipBagM _ EmptyBag = return (EmptyBag, EmptyBag)
mapAndUnzipBagM f (UnitBag x) = do (r,s) <- f x
return (UnitBag r, UnitBag s)
mapAndUnzipBagM f (TwoBags b1 b2) = do (r1,s1) <- mapAndUnzipBagM f b1
(r2,s2) <- mapAndUnzipBagM f b2
return (TwoBags r1 r2, TwoBags s1 s2)
mapAndUnzipBagM f (ListBag xs) = do ts <- mapM f xs
let (rs,ss) = unzip ts
return (ListBag rs, ListBag ss)
mapAccumBagL ::(acc -> x -> (acc, y)) -- ^ combining funcction
-> acc -- ^ initial state
-> Bag x -- ^ inputs
-> (acc, Bag y) -- ^ final state, outputs
mapAccumBagL _ s EmptyBag = (s, EmptyBag)
mapAccumBagL f s (UnitBag x) = let (s1, x1) = f s x in (s1, UnitBag x1)
mapAccumBagL f s (TwoBags b1 b2) = let (s1, b1') = mapAccumBagL f s b1
(s2, b2') = mapAccumBagL f s1 b2
in (s2, TwoBags b1' b2')
mapAccumBagL f s (ListBag xs) = let (s', xs') = mapAccumL f s xs
in (s', ListBag xs')
mapAccumBagLM :: Monad m
=> (acc -> x -> m (acc, y)) -- ^ combining funcction
-> acc -- ^ initial state
-> Bag x -- ^ inputs
-> m (acc, Bag y) -- ^ final state, outputs
mapAccumBagLM _ s EmptyBag = return (s, EmptyBag)
mapAccumBagLM f s (UnitBag x) = do { (s1, x1) <- f s x; return (s1, UnitBag x1) }
mapAccumBagLM f s (TwoBags b1 b2) = do { (s1, b1') <- mapAccumBagLM f s b1
; (s2, b2') <- mapAccumBagLM f s1 b2
; return (s2, TwoBags b1' b2') }
mapAccumBagLM f s (ListBag xs) = do { (s', xs') <- mapAccumLM f s xs
; return (s', ListBag xs') }
listToBag :: [a] -> Bag a
listToBag [] = EmptyBag
listToBag vs = ListBag vs
bagToList :: Bag a -> [a]
bagToList b = foldrBag (:) [] b
instance (Outputable a) => Outputable (Bag a) where
ppr bag = braces (pprWithCommas ppr (bagToList bag))
instance Data a => Data (Bag a) where
gfoldl k z b = z listToBag `k` bagToList b -- traverse abstract type abstractly
toConstr _ = abstractConstr $ "Bag("++show (typeOf (undefined::a))++")"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "Bag"
dataCast1 x = gcast1 x
instance Foldable.Foldable Bag where
foldr = foldrBag
|
mettekou/ghc
|
compiler/utils/Bag.hs
|
Haskell
|
bsd-3-clause
| 11,482
|
{-# LANGUAGE OverloadedStrings #-}
{-
This is a test of how the browser draws lines.
This is a second line.
This is a third.
That was a blank line above this.
@r@_Right justify
@c@_Center justify
@_Left justify
@bBold text
@iItalic text
@b@iBold Italic
@fFixed width
@f@bBold Fixed
@f@iItalic Fixed
@f@i@bBold Italic Fixed
@lLarge
@l@bLarge bold
@sSmall
@s@bSmall bold
@s@iSmall italic
@s@i@bSmall italic bold
@uunderscore
@C1RED
@C2Green
@C4Blue
You should try different browser types:
Fl_Browser
Fl_Select_Browser
Fl_Hold_Browser
Fl_Multi_Browser
-}
module Main where
import qualified Graphics.UI.FLTK.LowLevel.FL as FL
import Graphics.UI.FLTK.LowLevel.FLTKHS
import Control.Monad
import System.Environment
import qualified Data.Text as T
data CallbackType = Top | Middle | Bottom | Visible | Browser
bCb :: Ref SelectBrowser -> IO ()
bCb browser' = do
lineNumber <- getValue browser'
clicks <- FL.eventClicks
putStrLn ("callback, selection = " ++ (show lineNumber) ++ " eventClicks = " ++ (show clicks))
showCb :: CallbackType -> Ref Input -> Ref SelectBrowser -> IO ()
showCb buttontype' field' browser' = do
line' <- getValue field'
if (T.null line')
then print ("Please enter a number in the text field before clicking on the buttons." :: String)
else do
let lineNumber' = read (T.unpack line')
case buttontype' of
Top -> setTopline browser' (LineNumber lineNumber')
Bottom -> setBottomline browser' (LineNumber lineNumber')
Middle -> setMiddleline browser' (LineNumber lineNumber')
_ -> makeVisible browser' (LineNumber lineNumber')
swapCb :: Ref SelectBrowser -> Ref Button -> IO ()
swapCb browser' _ =
do
browserSize' <- getSize browser'
linesSelected' <- filterM (selected browser') (map LineNumber [0..(browserSize' - 1)])
case linesSelected' of
(l1:l2:_) -> swap browser' l1 l2
(l1:[]) -> swap browser' l1 (LineNumber (-1))
_ -> swap browser' (LineNumber (-1)) (LineNumber (-1))
sortCb :: Ref SelectBrowser -> Ref Button -> IO ()
sortCb browser' _ = sortWithSortType browser' SortAscending
btypeCb :: Ref SelectBrowser -> Ref Choice -> IO ()
btypeCb browser' btype' = do
numLines' <- getSize browser'
forM_ [1..(numLines' - 1)] (\l -> select browser' (LineNumber l) False)
_ <- select browser' (LineNumber 1) False -- leave focus box on first line
choice' <- getText btype'
case choice' of
"Normal" -> setType browser' NormalBrowserType
"Select" -> setType browser' SelectBrowserType
"Hold" -> setType browser' HoldBrowserType
"Multi" -> setType browser' MultiBrowserType
_ -> return ()
redraw browser'
main :: IO ()
main = do
args <- getArgs
if (null args) then print ("Enter the path to a text file as an argument. As an example use this file (./src/Examples/browser.hs) to see what Fl_Browser can do." :: String)
else do
let fname = T.pack (head args)
window <- doubleWindowNew (Size (Width 560) (Height 400)) Nothing (Just fname)
browser' <- selectBrowserNew (Rectangle (Position (X 0) (Y 0)) (Size (Width 560) (Height 350))) Nothing
setType browser' MultiBrowserType
setCallback browser' bCb
loadStatus' <- load browser' fname
case loadStatus' of
Left _ -> print ("Can't load " ++ T.unpack fname)
_ -> do
setPosition browser' (PixelPosition 0)
field <- inputNew (toRectangle (55,350,505,25)) (Just "Line #:") (Just FlIntInput)
setCallback field (\_ -> showCb Browser field browser')
top' <- buttonNew (toRectangle (0,375,80,25)) (Just "Top")
setCallback top' (\_ -> showCb Top field browser')
bottom' <- buttonNew (toRectangle (80,375,80,25)) (Just "Bottom")
setCallback bottom' (\_ -> showCb Bottom field browser')
middle' <- buttonNew (toRectangle (160,375,80,25)) (Just "Middle")
setCallback middle' (\_ -> showCb Middle field browser')
visible' <- buttonNew (toRectangle (240,375,80,25)) (Just "Make Vis.")
setCallback visible' (\_ -> showCb Visible field browser')
swap' <- buttonNew (toRectangle (320,375,80,25)) (Just "Swap")
setCallback swap' $ swapCb browser'
setTooltip swap' "Swaps two selected lines\n(Use CTRL-click to select two lines)"
sort' <- buttonNew (toRectangle (400,375,80,25)) (Just "Sort")
setCallback sort' (sortCb browser')
btype <- choiceNew (toRectangle (480,375,80,25)) Nothing
addName btype "Normal"
addName btype "Select"
addName btype "Hold"
addName btype "Multi"
setCallback btype $ btypeCb browser'
_ <- setValue btype (MenuItemByIndex (AtIndex 3))
setResizable window (Just browser')
showWidget window
_ <- FL.run
return ()
|
deech/fltkhs-demos
|
src/Examples/browser.hs
|
Haskell
|
mit
| 4,793
|
main = interact wordCount
where wordCount input = show (length (words input)) ++ "\n"
|
manhong2112/CodeColle
|
Haskell/WC.hs
|
Haskell
|
mit
| 89
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
-- | Utilities for reifying simplified datatype info. It omits details
-- that aren't usually relevant to generating instances that work with
-- the datatype. This makes it easier to use TH to derive instances.
--
-- The \"Simple\" in the module name refers to the simplicity of the
-- datatypes, not the module itself, which exports quite a few things
-- which are useful in some circumstance or another. I anticipate that
-- the most common uses of this will be the following APIs:
--
-- * Getting info about a @data@ or @newtype@ declaration, via
-- 'DataType', 'reifyDataType', and 'DataCon'. This is useful for
-- writing something which generates declarations based on a datatype,
-- one of the most common uses of Template Haskell.
--
-- * Getting nicely structured info about a named type. See 'TypeInfo'
-- and 'reifyType'. This does not yet support reifying typeclasses,
-- primitive type constructors, or type variables ('TyVarI').
--
-- Currently, this module supports reifying simplified versions of the
-- following 'Info' constructors:
--
-- * 'TyConI' with 'DataD' and 'NewtypeD' (becomes a 'DataType' value)
--
-- * 'FamilyI' becomes a 'DataFamily' or 'TypeFamily' value.
--
-- * 'DataConI' becomes a 'DataCon' value.
--
-- In the future it will hopefully also have support for the remaining
-- 'Info' constructors, 'ClassI', 'ClassOpI', 'PrimTyConI', 'VarI', and
-- 'TyVarI'.
module TH.ReifySimple
(
-- * Reifying simplified type info
TypeInfo, reifyType, infoToType
, reifyTypeNoDataKinds, infoToTypeNoDataKinds
-- * Reifying simplified info for specific declaration varieties
-- ** Datatype info
, DataType(..), reifyDataType, infoToDataType
-- ** Data constructor info
, DataCon(..), reifyDataCon, infoToDataCon, typeToDataCon
-- ** Data family info
, DataFamily(..), DataInst(..), reifyDataFamily, infoToDataFamily
-- ** Type family info
, TypeFamily(..), TypeInst(..), reifyTypeFamily, infoToTypeFamily
-- * Other utilities
, conToDataCons
, reifyDataTypeSubstituted
) where
import Control.Applicative
import Data.Data (Data, gmapT)
import Data.Generics.Aliases (extT)
import qualified Data.Map as M
import Data.Typeable (Typeable)
import GHC.Generics (Generic)
import Language.Haskell.TH
#if MIN_VERSION_template_haskell(2,16,0)
hiding (reifyType)
#endif
import Language.Haskell.TH.Instances ()
import TH.Utilities
data TypeInfo
= DataTypeInfo DataType
| DataFamilyInfo DataFamily
| TypeFamilyInfo TypeFamily
| LiftedDataConInfo DataCon
-- | Reifies a 'Name' as a 'TypeInfo', and calls 'fail' if this doesn't
-- work. Use 'reify' with 'infoToType' if you want to handle the failure
-- case more gracefully.
--
-- This does not yet support reifying typeclasses, primitive type
-- constructors, or type variables ('TyVarI').
reifyType :: Name -> Q TypeInfo
reifyType name = do
info <- reify name
mres <- infoToType info
case mres of
Just res -> return res
Nothing -> fail $
"Expected to reify a data type, data family, or type family. Instead got:\n" ++
pprint info
-- | Convert an 'Info' into a 'TypeInfo' if possible, and otherwise
-- yield 'Nothing'. Needs to run in 'Q' so that
infoToType :: Info -> Q (Maybe TypeInfo)
infoToType info =
case (infoToTypeNoDataKinds info, infoToDataCon info) of
(Just result, _) -> return (Just result)
(Nothing, Just dc) -> do
#if MIN_VERSION_template_haskell(2,11,0)
dataKindsEnabled <- isExtEnabled DataKinds
#else
reportWarning $
"For " ++ pprint (dcName dc) ++
", assuming DataKinds is on, and yielding LiftedDataConInfo."
let dataKindsEnabled = True
#endif
return $ if dataKindsEnabled then Just (LiftedDataConInfo dc) else Nothing
(Nothing, Nothing) -> return Nothing
-- | Reifies type info, but instead of yielding a 'LiftedDataConInfo',
-- will instead yield 'Nothing'.
reifyTypeNoDataKinds :: Name -> Q (Maybe TypeInfo)
reifyTypeNoDataKinds = fmap infoToTypeNoDataKinds . reify
-- | Convert an 'Info into a 'TypeInfo' if possible. If it's a data
-- constructor, instead of yielding 'LiftedDataConInfo', it will instead
-- yield 'Nothing'.
infoToTypeNoDataKinds :: Info -> Maybe TypeInfo
infoToTypeNoDataKinds info =
(DataTypeInfo <$> infoToDataType info) <|>
(DataFamilyInfo <$> infoToDataFamily info) <|>
(TypeFamilyInfo <$> infoToTypeFamily info)
--------------------------------------------------------------------------------
-- Reifying specific declaration varieties
-- | Simplified info about a 'DataD'. Omits deriving, strictness,
-- kind info, and whether it's @data@ or @newtype@.
data DataType = DataType
{ dtName :: Name
, dtTvs :: [Name]
, dtCxt :: Cxt
, dtCons :: [DataCon]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a 'Con'. Omits deriving, strictness, and kind
-- info. This is much nicer than consuming 'Con' directly, because it
-- unifies all the constructors into one.
data DataCon = DataCon
{ dcName :: Name
, dcTvs :: [Name]
, dcCxt :: Cxt
, dcFields :: [(Maybe Name, Type)]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a data family. Omits deriving, strictness, and
-- kind info.
data DataFamily = DataFamily
{ dfName :: Name
, dfTvs :: [Name]
, dfInsts :: [DataInst]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a data family instance. Omits deriving,
-- strictness, and kind info.
data DataInst = DataInst
{ diName :: Name
, diCxt :: Cxt
, diParams :: [Type]
, diCons :: [DataCon]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a type family. Omits kind info and injectivity
-- info.
data TypeFamily = TypeFamily
{ tfName :: Name
, tfTvs :: [Name]
, tfInsts :: [TypeInst]
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Simplified info about a type family instance. Omits nothing.
data TypeInst = TypeInst
{ tiName :: Name
, tiParams :: [Type]
, tiType :: Type
} deriving (Eq, Show, Ord, Data, Typeable, Generic)
-- | Reify the given data or newtype declaration, and yields its
-- 'DataType' representation.
reifyDataType :: Name -> Q DataType
reifyDataType name = do
info <- reify name
case infoToDataType info of
Nothing -> fail $ "Expected to reify a datatype. Instead got:\n" ++ pprint info
Just x -> return x
-- | Reify the given data constructor.
reifyDataCon :: Name -> Q DataCon
reifyDataCon name = do
info <- reify name
case infoToDataCon info of
Nothing -> fail $ "Expected to reify a constructor. Instead got:\n" ++ pprint info
Just x -> return x
-- | Reify the given data family, and yield its 'DataFamily'
-- representation.
reifyDataFamily :: Name -> Q DataFamily
reifyDataFamily name = do
info <- reify name
case infoToDataFamily info of
Nothing -> fail $ "Expected to reify a data family. Instead got:\n" ++ pprint info
Just x -> return x
-- | Reify the given type family instance declaration, and yields its
-- 'TypeInst' representation.
reifyTypeFamily :: Name -> Q TypeFamily
reifyTypeFamily name = do
info <- reify name
case infoToTypeFamily info of
Nothing -> fail $ "Expected to reify a type family. Instead got:\n" ++ pprint info
Just x -> return x
infoToDataType :: Info -> Maybe DataType
infoToDataType info = case info of
#if MIN_VERSION_template_haskell(2,11,0)
TyConI (DataD preds name tvs _kind cons _deriving) ->
#else
TyConI (DataD preds name tvs cons _deriving) ->
#endif
Just $ DataType name (map tyVarBndrName tvs) preds (concatMap conToDataCons cons)
#if MIN_VERSION_template_haskell(2,11,0)
TyConI (NewtypeD preds name tvs _kind con _deriving) ->
#else
TyConI (NewtypeD preds name tvs con _deriving) ->
#endif
Just $ DataType name (map tyVarBndrName tvs) preds (conToDataCons con)
_ -> Nothing
infoToDataFamily :: Info -> Maybe DataFamily
infoToDataFamily info = case info of
#if MIN_VERSION_template_haskell(2,11,0)
FamilyI (DataFamilyD name tvs _kind) insts ->
#else
FamilyI (FamilyD DataFam name tvs _kind) insts ->
#endif
Just $ DataFamily name (map tyVarBndrName tvs) (map go insts)
_ -> Nothing
where
#if MIN_VERSION_template_haskell(2,15,0)
go (NewtypeInstD preds _ lhs _kind con _deriving)
| ConT name:params <- unAppsT lhs
#elif MIN_VERSION_template_haskell(2,11,0)
go (NewtypeInstD preds name params _kind con _deriving)
#else
go (NewtypeInstD preds name params con _deriving)
#endif
= DataInst name preds params (conToDataCons con)
#if MIN_VERSION_template_haskell(2,15,0)
go (DataInstD preds _ lhs _kind cons _deriving)
| ConT name:params <- unAppsT lhs
#elif MIN_VERSION_template_haskell(2,11,0)
go (DataInstD preds name params _kind cons _deriving)
#else
go (DataInstD preds name params cons _deriving)
#endif
= DataInst name preds params (concatMap conToDataCons cons)
go info' = error $
"Unexpected instance in FamilyI in infoToDataInsts:\n" ++ pprint info'
infoToTypeFamily :: Info -> Maybe TypeFamily
infoToTypeFamily info = case info of
#if MIN_VERSION_template_haskell(2,11,0)
FamilyI (ClosedTypeFamilyD (TypeFamilyHead name tvs _result _injectivity) eqns) _ ->
Just $ TypeFamily name (map tyVarBndrName tvs) $ map (goEqn name) eqns
FamilyI (OpenTypeFamilyD (TypeFamilyHead name tvs _result _injectivity)) insts ->
Just $ TypeFamily name (map tyVarBndrName tvs) $ map (goInst name) insts
#else
FamilyI (ClosedTypeFamilyD name tvs _kind eqns) [] ->
Just $ TypeFamily name (map tyVarBndrName tvs) $ map (goEqn name) eqns
FamilyI (FamilyD TypeFam name tvs _kind) insts ->
Just $ TypeFamily name (map tyVarBndrName tvs) $ map (goInst name) insts
#endif
_ -> Nothing
where
#if MIN_VERSION_template_haskell(2,15,0)
toParams ps (AppT ty p) = toParams (p : ps) ty
toParams ps (AppKindT ty _) = toParams ps ty
toParams ps _ = ps
goEqn name (TySynEqn _ lty rty) = TypeInst name (toParams [] lty) rty
goInst name (TySynInstD eqn) = goEqn name eqn
goInst _ info' = error $
"Unexpected instance in FamilyI in infoToTypeInsts:\n" ++ pprint info'
#else
goEqn name (TySynEqn params ty) = TypeInst name params ty
goInst name (TySynInstD _ eqn) = goEqn name eqn
goInst _ info' = error $
"Unexpected instance in FamilyI in infoToTypeInsts:\n" ++ pprint info'
#endif
infoToDataCon :: Info -> Maybe DataCon
infoToDataCon info = case info of
#if MIN_VERSION_template_haskell(2,11,0)
DataConI name ty _parent ->
#else
DataConI name ty _parent _fixity ->
#endif
Just (typeToDataCon name ty)
_ -> Nothing
-- | Creates a 'DataCon' given the 'Name' and 'Type' of a
-- data-constructor. Note that the result the function type is *not* checked to match the provided 'Name'.
typeToDataCon :: Name -> Type -> DataCon
typeToDataCon dcName ty0 = DataCon {..}
where
(dcTvs, dcCxt, dcFields) = case ty0 of
ForallT tvs preds ty -> (map tyVarBndrName tvs, preds, typeToFields ty)
ty -> ([], [], typeToFields ty)
-- TODO: Should we sanity check the result type?
typeToFields = init . map (Nothing, ) . unAppsT
-- | Convert a 'Con' to a list of 'DataCon'. The result is a list
-- because 'GadtC' and 'RecGadtC' can define multiple constructors.
conToDataCons :: Con -> [DataCon]
conToDataCons = \case
NormalC name slots ->
[DataCon name [] [] (map (\(_, ty) -> (Nothing, ty)) slots)]
RecC name fields ->
[DataCon name [] [] (map (\(n, _, ty) -> (Just n, ty)) fields)]
InfixC (_, ty1) name (_, ty2) ->
[DataCon name [] [] [(Nothing, ty1), (Nothing, ty2)]]
ForallC tvs preds con ->
map (\(DataCon name tvs0 preds0 fields) ->
DataCon name (tvs0 ++ map tyVarBndrName tvs) (preds0 ++ preds) fields) (conToDataCons con)
#if MIN_VERSION_template_haskell(2,11,0)
GadtC ns slots _ ->
map (\dn -> DataCon dn [] [] (map (\(_, ty) -> (Nothing, ty)) slots)) ns
RecGadtC ns fields _ ->
map (\dn -> DataCon dn [] [] (map (\(fn, _, ty) -> (Just fn, ty)) fields)) ns
#endif
-- | Like 'reifyDataType', but takes a 'Type' instead of just the 'Name'
-- of the datatype. It expects a normal datatype argument (see
-- 'typeToNamedCon').
reifyDataTypeSubstituted :: Type -> Q DataType
reifyDataTypeSubstituted ty =
case typeToNamedCon ty of
Nothing -> fail $ "Expected a datatype, but reifyDataTypeSubstituted was applied to " ++ pprint ty
Just (n, args) -> do
dt <- reifyDataType n
let cons' = substituteTvs (M.fromList (zip (dtTvs dt) args)) (dtCons dt)
return (dt { dtCons = cons' })
-- TODO: add various handy generics based traversals to TH.Utilities
substituteTvs :: Data a => M.Map Name Type -> a -> a
substituteTvs mp = transformTypes go
where
go (VarT name) | Just ty <- M.lookup name mp = ty
go ty = gmapT (substituteTvs mp) ty
transformTypes :: Data a => (Type -> Type) -> a -> a
transformTypes f = gmapT (transformTypes f) `extT` (id :: String -> String) `extT` f
|
fpco/th-utilities
|
src/TH/ReifySimple.hs
|
Haskell
|
mit
| 13,624
|
{-# LANGUAGE CPP #-}
module GHCJS.DOM.MediaKeyMessageEvent (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.MediaKeyMessageEvent
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.MediaKeyMessageEvent
#else
#endif
|
plow-technologies/ghcjs-dom
|
src/GHCJS/DOM/MediaKeyMessageEvent.hs
|
Haskell
|
mit
| 373
|
import Data.Char (digitToInt)
asIntFold ('-' : s) = -1 * asIntFold s
asIntFold s = foldl (times_10) 0 (map digitToInt s)
where times_10 a b = a * 10 + b
concatFoldr a = foldr (\x y -> x ++ y) [] a
--takeCompare _ [] = ([], [])
--takeCompare _ (a: []) = ([a], [])
--takeCompare f (a: b: xs) =
-- if (f a b) then [a] ++ (takeCompare f (b: xs))
-- else [a]
--
|
gefei/learning_haskell
|
real_world_haskell/ch06.hs
|
Haskell
|
mit
| 380
|
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
module Nauva.Client
( runClient
) where
import qualified Data.Text as T
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import Data.Monoid
import Data.Maybe
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad
import Control.Monad.Except
import Control.Monad.Writer
import System.IO.Unsafe
import Nauva.App
import Nauva.Handle
import Nauva.Internal.Types
import Nauva.View
import Nauva.Native.Bridge
import GHCJS.Types
import GHCJS.Marshal
import Data.JSString.Text
import qualified Data.JSString as JSS
import qualified JavaScript.Object as O
import JavaScript.Array.Internal (fromList)
newHeadH :: Handle -> Bridge -> IO HeadH
newHeadH nauvaH bridge = do
var <- newTVarIO []
pure $ HeadH
{ hElements = var
, hReplace = \newElements -> do
print (length newElements)
atomically $ writeTVar var newElements
processSignals nauvaH
h <- atomically $ do
instances <- mapM (\x -> fst <$> runWriterT (instantiate (Path []) x)) newElements
mapM instanceToJSVal instances
renderHead bridge (jsval $ fromList h)
}
newRouterH :: Handle -> IO RouterH
newRouterH nauvaH = do
var <- newTVarIO (Location "/")
chan <- newTChanIO
pure $ RouterH
{ hLocation = (var, chan)
, hPush = \url -> do
putStrLn $ "Router hPush: " <> T.unpack url
atomically $ do
writeTVar var (Location url)
writeTChan chan (Location url)
processSignals nauvaH
}
runClient :: App -> IO ()
runClient app = do
appEl <- getElementById ("app" :: JSString)
nauvaH <- newHandle
routerH <- newRouterH nauvaH
bridge <- newBridge appEl $ Impl
{ sendLocationImpl = \path -> void $ hPush routerH path
, componentEventImpl = \path val -> void $ dispatchComponentEventHandler nauvaH path val
, nodeEventImpl = \path val -> void $ dispatchNodeEventHandler nauvaH path val
, attachRefImpl = \path val -> void $ attachRefHandler nauvaH path val
, detachRefImpl = \path val -> void $ detachRefHandler nauvaH path val
, componentDidMountImpl = \path vals -> void $ componentDidMountHandler nauvaH path vals
, componentWillUnmountImpl = \path vals -> void $ componentWillUnmountHandler nauvaH path vals
}
headH <- newHeadH nauvaH bridge
appH <- AppH <$> pure headH <*> pure routerH
render nauvaH (rootElement app appH)
locationSignalCopy <- atomically $ dupTChan (snd $ hLocation routerH)
void $ forkIO $ forever $ do
path <- atomically $ do
locPathname <$> readTChan locationSignalCopy
pushLocation bridge (jsval $ textToJSString path)
changeSignalCopy <- atomically $ dupTChan (changeSignal nauvaH)
void $ forkIO $ forever $ do
change <- atomically $ readTChan changeSignalCopy
case change of
(ChangeRoot inst) -> do
spine <- atomically $ do
instanceToJSVal inst
-- rootInstance <- readTMVar (hInstance nauvaH)
-- instanceToJSVal rootInstance
renderSpine bridge spine
(ChangeComponent path inst) -> do
spine <- atomically $ instanceToJSVal inst
renderSpineAtPath bridge (unPath path) spine
-- spine <- atomically $ do
-- rootInstance <- readTMVar (hInstance nauvaH)
-- instanceToJSVal rootInstance
-- renderSpine bridge spine
spine <- atomically $ do
rootInstance <- readTMVar (hInstance nauvaH)
instanceToJSVal rootInstance
renderSpine bridge spine
pure ()
foreign import javascript unsafe "console.log($1)" js_log :: JSVal -> IO ()
hookHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO (Either String ())
hookHandler h path vals = do
res <- atomically $ runExceptT $ do
SomeComponentInstance (ComponentInstance _ component stateRef) <- contextForPath h path
state <- lift $ readTMVar stateRef
let rawHookActions = fromMaybe [] (unsafePerformIO (fromJSVal vals)) :: [A.Value]
forM rawHookActions $ \rawValue -> do
case A.parseEither parseValue rawValue of
Left e -> throwError e
Right value -> do
actions <- lift $ do
state <- takeTMVar stateRef
let (newState, actions) = processLifecycleEvent component value (componentProps state) (componentState state)
(newInst, _effects) <- runWriterT $ instantiate path $ renderComponent component (componentProps state) newState
putTMVar stateRef (State (componentProps state) newState (componentSignals state) newInst)
-- traceShowM path
writeTChan (changeSignal h) (ChangeComponent path $ IComponent path component stateRef)
pure actions
pure $ Effect (ComponentInstance path component stateRef) actions
case res of
Left e -> pure $ Left e
Right effects -> do
executeEffects h effects
pure $ Right ()
componentDidMountHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO (Either String ())
componentDidMountHandler = hookHandler
componentWillUnmountHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO (Either String ())
componentWillUnmountHandler = hookHandler
attachRefHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO ()
attachRefHandler h path jsVal = do
res <- runExceptT $ do
rawValue <- lift (fromJSVal jsVal) >>= maybe (throwError "fromJSVal") pure
ExceptT $ dispatchRef h path rawValue
case res of
Left e -> putStrLn $ "attachRefHandler: " <> e
Right () -> pure ()
detachRefHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO ()
detachRefHandler h path jsVal = do
res <- runExceptT $ do
rawValue <- lift (fromJSVal jsVal) >>= maybe (throwError "fromJSVal") pure
ExceptT $ dispatchRef h path rawValue
case res of
Left e -> putStrLn $ "detachRefHandler: " <> e
Right () -> pure ()
dispatchNodeEventHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO ()
dispatchNodeEventHandler h path jsVal = do
res <- runExceptT $ do
rawValue <- lift (fromJSVal jsVal) >>= maybe (throwError "fromJSVal") pure
ExceptT $ dispatchEvent h path rawValue
case res of
Left e -> putStrLn $ "dispatchNodeEventHandler: " <> e
Right () -> pure ()
dispatchComponentEventHandler :: Nauva.Handle.Handle -> Path -> JSVal -> IO ()
dispatchComponentEventHandler h path jsVal = do
res <- runExceptT $ do
rawValue <- lift (fromJSVal jsVal) >>= maybe (throwError "fromJSVal") pure
ExceptT $ dispatchEvent h path rawValue
case res of
Left e -> putStrLn $ "dispatchComponentEventHandler: " <> e
Right () -> pure ()
foreign import javascript unsafe "$r = $1"
js_intJSVal :: Int -> JSVal
foreign import javascript unsafe "$r = $1"
js_doubleJSVal :: Double -> JSVal
foreign import javascript unsafe "true"
js_true :: JSVal
foreign import javascript unsafe "false"
js_false :: JSVal
foreign import javascript unsafe "$r = null"
js_null :: JSVal
jsCondition :: Condition -> JSVal
jsCondition (CMedia x) = jsval $ fromList [js_intJSVal 1, jsval $ textToJSString x]
jsCondition (CSupports x) = jsval $ fromList [js_intJSVal 2, jsval $ textToJSString x]
jsCSSRule :: CSSRule -> JSVal
jsCSSRule (CSSStyleRule name hash conditions suffixes styleDeclaration) = jsval $ fromList
[ js_intJSVal 1
, jsval $ textToJSString name
, jsval $ textToJSString $ unHash hash
, jsval $ fromList $ map jsCondition conditions
, jsval $ fromList $ map (jsval . JSS.pack . T.unpack . unSuffix) suffixes
, unsafePerformIO $ do
o <- O.create
forM_ styleDeclaration $ \(k, v) -> do
O.setProp (JSS.pack $ T.unpack k) (jsval $ JSS.pack $ T.unpack $ unCSSValue v) o
pure $ jsval o
]
jsCSSRule (CSSFontFaceRule hash styleDeclaration) = jsval $ fromList
[ js_intJSVal 5
, jsval $ textToJSString $ unHash hash
, unsafePerformIO $ do
o <- O.create
forM_ styleDeclaration $ \(k, v) -> do
O.setProp (JSS.pack $ T.unpack k) (jsval $ JSS.pack $ T.unpack $ unCSSValue v) o
pure $ jsval o
]
fToJSVal :: F -> JSVal
fToJSVal f = unsafePerformIO $ do
o <- O.create
O.setProp "id" (jsval $ textToJSString $ unFID $ fId f) o
O.setProp "constructors" (jsval $ fromList $ map (jsval . textToJSString) $ fConstructors f) o
O.setProp "arguments" (jsval $ fromList $ map (jsval . textToJSString) $ fArguments f) o
O.setProp "body" (jsval $ textToJSString $ fBody f) o
pure $ jsval o
instanceToJSVal :: Instance -> STM JSVal
instanceToJSVal = go []
where
go :: [Key] -> Instance -> STM JSVal
go path inst = case inst of
(INull _) -> pure js_null
(IText _ text) -> pure $ jsval $ textToJSString text
(INode _ tag attrs children) -> do
newChildren <- forM children $ \(key, childI) -> do
newChild <- instanceToJSVal childI
key' <- case key of
(KIndex i) -> pure $ js_intJSVal i
(KString s) -> pure $ (jsval $ textToJSString s)
pure $ jsval $ fromList [key', newChild]
pure $ unsafePerformIO $ do
o <- O.create
attributes' <- pure $ jsval $ fromList $ flip map attrs $ \x -> case x of
AVAL an (AVBool b) -> jsval $ fromList [jsval $ textToJSString "AVAL", jsval $ textToJSString an, if b then js_true else js_false]
AVAL an (AVString s) -> jsval $ fromList [jsval $ textToJSString "AVAL", jsval $ textToJSString an, jsval $ textToJSString s]
AVAL an (AVInt i) -> jsval $ fromList [jsval $ textToJSString "AVAL", jsval $ textToJSString an, js_intJSVal i]
AVAL an (AVDouble d) -> jsval $ fromList [jsval $ textToJSString "AVAL", jsval $ textToJSString an, js_doubleJSVal d]
AEVL (EventListener n f) -> jsval $ fromList
[ jsval $ textToJSString "AEVL"
, jsval $ textToJSString n
, fToJSVal f
]
ASTY style -> jsval $ fromList
[ jsval $ textToJSString "ASTY"
, jsval $ fromList $ map jsCSSRule (unStyle style)
]
AREF (Ref mbRefKey fra frd) -> unsafePerformIO $ do
o <- O.create
case mbRefKey of
Nothing -> pure ()
Just (RefKey k) -> O.setProp "key" (js_intJSVal $ k) o
O.setProp "attach" (fToJSVal fra) o
O.setProp "detach" (fToJSVal frd) o
pure $ jsval $ fromList [jsval $ textToJSString "AREF", jsval o]
O.setProp "type" (jsval ("Node" :: JSString)) o
O.setProp "tag" (jsval $ textToJSString $ unTag tag) o
O.setProp "attributes" attributes' o
O.setProp "children" (jsval $ fromList newChildren) o
pure $ jsval o
(IThunk _ _ _ childI) ->
instanceToJSVal childI
(IComponent _ component stateRef) -> do
state <- readTMVar stateRef
spine <- instanceToJSVal $ componentInstance state
eventListeners' <- pure $ jsval $ fromList $ flip map (componentEventListeners component (componentState state)) $ \el -> case el of
(EventListener n f) -> jsval $ fromList
[ jsval $ textToJSString n
, fToJSVal f
]
pure $ unsafePerformIO $ do
o <- O.create
hooks <- O.create
O.setProp "componentDidMount" (jsval $ fromList $ map fToJSVal (componentDidMount (componentHooks component))) hooks
O.setProp "componentWillUnmount" (jsval $ fromList $ map fToJSVal (componentWillUnmount (componentHooks component))) hooks
O.setProp "type" (jsval ("Component" :: JSString)) o
O.setProp "id" (js_intJSVal $ unComponentId $ componentId component) o
O.setProp "displayName" (jsval $ textToJSString $ componentDisplayName component) o
O.setProp "eventListeners" eventListeners' o
O.setProp "hooks" (jsval hooks) o
O.setProp "spine" spine o
pure $ jsval o
|
wereHamster/nauva
|
pkg/hs/nauva-native/src/Nauva/Client.hs
|
Haskell
|
mit
| 13,305
|
import Control.Monad
import Data.List
factorial n = product [1..n]
powerset :: [a] -> [[a]]
powerset = filterM $ \x->[True, False]
combination :: [a] -> Int -> [[a]]
combination list k = filter (\x -> length x == k) $ powerset list
permutation :: Eq a => [a] -> [[a]]
permutation = nub . perm
where perm [] = [[]]
perm list = [ x:xs | x <- list, xs <- perm $ delete x list ]
|
jwvg0425/HaskellScratchPad
|
src/factorial.hs
|
Haskell
|
mit
| 396
|
{-# htermination maximum :: (Ord a, Ord k) => [(Either a k)] -> (Either a k) #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_maximum_10.hs
|
Haskell
|
mit
| 81
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE OverloadedStrings, MultiParamTypeClasses #-}
module Util () where
import Data.ByteString.Builder (toLazyByteString)
import Text.Email.Validate
import Data.Text.Encoding
import Data.Aeson.Encode (encodeToByteStringBuilder)
import Data.Aeson.Types
import Happstack.Server
import Data.UUID.Aeson ()
import Hasql.Postgres
import Hasql.Backend
import Data.Text
instance ToMessage Value where
toContentType _ = "application/json; charset=utf-8"
toMessage = toLazyByteString . encodeToByteStringBuilder
toResponse x = toResponseBS (toContentType x) (toMessage x)
instance ToJSON EmailAddress where
toJSON e = String (decodeUtf8 $ toByteString e)
instance FromJSON EmailAddress where
parseJSON v = withText name (go . emailAddress . encodeUtf8) v where
go Nothing = typeMismatch name v
go (Just x) = return x
name = "EmailAddress"
instance CxValue Postgres EmailAddress where
encodeValue = encodeValue . decodeUtf8 . toByteString
decodeValue v = decodeValue v >>= \x -> case validate (encodeUtf8 x) of
Left l -> Left (pack $ l ++ show x)
Right r -> Right r
|
L8D/cido-api
|
lib/Util.hs
|
Haskell
|
mit
| 1,190
|
module Main where
import PostgREST.App
import PostgREST.Config (AppConfig (..),
minimumPgVersion,
prettyVersion,
readOptions)
import PostgREST.DbStructure
import PostgREST.Error (PgError, pgErrResponse)
import PostgREST.Middleware
import Control.Concurrent (myThreadId)
import Control.Exception.Base (throwTo, AsyncException(..))
import Control.Monad (unless, void)
import Control.Monad.IO.Class (liftIO)
import Data.Aeson (encode)
import Data.Functor.Identity
import Data.Monoid ((<>))
import Data.String.Conversions (cs)
import Data.Text (Text)
import Data.Time.Clock.POSIX (getPOSIXTime)
import qualified Hasql as H
import qualified Hasql.Postgres as P
import Network.Wai
import Network.Wai.Handler.Warp hiding (Connection)
import Network.Wai.Middleware.RequestLogger (logStdout)
import System.IO (BufferMode (..),
hSetBuffering, stderr,
stdin, stdout)
import System.Posix.Signals
import Web.JWT (secret)
isServerVersionSupported :: H.Session P.Postgres IO Bool
isServerVersionSupported = do
Identity (row :: Text) <- H.tx Nothing $ H.singleEx [H.stmt|SHOW server_version_num|]
return $ read (cs row) >= minimumPgVersion
hasqlError :: PgError -> IO a
hasqlError = error . cs . encode
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
hSetBuffering stdin LineBuffering
hSetBuffering stderr NoBuffering
conf <- readOptions
let port = configPort conf
unless (secret "secret" /= configJwtSecret conf) $
putStrLn "WARNING, running in insecure mode, JWT secret is the default value"
Prelude.putStrLn $ "Listening on port " ++
(show $ configPort conf :: String)
let pgSettings = P.StringSettings $ cs (configDatabase conf)
appSettings = setPort port
. setServerName (cs $ "postgrest/" <> prettyVersion)
$ defaultSettings
middle = logStdout . defaultMiddle
poolSettings <- maybe (fail "Improper session settings") return $
H.poolSettings (fromIntegral $ configPool conf) 30
pool :: H.Pool P.Postgres <- H.acquirePool pgSettings poolSettings
supportedOrError <- H.session pool isServerVersionSupported
either hasqlError
(\supported ->
unless supported $
error (
"Cannot run in this PostgreSQL version, PostgREST needs at least "
<> show minimumPgVersion)
) supportedOrError
tid <- myThreadId
void $ installHandler keyboardSignal (Catch $ do
H.releasePool pool
throwTo tid UserInterrupt
) Nothing
let txSettings = Just (H.ReadCommitted, Just True)
dbOrError <- H.session pool $ H.tx txSettings $ getDbStructure (cs $ configSchema conf)
dbStructure <- either hasqlError return dbOrError
runSettings appSettings $ middle $ \ req respond -> do
time <- getPOSIXTime
body <- strictRequestBody req
resOrError <- liftIO $ H.session pool $ H.tx txSettings $
runWithClaims conf time (app dbStructure conf body) req
either (respond . pgErrResponse) respond resOrError
|
NikolayS/postgrest
|
src/PostgREST/Main.hs
|
Haskell
|
mit
| 3,777
|
module Euler.E63 where
import Euler.Lib
( intLength
)
euler63 :: Int
euler63 = length $ concat $ takeWhile (not . null) $ map validNums [ 1 .. ]
validNums :: Integer -> [Integer]
validNums n = takeWhile ((== n) . intLength) $ dropWhile ((<n) . intLength) $
[ x^n
| x <- [ 1 .. ]
]
main :: IO ()
main = print $ euler63
|
D4r1/project-euler
|
Euler/E63.hs
|
Haskell
|
mit
| 327
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Protolude (
-- * Base functions
module Base,
identity,
pass,
#if !MIN_VERSION_base(4,8,0)
(&),
scanl',
#endif
-- * Function functions
module Function,
applyN,
-- * List functions
module List,
map,
uncons,
unsnoc,
-- * Data Structures
module DataStructures,
-- * Show functions
module Show,
show,
print,
-- * Bool functions
module Bool,
-- * Monad functions
module Monad,
liftIO1,
liftIO2,
-- * Functor functions
module Functor,
-- * Either functions
module Either,
-- * Applicative functions
module Applicative,
guarded,
guardedA,
-- * String conversion
module ConvertText,
-- * Debug functions
module Debug,
-- * Panic functions
module Panic,
-- * Exception functions
module Exception,
Protolude.throwIO,
Protolude.throwTo,
-- * Semiring functions
module Semiring,
-- * String functions
module String,
-- * Safe functions
module Safe,
-- * Eq functions
module Eq,
-- * Ord functions
module Ord,
-- * Traversable functions
module Traversable,
-- * Foldable functions
module Foldable,
-- * Semigroup functions
#if MIN_VERSION_base(4,9,0)
module Semigroup,
#endif
-- * Monoid functions
module Monoid,
-- * Bifunctor functions
module Bifunctor,
-- * Bifunctor functions
module Hashable,
-- * Deepseq functions
module DeepSeq,
-- * Tuple functions
module Tuple,
module Typeable,
#if MIN_VERSION_base(4,7,0)
-- * Typelevel programming
module Typelevel,
#endif
-- * Monads
module Fail,
module State,
module Reader,
module Except,
module Trans,
module ST,
module STM,
-- * Integers
module Int,
module Bits,
-- * Complex functions
module Complex,
-- * Char functions
module Char,
-- * Maybe functions
module Maybe,
-- * Generics functions
module Generics,
-- * ByteString functions
module ByteString,
LByteString,
-- * Text functions
module Text,
LText,
-- * Read functions
module Read,
readMaybe,
readEither,
-- * System functions
module System,
die,
-- * Concurrency functions
module Concurrency,
-- * Foreign functions
module Foreign,
) where
-- Protolude module exports.
import Protolude.Debug as Debug
import Protolude.List as List
import Protolude.Show as Show
import Protolude.Bool as Bool
import Protolude.Monad as Monad
import Protolude.Functor as Functor
import Protolude.Either as Either
import Protolude.Applicative as Applicative
import Protolude.ConvertText as ConvertText
import Protolude.Panic as Panic
import Protolude.Exceptions as Exception
import Protolude.Semiring as Semiring
import qualified Protolude.Conv as Conv
import Protolude.Base as Base hiding (
putStr -- Overriden by Show.putStr
, putStrLn -- Overriden by Show.putStrLn
, print -- Overriden by Protolude.print
, show -- Overriden by Protolude.show
, showFloat -- Custom Show instances deprecated.
, showList -- Custom Show instances deprecated.
, showSigned -- Custom Show instances deprecated.
, showSignedFloat -- Custom Show instances deprecated.
, showsPrec -- Custom Show instances deprecated.
)
import qualified Protolude.Base as PBase
-- Used for 'show', not exported.
import Data.String (String)
import Data.String as String (IsString)
-- Maybe'ized version of partial functions
import Protolude.Safe as Safe (
headMay
, headDef
, initMay
, initDef
, initSafe
, tailMay
, tailDef
, tailSafe
, lastDef
, lastMay
, foldr1May
, foldl1May
, foldl1May'
, maximumMay
, minimumMay
, maximumDef
, minimumDef
, atMay
, atDef
)
-- Applicatives
import Control.Applicative as Applicative (
Applicative(..)
, Alternative(..)
, Const(Const,getConst)
, ZipList(ZipList,getZipList)
, (<**>)
, liftA
, liftA2
, liftA3
, optional
)
-- Base typeclasses
import Data.Eq as Eq (
Eq(..)
)
import Data.Ord as Ord (
Ord(..)
, Ordering(LT,EQ,GT)
, Down(Down)
, comparing
)
import Data.Traversable as Traversable
import Data.Foldable as Foldable (
Foldable,
fold,
foldMap,
foldr,
foldr',
foldl,
foldl',
toList,
#if MIN_VERSION_base(4,8,0)
null,
length,
#endif
elem,
maximum,
minimum,
foldrM,
foldlM,
traverse_,
for_,
mapM_,
forM_,
sequence_,
sequenceA_,
asum,
msum,
concat,
concatMap,
and,
or,
any,
all,
maximumBy,
minimumBy,
notElem,
find,
)
import Data.Functor.Identity as Functor (
Identity(Identity, runIdentity)
)
#if MIN_VERSION_base(4,9,0)
import Data.List.NonEmpty as List (
NonEmpty((:|))
, nonEmpty
)
import Data.Semigroup as Semigroup (
Semigroup(sconcat, stimes)
, WrappedMonoid
, Option(..)
, option
, diff
, cycle1
, stimesMonoid
, stimesIdempotent
, stimesIdempotentMonoid
, mtimesDefault
)
#endif
import Data.Monoid as Monoid
#if !MIN_VERSION_base(4,8,0)
import Protolude.Bifunctor as Bifunctor (Bifunctor(bimap, first, second))
#else
import Data.Bifunctor as Bifunctor (Bifunctor(bimap, first, second))
#endif
-- Deepseq
import Control.DeepSeq as DeepSeq (
NFData(..)
, ($!!)
, deepseq
, force
)
-- Data structures
import Data.Tuple as Tuple (
fst
, snd
, curry
, uncurry
, swap
)
import Data.List as List (
splitAt
, break
, intercalate
, isPrefixOf
, drop
, filter
, reverse
, replicate
, take
, sortBy
, sort
, intersperse
, transpose
, subsequences
, permutations
, scanl
#if MIN_VERSION_base(4,8,0)
, scanl'
#endif
, scanr
, iterate
, repeat
, cycle
, unfoldr
, takeWhile
, dropWhile
, group
, inits
, tails
, zipWith
, zip
, unzip
, genericLength
, genericTake
, genericDrop
, genericSplitAt
, genericReplicate
)
#if !MIN_VERSION_base(4,8,0)
-- These imports are required for the scanl' rewrite rules
import GHC.Exts (build)
import Data.List (tail)
#endif
-- Hashing
import Data.Hashable as Hashable (
Hashable
, hash
, hashWithSalt
, hashUsing
)
import Data.Map as DataStructures (Map)
import Data.Set as DataStructures (Set)
import Data.Sequence as DataStructures (Seq)
import Data.IntMap as DataStructures (IntMap)
import Data.IntSet as DataStructures (IntSet)
import Data.Typeable as Typeable (
TypeRep
, Typeable
, typeOf
, cast
, gcast
#if MIN_VERSION_base(4,7,0)
, typeRep
, eqT
#endif
)
#if MIN_VERSION_base(4,7,0)
import Data.Proxy as Typelevel (
Proxy(..)
)
import Data.Type.Coercion as Typelevel (
Coercion(..)
, coerceWith
, repr
)
import Data.Type.Equality as Typelevel (
(:~:)(..)
, type (==)
, sym
, trans
, castWith
, gcastWith
)
#endif
#if MIN_VERSION_base(4,8,0)
import Data.Void as Typelevel (
Void
, absurd
, vacuous
)
#endif
import Control.Monad.Fail as Fail (
MonadFail
)
-- Monad transformers
import Control.Monad.State as State (
MonadState
, State
, StateT(StateT)
, put
, get
, gets
, modify
, state
, withState
, runState
, execState
, evalState
, runStateT
, execStateT
, evalStateT
)
import Control.Monad.Reader as Reader (
MonadReader
, Reader
, ReaderT(ReaderT)
, ask
, asks
, local
, reader
, runReader
, runReaderT
)
import Control.Monad.Trans.Except as Except (
throwE
, catchE
)
import Control.Monad.Except as Except (
MonadError
, Except
, ExceptT(ExceptT)
, throwError
, catchError
, runExcept
, runExceptT
, mapExcept
, mapExceptT
, withExcept
, withExceptT
)
import Control.Monad.Trans as Trans (
MonadIO
, lift
, liftIO
)
-- Base types
import Data.Int as Int (
Int
, Int8
, Int16
, Int32
, Int64
)
import Data.Bits as Bits (
Bits,
(.&.),
(.|.),
xor,
complement,
shift,
rotate,
#if MIN_VERSION_base(4,7,0)
zeroBits,
#endif
bit,
setBit,
clearBit,
complementBit,
testBit,
#if MIN_VERSION_base(4,7,0)
bitSizeMaybe,
#endif
bitSize,
isSigned,
shiftL,
shiftR,
rotateL,
rotateR,
popCount,
#if MIN_VERSION_base(4,7,0)
FiniteBits,
finiteBitSize,
bitDefault,
testBitDefault,
popCountDefault,
#endif
#if MIN_VERSION_base(4,8,0)
toIntegralSized,
countLeadingZeros,
countTrailingZeros,
#endif
)
import Data.Word as Bits (
Word
, Word8
, Word16
, Word32
, Word64
#if MIN_VERSION_base(4,7,0)
, byteSwap16
, byteSwap32
, byteSwap64
#endif
)
import Data.Either as Either (
Either(Left,Right)
, either
, lefts
, rights
, partitionEithers
#if MIN_VERSION_base(4,7,0)
, isLeft
, isRight
#endif
)
import Data.Complex as Complex (
Complex((:+))
, realPart
, imagPart
, mkPolar
, cis
, polar
, magnitude
, phase
, conjugate
)
import Data.Char as Char (
Char
, ord
, chr
, digitToInt
, intToDigit
, toUpper
, toLower
, toTitle
, isAscii
, isLetter
, isDigit
, isHexDigit
, isPrint
, isAlpha
, isAlphaNum
, isUpper
, isLower
, isSpace
, isControl
)
import Data.Bool as Bool (
Bool(True, False),
(&&),
(||),
not,
otherwise
)
import Data.Maybe as Maybe (
Maybe(Nothing, Just)
, maybe
, isJust
, isNothing
, fromMaybe
, listToMaybe
, maybeToList
, catMaybes
, mapMaybe
)
import Data.Function as Function (
const
, (.)
, ($)
, flip
, fix
, on
#if MIN_VERSION_base(4,8,0)
, (&)
#endif
)
-- Genericss
import GHC.Generics as Generics (
Generic(..)
, Generic1
, Rep
, K1(..)
, M1(..)
, U1(..)
, V1
, D1
, C1
, S1
, (:+:)(..)
, (:*:)(..)
, (:.:)(..)
, Rec0
, Constructor(..)
, Datatype(..)
, Selector(..)
, Fixity(..)
, Associativity(..)
#if ( __GLASGOW_HASKELL__ >= 800 )
, Meta(..)
, FixityI(..)
, URec
#endif
)
-- ByteString
import qualified Data.ByteString.Lazy
import Data.ByteString as ByteString (ByteString)
-- Text
import Data.Text as Text (
Text
, lines
, words
, unlines
, unwords
)
import qualified Data.Text.Lazy
import Data.Text.IO as Text (
getLine
, getContents
, interact
, readFile
, writeFile
, appendFile
)
import Data.Text.Lazy as Text (
toStrict
, fromStrict
)
import Data.Text.Encoding as Text (
encodeUtf8
, decodeUtf8
, decodeUtf8'
, decodeUtf8With
)
import Data.Text.Encoding.Error as Text (
OnDecodeError
, OnError
, UnicodeException
, lenientDecode
, strictDecode
, ignore
, replace
)
-- IO
import System.Environment as System (getArgs)
import qualified System.Exit
import System.Exit as System (
ExitCode(..)
, exitWith
, exitFailure
, exitSuccess
)
import System.IO as System (
Handle
, FilePath
, IOMode(..)
, stdin
, stdout
, stderr
, withFile
, openFile
)
-- ST
import Control.Monad.ST as ST (
ST
, runST
, fixST
)
-- Concurrency and Parallelism
import Control.Exception as Exception (
Exception,
toException,
fromException,
#if MIN_VERSION_base(4,8,0)
displayException,
#endif
SomeException(SomeException)
, IOException
, ArithException(
Overflow,
Underflow,
LossOfPrecision,
DivideByZero,
Denormal,
RatioZeroDenominator
)
, ArrayException(IndexOutOfBounds, UndefinedElement)
, AssertionFailed(AssertionFailed)
#if MIN_VERSION_base(4,7,0)
, SomeAsyncException(SomeAsyncException)
, asyncExceptionToException
, asyncExceptionFromException
#endif
, AsyncException(StackOverflow, HeapOverflow, ThreadKilled, UserInterrupt)
, NonTermination(NonTermination)
, NestedAtomically(NestedAtomically)
, BlockedIndefinitelyOnMVar(BlockedIndefinitelyOnMVar)
, BlockedIndefinitelyOnSTM(BlockedIndefinitelyOnSTM)
#if MIN_VERSION_base(4,8,0)
, AllocationLimitExceeded(AllocationLimitExceeded)
#endif
#if MIN_VERSION_base(4,10,0)
, CompactionFailed(CompactionFailed)
#endif
, Deadlock(Deadlock)
, NoMethodError(NoMethodError)
, PatternMatchFail(PatternMatchFail)
, RecConError(RecConError)
, RecSelError(RecSelError)
, RecUpdError(RecUpdError)
#if MIN_VERSION_base(4,9,0)
, ErrorCall(ErrorCall, ErrorCallWithLocation)
#else
, ErrorCall(ErrorCall)
#endif
#if MIN_VERSION_base(4,9,0)
, TypeError(TypeError)
#endif
, ioError
, catch
, catches
, Handler(Handler)
, catchJust
, handle
, handleJust
, try
, tryJust
, evaluate
, mapException
, mask
, mask_
, uninterruptibleMask
, uninterruptibleMask_
, MaskingState(..)
, getMaskingState
#if MIN_VERSION_base(4,9,0)
, interruptible
#endif
, allowInterrupt
, bracket
, bracket_
, bracketOnError
, finally
, onException
)
import qualified Control.Exception as PException
import Control.Monad.STM as STM (
STM
, atomically
#if !(MIN_VERSION_stm(2,5,0))
, always
, alwaysSucceeds
#endif
, retry
, orElse
, check
, throwSTM
, catchSTM
)
import Control.Concurrent.MVar as Concurrency (
MVar
, newEmptyMVar
, newMVar
, takeMVar
, putMVar
, readMVar
, swapMVar
, tryTakeMVar
, tryPutMVar
, isEmptyMVar
, withMVar
#if MIN_VERSION_base(4,7,0)
, withMVarMasked
#endif
, modifyMVar_
, modifyMVar
, modifyMVarMasked_
, modifyMVarMasked
#if MIN_VERSION_base(4,7,0)
, tryReadMVar
, mkWeakMVar
#endif
, addMVarFinalizer
)
import Control.Concurrent.Chan as Concurrency (
Chan
, newChan
, writeChan
, readChan
, dupChan
, getChanContents
, writeList2Chan
)
import Control.Concurrent.QSem as Concurrency (
QSem
, newQSem
, waitQSem
, signalQSem
)
import Control.Concurrent.QSemN as Concurrency (
QSemN
, newQSemN
, waitQSemN
, signalQSemN
)
import Control.Concurrent as Concurrency (
ThreadId
, forkIO
, forkFinally
, forkIOWithUnmask
, killThread
, forkOn
, forkOnWithUnmask
, getNumCapabilities
, setNumCapabilities
, threadCapability
, yield
, threadDelay
, threadWaitRead
, threadWaitWrite
#if MIN_VERSION_base(4,7,0)
, threadWaitReadSTM
, threadWaitWriteSTM
#endif
, rtsSupportsBoundThreads
, forkOS
#if MIN_VERSION_base(4,9,0)
, forkOSWithUnmask
#endif
, isCurrentThreadBound
, runInBoundThread
, runInUnboundThread
, mkWeakThreadId
, myThreadId
)
import Control.Concurrent.Async as Concurrency (
Async(..)
, Concurrently(..)
, async
, asyncBound
, asyncOn
, withAsync
, withAsyncBound
, withAsyncOn
, wait
, poll
, waitCatch
, cancel
, cancelWith
, asyncThreadId
, waitAny
, waitAnyCatch
, waitAnyCancel
, waitAnyCatchCancel
, waitEither
, waitEitherCatch
, waitEitherCancel
, waitEitherCatchCancel
, waitEither_
, waitBoth
, link
, link2
, race
, race_
, concurrently
)
import Foreign.Ptr as Foreign (IntPtr, WordPtr)
import Foreign.Storable as Foreign (Storable)
import Foreign.StablePtr as Foreign (StablePtr)
-- Read instances hiding unsafe builtins (read)
import qualified Text.Read as Read
import Text.Read as Read (
Read
, reads
)
-- Type synonymss for lazy texts
type LText = Data.Text.Lazy.Text
type LByteString = Data.ByteString.Lazy.ByteString
#if !MIN_VERSION_base(4,8,0)
infixl 1 &
(&) :: a -> (a -> b) -> b
x & f = f x
#endif
-- | The identity function, returns the give value unchanged.
identity :: a -> a
identity x = x
map :: Functor.Functor f => (a -> b) -> f a -> f b
map = Functor.fmap
uncons :: [a] -> Maybe (a, [a])
uncons [] = Nothing
uncons (x:xs) = Just (x, xs)
unsnoc :: [x] -> Maybe ([x],x)
unsnoc = Foldable.foldr go Nothing
where
go x mxs = Just (case mxs of
Nothing -> ([], x)
Just (xs, e) -> (x:xs, e))
-- | Apply a function n times to a given value
applyN :: Int -> (a -> a) -> a -> a
applyN n f = Foldable.foldr (.) identity (List.replicate n f)
-- | Parse a string using the 'Read' instance.
-- Succeeds if there is exactly one valid result.
--
-- >>> readMaybe ("123" :: Text) :: Maybe Int
-- Just 123
--
-- >>> readMaybe ("hello" :: Text) :: Maybe Int
-- Nothing
readMaybe :: (Read b, Conv.StringConv a String) => a -> Maybe b
readMaybe = Read.readMaybe . Conv.toS
-- | Parse a string using the 'Read' instance.
-- Succeeds if there is exactly one valid result.
-- A 'Left' value indicates a parse error.
--
-- >>> readEither "123" :: Either Text Int
-- Right 123
--
-- >>> readEither "hello" :: Either Text Int
-- Left "Prelude.read: no parse"
readEither :: (Read a, Conv.StringConv String e, Conv.StringConv e String) => e -> Either e a
readEither = first Conv.toS . Read.readEither . Conv.toS
-- | The print function outputs a value of any printable type to the standard
-- output device. Printable types are those that are instances of class Show;
-- print converts values to strings for output using the show operation and adds
-- a newline.
print :: (Trans.MonadIO m, PBase.Show a) => a -> m ()
print = liftIO . PBase.print
-- | Lifted throwIO
throwIO :: (Trans.MonadIO m, Exception e) => e -> m a
throwIO = liftIO . PException.throwIO
-- | Lifted throwTo
throwTo :: (Trans.MonadIO m, Exception e) => ThreadId -> e -> m ()
throwTo tid e = liftIO (PException.throwTo tid e)
-- | Do nothing returning unit inside applicative.
pass :: Applicative f => f ()
pass = pure ()
guarded :: (Alternative f) => (a -> Bool) -> a -> f a
guarded p x = Bool.bool empty (pure x) (p x)
guardedA :: (Functor.Functor f, Alternative t) => (a -> f Bool) -> a -> f (t a)
guardedA p x = Bool.bool empty (pure x) `Functor.fmap` p x
-- | Lift an 'IO' operation with 1 argument into another monad
liftIO1 :: MonadIO m => (a -> IO b) -> a -> m b
liftIO1 = (.) liftIO
-- | Lift an 'IO' operation with 2 arguments into another monad
liftIO2 :: MonadIO m => (a -> b -> IO c) -> a -> b -> m c
liftIO2 = ((.).(.)) liftIO
show :: (Show a, Conv.StringConv String b) => a -> b
show x = Conv.toS (PBase.show x)
{-# SPECIALIZE show :: Show a => a -> Text #-}
{-# SPECIALIZE show :: Show a => a -> LText #-}
{-# SPECIALIZE show :: Show a => a -> String #-}
#if MIN_VERSION_base(4,8,0)
-- | Terminate main process with failure
die :: Text -> IO a
die err = System.Exit.die (ConvertText.toS err)
#else
-- | Terminate main process with failure
die :: Text -> IO a
die err = hPutStrLn stderr err >> exitFailure
#endif
#if !MIN_VERSION_base(4,8,0)
-- This is a literal copy of the implementation in GHC.List in base-4.10.1.0.
-- | A strictly accumulating version of 'scanl'
{-# NOINLINE [1] scanl' #-}
scanl' :: (b -> a -> b) -> b -> [a] -> [b]
scanl' = scanlGo'
where
scanlGo' :: (b -> a -> b) -> b -> [a] -> [b]
scanlGo' f !q ls = q : (case ls of
[] -> []
x:xs -> scanlGo' f (f q x) xs)
{-# RULES
"scanl'" [~1] forall f a bs . scanl' f a bs =
build (\c n -> a `c` foldr (scanlFB' f c) (flipSeqScanl' n) bs a)
"scanlList'" [1] forall f a bs .
foldr (scanlFB' f (:)) (flipSeqScanl' []) bs a = tail (scanl' f a bs)
#-}
{-# INLINE [0] scanlFB' #-}
scanlFB' :: (b -> a -> b) -> (b -> c -> c) -> a -> (b -> c) -> b -> c
scanlFB' f c = \b g -> \x -> let !b' = f x b in b' `c` g b'
{-# INLINE [0] flipSeqScanl' #-}
flipSeqScanl' :: a -> b -> a
flipSeqScanl' a !_b = a
#endif
|
sdiehl/protolude
|
src/Protolude.hs
|
Haskell
|
mit
| 19,454
|
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{- |
Module : Data.Fix1
Description : Fixed point for types of kind (k -> *) -> k -> *
Copyright : (c) Paweł Nowak
License : MIT
Maintainer : pawel834@gmail.com
Stability : experimental
-}
module Data.Fix1 where
import Prelude.Compat
-- | This is similar to an "endofunctor on the category of endofunctors", but
-- the forall is lifted outside.
--
-- I speculate that this hmap is implementable for exactly the same types as
-- a hmap of type @(f ~> g) -> (h f ~> h g)@, yet allows more uses.
class HFunctor (h :: (k -> *) -> (k -> *)) where
hmap :: (f a -> g a) -> (h f a -> h g a)
-- | Types such that @g f@ is a functor given that @f@ is a functor.
class Functor1 (g :: (* -> *) -> (* -> *)) where
map1 :: Functor f => (a -> b) -> (g f a -> g f b)
-- | Types such that @g f@ is foldable given that @f@ is foldable.
class Foldable1 (g :: (* -> *) -> (* -> *)) where
foldMap1 :: (Foldable f, Monoid m) => (a -> m) -> (g f a -> m)
-- | Types such that @h f@ is traversable given that @f@ is traversable.
class (Functor1 h, Foldable1 h) => Traversable1 (h :: (* -> *) -> (* -> *)) where
traverse1 :: (Traversable f, Applicative g) => (a -> g b) -> (h f a -> g (h f b))
-- | Fixed point of a type with kind (k -> *) -> k -> *
data Fix1 (f :: (k -> *) -> k -> *) (a :: k) = Fix1 { unFix1 :: f (Fix1 f) a }
instance Functor1 f => Functor (Fix1 f) where
fmap f = Fix1 . map1 f . unFix1
instance Foldable1 f => Foldable (Fix1 f) where
foldMap f = foldMap1 f . unFix1
instance Traversable1 f => Traversable (Fix1 f) where
traverse f (Fix1 a) = Fix1 <$> traverse1 f a
cata1 :: HFunctor f => (f g a -> g a) -> Fix1 f a -> g a
cata1 f = f . hmap (cata1 f) . unFix1
ana1 :: HFunctor f => (g a -> f g a) -> g a -> Fix1 f a
ana1 f = Fix1 . hmap (ana1 f) . f
hylo1 :: HFunctor f => (f g a -> g a) -> (h a -> f h a) -> (h a -> g a)
hylo1 phi psi = cata1 phi . ana1 psi
infixr 9 .:
(.:) :: (c -> d) -> (a -> b -> c) -> a -> b -> d
(.:) = (.) . (.)
infixr 9 .::
(.::) :: (d -> e) -> (a -> b -> c -> d) -> a -> b -> c -> e
(.::) = (.:) . (.)
|
pawel-n/data-fix1
|
src/Data/Fix1.hs
|
Haskell
|
mit
| 2,175
|
module Alarm where
import Control.Probability
bool :: (Probability p, MonadProb p m) => p -> m p Bool
bool p = choose p True False
filterDist :: (Ord a, MonadProb p m) => (a -> Bool) -> m p a -> m p a
filterDist f m = do x <- m
condition (f x)
returning x
(>>=?) :: (Ord a, MonadProb p m) => m p a -> (a -> Bool) -> m p a
(>>=?) = flip filterDist
(?=<<) :: (Ord a, MonadProb p m) => (a -> Bool) -> m p a -> m p a
(?=<<) = filterDist
-- | prior burglary is 1%
b :: Dist Bool
b = bool 0.01
-- | prior earthqauke is 0.1%
e :: Dist Bool
e = bool 0.001
-- | conditional prob of alarm | burglary, earthquake
a :: Bool -> Bool -> Dist Bool
a b0 e0 =
case (b0,e0) of
(False,False) -> bool 0.01
(False,True) -> bool 0.1
(True,False) -> bool 0.7
(True,True) -> bool 0.9
-- | conditional prob of john calling | alarm
j :: Bool -> Dist Bool
j a = if a then bool 0.8 else bool 0.05
-- | conditional prob of mary calling | alarm
m :: Bool -> Dist Bool
m a = if a then bool 0.9 else bool 0.1
-- | full joint distribution
data Burglary = B
{ burglary :: Bool
, earthquake :: Bool
, alarm :: Bool
, john :: Bool
, mary :: Bool }
deriving (Eq,Ord,Show)
joint :: Dist Burglary
joint = do
b' <- b
e' <- e
a' <- a b' e'
j' <- j a'
m' <- m a'
returning $ B b' e' a' j' m'
-- | probability that mary calls given john calls
mj = mary ?? john ?=<< joint
-- | probability of burglary given mary calls
bm = burglary ?? mary ?=<< joint
-- | probability of burglary given john calls
bj = burglary ?? john ?=<< joint
|
chris-taylor/hs-probability-examples
|
Alarm.hs
|
Haskell
|
mit
| 1,651
|
module P8 where
import Data.List
{-
(**) Eliminate consecutive duplicates of list elements.
If a list contains repeated elements they should be replaced with a single copy of the element.
The order of the elements should not be changed.
Example:
* (compress '(a a a a b c c a a d e e e e))
(A B C A D E)
-}
compress :: (Eq a) => [a] -> [a]
compress [] = []
compress list = foldr (\y acc -> if elem y acc then acc else y : acc) [] list
compress' :: (Eq a) => [a] -> [a]
compress' (x:ys@(y:_))
| x == y = compress ys
| otherwise = x : compress ys
compress' ys = ys
compress'' :: (Eq a) => [a] -> [a]
compress'' = map head . group
|
nikolaspapirniywork/99_problems
|
haskell/src/P8.hs
|
Haskell
|
apache-2.0
| 685
|
{-# LANGUAGE BangPatterns #-}
{-|
Module : Data.Snowflake
Description : Unique id generator. Port of Twitter Snowflake.
License : Apache 2.0
Maintainer : edofic@gmail.com
Stability : experimental
This generates unique(guaranteed) identifiers build from time stamp,
counter(inside same millisecond) and node id - if you wish to generate
ids across several nodes. Identifiers are convertible to `Integer`
values which are monotonically increasing with respect to time.
-}
module Data.Snowflake
( SnowflakeConfig(..)
, Snowflake
, SnowflakeGen
, newSnowflakeGen
, nextSnowflake
, defaultConfig
, snowflakeToInteger
) where
import Data.Bits ((.|.), (.&.), shift, Bits)
import Control.Concurrent.MVar (MVar, newMVar, putMVar, takeMVar)
import Data.Time.Clock.POSIX (getPOSIXTime)
import Control.Monad (when)
import Control.Concurrent (threadDelay)
{-|
Configuration that specifies how much bits are used for each part of the id.
There are no limits to total bit sum.
-}
data SnowflakeConfig = SnowflakeConfig { confTimeBits :: {-# UNPACK #-} !Int
, confCountBits :: {-# UNPACK #-} !Int
, confNodeBits :: {-# UNPACK #-} !Int
} deriving (Eq, Show)
-- |Default configuration using 40 bits for time, 16 for count and 8 for node id.
defaultConfig :: SnowflakeConfig
defaultConfig = SnowflakeConfig 40 16 8
-- |Generator which contains needed state. You should use `newSnowflakeGen` to create instances.
newtype SnowflakeGen = SnowflakeGen { genLastSnowflake :: MVar Snowflake }
-- |Generated identifier. Can be converted to `Integer`.
data Snowflake = Snowflake { snowflakeTime :: !Integer
, snowflakeCount :: !Integer
, snowflakeNode :: !Integer
, snowflakeConf :: !SnowflakeConfig
} deriving (Eq)
-- |Converts an identifier to an integer with respect to configuration used to generate it.
snowflakeToInteger :: Snowflake -> Integer
snowflakeToInteger (Snowflake time count node config) = let
SnowflakeConfig _ countBits nodeBits = config
in
(time `shift` (countBits + nodeBits))
.|.
(count `shift` nodeBits)
.|.
node
instance Show Snowflake where
show = show . snowflakeToInteger
cutBits :: (Num a, Bits a) => a -> Int -> a
cutBits n bits = n .&. ((1 `shift` bits) - 1)
currentTimestamp :: IO Integer
currentTimestamp = (round . (*1000)) `fmap` getPOSIXTime
currentTimestampFixed :: Int -> IO Integer
currentTimestampFixed n = fmap (`cutBits` n) currentTimestamp
-- |Create a new generator. Takes a configuration and node id.
newSnowflakeGen :: SnowflakeConfig -> Integer -> IO SnowflakeGen
newSnowflakeGen conf@(SnowflakeConfig timeBits _ nodeBits) nodeIdRaw = do
timestamp <- currentTimestampFixed timeBits
let nodeId = nodeIdRaw `cutBits` nodeBits
initial = Snowflake timestamp 0 nodeId conf
mvar <- newMVar initial
return $ SnowflakeGen mvar
-- |Generates next id. The bread and butter. See module description for details.
nextSnowflake :: SnowflakeGen -> IO Snowflake
nextSnowflake (SnowflakeGen lastRef) = do
Snowflake lastTime lastCount node conf <- takeMVar lastRef
let SnowflakeConfig timeBits countBits _ = conf
getNextTime = do
time <- currentTimestampFixed timeBits
if (lastTime > time) then do
threadDelay $ fromInteger $ (lastTime - time) * 1000
getNextTime
else
return time
loop = do
timestamp <- getNextTime
let count = if timestamp == lastTime then lastCount + 1 else 0
if ((count `shift` (-1 * countBits)) /= 0) then
loop
else
return $ Snowflake timestamp count node conf
new <- loop
putMVar lastRef new
return new
|
edofic/snowflake-haskell
|
src/Data/Snowflake.hs
|
Haskell
|
apache-2.0
| 3,881
|
-- -*- coding: utf-8; -*-
module Filter where
import Model
import qualified Data.Map as Map
filterElements :: Map.Map String String -- props jakie muszą być znalezione żeby element był zwrócony
-> [Element] -- filtrowane elementy
-> [Element]
filterElements pattern (e@(Element _ props _):es) | areCompatible pattern props = e : filterElements pattern es
filterElements pattern (e@(Element _ _ subelements):es) = filterElements pattern subelements ++ filterElements pattern es
filterElements pattern (e@(Text props _ _):es) | areCompatible pattern props = e : filterElements pattern es
filterElements pattern (_:es) = filterElements pattern es
filterElements pattern [] = []
areCompatible template props = Map.intersection props template == template
|
grzegorzbalcerek/orgmode
|
Filter.hs
|
Haskell
|
bsd-2-clause
| 809
|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
-- | High-level API for CouchDB design documents. These methods are very
-- convenient for bootstrapping and testing.
module Database.CouchDB.Conduit.Design (
couchPutView
) where
import Prelude hiding (catch)
import Control.Monad (void)
import Control.Exception.Lifted (catch)
import qualified Data.ByteString as B
import Data.Text (Text)
import qualified Data.Text.Encoding as TE
import qualified Data.HashMap.Lazy as M
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as AT
import Database.CouchDB.Conduit.Internal.Connection
(MonadCouch, CouchError, Path, mkPath, Revision)
import Database.CouchDB.Conduit.Internal.Doc (couchGetWith, couchPutWith')
-- | Put view to design document. If design document does not exist,
-- it will be created.
couchPutView :: MonadCouch m =>
Path -- ^ Database
-> Path -- ^ Design document
-> Path -- ^ View name
-> B.ByteString -- ^ Map function
-> Maybe B.ByteString -- ^ Reduce function
-> m ()
couchPutView db designName viewName mapF reduceF = do
(_, A.Object d) <- getDesignDoc path
void $ couchPutWith' A.encode path [] $ inferViews (purge_ d)
where
path = designDocPath db designName
inferViews d = A.Object $ M.insert "views" (addView d) d
addView d = A.Object $ M.insert
(TE.decodeUtf8 viewName)
(constructView mapF reduceF)
(extractViews d)
constructView :: B.ByteString -> Maybe B.ByteString -> A.Value
constructView m (Just r) = A.object ["map" A..= m, "reduce" A..= r]
constructView m Nothing = A.object ["map" A..= m]
-----------------------------------------------------------------------------
-- Internal
-----------------------------------------------------------------------------
getDesignDoc :: MonadCouch m =>
Path
-> m (Revision, AT.Value)
getDesignDoc designName = catch
(couchGetWith A.Success designName [])
(\(_ :: CouchError) -> return (B.empty, AT.emptyObject))
designDocPath :: Path -> Path -> Path
designDocPath db dn = mkPath [db, "_design", dn]
-- | Purge underscore fields
purge_ :: AT.Object -> AT.Object
purge_ = M.filterWithKey (\k _ -> k `notElem` ["_id", "_rev"])
-- | Strip 'A.Value'
stripObject :: AT.Value -> AT.Object
stripObject (A.Object a) = a
stripObject _ = M.empty
-- Extract views field or return empty map
extractViews :: M.HashMap Text AT.Value -> M.HashMap Text AT.Value
extractViews o = maybe M.empty stripObject $ M.lookup "views" o
|
lostbean/neo4j-conduit
|
src/Database/CouchDB/Conduit/Design.hs
|
Haskell
|
bsd-2-clause
| 2,689
|
module GTL.Text (
gtlToText
) where
import GTL.Parser
import qualified Data.Map as Map
import Data.List ((\\), partition, sort, intercalate, foldl')
import Data.Tree
gtlToText :: MyTree -> [String]
gtlToText tree = reverse
$ concat
$ reverse
$ flatten
$ fmap (stringify time) tree
where
(time, _, _, _) = rootLabel tree
stringify :: ErlTime -> (ErlTime, Dur, Pid, [BRecord]) -> [String]
stringify startGTLTs (startPidTs, _, _, rs) = lines
where
(_, lines) = foldl' p (startPidTs,[]) rs
p (prevTs, lines) r = (time, line:lines)
where
(time, pid, m, f, a) = (rTime r, rPid r, rModule r, rFunction r, rArg r)
diffPrev = (time - prevTs) `div` 1000
diffBegin = (time - startGTLTs) `div` 1000
line = pid ++ " ( " ++ show diffPrev ++ " / "
++ show diffBegin ++ " ) "
++ m ++ ":" ++ f ++ " " ++ a
|
EchoTeam/gtl
|
tools/GTL/Text.hs
|
Haskell
|
bsd-2-clause
| 993
|
-- 248155780267521
import Data.List(sort)
import Euler(digitSum)
kk = 20
nn = 10^kk-1
mm = digitSum nn
vv = 30
findPowerSums n = map fst $ filter (\x -> snd x == n) ns
where ps = takeWhile (nn>) $ map (n^) [2..]
ns = map (\x -> (x, digitSum x)) ps
allPowerSums = sort $ concatMap findPowerSums [2..mm]
main = putStrLn $ show $ allPowerSums !! (vv-1)
|
higgsd/euler
|
hs/119.hs
|
Haskell
|
bsd-2-clause
| 368
|
-- Exercise 5 in chapter 3 of "Real World Haskell"
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome [] = True
isPalindrome ys@(x:xs) | odd (length ys) = False
isPalindrome ys@(x:xs) | ys == (reverse ys) = True
isPalindrome (x:xs) = False
|
ploverlake/practice_of_haskell
|
src/isPalindrome.hs
|
Haskell
|
bsd-2-clause
| 299
|
module Graphics.Pastel.WX.Test ( testWX ) where
import Graphics.UI.WX hiding (circle)
import Graphics.UI.WXCore.Image
import Graphics.Pastel
import Graphics.Pastel.WX.Draw
testWX :: (Int, Int) -> Drawing -> IO ()
testWX (w,h) d = start gui
where gui = do
window <- frame [text := "Pastel WX Runner"]
canvas <- panel window [on paint := redraw]
return ()
redraw dc viewArea = do image <- drawWX (w,h) d
drawImage dc image (Point 0 0) []
|
willdonnelly/pastel
|
Graphics/Pastel/WX/Test.hs
|
Haskell
|
bsd-3-clause
| 529
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude, MagicHash #-}
{-# LANGUAGE AutoDeriveTypeable, StandaloneDeriving #-}
-----------------------------------------------------------------------------
-- |
-- Module : Control.Exception.Base
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (extended exceptions)
--
-- Extensible exceptions, except for multiple handlers.
--
-----------------------------------------------------------------------------
module Control.Exception.Base (
-- * The Exception type
SomeException(..),
Exception(..),
IOException,
ArithException(..),
ArrayException(..),
AssertionFailed(..),
SomeAsyncException(..), AsyncException(..),
asyncExceptionToException, asyncExceptionFromException,
NonTermination(..),
NestedAtomically(..),
BlockedIndefinitelyOnMVar(..),
BlockedIndefinitelyOnSTM(..),
AllocationLimitExceeded(..),
Deadlock(..),
NoMethodError(..),
PatternMatchFail(..),
RecConError(..),
RecSelError(..),
RecUpdError(..),
ErrorCall(..),
-- * Throwing exceptions
throwIO,
throw,
ioError,
throwTo,
-- * Catching Exceptions
-- ** The @catch@ functions
catch,
catchJust,
-- ** The @handle@ functions
handle,
handleJust,
-- ** The @try@ functions
try,
tryJust,
onException,
-- ** The @evaluate@ function
evaluate,
-- ** The @mapException@ function
mapException,
-- * Asynchronous Exceptions
-- ** Asynchronous exception control
mask,
mask_,
uninterruptibleMask,
uninterruptibleMask_,
MaskingState(..),
getMaskingState,
-- * Assertions
assert,
-- * Utilities
bracket,
bracket_,
bracketOnError,
finally,
-- * Calls for GHC runtime
recSelError, recConError, irrefutPatError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError,
nonTermination, nestedAtomically,
) where
import GHC.Base
import GHC.IO hiding (bracket,finally,onException)
import GHC.IO.Exception
import GHC.Exception
import GHC.Show
-- import GHC.Exception hiding ( Exception )
import GHC.Conc.Sync
import Data.Dynamic
import Data.Either
-----------------------------------------------------------------------------
-- Catching exceptions
-- |This is the simplest of the exception-catching functions. It
-- takes a single argument, runs it, and if an exception is raised
-- the \"handler\" is executed, with the value of the exception passed as an
-- argument. Otherwise, the result is returned as normal. For example:
--
-- > catch (readFile f)
-- > (\e -> do let err = show (e :: IOException)
-- > hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
-- > return "")
--
-- Note that we have to give a type signature to @e@, or the program
-- will not typecheck as the type is ambiguous. While it is possible
-- to catch exceptions of any type, see the section \"Catching all
-- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
--
-- For catching exceptions in pure (non-'IO') expressions, see the
-- function 'evaluate'.
--
-- Note that due to Haskell\'s unspecified evaluation order, an
-- expression may throw one of several possible exceptions: consider
-- the expression @(error \"urk\") + (1 \`div\` 0)@. Does
-- the expression throw
-- @ErrorCall \"urk\"@, or @DivideByZero@?
--
-- The answer is \"it might throw either\"; the choice is
-- non-deterministic. If you are catching any type of exception then you
-- might catch either. If you are calling @catch@ with type
-- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
-- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
-- exception may be propogated further up. If you call it again, you
-- might get a the opposite behaviour. This is ok, because 'catch' is an
-- 'IO' computation.
--
catch :: Exception e
=> IO a -- ^ The computation to run
-> (e -> IO a) -- ^ Handler to invoke if an exception is raised
-> IO a
catch = catchException
-- | The function 'catchJust' is like 'catch', but it takes an extra
-- argument which is an /exception predicate/, a function which
-- selects which type of exceptions we\'re interested in.
--
-- > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
-- > (readFile f)
-- > (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
-- > return "")
--
-- Any other exceptions which are not matched by the predicate
-- are re-raised, and may be caught by an enclosing
-- 'catch', 'catchJust', etc.
catchJust
:: Exception e
=> (e -> Maybe b) -- ^ Predicate to select exceptions
-> IO a -- ^ Computation to run
-> (b -> IO a) -- ^ Handler
-> IO a
catchJust p a handler = catch a handler'
where handler' e = case p e of
Nothing -> throwIO e
Just b -> handler b
-- | A version of 'catch' with the arguments swapped around; useful in
-- situations where the code for the handler is shorter. For example:
--
-- > do handle (\NonTermination -> exitWith (ExitFailure 1)) $
-- > ...
handle :: Exception e => (e -> IO a) -> IO a -> IO a
handle = flip catch
-- | A version of 'catchJust' with the arguments swapped around (see
-- 'handle').
handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
handleJust p = flip (catchJust p)
-----------------------------------------------------------------------------
-- 'mapException'
-- | This function maps one exception into another as proposed in the
-- paper \"A semantics for imprecise exceptions\".
-- Notice that the usage of 'unsafePerformIO' is safe here.
mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
mapException f v = unsafePerformIO (catch (evaluate v)
(\x -> throwIO (f x)))
-----------------------------------------------------------------------------
-- 'try' and variations.
-- | Similar to 'catch', but returns an 'Either' result which is
-- @('Right' a)@ if no exception of type @e@ was raised, or @('Left' ex)@
-- if an exception of type @e@ was raised and its value is @ex@.
-- If any other type of exception is raised than it will be propogated
-- up to the next enclosing exception handler.
--
-- > try a = catch (Right `liftM` a) (return . Left)
try :: Exception e => IO a -> IO (Either e a)
try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
-- | A variant of 'try' that takes an exception predicate to select
-- which exceptions are caught (c.f. 'catchJust'). If the exception
-- does not match the predicate, it is re-thrown.
tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
tryJust p a = do
r <- try a
case r of
Right v -> return (Right v)
Left e -> case p e of
Nothing -> throwIO e
Just b -> return (Left b)
-- | Like 'finally', but only performs the final action if there was an
-- exception raised by the computation.
onException :: IO a -> IO b -> IO a
onException io what = io `catch` \e -> do _ <- what
throwIO (e :: SomeException)
-----------------------------------------------------------------------------
-- Some Useful Functions
-- | When you want to acquire a resource, do some work with it, and
-- then release the resource, it is a good idea to use 'bracket',
-- because 'bracket' will install the necessary exception handler to
-- release the resource in the event that an exception is raised
-- during the computation. If an exception is raised, then 'bracket' will
-- re-raise the exception (after performing the release).
--
-- A common example is opening a file:
--
-- > bracket
-- > (openFile "filename" ReadMode)
-- > (hClose)
-- > (\fileHandle -> do { ... })
--
-- The arguments to 'bracket' are in this order so that we can partially apply
-- it, e.g.:
--
-- > withFile name mode = bracket (openFile name mode) hClose
--
bracket
:: IO a -- ^ computation to run first (\"acquire resource\")
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracket before after thing =
mask $ \restore -> do
a <- before
-- 执行中间的过程的时候,不再屏蔽异常
-- 出现异常或者正常运行结束后再运行after
r <- restore (thing a) `onException` after a
_ <- after a
return r
-- | A specialised variant of 'bracket' with just a computation to run
-- afterward.
--
finally :: IO a -- ^ computation to run first
-> IO b -- ^ computation to run afterward (even if an exception
-- was raised)
-> IO a -- returns the value from the first computation
a `finally` sequel =
mask $ \restore -> do
r <- restore a `onException` sequel
_ <- sequel
return r
-- | A variant of 'bracket' where the return value from the first computation
-- is not required.
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ before after thing = bracket before (const after) (const thing)
-- | Like 'bracket', but only performs the final action if there was an
-- exception raised by the in-between computation.
bracketOnError
:: IO a -- ^ computation to run first (\"acquire resource\")
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracketOnError before after thing =
mask $ \restore -> do
a <- before
restore (thing a) `onException` after a
-----
-- |A pattern match failed. The @String@ gives information about the
-- source location of the pattern.
data PatternMatchFail = PatternMatchFail String deriving Typeable
instance Show PatternMatchFail where
showsPrec _ (PatternMatchFail err) = showString err
instance Exception PatternMatchFail
-----
-- |A record selector was applied to a constructor without the
-- appropriate field. This can only happen with a datatype with
-- multiple constructors, where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record selector.
data RecSelError = RecSelError String deriving Typeable
instance Show RecSelError where
showsPrec _ (RecSelError err) = showString err
instance Exception RecSelError
-----
-- |An uninitialised record field was used. The @String@ gives
-- information about the source location where the record was
-- constructed.
data RecConError = RecConError String deriving Typeable
instance Show RecConError where
showsPrec _ (RecConError err) = showString err
instance Exception RecConError
-----
-- |A record update was performed on a constructor without the
-- appropriate field. This can only happen with a datatype with
-- multiple constructors, where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record update.
data RecUpdError = RecUpdError String deriving Typeable
instance Show RecUpdError where
showsPrec _ (RecUpdError err) = showString err
instance Exception RecUpdError
-----
-- |A class method without a definition (neither a default definition,
-- nor a definition in the appropriate instance) was called. The
-- @String@ gives information about which method it was.
data NoMethodError = NoMethodError String deriving Typeable
instance Show NoMethodError where
showsPrec _ (NoMethodError err) = showString err
instance Exception NoMethodError
-----
-- |Thrown when the runtime system detects that the computation is
-- guaranteed not to terminate. Note that there is no guarantee that
-- the runtime system will notice whether any given computation is
-- guaranteed to terminate or not.
data NonTermination = NonTermination deriving Typeable
instance Show NonTermination where
showsPrec _ NonTermination = showString "<<loop>>"
instance Exception NonTermination
-----
-- |Thrown when the program attempts to call @atomically@, from the @stm@
-- package, inside another call to @atomically@.
data NestedAtomically = NestedAtomically deriving Typeable
instance Show NestedAtomically where
showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
instance Exception NestedAtomically
-----
recSelError, recConError, irrefutPatError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError
:: Addr# -> a -- All take a UTF8-encoded C string
recSelError s = throw (RecSelError ("No match in record selector "
++ unpackCStringUtf8# s)) -- No location info unfortunately
runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
absentError s = error ("Oops! Entered absent arg " ++ unpackCStringUtf8# s)
nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
recConError s = throw (RecConError (untangle s "Missing field in record construction"))
noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
-- GHC's RTS calls this
nonTermination :: SomeException
nonTermination = toException NonTermination
-- GHC's RTS calls this
nestedAtomically :: SomeException
nestedAtomically = toException NestedAtomically
|
DavidAlphaFox/ghc
|
libraries/base/Control/Exception/Base.hs
|
Haskell
|
bsd-3-clause
| 14,530
|
{-# LANGUAGE Arrows, OverloadedStrings #-}
import FRP.Yampa
import FRP.Yampa.Utilities
import Data.Colour.Names
import Graphics
import Shapes
import Input
type Scalar = Double
type Vector = (Scalar, Scalar)
type Position = (Scalar, Scalar)
main :: IO ()
main = animate "Demo" 640 480 (parseWinInput >>> ((demo >>> render) &&& handleExit))
-- | A ball will rest until the first click.
-- After the click it starts to fall.
-- The ball can be kicked with another click.
-- Ball has no limits, although you can bring it back.
demo :: SF AppInput Ball
demo = switch (constant ball &&& lbp) (const $ kickableBall ball)
gravity :: Vector
gravity = (0, -200)
data Ball = Ball { position :: Position
, velocity :: Vector
}
ball :: Ball
ball = Ball (320, 240) (0, 0)
-- | Kicks the ball in the direction of the specified point
kick :: Position -> Ball -> Ball
kick (tx, ty) (Ball p v) = Ball p (v ^+^ impulse)
where impulse = (tx,ty) ^-^ p
fallingBall :: Ball -> SF a Ball
fallingBall (Ball p0 v0) = lift2 Ball pos vel
where vel = constant gravity >>> imIntegral v0
pos = vel >>> imIntegral p0
kickableBall :: Ball -> SF AppInput Ball
kickableBall b0 =
kSwitch (fallingBall b0) -- initial SF
(first lbpPos >>^ uncurry attach) -- switch trigger
(\_old -> kickableBall . uncurry kick) -- create a new SF
render :: SF Ball Object
render = scene_ . (:[]) ^<< arr renderBall
-- Here is your wooden rectangular ball, son. Go play with your buddies.
where renderBall (Ball pos _) =
circle_ 100 ! pos_ pos
! colour_ red
-- | Returns False when there is a signal to exit
-- You might also want to handle other signals here (e.g. Esc button press)
handleExit :: SF AppInput Bool
handleExit = quitEvent >>> arr isEvent
|
pyrtsa/yampa-demos-template
|
src/Main.hs
|
Haskell
|
bsd-3-clause
| 1,890
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE GADTs #-}
module DodgerBlue.Types
(CustomDsl(..),
customCmd,
ConcurrentDslCmd(..),
CustomCommandStep) where
import Data.Text (Text)
import Data.Typeable
import Control.Monad.Free.Church
data ConcurrentDslCmd q d next where
NewQueue' :: Typeable a => (q a -> next) -> ConcurrentDslCmd q d next
WriteQueue' :: Typeable a => q a -> a -> next -> ConcurrentDslCmd q d next
TryReadQueue' :: Typeable a => q a -> (Maybe a -> next) -> ConcurrentDslCmd q d next
ReadQueue' :: Typeable a => q a -> (a -> next) -> ConcurrentDslCmd q d next
ForkChild' :: Text -> F (CustomDsl q d) () -> next -> ConcurrentDslCmd q d next
SetPulseStatus' :: Bool -> next -> ConcurrentDslCmd q d next
deriving instance Functor (ConcurrentDslCmd q d)
data CustomDsl q d next =
DslBase (ConcurrentDslCmd q d next)
| DslCustom (d next)
instance Functor d => Functor (CustomDsl q d) where
fmap f (DslBase a) = DslBase $ fmap f a
fmap f (DslCustom a) = DslCustom $ fmap f a
type CustomCommandStep t m = forall a. t (m a) -> m a
customCmd :: (Functor t, MonadFree (CustomDsl q t) m) => t a -> m a
customCmd x = liftF . DodgerBlue.Types.DslCustom $ x
|
adbrowne/dodgerblue
|
src/DodgerBlue/Types.hs
|
Haskell
|
bsd-3-clause
| 1,297
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
module Plots.Types.Points
( -- * Polar scatter plot
GPointsPlot
, mkPointsPlot
-- * Lenses
, doFill
-- * Points plot
, pointsPlot
, pointsPlot'
) where
import Control.Lens hiding (lmap, none, transform,
( # ))
import Control.Monad.State.Lazy
import Data.Typeable
import Diagrams.Prelude
import Diagrams.Coordinates.Isomorphic
import Diagrams.Coordinates.Polar
import Plots.Themes
import Plots.Types
import Plots.API
------------------------------------------------------------------------
-- GPoints plot
------------------------------------------------------------------------
data GPointsPlot n = GPointsPlot
{ sPoints :: [(n, Angle n)]
, sFill :: Bool
} deriving Typeable
-- options for style and transform.
-- lenses for style and transform,
-- scatter plot for example.
type instance V (GPointsPlot n) = V2
type instance N (GPointsPlot n) = n
instance (OrderedField n) => Enveloped (GPointsPlot n) where
getEnvelope GPointsPlot {..} = mempty
instance (v ~ V2, Typeable b, TypeableFloat n, Renderable (Path v n) b)
=> Plotable (GPointsPlot n) b where
renderPlotable _ GPointsPlot {..} pp =
mconcat [marker # applyMarkerStyle pp # scale 0.1 # moveTo (p2 (r*(cosA theta),r*(sinA theta)))| (r,theta) <- sPoints]
<> if sFill
then doline <> doarea
else mempty
where
marker = pp ^. plotMarker
doline = fromVertices (map p2 [(r*(cosA theta),r*(sinA theta)) | (r,theta) <- sPoints]) # mapLoc closeLine # stroke # applyLineStyle pp
doarea = fromVertices (map p2 [(r*(cosA theta),r*(sinA theta)) | (r,theta) <- sPoints]) # mapLoc closeLine # stroke # lw none # applyBarStyle pp
defLegendPic GPointsPlot {..} pp
= pp ^. plotMarker
& applyMarkerStyle pp
------------------------------------------------------------------------
-- Points plot
------------------------------------------------------------------------
-- | Plot a polar scatter plot given a list of radius and angle.
mkPointsPlot :: (RealFloat n, PointLike V2 n (Polar n), Num n)
=> [(n, Angle n)] -> GPointsPlot n
mkPointsPlot ds = GPointsPlot
{ sPoints = ds
, sFill = False
}
------------------------------------------------------------------------
-- Points lenses
------------------------------------------------------------------------
class HasPoints a n | a -> n where
pts :: Lens' a (GPointsPlot n)
doFill :: Lens' a Bool
doFill = pts . lens sFill (\s b -> (s {sFill = b}))
instance HasPoints (GPointsPlot n) n where
pts = id
instance HasPoints (PropertiedPlot (GPointsPlot n) b) n where
pts = _pp
------------------------------------------------------------------------
-- Points plot
------------------------------------------------------------------------
-- $ points plot
-- Points plot display data as scatter (dots) on polar co-ord.
-- Points plots have the following lenses:
--
-- @
-- * 'doFill' :: 'Lens'' ('BoxPlot' v n) 'Bool' - False
-- @
--
-- | Add a 'PointsPlot' to the 'AxisState' from a data set.
--
-- @
-- myaxis = polarAxis ~&
-- pointsPlot data1
-- @
--
-- === __Example__
--
-- <<plots/points.png#diagram=points&width=300>>
--
-- @
--
-- myaxis :: Axis B Polar Double
-- myaxis = polarAxis &~ do
-- pointsPlot mydata1
-- pointsPlot mydata2
-- pointsPlot mydata3
--
-- @
pointsPlot
:: (v ~ BaseSpace c, v ~ V2,
PointLike v n (Polar n),
MonadState (Axis b c n) m,
Plotable (GPointsPlot n) b,
RealFloat n)
=> [(n,Angle n)] -> m ()
pointsPlot ds = addPlotable (mkPointsPlot ds)
-- | Make a 'PointsPlot' and take a 'State' on the plot to alter it's
-- options
--
-- @
-- myaxis = polarAxis &~ do
-- pointsPlot' pointData1 $ do
-- addLegendEntry "data 1"
-- doFill .= True
-- @
pointsPlot'
:: (v ~ BaseSpace c, v ~ V2,
PointLike v n (Polar n),
MonadState (Axis b c n) m,
Plotable (GPointsPlot n) b,
RealFloat n)
=> [(n,Angle n)] -> PlotState (GPointsPlot n) b -> m ()
pointsPlot' ds = addPlotable' (mkPointsPlot ds)
|
bergey/plots
|
src/Plots/Types/Points.hs
|
Haskell
|
bsd-3-clause
| 4,812
|
{-# LANGUAGE
OverlappingInstances
,EmptyDataDecls
,FlexibleContexts
,FlexibleInstances
,FunctionalDependencies
,GeneralizedNewtypeDeriving
,KindSignatures
,MultiParamTypeClasses
,NoMonomorphismRestriction
,ScopedTypeVariables
,TemplateHaskell
,TypeOperators
,TypeSynonymInstances
,UndecidableInstances
,ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-missing-signatures
-fcontext-stack=81 #-}
-- I can't figure out an acceptable type for 'set' and similar:
-- ghc doesn't accept the type inferred by ghci
{- |
Module : XMonad.Config.Alt.Internal
Copyright : Adam Vogt <vogt.adam@gmail.com>
License : BSD3-style (see LICENSE)
Maintainer : Adam Vogt <vogt.adam@gmail.com>
Stability : unstable
Portability : unportable
Import "XMonad.Config.Alt".
-}
module XMonad.Config.Alt.Internal (
module XMonad.Config.Alt.QQ,
-- * Running
runConfig,
runConfig',
-- * Actions
-- $actions
set,
add,
modify,
modifyIO,
-- ** less useful
modifyIO',
insertInto,
-- * Things to modify
-- ** Special
LayoutHook(LayoutHook),
-- ** Others
FocusFollowsMouse(FocusFollowsMouse),
StartupHook(StartupHook),
LogHook(LogHook),
BorderWidth(BorderWidth),
MouseBindings(MouseBindings),
Keys(Keys),
ModMask(ModMask),
Workspaces(Workspaces),
HandleEventHook(HandleEventHook),
ManageHook(ManageHook),
Terminal(Terminal),
FocusedBorderColor(FocusedBorderColor),
NormalBorderColor(NormalBorderColor),
-- * Relatively private
-- | You probably don't need these
defaultPrec,
-- ** Ordered Insertion into HLists like [(Nat,a)]
insLt,
insGeq,
Ins2(..),
Ins'(..),
ins,
-- ** Useful functions
HCompose(hComp),
Snd(Snd),
HSubtract(hSubtract),
HReplicateF(hReplicateF),
HPred'(hPred'),
-- ** For overloading
Mode(..),
Add(Add),
Set(Set),
Modify(Modify),
ModifyIO(ModifyIO),
Config(..),
test,
module Data.HList,
) where
import Control.Monad.Writer
import Data.Char
import Data.HList
import Language.Haskell.TH
import qualified XMonad as X
import XMonad.Config.Alt.Types
import XMonad.Config.Alt.QQ
-- * Class to write set / modify as functions
class Mode action field e x y | action field e x -> y, action field x y -> e where
m :: action -> field -> e -> X.XConfig x -> Config (X.XConfig y)
-- * Actions for 'Mode'
data Add = Add -- ^ the 'Mode' instance combines the old value like @new `mappend` old@
data Set = Set
data Modify = Modify
data ModifyIO = ModifyIO
$(decNat "defaultPrec" 4)
{- $actions
Use 'set', 'add', 'modify', 'modifyIO' for most predefined fields in 'XConfig'.
For constructing things to modify a config:
> insertInto action hold prec field v
* @action@ is an instance of 'Mode' so you only need to write 'ModifyIO' to describe how to access this field.
* @hold@ is 'HTrue' if you don't want to overwrite a preexisting value at the same @prec@. This is for things that should be applied once-only.
* @field@ used with the 'Mode'
* @v@ the value that is being updated (or a function if you use 'Modify' or similar)
-}
set f v = insertInto Set hFalse defaultPrec f v
add f v = insertInto Add hFalse defaultPrec f v
modify f v = insertInto Modify hFalse defaultPrec f v
modifyIO = modifyIO' hFalse defaultPrec
modifyIO' x = insertInto ModifyIO x
insertInto action hold prec f x = ins' prec hold (m action f x =<<)
-- | Represent setting layouts and layout modifiers
data LayoutHook = LayoutHook
instance Mode ModifyIO LayoutHook (l X.Window -> Config (m X.Window)) l m where
m _ _ l c = do
l' <- l $ X.layoutHook c
return $ c { X.layoutHook = l' }
-- | 'Add' means something else for 'X.layoutHook' because there's no suitable
-- mempty for the general instance of 'X.LayoutClass'
instance (X.LayoutClass l X.Window, X.LayoutClass l' X.Window) =>
Mode Add LayoutHook (l' X.Window) l (X.Choose l' l) where
m _ _ l = \x -> return $ x { X.layoutHook = l X.||| X.layoutHook x }
instance (Read (l X.Window), X.LayoutClass l X.Window,
Read (l' X.Window), X.LayoutClass l' X.Window) =>
Mode Modify LayoutHook (l X.Window -> l' X.Window) l l' where
m _ _ l = \x -> return $ x { X.layoutHook = l (X.layoutHook x) }
instance (X.LayoutClass l' X.Window) =>
Mode Set LayoutHook (l' X.Window) l l' where
m _ _ l = \x -> return $ x { X.layoutHook = l }
data Snd = Snd
instance Apply Snd (a, b) b where
apply _ (_, b) = b
-- | like @foldr (.) id@, but for a heteregenous list.
class HCompose l f | l -> f where
hComp :: l -> f
instance HCompose HNil (a -> a) where
hComp _ = id
instance HCompose r (a -> b) => HCompose ((b -> c) :*: r) (a -> c) where
hComp (HCons g r) = g . hComp r
-- | The difference between HNats. Clamped to HZero
class HSubtract a b c | a b -> c where
hSubtract :: a -> b -> c
instance (HNat a, HNat b, HSubtract a b c) => HSubtract (HSucc a) (HSucc b) c where
hSubtract a b = hSubtract (hPred a) (hPred b)
instance HNat a => HSubtract a HZero a where
hSubtract a _ = a
instance HSubtract HZero b HZero where
hSubtract _ _ = hZero
class HNat n => HReplicateF n e l | n e -> l where
hReplicateF :: n -> e -> l
instance HReplicateF HZero e HNil where
hReplicateF _ _ = HNil
instance (Apply e x y, HReplicateF n e r) => HReplicateF (HSucc n) e ((HFalse, x -> y) :*: r) where
hReplicateF n e = (hFalse, apply e) `HCons` hReplicateF (hPred n) e
-- | exactly like hPred, but accept HZero too
class HPred' n n' | n -> n' where
hPred' :: n -> n'
instance HPred' HZero HZero where
hPred' _ = hZero
instance HNat n => HPred' (HSucc n) n where
hPred' = hPred
insLt n hold f l =
l
`hAppend`
(hReplicateF ({-hPred' $ -} n `hSubtract` hLength l) Id)
`hAppend`
((hold,f) `HCons` HNil)
insGeq n a f l =
let (b,g) = hLookupByHNat n l
h = hCond b (b,g) (a,f . g)
in hUpdateAtHNat n h l
-- | utility class, so that we can use contexts that may not be satisfied,
-- depending on the length of the accumulated list.
class (HBool hold) => Ins2 b n hold f l l' | b n hold f l -> l' where
ins2 :: b -> n -> hold -> f -> l -> l'
-- | when l needs to be padded with id
instance
(-- HPred' a n',
HLength l n,
HSubtract a1 n a,
-- HReplicateF n' Id l',
HReplicateF a Id l',
HAppend l l' l'',
HAppend l'' (HCons (hold,e) HNil) l''1,
HBool hold) =>
Ins2 HTrue a1 hold e l l''1
where ins2 _ = insLt
-- | when l already has enough elements, just compose. Only when the existing HBool is HFalse
instance
(HLookupByHNat n l (t, a -> b),
HUpdateAtHNat n z l l',
HCond t (t, a -> b) (t1, a -> c) z,
HBool t1) =>
Ins2 HFalse n t1 (b -> c) l l'
where ins2 _ = insGeq
class Ins' n hold f l l' | n hold f l -> l' where
ins' :: n -> hold -> f -> l -> l'
instance (HLength l ll, HLt ll n b, Ins2 b n hold f l l') => Ins' n hold f l l' where
ins' = ins2 (undefined :: b)
{- | @ins n f xs@ inserts at index @n@ the function f, or extends the list @xs@
with 'id' if there are too few elements. This way the precedence is not
bounded.
-}
ins n e = ins' n hFalse (e =<<)
runConfig' defConfig x = do
let Config c = hComp (hMap Snd (hComp (hEnd x) HNil)) (return defConfig)
(a,w) <- runWriterT c
print (w [])
return a
--runConfig :: (X.LayoutClass l X.Window, Read (l X.Window)) => Config (X.XConfig l) -> IO ()
runConfig x = X.xmonad =<< runConfig' X.defaultConfig x
-- * Tests
data T1 a = T1 a deriving Show
data T2 a = T2 a deriving Show
data T3 a = T3 a deriving Show
data T3a a = T3a a deriving Show
data RunMWR = RunMWR
instance (Monad m, HCompose l (m () -> Writer w a)) => Apply RunMWR l (a, w) where
apply _ x = runWriter $ hComp x (return ())
data Print = Print
instance Show a => Apply Print a (IO ()) where
apply _ = print
data HHMap a = HHMap a
instance HMap f a b => Apply (HHMap f) a b where
apply (HHMap f) = hMap f
{- | Verification that insertions happen in order
> (T1 (),"3")
> (T2 (T1 ()),"31")
> (T2 (T3 (T1 ())),"321")
> (T2 (T3a (T3 (T1 ()))),"3221")
-}
test :: IO ()
test = sequence_ $ hMapM Print $ hMap RunMWR $ hMap (HHMap Snd) $ hEnd $ hBuild
test1_
test2_
test3_
test3a_
where
test1_ = ins (undefined `asTypeOf` hSucc (hSucc (hSucc hZero))) (\x -> tell "3" >> return (T1 x)) hNil
test2_ = ins (hSucc hZero) (\x -> tell "1" >> return (T2 x)) test1_
test3_ = ins (hSucc (hSucc hZero)) (\x -> tell "2" >> return (T3 x)) test2_
test3a_ = ins (hSucc (hSucc hZero)) (\x -> tell "2" >> return (T3a x)) test3_
{- Generated instances for monomorphic fields in 'X.XConfig'
Follows the style of:
> data FFM = FFM
> instance Mode ModifyIO FFM (Bool -> Config Bool) l l where
> m _ _ f c = do
> r <- f (X.fFM c)
> return $ c { X.fFM = r }
And the same for Modify, Set
> instance (Fail (Expected String)) => Mode ModifyIO FFM y z w where
> instance (Fail (Expected String)) => Mode Modify FFM y z w where
> instance (Fail (Expected String)) => Mode Set FFM y z w where
The last set of overlapping instances exist to help type inference here:
> :t m ModifyIO NormalBorderColor
> m ModifyIO NormalBorderColor
> :: (String -> Config String) -> XConfig x -> Config (XConfig x)
Otherwise it would just give you:
> m ModifyIO NormalBorderColor
> :: Mode ModifyIO NormalBorderColor e x y =>
> e -> XConfig x -> Config (XConfig y)
Which doesn't really matter overall since @x@ ends up fixed when you try
to run the config.
-}
-- | Improve error messages maybe.
data Expected a
$(fmap concat $ sequence
[ do
-- do better by using quoted names in the first place?
let accessor = "X." ++ (case nameBase d of
x:xs -> toLower x:xs
_ -> [])
acc = mkName accessor
VarI _ (ForallT _ _ (_ `AppT` (return -> ty))) _ _ <- reify acc
l <- fmap varT $ newName "l"
let mkId action tyIn body = instanceD
(return [])
[t| $(conT ''Mode) $(conT action) $(conT d) $(tyIn) $l $l |]
[funD 'm
[clause
[wildP,wildP]
(normalB body
)
[]
]
]
`const` (action, tyIn) -- suppress unused var warning
let fallback act = instanceD
(sequence [classP ''Fail [[t| Expected $ty |]]])
[t| $(conT ''Mode) $act $(conT d) $(varT =<< newName "x") $l $l |]
[funD 'm [clause [] (normalB [| error "impossible to satisfy" |]) [] ]]
`const` act -- suppress unused var warning
sequence $
[fallback (conT n) | n <- [''ModifyIO, ''Modify, ''Set] ] ++
[dataD (return []) d [] [normalC d []] []
,mkId ''ModifyIO [t| $ty -> Config $ty |]
[| \f c -> do
r <- f ($(varE acc) c)
return $(recUpdE
[| c |]
[fmap (\r' -> (acc,r')) [| r |]])
|]
,mkId ''Modify [t| $ty -> $ty |]
[| \f c -> do
r <- return $ f ($(varE acc) c)
return $(recUpdE
[| c |]
[fmap (\r' -> (acc,r')) [| r |]])
|]
,mkId ''Set [t| $ty |]
[| \f c -> do
return $(recUpdE
[| c |]
[fmap ((,) acc) [| f |]])
|]
]
| d <- map mkName
-- fields in XConf
-- XXX make these ' versions so we can be hygenic
["NormalBorderColor",
"FocusedBorderColor",
"Terminal",
-- "LayoutHook", -- types $l and $l change with updates
"ManageHook",
"HandleEventHook",
"Workspaces",
"ModMask",
"Keys",
"MouseBindings",
"BorderWidth",
"LogHook",
"StartupHook",
"FocusFollowsMouse"]
]
)
|
LeifW/xmonad-extras
|
XMonad/Config/Alt/Internal.hs
|
Haskell
|
bsd-3-clause
| 12,595
|
module Bead.View.Markdown (
markdownToHtml
, serveMarkdown
) where
{- A markdown to HTML conversion. -}
import Control.Monad.IO.Class
import qualified Data.ByteString.Char8 as BS
import Data.Either
import Data.String
import Data.String.Utils (replace)
import System.Directory
import System.FilePath
import Snap.Core
import Text.Pandoc.Options
import Text.Pandoc.Readers.Markdown (readMarkdown)
import Text.Pandoc.Writers.HTML (writeHtml)
import Text.Blaze.Html5
import Bead.View.BeadContext
import Bead.View.ContentHandler
import Bead.View.I18N
import Bead.View.Pagelets
import Bead.View.Translation
-- Produces an HTML value from the given markdown formatted strings what
-- comes from a text area field, crlf endings must be replaced with lf in the string
markdownToHtml :: String -> Html
markdownToHtml = either (fromString . show) (writeHtml def') . readMarkdown def . replaceCrlf
where def' = def { writerHTMLMathMethod = MathML Nothing }
replaceCrlf :: String -> String
replaceCrlf = replace "\r\n" "\n"
serveMarkdown :: BeadHandler ()
serveMarkdown = do
rq <- getRequest
let path = "markdown" </> (BS.unpack $ rqPathInfo rq)
exists <- liftIO $ doesFileExist path
let render = renderBootstrapPublicPage . publicFrame
if exists
then do
contents <- liftIO $ readFile path
render $ return $ markdownToHtml contents
else do
render $ do
msg <- getI18N
return $ do
p $ fromString . msg $
msg_Markdown_NotFound "Sorry, but the requested page could not be found."
|
pgj/bead
|
src/Bead/View/Markdown.hs
|
Haskell
|
bsd-3-clause
| 1,713
|
{-# LANGUAGE TemplateHaskell #-}
module UnitTest.Util.HogeTest (testSuite) where
import Test.Framework (defaultMain, Test)
import Test.Framework.Providers.QuickCheck2
import Test.Framework.TH
main = defaultMain [testSuite]
testSuite :: Test
testSuite = $(testGroupGenerator)
prop_concat :: [[Int]] -> Bool
prop_concat xs = concat xs == foldr (++) [] xs
|
hyone/haskell-unittest-project-template
|
src/UnitTest/Util/HogeTest.hs
|
Haskell
|
bsd-3-clause
| 360
|
module System.GPIO
-- Re-exported types
( Pin(..)
, fromInt
, ActivePin
, Value(..)
, Direction
-- Exported API
, initReaderPin
, initWriterPin
, readPin
, writePin
, reattachToReaderPin
, reattachToWriterPin
, closePin
) where
import Control.Exception (SomeException (..))
import Control.Monad
import Control.Monad.Catch
import Control.Monad.IO.Class
import Data.Maybe
import Safe
import System.Directory
import System.GPIO.Path
import System.GPIO.Types
data PinException
= InitPinException Pin String
| SetDirectionException Pin Direction String
| ReadPinException Pin String
| WritePinException Pin Value String
| ReattachPinException Pin String
| ClosePinException Pin String
deriving (Show)
instance Exception PinException
initReaderPin :: (MonadCatch m, MonadIO m) => Pin -> m (ActivePin 'In)
initReaderPin = initPin . ReaderPin
initWriterPin :: (MonadCatch m, MonadIO m) => Pin -> m (ActivePin 'Out)
initWriterPin = initPin . WriterPin
initPin :: (MonadCatch m, MonadIO m) => ActivePin a -> m (ActivePin a)
initPin pin = do
withVerboseError (InitPinException (unpin pin)) $
writeFileM exportPath (toData $ unpin pin)
withVerboseError (SetDirectionException (unpin pin) (direction pin)) $
writeFileM (directionPath $ unpin pin) (toData (direction pin))
return pin
readPin :: (MonadCatch m, MonadIO m) => ActivePin a -> m Value
readPin pin = do
x <- readFirstLine $ valuePath (unpin pin)
case fromData x of
Right v -> return v
Left e -> throwM $ ReadPinException (unpin pin) e
writePin :: (MonadCatch m, MonadIO m) => Value -> ActivePin 'Out -> m ()
writePin value pin = withVerboseError (WritePinException (unpin pin) value)
$ writeFileM (valuePath $ unpin pin) (toData value)
-- Get an active pin from a pin, preserving the invariants required when a pin is initialized.
-- Useful for CLI type commands where pointers to an active pin can be lost between calls.
reattachToReaderPin :: (MonadCatch m, MonadIO m) => Pin -> m (ActivePin 'In)
reattachToReaderPin = reattachToPin . ReaderPin
reattachToWriterPin :: (MonadCatch m, MonadIO m) => Pin -> m (ActivePin 'Out)
reattachToWriterPin = reattachToPin . WriterPin
reattachToPin :: (MonadCatch m, MonadIO m) => ActivePin a -> m (ActivePin a)
reattachToPin pin = do
let err = ReattachPinException (unpin pin)
exists <- liftIO $ doesFileExist (directionPath (unpin pin))
unless exists $ throwM (err "Pin was never initialized")
v <- fromData <$> readFirstLine (directionPath (unpin pin))
dir <- either (throwM . err) return v
unless (dir == direction pin) $ throwM (err "Attempting to reattach to pin in wrong direction")
return pin
closePin :: (MonadCatch m, MonadIO m) => ActivePin a -> m ()
closePin pin = withVerboseError (ClosePinException (unpin pin))
$ writeFileM unexportPath (toData $ unpin pin)
withVerboseError :: MonadCatch m => (String -> PinException) -> m () -> m ()
withVerboseError pinException = handle $ \(e :: SomeException) -> throwM $ pinException (show e)
writeFileM :: MonadIO m => FilePath -> String -> m ()
writeFileM fp = liftIO . writeFile fp
readFileM :: MonadIO m => FilePath -> m String
readFileM = liftIO . readFile
readFirstLine :: MonadIO m => FilePath -> m String
readFirstLine = fmap (fromMaybe mempty . headMay . lines) . readFileM
|
TGOlson/gpio
|
lib/System/GPIO.hs
|
Haskell
|
bsd-3-clause
| 3,434
|
module Tests.Development.Cake where
import qualified Tests.Development.Cake.Options
import qualified Tests.Development.Cake.Core.Types
import Test.Framework
tests =
[ testGroup "Tests.Development.Cake.Core.Types"
Tests.Development.Cake.Core.Types.tests
, testGroup "Tests.Development.Cake.Options"
Tests.Development.Cake.Options.tests
]
main = defaultMain tests
|
nominolo/cake
|
unittests/Tests/Development/Cake.hs
|
Haskell
|
bsd-3-clause
| 399
|
module Text.Icalendar (
module Text.Icalendar.Event
, module Text.Icalendar.Types
, events
, parser
) where
import Data.Maybe
import Data.Time
import Text.Parsec
import qualified Text.Parsec.ByteString as PBS
import Text.Icalendar.Event
import Text.Icalendar.Parser
import Text.Icalendar.Token
import Text.Icalendar.Types
import Text.Icalendar.Util
parser :: PBS.Parser Vcalendar
parser = vcalendar <.> many tokenP
events :: Vcalendar -> [Event]
events = map nicerEvent . vcalEvents
nicerEvent :: Component -> Event
nicerEvent evt | isEvent evt = Event {
eventStart = start
, eventEnd = end
, eventSummary = summary
, eventProperties = properties
} where
properties = map prop2tuple $ componentProperties evt
prop2tuple (Property k params v) = (k, (params, v))
start = uncurry parseDateTimeField $ properties <!> "DTSTART"
end = uncurry parseDateTimeField $ properties <!> "DTEND"
summary = snd $ properties <!> "SUMMARY"
nicerEvent c = error $ "Unexpected component type " ++ componentType c
parseDateTimeField :: [(String, String)] -> String -> ZonedTime
parseDateTimeField params s = if isDate then parseDate Nothing s else parseDateTime tz s
where
isDate = Just "DATE" == lookup "VALUE" params
tz | last s == 'Z' = Nothing
| otherwise = Just . zone $ fromMaybe (error $ "Can't determine time zone for " ++ s) $ lookup "TZID" params
zone _ = read "PST" :: TimeZone -- TODO!
(<!>) :: [(String, v)] -> String -> v
l <!> k = fromMaybe (error $ "missing property " ++ k) $ lookup k l
|
samstokes/icalendar-parser
|
Text/Icalendar.hs
|
Haskell
|
bsd-3-clause
| 1,558
|
{-# LANGUAGE OverloadedStrings #-}
module Parse ( train,
test
) where
import DataPath
import qualified Data.ByteString as B
import qualified Data.Attoparsec.ByteString as P
--parsing byte file
read32BitInt :: (Num a) => B.ByteString -> a
read32BitInt b = fromInteger $ sum $ fmap (uncurry (*)) $ zip [2^24,2^16,2^8,1] $ toInteger <$> ub
where ub = B.unpack b
parse32BitInt = read32BitInt <$> (P.take 4)
parseLabels = do magicNumber <- parse32BitInt
numberOfItems <- parse32BitInt
labels' <- B.unpack <$> (P.take numberOfItems)
let labels = toInteger <$> labels'
return ((magicNumber,numberOfItems),labels)
parseRow numberOfCols = B.unpack <$> (P.take numberOfCols)
parseImage numberOfRows numberOfCols = sequence $ take numberOfRows $ repeat $ parseRow numberOfCols
parseImages = do magicNumber <- parse32BitInt
numberOfImages <- parse32BitInt
numberOfRows <- parse32BitInt
numberOfCols <- parse32BitInt
images' <- P.many1 $ parseImage numberOfRows numberOfCols
let images = (fmap . fmap . fmap) toInteger images'
return ((magicNumber,numberOfImages,numberOfRows,numberOfCols),images)
killEither :: Either a b -> b
killEither (Left x) = undefined
killEither (Right x) = x
train' :: IO [(Integer,[[Integer]])]
train' = do labels' <- (P.parseOnly parseLabels) <$> (B.readFile trainLabelPath)
let labels = snd $ killEither labels'
images' <- (P.parseOnly parseImages) <$> (B.readFile trainImagePath)
let images = snd $ killEither images'
return $ zip labels images
test' :: IO [(Integer,[[Integer]])]
test' = do labels' <- (P.parseOnly parseLabels) <$> (B.readFile testLabelPath)
let labels = snd $ killEither labels'
images' <- (P.parseOnly parseImages) <$> (B.readFile testImagePath)
let images = snd $ killEither images'
return $ zip labels images
-- pixels above 100 go to 1
-- pixels below 100 go to 0
threshhold = 127
f x = if x < threshhold then 0 else 1
removeGreyScale (x,y) = (x, (fmap . fmap) f y)
train = (fmap . fmap) removeGreyScale train'
test = (fmap . fmap) removeGreyScale test'
|
danielbarter/personal_website_code
|
blog_notebooks/Niave_Bayes_classification_MNIST/mnistclean/app/Parse.hs
|
Haskell
|
bsd-3-clause
| 2,317
|
{-# LANGUAGE OverloadedStrings #-}
module API.Campbx (
feed
)
where
---------------------------------------------------------------------------------------------------
import Pipes
---------------------------------------------------------------------------------------------------
import qualified Data.ByteString.Char8 as BC
---------------------------------------------------------------------------------------------------
import API.BtcExchanges.Internal
feed :: Producer BC.ByteString IO ()
feed = httpFeed "campbx.com" 443 "/api/xdepth.php" 1
|
RobinKrom/BtcExchanges
|
src/API/Campbx.hs
|
Haskell
|
bsd-3-clause
| 565
|
-- 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.Default
(getDefaultConfig)
where
import Network.IRC.Client.Amphibian.Types
import qualified Network.IRC.Client.Amphibian.Encoding as E
import qualified Data.Text as T
import System.Locale (TimeLocale,
defaultTimeLocale)
import System.IO (FilePath)
import System.Directory (createDirectoryIfMissing,
doesDirectoryExist,
getAppUserDataDirectory)
import System.Environment.XDG.BaseDir (getUserConfigDir, getUserDataDir)
-- | Application name
applicationName :: T.Text
applicationName = "amphibian"
-- | Get default configuration.
getDefaultConfig :: IO Config
getDefaultConfig = do
configDir <- getDirectory getUserConfigDir
dataDir <- getDirectory getUserDataDir
return $ Config { confConfigDir = configDir,
confDataDir = dataDir,
confConfigPluginName = "amphibian.hs",
confPluginError = Right (),
confServerList = [],
confDefaultScriptEntry = "entry",
confScriptCompileOptions = ["-O2"],
confScriptEvalOptions = ["-02"],
confLanguage = "en",
confTimeLocale = defaultTimeLocale,
confLightBackground = False,
confCtcpVersion = "Amphibian 0.1",
confCtcpSource = "http://github.com/tabemann/amphibian",
confDefaultPort = 6667,
confDefaultUserName = "jrandomhacker",
confDefaultName = "J. Random Hacker",
confDefaultAllNicks = ["jrandomhacker"],
confDefaultPassword = Nothing,
confDefaultMode = [],
confDefaultEncoding = E.defaultEncoding,
confDefaultCtcpUserInfo = "I am J. Random Hacker." }
-- | Get directory.
getDirectory :: (String -> IO FilePath) -> IO FilePath
getDirectory query = do
newDir <- query $ T.unpack applicationName
newDirExists <- doesDirectoryExist newDir
if newDirExists
then return newDir
else do
oldDir <- getAppUserDataDirectory $ T.upack applicationName
oldDirExists <- doesDirectoryExist oldDir
if oldDirExists
then return oldDir
else do
createDirectoryIfMissing True newDir
return newDir
|
tabemann/amphibian
|
src_old/Network/IRC/Client/Amphibian/Default.hs
|
Haskell
|
bsd-3-clause
| 3,985
|
-- |
-- Module : Data.CVector.Mutable
-- Copyright : (c) 2012-2013 Michal Terepeta
-- (c) 2009-2010 Roman Leshchinskiy
-- License : BSD-style
--
-- Maintainer : Michal Terepeta <michal.terepeta@gmail.com>
-- Stability : experimental
-- Portability : non-portable
--
-- Wrapper around unboxed mutable 'Vector's implementing efficient 'pushBack' and
-- 'popBack' operations.
--
module Data.CVector.Unboxed.Mutable (
-- * CVector specific
CMVector, MVector(..), IOCVector, STCVector, Unbox,
capacity, fromVector, toVector, pushBack, popBack,
-- * Accessors
-- ** Length information
length, null,
-- ** Extracting subvectors
slice, init, tail, take, drop, splitAt,
unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop,
-- ** Overlapping
overlaps,
-- * Construction
-- ** Initialisation
new, unsafeNew, replicate, replicateM, clone,
-- ** Growing
grow, unsafeGrow,
-- ** Restricting memory usage
clear,
-- FIXME: what's up with those..?
-- * Zipping and unzipping
-- zip, zip3, zip4, zip5, zip6,
-- unzip, unzip3, unzip4, unzip5, unzip6,
-- * Accessing individual elements
read, write, swap,
unsafeRead, unsafeWrite, unsafeSwap,
-- * Modifying vectors
-- ** Filling and copying
set, copy, move, unsafeCopy, unsafeMove
) where
import Data.Vector.Unboxed.Base
import qualified Data.CVector.Generic.Mutable as G
import Control.Monad.Primitive
import Prelude hiding ( length, null, replicate, reverse, map, read,
take, drop, splitAt, init, tail,
zip, zip3, unzip, unzip3 )
import qualified Data.CVector.Generic.MutableInternal as GI
--
-- CVector specific
--
type CMVector = GI.CMVector MVector
type IOCVector = CMVector RealWorld
type STCVector = CMVector
-- | Yields the allocated size of the underlying 'Vector' (not the number of
-- elements kept in the CMVector). /O(1)/
capacity :: (Unbox a) => CMVector s a -> Int
capacity = G.capacity
{-# INLINE capacity #-}
-- | Create a CMVector from MVector. /O(1)/
fromVector :: (Unbox a) => MVector s a -> CMVector s a
fromVector = G.fromVector
{-# INLINE fromVector #-}
-- | Convert the CMVector to MVector (using 'slice'). /O(1)/
toVector :: (Unbox a) => CMVector s a -> MVector s a
toVector = G.toVector
{-# INLINE toVector #-}
-- | Push an element at the back of the CVector. If the size of the CVector and
-- its length are equal (i.e., it's full), the underlying Vector will be doubled
-- in size. Otherwise no allocation will be done and the underlying vector will
-- be shared between the argument and the result. /amortized O(1)/
pushBack :: (Unbox a, PrimMonad m)
=> CMVector (PrimState m) a -> a -> m (CMVector (PrimState m) a)
pushBack = G.pushBack
{-# INLINE pushBack #-}
-- | Remove an element from the back of the CVector. Calls 'error' if the
-- CVector is empty. Does not shrink the underlying Vector. /O(1)/
popBack :: (Unbox a, PrimMonad m) =>
CMVector (PrimState m) a -> m (CMVector (PrimState m) a)
popBack = G.popBack
{-# INLINE popBack #-}
--
-- Length information
--
length :: Unbox a => CMVector s a -> Int
length = G.length
{-# INLINE length #-}
null :: Unbox a => CMVector s a -> Bool
null = G.null
{-# INLINE null #-}
--
-- Extracting subvectors
--
slice :: Unbox a => Int -> Int -> CMVector s a -> CMVector s a
slice = G.slice
{-# INLINE slice #-}
take :: Unbox a => Int -> CMVector s a -> CMVector s a
take = G.take
{-# INLINE take #-}
drop :: Unbox a => Int -> CMVector s a -> CMVector s a
drop = G.drop
{-# INLINE drop #-}
splitAt :: Unbox a => Int -> CMVector s a -> (CMVector s a, CMVector s a)
splitAt = G.splitAt
{-# INLINE splitAt #-}
init :: Unbox a => CMVector s a -> CMVector s a
init = G.init
{-# INLINE init #-}
tail :: Unbox a => CMVector s a -> CMVector s a
tail = G.tail
{-# INLINE tail #-}
unsafeSlice :: (Unbox a) => Int -> Int -> CMVector s a -> CMVector s a
unsafeSlice = G.unsafeSlice
{-# INLINE unsafeSlice #-}
unsafeTake :: Unbox a => Int -> CMVector s a -> CMVector s a
unsafeTake = G.unsafeTake
{-# INLINE unsafeTake #-}
unsafeDrop :: Unbox a => Int -> CMVector s a -> CMVector s a
unsafeDrop = G.unsafeDrop
{-# INLINE unsafeDrop #-}
unsafeInit :: Unbox a => CMVector s a -> CMVector s a
unsafeInit = G.unsafeInit
{-# INLINE unsafeInit #-}
unsafeTail :: Unbox a => CMVector s a -> CMVector s a
unsafeTail = G.unsafeTail
{-# INLINE unsafeTail #-}
--
-- Overlapping
--
overlaps :: Unbox a => CMVector s a -> CMVector s a -> Bool
overlaps = G.overlaps
{-# INLINE overlaps #-}
--
-- Initialisation
--
new :: (PrimMonad m, Unbox a) => Int -> m (CMVector (PrimState m) a)
new = G.new
{-# INLINE new #-}
unsafeNew :: (PrimMonad m, Unbox a) => Int -> m (CMVector (PrimState m) a)
unsafeNew = G.unsafeNew
{-# INLINE unsafeNew #-}
replicate :: (PrimMonad m, Unbox a) => Int -> a -> m (CMVector (PrimState m) a)
replicate = G.replicate
{-# INLINE replicate #-}
replicateM :: (PrimMonad m, Unbox a) => Int -> m a -> m (CMVector (PrimState m) a)
replicateM = G.replicateM
{-# INLINE replicateM #-}
clone :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> m (CMVector (PrimState m) a)
clone = G.clone
{-# INLINE clone #-}
-- Growing
-- -------
grow :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> Int -> m (CMVector (PrimState m) a)
grow = G.grow
{-# INLINE grow #-}
unsafeGrow :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> Int -> m (CMVector (PrimState m) a)
unsafeGrow = G.unsafeGrow
{-# INLINE unsafeGrow #-}
--
-- Restricting memory usage
--
clear :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> m ()
clear = G.clear
{-# INLINE clear #-}
--
-- Accessing individual elements
--
read :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> Int -> m a
read = G.read
{-# INLINE read #-}
write :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> Int -> a -> m ()
write = G.write
{-# INLINE write #-}
swap :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> Int -> Int -> m ()
swap = G.swap
{-# INLINE swap #-}
unsafeRead :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> Int -> m a
unsafeRead = G.unsafeRead
{-# INLINE unsafeRead #-}
unsafeWrite :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> Int -> a -> m ()
unsafeWrite = G.unsafeWrite
{-# INLINE unsafeWrite #-}
unsafeSwap :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> Int -> Int -> m ()
unsafeSwap = G.unsafeSwap
{-# INLINE unsafeSwap #-}
--
-- Filling and copying
--
set :: (PrimMonad m, Unbox a) => CMVector (PrimState m) a -> a -> m ()
set = G.set
{-# INLINE set #-}
copy :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> CMVector (PrimState m) a -> m ()
copy = G.copy
{-# INLINE copy #-}
unsafeCopy :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> CMVector (PrimState m) a -> m ()
unsafeCopy = G.unsafeCopy
{-# INLINE unsafeCopy #-}
move :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> CMVector (PrimState m) a -> m ()
move = G.move
{-# INLINE move #-}
unsafeMove :: (PrimMonad m, Unbox a)
=> CMVector (PrimState m) a -> CMVector (PrimState m) a -> m ()
unsafeMove = G.unsafeMove
{-# INLINE unsafeMove #-}
|
michalt/cvector
|
Data/CVector/Unboxed/Mutable.hs
|
Haskell
|
bsd-3-clause
| 7,195
|
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- | This module provides the abstract domain for primitive values.
module Jat.PState.AbstrDomain
( AbstrDomain (..), mkcon)
where
import Jat.JatM
import Jat.Utils.Pretty
import Jat.Constraints (PATerm, ass)
import Data.Maybe (isJust)
-- | The 'AbstrDomain' class.
class Pretty a => AbstrDomain a b | a -> b where
--join semi lattice
lub :: Monad m => a -> a -> JatM m a
top :: Monad m => JatM m a
isTop :: a -> Bool
leq :: a -> a -> Bool
--abstract domain
atom :: a -> PATerm
constant :: b -> a
fromConstant :: a -> Maybe b
isConstant :: a -> Bool
isConstant = isJust . fromConstant
widening :: Monad m => a -> a -> JatM m a
widening = lub
-- | Assignment constructor.
mkcon :: (AbstrDomain a b, AbstrDomain c d, AbstrDomain e f) =>
a -> (PATerm -> PATerm -> PATerm) -> c -> e -> PATerm
mkcon i f j k = atom i `ass` (atom j `f` atom k)
|
ComputationWithBoundedResources/jat
|
src/Jat/PState/AbstrDomain.hs
|
Haskell
|
bsd-3-clause
| 961
|
module Main where
import qualified Text.Scalar.CLI as CLI
main :: IO ()
main = CLI.main
|
corajr/scalar-convert
|
app/Main.hs
|
Haskell
|
bsd-3-clause
| 90
|
{-# LANGUAGE MultiParamTypeClasses,TemplateHaskell,QuasiQuotes #-}
module Language.XHaskell where
import Data.List (zip4,sort,nub,foldl1)
import qualified Data.Traversable as Trvsbl (mapM)
-- import Data.Generics
import Control.Monad
import qualified Language.Haskell.TH as TH
import Language.Haskell.TH.Quote
import qualified Data.Map as M
import Language.Haskell.Exts.Parser
import Language.Haskell.Exts.Syntax
import Language.Haskell.Exts.Extension
import Language.Haskell.Exts.Pretty
import qualified Language.XHaskell.Source as S
import qualified Language.XHaskell.Target as T
import Language.XHaskell.Error
import Language.XHaskell.Subtype
import Language.XHaskell.Environment ( TyEnv, mkTyEnv, addTyEnv, addRecTyEnv, unionTyEnv,
BdEnv, mkBdEnv,
ClEnv, mkClEnv, mkClTyEnv,
mkDtTyEnv,
InstEnv, mkInstEnv,
Constraint, ConstrEnv, unionConstrEnv, cxtToConstrs, cxtToConstrEnv, addConstrEnv, buildConstrEnv, deducible,
translateKind, translateType, translateContext, translateAsst, translateTyVarBind,
translateName, translateQName, untranslateName,
lookupQName, checkLitTy
)
import Language.XHaskell.LocalTypeInference ( SubtypeConstr, genSubtypeConstrs, solveSubtypeConstrs,
collapseConstrs, findMinSubst
)
-- | main function
xhDecls :: String -> TH.DecsQ
xhDecls s = case parseModuleWithMode S.xhPm s of
{ ParseFailed srcLoc errMsg -> failWithSrcLoc srcLoc $ "Parser failed " ++ errMsg
; ParseOk (Module srcLoc moduleName pragmas mb_warning mb_export import_decs decs) -> do
{ let tySigs = filter S.isTypeSig decs
funBinds = filter S.isFunBind decs
clDecls = filter S.isClassDecl decs
instDecls = filter S.isInstDecl decs
dtDecls = filter S.isDtDecl decs
; tyEnv1 <- mkTyEnv tySigs -- the type environment is using TH.Type
; tyEnv2 <- mkClTyEnv clDecls
; tyEnv3 <- mkDtTyEnv dtDecls
; let tyEnv = tyEnv1 `unionTyEnv` tyEnv2 `unionTyEnv` tyEnv3 -- 2) get the type environment
bdEnv = mkBdEnv funBinds -- 3) build the function name -> def binding environment
clEnv = mkClEnv clDecls -- 4) get the type class environment, name -> vars, functional dep, classFuncDecs
instEnv = mkInstEnv instDecls -- we don't need this -- 5) get the type class instance decls
; decsTH <- translateDecs tyEnv bdEnv clEnv instEnv decs
-- 6) for each type sig \in tyTEnv,
-- a) translate the type signatures to haskell representation
-- b) translate the body decl to haskell representation
; return decsTH }
}
translateDataDecl :: Decl -> TH.Q TH.Dec
translateDataDecl (DataDecl srcLoc DataType context dtName tyVarBinds qualConDecls derivings) = do
{ cxt <- translateContext context
; dtName' <- translateName dtName
; tyVarBinds' <- mapM translateTyVarBind tyVarBinds
; cons <- mapM translateQualConDecl qualConDecls
; names <- mapM translateDeriving derivings
; return $ TH.DataD cxt dtName' tyVarBinds' cons names
}
translateDataDecl (DataDecl srcLoc NewType context dtName tyVarBinds qualConDecls derivings) = do
{ cxt <- translateContext context
; dtName' <- translateName dtName
; tyVarBinds' <- mapM translateTyVarBind tyVarBinds
; con <- translateQualConDecl (head qualConDecls)
; names <- mapM translateDeriving derivings
; return $ TH.NewtypeD cxt dtName' tyVarBinds' con names
}
translateQualConDecl :: QualConDecl -> TH.Q TH.Con
translateQualConDecl (QualConDecl srcLoc [] [] (ConDecl dcName dtypes)) = do
-- NormalC
{ sTys <- mapM translateBangType dtypes
; name' <- translateName dcName
; return (TH.NormalC name' sTys)
}
translateQualConDecl (QualConDecl srcLoc [] [] (RecDecl dcName names_type_pair)) = do
-- RecC
{ varStrictTypes <- mapM (\ (names, dtype) -> do
{ (s,ty) <- translateBangType dtype
; names' <- mapM translateName names
; return (map (\name' -> (name', s, ty)) names')
} ) names_type_pair
; name' <- translateName dcName
; return (TH.RecC name' (concat varStrictTypes))
}
translateQualConDecl (QualConDecl srcLoc [] [] (InfixConDecl dtype1 dcName dtype2)) = do
-- InfixC
{ name' <- translateName dcName
; sty1 <- translateBangType dtype1
; sty2 <- translateBangType dtype2
; return (TH.InfixC sty1 name' sty2)
}
translateQualConDecl (QualConDecl srcLoc tyVarBinds context condecl) = do
{ con <- translateQualConDecl (QualConDecl srcLoc [] [] condecl)
; tyVarBinds' <- mapM translateTyVarBind tyVarBinds
; context' <- translateContext context
; return (TH.ForallC tyVarBinds' context' con)
}
translateBangType :: Type -> TH.Q (TH.Strict, TH.Type)
translateBangType (TyBang BangedTy t) = do
{ t' <- translateType t
; return (TH.IsStrict, T.xhTyToHsTy t')
}
translateBangType (TyBang UnpackedTy t) = do
{ t' <- translateType t
; return (TH.Unpacked, T.xhTyToHsTy t')
}
translateBangType t = do
{ t' <- translateType t
; return (TH.NotStrict, T.xhTyToHsTy t')
}
translateDeriving :: Deriving -> TH.Q TH.Name
translateDeriving (qname, tys) = translateQName qname -- what are the types 'tys'?
-- getting across target and src types
instance Subtype TH.Type Type where
ucast srcLoc t1 t2 = do
{ t2' <- translateType t2
; ucast srcLoc t1 t2'
}
dcast srcLoc t1 t2 = do
{ t2' <- translateType t2
; dcast srcLoc t1 t2'
}
-- | translate XHaskell Decls (in Language.Haskell.Exts.Syntax ) to Template Haskell (in Language.Haskell.TH.Syntax)
translateDecs :: TyEnv -> BdEnv -> ClEnv -> InstEnv -> [Decl] -> TH.Q [TH.Dec]
translateDecs tyEnv bdEnv clEnv instEnv [] = return []
{-
tenv U { (f:t) }, bdEnv, clEnv |- bdEnv(f) : t ~> E
------------------------------------------------------------
tenv, bdEnv, clEnv |- f : t ~> f : [[t]]
f = E
-}
translateDecs tyEnv bdEnv clEnv instEnv ((TypeSig src idents ty):decs) = do
-- The translation is triggered by the type signature (which is compulsory in xhaskell)
-- The function bindings are read off from bdEnv. Those remain in decs will be skipped.
{ qDecs <- mapM (\ident -> translateFunc tyEnv bdEnv clEnv instEnv ident) idents
-- ; TH.runIO (putStrLn (TH.pprint qDecs))
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return ((concat qDecs) ++ qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (dec@(InstDecl src mb_overlap tvbs ctxt name tys instDecl):decs) = do
{ qDec <- translateInst tyEnv clEnv instEnv dec
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return (qDec:qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (dec@(ClassDecl src ctxt name tybnd fds classDecl):decs) = do
{ qDec <- translateClass tyEnv clEnv instEnv dec
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return (qDec:qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (dec@(DataDecl src dataOrNew context dtName tyVarBinds qualConDecls derivings):decs) = do
{ qDec <- translateDataDecl dec
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return (qDec:qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (pBnd@(PatBind src p {- mbTy -} rhs bdDecs):decs) = do
{ qDec <- translatePatBind tyEnv bdEnv clEnv instEnv pBnd
; qDecss <- translateDecs tyEnv bdEnv clEnv instEnv decs
; return (qDec:qDecss)
}
translateDecs tyEnv bdEnv clEnv instEnv (_:decs) = translateDecs tyEnv bdEnv clEnv instEnv decs
translatePatBind :: TyEnv -> BdEnv -> ClEnv -> InstEnv -> Decl -> TH.Q TH.Dec {- removed after HSX 1.16. Question when do we get this on the declaration level???
translatePatBind tyEnv bdEnv clEnv instEnv (PatBind src (PVar ident) (Just ty) (UnGuardedRhs e) bdDecs) = do
{ let cenv = buildConstrEnv clEnv instEnv
; ident' <- translateName ident
; ty' <- translateType ty
; e' <- translateExpC src tyEnv cenv e ty'
; return $ TH.ValD (TH.VarP ident') (TH.NormalB e') []
}
-}
translatePatBind tyEnv bdEnv clEnv instEnv (PatBind src (PVar ident) {- Nothing -} (UnGuardedRhs e) bdDecs) = do
{ let cenv = buildConstrEnv clEnv instEnv
; ident' <- translateName ident
; case M.lookup ident tyEnv of
{ Nothing -> failWithSrcLoc src $ "unable to find type info for variable " ++ TH.pprint ident'
; Just (ty',_) -> do
{ e' <- translateExpC src tyEnv cenv e ty'
; return $ TH.ValD (TH.VarP ident') (TH.NormalB e') []
}
}
}
{-
tenv, bdEnv, clEnv |- class ctxt => C \bar{t} | \bar{fd} where \bar{f:t'} ~>
class ctxt => C \bar{t} | \bar{fd} where \bar{f:[[t']]}
-}
translateClass :: TyEnv -> ClEnv -> InstEnv -> Decl -> TH.Q TH.Dec
translateClass tyEnv clEnv instEnv (ClassDecl src ctxt name tybnds fds classDecls) = do
{ ctxt' <- translateContext ctxt
; name' <- translateName name
; tybnds' <- mapM translateTyVarBind tybnds
; fds' <- mapM translateFunDep fds
; classDecls' <- mapM translateClassDecl classDecls
; return (TH.ClassD ctxt' name' tybnds' fds' (concat classDecls'))
}
{-
clEnv(C) = class C \bar{a} | \bar{fd} where \bar{f:t'}
theta = [\bar{t/a}]
tenv_c = \bar{f:theta(t')}
tenv U tenv_c, bdEnv, clEnv U \theta(ctxt) |- \bar{f = e : \theta(t')} ~> \bar{f = E}
-------------------------------------------------------------------------------------------------
tenv, bdEnv, clEnv |- instance ctxt => C \bar{t} where \bar{f=e} ~> instance ctxt => C \bar{[[t]]} where \bar{f=E}
-}
translateInst :: TyEnv -> ClEnv -> InstEnv -> Decl -> TH.Q TH.Dec
translateInst tyEnv clEnv instEnv (InstDecl src mb_overlap tvbs ctxt (UnQual name) tys instDecls) = do
{ ctxt' <- translateContext ctxt
; name' <- translateName name
; tys' <- mapM translateType tys
-- look for the theta, and the type class function definitions \bar{ f : t'}
; mbSubsts <- case M.lookup name clEnv of
{ Nothing -> {- get from reification -}
do { info <- TH.reify name'
; case info of
{ TH.ClassI (TH.ClassD cxt name tvbs fds decs) classInstances -> do
-- subst from TH.names to TH.types
-- tyEnv from class function name to TH.type
-- for tyEnv, we need to convert TH.name back to name,
-- todo: in future maybe tyenv should map TH.name to TH.type instead of name ot TH.type
{ let vs = map T.getTvFromTvb tvbs
subst = M.fromList (zip vs tys')
extractNameType (TH.SigD n t) = (untranslateName n,t)
tyEnv' = M.fromList (map extractNameType decs)
; return (Just (subst, M.map (T.applySubst subst) tyEnv'))
}
; _ -> return Nothing
}
}
; Just (srcLoc, ctxt, tvbs, fds, classDecls) ->
let varNames = map (\tyVar -> case tyVar of
{ UnkindedVar n -> n
; KindedVar n _ -> n
}) tvbs
in do
{ tyEnv' <- do { ntys <- mapM (\(ClsDecl (TypeSig src idents ty)) -> do
{ ty' <- translateType ty
; return (zip idents (repeat ty'))
}) classDecls
; return (M.fromList (concat ntys))
}
; varNames' <- mapM translateName varNames
; let subst = M.fromList (zip varNames' tys')
; return (Just (subst, M.map (T.applySubst subst) tyEnv'))
}
}
; case mbSubsts of
{ Nothing -> failWithSrcLoc src $ "unable to find the class definition given the instance definition"
; Just (subst, tenv') -> do
{ let tenv'' = M.map (\t -> (t,[])) tenv' -- padding with the empty list of record label names
tyEnv' = tyEnv `unionTyEnv` tenv''
cenv = buildConstrEnv clEnv instEnv
cenv' = cxtToConstrEnv ctxt'
cenv'' = cenv `unionConstrEnv` cenv'
; instDecls' <- mapM (translateInstDecl tyEnv' cenv'' subst tenv'') instDecls
; let htys' = map T.xhTyToHsTy tys'
; let ty' = foldl TH.AppT (TH.ConT name') htys'
; return (TH.InstanceD ctxt' ty' instDecls')
}
}
}
translateInst tyEnv clEnv instEnv (InstDecl src mb_overlap tvbs ctxt qname@(Qual modName name) tys instDecls) = -- since the the modName is qualified, it must be from another module
do
{ ctxt' <- translateContext ctxt
; name' <- translateQName qname
; tys' <- mapM translateType tys
; mbSubsts <- do
{ info <- TH.reify name'
; case info of
{ TH.ClassI (TH.ClassD cxt name tvbs fds decs) classInstances -> do
-- subst from TH.names to TH.types
-- tyEnv from class function name to TH.type
-- for tyEnv, we need to convert TH.name back to name,
-- todo: in future maybe tyenv should map TH.name to TH.type instead of name ot TH.type
{ let vs = map T.getTvFromTvb tvbs
subst = M.fromList (zip vs tys')
extractNameType (TH.SigD n t) = (untranslateName n,t)
tyEnv' = M.fromList (map extractNameType decs)
; return (Just (subst, M.map (T.applySubst subst) tyEnv'))
}
; _ -> return Nothing
}
}
; case mbSubsts of
{ Nothing -> failWithSrcLoc src $ "unable to find the class definition given the instance definition"
; Just (subst, tenv') -> do
{ let tenv'' = M.map (\t -> (t,[])) tenv' -- padding with the empty list of record label names
tyEnv' = tyEnv `unionTyEnv` tenv''
cenv = buildConstrEnv clEnv instEnv
cenv' = cxtToConstrEnv ctxt'
cenv'' = cenv `unionConstrEnv` cenv'
; instDecls' <- mapM (translateInstDecl tyEnv' cenv'' subst tenv'') instDecls
; let ty' = foldl TH.AppT (TH.ConT name') tys'
; return (TH.InstanceD ctxt' ty' instDecls')
}
}
}
-- | translate the instance function declaration
translateInstDecl :: TyEnv -> ConstrEnv -> T.Subst -> TyEnv -> InstDecl -> TH.Q TH.Dec
translateInstDecl tyEnv cenv subst tyEnv' (InsDecl (FunBind matches@((Match srcLoc name _ _ _ _):_))) =
case M.lookup name tyEnv' of
{ Nothing -> failWithSrcLoc srcLoc $ "unable to find type info for instance method"
; Just (ty,_) -> translateBody srcLoc tyEnv cenv name ty matches
}
-- translateBody tyEnv clEnv instEnv name ty matches
translateInstDecl _ _ _ _ _ = fail "associate data type declaration in type class instance is not suppported."
-- | translate a function definition
translateFunc :: TyEnv -> BdEnv -> ClEnv -> InstEnv -> Name -> TH.Q [TH.Dec]
translateFunc tyEnv bdEnv clEnv instEnv name =
case (M.lookup name tyEnv, M.lookup name bdEnv) of
{ (Just (ty,_), Just matches@((Match srcLoc _ _ _ _ _):_)) -> do
{ qTySig <- translateTypeSig name ty
; let cenv = buildConstrEnv clEnv instEnv
; qFunDec <- translateBody srcLoc tyEnv cenv name ty matches
; return [qTySig, qFunDec]
}
; (_, _) -> return []
}
{- not needed
isPolymorphic :: Type -> Bool
isPolymorphic (TyForall _ ctxt t) = isPolymorphic t
isPolymorphic (TyFun t1 t2) = isPolymorphic t1 || isPolymorphic t2
isPolymorphic (TyTuple _ ts) = any isPolymorphic ts
isPolymorphic (TyList t) = isPolymorphic t
isPolymorphic (TyApp t1 t2) = isPolymorphic t1 || isPolymorphic t2
isPolymorphic (TyVar _ ) = True
isPolymorphic (TyCon _ ) = False
isPolymorphic (TyParen t) = isPolymorphic t
isPolymorphic (TyInfix t1 qop t2) = isPolymorphic t1 || isPolymorphic t2
isPolymorphic (TyKind t k) = False
-}
-- | translate a type signature, the XHaskell type will be turned into Haskell type
translateTypeSig :: Name -> TH.Type -> TH.Q TH.Dec
translateTypeSig name ty = do
{ qName <- translateName name
-- ; qType <- translateType ty -- already in TH.Type
; let hsType = T.xhTyToHsTy ty
; return (TH.SigD qName hsType)
{- tvs = nub (sort (T.typeVars hsType))
; if (length tvs == 0)
then return (TH.SigD qName hsType)
else return (TH.SigD qName (TH.ForallT (map (\n -> TH.PlainTV n) tvs) emptyCtxt hsType))
-}
}
where emptyCtxt = []
-- | translate the functional dependency
translateFunDep :: FunDep -> TH.Q TH.FunDep
translateFunDep (FunDep names names') = do
{ names'' <- mapM translateName names
; names''' <- mapM translateName names'
; return (TH.FunDep names'' names''')
}
-- | translate the class function declaration
translateClassDecl :: ClassDecl -> TH.Q [TH.Dec]
translateClassDecl (ClsDecl (TypeSig src idents ty)) = do
{ ty' <- translateType ty
; mapM (\ident -> translateTypeSig ident ty') idents
}
translateClassDecl (ClsDecl decl) | S.isFunBind decl = fail "default function declaration in type class is not supported."
translateClassDecl (ClsDataFam _ _ _ _ _) = fail "associate data type declaration in type class is not suppported."
translateClassDecl (ClsTyFam _ _ _ _) = fail "type family declaration in type class is not suppported."
translateClassDecl (ClsTyDef _ _ _) = fail "associate type synonum declaration in type class is not suppported."
-- | translate a literal from Haskell Source Exts to Template Haskell Representation
translateLit :: Literal -> TH.Q TH.Lit
translateLit (Char c) = return (TH.CharL c)
translateLit (String s) = return (TH.StringL s)
translateLit (Int i) = return (TH.IntegerL i)
translateLit (Frac r) = return (TH.RationalL r)
translateLit (PrimInt i) = return (TH.IntPrimL i)
translateLit (PrimWord w) = return (TH.WordPrimL w)
translateLit (PrimFloat f) = return (TH.FloatPrimL f)
translateLit (PrimDouble d) = return (TH.DoublePrimL d)
translateLit (PrimChar c) = return (TH.CharL c)
translateLit (PrimString s) = return (TH.StringL s)
-- | translate the body of a function definition, which is a list of match-clauses from Haskell Source Exts to Template Haskell Representation
translateBody :: SrcLoc -> TyEnv -> ConstrEnv -> Name -> TH.Type -> [Match] -> TH.Q TH.Dec
translateBody pSrcLoc tenv cenv name ty ms = do
{ e <- desugarMatches pSrcLoc ms
; qe <- translateExpC pSrcLoc tenv cenv e ty
; qName <- translateName name
; return (TH.ValD (TH.VarP qName) (TH.NormalB qe) [{-todo:where clause-}] ) -- f = \x -> ...
}
{- | desugaring the function pattern syntax to the unabridged version
f [p = e] ==> f = \x -> case x of [p -> e]
-}
desugarMatches pSrcLoc ms = do
{ alts <- mapM matchToAlt ms
; let srcLoc = pSrcLoc
e = Lambda srcLoc [PVar (Ident "x")] (Case (Var (UnQual (Ident "x"))) alts)
; return e
}
where matchToAlt (Match srcLoc name [p] mbTy rhs binds) =
return (Alt srcLoc p rhs binds)
{-
where matchToAlt (Match srcLoc name [p] mbTy rhs binds) = do
{ let guardAlt = rhsToGuardAlt rhs
; return (Alt srcLoc p guardAlt binds) }
matchToAlt (Match srcLoc name _ mbTy rhs binds) = failWithSrcLoc srcLoc $ "can't handle multiple patterns binding \"f p1 p2 ... = e\" yet"
rhsToGuardAlt (UnGuardedRhs e) = UnGuardedAlt e
rhsToGuardAlt (GuardedRhss grhss) = GuardedAlts (map gRhsToGAlt grhss)
gRhsToGAlt (GuardedRhs srcLoc stmts e) = GuardedAlt srcLoc stmts e
-}
{-
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| tenv |- e : t ~> E |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-}
{-
getType :: String -> TH.Q TH.Info
getType s = do
{ let n = TH.mkName s
; info <- TH.reify n
; return info -- we will get can't run reify in IO Monad error if we do it in GHCi, we need
-- $(TH.stringE . show =<< TH.reify (TH.mkName "map"))
}
-}
{-
*XHaskell Data.Typeable Language.Haskell.Exts.Pretty Language.Haskell.TH.Ppr> let (ParseOk t) = parseType ("Choice (Star Char) Int")
*XHaskell Data.Typeable Language.Haskell.Exts.Pretty Language.Haskell.TH.Ppr> x <- TH.runQ $ translateType t
*XHaskell Data.Typeable Language.Haskell.Exts.Pretty Language.Haskell.TH.Ppr> toRE x
Choice (Star (L "Char")) (L "Int")
-}
-- | translation of expression from Haskell Source Exts to TH.
-- | semantic subtyping is translated into ucast and regular expression pattern matching is translated into dcast
-- | type checking mode
translateExpC :: SrcLoc -> TyEnv -> ConstrEnv -> Exp -> TH.Type -> (TH.Q TH.Exp)
translateExpC pSrcLoc tenv cenv e@(Var qn) ty = do
{ (ty',_) <- lookupQName qn tenv
; case (T.isMono ty, T.isMono ty') of
{-
x : t' \in tenv
|- t' <= t ~> u
--------------------- (CVarM)
tenv, cenv |-^c x : t ~> u x
-}
{ (True, True) -> -- both are mono types
do
{ uc <- ucast pSrcLoc ty' ty
; qName <- translateQName qn
; return (TH.AppE uc (TH.VarE qName))
}
{-
x : \forall \bar{a}. C' => t' \in tenv
C' == C t' == t note: == modulo \bar{a}
--------------------- (CVarP)
tenv, cenv |-^c x : \forall \bar{a}. C => t ~> x
-}
; (False, False) | T.isomorphic ty ty' -> do
{ qName <- translateQName qn
; return (TH.VarE qName)
}
{- The inferred type is poly, but the incoming type is mono, it is a type application
x : \forall \bar{a}. C' => t' \in tenv
dom(theta) = \bar{a}
theta(t') = t note theta is a just substitution that grounds t' to t
theta(C) \subseteq cenv
--------------------- (CVarA)
tenv, cenv |-^c x : t ~> u x
-}
; (True, False) ->
case ty' of
{ TH.ForallT tvbs cxt ty'' ->
case T.findSubst ty' ty of
{ Just theta -> do
{ let constrs = cxtToConstrs $ T.applySubst theta cxt
; qName <- translateQName qn
; if (deducible constrs cenv)
then return (TH.VarE qName)
else failWithSrcLoc pSrcLoc $ "Unable to deduce " ++ (TH.pprint cxt) ++ " from the context " ++ (show cenv)
}
; Nothing -> failWithSrcLoc pSrcLoc $ "Unable to build substitution of " ++ (prettyPrint e) ++ ":" ++ (TH.pprint ty') ++ " from the type " ++ (TH.pprint ty)
}
}
; _ -> failWithSrcLoc pSrcLoc $ "translation failed. Trying to match expected type " ++ (TH.pprint ty) ++ " with inferred type " ++ (TH.pprint ty')
}
}
translateExpC pSrcLoc tenv cenv e@(Con qn) ty = do
{ (ty',_) <- lookupQName qn tenv
; case (T.isMono ty, T.isMono ty') of
{-
K : \forall a. C' => t' \in tenv
C' == C t' == t
--------------------- (CConP)
tenv, cenv |-^c K : \forall a. C => t ~> x
-}
{ (True, True) -> -- both are mono types
do
{ uc <- ucast pSrcLoc ty' ty
; qName <- translateQName qn
; return (TH.AppE uc (TH.ConE qName))
}
{-
K : t' \in tenv
|- t' <= t ~> u
--------------------- (CConM)
tenv, cenv |-^c K : t ~> u x
-}
; (False, False) | T.isomorphic ty ty' -> do
{ qName <- translateQName qn
; return (TH.ConE qName)
}
{-
K : \forall \bar{a}. C' => t' \in tenv
dom(theta) = \bar{a}
theta(t') = t note theta is a just subsitution that grounds t' to t
theta(C) \subseteq cenv
--------------------- (CConA)
tenv, cenv |-^c K : t ~> x
-}
; (True, False) ->
case ty' of
{ TH.ForallT tvbs cxt ty'' ->
case T.findSubst ty' ty of
{ Just theta -> do
{ let constrs = cxtToConstrs $ T.applySubst theta cxt
; qName <- translateQName qn
; if (deducible constrs cenv)
then return (TH.ConE qName)
else failWithSrcLoc pSrcLoc $ "Unable to deduce " ++ (TH.pprint cxt) ++ " from the context " ++ (show cenv)
}
; Nothing -> failWithSrcLoc pSrcLoc $ "Unable to build substitution of " ++ (prettyPrint e) ++ ":" ++ (TH.pprint ty') ++ " from the type " ++ (TH.pprint ty)
}
}
; _ -> failWithSrcLoc pSrcLoc $ "translation failed. Trying to match expected type " ++ (TH.pprint ty) ++ " with inferred type " ++ (TH.pprint ty')
}
}
{-
|- Lit : t'
t' <= t ~> u
--------------------------- (CLit)
tenv, cenv |-^c Lit : t ~> u Lit
-}
translateExpC pSrcLoc tenv cenv (Lit l) ty = do
{ ql <- translateLit l
; ty' <- checkLitTy l
; uc <- ucast pSrcLoc ty' ty
; return (TH.AppE uc (TH.LitE ql))
}
{-
(op : t1 -> t2 -> t3) \in tenv
tenv, cenv |-^i e1 : t1' ~> E1
tenv, cenv |-^i e2 : t2' ~> E2
|- t1' <= t1 ~> u1
|- t2' <= t2 ~> u2
|- t3 <= t ~> u3
-------------------------------------- (CBinOp)
tenv, cenv |-^c e1 `op` e2 : t ~> u3 ((op (u1 E1)) (u2 E2))
-}
translateExpC pSrcLoc tenv cenv (InfixApp e1 qop e2) ty = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e1
; (e2',t2') <- translateExpI pSrcLoc tenv cenv e2
; (qn, op') <- case qop of
{ QVarOp qn -> do
{ n <- translateQName qn
; return (qn, TH.VarE n)
}
; QConOp qn -> do
{ n <- translateQName qn
; return (qn, TH.ConE n)
}
}
; (ty',_) <- lookupQName qn tenv -- TH type
; case ty' of
{ TH.AppT (TH.AppT TH.ArrowT t1) (TH.AppT (TH.AppT TH.ArrowT t2) t3) -> do
{ u1 <- ucast pSrcLoc t1' t1
; u2 <- ucast pSrcLoc t2' t2
; u3 <- ucast pSrcLoc t3 ty
; return (TH.AppE u3 (TH.AppE (TH.AppE op' (TH.AppE u1 e1')) (TH.AppE u2 e2')))
}
; TH.ForallT tyVarBnds cxt t -> failWithSrcLoc pSrcLoc ((prettyPrint qop) ++ " has the the type " ++ (TH.pprint ty') ++ " is still polymorphic, please give it a type annotation.")
; _ -> failWithSrcLoc pSrcLoc ((prettyPrint qop) ++ ":" ++ (TH.pprint ty') ++ " is not a binary op.")
}
}
{-
f : forall \bar{a}. c => t1' -> ... tn' -> r \in tenv
tenv,cenv |-^i ei : ti ~> Ei
\bar{a} |- ti <: ti' ==> Di
S = solve(D1++ ... ++Dn, r)
|- ti <= S(ti') ~> ui
S(c) \subseteq cenv
S(r) <= t ~> u
----------------------------------------- (CEAppInf)
tenv,cenv |-^c f e1 ... en : t ~>
u (f (u1 E1) ... (un En))
-}
translateExpC pSrcLoc tenv cenv e@(App e1 e2) ty = do
{ mb <- appWithPolyFunc tenv e
; case mb of
{ Just (f, es) -> do
{ (f', tyF) <- translateExpI pSrcLoc tenv cenv f
; e't's <- mapM (translateExpI pSrcLoc tenv cenv) es
; case tyF of
{ TH.ForallT tyVarBnds ctxt t -> do
{ let as = map T.getTvFromTvb tyVarBnds
(ts, r) = T.breakFuncType t (length e't's)
es' = map fst e't's
ts' = map snd e't's
ds = concatMap (\(t,t') -> genSubtypeConstrs as [] t t') (zip ts' ts)
; s <- solveSubtypeConstrs ds r
{- ; TH.runIO ((putStrLn "====") >> putStrLn (prettyPrint e) >> (putStrLn ("s" ++ (show s))))
; TH.runIO (putStrLn ("ts':" ++ (TH.pprint ts')))
; TH.runIO (putStrLn ("t:" ++ (TH.pprint t)))
; TH.runIO (putStrLn ("ds:" ++ (show ds)))
; TH.runIO (putStrLn ("r:" ++ (TH.pprint r))) -}
; if deducible (cxtToConstrs $ T.applySubst s ctxt) cenv
then do
{ -- TH.runIO (putStrLn (TH.pprint (T.applySubst s t)))
; us <- mapM (\(t,t') -> inferThenUpCast pSrcLoc t t' -- t might be still polymorphic
) (zip ts' (map (T.applySubst s) ts))
; let ues = map (\(u,e) -> TH.AppE u e) (zip us es')
; u <- ucast pSrcLoc (T.applySubst s r) ty
; return (TH.AppE u (foldl TH.AppE f' ues))
}
else failWithSrcLoc pSrcLoc $ "Unable to deduce " ++ (TH.pprint (T.applySubst s ctxt)) ++ "from the context " ++ show cenv
}
; _ -> failWithSrcLoc pSrcLoc (TH.pprint tyF ++ " is not polymorphic.")
}
}
; _ -> do
{-
tenv, cenv |-^I e1 : t1 -> t2 ~> E1
tenv, cenv |-^I e2 : t1' ~> E2
|- t1' <= t1 ~> u1
|- t2 <= t ~> u2
------------------------------------- (CEApp)
tenv , cenv |-^c e1 e2 : t ~> u2 (E1 (u1 E2))
-}
{ (e1', t12) <- translateExpI pSrcLoc tenv cenv e1
; case t12 of
{ TH.AppT (TH.AppT TH.ArrowT t1) t2 -> do
{ (e2', t1') <- translateExpI pSrcLoc tenv cenv e2
; u1 <- ucast pSrcLoc t1' t1
; u2 <- ucast pSrcLoc t2 ty
; return (TH.AppE u2 (TH.AppE e1' (TH.AppE u1 e2')))
}
; TH.ForallT tyVarBnds cxt t -> failWithSrcLoc pSrcLoc ((prettyPrint e1) ++ ":" ++ (TH.pprint t12) ++ " is still polymorphic, please give it a type annotation.")
; _ -> failWithSrcLoc pSrcLoc ((prettyPrint e1) ++ ":" ++ (TH.pprint t12) ++ " is not a function.")
}
}
}
}
{-
tenv, cenv |-^c e : t ~> E
----------------------------- (CNeg)
tenv, cenv |-^c -e : t ~> -E
-}
translateExpC pSrcLoc tenv cenv (NegApp e) ty = do
{ e' <- translateExpC pSrcLoc tenv cenv e ty
; return (TH.AppE (TH.VarE (TH.mkName "GHC.Num.negate")) e')
}
{-
tenv U {(x:t1)}, cenv U C |- e : t2 ~> E
--------------------------------------------------------------------(CAbs)
tenv, cenv |-^c \x -> e : \forall \bar{a} C => t1 -> t2 ~> \x -> E
-}
translateExpC pSrcLoc tenv cenv e1@(Lambda srcLoc [PVar x] e) ty =
case ty of
{ TH.AppT (TH.AppT TH.ArrowT t1) t2 -> do
{ let tenv' = addTyEnv x t1 tenv
; e' <- translateExpC srcLoc tenv' cenv e t2
; x' <- translateName x
; return (TH.LamE [TH.VarP x'] e')
}
; TH.ForallT tvbs ctxt (TH.AppT (TH.AppT TH.ArrowT t1) t2) -> do
{ let tenv' = addTyEnv x t1 tenv
cenv' = addConstrEnv ctxt cenv
; e' <- translateExpC srcLoc tenv' cenv' e t2
; x' <- translateName x
; return (TH.LamE [TH.VarP x'] e')
}
; _ -> failWithSrcLoc srcLoc $ ((prettyPrint e1) ++ ":" ++ (TH.pprint ty) ++ " is not a function.")
}
{-
tenv U {(x:t3)}, cenv |- e : t2 ~> E
t1 <= t3 ~> u
-------------------------------------------------------(CAbsVA)
tenv, cenv |-^c \x:t3 -> e : t1 -> t2 ~> (\x -> E) . u
-}
translateExpC pSrcLoc tenv cenv e1@(Lambda srcLoc [(PParen (PatTypeSig srcLoc' (PVar x) t3))] e) ty =
case ty of
{ TH.AppT (TH.AppT TH.ArrowT t1) t2 -> do
{ t3' <- translateType t3
; u <- ucast srcLoc' t1 t3'
; let tenv' = addTyEnv x t3' tenv
; e' <- translateExpC srcLoc tenv' cenv e t2
; x' <- translateName x
; y <- TH.newName "y"
; return (TH.LamE [TH.VarP y] (TH.AppE (TH.LamE [TH.VarP x'] e') (TH.AppE u (TH.VarE y))))
}
; TH.ForallT tvbs ctxt (TH.AppT (TH.AppT TH.ArrowT t1) t2) ->
failWithSrcLoc srcLoc $ ((prettyPrint e1) ++ " has an polymorphic type annotation " ++ (TH.pprint ty))
; _ -> failWithSrcLoc srcLoc $ ((prettyPrint e1) ++ ":" ++ (TH.pprint ty) ++ " is not a function.")
}
{-
tenv, cenv |-^c \x -> case x of p -> e : t1 -> t2 ~> E
---------------------------------------------
tenv, cenv |-^c \p -> e : t1 -> t2 ~> \x -> E
-}
translateExpC pSrcLoc tenv cenv e0@(Lambda srcLoc [p] e) ty =
translateExpC pSrcLoc tenv cenv (Lambda srcLoc [PVar (Ident "x")]
(Case (Var (UnQual (Ident "x"))) [Alt srcLoc p (UnGuardedRhs e) (BDecls [])])) ty
translateExpC pSrcLoc tenv cenv (Lambda srcLoc ps e) ty = failWithSrcLoc srcLoc $ "can't handle multiple patterns lambda yet."
translateExpC pSrcLoc tenv cenv (Let binds e) ty = failWithSrcLoc pSrcLoc $ "can't handle let bindings yet."
{- tenv |-^c e1 : Bool ~> E1
tenv |-^c e2 : t ~> E2
tenv |-^c e3 : t ~> E3
------------------------------------------------------------ (CIf)
tenv |-^c if e1 then e2 else e3 : t ~> if E1 then E2 else E3
-}
translateExpC pSrcLoc tenv cenv (If e1 e2 e3) ty = do
{ e1' <- translateExpC pSrcLoc tenv cenv e1 (TH.ConT (TH.mkName "Bool"))
; e2' <- translateExpC pSrcLoc tenv cenv e2 ty
; e3' <- translateExpC pSrcLoc tenv cenv e3 ty
; return (TH.CondE e1' e2' e3')
}
{- old
tenv |-^I e : t ~> E'
foreach i
stripT p_i = t_i
stripP p_i = p_i'
p_i |- tenv_i
tenv U tenv_i |-^c e_i : t ~> E_i
|- t_i <= t ~> d_i
g_i next = case d_i E of {Just p_i' -> E_i; _ -> next}
--------------------------------------------------- (CCase)
tenv |-^c case e of [p -> e] : t ~>
g_1 (g_2 ... (g_n (error "unexhaustive pattern")))
-}
{-
translateExpC tenv cenv (Case e alts) ty = do
{ pis <- mapM pat alts
; eis <- mapM rhs alts
; pi's <- mapM patStripP pis
; tis <- mapM (patStripT tenv) pis
; tenvis <- mapM patTEnv pis
; (e', t) <- translateExpI tenv cenv e
; dis <- mapM (\ti -> dcast ti t) tis
; gis <- mapM (\(di,pi',ei, tenvi) -> do
{ let tenv' = unionTyEnv tenvi tenv
; ei' <- translateExpC tenv' cenv ei ty
; return (TH.LamE [TH.VarP (TH.mkName "next")]
(TH.CaseE (TH.AppE di e')
[ (TH.Match (TH.ConP (TH.mkName "Just") [pi']) (TH.NormalB ei') [])
, (TH.Match TH.WildP (TH.NormalB (TH.VarE (TH.mkName "next"))) [] )
]))
}) (zip4 dis pi's eis tenvis)
; err <- [|error "Pattern is not exhaustive."|]
; return $ foldl (\e g -> TH.AppE g e) err (reverse gis)
}
where pat :: Alt -> TH.Q Pat
pat (Alt srcLoc p _ _) = return p
rhs :: Alt -> TH.Q Exp
rhs (Alt srcLoc p (UnGuardedAlt e) _) = return e
rhs _ = fail "can't handled guarded pattern."
-}
{- newly extended with nested pattern matching
tenv,cenv |-^I e : t ~> E'
foreach i
stripT p_i = t_i
stripP p_i = p_i'
t_i, p_i |- tenv_i, guard_i, extract_i , p_i'', t_i' -- new extension
tenv U tenv_i, cenv |-^c e_i : t ~> E_i
|- t_i <= t ~> d_i
g_i guard_i extract_i next = case d_i E of {Just x@p_i' | guard_i x -> let p_i'' = extract_i x
in E_i; _ -> next}
--------------------------------------------------- (CCaseNested)
tenv,cenv |-^c case e of [p -> e] : t ~>
g_1 guard_1 extract_1 (g_2 ... (g_n guard_n extract_n (error "unexhaustive pattern")))
-}
translateExpC pSrcLoc tenv cenv (Case e alts) ty = do
{ pis <- mapM pat alts
; eis <- mapM rhs alts
; pi's <- mapM (patStripP pSrcLoc) pis
; tis <- mapM (patStripT pSrcLoc tenv) pis
; tenv_gd_ex_pi''s <- mapM (\(ti,pi) -> patEnv pSrcLoc tenv ti pi) (zip tis pis)
; (e', t) <- translateExpI pSrcLoc tenv cenv e
; dis <- mapM (\ti -> dcast pSrcLoc ti t) tis
; gis <- mapM (\(di,pi',ei, (tenvi,gdi,exti,pi'')) -> do
{ let tenv' = unionTyEnv tenvi tenv
; ei' <- translateExpC pSrcLoc tenv' cenv ei ty
; nn <- TH.newName "x"
; return (TH.LamE [TH.VarP (TH.mkName "next")]
(TH.CaseE (TH.AppE di e')
[ (TH.Match (TH.ConP (TH.mkName "Just") [TH.AsP nn pi']) (TH.GuardedB [ (TH.NormalG (TH.AppE gdi (TH.VarE nn)),
{- ei' -} TH.LetE [TH.ValD pi'' (TH.NormalB (TH.AppE exti (TH.VarE nn))) []] ei')]) [])
, (TH.Match TH.WildP (TH.NormalB (TH.VarE (TH.mkName "next"))) [] )
]))
}) (zip4 dis pi's eis tenv_gd_ex_pi''s)
; err <- [|error "Pattern is not exhaustive."|]
; return $ foldl (\e g -> TH.AppE g e) err (reverse gis)
}
where pat :: Alt -> TH.Q Pat
pat (Alt srcLoc p _ _) = return p
rhs :: Alt -> TH.Q Exp
rhs (Alt srcLoc p (UnGuardedRhs e) _) = return e
rhs (Alt srcLoc p _ _) = failWithSrcLoc srcLoc $ "can't handled guarded pattern."
patToExp :: TH.Pat -> TH.Exp
patToExp (TH.VarP n) = TH.VarE n
patToExp (TH.ConP n ps) = foldl (\e1 e2 -> TH.AppE e1 e2) (TH.ConE n) (map patToExp ps)
patToExp (TH.TupP ps) = TH.TupE (map patToExp ps)
patToExp p = error $ "patToExp failed: unexpected pattern " ++ (TH.pprint p)
{-
tenv, cenv |-^i e1 : t1 ~> E1
tenv, cenv |-^i e2 : t2 ~> E2
(t1,t2) <= t ~> u
--------------------------------------
tenv, cenv |-^c (e1,e2) : t ~> u (E1,E2)
-}
translateExpC pSrcLoc tenv cenv (Tuple boxed []) _ = failWithSrcLoc pSrcLoc ("empty tuple expxpression")
translateExpC pSrcLoc tenv cenv (Tuple boxed [e]) _ = failWithSrcLoc pSrcLoc ("singleton tuple expression")
translateExpC pSrcLoc tenv cenv (Tuple boxed [e1,e2]) t = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e1 -- todo: ensure t, t1' and t2' are monotype
; (e2',t2') <- translateExpI pSrcLoc tenv cenv e2
; u <- ucast pSrcLoc (TH.AppT (TH.AppT (TH.TupleT 2) t1') t2') t
; return (TH.AppE u (TH.TupE [e1',e2']))
}
translateExpC pSrcLoc tenv cenv (Tuple boxed (e:es)) t = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e
; (e2',t2') <- translateExpI pSrcLoc tenv cenv (Tuple boxed es)
; u <- ucast pSrcLoc (TH.AppT (TH.AppT (TH.TupleT 2) t1') t2') t
; return (TH.AppE u (TH.TupE [e1',e2']))
}
{-
tenv, cenv |-^c e : t ~> E
t <= t' ~> u
------------------------------------- (CTApp)
tenv , cenv |-^c (e :: t) : t' ~> u E
-}
translateExpC pSrcLoc tenv cenv e1@(ExpTypeSig srcLoc e t) t' = do
{ t'' <- translateType t
; e' <- translateExpC pSrcLoc tenv cenv e t''
; u <- ucast srcLoc t'' t'
; return (TH.AppE u e')
}
{-
tenv, cenv |-^i e : t' ~> E
for each i
l_i : t' -> t_i \in tenv
tenv, cenv |-^c e_i : t_i ~> E_i
|- t' <= t ~> u
------------------------------------- (CRecUM)
tenv, cenv |-^c e@{[l=e]} : t ~> u e@{[l=E]}
-}
{-
tenv, cenv |-^i e : forall a. t' ~> E
for each i
l_i : forall a. C => t' -> t_i \in tenv
\theta(t') = t \theta is a substitution grounds t' to t
\theta(C) \subseteq cenv
tenv, cenv |-^c e_i : \theta(t_i) ~> E_i
------------------------------------- (CRecUP)
tenv, cenv |-^c e@{[l=e]} : t ~> e@{[l=E]}
-}
translateExpC pSrcLoc tenv cenv (RecUpdate e fieldUpds) t = do -- todo poly version
{ (e',t') <- translateExpI pSrcLoc tenv cenv e
; if T.isMono t'
then do
{ fieldExps' <- mapM (\fu -> translateFieldUpd pSrcLoc tenv cenv fu t) fieldUpds
; u <- ucast pSrcLoc t' t
; return (TH.AppE u (TH.RecUpdE e' fieldExps'))
}
else failWithSrcLoc pSrcLoc $ "Type checker can't to handle polymorphic record exp"
}
{-
tenv, cenv |-^i K : t1 -> ... -> tn -> t' ~> K
for each i
l_i : t' -> t_i \in tenv
tenv, cenv |-^c e_i : t_i ~> E_i
|- t' <= t ~> u
------------------------------------- (CRecKM)
tenv, cenv |-^c e@{[l=e]} : t ~> u e@{[l=E]}
-}
{-
tenv, cenv |-^i e : forall a. t' ~> E
for each i
l_i : forall a. C => t' -> t_i \in tenv
\theta(t') = t \theta is a substitution grounds t' to t
\theta(C) \subseteq cenv
tenv, cenv |-^c e_i : \theta(t_i) ~> E_i
------------------------------------- (CRecKP)
tenv, cenv |-^c e@{[l=e]} : t ~> e@{[l=E]}
-}
translateExpC pSrcLoc tenv cenv (RecConstr n fieldUpds) t = do
-- todo poly version
{ n' <- translateQName n
; (r,ns) <- lookupQName n tenv
-- check the parity and prepare to fill the missing optional filed with ()s
; let missingFieldNames = findMissingFieldNames ns fieldUpds
; missingFieldNameTypeLookups <- mapM (\n -> lookupQName (UnQual n) tenv) missingFieldNames
; let missingFieldNameResultTypes = map (\(t,_) -> T.resultType t) missingFieldNameTypeLookups
; if T.isMono r
then do
{ let t' = T.resultType r
; fieldExps' <- mapM (\fu -> translateFieldUpd pSrcLoc tenv cenv fu t') fieldUpds
; u <- ucast pSrcLoc t' t
-- make sure all the missing names are having optional result type
-- and generate the expression
; missingFExps <- mapM (reconstructMissingFieldUpd pSrcLoc)
(zip missingFieldNames missingFieldNameResultTypes)
; return (TH.AppE u (TH.RecConE n' (fieldExps' ++ missingFExps)))
}
else failWithSrcLoc pSrcLoc "Type checker can't to handle polymorphic record exp"
}
translateExpC pSrcLoc tenv cenv (Paren e) t = translateExpC pSrcLoc tenv cenv e t
translateExpC pSrcLoc tenv cenv e ty = failWithSrcLoc pSrcLoc ("Type checker can't handle expression : " ++ (prettyPrint e))
-- | Inference mode
translateExpI :: SrcLoc -> TyEnv -> ConstrEnv -> Exp -> TH.Q (TH.Exp, TH.Type)
{-
x : \forall \bar{a}. C => t \in tenv
----------------------------------(IVarP)
tenv, cenv |-^i x : \forall \bar{a} . C => t ~> x
x : t \in tenv
-----------------------------------(IVarM)
tenv, cenv |-^i x : t ~> x
-}
translateExpI pSrcLoc tenv cenv (Var qn) = do
{ (ty,_) <- lookupQName qn tenv
; qName <- translateQName qn
; return (TH.VarE qName, ty)
}
{-
K : \forall \bar{a}. C => t \in tenv
----------------------------------(IConP)
tenv, cenv |-^i K : \forall \bar{a} . C => t ~> K
K : t \in tenv
-----------------------------------(IConM)
tenv, cenv |-^i K : t ~> K
-}
translateExpI pSrcLoc tenv cenv (Con qn) = do
{ (ty,_) <- lookupQName qn tenv
; qName <- translateQName qn
; return (TH.ConE qName, ty)
}
{-
|- Lit : t
--------------------------- (ILit)
tenv, cenv |-^c Lit : t ~> Lit
-}
translateExpI pSrcLoc tenv cenv (Lit l) = do
{ ql <- translateLit l
; ty <- checkLitTy l
; return (TH.LitE ql, ty)
}
{-
(op : t1 -> t2 -> t3) \in tenv
tenv,cenv |-^i e1 : t1' ~> E1
tenv,cenv |-^i e2 : t2' ~> E2
|- t1' <= t1 ~> u1
|- t2' <= t2 ~> u2
----------------------------- (IBinOp)
tenv,cenv |-^i e1 `op` e2 : t3 ~> (op (u1 E1)) (u2 E2)
-}
translateExpI pSrcLoc tenv cenv (InfixApp e1 qop e2) = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e1
; (e2',t2') <- translateExpI pSrcLoc tenv cenv e2
; (qn, op') <- case qop of
{ QVarOp qn -> do
{ n <- translateQName qn
; return (qn, TH.VarE n)
}
; QConOp qn -> do
{ n <- translateQName qn
; return (qn, TH.ConE n)
}
}
; (ty',_) <- lookupQName qn tenv -- TH type
; case ty' of
{ TH.AppT (TH.AppT TH.ArrowT t1) (TH.AppT (TH.AppT TH.ArrowT t2) t3) -> do
{ u1 <- ucast pSrcLoc t1' t1
; u2 <- ucast pSrcLoc t2' t2
; return (TH.AppE (TH.AppE op' (TH.AppE u1 e1')) (TH.AppE u2 e2'), t3)
}
; TH.ForallT tyVarBnds cxt t -> failWithSrcLoc pSrcLoc $ ((prettyPrint qop) ++ ":" ++ (TH.pprint ty') ++ " is still polymorphic, please give it a type annotation.")
; _ -> failWithSrcLoc pSrcLoc ((prettyPrint qop) ++ ":" ++ (TH.pprint ty') ++ " is not a binary op")
}
}
{-
f : forall \bar{a}. c => t1' -> ... tn' -> r \in tenv
tenv,cenv |-^i ei : ti ~> Ei
\bar{a} |- ti <: ti' ==> Di
S = solve(D1++ ... ++Dn, r)
|- ti <= S(ti') ~> ui
S(c) \subseteq cenv
----------------------------------------- (IEAppInf)
tenv,cenv |-^i f e1 ... en : S(r) ~>
f (u1 E1) ... (un En)
-}
translateExpI pSrcLoc tenv cenv e@(App e1 e2) = do
{ mb <- appWithPolyFunc tenv e
; case mb of
{ Just (f, es) -> do
{ (f', tyF) <- translateExpI pSrcLoc tenv cenv f
; e't's <- mapM (translateExpI pSrcLoc tenv cenv) es
; case tyF of
{ TH.ForallT tyVarBnds ctxt t -> do
{ let as = map T.getTvFromTvb tyVarBnds
(ts, r) = T.breakFuncType t (length e't's)
es' = map fst e't's
ts' = map snd e't's
ds = concatMap (\(t,t') -> genSubtypeConstrs as [] t t') (zip ts' ts)
; s <- solveSubtypeConstrs ds r
{- ; TH.runIO ((putStrLn "====") >> putStrLn (prettyPrint e) >> (putStrLn ("s" ++ (show s))))
; TH.runIO (putStrLn ("ts':" ++ (TH.pprint ts')))
; TH.runIO (putStrLn ("t:" ++ (TH.pprint t)))
; TH.runIO (putStrLn ("ds:" ++ (show ds)))
; TH.runIO (putStrLn ("r:" ++ (TH.pprint r))) -}
; if deducible (cxtToConstrs $ T.applySubst s ctxt) cenv
then do
{ -- TH.runIO (putStrLn (TH.pprint (T.applySubst s t)))
; us <- mapM (\(t,t') -> inferThenUpCast pSrcLoc t t' -- t might be still polymorphic
) (zip ts' (map (T.applySubst s) ts))
; let ues = map (\(u,e) -> TH.AppE u e) (zip us es')
; return (foldl TH.AppE f' ues, T.applySubst s r)
}
else failWithSrcLoc pSrcLoc $ "Unable to deduce " ++ (TH.pprint (T.applySubst s ctxt)) ++ "from the context " ++ show cenv
}
; _ -> failWithSrcLoc pSrcLoc (TH.pprint tyF ++ " is not polymorphic.")
}
}
; _ -> do
{-
tenv,cenv |-^i e1 : t1 -> t2 ~> E1
tenv,cenv |-^i e2 : t1' ~> E2
|- t1' <= t1 ~> u1
----------------------------------------- (IEApp)
tenv,cenv |-^c e1 e2 : t2 ~> E1 (u1 E2)
-}
-- translateExpI tenv cenv (App e1 e2) = do
{ (e1', t12) <- translateExpI pSrcLoc tenv cenv e1
; case t12 of
{ TH.AppT (TH.AppT TH.ArrowT t1) t2 -> do
{ (e2', t1') <- translateExpI pSrcLoc tenv cenv e2
; u1 <- ucast pSrcLoc t1' t1
; return (TH.AppE e1' (TH.AppE u1 e2'), t2)
}
; TH.ForallT tyVarBnds cxt t -> failWithSrcLoc pSrcLoc ((prettyPrint e1) ++ ":" ++ (TH.pprint t12) ++ " is still polymorphic, please give it a type annotation.")
; _ -> failWithSrcLoc pSrcLoc ((prettyPrint e1) ++ ":" ++ (TH.pprint t12) ++ " is not a function.")
}
}
}
}
{-
tenv |-^i e : t ~> E
-------------------------- (INeg)
tenv |-^i -e : t ~> -E
-}
translateExpI pSrcLoc tenv cenv (NegApp e) = do
{ (e',t) <- translateExpI pSrcLoc tenv cenv e
; return (TH.AppE (TH.VarE (TH.mkName "GHC.Num.negate")) e',t)
}
translateExpI pSrcLoc tenv cenv (Let binds e) = failWithSrcLoc pSrcLoc $ "can't handle let bindings yet."
{- tenv, cenv |-^c e1 : Bool ~> E1
tenv, cenv |-^i e2 : t2 ~> E2
tenv,cenv |-^i e3 : t3 ~> E3
------------------------------------------------------------
tenv, cenv |-^i if e1 then e2 else e3 : (t2|t3) ~> if E1 then E2 else E3
-}
translateExpI pSrcLoc tenv cenv (If e1 e2 e3) = do
{ e1' <- translateExpC pSrcLoc tenv cenv e1 (TH.ConT (TH.mkName "Bool")) -- (TyCon (UnQual (Ident "Bool")))
; (e2',t2) <- translateExpI pSrcLoc tenv cenv e2
; (e3',t3) <- translateExpI pSrcLoc tenv cenv e3
; return (TH.CondE e1' e2' e3', TH.AppT (TH.AppT (TH.ConT (TH.mkName "Choice")) t2) t3)
}
{-
tenv |-^i e1 : t1 ~> E1
tenv |-^i e2 : t2 ~> E2
--------------------------------------
tenv |-^i (e1,e2) : (t1,t2) ~> (E1,E2)
-}
translateExpI pSrcLoc tenv cenv (Tuple boxed []) = failWithSrcLoc pSrcLoc ("empty tuple expxpression")
translateExpI pSrcLoc tenv cenv (Tuple boxed [e]) = failWithSrcLoc pSrcLoc ("singleton tuple expression")
translateExpI pSrcLoc tenv cenv (Tuple boxed [e1,e2]) = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e1
; (e2',t2') <- translateExpI pSrcLoc tenv cenv e2
; let t = TH.AppT (TH.AppT (TH.TupleT 2) t1') t2'
; return (TH.TupE [e1',e2'], t)
}
translateExpI pSrcLoc tenv cenv (Tuple boxed (e:es)) = do
{ (e1',t1') <- translateExpI pSrcLoc tenv cenv e
; (e2',t2') <- translateExpI pSrcLoc tenv cenv (Tuple boxed es)
; let t = TH.AppT (TH.AppT (TH.TupleT 2) t1') t2'
; return (TH.TupE [e1',e2'], t)
}
{-
tenv, cenv |-^c e : t ~> E
------------------------ (ITApp)
tenv, cenv |-^i e :: t : t ~> E
-}
translateExpI pSrcLoc tenv cenv e1@(ExpTypeSig srcLoc e t) = do
{ t' <- translateType t
; e' <- translateExpC pSrcLoc tenv cenv e t'
; return (e', t')
}
{-
tenv U {(x:t1)}, cenv |-^i e : t2 ~> E
-----------------------------------------(IAbsVA)
tenv, cenv |-^i \x::t1 -> e : t1 -> t2 ~> \x -> E
-}
translateExpI pSrcLoc tenv cenv e1@(Lambda srcLoc [(PParen (PatTypeSig srcLoc' (PVar x) t1))] e) = do
{ t1' <- translateType t1
; let tenv' = addTyEnv x t1' tenv
; (e',t2) <- translateExpI srcLoc tenv' cenv e
; x' <- translateName x
; return ((TH.LamE [TH.VarP x'] e'), TH.AppT (TH.AppT TH.ArrowT t1') t2)
}
{-
---------------------------------------------
tenv |-^i \x -> e : ~> error
-}
translateExpI pSrcLoc tenv cenv e1@(Lambda srcLoc _ e) = failWithSrcLoc srcLoc $ "Type inferencer failed: unannotated lambda expression : \n " ++ (prettyPrint e1)
translateExpI pSrcLoc tenv cenv e1@(Case _ _) = failWithSrcLoc pSrcLoc $ "Type inferencer failed: unannotated case expression : \n" ++ (prettyPrint e1)
translateExpI pSrcLoc tenv cenv (Paren e) = translateExpI pSrcLoc tenv cenv e
{-
tenv, cenv |-^i e : t' ~> E
for each i
l_i : t' -> t_i \in tenv
tenv, cenv |-^c e_i : t_i ~> E_i
------------------------------------- (IRecUM)
tenv, cenv |-^i e@{[l=e]} : t' ~> e@{[l=E]}
-}
{-
tenv, cenv |-^i e : forall a. t' ~> E
for each i
l_i : forall a. C => t' -> t_i \in tenv
\theta(t') = t \theta is a substitution grounds t' to t
\theta(C) \subseteq cenv
tenv, cenv |-^c e_i : \theta(t_i) ~> E_i
------------------------------------- (IRecUP)
tenv, cenv |-^i e@{[l=e]} : t ~> e@{[l=E]}
-}
translateExpI pSrcLoc tenv cenv (RecUpdate e fieldUpds) = do
{ (e',t) <- translateExpI pSrcLoc tenv cenv e
; if T.isMono t
then do
{ fieldExps' <- mapM (\fu -> translateFieldUpd pSrcLoc tenv cenv fu t) fieldUpds
; return (TH.RecUpdE e' fieldExps', t)
}
else failWithSrcLoc pSrcLoc $ "Type inferencer can't to handle polymorphic record exp"
}
{-
tenv, cenv |-^i K : t1 -> ... -> tn -> t' ~> K
for each i
l_i : t' -> t_i \in tenv
tenv, cenv |-^c e_i : t_i ~> E_i
------------------------------------- (IRecKM)
tenv, cenv |-^i e@{[l=e]} : t' ~> e@{[l=E]}
-}
{-
tenv, cenv |-^i e : forall a. t' ~> E
for each i
-- we might need to build the theta from the individual e_i
------------------------------------- (IRecKP)
tenv, cenv |-^c e@{[l=e]} : t ~> e@{[l=E]}
-}
translateExpI pSrcLoc tenv cenv (RecConstr n fieldUpds) = do
-- todo polymoprhic
{ n' <- translateQName n
; (r,ns) <- lookupQName n tenv
-- check the parity and prepare to fill the missing optional filed with ()s
; let missingFieldNames = findMissingFieldNames ns fieldUpds
; missingFieldNameTypeLookups <- mapM (\n -> lookupQName (UnQual n) tenv) missingFieldNames
; let missingFieldNameResultTypes = map (\(t,_) -> T.resultType t) missingFieldNameTypeLookups
; if T.isMono r
then do
{ let t' = T.resultType r
; fieldExps' <- mapM (\fu -> translateFieldUpd pSrcLoc tenv cenv fu t') fieldUpds
-- make sure all the missing names are having optional result type
-- and generate the expression
; missingFExps <- mapM (reconstructMissingFieldUpd pSrcLoc)
(zip missingFieldNames missingFieldNameResultTypes)
; return (TH.RecConE n' (fieldExps' ++ missingFExps),t')
}
else failWithSrcLoc pSrcLoc $ "Type inferencer can't unable to handle polymorphic record exp"
}
translateExpI pSrcLoc tenv cenv e = failWithSrcLoc pSrcLoc ("Type inferencer can't handle expression : \n" ++ (prettyPrint e))
-- translate the field update
translateFieldUpd :: SrcLoc -> TyEnv -> ConstrEnv -> FieldUpdate -> TH.Type -> TH.Q TH.FieldExp
translateFieldUpd pSrcLoc tenv cenv (FieldUpdate qname e) t = do
{ (t',_) <- lookupQName qname tenv
; if T.isMono t'
then do
{ let r = T.resultType t'
; e' <- translateExpC pSrcLoc tenv cenv e r
; n' <- translateQName qname
; return (n',e')
}
else failWithSrcLoc pSrcLoc $ "Type inferencer can't handle polymorphic record exp"
}
-- find the missing field names
findMissingFieldNames :: [Name] -> [FieldUpdate] -> [Name]
findMissingFieldNames allNames fieldUpds =
let names = foldl (\names fu -> case fu of
{ FieldUpdate qn _ ->
let n = case qn of {UnQual x-> x; Qual mn x -> x; e -> error (show e)}
in if n `elem` names
then names
else names ++ [n]
; _ -> names }) [] fieldUpds
in filter (\n -> not (n `elem` names)) allNames
-- reconstruct the missing field name expression from ()s
reconstructMissingFieldUpd :: SrcLoc -> (Name, TH.Type) -> TH.Q TH.FieldExp
reconstructMissingFieldUpd pSrcLoc (n,t) = do
{ u <- ucast pSrcLoc (TH.ConT $ TH.mkName "()") t
; n' <- translateName n
; return $ (n', TH.AppE u (TH.ConE $ TH.mkName "()"))
}
-- | extract the type annotations from a pattern
-- | | (x :: t) | = t
-- | | (p1,p2) | = (|p1|, |p2|)
patStripT :: SrcLoc -> TyEnv -> Pat -> TH.Q TH.Type
-- for haskell-src-exts 1.14 +
patStripT pSrcLoc _ (PTuple box []) = failWithSrcLoc pSrcLoc "empty tuple pattern encountered"
patStripT pSrcLoc tenv (PTuple box [p]) = patStripT pSrcLoc tenv p
patStripT pSrcLoc tenv (PTuple box (p:ps)) = do
{ t <- patStripT pSrcLoc tenv p
; ts <- mapM (patStripT pSrcLoc tenv) ps
; return $ foldl (\t1 t2 -> TH.AppT (TH.AppT (TH.TupleT 2) t1) t2) t ts
}
-- for haskell-src-exts < 1.14
{-
patStripT (PTuple []) = fail "empty tuple pattern encountered"
patStripT (PTuple [p]) = patStripT p
patStripT (PTuple (p:ps)) = do
{ t <- patStripT p
; ts <- mapM patStripT ps
; return $ foldl (\t1 t2 -> TH.AppT (TH.AppT (TH.TupleT 2) t1) t2) t ts
}
-}
patStripT pSrcLoc tenv (PatTypeSig srcLoc (PVar n) t) = translateType t
patStripT pSrcLoc tenv (PParen p) = patStripT pSrcLoc tenv p
patStripT pSrcLoc tenv (PApp qname ps) = do
{ ts <- mapM (patStripT pSrcLoc tenv) ps -- todo check ts with the type of qName : t \in tenv
; (ty,_) <- lookupQName qname tenv
; T.lineUpTypes pSrcLoc ty ts
}
patStripT pSrcLoc tenv (PRec qname fps) = do
{ (ty,_) <- lookupQName qname tenv
; return $ T.resultType ty
}
patStripT pSrcLoc _ p = failWithSrcLoc pSrcLoc ("unhandle pattern " ++ (prettyPrint p) ++ (show p))
-- | remove the type annotation from a pattern
-- | { x :: t } = x
-- | { (p1,p2) } = ({p1},{p2})
patStripP :: SrcLoc -> Pat -> TH.Q TH.Pat
patStripP pSrcLoc (PTuple box []) = failWithSrcLoc pSrcLoc "empty tuple pattern encountered"
patStripP pSrcLoc (PTuple box [p]) = patStripP pSrcLoc p
patStripP pSrcLoc (PTuple box (p:ps)) = do
{ q <- patStripP pSrcLoc p
; qs <- mapM (patStripP pSrcLoc) ps
; return $ foldl (\p1 p2 -> TH.TupP [p1, p2]) q qs
}
patStripP pSrcLoc (PatTypeSig srcLoc (PVar n) t) = do
{ n' <- translateName n
; return (TH.VarP n')
}
patStripP pSrcLoc (PParen p) = patStripP pSrcLoc p
patStripP pSrcLoc (PApp qname ps) = do
{ qs <- mapM (patStripP pSrcLoc) ps
; name' <- translateQName qname
; return (TH.ConP name' qs)
}
patStripP pSrcLoc (PRec qname fps) = do
{ name' <- translateQName qname
; fps' <- mapM (\(PFieldPat qname p) -> do
{ p' <- patStripP pSrcLoc p
; name' <- translateQName qname
; return (name', p')
}) fps
; return (TH.RecP name' fps')
}
patStripP pSrcLoc p = failWithSrcLoc pSrcLoc ("unhandle pattern " ++ (prettyPrint p) ++ (show p))
{-
-- | build type environment from a pattern
-- | [ x :: t ] = { (x, t) }
-- | [ (p1,p2) ] = [p1] ++ [p2]
patTEnv :: Pat -> TH.Q TyEnv
patTEnv (PTuple box []) = fail "empty tuple pattern encountered"
patTEnv (PTuple box [p]) = patTEnv p
patTEnv (PTuple box (p:ps)) = do
{ e <- patTEnv p
; es <- mapM patTEnv ps
; return $ foldl unionTyEnv e es
}
patTEnv (PatTypeSig srcLoc (PVar n) t) = do
{ t' <- translateType t
; return (addTyEnv n t' M.empty)
}
patTEnv (PParen p) = patTEnv p
patTEnv (PApp qname ps) = do
{ es <- mapM patTEnv ps
; return $ foldl unionTyEnv M.empty es
}
patTEnv p = fail ("unhandle pattern " ++ (prettyPrint p) ++ (show p))
-}
-------------------------------------------- helper functions for nested pattern matching -------------------------
-- | extended patTEnv
patEnv :: SrcLoc -> TyEnv -> TH.Type -> Pat -> TH.Q (TyEnv, TH.Exp, TH.Exp, TH.Pat) -- the codomain type env is not generated
patEnv pSrcLoc te t (PTuple box []) = failWithSrcLoc pSrcLoc "Pattern Environment construction failed, an empty tuple pattern encountered."
patEnv pSrcLoc te t (PTuple box [p]) = patEnv pSrcLoc te t p
{-
t1,p1 |- tenv1, gd1, ex1, dom1, cod1
t2,p2 |- tenv2, gd2, ex2, dom2, cod2
------------------------------------------------------------------------------
(t1,t2), (p1,p2) |- tenv1 U tenv2, \(x,y) -> (gd1 x && gd2 y), \(x,y) -> (ex1 x, ex2 y), (dom1,dom2), (cod1,cod2)
-}
patEnv pSrcLoc te t (PTuple box (p:ps)) = do
{ let ts = unTupleTy t
; xs <- mapM (\ (t',p) -> patEnv pSrcLoc te t' p) (zip ts (p:ps))
; names' <- T.newNames (length (p:ps)) "x"
; let (tenv, gds, exs, ps') = foldl (\(tenv,gds,exs,qs) (tenv',gd,ex,q) ->
(tenv `unionTyEnv` tenv',
gds ++ [gd],
exs ++ [ex],
qs ++ [q])) (M.empty,[],[],[]) xs
p' = TH.TupP ps'
vps = map TH.VarP names'
ves = map TH.VarE names'
gdes = map (\(gd,ve) -> TH.AppE gd ve) (zip gds ves)
gd = TH.LamE [TH.TupP vps] (TH.AppE (TH.VarE $ TH.mkName "and") (TH.ListE gdes))
exes = map (\(ex,ve) -> TH.AppE ex ve) (zip exs ves)
ex = TH.LamE [TH.TupP vps] (TH.TupE exes)
; return (tenv, gd, ex, p')
}
patEnv pSrcLoc te t (PatTypeSig srcLoc (PVar n) t') = do
{ t'' <- translateType t'
; if (t'' == t)
then do
{- t, (x :: t) |- { (x, t) }, (\x -> True), id, x, t -}
{ let tenv = addTyEnv n t M.empty
gd = TH.LamE [TH.VarP (TH.mkName "x")] (TH.ConE (TH.mkName "True"))
ex = TH.LamE [TH.VarP (TH.mkName "x")] (TH.VarE (TH.mkName "x"))
; n' <- translateName n
; let p' = TH.VarP n'
; return (tenv, gd, ex, p')
}
else do
{-
t' <= t ~> d
-----------------------------------------
t, (x :: t') |- { (x, t') }, isJust . d, fromJust . d , x, t'
-}
{ d <- dcast pSrcLoc t'' t
; let tenv = addTyEnv n t'' M.empty
gd = TH.LamE [TH.VarP (TH.mkName "x")] (TH.AppE (TH.VarE $ TH.mkName "Data.Maybe.isJust") (TH.AppE d (TH.VarE $ TH.mkName "x")))
ex = TH.LamE [TH.VarP (TH.mkName "x")] (TH.AppE (TH.VarE $ TH.mkName "Data.Maybe.fromJust") (TH.AppE d (TH.VarE $ TH.mkName "x")))
; n' <- translateName n
; let p' = TH.VarP n'
; return (tenv, gd, ex, p')
}
}
patEnv pSrcLoc te t (PParen p) = patEnv pSrcLoc te t p
{-
K :: t1 -> ... -> tn -> t
t_i, p_i |- tenv_i, gd_i, ex_i, dom_i, cod_i
------------------------------------------------------------------------------------------------------------------------------------------------
t, K [p] |- U tenv_i, \(K [p']) -> gd_1 p_1' && ... && gd_n p_n', \(K [p']) -> (ex1 p'1, ex2 p_2', ... ), (dom_1,...,dom_n), (cod_1,...,cod_i)
-}
patEnv pSrcLoc te t p@(PApp qname ps) = do
{ (t',_) <- lookupQName qname te
; let ts = T.argsTypes t'
r = T.resultType t'
-- todo check r == t?
; if (length ps == length ts)
then do
{ let tps = zip ts ps
; qname' <- translateQName qname
; xs <- mapM (\(t,p) -> patEnv pSrcLoc te t p) tps
; names' <- T.newNames (length ps) "x"
; let (tenv, gds, exs, ps') = foldl (\(tenv,gds,exs,qs) (tenv',gd,ex,q) ->
(tenv `unionTyEnv` tenv',
gds ++ [gd],
exs ++ [ex],
qs ++ [q])) (M.empty,[],[],[]) xs
p' = TH.TupP ps'
vps = map TH.VarP names'
ves = map TH.VarE names'
gdes = map (\(gd,ve) -> TH.AppE gd ve) (zip gds ves)
gd = TH.LamE [TH.ConP qname' vps] (TH.AppE (TH.VarE $ TH.mkName "and") (TH.ListE gdes))
exes = map (\(ex,ve) -> TH.AppE ex ve) (zip exs ves)
ex = TH.LamE [TH.ConP qname' vps] (TH.TupE exes)
; return (tenv, gd, ex, p')
}
else failWithSrcLoc pSrcLoc ("Fail to construct pattern environment from the pattern " ++ (prettyPrint p) ++ " the number of pattern args is wrong.")
}
{-
l_i :: t -> t_i
t_i, p_i |- tenv_i, gd_i, ex_i, dom_i, cod_i
---------------------------------------
t, K { [l=p] } |- U tenv_i, \x -> gd_1 (l_1 x) && ... && gd_n (l_n x), \x ->(ex1 (l_1 x), ..., (exn (l_n x) )), (dom_1,...,dom_n), (cod_1,...,cod_i)
-}
patEnv pSrcLoc te t p@(PRec qname fps) = do
{ (t', ns) <- lookupQName qname te
; let ts = T.argsTypes t'
r = T.resultType t'
names = map (\(PFieldPat l p) -> l) fps
ps = map (\(PFieldPat l p) -> p) fps
; ats <- mapM (\l -> lookupQName l te) names
; let ts = map (T.resultType . fst) ats
; xs <- mapM (\(t,p) -> patEnv pSrcLoc te t p) (zip ts ps)
; nn <- TH.newName "x"
; names' <- mapM translateQName names
; let (tenv, gds, exs, ps') = foldl (\(tenv, gds, exs, qs) (tenv', gd,ex,q) ->
(tenv `unionTyEnv` tenv',
gds ++ [gd],
exs ++ [ex],
qs ++ [q])) (M.empty,[],[],[]) xs
p' = TH.TupP ps'
gdes = map (\(l,gd) -> TH.AppE gd (TH.AppE (TH.VarE l) (TH.VarE nn))) (zip names' gds)
gd = TH.LamE [TH.VarP nn] (TH.AppE (TH.VarE $ TH.mkName "and") (TH.ListE gdes))
exes = map (\(l,ex) -> TH.AppE ex (TH.AppE (TH.VarE l) (TH.VarE nn))) (zip names' exs)
ex = TH.LamE [TH.VarP nn] (TH.TupE (exes))
; return (tenv, gd, ex, p')
}
patEnv pSrcLoc te t p = failWithSrcLoc pSrcLoc ("Fail to construct pattern environment from the pattern " ++ (prettyPrint p) ++ (show p))
{-
joinAppEWith :: TH.Exp -> TH.Exp -> TH.Exp -> TH.Exp
joinAppEWith e1 e2 e3 =
TH.LamE [TH.TupP [ TH.VarP (TH.mkName "x"), TH.VarP (TH.mkName "y")]] (TH.AppE
(TH.AppE
e1
(TH.AppE e2 (TH.VarE (TH.mkName "x"))))
(TH.AppE e3 (TH.VarE (TH.mkName "y"))))
-}
-- (t1,t2,t3) -> [t1,t2,t3]
unTupleTy :: TH.Type -> [TH.Type]
unTupleTy (TH.AppT (TH.AppT (TH.TupleT 2) t1) t2) =
let ts = unTupleTy t1
in ts ++ [t2]
unTupleTy t = [t]
---------------- helper functions for local type inference ------------------------
-- test whether a application expression is started with an polymoprhic f
-- if so, the f and the args are seperated and returned as a pair
appWithPolyFunc :: TyEnv -> Exp -> TH.Q (Maybe (Exp, [Exp]))
appWithPolyFunc tenv e =
case S.flatten e of
{ l@((Var f):es) -> do
{ (t,_) <- lookupQName f tenv
; if T.isPoly t
then return (Just (Var f, es))
else return Nothing
}
; _ -> return Nothing }
inferThenUpCast :: SrcLoc -> TH.Type -> TH.Type -> TH.Q TH.Exp
inferThenUpCast pSrcLoc (TH.ForallT tvbs ctxt t1) t2 | T.isMono t2 = do -- the arg type can be still poly, we apply local inference again
{ let as = map T.getTvFromTvb tvbs
ts1 = T.argsTypes t1
ts2 = T.argsTypes t2
r1 = T.resultType t1
ds = concatMap (\(t,t') -> genSubtypeConstrs as [] t t') (zip ts1 ts2)
; s <- solveSubtypeConstrs ds r1
; ucast pSrcLoc (T.applySubst s t1) t2
}
inferThenUpCast pSrcLoc t1 t2 = ucast pSrcLoc t1 t2
xh :: QuasiQuoter
xh = QuasiQuoter { quoteExp = undefined, -- not in used
quotePat = undefined, -- not in used
quoteType = undefined, -- not in used
quoteDec = xhDecls
}
{-
import Language.Haskell.TH as TH
$(TH.stringE . show =<< TH.reify (TH.mkName "()"))
parseDeclWithMode pmScopedTyVar "f x = g f x"
-}
|
luzhuomi/xhaskell
|
Language/XHaskell.hs
|
Haskell
|
bsd-3-clause
| 69,224
|
-- | Download and import feeds from various sources.
module HN.Model.Feeds where
import HN.Data
import HN.Monads
import HN.Model.Items
import HN.Types
import HN.Curl
import qualified HN.Model.Mailman (downloadFeed)
import Control.Applicative
import Network.URI
import Snap.App
import Text.Feed.Import
import Text.Feed.Query
import Text.Feed.Types
--------------------------------------------------------------------------------
-- Various service feeds
importHaskellCafe :: Model c s (Either String ())
importHaskellCafe =
importMailman 50
HaskellCafe
"https://mail.haskell.org/pipermail/haskell-cafe/"
(\item -> return (item { niTitle = strip "[Haskell-cafe]" (niTitle item) }))
importLibraries :: Model c s (Either String ())
importLibraries =
importMailman 50
Libraries
"https://mail.haskell.org/pipermail/libraries/"
(\item -> return (item { niTitle = strip "[libraries]" (niTitle item) }))
importGhcDevs :: Model c s (Either String ())
importGhcDevs =
importMailman 50
GhcDevs
"https://mail.haskell.org/pipermail/ghc-devs/"
(\item -> return (item { niTitle = strip "[ghc-devs]" (niTitle item) }))
strip label x | isPrefixOf "re: " (map toLower x) = strip label (drop 4 x)
| isPrefixOf label x = drop (length label) x
| otherwise = x
importPlanetHaskell :: Model c s (Either String ())
importPlanetHaskell =
importGeneric PlanetHaskell "http://planet.haskell.org/rss20.xml"
importJobs :: Model c s (Either String ())
importJobs =
importGeneric Jobs "http://www.haskellers.com/feed/jobs"
importStackOverflow :: Model c s (Either String ())
importStackOverflow = do
importGeneric StackOverflow "http://stackoverflow.com/feeds/tag/haskell"
importGeneric StackOverflow "http://programmers.stackexchange.com/feeds/tag/haskell"
importGeneric StackOverflow "http://codereview.stackexchange.com/feeds/tag/haskell"
importHaskellWiki :: Model c s (Either String ())
importHaskellWiki =
importGeneric HaskellWiki "http://wiki.haskell.org/index.php?title=Special:RecentChanges&feed=atom"
importHackage :: Model c s (Either String ())
importHackage =
importGeneric Hackage "http://hackage.haskell.org/packages/recent.rss"
-- | Import all vimeo content.
importVimeo :: Model c s (Either String ())
importVimeo = do
importGeneric Vimeo "https://vimeo.com/channels/haskell/videos/rss"
importGeneric Vimeo "https://vimeo.com/channels/galois/videos/rss"
importGenerically Vimeo "https://vimeo.com/rickasaurus/videos/rss"
(\ni -> if isInfixOf "haskell" (map toLower (niTitle ni)) then return ni else Nothing)
-- | Import @remember'd IRC quotes from ircbrowse.
importIrcQuotes :: Model c s (Either String ())
importIrcQuotes = do
importGeneric IrcQuotes
"http://ircbrowse.net/quotes.rss"
-- | Import pastes about Haskell.
importPastes :: Model c s (Either String ())
importPastes = do
importGeneric Pastes
"http://lpaste.net/channel/haskell/rss"
--------------------------------------------------------------------------------
-- Reddit
-- | Get /r/haskell.
importRedditHaskell :: Model c s (Either String ())
importRedditHaskell = do
result <- io $ getReddit "haskell"
case result of
Left e -> return (Left e)
Right items -> do
mapM_ (addItem Reddit) items
return (Right ())
-- | Import from proggit.
importProggit :: Model c s (Either String ())
importProggit = do
result <- io $ getReddit "programming"
case result of
Left e -> return (Left e)
Right items -> do
mapM_ (addItem Reddit) (filter (hasHaskell . niTitle) items)
return (Right ())
where hasHaskell = isInfixOf "haskell" . map toLower
-- | Get Reddit feed.
getReddit :: String -> IO (Either String [NewItem])
getReddit subreddit = do
result <- downloadFeed ("https://www.reddit.com/r/" ++ subreddit ++ "/.rss")
case result of
Left e -> return (Left e)
Right e -> return (mapM makeItem (feedItems e))
--------------------------------------------------------------------------------
-- Get feeds
-- | Import from a generic feed source.
importGeneric :: Source -> String -> Model c s (Either String ())
importGeneric source uri = do
importGenerically source uri return
-- | Import from a generic feed source.
importGenerically :: Source -> String -> (NewItem -> Maybe NewItem) -> Model c s (Either String ())
importGenerically source uri f = do
result <- io $ downloadFeed uri
case result >>= mapM (fmap f . makeItem) . feedItems of
Left e -> do
return (Left e)
Right items -> do
mapM_ (addItem source) (catMaybes items)
return (Right ())
importMailman :: Int -> Source -> String -> (NewItem -> Maybe NewItem) -> Model c s (Either String ())
importMailman its source uri f = do
result <- io $ HN.Model.Mailman.downloadFeed its uri
case result >>= mapM (fmap f . makeItem) . feedItems of
Left e -> do
return (Left e)
Right items -> do
mapM_ (addItem source) (catMaybes items)
return (Right ())
-- | Make an item from a feed item.
makeItem :: Item -> Either String NewItem
makeItem item =
NewItem <$> extract "item" (getItemTitle item)
<*> extract "publish date" (join (getItemPublishDate item))
<*> extract "description" (getItemDescription item <|> getItemTitle item)
<*> extract "link" (getItemLink item >>= parseURILeniently)
where extract label = maybe (Left ("Unable to extract " ++ label ++ " for " ++ show item)) Right
-- | Escape any characters not allowed in URIs because at least one
-- feed (I'm looking at you, reddit) do not escape characters like ö.
parseURILeniently :: String -> Maybe URI
parseURILeniently = parseURI . escapeURIString isAllowedInURI
-- | Download and parse a feed.
downloadFeed :: String -> IO (Either String Feed)
downloadFeed uri = do
result <- downloadString uri
case result of
Left e -> return (Left (show e))
Right str -> case parseFeedString str of
Nothing -> do
writeFile "/tmp/feed.xml" str
return (Left ("Unable to parse feed from: " ++ uri))
Just feed -> return (Right feed)
--------------------------------------------------------------------------------
-- Utilities
-- | Parse one of the two dates that might occur out there.
parseDate :: String -> Maybe ZonedTime
parseDate x = parseRFC822 x <|> parseRFC3339 x
-- | Parse an RFC 3339 timestamp.
parseRFC3339 :: String -> Maybe ZonedTime
parseRFC3339 = (parseTimeM True) defaultTimeLocale "%Y-%m-%dT%TZ"
-- | Parse an RFC 822 timestamp.
parseRFC822 :: String -> Maybe ZonedTime
parseRFC822 = (parseTimeM True) defaultTimeLocale rfc822DateFormat
|
jwaldmann/haskellnews
|
src/HN/Model/Feeds.hs
|
Haskell
|
bsd-3-clause
| 6,761
|
{-# LINE 1 "System.Environment.ExecutablePath.hsc" #-}
{-# LANGUAGE Safe #-}
{-# LINE 2 "System.Environment.ExecutablePath.hsc" #-}
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : System.Environment.ExecutablePath
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Function to retrieve the absolute filepath of the current executable.
--
-- @since 4.6.0.0
-----------------------------------------------------------------------------
module System.Environment.ExecutablePath ( getExecutablePath ) where
-- The imports are purposely kept completely disjoint to prevent edits
-- to one OS implementation from breaking another.
{-# LINE 42 "System.Environment.ExecutablePath.hsc" #-}
import Foreign.C
import Foreign.Marshal.Alloc
import Foreign.Ptr
import Foreign.Storable
import System.Posix.Internals
{-# LINE 48 "System.Environment.ExecutablePath.hsc" #-}
-- The exported function is defined outside any if-guard to make sure
-- every OS implements it with the same type.
-- | Returns the absolute pathname of the current executable.
--
-- Note that for scripts and interactive sessions, this is the path to
-- the interpreter (e.g. ghci.)
--
-- @since 4.6.0.0
getExecutablePath :: IO FilePath
--------------------------------------------------------------------------------
-- Mac OS X
{-# LINE 156 "System.Environment.ExecutablePath.hsc" #-}
foreign import ccall unsafe "getFullProgArgv"
c_getFullProgArgv :: Ptr CInt -> Ptr (Ptr CString) -> IO ()
getExecutablePath =
alloca $ \ p_argc ->
alloca $ \ p_argv -> do
c_getFullProgArgv p_argc p_argv
argc <- peek p_argc
if argc > 0
-- If argc > 0 then argv[0] is guaranteed by the standard
-- to be a pointer to a null-terminated string.
then peek p_argv >>= peek >>= peekFilePath
else errorWithoutStackTrace $ "getExecutablePath: " ++ msg
where msg = "no OS specific implementation and program name couldn't be " ++
"found in argv"
--------------------------------------------------------------------------------
{-# LINE 176 "System.Environment.ExecutablePath.hsc" #-}
|
phischu/fragnix
|
builtins/base/System.Environment.ExecutablePath.hs
|
Haskell
|
bsd-3-clause
| 2,382
|
-- | This module provides functionality for retrieving and parsing the
-- quantum random number data from the Australian National University QRN server.
--
-- This module can be used when one only wants to use live data directly from the server,
-- without using any of the data store functionality.
--
-- In most other cases it should be imported via the "Quantum.Random" module.
module Quantum.Random.ANU (
-- ** QRN data retrieval
fetchQR,
fetchQRBits,
) where
import Quantum.Random.Codec
import Quantum.Random.Exceptions
import Data.Word (Word8)
import Data.Bits (testBit)
import Data.ByteString.Lazy (ByteString)
import Network.HTTP.Conduit (simpleHttp)
anuURL :: Int -> String
anuURL n = "https://qrng.anu.edu.au/API/jsonI.php?length=" ++ show n ++ "&type=uint8"
getANU :: Int -> IO ByteString
getANU = simpleHttp . anuURL
fetchQRResponse :: Int -> IO QRResponse
fetchQRResponse n = throwLeft $ parseResponse <$> getANU n
-- | Fetch quantum random data from ANU server as a linked list of bytes via HTTPS. Network
-- problems may result in an `HttpException`. An invalid response triggers a 'QRException'.
fetchQR :: Int -> IO [Word8]
fetchQR n = map fromIntegral . qdata <$> fetchQRResponse n
-- | Fetch QRN data from ANU server as a linked list of booleans via HTTPS. Network
-- problems may result in an `HttpException`. An invalid response triggers a 'QRException'.
fetchQRBits :: Int -> IO [Bool]
fetchQRBits n = concat . map w8bools <$> fetchQR n
-- Converts a byte (Word8) to the corresponding list of 8 boolean values.
-- 'Bits' type class indexes bits from least to most significant, thus the reverse
w8bools :: Word8 -> [Bool]
w8bools w = reverse $ testBit w <$> [0..7]
|
BlackBrane/quantum-random-numbers
|
src-lib/Quantum/Random/ANU.hs
|
Haskell
|
mit
| 1,737
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.