code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
module UI.Command.Command (
Command (..),
defCmd
) where
import Data.Default
import Control.Monad.Trans (liftIO)
import UI.Command.App (App)
------------------------------------------------------------
-- Command class
--
-- | It is often simpler to use the default implementation of Command, and
-- override it with the details you choose to use.
-- For example, an implementation of the ''hello world'' command:
--
-- > world = def {
-- > cmdName = "world",
-- > cmdHandler = worldHandler,
-- > cmdCategory = "Greetings",
-- > cmdShortDesc = "An implementation of the standard software greeting."
-- > }
-- >
-- > worldHandler = liftIO $ putStrLn "Hello world!"
--
data (Default config) => Command config = Command {
-- | Name of the cmdcommand
cmdName :: String,
-- | Handler
cmdHandler :: App config (),
-- | Category in this program's documentation
cmdCategory :: String,
-- | Synopsis
cmdSynopsis :: String,
-- | Short description
cmdShortDesc :: String,
-- | [(example description, args)]
cmdExamples :: [(String, String)]
}
instance (Default config) => Default (App config ()) where
def = liftIO $ putStrLn "Unimplemented command"
instance (Default config) => Default (Command config) where
def = Command "<Anonymous command>" def def def def def
defCmd :: Command ()
defCmd = Command "<Anonymous command>" def def def def def
|
kfish/ui-command
|
UI/Command/Command.hs
|
bsd-3-clause
| 1,509 | 0 | 10 | 332 | 248 | 152 | 96 | 20 | 1 |
#!/usr/local/bin/runhaskell
-----------------------------------------------------------------------------
-- |
-- Program : List Buckets
-- Copyright : (c) Greg Heartsfield 2007
-- License : BSD3
--
-- List all buckets for an S3 account
-- Usage:
-- listBuckets.hs
--
-- This requires the following environment variables to be set with
-- your Amazon keys:
-- AWS_ACCESS_KEY_ID
-- AWS_ACCESS_KEY_SECRET
-----------------------------------------------------------------------------
import Network.AWS.S3Bucket
import Network.AWS.S3Object
import Network.AWS.AWSConnection
import Network.AWS.AWSResult
import System.Environment
import Data.Maybe
main = do mConn <- amazonS3ConnectionFromEnv
let conn = fromJust mConn
res <- listBuckets conn
either print (mapM_ (putStrLn . bucket_name)) res
|
scsibug/hS3
|
examples/listBuckets.hs
|
bsd-3-clause
| 841 | 0 | 11 | 141 | 108 | 64 | 44 | 10 | 1 |
------------------------------------------------------------------------------
--
-- Inductive.hs -- Functional Graph Library
--
-- (c) 1999-2007 by Martin Erwig [see file COPYRIGHT]
--
------------------------------------------------------------------------------
module Data.Graph.Inductive(
module Data.Graph.Inductive.Graph,
module Data.Graph.Inductive.PatriciaTree,
module Data.Graph.Inductive.Basic,
module Data.Graph.Inductive.Monad,
module Data.Graph.Inductive.Monad.IOArray,
module Data.Graph.Inductive.Query,
module Data.Graph.Inductive.NodeMap,
-- * Version Information
version
) where
import Data.Graph.Inductive.Basic
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Monad
import Data.Graph.Inductive.Monad.IOArray
import Data.Graph.Inductive.NodeMap
import Data.Graph.Inductive.PatriciaTree
import Data.Graph.Inductive.Query
import Data.Version (showVersion)
import qualified Paths_fgl as Paths (version)
-- | Version info
version :: IO ()
version = putStrLn $ "\nFGL - Functional Graph Library, version "
++ showVersion Paths.version
|
flowbox-public/fgl
|
Data/Graph/Inductive.hs
|
bsd-3-clause
| 1,139 | 0 | 7 | 165 | 177 | 124 | 53 | 21 | 1 |
module Main (main) where
import GenUtils
import DataTypes
import Parser
import Interp
import PrintTEX
import System.Environment -- 1.3 (partain)
import Data.Char -- 1.3
--fakeArgs = "game001.txt"
--fakeArgs = "pca2.pgn"
--fakeArgs = "silly.pgn"
--fakeArgs = "small.pgn"
--fakeArgs = "sicil.pgn"
--fakeArgs = "badgame.pgn"
--fakeArgs = "mycgames.pgn"
fakeArgs = "rab.pgn"
version = "0.3"
main = do
[test_dir] <- getArgs
let (style,fn,filename) = interpArgs (words "-d tex mygames.pgn")
file <- readFile (test_dir ++ "/" ++filename)
std_in <- getContents
let games = pgnParser fn file -- parse relevant pgn games
putStr (prog style std_in games)
{- OLD 1.2:
main =
getArgs abort $ \ args ->
--let args = (words "-d tex analgames.pgn") in
let (style,fn,filename) = interpArgs args in
readFile filename abort $ \ file ->
readChan stdin abort $ \ std_in ->
let games = pgnParser fn file -- parse relevant pgn games
in
appendChan stdout (prog style std_in games) abort done
-}
interpArgs :: [String] -> (OutputStyle,Int -> Bool,String)
--interpArgs [] = (ViewGame,const True,fakeArgs)
interpArgs [] = interpArgs (words "-d pgn analgames.pgn")
interpArgs files = interpArgs' OutputPGN (const True) files
interpArgs' style fn ("-d":"pgn":xs) = interpArgs' OutputPGN fn xs
interpArgs' style fn ("-d":"rawpgn":xs) = interpArgs' OutputRawPGN fn xs
interpArgs' style fn ("-d":"play":xs) = interpArgs' ViewGame fn xs
interpArgs' style fn ("-d":"parser":xs) = interpArgs' OutputParser fn xs
interpArgs' style fn ("-d":"tex":xs) = interpArgs' OutputTEX fn xs
interpArgs' style fn ("-d":"head":xs) = interpArgs' OutputHeader fn xs
interpArgs' style fn ("-g":range:xs)
= interpArgs' style (changeFn (parse range)) xs
where
changeFn (Digit n:Line:Digit m:r) x = moreChangeFn r x || x >= n && x <= m
changeFn (Line:Digit m:r) x = moreChangeFn r x || x <= m
changeFn (Digit n:Line:r) x = moreChangeFn r x || x >= n
changeFn (Digit n:r) x = moreChangeFn r x || x == n
changeFn _ _ = rangeError
moreChangeFn [] = const False
moreChangeFn (Comma:r) = changeFn r
moreChangeFn _ = rangeError
parse xs@(n:_)
| isDigit n = case span isDigit xs of
(dig,rest) -> Digit (read dig) : parse rest
parse ('-':r) = Line : parse r
parse (',':r) = Comma : parse r
parse [] = []
parse _ = rangeError
rangeError = error ("incorrect -g option (" ++ range ++ ")\n")
interpArgs' style fn [file] = (style,fn,file)
interpArgs' style fn args = error ("bad args: " ++ unwords args)
data Tok
= Digit Int -- n
| Line -- -
| Comma -- ,
data OutputStyle
= OutputPGN -- pgn
| OutputRawPGN -- rawpgn
| OutputHeader -- header
| ViewGame -- play
| ViewGameEmacs -- emacs
| TwoColumn -- 2col
| TestGames -- test
| OutputTEX
| OutputParser -- simply dump out the string read in.
| CmpGen -- cmp 2nd and 3rd generations of output
prog :: OutputStyle -- style of action
-> String -- stdin (for interactive bits)
-> [AbsGame] -- input games
-> String -- result
prog OutputPGN _
= pgnPrinter True -- print out game(s)
. map runInterp -- interpret all games
prog OutputRawPGN _
= pgnPrinter False -- print out game(s)
. map runInterp -- interpret all games
prog OutputHeader _
= pgnHeadPrinter -- print out game(s) headers
. map runInterp -- interpret all games
prog OutputTEX _
= texPrinter -- print out game(s)
. map runInterp -- interpret all games
prog ViewGame std_in
= interactViewer std_in -- print out game(s)
. runInterp -- interpret the game
. head -- should check for only *one* object
prog OutputParser _
= userFormat
type PrintState = (Bool,MoveNumber)
pgnPrinter :: Bool -> [RealGame] -> String
pgnPrinter detail = unlines . concat . map printGame
where
printMoveNumber :: Bool -> MoveNumber -> String
printMoveNumber False (MoveNumber _ Black) = ""
printMoveNumber _ mvnum = userFormat mvnum ++ " "
printQuantums :: PrintState -> [Quantum] -> [String]
printQuantums ps = concat . fst . mapAccumL printQuantum ps
printQuantum :: PrintState -> Quantum -> ([String],PrintState)
printQuantum (pnt,mv) (QuantumMove move ch an brd) =
([printMoveNumber pnt mv ++ move ++ ch],(False,incMove mv))
printQuantum (pnt,mv) (QuantumNAG i) =
if detail
then (["$" ++ show i],(False,mv))
else ([],(False,mv))
printQuantum (pnt,mv) (QuantumComment comms) =
if detail
then ("{" : comms ++ ["}"],(True,mv))
else ([],(False,mv))
printQuantum (pnt,mv) (QuantumAnalysis anal) =
if detail
then ("(" : printQuantums (True,decMove mv) anal ++ [")"],
(True,mv))
else ([],(False,mv))
printQuantum (pnt,mv) (QuantumResult str) = ([str],(True,mv))
printQuantum _ _ = error "PANIC: strange Quantum"
printGame :: RealGame -> [String]
printGame (Game tags qu) =
[ userFormat tag | tag <- tags] ++
formatText 75 (printQuantums (False,initMoveNumber) qu)
printHeadGame :: RealGame -> [String]
printHeadGame (Game tags qu) = [
rjustify 4 gameno ++ " " ++
take 20 (rjustify 20 white) ++ " - " ++
take 20 (ljustify 20 black) ++ " " ++
take 26 (ljustify 28 site) ++ " " ++ result ]
where
(date,site,game_no,res,white,black,opening) = getHeaderInfo tags
gameno = case game_no of
Nothing -> ""
Just n -> show n
result = userFormat res
pgnHeadPrinter :: [RealGame] -> String
pgnHeadPrinter = unlines . concat . map printHeadGame
interactViewer :: String -> RealGame -> String
interactViewer stdin (Game tags qu) = replayQ qu (lines stdin)
replayQ (QuantumMove _ _ _ brd:rest) std_in
= "\027[H" ++ userFormat brd ++ waitQ rest std_in
replayQ (_:rest) std_in = replayQ rest std_in
replayQ [] _ = []
waitQ game std_in = ">>" ++
(case std_in of
[] -> ""
(q:qs) -> replayQ game qs)
|
sdiehl/ghc
|
testsuite/tests/programs/andy_cherry/Main.hs
|
bsd-3-clause
| 6,947 | 0 | 15 | 2,345 | 1,967 | 1,044 | 923 | 136 | 11 |
module LiftToToplevel.Where1 where
import Data.Tree.DUAL.Internal
import Data.Semigroup
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NEL
unpack = undefined
foldDUALNE :: (Semigroup d, Monoid d)
=> (d -> l -> r) -- ^ Process a leaf datum along with the
-- accumulation of @d@ values along the
-- path from the root
-> r -- ^ Replace @LeafU@ nodes
-> (NonEmpty r -> r) -- ^ Combine results at a branch node
-> (d -> r -> r) -- ^ Process an internal d node
-> (a -> r -> r) -- ^ Process an internal datum
-> DUALTreeNE d u a l -> r
foldDUALNE = foldDUALNE' (Option Nothing)
where
foldDUALNE' dacc lf _ _ _ _ (Leaf _ l) = lf (option mempty id dacc) l
foldDUALNE' _ _ lfU _ _ _ (LeafU _) = lfU
foldDUALNE' dacc lf lfU con down ann (Concat ts)
= con (NEL.map (foldDUALNE' dacc lf lfU con down ann . snd . unpack) ts)
foldDUALNE' dacc lf lfU con down ann (Act d t)
= down d (foldDUALNE' (dacc <> (Option (Just d))) lf lfU con down ann . snd . unpack $ t)
foldDUALNE' dacc lf lfU con down ann (Annot a t)
= ann a (foldDUALNE' dacc lf lfU con down ann . snd . unpack $ t)
|
RefactoringTools/HaRe
|
test/testdata/LiftToToplevel/Where1.hs
|
bsd-3-clause
| 1,325 | 0 | 18 | 445 | 439 | 232 | 207 | 22 | 5 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE MagicHash, UnboxedTuples, DeriveDataTypeable #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.Exts
-- Copyright : (c) The University of Glasgow 2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- GHC Extensions: this is the Approved Way to get at GHC-specific extensions.
--
-----------------------------------------------------------------------------
module GHC.Exts
(
-- * Representations of some basic types
Int(..),Word(..),Float(..),Double(..),
Char(..),
Ptr(..), FunPtr(..),
-- * The maximum tuple size
maxTupleSize,
-- * Primitive operations
module GHC.Prim,
shiftL#, shiftRL#, iShiftL#, iShiftRA#, iShiftRL#,
uncheckedShiftL64#, uncheckedShiftRL64#,
uncheckedIShiftL64#, uncheckedIShiftRA64#,
-- * Fusion
build, augment,
-- * Overloaded string literals
IsString(..),
-- * Debugging
breakpoint, breakpointCond,
-- * Ids with special behaviour
lazy, inline,
-- * Transform comprehensions
Down(..), groupWith, sortWith, the,
-- * Event logging
traceEvent,
-- * SpecConstr annotations
SpecConstrAnnotation(..),
-- * The call stack
currentCallStack,
-- * The Constraint kind
Constraint
) where
import Prelude
import GHC.Prim
import GHC.Base
import GHC.Magic
import GHC.Word
import GHC.Int
import GHC.Ptr
import GHC.Stack
import Data.String
import Data.List
import Data.Data
import qualified Debug.Trace
-- XXX This should really be in Data.Tuple, where the definitions are
maxTupleSize :: Int
maxTupleSize = 62
-- | The 'Down' type allows you to reverse sort order conveniently. A value of type
-- @'Down' a@ contains a value of type @a@ (represented as @'Down' a@).
-- If @a@ has an @'Ord'@ instance associated with it then comparing two
-- values thus wrapped will give you the opposite of their normal sort order.
-- This is particularly useful when sorting in generalised list comprehensions,
-- as in: @then sortWith by 'Down' x@
newtype Down a = Down a deriving (Eq)
instance Ord a => Ord (Down a) where
compare (Down x) (Down y) = y `compare` x
-- | 'the' ensures that all the elements of the list are identical
-- and then returns that unique element
the :: Eq a => [a] -> a
the (x:xs)
| all (x ==) xs = x
| otherwise = error "GHC.Exts.the: non-identical elements"
the [] = error "GHC.Exts.the: empty list"
-- | The 'sortWith' function sorts a list of elements using the
-- user supplied function to project something out of each element
sortWith :: Ord b => (a -> b) -> [a] -> [a]
sortWith f = sortBy (\x y -> compare (f x) (f y))
-- | The 'groupWith' function uses the user supplied function which
-- projects an element out of every list element in order to to first sort the
-- input list and then to form groups by equality on these projected elements
{-# INLINE groupWith #-}
groupWith :: Ord b => (a -> b) -> [a] -> [[a]]
groupWith f xs = build (\c n -> groupByFB c n (\x y -> f x == f y) (sortWith f xs))
groupByFB :: ([a] -> lst -> lst) -> lst -> (a -> a -> Bool) -> [a] -> lst
groupByFB c n eq xs0 = groupByFBCore xs0
where groupByFBCore [] = n
groupByFBCore (x:xs) = c (x:ys) (groupByFBCore zs)
where (ys, zs) = span (eq x) xs
-- -----------------------------------------------------------------------------
-- tracing
traceEvent :: String -> IO ()
traceEvent = Debug.Trace.traceEventIO
{-# DEPRECATED traceEvent "Use Debug.Trace.traceEvent or Debug.Trace.traceEventIO" #-}
{- **********************************************************************
* *
* SpecConstr annotation *
* *
********************************************************************** -}
-- Annotating a type with NoSpecConstr will make SpecConstr
-- not specialise for arguments of that type.
-- This data type is defined here, rather than in the SpecConstr module
-- itself, so that importing it doesn't force stupidly linking the
-- entire ghc package at runtime
data SpecConstrAnnotation = NoSpecConstr | ForceSpecConstr
deriving( Data, Typeable, Eq )
|
Kyly/liquidhaskell
|
benchmarks/ghc-7.4.1/Exts.hs
|
bsd-3-clause
| 4,473 | 0 | 12 | 1,038 | 759 | 451 | 308 | 58 | 2 |
module Filters where
import qualified Data.ByteString as B
import Data.Bits
import Data.Word
unhex :: [Word8] -> [Word8]
unhex [] = []
unhex (_:[]) = error "invalid input length"
unhex (x:y:xs) = (shiftL (hex2val x) 4 .|. hex2val y) : unhex xs
where hex2val x' = hex2val' (x' .|. 0x20) -- lowercase char
hex2val' x'
| x' >= 48 && x' < 48 + 10 = 0 + x' - 48 -- 48 is '0' in ascii
| x' >= 97 && x' < 97 + 6 = 10 + x' - 97 -- 97 is 'a' in ascii
| otherwise = error "invalid hex input"
hex2ascii :: B.ByteString -> B.ByteString
hex2ascii x = B.pack $ unhex $ B.unpack x
-- test
--main = do
-- input <- B.getContents
-- B.putStrLn $ hex2ascii input
|
alterapraxisptyltd/serialterm
|
src/filters.hs
|
isc
| 736 | 0 | 13 | 225 | 262 | 137 | 125 | 15 | 1 |
let x h = h == 3
|
chreekat/vim-haskell-syntax
|
test/golden/nested/let-decl-badequals.hs
|
mit
| 19 | 1 | 7 | 7 | 16 | 7 | 9 | -1 | -1 |
module ConnectFour.Protocol where
import qualified ConnectFour.Board as Board
handshake :: [String] -> Bool
handshake s = head s == "hello" && length s == 3
play :: [String] -> Bool
play s = head s == "play" && length s == 1
move :: [String] -> Bool
move s = head s == "move" && length s == 2 && r /= [] && row >= 0 && row < Board.columns where
r = reads (last s) :: [(Int, String)]
row = fst $ head r
chat :: [String] -> Bool
chat s = head s == "chat" && length s >= 2
challenge :: [String] -> Bool
challenge s = head s == "challenge" && length s == 2
acceptChallenge :: [String] -> Bool
acceptChallenge s = head s == "acceptChallenge" && length s == 1
rejectChallenge :: [String] -> Bool
rejectChallenge s = head s == "rejectChallenge" && length s == 1
true :: String
true = "true"
false :: String
false = "false"
ack :: String
ack = "hello"
gameStarted :: String
gameStarted = "makeGame"
moveDone :: String
moveDone = "makeMove"
gameOver :: String
gameOver = "gameOver"
sendPlayers :: String
sendPlayers = "sendPlayers"
sendChat :: String
sendChat = "sendChat"
challenged :: String
challenged = "challenged"
challengeCancelled :: String
challengeCancelled = "challengeCancelled"
reject :: String
reject = "reject"
supported :: String
supported = "110"
boolTrue :: Char
boolTrue = '1'
boolFalse :: Char
boolFalse = '0'
errorNameInUse :: String
errorNameInUse = "error invalidName"
errorUnknownCommand :: String
errorUnknownCommand = "error invalidCommand"
errorInvalidMove :: String
errorInvalidMove = "error invalidMove"
errorInvalidClient :: String
errorInvalidClient = "error invalidClient"
|
tcoenraad/connect-four
|
src/ConnectFour/Protocol.hs
|
mit
| 1,732 | 0 | 14 | 402 | 528 | 287 | 241 | 54 | 1 |
-- Generated by protobuf-simple. DO NOT EDIT!
module Types.Fixed32ListPacked where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype Fixed32ListPacked = Fixed32ListPacked
{ value :: PB.Seq PB.Word32
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default Fixed32ListPacked where
defaultVal = Fixed32ListPacked
{ value = PB.defaultVal
}
instance PB.Mergeable Fixed32ListPacked where
merge a b = Fixed32ListPacked
{ value = PB.merge (value a) (value b)
}
instance PB.Required Fixed32ListPacked where
reqTags _ = PB.fromList []
instance PB.WireMessage Fixed32ListPacked where
fieldToValue (PB.WireTag 1 PB.LenDelim) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getFixed32Packed
fieldToValue (PB.WireTag 1 PB.Bit32) self = (\v -> self{value = PB.append (value self) v}) <$> PB.getFixed32
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putFixed32Packed (PB.WireTag 1 PB.LenDelim) (value self)
|
sru-systems/protobuf-simple
|
test/Types/Fixed32ListPacked.hs
|
mit
| 1,030 | 0 | 13 | 174 | 348 | 186 | 162 | 21 | 0 |
{-# LANGUAGE NamedFieldPuns #-}
module Main (main) where
import Control.Monad.IO.Class (liftIO)
import Control.Monad.SFML (runSFML)
import qualified Control.Monad.SFML.System as S
import qualified Control.Monad.SFML.Graphics as G
import SFML.Graphics (RenderWindow)
import SFML.System.Time (Time, microseconds, asSeconds)
import qualified SFML.Window as W
import Game.Breakout.Behavior (updateWorld)
import Game.Breakout.Types (defaultWorld)
import Game.Breakout.Graphics (renderWorld)
main :: IO ()
main = runSFML $ do
context <- defaultContext
gameloop context defaultWorld
data GameContext = GameContext
{ window :: RenderWindow
, clock :: W.Clock
, delay :: Time
}
defaultContext = do
let settings = Just $ W.ContextSettings 24 8 0 1 2
delay = fps2Micro 60
window <- G.createRenderWindow
(W.VideoMode 640 480 24)
"Breakout"
[W.SFDefaultStyle]
settings
clock <- S.createClock
return $ GameContext {window, clock, delay}
where fps2Micro = microseconds . floor . (* 1000000) . (1 /) . fromIntegral
gameloop context world = unlessClose (window context) $ do
sleepMinDelay (clock context) (delay context)
renderWorld world $ window context
let w' = updateWorld world
gameloop context w'
unlessClose window action = do
event <- G.pollEvent window
case event of
Just W.SFEvtClosed -> return ()
_ -> action
sleepMinDelay clock delay = do
elapsed <- S.restartClock clock
S.sfSleep $ max 0 $ delay - elapsed
S.restartClock clock
return ()
|
j-rock/breakout
|
src/Game/Main.hs
|
mit
| 1,603 | 0 | 12 | 367 | 501 | 265 | 236 | 46 | 2 |
{-# LANGUAGE BangPatterns #-}
module Rx.Observable.Interval where
import Tiempo (TimeInterval)
import Rx.Scheduler (Async, IScheduler, newThread, scheduleTimedRecursiveState)
import Rx.Observable.Types
interval' :: IScheduler scheduler
=> scheduler Async -> TimeInterval -> Observable Async Int
interval' scheduler !intervalDelay =
Observable $ \observer -> do
scheduleTimedRecursiveState
scheduler intervalDelay (0 :: Int) $ \count -> do
onNext observer count
return $ Just (succ count, intervalDelay)
interval :: TimeInterval -> Observable Async Int
interval = interval' newThread
|
roman/Haskell-Reactive-Extensions
|
rx-core/src/Rx/Observable/Interval.hs
|
mit
| 625 | 0 | 16 | 112 | 163 | 86 | 77 | 15 | 1 |
{-# LANGUAGE DeriveFunctor #-}
module Data.Dani.Types (
Symbol(asText)
, symbol
, ValueF(..)
, _Symbol
, _String
, _Number
, _List
, _BoundedInteger
, _RealFloat
, _atomic
) where
import qualified Data.Text as T
import qualified Data.Scientific as N
import Data.String
import Data.Void
import Control.Comonad.Trans.Cofree
import Control.Comonad.Env
import Data.Dani.Lens
newtype Symbol = MakeSymbol { asText :: T.Text } deriving (Show, Eq)
instance IsString Symbol where
fromString = MakeSymbol . T.pack
symbol :: T.Text -> Symbol
symbol = MakeSymbol
data ValueF a = Symbol Symbol
| String T.Text
| Number N.Scientific
| List [a]
deriving (Show,Eq,Functor)
_Symbol :: Prism' (ValueF a) Symbol
_Symbol = prism' Symbol deconstruct
where
deconstruct v = case v of
Symbol s -> Just s
_ -> Nothing
_String :: Prism' (ValueF a) T.Text
_String = prism' String deconstruct
where
deconstruct v = case v of
String s -> Just s
_ -> Nothing
_Number :: Prism' (ValueF a) N.Scientific
_Number = prism' Number deconstruct
where
deconstruct v = case v of
Number s -> Just s
_ -> Nothing
_List :: Prism' (ValueF a) [a]
_List = prism' List deconstruct
where
deconstruct v = case v of
List as -> Just as
_ -> Nothing
_BoundedInteger :: (Integral i, Bounded i) => Prism' N.Scientific i
_BoundedInteger = prism' (\i -> N.scientific (toInteger i) 1) N.toBoundedInteger
_RealFloat :: RealFloat f => Iso' N.Scientific f
_RealFloat = iso N.toRealFloat N.fromFloatDigits
_atomic :: Prism' (ValueF a) (ValueF Void)
_atomic = prism' construct deconstruct
where
deconstruct v = case v of
Symbol s -> Just $ Symbol s
String str -> Just $ String str
Number n -> Just $ Number n
List [] -> Just $ List []
List (_:_) -> Nothing
construct v = fmap absurd v
instance IsString (ValueF a) where
fromString = String . T.pack
|
danidiaz/dani-dn
|
library/Data/Dani/Types.hs
|
mit
| 2,088 | 0 | 12 | 599 | 701 | 369 | 332 | 67 | 5 |
-- Closest and Smallest
-- https://www.codewars.com/kata/5868b2de442e3fb2bb000119
module Codewars.G964.Closest where
import Data.Tuple (swap)
import Data.Char (digitToInt)
import Control.Arrow ((&&&))
import Data.List (unfoldr, sortBy)
import Data.Maybe (listToMaybe)
closest :: String -> ([Int], [Int])
closest = maybe ([], []) h . listToMaybe . sortBy g . concat . unfoldr f . map(\(i, (w, v)) -> (i, w, v)) . zip [0..] . map (weight &&& read) . words
where weight :: String -> Int
weight = sum . map digitToInt
f [] = Nothing
f (x: xs) = Just (map (\s -> (x, s)) xs , xs)
g ((ai, aw, av), (ai', aw', av')) ((bi, bw, bv), (bi', bw', bv')) = compare (abs (aw' - aw), aw+aw' , ai+ai') (abs (bw' - bw), bw+bw' , bi+bi')
h ((ai, aw, av), (bi, bw, bv)) | aw < bw = p
| aw > bw = swap p
| otherwise = if ai <= bi then p else swap p
where p = ([aw, ai, av], [bw, bi, bv])
|
gafiatulin/codewars
|
src/5 kyu/ClosestAndSmallest.hs
|
mit
| 1,048 | 0 | 15 | 345 | 497 | 284 | 213 | 17 | 3 |
-- Problems/Problem092.hs
module Problems.Problem092 (p92) where
import Data.Char
main = print p92
p92 :: Int
p92 = length $ filter (flip elem ds567 . digitSquare) [568..9999999] ++ ds567
where ds567 = filter dsIs89 [1..567]
dsIs89 :: Int -> Bool
dsIs89 1 = False
dsIs89 89 = True
dsIs89 num = dsIs89 $ digitSquare num
digitSquare :: Int -> Int
digitSquare num = foldr (\x r -> r + (digitToInt x)^2) 0 $ show num
|
Sgoettschkes/learning
|
haskell/ProjectEuler/src/Problems/Problem092.hs
|
mit
| 422 | 0 | 12 | 83 | 175 | 92 | 83 | 12 | 1 |
module Demiurge.Worker where
import Antiqua.Common
import qualified Antiqua.Graphics.Tile as Antiqua
import Antiqua.Graphics.Colors
import Antiqua.Graphics.TileRenderer
import Antiqua.Data.Coordinate
import Antiqua.Data.CP437
import Demiurge.Drawing.Renderable
import Demiurge.Common
import qualified Demiurge.Tile as T
import Demiurge.Utils
import qualified Demiurge.Entity as E
data WGoal = Major E.Job Int Goal | Minor Goal
data Task = Drop
| Gather
| Navigate XYZ XYZ
| Path (NonEmpty XYZ)
| Place XYZ
data Goal = Build XYZ
data Reason = Message String | GoalFail String Int deriving Show
data Status = Working | Idle
data Worker k where
Employed :: (k ~ Status)
=> E.Entity
-> WGoal -- | current goal
-> NonEmpty Task -- | current tasks
-> Worker 'Working
Unemployed :: (k ~ Status)
=> E.Entity
-> Reason -- | why unemployed
-> Worker 'Idle
data EWorker = WorkingWorker (Worker 'Working)
| IdleWorker (Worker 'Idle)
data TaskPermission = TaskPermitted
| TaskBlocked EWorker
| TaskForbidden Reason
pack :: Worker t -> EWorker
pack e@(Employed _ _ _) = WorkingWorker e
pack u@(Unemployed _ _) = IdleWorker u
getTask :: Worker 'Working -> Task
getTask (Employed _ _ tsk) = headOf tsk
mapTask :: (Task -> Task) -> Worker 'Working -> Worker 'Working
mapTask f (Employed e gol tsk) = Employed e gol (mapHead f tsk)
getEntity :: EWorker -> E.Entity
getEntity (WorkingWorker (Employed e _ _)) = e
getEntity (IdleWorker (Unemployed e _)) = e
getResource :: EWorker -> Maybe T.Resource
getResource = E.getResource . getEntity
mapResource :: (T.Resource -> Maybe T.Resource) -> Worker t -> Worker t
mapResource f (Employed e gol tsks) =
Employed (E.mapResource e f) gol tsks
mapResource f (Unemployed e rsn) =
Unemployed (E.mapResource e f) rsn
spendResource :: Worker t -> Worker t
spendResource = mapResource (\_ -> Nothing)
giveResource :: T.Resource -> Worker t -> Worker t
giveResource r = mapResource (\_ -> Just r)
getPos :: EWorker -> XYZ
getPos (WorkingWorker (Employed e _ _)) = E.getPos e
getPos (IdleWorker (Unemployed e _)) = E.getPos e
setPos :: XYZ -> Worker t -> Worker t
setPos xyz (Employed e gol tsk) = Employed ((E.setPos xyz) e) gol tsk
setPos xyz (Unemployed e rsn) = Unemployed ((E.setPos xyz) e) rsn
jobToColor :: Status -> Color
jobToColor Working = yellow
jobToColor Idle = white
workerToTile :: E.Job -> Status -> Antiqua.Tile CP437
workerToTile j st =
let code =
case j of
E.Builder -> C'B
E.Gatherer -> C'G
E.Miner -> C'M
in
Antiqua.Tile code black $ jobToColor st
instance Renderable EWorker where
render (WorkingWorker (Employed (E.Entity _ pos job _) _ _)) tr =
let t1 = (fstsnd pos, workerToTile job Working) in
tr <+ t1
render (IdleWorker (Unemployed (E.Entity _ pos job _) _)) tr =
let t1 = (fstsnd pos, workerToTile job Idle) in
let t2 = (fstsnd $ pos ~~> D'North, Antiqua.Tile (:?) black white) in
tr <++ [t1, t2]
|
olive/demiurge
|
src/Demiurge/Worker.hs
|
mit
| 3,212 | 0 | 14 | 836 | 1,164 | 605 | 559 | -1 | -1 |
{-# LANGUAGE FlexibleInstances #-}
import Text.PrettyPrint
import Text.Show.Pretty (ppShow)
parensIf :: Bool -> Doc -> Doc
parensIf True = parens
parensIf False = id
type Name = String
data Expr
= Var String
| Lit Ground
| App Expr Expr
| Lam Name Expr
deriving (Eq, Show)
data Ground
= LInt Int
| LBool Bool
deriving (Show, Eq, Ord)
class Pretty p where
ppr :: Int -> p -> Doc
instance Pretty String where
ppr _ x = text x
instance Pretty Expr where
ppr _ (Var x) = text x
ppr _ (Lit (LInt a)) = text (show a)
ppr _ (Lit (LBool b)) = text (show b)
ppr p e@(App _ _) =
let (f, xs) = viewApp e in
let args = sep $ map (ppr (p+1)) xs in
parensIf (p>0) $ ppr p f <+> args
ppr p e@(Lam _ _) =
let body = ppr (p+1) (viewBody e) in
let vars = map (ppr 0) (viewVars e) in
parensIf (p>0) $ char '\\' <> hsep vars <+> text "." <+> body
viewVars :: Expr -> [Name]
viewVars (Lam n a) = n : viewVars a
viewVars _ = []
viewBody :: Expr -> Expr
viewBody (Lam _ a) = viewBody a
viewBody x = x
viewApp :: Expr -> (Expr, [Expr])
viewApp (App e1 e2) = go e1 [e2]
where
go (App a b) xs = go a (b : xs)
go f xs = (f, xs)
ppexpr :: Expr -> String
ppexpr = render . ppr 0
s, k, example :: Expr
s = Lam "f" (Lam "g" (Lam "x" (App (Var "f") (App (Var "g") (Var "x")))))
k = Lam "x" (Lam "y" (Var "x"))
example = App s k
main :: IO ()
main = do
putStrLn $ ppexpr s
putStrLn $ ppShow example
|
riwsky/wiwinwlh
|
src/pretty.hs
|
mit
| 1,462 | 11 | 17 | 398 | 819 | 404 | 415 | 53 | 2 |
{-# LANGUAGE DeriveDataTypeable,
FlexibleInstances,
GeneralizedNewtypeDeriving,
OverlappingInstances,
UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module App.Entity where
import Control.Applicative
import Data.Aeson (ToJSON(..), (.=), object)
import Data.Monoid
import Data.Typeable (Typeable)
import Database.SQLite.Simple (FromRow(..), SQLData(..), field)
import Database.SQLite.Simple.FromField (FromField(..), ResultError(..), returnError, fieldData)
import Database.SQLite.Simple.Ok (Ok(..))
import Database.SQLite.Simple.ToField (ToField(..))
import Network.Skype.Core
import Network.Skype.Protocol
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
class ToString a where
toString :: a -> String
instance (ToString a) => ToJSON a where
toJSON = toJSON . toString
instance (ToString a) => ToField a where
toField = toField . toString
-- * Chat
newtype ChatIDWrapper = ChatIDWrapper { unChatID :: ChatID }
deriving (Eq, Show)
data ChatEntity = ChatEntity
{ _chatID :: ChatID
, _chatTimestamp :: Timestamp
, _chatAdder :: Maybe UserID
, _chatStatus :: ChatStatus
, _chatTopic :: ChatTopic
, _chatWindowTitle :: ChatWindowTitle
}
deriving (Show, Typeable)
instance Eq ChatEntity where
(==) x y = _chatID x == _chatID y
instance ToJSON ChatIDWrapper where
toJSON = toJSON . T.decodeLatin1 . unChatID
instance ToJSON ChatEntity where
toJSON chat = object
[ "chat_id" .= (ChatIDWrapper $ _chatID chat)
, "timestamp" .= _chatTimestamp chat
, "adder" .= (UserIDWrapper <$> _chatAdder chat)
, "status" .= _chatStatus chat
, "topic" .= _chatTopic chat
, "window_title" .= _chatWindowTitle chat
]
instance FromRow ChatEntity where
fromRow = ChatEntity <$> field -- chat_id
<*> field -- timestamp
<*> field -- adder
<*> field -- status
<*> field -- topic
<*> field -- window_title
instance ToString ChatStatus where
toString ChatStatusLegacyDialog = "legacy_dialog"
toString ChatStatusDialog = "dialog"
toString ChatStatusMultiSubscribed = "multi_subscribed"
toString ChatStatusUnsubscribed = "unsubscribed"
instance FromField ChatStatus where
fromField f = case fieldData f of
SQLText "legacy_dialog" -> Ok ChatStatusLegacyDialog
SQLText "dialog" -> Ok ChatStatusDialog
SQLText "multi_subscribed" -> Ok ChatStatusMultiSubscribed
SQLText "unsubscribed" -> Ok ChatStatusUnsubscribed
SQLText t -> returnError ConversionFailed f ("unexpected text: " <> T.unpack t)
_ -> returnError ConversionFailed f "need a text"
-- * Chat message
data ChatMessageEntity = ChatMessageEntity
{ _chatMessageID :: ChatMessageID
, _chatMessageTimestamp :: Timestamp
, _chatMessageSender :: UserID
, _chatMessageSenderDisplayName :: UserDisplayName
, _chatMessageType :: ChatMessageType
, _chatMessageStatus :: ChatMessageStatus
, _chatMessageLeaveReason :: Maybe ChatMessageLeaveReason
, _chatMessageChat :: ChatID
, _chatMessageBody :: ChatMessageBody
}
deriving (Show, Typeable)
instance Eq ChatMessageEntity where
(==) x y = _chatMessageID x == _chatMessageID y
instance ToJSON ChatMessageEntity where
toJSON chatMessage = object
[ "chat_message_id" .= _chatMessageID chatMessage
, "timestamp" .= _chatMessageTimestamp chatMessage
, "sender" .= (UserIDWrapper $ _chatMessageSender chatMessage)
, "sender_display_name" .= _chatMessageSenderDisplayName chatMessage
, "type" .= _chatMessageType chatMessage
, "status" .= _chatMessageStatus chatMessage
, "leave_reason" .= _chatMessageLeaveReason chatMessage
, "chat" .= (ChatIDWrapper $ _chatMessageChat chatMessage)
, "body" .= _chatMessageBody chatMessage
]
instance FromRow ChatMessageEntity where
fromRow = ChatMessageEntity <$> field -- chat_message_id
<*> field -- timestamp
<*> field -- sender
<*> field -- sender_display_name
<*> field -- type
<*> field -- status
<*> field -- leave_reason
<*> field -- chat
<*> field -- body
instance ToString ChatMessageType where
toString ChatMessageTypeSetTopic = "set_topic"
toString ChatMessageTypeSaid = "said"
toString ChatMessageTypeAddedMembers = "added_members"
toString ChatMessageTypeSawMembers = "saw_members"
toString ChatMessageTypeCreatedChatWith = "created_chat_with"
toString ChatMessageTypeLeft = "left"
toString ChatMessageTypePostedContacts = "posted_contacts"
toString ChatMessageTypeGapInChat = "gap_in_chat"
toString ChatMessageTypeSetRole = "set_role"
toString ChatMessageTypeKicked = "kicked"
toString ChatMessageTypeKickBanned = "kick_banned"
toString ChatMessageTypeSetOptions = "set_options"
toString ChatMessageTypeSetPicture = "set_picture"
toString ChatMessageTypeSetGuideLines = "set_guide_lines"
toString ChatMessageTypeJoinedAsApplicant = "joined_as_applicant"
toString ChatMessageTypeEmoted = "emoted"
toString ChatMessageTypeUnkown = "unknown"
instance FromField ChatMessageType where
fromField f = case fieldData f of
SQLText "set_topic" -> Ok ChatMessageTypeSetTopic
SQLText "said" -> Ok ChatMessageTypeSaid
SQLText "added_members" -> Ok ChatMessageTypeAddedMembers
SQLText "saw_members" -> Ok ChatMessageTypeSawMembers
SQLText "created_chat_with" -> Ok ChatMessageTypeCreatedChatWith
SQLText "left" -> Ok ChatMessageTypeLeft
SQLText "posted_contacts" -> Ok ChatMessageTypePostedContacts
SQLText "gap_in_chat" -> Ok ChatMessageTypeGapInChat
SQLText "set_role" -> Ok ChatMessageTypeSetRole
SQLText "kicked" -> Ok ChatMessageTypeKicked
SQLText "kick_banned" -> Ok ChatMessageTypeKickBanned
SQLText "set_options" -> Ok ChatMessageTypeSetOptions
SQLText "set_picture" -> Ok ChatMessageTypeSetPicture
SQLText "set_guide_lines" -> Ok ChatMessageTypeSetGuideLines
SQLText "joined_as_applicant" -> Ok ChatMessageTypeJoinedAsApplicant
SQLText "emoted" -> Ok ChatMessageTypeEmoted
SQLText "unknown" -> Ok ChatMessageTypeUnkown
SQLText t -> returnError ConversionFailed f ("unexpected text: " <> T.unpack t)
_ -> returnError ConversionFailed f "need a text"
instance ToString ChatMessageStatus where
toString ChatMessageStatusSending = "sending"
toString ChatMessageStatusSent = "sent"
toString ChatMessageStatusReceived = "received"
toString ChatMessageStatusRead = "read"
instance FromField ChatMessageStatus where
fromField f = case fieldData f of
SQLText "sending " -> Ok ChatMessageStatusSending
SQLText "sent" -> Ok ChatMessageStatusSent
SQLText "received" -> Ok ChatMessageStatusReceived
SQLText "read" -> Ok ChatMessageStatusRead
SQLText _ -> returnError ConversionFailed f "unexpected text"
_ -> returnError ConversionFailed f "need a text"
instance ToString ChatMessageLeaveReason where
toString ChatMessageLeaveReasonUserNotFound = "user_not_found"
toString ChatMessageLeaveReasonUserIncapable = "user_incapable"
toString ChatMessageLeaveReasonAdderMustBeFriend = "adder_must_be_friend"
toString ChatMessageLeaveReasonAdderMustBeAuthorized = "adder_must_be_authorized"
toString ChatMessageLeaveReasonUnsubscribe = "unsubscribe"
instance FromField ChatMessageLeaveReason where
fromField f = case fieldData f of
SQLText "user_not_found" -> Ok ChatMessageLeaveReasonUserNotFound
SQLText "user_incapable" -> Ok ChatMessageLeaveReasonUserIncapable
SQLText "adder_must_be_friend" -> Ok ChatMessageLeaveReasonAdderMustBeFriend
SQLText "adder_must_be_authorized" -> Ok ChatMessageLeaveReasonAdderMustBeAuthorized
SQLText "unsubscribe" -> Ok ChatMessageLeaveReasonUnsubscribe
SQLText t -> returnError ConversionFailed f ("unexpected text: " <> T.unpack t)
_ -> returnError ConversionFailed f "need a text"
-- * Error
instance ToJSON SkypeError where
toJSON (SkypeError code command description) = object
[ "error_code" .= code
, "error_command" .= T.decodeLatin1 command
, "error_description" .= description
]
-- * User
--
newtype UserIDWrapper = UserIDWrapper { unUserID :: UserID }
deriving (Eq, Show)
data UserEntity = UserEntity
{ _userID :: UserID
, _userFullName :: UserFullName
, _userBirthday :: Maybe UserBirthday
, _userSex :: UserSex
, _userLanguage :: Maybe (UserLanguageISOCode, UserLanguage)
, _userCountry :: Maybe (UserCountryISOCode, UserCountry)
, _userProvince :: UserProvince
, _userCity :: UserCity
, _userHomePhone :: UserPhone
, _userOfficePhone :: UserPhone
, _userMobilePhone :: UserPhone
, _userHomepage :: UserHomepage
, _userAbout :: UserAbout
, _userIsVideoCapable :: Bool
, _userIsVoicemailCapable :: Bool
, _userBuddyStatus :: UserBuddyStatus
, _userIsAuthorized :: Bool
, _userIsBlocked :: Bool
, _userOnlineStatus :: UserOnlineStatus
, _userLastOnlineTimestamp :: Timestamp
, _userCanLeaveVoicemail :: Bool
, _userSpeedDial :: UserSpeedDial
, _userMoodText :: UserMoodText
, _userTimezone :: UserTimezoneOffset
, _userIsCallForwardingActive :: Bool
, _userNumberOfAuthedBuddies :: Int
, _userDisplayName :: UserDisplayName
}
deriving (Show, Typeable)
instance Eq UserEntity where
(==) x y = _userID x == _userID y
instance ToJSON UserIDWrapper where
toJSON = toJSON . T.decodeLatin1 . unUserID
instance ToJSON UserEntity where
toJSON user = object
[ "user_id" .= (UserIDWrapper $ _userID user)
, "full_name" .= _userFullName user
, "birthday" .= (show <$> _userBirthday user)
, "sex" .= _userSex user
, "language" .= (snd <$> _userLanguage user)
, "language_iso_code" .= (fst <$> _userLanguage user)
, "country" .= (snd <$> _userCountry user)
, "country_iso_code" .= (fst <$> _userCountry user)
, "province" .= _userProvince user
, "city" .= _userCity user
, "home_phone" .= _userHomePhone user
, "office_phone" .= _userOfficePhone user
, "mobile_phone" .= _userMobilePhone user
, "homepage" .= _userHomepage user
, "about" .= _userAbout user
, "is_video_capable" .= _userIsVideoCapable user
, "is_voice_mail_capable" .= _userIsVoicemailCapable user
, "buddy_status" .= _userBuddyStatus user
, "is_authorized" .= _userIsAuthorized user
, "is_blocked" .= _userIsBlocked user
, "online_status" .= _userOnlineStatus user
, "last_online_timestamp" .= _userLastOnlineTimestamp user
, "can_leave_voicemail" .= _userCanLeaveVoicemail user
, "speed_dial" .= _userSpeedDial user
, "mood_text" .= _userMoodText user
, "timezone" .= _userTimezone user
, "is_call_forwarding_active" .= _userIsCallForwardingActive user
, "number_of_authed_buddies" .= _userNumberOfAuthedBuddies user
, "display_name" .= _userDisplayName user
]
instance ToString UserSex where
toString UserSexUnknown = "unknown"
toString UserSexMale = "male"
toString UserSexFemale = "female"
instance ToString UserStatus where
toString UserStatusUnknown = "unknown"
toString UserStatusOnline = "online"
toString UserStatusOffline = "offline"
toString UserStatusSkypeMe = "skype_me"
toString UserStatusAway = "away"
toString UserStatusNotAvailable = "not_available"
toString UserStatusDoNotDisturb = "do_not_disturb"
toString UserStatusInvisible = "invisible"
toString UserStatusLoggedOut = "logged_out"
instance ToString UserBuddyStatus where
toString UserBuddyStatusNeverBeen = "never_been"
toString UserBuddyStatusDeleted = "deleted"
toString UserBuddyStatusPending = "pending"
toString UserBuddyStatusAdded = "added"
instance ToString UserOnlineStatus where
toString UserOnlineStatusUnknown = "unknown"
toString UserOnlineStatusOffline = "offline"
toString UserOnlineStatusOnline = "online"
toString UserOnlineStatusAway = "away"
toString UserOnlineStatusNotAvailable = "not_available"
toString UserOnlineStatusDoNotDisturb = "do_not_disturb"
|
emonkak/skype-rest-api-server
|
src/App/Entity.hs
|
mit
| 13,373 | 0 | 14 | 3,471 | 2,570 | 1,346 | 1,224 | 265 | 0 |
{-
Author: Nick(Mykola) Pershyn
Language: Haskell
Program: Monte-Carlo integration with OpenCL in Haskell
-}
module KernelGen where
import Data.List(intercalate)
import FunctionTypes
genKernel :: FunctionExpression -> String
genKernel expr = {-"#pragma OPENCL EXTENSION cl_khr_fp64 : enable\n"
++ -} "__kernel " ++ "void " ++ (name expr)
++ "(" ++ farg ++ ")"
++ "{"
++ limits
++ "int id = get_global_id(0);"
++ "double output = 0;"
++ (foldedLoops dim subDiv body)
++ "out[id] = output / (" ++ intercalate ("*") (replicate dim (show subDiv)) ++");"
++ "}"
where
subDiv :: Int
subDiv = 2^10
args = concatMap var [0..dim-1]
limit i = "const double lower" ++ (show i) ++ " = " ++ (show $ lower . snd $ (variables expr)!!i) ++ ";"
++ "const double upper" ++ (show i) ++ " = " ++ (show $ upper . snd $ (variables expr)!!i) ++ ";"
limits = concatMap limit [0..dim-1]
farg = "__global const double *x, __global double *out"
fexpr = expression expr
dim = length $ variables expr
var :: Int -> String
var i = "const double " ++ (fst $ (variables expr)!!i) ++
concat [" = ",li i," + (",ui i," - ",li i,") * (",ii i," + ",xi i,") / ",show subDiv,";"]
loop :: String -> Int -> String -> String
-- loop "i" 1000 "" = "for(int i = 0; i < 1000; ++i){}"
loop i n body' = "for(int " ++ i ++ " = 0; " ++ i ++ " < " ++ (show n) ++ "; ++" ++ i ++ "){" ++ body' ++"}"
foldedLoops 0 _ body' = body'
foldedLoops depth n body' = loop ("i" ++ (show (depth - 1))) n (foldedLoops (depth - 1) n body')
body = args ++ "output += " ++ fexpr ++ ";"
loopVarsList = map (("i" ++) . show) [0..dim-1]
li i = "lower" ++ (show i)
ui i = "upper" ++ (show i)
ii i = "i" ++ (show i)
xi i = "x[id + " ++ (show i) ++ "]"
|
LinuxUser404/haskell-mcint
|
src/KernelGen.hs
|
mit
| 1,919 | 0 | 19 | 576 | 684 | 358 | 326 | 36 | 2 |
{- |
Module : $Header$
Description : Basic analysis for common logic
Copyright : (c) Eugen Kuksa, Karl Luc, Uni Bremen 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
Basic and static analysis for common logic
-}
module CommonLogic.Analysis
( basicCommonLogicAnalysis
, negForm
, symsOfTextMeta
, mkStatSymbItems
, mkStatSymbMapItem
, inducedFromMorphism
, inducedFromToMorphism
)
where
import Common.ExtSign
import Common.Result as Result
import Common.GlobalAnnotations
import qualified Common.AS_Annotation as AS_Anno
import Common.Id as Id
import Common.IRI (parseIRIReference)
import Common.DocUtils
import CommonLogic.Symbol as Symbol
import qualified CommonLogic.AS_CommonLogic as AS
import CommonLogic.Morphism as Morphism
import CommonLogic.Sign as Sign
import CommonLogic.ExpandCurie
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Common.Lib.MapSet as MapSet
import qualified Data.List as List
data DIAG_FORM = DiagForm
{
formula :: AS_Anno.Named AS.TEXT_META,
diagnosis :: Result.Diagnosis
}
-- | retrieves the signature out of a basic spec
makeSig :: AS.BASIC_SPEC -> Sign.Sign -> Sign.Sign
makeSig (AS.Basic_spec spec) sig = List.foldl retrieveBasicItem sig spec
retrieveBasicItem :: Sign.Sign -> AS_Anno.Annoted AS.BASIC_ITEMS -> Sign.Sign
retrieveBasicItem sig x = case AS_Anno.item x of
AS.Axiom_items xs -> List.foldl retrieveSign sig xs
retrieveSign :: Sign.Sign -> AS_Anno.Annoted AS.TEXT_META -> Sign.Sign
retrieveSign sig (AS_Anno.Annoted tm _ _ _) =
Sign.unite (Sign.unite sig $ nondiscItems $ AS.nondiscourseNames tm)
(propsOfFormula $ AS.getText tm)
nondiscItems :: Maybe (Set.Set AS.NAME) -> Sign.Sign
nondiscItems s = case s of
Nothing -> Sign.emptySig
Just ns -> Sign.emptySig {Sign.nondiscourseNames = Set.map Id.simpleIdToId ns}
-- | retrieve sentences
makeFormulas :: AS.BASIC_SPEC -> Sign.Sign -> [DIAG_FORM]
makeFormulas (AS.Basic_spec bspec) sig =
List.foldl (\ xs bs -> retrieveFormulaItem xs bs sig) [] bspec
retrieveFormulaItem :: [DIAG_FORM] -> AS_Anno.Annoted AS.BASIC_ITEMS
-> Sign.Sign -> [DIAG_FORM]
retrieveFormulaItem axs x sig =
case AS_Anno.item x of
AS.Axiom_items ax ->
List.foldl (\ xs bs -> addFormula xs bs sig) axs $ numberFormulae ax 0
data NUM_FORM = NumForm
{
nfformula :: AS_Anno.Annoted AS.TEXT_META
, nfnum :: Int
}
numberFormulae :: [AS_Anno.Annoted AS.TEXT_META] -> Int -> [NUM_FORM]
numberFormulae [] _ = []
numberFormulae (x : xs) i =
if null $ AS_Anno.getRLabel x
then NumForm {nfformula = x, nfnum = i} : numberFormulae xs (i + 1)
else NumForm {nfformula = x, nfnum = 0} : numberFormulae xs i
addFormula :: [DIAG_FORM]
-> NUM_FORM
-> Sign.Sign
-> [DIAG_FORM]
addFormula formulae nf _ = formulae ++
[DiagForm {
formula = makeNamed (setTextIRI f) i
, diagnosis = Result.Diag
{
Result.diagKind = Result.Hint
, Result.diagString = "All fine"
, Result.diagPos = lnum
}
}]
where
f = nfformula nf
i = nfnum nf
lnum = AS_Anno.opt_pos f
-- | generates a named formula
makeNamed :: AS_Anno.Annoted AS.TEXT_META -> Int
-> AS_Anno.Named AS.TEXT_META
makeNamed f i =
(AS_Anno.makeNamed (
if null label
then case text of
AS.Named_text n _ _ -> Id.tokStr n
_ -> "Ax_" ++ show i
else label
) $ AS_Anno.item f)
{ AS_Anno.isAxiom = not isTheorem }
where
text = AS.getText $ AS_Anno.item f
label = AS_Anno.getRLabel f
annos = AS_Anno.r_annos f
isImplies = any AS_Anno.isImplies annos
isImplied = any AS_Anno.isImplied annos
isTheorem = isImplies || isImplied
setTextIRI :: AS_Anno.Annoted AS.TEXT_META -> AS_Anno.Annoted AS.TEXT_META
setTextIRI atm@(AS_Anno.Annoted { AS_Anno.item = tm }) =
let mi = case AS.getText tm of
AS.Named_text n _ _ -> parseIRIReference $ init $ tail $ Id.tokStr n
_ -> Nothing
in atm { AS_Anno.item = tm { AS.textIri = mi } }
-- | Retrives the signature of a sentence
propsOfFormula :: AS.TEXT -> Sign.Sign
propsOfFormula (AS.Named_text _ txt _) = propsOfFormula txt
propsOfFormula (AS.Text phrs _) = Sign.uniteL $ map propsOfPhrase phrs
propsOfPhrase :: AS.PHRASE -> Sign.Sign
propsOfPhrase (AS.Module m) = propsOfModule m
propsOfPhrase (AS.Sentence s) = propsOfSentence s
propsOfPhrase (AS.Comment_text _ txt _) = propsOfFormula txt
propsOfPhrase (AS.Importation _) = Sign.emptySig
propsOfModule :: AS.MODULE -> Sign.Sign
propsOfModule m = case m of
(AS.Mod n txt _) -> Sign.unite (propsOfFormula txt) $ nameToSign n
(AS.Mod_ex n exs txt _) -> Sign.unite (propsOfFormula txt)
$ Sign.uniteL $ nameToSign n : map nameToSign exs
where nameToSign x = Sign.emptySig {
Sign.discourseNames = Set.singleton $ Id.simpleIdToId x
}
propsOfSentence :: AS.SENTENCE -> Sign.Sign
propsOfSentence (AS.Atom_sent form _) = case form of
AS.Equation term1 term2 -> Sign.unite (propsOfTerm term1)
(propsOfTerm term2)
AS.Atom term ts -> Sign.unite (propsOfTerm term)
(uniteMap propsOfTermSeq ts)
propsOfSentence (AS.Quant_sent _ xs s _) =
Sign.sigDiff (propsOfSentence s) (uniteMap propsOfNames xs)
propsOfSentence (AS.Bool_sent bs _) = case bs of
AS.Junction _ xs -> uniteMap propsOfSentence xs
AS.Negation x -> propsOfSentence x
AS.BinOp _ s1 s2 -> Sign.unite (propsOfSentence s1) (propsOfSentence s2)
propsOfSentence (AS.Comment_sent _ s _) = propsOfSentence s
propsOfSentence (AS.Irregular_sent s _) = propsOfSentence s
propsOfTerm :: AS.TERM -> Sign.Sign
propsOfTerm term = case term of
AS.Name_term x -> Sign.emptySig {
Sign.discourseNames = Set.singleton $ Id.simpleIdToId x
}
AS.Funct_term t ts _ -> Sign.unite (propsOfTerm t)
(uniteMap propsOfTermSeq ts)
AS.Comment_term t _ _ -> propsOfTerm t -- fix
AS.That_term s _ -> propsOfSentence s
propsOfNames :: AS.NAME_OR_SEQMARK -> Sign.Sign
propsOfNames (AS.Name x) = Sign.emptySig {
Sign.discourseNames = Set.singleton $ Id.simpleIdToId x
}
propsOfNames (AS.SeqMark x) = Sign.emptySig {
Sign.sequenceMarkers = Set.singleton $ Id.simpleIdToId x
}
propsOfTermSeq :: AS.TERM_SEQ -> Sign.Sign
propsOfTermSeq s = case s of
AS.Term_seq term -> propsOfTerm term
AS.Seq_marks x -> Sign.emptySig {
Sign.sequenceMarkers = Set.singleton $ Id.simpleIdToId x
}
uniteMap :: (a -> Sign.Sign) -> [a] -> Sign
uniteMap p = List.foldl (\ sig -> Sign.unite sig . p)
Sign.emptySig
-- | Common Logic static analysis
basicCommonLogicAnalysis :: (AS.BASIC_SPEC, Sign.Sign, GlobalAnnos)
-> Result (AS.BASIC_SPEC,
ExtSign Sign.Sign Symbol.Symbol,
[AS_Anno.Named AS.TEXT_META])
basicCommonLogicAnalysis (bs', sig, ga) =
Result.Result [] $ if exErrs then Nothing else
Just (bs', ExtSign sigItems newSyms, sentences)
where
bs = expandCurieBS (prefix_map ga) bs'
sigItems = makeSig bs sig
newSyms = Set.map Symbol.Symbol
$ Set.difference (Sign.allItems sigItems) $ Sign.allItems sig
bsform = makeFormulas bs sigItems
-- [DIAG_FORM] signature and list of sentences
sentences = map formula bsform
-- Annoted Sentences (Ax_), numbering, DiagError
exErrs = False
-- | creates a morphism from a symbol map
inducedFromMorphism :: Map.Map Symbol.Symbol Symbol.Symbol
-> Sign.Sign
-> Result.Result Morphism.Morphism
inducedFromMorphism m s = let
p = Map.mapKeys symName $ Map.map symName m
t = Sign.emptySig { discourseNames = Set.map (applyMap p) $ discourseNames s
, nondiscourseNames = Set.map (applyMap p) $ nondiscourseNames s
, sequenceMarkers = Set.map (applyMap p) $ sequenceMarkers s
}
in return $ mkMorphism s t p
splitFragment :: Id -> (String, String)
splitFragment = span (/= '#') . show
inducedFromToMorphism :: Map.Map Symbol.Symbol Symbol.Symbol
-> ExtSign Sign.Sign Symbol.Symbol
-> ExtSign Sign.Sign Symbol.Symbol
-> Result.Result Morphism.Morphism
inducedFromToMorphism m (ExtSign s sys) (ExtSign t ty) = let
tsy = Set.fold (\ r -> let (q, f) = splitFragment $ symName r
in MapSet.insert f q) MapSet.empty ty
p = Set.fold (\ sy -> let n = symName sy in case Map.lookup sy m of
Just r -> Map.insert n $ symName r
Nothing -> if Set.member sy ty then id else
let (_, f) = splitFragment n
in case Set.toList $ MapSet.lookup f tsy of
[q] -> Map.insert n $ simpleIdToId
$ mkSimpleId $ q ++ f
_ -> id) Map.empty sys
t2 = Sign.emptySig
{ discourseNames = Set.map (applyMap p) $ discourseNames s
, nondiscourseNames = Set.map (applyMap p) $ nondiscourseNames s
, sequenceMarkers = Set.map (applyMap p) $ sequenceMarkers s
}
in if isSubSigOf t2 t then return $ mkMorphism s t p else
fail $ "cannot map symbols from\n" ++ showDoc (sigDiff t2 t) "\nto\n"
++ showDoc t ""
-- | negate sentence (text) - propagates negation to sentences
negForm :: AS.TEXT_META -> AS.TEXT_META
negForm tm = tm { AS.getText = negForm_txt $ AS.getText tm }
negForm_txt :: AS.TEXT -> AS.TEXT
negForm_txt t = case t of
AS.Text phrs r -> AS.Text (map negForm_phr phrs) r
AS.Named_text n txt r -> AS.Named_text n (negForm_txt txt) r
-- negate phrase - propagates negation to sentences
negForm_phr :: AS.PHRASE -> AS.PHRASE
negForm_phr phr = case phr of
AS.Module m -> AS.Module $ negForm_mod m
AS.Sentence s -> AS.Sentence $ negForm_sen s
AS.Comment_text c t r -> AS.Comment_text c (negForm_txt t) r
x -> x
-- negate module - propagates negation to sentences
negForm_mod :: AS.MODULE -> AS.MODULE
negForm_mod m = case m of
AS.Mod n t r -> AS.Mod n (negForm_txt t) r
AS.Mod_ex n exs t r -> AS.Mod_ex n exs (negForm_txt t) r
-- negate sentence
negForm_sen :: AS.SENTENCE -> AS.SENTENCE
negForm_sen f = case f of
AS.Quant_sent _ _ _ r -> AS.Bool_sent (AS.Negation f) r
AS.Bool_sent bs r -> case bs of
AS.Negation s -> s
_ -> AS.Bool_sent (AS.Negation f) r
_ -> AS.Bool_sent (AS.Negation f) Id.nullRange
-- | Static analysis for symbol maps
mkStatSymbMapItem :: [AS.SYMB_MAP_ITEMS]
-> Result.Result (Map.Map Symbol.Symbol Symbol.Symbol)
mkStatSymbMapItem xs =
Result.Result
{
Result.diags = []
, Result.maybeResult = Just $
foldl
(
\ smap x ->
case x of
AS.Symb_map_items sitem _ ->
Map.union smap $ statSymbMapItem sitem
)
Map.empty
xs
}
statSymbMapItem :: [AS.SYMB_OR_MAP] -> Map.Map Symbol.Symbol Symbol.Symbol
statSymbMapItem =
foldl
(
\ mmap x ->
case x of
AS.Symb sym -> Map.insert (nosToSymbol sym) (nosToSymbol sym) mmap
AS.Symb_mapN s1 s2 _
-> Map.insert (symbToSymbol s1) (symbToSymbol s2) mmap
AS.Symb_mapS s1 s2 _
-> Map.insert (symbToSymbol s1) (symbToSymbol s2) mmap
)
Map.empty
-- | Retrieve raw symbols
mkStatSymbItems :: [AS.SYMB_ITEMS] -> Result.Result [Symbol.Symbol]
mkStatSymbItems a = Result.Result
{
Result.diags = []
, Result.maybeResult = Just $ statSymbItems a
}
statSymbItems :: [AS.SYMB_ITEMS] -> [Symbol.Symbol]
statSymbItems = concatMap symbItemsToSymbol
symbItemsToSymbol :: AS.SYMB_ITEMS -> [Symbol.Symbol]
symbItemsToSymbol (AS.Symb_items syms _) = map nosToSymbol syms
nosToSymbol :: AS.NAME_OR_SEQMARK -> Symbol.Symbol
nosToSymbol nos = case nos of
AS.Name tok -> symbToSymbol tok
AS.SeqMark tok -> symbToSymbol tok
symbToSymbol :: Id.Token -> Symbol.Symbol
symbToSymbol tok = Symbol.Symbol {Symbol.symName = Id.simpleIdToId tok}
-- | retrieves all symbols from the text
symsOfTextMeta :: AS.TEXT_META -> [Symbol.Symbol]
symsOfTextMeta tm =
Set.toList $ Symbol.symOf $ retrieveSign Sign.emptySig $ AS_Anno.emptyAnno tm
|
nevrenato/HetsAlloy
|
CommonLogic/Analysis.hs
|
gpl-2.0
| 12,866 | 0 | 28 | 3,467 | 3,970 | 2,023 | 1,947 | 258 | 5 |
module Types where
data SmExpression = SmInt Integer
| SmFloat Double
| SmChar Char
| SmOperator Char
| SmString String
| SmList [SmExpression]
deriving (Show,Eq,Read)
instance Ord SmExpression where
(SmInt x1) <= (SmInt x2) = x1 <= x2
(SmFloat x1) <= (SmFloat x2) = x1 <= x2
(SmChar x1) <= (SmChar x2) = x1 <= x2
(SmOperator x1) <= (SmOperator x2) = x1 <= x2
(SmString x1) <= (SmString x2) = x1 <= x2
(SmList x1) <= (SmList x2) = x1 <= x2
(SmInt x1) <= (SmFloat x2) = fromInteger x1 <= x2
(SmFloat x1) <= (SmInt x2) = x1 < fromInteger x2
(SmInt _) <= _ = True
(SmFloat _) <= _ = True
(SmChar _) <= (SmInt _) = False
(SmChar _) <= (SmFloat _) = False
(SmChar _) <= _ = True
(SmOperator _) <= (SmString _) = True
(SmOperator _) <= (SmList _) = True
(SmString _) <= (SmList _) = True
_ <= _ = False
type SmProgram = [SmExpression]
type SmStack = [SmExpression]
type SmFunction = SmStack -> SmStack
-- Type Conversion
toInt :: SmExpression -> Integer
toInt (SmInt x) = x
toInt (SmFloat x)
| x >= 0 = floor x
| otherwise = ceiling x
toInt (SmChar x) = toInteger $ fromEnum x
toInt (SmOperator x) = toInteger $ fromEnum x
toFloat :: SmExpression -> Double
toFloat (SmInt x) = fromInteger x
toFloat (SmFloat x) = x
toFloat (SmChar x) = fromIntegral $ fromEnum x
toFloat (SmOperator x) = fromIntegral $ fromEnum x
toChar :: SmExpression -> Char
toChar (SmInt x) = toEnum $ fromIntegral x
toChar (SmFloat x) = toEnum $ floor x
toChar (SmChar x) = x
toChar (SmOperator x) = x
toString :: SmExpression -> String
toString (SmInt x) = show x
toString (SmFloat x) = show x
toString (SmChar x) = [x]
toString (SmString xs) = xs
toString (SmList xs) = xs >>= toString
toString (SmOperator x) = [x]
toList :: SmExpression -> [SmExpression]
toList (SmString xs) = map SmChar xs
toList (SmList xs) = xs
toList x = [x]
|
AlephAlpha/Samau
|
OldSamau/Types.hs
|
gpl-2.0
| 2,220 | 0 | 8 | 762 | 922 | 458 | 464 | 57 | 1 |
module Monadius (
Monadius(..) ,initialMonadius,getVariables,
GameVariables(..),
shotButton,missileButton,powerUpButton,upButton,downButton,leftButton,rightButton,selfDestructButton
) where
import Data.Array ((!), Array(), array)
import Data.Complex -- ((:+))
import Data.List (intersect, find)
import Data.Maybe (fromJust, isJust, isNothing)
import Prelude hiding (catch)
import Game
import Util
import GLWrapper
import GameObject
import GOConst
import GameObjectRender
import Stage
instance Game Monadius where
update = updateMonadius
render = renderMonadius
isGameover = isMonadiusOver
data HitClass = BacterianShot |
BacterianBody |
LaserAbsorber |
MetalionShot |
MetalionBody |
ItemReceiver |
PowerUp |
LandScape
deriving(Eq)
data WeaponType = NormalShot | Missile | DoubleShot | Laser
deriving (Eq)
-- WeaponType NormalShot | Missile | DoubleShot | Laser ... represents function of weapon that player selected, while
-- GameObject StandardRailgun | StandardLaser ... represents the object that is actually shot and rendered.
-- for example;
-- shooting NormalShot :: WeaponType and DoubleShot :: WeaponType both result in StandardRailgun :: GameObject creation, and
-- shooting Laser :: WeaponType creates StandardLaser :: GameObject when player is operating VicViper, or RippleLaser :: GameObject when LordBritish ... etc.
data ScrollBehavior = Enclosed{doesScroll :: Bool} | NoRollOut{doesScroll :: Bool}
| RollOutAuto{doesScroll :: Bool, range :: Double} | RollOutFold{doesScroll :: Bool}
-----------------------------
--
-- initialization
--
------------------------------
initialMonadius :: GameVariables -> Monadius
initialMonadius initVs = Monadius (initVs,initGameObjects)
where
initGameObjects = stars ++ [freshVicViper,freshPowerUpGauge]
stars = take 26 $ map (\(t,i) -> Star{tag=Nothing,position = (fix 320 t:+fix 201 t),particleColor=colors!!i}) $ zip (map (\x -> square x + x + 41) [2346,19091..]) [1..]
fix :: Int -> Int -> Double
fix limit value = intToDouble $ (value `mod` (2*limit) - limit)
colors = [Color3 1 1 1,Color3 1 1 0,Color3 1 0 0, Color3 0 1 1] ++ colors
{-
Default settings of game objects and constants
-}
downButton,leftButton,missileButton,powerUpButton,rightButton,selfDestructButton,shotButton,upButton :: Key
downButton = SpecialKey KeyDown
leftButton = SpecialKey KeyLeft
missileButton = Char 'x'
powerUpButton = Char 'c'
rightButton = SpecialKey KeyRight
selfDestructButton = Char 'g'
shotButton = Char 'z'
upButton = SpecialKey KeyUp
landScapeSensitive :: GameObject -> Bool
landScapeSensitive StandardRailgun{} = True -- these objects has hitDispLand
landScapeSensitive StandardLaser{} = True -- in addition to hitDisp
landScapeSensitive Shield{} = True
landScapeSensitive _ = False
-----------------------------
--
-- game progress
--
-----------------------------
updateMonadius :: [Key] -> Monadius -> Monadius
updateMonadius realKeys (Monadius (variables,objects))
= Monadius (newVariables,newObjects) where
gameLevel = baseGameLevel variables
bacterianShotSpeed = bacterianShotSpeedList!!gameLevel
keys = if hp vicViper<=0 then [] else realKeys
-- almost all operation dies when vicViper dies. use realKeys to fetch unaffected keystates.
(newNextTag,newObjects) = issueTag (nextTag variables)
$ ((loadObjects clock isEasy vicViper objects) ++)
$ filterJust.map scroll
$ concatMap updateGameObject
$ gameObjectsAfterCollision
gameObjectsAfterCollision = collide objects
-- * collision must be done BEFORE updateGameObject(moving), for
-- players would like to see the moment of collision.
-- * loading new objects after collision and moving is nice idea, since
-- you then have new objects appear at exact place you wanted them to.
-- * however, some operation would like to refer the result of the collision
-- before it is actually taken effect in updateGameObject.
-- such routine should use gameObjectsAfterCollision.
newVariables = variables{
nextTag = newNextTag,
flagGameover = flagGameover variables || ageAfterDeath vicViper > 240,
gameClock = (\c -> if hp vicViper<=0 then c else if goNextStage then 0 else c+1) $ gameClock variables,
baseGameLevel = (\l -> if goNextStage then l+1 else l) $ baseGameLevel variables,
totalScore = newScore,
hiScore = hiScore variables `max` newScore
}
where
goNextStage = gameClock variables > stageClearTime
newScore = totalScore variables + sum (map (\obj -> case obj of
ScoreFragment{score = p} -> p
_ -> 0) objects)
updateGameObject :: GameObject -> [GameObject]
-- update each of the objects and returns list of resulting objects.
-- the list usually includes the modified object itself,
-- may include several generated objects such as bullets and explosions,
-- or include nothing if the object has vanished.
updateGameObject vic@VicViper{} = newShields ++ makeMetalionShots vic{
position=position vic + (vmag*(speed vic):+0) * (vx:+vy) ,
trail=(if isMoving then ((position vic-(10:+0)):) else id) $ trail vic,
powerUpLevels =
(modifyArray gaugeOfShield (const (if (shieldCount > 0) then 1 else 0))) $
(if doesPowerUp then (
modifyArray (powerUpPointer vic)
(\x -> if x<powerUpLimits!!powerUpPointer vic then x+1 else 0) . -- overpowering-up results in initial powerup level.
(if powerUpPointer vic==gaugeOfDouble then modifyArray gaugeOfLaser (const 0) else id) . -- laser and double are
(if powerUpPointer vic==gaugeOfLaser then modifyArray gaugeOfDouble (const 0) else id) ) -- exclusive equippment.
else id) (powerUpLevels vic),
powerUpPointer = if doesPowerUp then (-1) else powerUpPointer vic,
speed = speeds !! (powerUpLevels vic!0),
reloadTime = max 0 $ reloadTime vic - 1,
ageAfterDeath = if hp vic>0 then 0
else ageAfterDeath vic+1,
hitDisp = if treasure!!gameLevel then Circular 0 0 else Circular (0:+0) vicViperSize,
hp = if selfDestructButton `elem` keys then 0 else hp vic
} where
isKey k = if k `elem` keys then 1 else 0
vx = isKey rightButton + (-(isKey leftButton))
vy = isKey upButton + (-(isKey downButton))
vmag = if vx*vx+vy*vy>1.1 then sqrt(0.5) else 1
isMoving = any (\b -> elem b keys) [rightButton,leftButton,upButton,downButton]
doesPowerUp = (powerUpButton `elem` keys) && (powerUpPointer vic >=0) &&
(powerUpPointer vic ==0 ||
powerUpLevels vic!powerUpPointer vic<powerUpLimits!!powerUpPointer vic)
speeds = [2,4,6,8,11,14] ++ speeds
shieldCount = sum $ map (\o -> case o of
Shield{} -> 1
_ -> 0) objects
newShields = if (doesPowerUp && powerUpPointer vic==gaugeOfShield) then
[freshShield{position=350:+260 ,placement=40:+shieldPlacementMargin, angle=30,omega=10 },
freshShield{position=350:+(-260),placement=40:+(-shieldPlacementMargin),angle=0 ,omega=(-10)}]
else []
updateGameObject option@Option{} = makeMetalionShots option{
position = trail vicViper !! (10*optionTag option),
reloadTime = max 0 $ reloadTime option - 1
}
updateGameObject miso@StandardMissile{} = [
miso{position=newpos,
mode = newmode,
velocity=v,
probe = (probe miso){position=newpos,hp=1}
}
] where
newmode = if hp(probe miso) <= 0 then 1 else
if mode miso == 0 then 0 else 2
v = case newmode of
0 -> 3.5:+(-7)
1 -> 8:+0
2 -> 0:+(-8)
_ -> 0
newpos = position miso + v
updateGameObject shot@StandardRailgun{} = if hp shot <=0 then [] else
[shot{position=position shot + velocity shot}]
updateGameObject laser@StandardLaser{} = if hp laser <=0 then [] else
[laser{position=(\(x:+_) -> x:+parentY) $ position laser + velocity laser,age=age laser+1}] where
myParent = head $ filter (\o -> tag o==Just (parentTag laser)) objects
_:+parentY = position myParent
updateGameObject shield@Shield{} = if(hp shield<=0) then [] else [
(if settled shield then
shield{
position=target,size=shieldPlacementMargin+intToDouble (hp shield),
hitDisp = Circular (0:+0) (size shield+shieldHitMargin),
hitDispLand = Circular (0:+0) (size shield)
}
else
shield{hp=shieldMaxHp,size=5+intToDouble (hp shield),position=newPosition,settled=chaseFactor>0.6})
{angle=angle shield + omega shield}
] where
newPosition = position shield + v
v = difference * (chaseFactor:+0)
chaseFactor = (10/magnitude difference)
difference = target-position shield
target = position vicViper+(realPart (placement shield) :+ additionalPlacementY)
additionalPlacementY = signum (imagPart$placement shield)*size shield
updateGameObject pow@PowerUpCapsule{} = if(hp pow<=0) then [freshScore 800] else [
pow{age=age pow + 1}
] ++ if powerUpCapsuleHitBack!!gameLevel && age pow ==1 then
map (\theta -> freshDiamondBomb{position=position pow,velocity=mkPolar (bacterianShotSpeed*0.5) theta}) $
take 8 $ iterate (+(2*pi/8)) (pi/8) else []
updateGameObject bullet@DiamondBomb{} = if hp bullet<=0 then [] else
[bullet{position=position bullet + velocity bullet,age=age bullet+1}]
updateGameObject self@TurnGear{position=pos@(x:+y),mode=m} = if hp self<=0 then
[freshScore 50] ++ freshExplosions pos ++ if turnGearHitBack!!gameLevel then [scatteredNeraiDan pos (bacterianShotSpeed:+0)] else []
else [
self{
position = position self + velocity self,
age = age self + 1,
mode = newmode,
velocity = newv
}] where
newv = case m of
0 -> ((-4):+0)
1 -> if (y - (imagPart.position) vicViper) > 0 then (3:+(-5)) else (3:+(5))
_ -> if isEasy then 2:+0 else 6:+0
newmode = if m==0 && x < (if not isEasy then -280 else 0) && (realPart.position) vicViper> (-270) then 1 else
if m==1 && abs (y - (imagPart.position) vicViper) < 20 then 2 else m
updateGameObject me@SquadManager{position=pos,interval=intv,members=membs,age=clock,tag=Just myTag} =
if mySquadIsWipedOut then(
if currentScore me >= bonusScore me then map (\o -> o{position=pos}) (items me) else []
)else me{
age = age me + 1,
currentScore = currentScore me + todaysDeaths,
position = if clock <= releaseTimeOfLastMember then pos else warFront
}:dispatchedObjects where
dispatchedObjects = if (clock `div` intv < length membs && clock `mod` intv == 0) then
[(membs!!(clock `div` intv)){position=pos,managerTag=myTag}] else []
todaysDeaths = sum $ map (\o -> if hp o <=0 then 1 else 0) $ mySquad
mySquadIsWipedOut = clock > releaseTimeOfLastMember && length mySquad <= 0
warFront = position $ head $ mySquad
releaseTimeOfLastMember = intv * (length membs-1)
mySquad = filter (\o -> case o of
TurnGear{managerTag=hisManagerTag} -> hisManagerTag == myTag -- bad, absolutely bad code
_ -> False) gameObjectsAfterCollision
updateGameObject this@Flyer{position=pos@(x:+_),age=myAge,mode=m,velocity =v} =
if gameClock variables > stageClearTime - 100 then freshExplosions pos else
if hp this <=0 then ([freshScore (if mode this == 10 then 30 else 110)] ++ freshExplosions pos++(if hasItem this then [freshPowerUpCapsule{position=pos}] else if flyerHitBack!!gameLevel then [scatteredNeraiDan pos (bacterianShotSpeed:+0)] else []))
else
[this{
age=myAge+1,
position = pos + v ,
velocity = newV,
mode = newMode
}]++myShots where
newV = case m of
00 -> (realPart v):+sin(intToDouble myAge / 5)
01 -> v --if magnitude v <= 0.01 then if imagPart (position vicViper-pos)>0 then 0:+10 else 0:+(-10) else v
02 -> (-4):+0
10 -> if (not isEasy) || myAge < 10 then stokeV else v
_ -> v
stokeV = angleAccuracy 16 $ (* ((min (speed vicViper*0.75) (intToDouble$round$magnitude v)):+0) ) $ unitVector $ position vicViper-pos
newMode = case m of
01 -> if myAge > 20 && (position vicViper - pos) `innerProduct` v < 0 then 02 else 01
_ -> m
myShots = if (myAge+13*(fromJust $tag this)) `mod` myInterval == 0 && (x <= (-80) || x <= realPart(position vicViper))
then [jikiNeraiDan pos (bacterianShotSpeed:+0)] else []
myInterval = if m==00 || m==03 then flyerShotInterval!!gameLevel else inceptorShotInterval!!gameLevel
updateGameObject me@Ducker{position=pos,velocity = v,age=myAge,gVelocity= vgrav,touchedLand = touched} =
if hp me <=0 then ([freshScore 130] ++ freshExplosions pos ++ if hasItem me then [freshPowerUpCapsule{position=pos}] else[]) else
[me{
age=myAge+1,
position = pos + v,
charge = if charge me <=0 && aimRate > 0.9 && aimRate < 1.1 then (duckerShotCount!!gameLevel)*7+3
else ((\x -> if x>0 then x-1 else x) $ charge me),
vgun = unitVector $ aimX:+aimY,
velocity = if charge me >0 then 0:+0 else
if magnitude v <= 0.01 then (
if realPart(position vicViper - pos)>0 then 3:+0 else (-3):+0
) else if touched then
((realPart v):+(-imagPart vgrav))
else (realPart v:+(imagPart vgrav)),
touchedLand = False
}]++myShots where
aimX:+aimY = position vicViper - pos
aimRate = (-(signum$realPart v))*aimX / (abs(aimY) +0.1)
myShots = if charge me `mod` 7 /= 6 then [] else
map (\w -> freshDiamondBomb{position=pos,velocity=w}) vs
vs = map (\vy -> (vgun me)*(bacterianShotSpeed:+(1.5*(vy)))) [-duckerShotWay!!gameLevel+1 , -duckerShotWay!!gameLevel+3 .. duckerShotWay!!gameLevel-0.9]
updateGameObject me@Jumper{position=pos@(_:+_),velocity = v,age=_,gravity= g,touchedLand = touched} =
if hp me <=0 then ([freshScore 300] ++ freshExplosions pos ++if hasItem me then [freshPowerUpCapsule{position=pos}] else[]) else
[
me{
position = pos + v,
velocity = if touched then (signum(realPart $ position vicViper-pos)*abs(realPart v):+imagPart(jumpSize*g)) else v + g,
jumpCounter = (if touched && v`innerProduct` g >0 then (+1) else id) $
(if doesShot then (+1) else id) $ jumpCounter me,
touchedLand = False
}
] ++shots where
jumpSize = if jumpCounter me `mod` 4 == 2 then (-30) else (-20)
doesShot = jumpCounter me `mod` 4 == 2 && v`innerProduct` g >0
shots = if doesShot then
map (\theta -> freshDiamondBomb{position=pos,velocity=mkPolar (bacterianShotSpeed*jumperShotFactor!!gameLevel) theta}) $
take way $ iterate (+(2*pi/intToDouble way)) 0
else []
way=jumperShotWay!!gameLevel
updateGameObject me@ScrambleHatch{position = pos,age=a} =
if hp me <=0 then [freshScore 3000] ++ freshMiddleExplosions pos ++
if scrambleHatchHitBack!!gameLevel then hatchHitBacks else []
else
[me{
age = a + 1,
gateAngle = max 0$ min pi$ (if length currentLaunches>0 then (+1) else (+(-0.05))) $ gateAngle me
}] ++ currentLaunches where
currentLaunches = if a <= scrambleHatchLaunchLimitAge!!gameLevel then
(map (\obj -> obj{position = pos}) $ launchProgram me!!a)
else []
hatchHitBacks =
(map (\theta -> freshDiamondBomb{position=pos-16*gravity me,velocity=mkPolar (bacterianShotSpeed*0.5) theta}) $ take way $ iterate (+2*pi/intToDouble way) 0 )++
(map (\theta -> freshDiamondBomb{position=pos-16*gravity me,velocity=mkPolar (bacterianShotSpeed*0.4) theta}) $ take way $ iterate (+2*pi/intToDouble way) (pi/intToDouble way) )
way = 16
updateGameObject me@Grashia{position = pos} =
if hp me <=0 then ([freshScore 150] ++ freshExplosions pos++ if hasItem me then [freshPowerUpCapsule{position=pos}] else[]) else
[
me{
age=age me+1,
gunVector = unitVector $ position vicViper - pos,
position = position me + ((-3)*sin(intToDouble (age me*mode me)/8):+0)
} --V no shotto wo osoku
] ++ if age me `mod` myInterval == 0 && age me `mod` 200 > grashiaShotHalt!!gameLevel then
[jikiNeraiDanAc (pos+gunVector me*(16:+0)) (grashiaShotSpeedFactor!!gameLevel*bacterianShotSpeed:+0) 64] else [] where
myInterval = if mode me == 0 then grashiaShotInterval!!gameLevel else landRollShotInterval!!gameLevel
updateGameObject me@Particle{position = pos} =
if age me > expireAge me then (if particleHitBack!!gameLevel then [freshScore 10,scatteredNeraiDan pos (bacterianShotSpeed:+0)] else []) else
[me{
age = age me + 1,
position = position me + (decay:+0) * velocity me
}] where
decay = exp $ - intToDouble (age me) / decayTime me
updateGameObject me@LandScapeBlock{position = pos,velocity = v} = [me{position = pos+v}]
updateGameObject DebugMessage{} = []
updateGameObject ScoreFragment{} = []
updateGameObject me@SabbathicAgent{fever = f} = if gameClock variables>stageClearTime-180 then [] else [
me{
fever = if launch then f+1 else f
}]
++ if launch then map (\pos -> freshStalk{position = pos,velocity=(-4):+0,hasItem = (realPart pos>0 && (round $ imagPart pos :: Int) `mod` (3*round margin)==0)}) $
concat $ map (\t -> [(340:+t),((-340):+t),(t:+(260)),(t:+(-260))]) $[(-margin*df),(((negate margin) * df) + (margin * 2))..(margin*df+1)] else [] where
launch = (<=0) $ length $ filter (\obj -> case obj of
Flyer{} -> True
_ -> False) objects
df = intToDouble f - 1
margin :: Double
margin = 20
updateGameObject x = [x]
makeMetalionShots :: GameObject -> [GameObject]
{- this generates proper playerside bullets
according to the current power up state of vicviper.
both options and vicviper is updated using this. -}
makeMetalionShots obj = obj{reloadTime=reloadTime obj+penalty1+penalty2,
weaponEnergy = max 0 $ min 100 $ weaponEnergy obj + if doesLaser then (-10) else 50 }
:(shots ++ missiles) where
(shots,penalty1) = if doesNormal then ([freshStandardRailgun{position=position obj,parentTag=myTag}] ,2)
else if doesDouble then ([freshStandardRailgun{position=position obj,parentTag=myTag},freshStandardRailgun{position=position obj,parentTag=myTag,velocity=mkPolar 1 (pi/4)*velocity freshStandardRailgun}] ,2)
else if doesLaser then ([freshStandardLaser{position=position obj+(shotSpeed/2:+0),parentTag=myTag}] ,1)
else ([],0)
penalty2 = if weaponEnergy obj <= 0 then 8 else 0
missiles = if doesMissile then [freshStandardMissile{position=position obj}] else []
doesShot = (isJust $tag obj) && (reloadTime obj <=0) && (shotButton `elem` keys)
doesNormal = doesShot && elem NormalShot types && (shotCount<2)
doesDouble = doesShot && elem DoubleShot types && (shotCount<1)
doesLaser = doesShot && elem Laser types
doesMissile = (isJust $tag obj) && elem Missile types && (missileButton `elem` keys) && (missileCount<=0)
myTag = fromJust $ tag obj
shotCount = length $ filter (\o -> case o of
StandardRailgun{} -> parentTag o==myTag
_ -> False) objects
missileCount = length $ filter (\o -> case o of
StandardMissile{} -> True
_ -> False) objects
types = weaponTypes vicViper
jikiNeraiDan :: Complex Double -> Complex Double -> GameObject
-- an enemy bullet starting at position sourcePos and with relative velocity initVelocity.
-- bullet goes straight to vicviper if initVelocity is a positive real number.
jikiNeraiDanAc sourcePos initVelocity accuracy = freshDiamondBomb{
position = sourcePos,
velocity = (*initVelocity) $ (angleAccuracy accuracy) $ unitVector $ position vicViper - sourcePos
}
jikiNeraiDan sourcePos initVelocity = jikiNeraiDanAc sourcePos initVelocity 32
scatteredNeraiDan :: Complex Double -> Complex Double -> GameObject
-- a rather scattered jikiNeraiDan.
scatteredNeraiDan sourcePos initVelocity = freshDiamondBomb{
position = sourcePos,
velocity = scatter $ (*initVelocity) $ (angleAccuracy 32) $ unitVector $ position vicViper - sourcePos
} where
scatter z = let (r,theta)=polar z in
mkPolar r (theta+pi/8*((^(3::Int)).sin)((intToDouble $ gameClock variables) + magnitude sourcePos))
freshExplosionParticle pos vel a = Particle{tag=Nothing,position=pos,velocity=vel,size=8,particleColor=Color3 1 0.5 0,age=a,decayTime=6,expireAge=20}
freshExplosions pos = take 5 expls where
expls :: [GameObject]
expls = makeExp randoms
randoms = [square $ sin(9801*sqrt t*(intToDouble$gameClock variables) + magnitude pos)|t<-[1..]]
makeExp (a:b:c:xs) = (freshExplosionParticle pos (mkPolar (3*a) (2*pi*b)) (round $ -5*c)):makeExp xs
makeExp _ = []
freshMiddleExplosions pos = take 16 expls where
expls :: [GameObject]
expls = makeExp randoms 0
randoms = [square $ sin(8086*sqrt t*(intToDouble$gameClock variables) + magnitude pos)|t<-[1..]]
makeExp (a:b:xs) i = (freshExplosionParticle (pos+mkPolar 5 (pi/8*i)) (mkPolar (6+3*a) (pi/8*i)) (round $ -5*b)){size=16}:makeExp xs (i+1)
makeExp _ _ = []
-- issue tag so that each objcet has unique tag,
-- and every object will continue to hold the same tag.
issueTag :: Int -> [GameObject] -> (Int,[GameObject])
issueTag nt [] = (nt,[])
issueTag nt (x:xs) = (newNextTag,taggedX:taggedXs)
where
(nextTagForXs,taggedX) = if(isNothing $ tag x) then (nt+1,x{tag = Just nt}) else (nt,x)
(newNextTag,taggedXs) = issueTag nextTagForXs xs
collide :: [GameObject] -> [GameObject]
-- collide a list of GameObjects and return the result.
-- it is important NOT to delete any object at the collision -- collide, show then delete
collide = map personalCollide
where
-- each object has its own hitClasses and weakPoints.
-- collision is not symmetric: A may crushed by B while B doesn't feel A.
-- object X is hit by only objectsWhoseHitClassIsMyWeakPoint X.
personalCollide :: GameObject -> GameObject
personalCollide obj = foldr check obj $ objectsWhoseHitClassIsMyWeakPoint obj
objectsWhoseHitClassIsMyWeakPoint :: GameObject -> [GameObject]
objectsWhoseHitClassIsMyWeakPoint me =
filter (\him -> not $ null $ (weakPoint me) `intersect` (hitClass him)) objects
hitClass :: GameObject -> [HitClass]
hitClass VicViper{} = [MetalionBody,ItemReceiver]
hitClass StandardMissile{} = [MetalionShot]
hitClass StandardRailgun{} = [MetalionShot]
hitClass StandardLaser{} = [MetalionShot]
hitClass Shield{} = [MetalionBody]
hitClass PowerUpCapsule{} = [PowerUp]
hitClass DiamondBomb{} = [BacterianShot]
hitClass TurnGear{} = [BacterianBody]
hitClass Flyer{} = [BacterianBody]
hitClass Ducker{} = [BacterianBody]
hitClass Jumper{} = [BacterianBody]
hitClass Grashia{} = [BacterianBody]
hitClass ScrambleHatch{} = [BacterianBody,LaserAbsorber]
hitClass LandScapeBlock{} = [LandScape]
hitClass _ = []
weakPoint :: GameObject -> [HitClass]
weakPoint VicViper{} = [PowerUp,BacterianBody,BacterianShot,LandScape]
weakPoint StandardMissile{} = [BacterianBody,LandScape]
weakPoint Probe{} = [LandScape]
weakPoint StandardRailgun{} = [BacterianBody,LandScape]
weakPoint StandardLaser{} = [LaserAbsorber,LandScape]
weakPoint Shield{} = [BacterianBody,BacterianShot,LandScape]
weakPoint PowerUpCapsule{} = [ItemReceiver]
weakPoint DiamondBomb{} = [MetalionBody,LandScape]
weakPoint TurnGear{} = [MetalionBody,MetalionShot]
weakPoint Flyer{} = [MetalionBody,MetalionShot]
weakPoint Ducker{} = [MetalionBody,MetalionShot,LandScape]
weakPoint Jumper{} = [MetalionBody,MetalionShot,LandScape]
weakPoint Grashia{} = [MetalionBody,MetalionShot]
weakPoint ScrambleHatch{} = [MetalionBody,MetalionShot]
weakPoint _ = []
-- after matching hitClass-weakPoint, you must check the shape of the pair of object
-- to see if source really hits the target.
check :: GameObject -> GameObject -> GameObject
check source target = case (source, target) of
(LandScapeBlock{},StandardMissile{}) -> if(hit source target) then (affect source target2) else target2 where
target2 = target{probe = if(hit source p) then (affect source p) else p}
p = probe target
_ -> if(hit source target) then (affect source target) else target
-- if a is really hitting b, a affects b (usually, decreases hitpoint of b).
-- note that landScapeSensitive objects have special hitDispLand other than hitDisp.
-- this allows some weapons to go through narrow land features, and yet
-- wipe out wider area of enemies.
hit :: GameObject -> GameObject -> Bool
hit a b = case (a,b) of
(LandScapeBlock{},c) -> if landScapeSensitive c then (position a +> hitDisp a) >?< (position c +> hitDispLand c)
else (position a +> hitDisp a) >?< (position b +> hitDisp b)
_ -> (position a +> hitDisp a) >?< (position b +> hitDisp b)
affect :: GameObject -> GameObject -> GameObject
affect VicViper{} obj = case obj of
pow@PowerUpCapsule{} -> pow{hp = hp pow-1}
x -> x
affect PowerUpCapsule{} obj = case obj of
viper@VicViper{} -> viper{powerUpPointer = (\x -> if x >=5 then 0 else x+1)$powerUpPointer viper}
_ -> error "Power capsule should not have been able to affect anything but the player craft."
affect StandardMissile{} obj = obj{hp = hp obj-(hatchHP`div`2 + 2)} -- 2 missiles can destroy a hatch
affect StandardRailgun{} obj = obj{hp = hp obj-(hatchHP`div`4 + 1)} -- 4 shots can also destroy a hatch
affect StandardLaser{} obj = obj{hp = hp obj-1}
affect Shield{} obj = obj{hp = hp obj-1}
affect DiamondBomb{} obj = obj{hp = hp obj-1}
affect TurnGear{} obj = obj{hp = hp obj-1}
affect Flyer{} obj = obj{hp = hp obj-1}
affect Ducker{} obj= obj{hp = hp obj-1}
affect Jumper{} obj= obj{hp = hp obj-1}
affect Grashia{} obj= obj{hp = hp obj-1}
affect ScrambleHatch{} obj= obj{hp = hp obj-1}
affect LandScapeBlock{} obj = case obj of
-- miso@StandardMissile{velocity=v} -> miso{velocity = (1:+0)*abs v}
duck@Ducker{} -> duck{touchedLand=True}
that@Jumper{} -> that{touchedLand=True}
_ -> obj{hp = hp obj-1}
affect _ t = t
scroll :: GameObject -> Maybe GameObject
-- make an object scroll.
-- if the object is to vanish out of the screen, it becomes Nothing.
scroll obj = let
(x:+y) = position obj
scrollBehavior :: GameObject -> ScrollBehavior
scrollBehavior VicViper{} = Enclosed False
scrollBehavior Option {} = NoRollOut False
-- We use the more verbose way of setting records here to guarantee
-- 'range' is needed so -Wall doesn't get fooled.
scrollBehavior StandardRailgun{} = RollOutAuto True shotSpeed
scrollBehavior StandardLaser{} = RollOutAuto True laserSpeed
scrollBehavior PowerUpGauge{} = NoRollOut False
scrollBehavior PowerUpCapsule{} = RollOutAuto True 40
scrollBehavior Shield{} = NoRollOut False
scrollBehavior DiamondBomb{} = RollOutAuto False 10
scrollBehavior TurnGear{} = RollOutAuto False 20
scrollBehavior SquadManager{} = NoRollOut False
scrollBehavior ScrambleHatch{} = RollOutAuto True 60
scrollBehavior LandScapeBlock{} = RollOutAuto True 160
scrollBehavior Star{} = RollOutFold True
scrollBehavior DebugMessage{} = NoRollOut False
scrollBehavior ScoreFragment{} = NoRollOut False
scrollBehavior SabbathicAgent{} = NoRollOut False
scrollBehavior _ = RollOutAuto True 40
scrollSpeed = if hp vicViper <= 0 then 0 else if gameClock variables <=6400 then 1 else 2
rolledObj = if doesScroll $ scrollBehavior obj then obj{position=(x-scrollSpeed):+y} else obj
in case scrollBehavior obj of
Enclosed _ -> Just rolledObj{position = (max (-300) $ min 280 x):+(max (-230) $ min 230 y)}
NoRollOut _ -> Just rolledObj
RollOutAuto _ r -> if any (>r) [x-320,(-320)-x,y-240,(-240)-y] then Nothing
else Just rolledObj
RollOutFold _ -> Just rolledObj{position = (if x< -320 then x+640 else x):+y} where
(_:+_) = position rolledObj
clock = gameClock variables
isEasy = gameLevel <= 1
vicViper = fromJust $ find (\obj -> case obj of
VicViper{} -> True
_ -> False) objects
-- things needed both for progress and rendering
weaponTypes :: GameObject -> [WeaponType]
weaponTypes viper@VicViper{}
| check gaugeOfDouble = DoubleShot : missile
| check gaugeOfLaser = Laser : missile
| otherwise = NormalShot : missile
where
check g = powerUpLevels viper!g>0
missile = if check gaugeOfMissile then [Missile] else []
weaponTypes _ = []
isMonadiusOver :: Monadius -> Bool
isMonadiusOver (Monadius (vars,_)) = flagGameover vars
|
keqh/Monadius_rewrite
|
Monadius/Monadius.hs
|
gpl-2.0
| 30,322 | 1 | 24 | 7,508 | 10,249 | 5,594 | 4,655 | 461 | 201 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : ./HasCASL/As.hs
Description : abstract syntax for HasCASL
Copyright : (c) Christian Maeder and Uni Bremen 2003-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : experimental
Portability : portable
abstract syntax for HasCASL,
more liberal than Concrete-Syntax.txt,
annotations are almost as for CASL
-}
module HasCASL.As where
import Common.Id
import Common.Keywords
import Common.AS_Annotation
import Data.Data
import qualified Data.Set as Set
-- * abstract syntax entities with small utility functions
-- | annotated basic items
data BasicSpec = BasicSpec [Annoted BasicItem] deriving (Show, Typeable, Data)
-- | the possible items
data BasicItem =
SigItems SigItems
| ProgItems [Annoted ProgEq] Range
-- pos "program", dots
| ClassItems Instance [Annoted ClassItem] Range
-- pos "class", ";"s
| GenVarItems [GenVarDecl] Range
-- pos "var", ";"s
| FreeDatatype [Annoted DatatypeDecl] Range
-- pos "free", "type", ";"s
| GenItems [Annoted SigItems] Range
{- pos "generated" "{", ";"s, "}"
or "generated" "type" ";"s -}
| AxiomItems [GenVarDecl] [Annoted Term] Range
-- pos "forall" (if GenVarDecl not empty), dots
| Internal [Annoted BasicItem] Range
-- pos "internal" "{", ";"s, "}"
deriving (Show, Typeable, Data)
-- | signature items are types or functions
data SigItems =
TypeItems Instance [Annoted TypeItem] Range {- including sort
pos "type", ";"s -}
| OpItems OpBrand [Annoted OpItem] Range
-- pos "op", ";"s
deriving (Show, Typeable, Data)
-- | indicator for predicate, operation or function
data OpBrand = Pred | Op | Fun deriving (Eq, Ord, Typeable, Data)
-- | test if the function was declared as predicate
isPred :: OpBrand -> Bool
isPred b = case b of
Pred -> True
_ -> False
instance Show OpBrand where
show b = case b of
Pred -> predS
Op -> opS
Fun -> functS
-- | indicator in 'ClassItems' and 'TypeItems'
data Instance = Instance | Plain deriving (Eq, Ord, Typeable, Data)
instance Show Instance where
show i = case i of
Instance -> instanceS
Plain -> ""
-- | a class item
data ClassItem = ClassItem ClassDecl [Annoted BasicItem] Range
deriving (Show, Typeable, Data)
-- pos "{", ";"s "}"
-- | declaring class identifiers
data ClassDecl = ClassDecl [Id] Kind Range deriving (Show, Typeable, Data)
-- pos ","s
-- | co- or contra- variance indicator
data Variance = InVar | CoVar | ContraVar | NonVar
deriving (Eq, Ord, Typeable, Data)
instance Show Variance where
show v = case v of
InVar -> plusS ++ minusS
CoVar -> plusS
ContraVar -> minusS
NonVar -> ""
-- | (higher) kinds
data AnyKind a =
ClassKind a
| FunKind Variance (AnyKind a) (AnyKind a) Range
-- pos "+" or "-"
deriving (Show, Typeable, Data)
instance Ord a => Eq (AnyKind a) where
k1 == k2 = compare k1 k2 == EQ
instance Ord a => Ord (AnyKind a) where
compare k1 k2 = case (k1, k2) of
(ClassKind c1, ClassKind c2) -> compare c1 c2
(ClassKind _, _) -> LT
(FunKind v1 k3 k4 _, FunKind v2 k5 k6 _) ->
compare (v1, k3, k4) (v2, k5, k6)
_ -> GT
type Kind = AnyKind Id
type RawKind = AnyKind ()
-- | the possible type items
data TypeItem =
TypeDecl [TypePattern] Kind Range
-- pos ","s
| SubtypeDecl [TypePattern] Type Range
-- pos ","s, "<"
| IsoDecl [TypePattern] Range
-- pos "="s
| SubtypeDefn TypePattern Vars Type (Annoted Term) Range
-- pos "=", "{", ":", dot, "}"
| AliasType TypePattern (Maybe Kind) TypeScheme Range
-- pos ":="
| Datatype DatatypeDecl
deriving (Show, Typeable, Data)
-- | a tuple pattern for 'SubtypeDefn'
data Vars = Var Id | VarTuple [Vars] Range
deriving (Show, Eq, Ord, Typeable, Data)
-- | the lhs of most type items
data TypePattern =
TypePattern Id [TypeArg] Range
-- pos "("s, ")"s
| TypePatternToken Token
| MixfixTypePattern [TypePattern]
| BracketTypePattern BracketKind [TypePattern] Range
-- pos brackets (no parenthesis)
| TypePatternArg TypeArg Range
-- pos "(", ")"
deriving (Show, Typeable, Data)
-- | types based on variable or constructor names and applications
data Type =
TypeName Id RawKind Int
-- Int == 0 means constructor, negative are bound variables
| TypeAppl Type Type
| ExpandedType Type Type {- an alias type with its expansion
only the following variants are parsed -}
| TypeAbs TypeArg Type Range
| KindedType Type (Set.Set Kind) Range
-- pos ":"
| TypeToken Token
| BracketType BracketKind [Type] Range
-- pos "," (between type arguments)
| MixfixType [Type]
deriving (Show, Typeable, Data)
-- | change the type within a scheme
mapTypeOfScheme :: (Type -> Type) -> TypeScheme -> TypeScheme
mapTypeOfScheme f (TypeScheme args t ps) = TypeScheme args (f t) ps
{- | a type with bound type variables. The bound variables within the
scheme should have negative numbers in the order given by the type
argument list. The type arguments store proper kinds (including
downsets) whereas the kind within the type names are only raw
kinds. -}
data TypeScheme = TypeScheme [TypeArg] Type Range
deriving (Show, Eq, Ord, Typeable, Data)
{- pos "forall", ";"s, dot (singleton list)
pos "\" "("s, ")"s, dot for type aliases -}
-- | indicator for partial or total functions
data Partiality = Partial | Total deriving (Eq, Ord, Typeable, Data)
instance Show Partiality where
show p = case p of
Partial -> quMark
Total -> exMark
-- | function declarations or definitions
data OpItem =
OpDecl [PolyId] TypeScheme [OpAttr] Range
-- pos ","s, ":", ","s, "assoc", "comm", "idem", "unit"
| OpDefn PolyId [[VarDecl]] TypeScheme Term Range
-- pos "("s, ";"s, ")"s, ":" and "="
deriving (Show, Typeable, Data)
-- | attributes without arguments for binary functions
data BinOpAttr = Assoc | Comm | Idem deriving (Eq, Ord, Typeable, Data)
instance Show BinOpAttr where
show a = case a of
Assoc -> assocS
Comm -> commS
Idem -> idemS
-- | possible function attributes (including a term as a unit element)
data OpAttr =
BinOpAttr BinOpAttr Range
| UnitOpAttr Term Range deriving (Show, Typeable, Data)
instance Eq OpAttr where
o1 == o2 = compare o1 o2 == EQ
instance Ord OpAttr where
compare o1 o2 = case (o1, o2) of
(BinOpAttr b1 _, BinOpAttr b2 _) -> compare b1 b2
(BinOpAttr _ _, _) -> LT
(UnitOpAttr t1 _, UnitOpAttr t2 _) -> compare t1 t2
_ -> GT
-- | a polymorphic data type declaration with a deriving clause
data DatatypeDecl =
DatatypeDecl TypePattern Kind [Annoted Alternative] [Id] Range
-- pos "::=", "|"s, "deriving"
deriving (Show, Typeable, Data)
{- | Alternatives are subtypes or a constructor with a list of
(curried) tuples as arguments. Only the components of the first tuple
can be addressed by the places of the mixfix constructor. -}
data Alternative =
Constructor Id [[Component]] Partiality Range
-- pos: "("s, ";"s, ")"s, "?"
| Subtype [Type] Range
-- pos: "type", ","s
deriving (Show, Typeable, Data)
{- | A component is a type with on optional (only pre- or postfix)
selector function. -}
data Component =
Selector Id Partiality Type SeparatorKind Range
-- pos ",", ":" or ":?"
| NoSelector Type
deriving (Show, Eq, Ord, Typeable, Data)
-- | the possible quantifiers
data Quantifier = Universal | Existential | Unique
deriving (Show, Eq, Ord, Typeable, Data)
-- | the possibly type annotations of terms
data TypeQual = OfType | AsType | InType | Inferred
deriving (Show, Eq, Ord, Typeable, Data)
-- | an indicator of (otherwise equivalent) let or where equations
data LetBrand = Let | Where | Program deriving (Show, Eq, Ord, Typeable, Data)
-- | the possible kinds of brackets (that should match when parsed)
data BracketKind = Parens | Squares | Braces | NoBrackets
deriving (Show, Eq, Ord, Typeable, Data)
-- | the brackets as strings for printing
getBrackets :: BracketKind -> (String, String)
getBrackets b = case b of
Parens -> ("(", ")")
Squares -> ("[", "]")
Braces -> ("{", "}")
NoBrackets -> ("", "") -- for printing only
data InstKind = UserGiven | Infer deriving (Show, Eq, Ord, Typeable, Data)
{- | The possible terms and patterns. Formulas are also kept as
terms. Local variables and constants are kept separatetly. The variant
'ResolvedMixTerm' is an intermediate representation for type checking
only. -}
data Term =
QualVar VarDecl
-- pos "(", "var", ":", ")"
| QualOp OpBrand PolyId TypeScheme [Type] InstKind Range
-- pos "(", "op", ":", ")"
| ApplTerm Term Term Range {- analysed
pos? -}
| TupleTerm [Term] Range {- special application
pos "(", ","s, ")" -}
| TypedTerm Term TypeQual Type Range
-- pos ":", "as" or "in"
| AsPattern VarDecl Term Range
{- pos "@"
patterns are terms constructed by the first six variants -}
| QuantifiedTerm Quantifier [GenVarDecl] Term Range
{- pos quantifier, ";"s, dot
only "forall" may have a TypeVarDecl -}
| LambdaTerm [Term] Partiality Term Range
-- pos "\", dot (plus "!")
| CaseTerm Term [ProgEq] Range
-- pos "case", "of", "|"s
| LetTerm LetBrand [ProgEq] Term Range
-- pos "where", ";"s
| ResolvedMixTerm Id [Type] [Term] Range
| TermToken Token
| MixTypeTerm TypeQual Type Range
| MixfixTerm [Term]
| BracketTerm BracketKind [Term] Range
-- pos brackets, ","s
deriving (Show, Eq, Ord, Typeable, Data)
-- | an equation or a case as pair of a pattern and a term
data ProgEq = ProgEq Term Term Range deriving (Show, Eq, Ord, Typeable, Data)
-- pos "=" (or "->" following case-of)
-- | an identifier with an optional list of type declarations
data PolyId = PolyId Id [TypeArg] Range deriving (Show, Eq, Ord, Typeable, Data)
-- pos "[", ",", "]"
{- | an indicator if variables were separated by commas or by separate
declarations -}
data SeparatorKind = Comma | Other deriving (Show, Typeable, Data)
-- ignore all separator kinds in comparisons
instance Eq SeparatorKind where
_ == _ = True
-- Ord must be consistent with Eq
instance Ord SeparatorKind where
compare _ _ = EQ
-- | a variable with its type
data VarDecl = VarDecl Id Type SeparatorKind Range
deriving (Show, Eq, Ord, Typeable, Data)
-- pos "," or ":"
-- | the kind of a type variable (or a type argument in schemes)
data VarKind = VarKind Kind | Downset Type | MissingKind
deriving (Show, Eq, Ord, Typeable, Data)
-- | a (simple) type variable with its kind (or supertype)
data TypeArg =
TypeArg Id Variance VarKind RawKind Int SeparatorKind Range
-- pos "," or ":", "+" or "-"
deriving (Show, Typeable, Data)
-- | a value or type variable
data GenVarDecl =
GenVarDecl VarDecl
| GenTypeVarDecl TypeArg
deriving (Show, Eq, Ord, Typeable, Data)
{- * symbol data types
symbols -}
data SymbItems =
SymbItems SymbKind [Symb] [Annotation] Range
deriving (Show, Eq, Ord, Typeable, Data)
-- pos: kind, commas
-- | mapped symbols
data SymbMapItems =
SymbMapItems SymbKind [SymbOrMap] [Annotation] Range
deriving (Show, Eq, Ord, Typeable, Data)
-- pos: kind commas
-- | kind of symbols
data SymbKind =
Implicit
| SyKtype
| SyKsort
| SyKfun
| SyKop
| SyKpred
| SyKclass
deriving (Show, Eq, Ord, Typeable, Data)
-- | type annotated symbols
data Symb = Symb Id (Maybe SymbType) Range
deriving (Show, Eq, Ord, Typeable, Data)
-- pos: colon (or empty)
-- | type for symbols
data SymbType = SymbType TypeScheme deriving (Show, Eq, Ord, Typeable, Data)
-- | mapped symbol
data SymbOrMap = SymbOrMap Symb (Maybe Symb) Range
deriving (Show, Eq, Ord, Typeable, Data)
-- pos: "|->" (or empty)
-- * equality instances ignoring positions
instance Eq Type where
t1 == t2 = compare t1 t2 == EQ
instance Ord Type where
compare ty1 ty2 = case (ty1, ty2) of
(TypeName i1 k1 v1, TypeName i2 k2 v2) ->
if v1 == 0 && v2 == 0 then compare (i1, k1) (i2, k2)
else compare (v1, k1) (v2, k2)
(TypeAppl f1 a1, TypeAppl f2 a2) -> compare (f1, a1) (f2, a2)
(TypeAbs v1 a1 _, TypeAbs v2 a2 _) -> compare (v1, a1) (v2, a2)
(TypeToken t1, TypeToken t2) -> compare t1 t2
(BracketType b1 l1 _, BracketType b2 l2 _) -> compare (b1, l1) (b2, l2)
(KindedType t1 k1 _, KindedType t2 k2 _) -> compare (t1, k1) (t2, k2)
(MixfixType l1, MixfixType l2) -> compare l1 l2
(ExpandedType _ t1, t2) -> compare t1 t2
(t1, ExpandedType _ t2) -> compare t1 t2
(TypeName {}, _) -> LT
(_, TypeName {}) -> GT
(TypeAppl {}, _) -> LT
(_, TypeAppl {}) -> GT
(TypeAbs {}, _) -> LT
(_, TypeAbs {}) -> GT
(TypeToken _, _) -> LT
(_, TypeToken _) -> GT
(BracketType {}, _) -> LT
(_, BracketType {}) -> GT
(KindedType {}, _) -> LT
(_, KindedType {}) -> GT
-- used within quantified formulas
instance Eq TypeArg where
t1 == t2 = compare t1 t2 == EQ
instance Ord TypeArg where
compare (TypeArg i1 v1 e1 r1 c1 _ _) (TypeArg i2 v2 e2 r2 c2 _ _) =
if c1 < 0 && c2 < 0 then compare (v1, e1, r1, c1) (v2, e2, r2, c2)
else compare (i1, v1, e1, r1, c1) (i2, v2, e2, r2, c2)
-- * compute better position
-- | get a reasonable position for a list with an additional position list
bestRange :: GetRange a => [a] -> Range -> Range
bestRange l (Range ps) = Range (rangeToList (getRange l) ++ ps)
instance GetRange OpAttr where
getRange a = case a of
BinOpAttr _ r -> r
UnitOpAttr _ r -> r
instance GetRange Type where
getRange ty = case ty of
TypeName i _ _ -> posOfId i
TypeAppl t1 t2 -> getRange [t1, t2]
TypeAbs _ t ps -> bestRange [t] ps
ExpandedType t1 t2 -> getRange [t1, t2]
TypeToken t -> tokPos t
BracketType _ ts ps -> bestRange ts ps
KindedType t _ ps -> bestRange [t] ps
MixfixType ts -> getRange ts
instance GetRange Term where
getRange trm = case trm of
QualVar v -> getRange v
QualOp _ (PolyId i _ _) _ _ _ qs -> bestRange [i] qs
ResolvedMixTerm i _ _ _ -> posOfId i
ApplTerm t1 t2 ps -> bestRange [t1, t2] ps
TupleTerm ts ps -> bestRange ts ps
TypedTerm t _ _ ps -> bestRange [t] ps
QuantifiedTerm _ _ t ps -> bestRange [t] ps
LambdaTerm _ _ t ps -> bestRange [t] ps
CaseTerm t _ ps -> bestRange [t] ps
LetTerm _ _ t ps -> bestRange [t] ps
TermToken t -> tokPos t
MixTypeTerm _ t ps -> bestRange [t] ps
MixfixTerm ts -> getRange ts
BracketTerm _ ts ps -> bestRange ts ps
AsPattern v _ ps -> bestRange [v] ps
instance GetRange TypePattern where
getRange pat = case pat of
TypePattern t _ ps -> bestRange [t] ps
TypePatternToken t -> tokPos t
MixfixTypePattern ts -> getRange ts
BracketTypePattern _ ts ps -> bestRange ts ps
TypePatternArg (TypeArg t _ _ _ _ _ _) ps -> bestRange [t] ps
instance GetRange VarDecl where
getRange (VarDecl v _ _ p) = bestRange [v] p
instance GetRange TypeArg where
getRange (TypeArg v _ _ _ _ _ p) = bestRange [v] p
instance GetRange TypeScheme where
getRange (TypeScheme args t ps) = bestRange args $ bestRange [t] ps
instance GetRange BasicSpec
|
gnn/Hets
|
HasCASL/As.hs
|
gpl-2.0
| 15,375 | 0 | 12 | 3,627 | 4,333 | 2,333 | 2,000 | 280 | 4 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram
-- Copyright : (c) Sven Panne 2002-2009
-- License : BSD-style (see the file libraries/OpenGL/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
--
-- This module corresponds to a part of section 3.6.1 (Pixel Storage Modes) of
-- the OpenGL 2.1 specs.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.PixelRectangles.Histogram (
Sink(..), histogram, Reset(..), getHistogram, resetHistogram,
histogramRGBASizes, histogramLuminanceSize
) where
import Data.StateVar
import Foreign.Marshal.Alloc
import Graphics.Rendering.OpenGL.GL.Capability
import Graphics.Rendering.OpenGL.GL.PeekPoke
import Graphics.Rendering.OpenGL.GL.PixelData
import Graphics.Rendering.OpenGL.GL.PixelRectangles.ColorTable
import Graphics.Rendering.OpenGL.GL.PixelRectangles.Reset
import Graphics.Rendering.OpenGL.GL.PixelRectangles.Sink
import Graphics.Rendering.OpenGL.GL.Texturing.PixelInternalFormat
import Graphics.Rendering.OpenGL.GL.VertexSpec
import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility (
glGetHistogram, glGetHistogramParameteriv, glHistogram, glResetHistogram,
gl_HISTOGRAM, gl_HISTOGRAM_ALPHA_SIZE, gl_HISTOGRAM_BLUE_SIZE,
gl_HISTOGRAM_FORMAT, gl_HISTOGRAM_GREEN_SIZE, gl_HISTOGRAM_LUMINANCE_SIZE,
gl_HISTOGRAM_RED_SIZE, gl_HISTOGRAM_SINK, gl_HISTOGRAM_WIDTH,
gl_PROXY_HISTOGRAM )
import Graphics.Rendering.OpenGL.Raw.Core31
--------------------------------------------------------------------------------
data HistogramTarget =
Histogram
| ProxyHistogram
marshalHistogramTarget :: HistogramTarget -> GLenum
marshalHistogramTarget x = case x of
Histogram -> gl_HISTOGRAM
ProxyHistogram -> gl_PROXY_HISTOGRAM
proxyToHistogramTarget :: Proxy -> HistogramTarget
proxyToHistogramTarget x = case x of
NoProxy -> Histogram
Proxy -> ProxyHistogram
--------------------------------------------------------------------------------
histogram :: Proxy -> StateVar (Maybe (GLsizei, PixelInternalFormat, Sink))
histogram proxy =
makeStateVarMaybe
(return CapHistogram) (getHistogram' proxy) (setHistogram proxy)
getHistogram' :: Proxy -> IO (GLsizei, PixelInternalFormat, Sink)
getHistogram' proxy = do
w <- getHistogramParameteri fromIntegral proxy HistogramWidth
f <- getHistogramParameteri unmarshalPixelInternalFormat proxy HistogramFormat
s <- getHistogramParameteri unmarshalSink proxy HistogramSink
return (w, f, s)
getHistogramParameteri ::
(GLint -> a) -> Proxy -> GetHistogramParameterPName -> IO a
getHistogramParameteri f proxy p =
alloca $ \buf -> do
glGetHistogramParameteriv
(marshalHistogramTarget (proxyToHistogramTarget proxy))
(marshalGetHistogramParameterPName p)
buf
peek1 f buf
setHistogram :: Proxy -> (GLsizei, PixelInternalFormat, Sink) -> IO ()
setHistogram proxy (w, int, sink) =
glHistogram
(marshalHistogramTarget (proxyToHistogramTarget proxy))
w
(marshalPixelInternalFormat' int)
(marshalSink sink)
--------------------------------------------------------------------------------
getHistogram :: Reset -> PixelData a -> IO ()
getHistogram reset pd =
withPixelData pd $
glGetHistogram
(marshalHistogramTarget Histogram)
(marshalReset reset)
--------------------------------------------------------------------------------
resetHistogram :: IO ()
resetHistogram = glResetHistogram (marshalHistogramTarget Histogram)
--------------------------------------------------------------------------------
data GetHistogramParameterPName =
HistogramWidth
| HistogramFormat
| HistogramRedSize
| HistogramGreenSize
| HistogramBlueSize
| HistogramAlphaSize
| HistogramLuminanceSize
| HistogramSink
marshalGetHistogramParameterPName :: GetHistogramParameterPName -> GLenum
marshalGetHistogramParameterPName x = case x of
HistogramWidth -> gl_HISTOGRAM_WIDTH
HistogramFormat -> gl_HISTOGRAM_FORMAT
HistogramRedSize -> gl_HISTOGRAM_RED_SIZE
HistogramGreenSize -> gl_HISTOGRAM_GREEN_SIZE
HistogramBlueSize -> gl_HISTOGRAM_BLUE_SIZE
HistogramAlphaSize -> gl_HISTOGRAM_ALPHA_SIZE
HistogramLuminanceSize -> gl_HISTOGRAM_LUMINANCE_SIZE
HistogramSink -> gl_HISTOGRAM_SINK
--------------------------------------------------------------------------------
histogramRGBASizes :: Proxy -> GettableStateVar (Color4 GLsizei)
histogramRGBASizes proxy =
makeGettableStateVar $ do
r <- getHistogramParameteri fromIntegral proxy HistogramRedSize
g <- getHistogramParameteri fromIntegral proxy HistogramGreenSize
b <- getHistogramParameteri fromIntegral proxy HistogramBlueSize
a <- getHistogramParameteri fromIntegral proxy HistogramAlphaSize
return $ Color4 r g b a
histogramLuminanceSize :: Proxy -> GettableStateVar GLsizei
histogramLuminanceSize proxy =
makeGettableStateVar $
getHistogramParameteri fromIntegral proxy HistogramLuminanceSize
|
ducis/haAni
|
hs/common/Graphics/Rendering/OpenGL/GL/PixelRectangles/Histogram.hs
|
gpl-2.0
| 5,186 | 0 | 13 | 701 | 895 | 498 | 397 | 96 | 8 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Window
-- Copyright : (c) 2014 Ian-Woo Kim
--
-- License : BSD3
-- Maintainer : Ian-Woo Kim <[email protected]>
-- Stability : experimental
-- Portability : GHC
--
-----------------------------------------------------------------------------
module Window where
import Control.Concurrent
import Control.Monad (when)
import qualified Data.Foldable as F (mapM_,forM_)
import Data.List.Split (splitOn)
import qualified Data.Map as M
import Data.Maybe (mapMaybe)
import qualified Data.Text as T
import DBus
import DBus.Client
import System.Exit
import System.FilePath
import System.Process
data WindowInfo = WInfo { windowId :: String
, desktopId :: String
, processId :: String
, hostName :: String
, windowTitle :: String }
deriving (Show,Eq,Ord)
server :: Client -> IO ()
server client = do
listen client matchAny { matchInterface = Just "org.ianwookim.hoodle"
, matchMember = Just "findWindow"
}
findWindow
findWindow :: Signal -> IO ()
findWindow sig = do
let txts = mapMaybe fromVariant (signalBody sig) :: [String]
when ((not.null) txts) $ do
let fpath = head txts
(fdir,fname) = splitFileName fpath
print fname
mwid <- getWindow fname
print mwid
case mwid of
Nothing -> createProcess (proc "hoodle" [fpath])
>> return ()
Just wid -> do
(excode,sout,serr) <- readProcessWithExitCode "wmctrl" [ "-i", "-a", wid ] ""
print excode
return ()
getWindow :: String -> IO (Maybe String)
getWindow title = do
putStrLn "Window server process"
(excode,sout,serr) <- readProcessWithExitCode "wmctrl" [ "-l", "-p" ] ""
case excode of
ExitSuccess -> do
let xs = lines sout
mkWInfo x =
let rest0 = dropWhile (== ' ') x
(wid,rest1) = break (== ' ') rest0
(did,rest2) = (break (== ' ') . dropWhile (== ' ')) rest1
(pid,rest3) = (break (== ' ') . dropWhile (== ' ')) rest2
(hname,rest4) = (break (== ' ') . dropWhile (== ' ')) rest3
title = dropWhile (== ' ') rest4
in WInfo wid did pid hname title
insertToMap x = M.insert (windowTitle x) x
wmap = foldr insertToMap M.empty (map mkWInfo xs)
F.mapM_ print wmap
case M.lookup title wmap of
Nothing -> return Nothing
Just w -> return (Just (windowId w))
ExitFailure _ -> return Nothing
serverLink :: Client -> IO ()
serverLink client = do
putStrLn "start serverLink"
listen
client
matchAny { matchInterface = Just "org.ianwookim.hoodle"
, matchMember = Just "callLink" }
(callLink client)
callLink :: Client -> Signal -> IO ()
callLink cli sig = do
let txts = mapMaybe fromVariant (signalBody sig) :: [String]
case txts of
txt : _ -> do
let r = splitOn "," txt
case r of
docid:anchorid:_ -> do
emit cli (signal "/" "org.ianwookim.hoodle" "link")
{ signalBody = [ toVariant txt ] }
putStrLn ( docid ++ ":" ++ anchorid)
_ -> return ()
_ -> return ()
|
wavewave/hoodle-daemon
|
exe/Window.hs
|
gpl-2.0
| 3,591 | 2 | 23 | 1,222 | 1,046 | 541 | 505 | 84 | 3 |
module Utility ((//), (<$>), (<*>), date, Replacer, Filter, filterReplace, readProcessLBS, assert) where
import System.Time (getClockTime, toCalendarTime, formatCalendarTime)
import System.Locale (defaultTimeLocale)
import Data.Functor ((<$>))
import Data.List (mapAccumL)
import Data.List.Split (splitOn)
import qualified Data.Map.Strict as Map
import Data.Map.Strict (Map, (!), (\\), keys)
import Data.Maybe (fromMaybe)
import Control.Applicative ((<*>))
import Control.Exception
import Control.Monad
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString as SB
import System.Process
import System.Exit (ExitCode)
import System.IO
import Control.Concurrent
forkWait :: IO a -> IO (IO a)
forkWait a = do
res <- newEmptyMVar
_ <- mask $ \restore -> forkIO $ try (restore a) >>= putMVar res
return (takeMVar res >>= either (\ex -> throwIO (ex :: SomeException)) return)
readProcessWithExitCodeBS :: FilePath -> [String] -> SB.ByteString -> IO (ExitCode, SB.ByteString, SB.ByteString)
readProcessWithExitCodeBS cmd args input = mask $ \restore -> do
(Just inh, Just outh, Just errh, pid) <- createProcess (proc cmd args) { std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe }
flip onException
(do hClose inh; hClose outh; hClose errh;
terminateProcess pid; waitForProcess pid) $ restore $ do
waitOut <- forkWait $ SB.hGetContents outh
waitErr <- forkWait $ SB.hGetContents errh
unless (SB.null input) $ do SB.hPutStr inh input; hFlush inh
hClose inh
out <- waitOut
err <- waitErr
hClose outh
hClose errh
ex <- waitForProcess pid
return (ex, out, err)
readProcessBS :: FilePath -> [String] -> SB.ByteString -> IO SB.ByteString
readProcessBS c a i = snd3 <$> readProcessWithExitCodeBS c a i
--readProcessWithExitCodeLBS :: FilePath -> [String] -> LB.ByteString -> IO (ExitCode, LB.ByteString, LB.ByteString)
--readProcessWithExitCodeLBS = (liftM \(x,o,e) -> LB.fromStrict) . readProcessWithExitCodeBS
readProcessLBS :: FilePath -> [String] -> LB.ByteString -> IO LB.ByteString
readProcessLBS c a i = LB.fromStrict <$> readProcessBS c a (LB.toStrict i)
x // y = fromIntegral x / fromIntegral y
fst3 (x,_,_) = x
snd3 (_,x,_) = x
thd3 (_,_,x) = x
date :: String -> IO String
date s = do
time <- getClockTime >>= toCalendarTime
return $ formatCalendarTime defaultTimeLocale s time
type Replacer = Map String String
type Filter = Map String (String -> String)
applyFilters :: Filter -> Replacer -> Replacer
applyFilters f r = Map.mapWithKey (f'' !) r
where
f' = map ((flip Map.insert) (id)) (keys (r \\ f))
f'' = ((flip $ foldr ($)) f') f
replaceCore :: Replacer -> [String] -> String
replaceCore r = concat . fromMaybe (error "Invalid parse") . g
where
g = sequence . f
f = (\(x, y) -> if odd x then y else Nothing:y) . mapAccumL (\a x -> (a + 1, if odd a then Map.lookup x r else return x)) 0
replace :: String -> Replacer -> String -> String
replace del r s = replaceCore r (splitOn del s)
filterReplace :: String -> Filter -> [Replacer] -> (String -> String)
filterReplace del f rs = replace del $ applyFilters f (Map.unions rs)
|
taktoa/TSBannerGen
|
src/Utility.hs
|
gpl-3.0
| 3,228 | 0 | 16 | 633 | 1,207 | 641 | 566 | -1 | -1 |
{-# LANGUAGE CPP #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Safe #-}
#endif
module IO (
Handle, HandlePosn,
IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
BufferMode(NoBuffering,LineBuffering,BlockBuffering),
SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
stdin, stdout, stderr,
openFile, hClose, hFileSize, hIsEOF, isEOF,
hSetBuffering, hGetBuffering, hFlush,
hGetPosn, hSetPosn, hSeek,
hWaitForInput, hReady, hGetChar, hGetLine, hLookAhead, hGetContents,
hPutChar, hPutStr, hPutStrLn, hPrint,
hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable,
isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError,
isFullError, isEOFError,
isIllegalOperation, isPermissionError, isUserError,
ioeGetErrorString, ioeGetHandle, ioeGetFileName,
try, bracket, bracket_,
-- ...and what the Prelude exports
IO, FilePath, IOError, ioError, userError, catch, interact,
putChar, putStr, putStrLn, print, getChar, getLine, getContents,
readFile, writeFile, appendFile, readIO, readLn
) where
import System.IO
import System.IO.Error
-- | The 'bracket' function captures a common allocate, compute, deallocate
-- idiom in which the deallocation step must occur even in the case of an
-- error during computation. This is similar to try-catch-finally in Java.
--
-- This version handles only IO errors, as defined by Haskell 98.
-- The version of @bracket@ in "Control.Exception" handles all exceptions,
-- and should be used instead.
bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket before after m = do
x <- before
rs <- try (m x)
_ <- after x
case rs of
Right r -> return r
Left e -> ioError e
-- | A variant of 'bracket' where the middle computation doesn't want @x@.
--
-- This version handles only IO errors, as defined by Haskell 98.
-- The version of @bracket_@ in "Control.Exception" handles all exceptions,
-- and should be used instead.
bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
bracket_ before after m = do
x <- before
rs <- try m
_ <- after x
case rs of
Right r -> return r
Left e -> ioError e
-- | The construct 'try' @comp@ exposes IO errors which occur within a
-- computation, and which are not fully handled.
--
-- Non-I\/O exceptions are not caught by this variant; to catch all
-- exceptions, use 'Control.Exception.try' from "Control.Exception".
try :: IO a -> IO (Either IOError a)
try f = catch (do r <- f
return (Right r))
(return . Left)
|
jwiegley/ghc-release
|
libraries/haskell98/IO.hs
|
gpl-3.0
| 2,733 | 0 | 11 | 709 | 556 | 322 | 234 | 50 | 2 |
module WildFire.WildFireModelDynamic where
import System.Random
import Data.Maybe
import Control.Monad.STM
import Control.Concurrent.STM.TVar
import qualified Data.Map as Map
import qualified PureAgentsConc as PA
type WFCellIdx = Int
type WFCellCoord = (Int, Int)
data WFCellState = Living | Burning | Dead deriving (Eq, Show)
type WFMsg = ()
data WFCell = WFCell {
cellIdx :: WFCellIdx,
coord :: WFCellCoord,
burnable :: Double,
cellState :: WFCellState
} deriving (Show)
data WFAgentState = WFAgentState {
cidx :: WFCellIdx,
rng :: StdGen
} deriving (Show)
type WFCellContainer = Map.Map WFCellIdx (TVar WFCell)
data WFEnvironment = WFEnvironment {
cells :: WFCellContainer,
cellLimits :: WFCellCoord -- NOTE: this will stay constant
-- TODO: add wind-direction
}
type WFAgent = PA.Agent WFMsg WFAgentState WFEnvironment
type WFTransformer = PA.AgentTransformer WFMsg WFAgentState WFEnvironment
type WFSimHandle = PA.SimHandle WFMsg WFAgentState WFEnvironment
burnPerTimeUnit :: Double
burnPerTimeUnit = 0.3
wfTransformer :: WFTransformer
wfTransformer (a, _) PA.Start = return a
wfTransformer ae (PA.Dt dt) = wfUpdtHandler ae dt
wfTransformer (a, e) (PA.Message m) = return a -- NOTE: in this case no messages are sent between agents
-- NOTE: an active agent is always burning: it can be understood as the process of a burning cell
wfUpdtHandler :: (WFAgent, WFEnvironment) -> Double -> STM WFAgent
wfUpdtHandler ae@(a, _) dt = do
hasBurnedDown <- burnDown ae dt
if hasBurnedDown then
killCellAndAgent ae
else
igniteRandomNeighbour ae
igniteRandomNeighbour :: (WFAgent, WFEnvironment) -> STM WFAgent
igniteRandomNeighbour ae@(a, e) = do
cell <- readTVar cVar
let (randCoord, g') = randomNeighbourCoord g (coord cell)
let a' = PA.updateState a (\sOld -> sOld { rng = g' } )
let randCellVarMaybe = cellByCoord e randCoord
maybe (return a') (igniteValidCell a) randCellVarMaybe
where
cVar = cellOfAgent ae
g = (rng (PA.state a))
igniteValidCell :: WFAgent -> TVar WFCell -> STM WFAgent
igniteValidCell a cVar = do
isLiving <- isLiving cVar
if isLiving then
igniteLivingCell a cVar
else
return a
igniteLivingCell :: WFAgent -> TVar WFCell -> STM WFAgent
igniteLivingCell a cVar = do
let g = (rng (PA.state a))
(aNew, g') <- igniteCell g cVar
let a' = PA.updateState a (\sOld -> sOld { rng = g' } )
return (PA.newAgent a' aNew)
isLiving :: TVar WFCell -> STM Bool
isLiving cVar = do
cell <- readTVar cVar
return ((cellState cell) == Living)
burnDown :: (WFAgent, WFEnvironment) -> Double -> STM Bool
burnDown ae dt = do
cell <- readTVar cVar
let b = burnable cell
let burnableLeft = max (b - (burnPerTimeUnit * dt)) 0.0
modifyTVar cVar (\c -> c { burnable = burnableLeft })
return (burnableLeft <= 0.0)
where
cVar = cellOfAgent ae
killCellAndAgent :: (WFAgent, WFEnvironment) -> STM WFAgent
killCellAndAgent ae@(a, e) = do
changeCell cVar (\c -> c { burnable = 0.0, cellState = Dead } )
return (PA.kill a)
where
cVar = cellOfAgent ae
changeCell :: TVar WFCell -> (WFCell -> WFCell) -> STM ()
changeCell cVar tx = modifyTVar cVar tx
cellOfAgent :: (WFAgent, WFEnvironment) -> TVar WFCell
cellOfAgent (a, e) = fromJust maybeCell
where
maybeCell = Map.lookup (cidx (PA.state a)) (cells e)
neighbourhood :: [WFCellCoord]
neighbourhood = [topLeft, top, topRight,
left, right,
bottomLeft, bottom, bottomRight]
where
topLeft = (-1, -1)
top = (0, -1)
topRight = (1, -1)
left = (-1, 0)
right = (1, 0)
bottomLeft = (-1, 1)
bottom = (0, 1)
bottomRight = (1, 1)
randomNeighbourCoord :: StdGen -> WFCellCoord -> (WFCellCoord, StdGen)
randomNeighbourCoord g (cx, cy) = (randC, g')
where
nsCells = map (\(nx, ny) -> (cx + nx, cy + ny) :: WFCellCoord) neighbourhood
(randIdx, g') = randomR (0, (length nsCells) - 1) g
randC = nsCells !! randIdx
igniteCell :: StdGen -> TVar WFCell -> STM (WFAgent, StdGen)
igniteCell g cVar = do
cell <- readTVar cVar
let aState = WFAgentState { cidx = (cellIdx cell), rng = g' }
let id = (cellIdx cell)
a <- PA.createAgent id aState wfTransformer
changeCell cVar (\c -> c { cellState = Burning } ) -- NOTE: don't need any neighbours because no messaging!
return (a, g'')
where
(g', g'') = split g
cellByCoord :: WFEnvironment -> WFCellCoord -> Maybe (TVar WFCell)
cellByCoord env co = Map.lookup idx cs
where
limits = cellLimits env
cs = cells env
idx = idxByCoord co limits
createEnvironment :: (Int, Int) -> STM WFEnvironment
createEnvironment mcs@(maxX, maxY) = do
let cs = [ WFCell { cellIdx = (y*maxX) + x,
coord = (x, y),
burnable = 1.0,
cellState = Living } | y <- [0..maxY-1], x <- [0..maxX-1] ]
csVars <- mapM newTVar cs
csVarsMaped <- foldl insertCell (return Map.empty) cs
return WFEnvironment { cells = csVarsMaped, cellLimits = mcs }
insertCell :: STM (Map.Map WFCellIdx (TVar WFCell)) -> WFCell -> STM (Map.Map WFCellIdx (TVar WFCell))
insertCell m c = do
cVar <- newTVar c
m' <- m
return (Map.insert (cellIdx c) cVar m')
idxByCoord :: WFCellCoord -> (Int, Int) -> Int
idxByCoord (x, y) (maxX, maxY) = (y*maxX) + x
|
thalerjonathan/phd
|
public/ArtIterating/code/haskell/PureAgentsConc/src/WildFire/WildFireModelDynamic.hs
|
gpl-3.0
| 6,776 | 0 | 16 | 2,635 | 1,956 | 1,046 | 910 | 130 | 2 |
{-# LANGUAGE TemplateHaskell, RecordWildCards #-}
-- | A font attached to its size
module Graphics.UI.Bottle.SizedFont
( SizedFont(..), font, fontSize
, render
, textHeight
, textSize
) where
import qualified Control.Lens as Lens
import Data.Vector.Vector2 (Vector2)
import Graphics.DrawingCombinators ((%%))
import qualified Graphics.DrawingCombinators as Draw
import qualified Graphics.DrawingCombinators.Utils as DrawUtils
data SizedFont = SizedFont
{ _font :: Draw.Font
, _fontSize :: Double
}
Lens.makeLenses ''SizedFont
render :: SizedFont -> String -> Draw.Image ()
render SizedFont{..} str =
DrawUtils.scale (realToFrac _fontSize) %%
DrawUtils.drawText _font str
textHeight :: SizedFont -> Draw.R
textHeight SizedFont{..} = DrawUtils.textHeight * realToFrac _fontSize
textSize :: SizedFont -> String -> Vector2 Draw.R
textSize SizedFont{..} str = realToFrac _fontSize * DrawUtils.textSize _font str
|
rvion/lamdu
|
bottlelib/Graphics/UI/Bottle/SizedFont.hs
|
gpl-3.0
| 973 | 0 | 9 | 178 | 255 | 144 | 111 | 23 | 1 |
module Pudding.Storage.Binary
(
) where
import Pudding.Storage.Internal.Binary
|
jfulseca/Pudding
|
src/Pudding/Storage/Binary.hs
|
gpl-3.0
| 80 | 0 | 4 | 8 | 17 | 12 | 5 | 3 | 0 |
{- |
Module : Hazel.Normalize
Description : Functions for reasoning according to completion algorithm
License : GPL-3
Stability : experimental
Portability : unknown
Completion Algorithm for EL
-}
module Hazel.Completion
where
import Control.Monad.State.Lazy
import Data.List
import Data.Set (elems)
import Hazel.Core
-- data structure for completion graph
-- getNodes models the (inverse) function S from completion algorithm
-- getRoles models the (inverse) function R from completion algorithm
data CGraph = CGraph { getNodes :: Concept -> [Node]
, getRoles :: Role -> [CEdge]
}
type Node = Concept
type CEdge = (Concept, Concept)
data CState = CState [Node] [CEdge]
deriving (Eq)
type Completion = State CState CGraph
-- Auxiliary functions
-- | Returns a function that is like f, except one argument gets a new value
except :: (Eq a)
=> (a -> b) -- ^ original function
-> a -- ^ argument whose function value should be replaced
-> b -- ^ new value
-> a -> b
except f x' y' x
| x == x' = y'
| otherwise = f x
initGraph :: [Node] -> CGraph
-- ^ Initialization of the completion graph
initGraph allNodes =
CGraph n r
where
n Top = nub $ Top : allNodes
n x@(Name _) = [x]
n x@(Dummy _) = [x]
n _ = error "Complex concepts are not valid nodes in CGraph"
r _ = []
-- Functions applying Completion Rules
cr1 :: GCI -> CGraph -> Concept -> Completion
cr2 :: GCI -> CGraph -> Concept -> Completion
cr3 :: GCI -> CGraph -> Concept -> Completion
cr4 :: GCI -> CGraph -> (Concept, Concept) -> Completion
changeNode :: Node -> State CState ()
changeNode node = do
CState ns es <- get
put $ CState (node:ns) es
cr1 (Subclass c' d) (CGraph n r) c
| (c `notElem` n d) && (c `elem` n c') = do
changeNode c
return $ CGraph n' r
| otherwise = return $ CGraph n r
where
n' = except n d (c:n d)
cr2 (Subclass (And c1 c2) d) (CGraph n r) c
| (c `elem` n c1) && (c `elem` n c2) && (c `notElem` n d) = do
changeNode c
return $ CGraph n' r
| otherwise = return $ CGraph n r
where
n' = except n d (c:n d)
cr2 _ _ _ = error "Application of Rule CR2 not possible"
cr3 (Subclass c' (Exists role d)) (CGraph n r) c
| (c `elem` n c') && ((c, d) `notElem` r role) = do
CState ns es <- get
put $ CState ns ((c, d):es)
return $ CGraph n r'
| otherwise = return $ CGraph n r
where
r' = except r role ((c, d):r role)
cr3 _ _ _ = error "Application of Rule CR3 not possible"
cr4 (Subclass (Exists role d') e) (CGraph n r) (c, d)
| ((c, d) `elem` r role) && (d `elem` n d') && (c `notElem` n e) = do
changeNode c
return $ CGraph n' r
| otherwise = return $ CGraph n r
where
n' = except n e (c:n e)
cr4 _ _ _ = error "Application of Rule CR4 not possible"
-- Functions ensuring the rules are applied exhaustively
emptyState :: CState
emptyState = CState [] []
complete :: TBox -> CGraph
complete (TBox gcis cs _) =
go . initGraph $ elems cs
where
go :: CGraph -> CGraph
go graph
| state' == emptyState = graph'
| otherwise = go graph'
where
(graph', state') = runState (iterateGCI graph gcis) emptyState
iterateNodes :: CGraph -> GCI -> Completion
iterateNodes cG@(CGraph n r) gci = case gci of
(Subclass (And c d) _) -> foldM (cr2 gci) cG (n c `intersect` n d)
(Subclass c' (Exists _ _)) -> foldM (cr3 gci) cG (n c')
(Subclass (Exists role _) _) -> foldM (cr4 gci) cG (r role)
(Subclass c' _) -> foldM (cr1 gci) cG (n c')
iterateGCI :: CGraph -> [GCI] -> Completion
iterateGCI = foldM iterateNodes
|
hazel-el/hazel
|
Hazel/Completion.hs
|
gpl-3.0
| 3,815 | 0 | 12 | 1,115 | 1,435 | 737 | 698 | 82 | 4 |
{-# LANGUAGE ExtendedDefaultRules #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
-- Module : Khan.Model.Tag
-- Copyright : (c) 2013 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Khan.Model.Tag
(
-- * From EC2/ASG
annotate
, parse
-- * Constants
, env
, role
, domain
, name
, version
, weight
, group
-- * Filters
, filter
-- * Tags
, cached
, require
, instances
, images
, defaults
) where
import Control.Monad.Except
import qualified Data.Attoparsec.Text as AText
import Data.Bifunctor (first)
import qualified Data.CaseInsensitive as CI
import qualified Data.HashMap.Strict as Map
import qualified Data.SemVer as Ver
import qualified Data.Text as Text
import Data.Text.Lazy.IO as LText
import Filesystem as FS
import Khan.Internal hiding (group)
import Khan.Model.Tag.Tagged
import Khan.Prelude hiding (filter)
import Network.AWS
import Network.AWS.EC2
default (Text)
annotate :: Tagged a => a -> Maybe (Ann a)
annotate x = Ann x <$> hush (parse x)
parse :: Tagged a => a -> Either String Tags
parse (tags -> ts) = Tags
<$> (newRole <$> key role)
<*> (newEnv <$> key env)
<*> key domain
<*> opt (key name)
<*> lookupVersion
<*> lookupWeight
<*> opt (key group)
where
ciTags = Map.fromList . map (first CI.mk) $ Map.toList ts
lookupVersion = opt $
key version >>= Ver.fromText
lookupWeight = maybe (Right 0) Right . hush $
key weight >>= AText.parseOnly AText.decimal
key k = note ("Failed to find key: " ++ Text.unpack k)
(Map.lookup (CI.mk k) ciTags)
opt (Left _) = Right Nothing
opt (Right x) = Right (Just x)
env, role, domain, name, version, weight, group :: Text
env = "Env"
role = "Role"
domain = "Domain"
name = "Name"
version = "Version"
weight = "Weight"
group = "aws:autoscaling:groupName"
filter :: Text -> [Text] -> Filter
filter k = ec2Filter ("tag:" <> k)
cached :: CacheDir -> Text -> AWS Tags
cached (CacheDir dir) iid = do
say "Lookup cached tags from {} for Instance {}..." [B path, B iid]
r <- load
either (\e -> say "Error reading cached tags: {}" [e] >> store)
return
r
where
path = dir </> ".tags"
store = do
ts <- require iid
liftIO . FS.withTextFile path WriteMode $ \hd ->
LText.hPutStr hd (renderEnv True ts)
return ts
load = liftIO $
FS.isFile path >>=
bool (return (Left "Missing cached .tags"))
(parse . hashMap <$> FS.readTextFile path)
where
hashMap = Map.fromList . mapMaybe split . Text.lines
split x =
case Text.split (== '=') x of
[k, v] -> Just (strip k, v)
_ -> Nothing
strip x = Text.toUpper . fromMaybe x $ Text.stripPrefix "KHAN_" x
require :: Text -> AWS Tags
require iid = do
say "Describing tags for Instance {}..." [iid]
parse <$> send (DescribeTags [TagResourceId [iid]]) >>=
liftEitherT . hoistEither
instances :: Naming a => a -> Text -> [Text] -> AWS ()
instances n dom ids = do
say "Tagging: {}" [L ids]
send_ . CreateTags ids
$ map (uncurry ResourceTagSetItemType) (defaults n dom)
images :: Naming a => a -> [Text] -> AWS ()
images (names -> Names{..}) ids = do
say "Tagging: {}" [L ids]
send_ $ CreateTags ids
[ ResourceTagSetItemType role roleName
, ResourceTagSetItemType version (fromMaybe "" versionName)
, ResourceTagSetItemType name imageName
]
defaults :: Naming a => a -> Text -> [(Text, Text)]
defaults (names -> Names{..}) dom =
[ (role, roleName)
, (env, envName)
, (domain, dom)
, (name, appName)
, (weight, "0")
] ++ maybe [] (\v -> [(version, v)]) versionName
|
brendanhay/khan
|
khan/Khan/Model/Tag.hs
|
mpl-2.0
| 4,626 | 0 | 15 | 1,428 | 1,308 | 705 | 603 | 117 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DLP.Organizations.DeidentifyTemplates.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a DeidentifyTemplate. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates-deid to learn
-- more.
--
-- /See:/ <https://cloud.google.com/dlp/docs/ Cloud Data Loss Prevention (DLP) API Reference> for @dlp.organizations.deidentifyTemplates.delete@.
module Network.Google.Resource.DLP.Organizations.DeidentifyTemplates.Delete
(
-- * REST Resource
OrganizationsDeidentifyTemplatesDeleteResource
-- * Creating a Request
, organizationsDeidentifyTemplatesDelete
, OrganizationsDeidentifyTemplatesDelete
-- * Request Lenses
, odtdXgafv
, odtdUploadProtocol
, odtdAccessToken
, odtdUploadType
, odtdName
, odtdCallback
) where
import Network.Google.DLP.Types
import Network.Google.Prelude
-- | A resource alias for @dlp.organizations.deidentifyTemplates.delete@ method which the
-- 'OrganizationsDeidentifyTemplatesDelete' request conforms to.
type OrganizationsDeidentifyTemplatesDeleteResource =
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Delete '[JSON] GoogleProtobufEmpty
-- | Deletes a DeidentifyTemplate. See
-- https:\/\/cloud.google.com\/dlp\/docs\/creating-templates-deid to learn
-- more.
--
-- /See:/ 'organizationsDeidentifyTemplatesDelete' smart constructor.
data OrganizationsDeidentifyTemplatesDelete =
OrganizationsDeidentifyTemplatesDelete'
{ _odtdXgafv :: !(Maybe Xgafv)
, _odtdUploadProtocol :: !(Maybe Text)
, _odtdAccessToken :: !(Maybe Text)
, _odtdUploadType :: !(Maybe Text)
, _odtdName :: !Text
, _odtdCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OrganizationsDeidentifyTemplatesDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'odtdXgafv'
--
-- * 'odtdUploadProtocol'
--
-- * 'odtdAccessToken'
--
-- * 'odtdUploadType'
--
-- * 'odtdName'
--
-- * 'odtdCallback'
organizationsDeidentifyTemplatesDelete
:: Text -- ^ 'odtdName'
-> OrganizationsDeidentifyTemplatesDelete
organizationsDeidentifyTemplatesDelete pOdtdName_ =
OrganizationsDeidentifyTemplatesDelete'
{ _odtdXgafv = Nothing
, _odtdUploadProtocol = Nothing
, _odtdAccessToken = Nothing
, _odtdUploadType = Nothing
, _odtdName = pOdtdName_
, _odtdCallback = Nothing
}
-- | V1 error format.
odtdXgafv :: Lens' OrganizationsDeidentifyTemplatesDelete (Maybe Xgafv)
odtdXgafv
= lens _odtdXgafv (\ s a -> s{_odtdXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
odtdUploadProtocol :: Lens' OrganizationsDeidentifyTemplatesDelete (Maybe Text)
odtdUploadProtocol
= lens _odtdUploadProtocol
(\ s a -> s{_odtdUploadProtocol = a})
-- | OAuth access token.
odtdAccessToken :: Lens' OrganizationsDeidentifyTemplatesDelete (Maybe Text)
odtdAccessToken
= lens _odtdAccessToken
(\ s a -> s{_odtdAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
odtdUploadType :: Lens' OrganizationsDeidentifyTemplatesDelete (Maybe Text)
odtdUploadType
= lens _odtdUploadType
(\ s a -> s{_odtdUploadType = a})
-- | Required. Resource name of the organization and deidentify template to
-- be deleted, for example
-- \`organizations\/433245324\/deidentifyTemplates\/432452342\` or
-- projects\/project-id\/deidentifyTemplates\/432452342.
odtdName :: Lens' OrganizationsDeidentifyTemplatesDelete Text
odtdName = lens _odtdName (\ s a -> s{_odtdName = a})
-- | JSONP
odtdCallback :: Lens' OrganizationsDeidentifyTemplatesDelete (Maybe Text)
odtdCallback
= lens _odtdCallback (\ s a -> s{_odtdCallback = a})
instance GoogleRequest
OrganizationsDeidentifyTemplatesDelete
where
type Rs OrganizationsDeidentifyTemplatesDelete =
GoogleProtobufEmpty
type Scopes OrganizationsDeidentifyTemplatesDelete =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient
OrganizationsDeidentifyTemplatesDelete'{..}
= go _odtdName _odtdXgafv _odtdUploadProtocol
_odtdAccessToken
_odtdUploadType
_odtdCallback
(Just AltJSON)
dLPService
where go
= buildClient
(Proxy ::
Proxy OrganizationsDeidentifyTemplatesDeleteResource)
mempty
|
brendanhay/gogol
|
gogol-dlp/gen/Network/Google/Resource/DLP/Organizations/DeidentifyTemplates/Delete.hs
|
mpl-2.0
| 5,503 | 0 | 15 | 1,140 | 702 | 413 | 289 | 106 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
module Main (main) where
import Import
import Run
main :: IO ()
main = run
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/course/2018-06-roman-gonzales-rock-solid-haskell-services-lambdaconf/hc/app/Main.hs
|
unlicense
| 113 | 0 | 6 | 22 | 31 | 19 | 12 | 6 | 1 |
module Stuff.Pls
import Options.Applicative
stuff :: Stuff -> IO ()
stuff = putStrLn "Hai!"
main :: IO ()
main = execParser opts >>= stuff
where
opts = info (helper <*> stuff)
( fullDesc
<> progDesc "Stuff"
<> header "Hai!" )
|
zackp30/programs
|
hs/Hai.hs
|
apache-2.0
| 290 | 1 | 11 | 104 | 91 | 46 | 45 | -1 | -1 |
{-# LANGUAGE GADTSyntax #-}
{-# LANGUAGE KindSignatures #-}
{-
Copyright 2019 The CodeWorld Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
module CodeWorld.App2
{-# WARNING "This is an experimental API. It can change at any time." #-}
(
Application,
defaultApplication,
withTimeStep,
withEventHandler,
withPicture,
withMultiEventHandler,
withMultiPicture,
subapplication,
applicationOf
) where
import CodeWorld
import Data.List (foldl')
import System.Random (StdGen)
data Application :: * -> * where
App :: state
-> (Double -> state -> state)
-> (Int -> Event -> state -> state)
-> (Int -> state -> Picture)
-> Application state
defaultApplication :: state -> Application state
defaultApplication s =
App s (const id) (const (const id)) (const (const blank))
withTimeStep :: (Double -> state -> state)
-> Application state
-> Application state
withTimeStep f (App initial step event picture) =
App initial (\dt -> f dt . step dt) event picture
withEventHandler :: (Event -> state -> state)
-> Application state
-> Application state
withEventHandler f (App initial step event picture) =
App initial step (\k ev -> f ev . event k ev) picture
withPicture :: (state -> Picture) -> Application state -> Application state
withPicture f (App initial step event picture) =
App initial step event (\k s -> f s & picture k s)
withMultiEventHandler :: (Int -> Event -> state -> state)
-> Application state
-> Application state
withMultiEventHandler f (App initial step event picture) =
App initial step (\k ev -> f k ev . event k ev) picture
withMultiPicture :: (Int -> state -> Picture)
-> Application state
-> Application state
withMultiPicture f (App initial step event picture) =
App initial step event (\k s -> f k s & picture k s)
subapplication :: (a -> b)
-> (b -> a -> a)
-> Application b
-> (b -> a)
-> Application a
subapplication getter setter (App initial step event picture) f =
App (f initial)
(\dt s -> setter (step dt (getter s)) s)
(\k ev s -> setter (event k ev (getter s)) s)
(\k -> picture k . getter)
applicationOf :: Application world -> IO ()
applicationOf (App initial step event picture) =
interactionOf initial step (event 0) (picture 0)
|
pranjaltale16/codeworld
|
codeworld-api/src/CodeWorld/App2.hs
|
apache-2.0
| 3,043 | 0 | 12 | 820 | 836 | 429 | 407 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import HEP.Automation.Model.Server.Type
import HEP.Automation.Model.Server.Yesod ()
import Yesod
import qualified Data.Map as M
import Data.Acid
main :: IO ()
main = do
putStrLn "model-server"
acid <- openLocalState M.empty
warpDebug 7800 (ModelServer acid)
|
wavewave/model-server
|
exe/model-server.hs
|
bsd-2-clause
| 323 | 0 | 9 | 50 | 87 | 50 | 37 | 12 | 1 |
module Network.Minecraft.Entity (
Entity(..),
PosLook,
Position,
Look,
EID,
) where
import Network.Minecraft.GameMode
import Network.Minecraft.Inventory as Inv
type Position = (Double, Double, Double)
type Look = (Float, Float)
type Velocity = (Integer, Integer, Integer)
type PosLook = (Position, Look)
type EID = Integer
data Entity = Entity {
eid :: EID,
name :: String,
posLook :: PosLook
}
position = fst . posLook
setPosition p e = e { posLook = (p, look e) }
look = snd . posLook
setLook l e = e { posLook = (position e, l) }
|
ziocroc/Minetlib
|
Network/Minecraft/Entity.hs
|
bsd-2-clause
| 552 | 16 | 8 | 110 | 218 | 135 | 83 | 21 | 1 |
module Data.RDF.Query (
-- * Query functions
equalSubjects, equalPredicates, equalObjects,
subjectOf, predicateOf, objectOf, isEmpty,
rdfContainsNode, tripleContainsNode,
listSubjectsWithPredicate, listObjectsOfPredicate,
-- * RDF graph functions
isIsomorphic, expandTriples, fromEither,
-- * expansion functions
expandTriple, expandNode, expandURI,
-- * absolutizing functions
absolutizeTriple, absolutizeNode
) where
import Prelude hiding (pred)
import Data.List
import Data.RDF.Types
import qualified Data.RDF.Namespace as NS (toPMList, uriOf, rdf)
import qualified Data.Text as T
import Data.Maybe (catMaybes)
-- |Answer the subject node of the triple.
{-# INLINE subjectOf #-}
subjectOf :: Triple -> Node
subjectOf (Triple s _ _) = s
-- |Answer the predicate node of the triple.
{-# INLINE predicateOf #-}
predicateOf :: Triple -> Node
predicateOf (Triple _ p _) = p
-- |Answer the object node of the triple.
{-# INLINE objectOf #-}
objectOf :: Triple -> Node
objectOf (Triple _ _ o) = o
-- |Answer if rdf contains node.
rdfContainsNode :: forall rdf. (RDF rdf) => rdf -> Node -> Bool
rdfContainsNode rdf node =
let ts = triplesOf rdf
xs = map (tripleContainsNode node) ts
in elem True xs
-- |Answer if triple contains node.
-- Note that it doesn't perform namespace expansion!
tripleContainsNode :: Node -> Triple -> Bool
{-# INLINE tripleContainsNode #-}
tripleContainsNode node t =
subjectOf t == node || predicateOf t == node || objectOf t == node
-- |Determine whether two triples have equal subjects.
-- Note that it doesn't perform namespace expansion!
equalSubjects :: Triple -> Triple -> Bool
equalSubjects (Triple s1 _ _) (Triple s2 _ _) = s1 == s2
-- |Determine whether two triples have equal predicates.
-- Note that it doesn't perform namespace expansion!
equalPredicates :: Triple -> Triple -> Bool
equalPredicates (Triple _ p1 _) (Triple _ p2 _) = p1 == p2
-- |Determine whether two triples have equal objects.
-- Note that it doesn't perform namespace expansion!
equalObjects :: Triple -> Triple -> Bool
equalObjects (Triple _ _ o1) (Triple _ _ o2) = o1 == o2
-- |Determines whether the 'RDF' contains zero triples.
isEmpty :: RDF rdf => rdf -> Bool
isEmpty rdf =
let ts = triplesOf rdf
in null ts
-- |Lists of all subjects of triples with the given predicate.
listSubjectsWithPredicate :: RDF rdf => rdf -> Predicate -> [Subject]
listSubjectsWithPredicate rdf pred =
listNodesWithPredicate rdf pred subjectOf
-- |Lists of all objects of triples with the given predicate.
listObjectsOfPredicate :: RDF rdf => rdf -> Predicate -> [Object]
listObjectsOfPredicate rdf pred =
listNodesWithPredicate rdf pred objectOf
listNodesWithPredicate :: RDF rdf => rdf -> Predicate -> (Triple -> Node) -> [Node]
listNodesWithPredicate rdf pred f =
let ts = triplesOf rdf
xs = filter (\t -> predicateOf t == pred) ts
in map f xs
-- |Convert a parse result into an RDF if it was successful
-- and error and terminate if not.
fromEither :: RDF rdf => Either ParseFailure rdf -> rdf
fromEither res =
case res of
(Left err) -> error (show err)
(Right rdf) -> rdf
-- |This determines if two RDF representations are equal regardless of blank
-- node names, triple order and prefixes. In math terms, this is the \simeq
-- latex operator, or ~=
isIsomorphic :: forall rdf1 rdf2. (RDF rdf1, RDF rdf2) => rdf1 -> rdf2 -> Bool
isIsomorphic g1 g2 = normalize g1 == normalize g2
where normalize :: forall rdf. (RDF rdf) => rdf -> Triples
normalize = sort . nub . expandTriples
-- |Expand the triples in a graph with the prefix map and base URL for that
-- graph.
expandTriples :: (RDF rdf) => rdf -> Triples
expandTriples rdf = expandTriples' [] (baseUrl rdf) (prefixMappings rdf) (triplesOf rdf)
expandTriples' :: Triples -> Maybe BaseUrl -> PrefixMappings -> Triples -> Triples
expandTriples' acc _ _ [] = acc
expandTriples' acc baseURL prefixMaps (t:rest) = expandTriples' (normalize baseURL prefixMaps t : acc) baseURL prefixMaps rest
where normalize baseURL' prefixMaps' = absolutizeTriple baseURL' . expandTriple prefixMaps'
-- |Expand the triple with the prefix map.
expandTriple :: PrefixMappings -> Triple -> Triple
expandTriple pms t = triple (expandNode pms $ subjectOf t) (expandNode pms $ predicateOf t) (expandNode pms $ objectOf t)
-- |Expand the node with the prefix map.
-- Only UNodes are expanded, other kinds of nodes are returned as-is.
expandNode :: PrefixMappings -> Node -> Node
expandNode pms (UNode n) = unode $ expandURI pms n
expandNode _ n' = n'
-- |Expand the URI with the prefix map.
-- Also expands "a" to "http://www.w3.org/1999/02/22-rdf-syntax-ns#type".
expandURI :: PrefixMappings -> T.Text -> T.Text
expandURI _ "a" = T.append (NS.uriOf NS.rdf) "type"
expandURI pms' x = firstExpandedOrOriginal x $ catMaybes $ map (resourceTail x) (NS.toPMList pms')
where resourceTail :: T.Text -> (T.Text, T.Text) -> Maybe T.Text
resourceTail x' (p', u') = T.stripPrefix (T.append p' ":") x' >>= Just . T.append u'
firstExpandedOrOriginal :: a -> [a] -> a
firstExpandedOrOriginal orig' [] = orig'
firstExpandedOrOriginal _ (e:_) = e
-- |Prefixes relative URIs in the triple with BaseUrl.
absolutizeTriple :: Maybe BaseUrl -> Triple -> Triple
absolutizeTriple base t = triple (absolutizeNode base $ subjectOf t) (absolutizeNode base $ predicateOf t) (absolutizeNode base $ objectOf t)
-- |Prepends BaseUrl to UNodes with relative URIs.
absolutizeNode :: Maybe BaseUrl -> Node -> Node
absolutizeNode (Just (BaseUrl b')) (UNode u') = unode $ mkAbsoluteUrl b' u'
absolutizeNode _ n = n
|
LeifW/rdf4h
|
src/Data/RDF/Query.hs
|
bsd-3-clause
| 5,665 | 0 | 13 | 1,048 | 1,496 | 787 | 709 | -1 | -1 |
module Ebitor.RopeUtils where
import Test.Framework
import Test.QuickCheck.Arbitrary
import qualified Data.Text as T
import Ebitor.Rope as R
pack' :: String -> Rope
pack' = R.packWithSize 5
packRope :: String -> Rope
packRope = pack'
instance Arbitrary Rope where
arbitrary = do
s <- arbitrary
return $ pack' s
instance Arbitrary T.Text where
arbitrary = do
s <- arbitrary
return $ T.pack s
|
benekastah/ebitor
|
test/Ebitor/RopeUtils.hs
|
bsd-3-clause
| 438 | 0 | 10 | 108 | 129 | 70 | 59 | 17 | 1 |
{-# LANGUAGE
TypeOperators
, NoMonomorphismRestriction
#-}
-- Generate a dataset
-- Using a the bicicle model
module Attitude where
import Data.List(transpose)
import Scaling.S1
import Scaling.Time
import Linear.V1
import Linear.V2
import Linear.V3
import Data.Distributive
import Solver.RungeKutta
import Linear.Metric
import Control.Monad (when)
import Product
import Sensor.Razor9DOF
import Vectorization
import Local
import Exponential.SO3
import Exponential.SO2
import Exponential.Class
import Rotation.SO3
import Rotation.SO2
import Space.SO2
import Space.SO3
import Space.Class
import Kalman
import Prelude hiding(sequence,readFile,writeFile)
import As
import Data.Data
import Linear.Matrix
import Data.Maybe
import System.Environment
import Data.Foldable(toList,Foldable)
import Control.Lens hiding ((|>))
import Control.Lens.Getter
import Control.Lens.Setter
import Control.Lens.TH
import Control.Monad (liftM,replicateM,(>=>))
import Data.Word
import Data.Traversable
import Control.Applicative
import Data.Distributive
import Data.Functor.Compose
import CartesianProduct
import System.IO
import Data.Time
import Foreign.Storable
import Linear.Vector
import Space.SE3
import SemiProduct
import Ellipsoid
{-
data Filtro
= Filtro
{ _time :: V1 Double
, _se3 :: SE3 Double
, _speed :: V3 Double
, _orientationOffset :: SO3 Double
, _accCalib :: LinearParamV3 Double
, _magCalib :: LinearParamV3 Double
, _gyroCalib:: LinearParamV3 Double
, _gravityMagnitude :: V1 Double
}deriving(Show,Read)
makeLenses ''Filtro
-}
position = se3 . sndPL1
orientation = se3 . fstPL1
-- Time
time = fstPL1
-- Dynamics
se3 = sndPL1 . fstPL1
orientationOffset = sndPL3 . fstPL1
speed = sndPL2 . fstPL1
-- Sensor Calibration
accCalib = sndPL4 . fstPL1
magCalib = sndPL5 . fstPL1
gyroCalib = sndPL6 . fstPL1
-- Field Parameters
gravityMagnitude = sndPL7
type Attitude
= V1 :|: SO3 :|: SO2 :|: LinearParamV3 :|: LinearParamV3 :|: LinearParamV3
type Position
= V1 :|: SE3 :|: V3 :|: SO2 :|: LinearParamV3 :|: LinearParamV3 :|: LinearParamV3 :|: V1
type GyroscopeAccelerometerTransition = SE3 :|: V3 :|: LinearParamV3 :|: LinearParamV3 :|: V1
sensorScaling gyroRaw accRaw (Compose ggo) (Compose ago ) = acc :|: gyro
where
acc = linScaleA ago accRaw
gyro = linScaleA ggo gyroRaw
positionTransition :: (V3 :|: V3 ) Double -> V1 Double -> ( V1 :|: SE3 :|: V3 ) Double -> Local (SE3 :|: V3 ) Double
positionTransition (acc :|: gyro) (V1 g) (t :|: (r :>: position ) :|: speed )
= ( gyro :|: speed ) :|: ((invert r) |> acc ^-^ (V3 0 0 g) ^-^ (skewV3 gyro !* speed))
type GyroTransition = V1 :|: SO3 :|: LinearParamV3
gyr = time |:| orientation |:| gyroCalib
gyr' = time |:| orientation
type MagnetometerMeasure = SO3 :|: SO2 :|: LinearParamV3 :|: LinearParamV3
magCalibration = orientation |:| orientationOffset |:| magCalib |:| gyroCalib
mag = orientation |:| orientationOffset
type AccelerometerMeasure = SO3 :|: LinearParamV3 :|: LinearParamV3
acc = orientation
accCalibration = orientation |:| accCalib |:| gyroCalib
positionMeasure = position
positionTransitionFocus = time |:| se3 |:| speed |:| accCalib |:| gyroCalib |:| gravityMagnitude
matI :: Num a => Int -> [[a]]
matI n = [ [fromIntegral $ fromEnum $ i == j | i <- [1..n]] | j <- [1..n]]
liftIdent ::(R f,Num a,Storable a,Vectorize f,Functor f,Applicative f)=> f a -> M f a
liftIdent x = fmap (liftA2 (*) x) (fromLists $ matI n )
where n = dimM x
identM ::(R f,Num a,Storable a,Vectorize f,Functor f,Applicative f)=> f a -> M f a
identM x = fmap (liftA2 (*) (liftA2 (*) x x)) (fromLists $ matI n )
where n = dimM x
backScaleA = liftA2 backscale
linScaleA = liftA2 linscale
gyroTransition :: V3 Double -> LinearParamV3 Double -> (V1 :|: SO3 ) Double -> Local SO3 Double
gyroTransition gyroRaw (Compose ggo) (t :|: SO3 r )
= fmap negate $ linScaleA ggo gyro
where gyro = gyroRaw
magneticFieldGyro (Compose mgo) ((SO3 r):|: (SO2 od ) :|: ggo )
-- = backScaleA mgo (r !* (odV3 !* V3 1 0 0 ) )
= backScaleA mgo (r !* (V3 1 0 0 ) )
where odV3 = alongMatrix _zx .~ od $ identV3
magneticFieldCalib ((SO3 r):|: (SO2 od ) :|: (Compose mgo):|: ggo )
= backScaleA mgo (r !* (odV3 !* V3 1 0 0 ) )
where odV3 = alongMatrix _zx .~ od $ identV3
northPoleField declination = odV3 !* V3 1 0 0
where odV3 = alongMatrix _zx .~ declination $ expM 0
magneticField (Compose mgo :|: ggo) ((SO3 r):|: (SO2 od ))
= backScaleA mgo (r !* (odV3 !* V3 1 0 0 ) )
where odV3 = alongMatrix _zx .~ od $ identV3
gravity :: Double
gravity = 9.81
gravityFieldGyro (Compose ago) ((SO3 r):|: (Compose ggo ))
= backScaleA ago (r !* V3 0 0 gravity )
gravityFieldCalib ((SO3 r):|: (Compose ago):|: (Compose ggo ))
= backScaleA ago (r !* V3 0 0 (gravity) )
gravityField ( Compose ago :|: Compose ggo ) (SO3 r)
= backScaleA ago (r !* V3 0 0 (gravity) )
type Covariance f a= Local f (Local f a )
anglesMeasure (IMU acc _ mag)= angles
where
ax = atan2 (acc ^. _y) (acc ^. _z )
ay = atan2 (-acc ^. _x) (sqrt $ (acc ^._y)^2 + (acc ^. _z )^2)
magr = distribute r !* mag
SO3 r = rotation (V3 ax ay 0)
az = atan2 (- magr ^. _y) (magr ^. _x )
angles = V3 ax ay az
-- Product Lenses
deCompose = lens get set
where set (Compose x ) y = Compose y
get (Compose x) = x
fstPL = _ffst
sndPL = _fsnd
sndPL1 = sndPL
fstPL1 = fstPL
fstPL2 = fstPL1 . fstPL1
fstPL3 = fstPL1 . fstPL2
fstPL4 = fstPL1 . fstPL3
fstPL5 = fstPL1 . fstPL4
fstPL6 = fstPL1 . fstPL5
sndPL2 = sndPL1 . sndPL1
sndPL3 = sndPL1 . sndPL2
sndPL4 = sndPL1 . sndPL3
sndPL5 = sndPL1 . sndPL4
sndPL6 = sndPL1 . sndPL5
sndPL7 = sndPL1 . sndPL6
v3toTuple (V3 x y z) = (x,y,z)
degrees x = x*180/pi
|
massudaw/mtk
|
filters/attitude/Attitude.hs
|
bsd-3-clause
| 5,868 | 0 | 14 | 1,265 | 2,042 | 1,097 | 945 | 145 | 1 |
{-|
Module : Utils
Description : Some useful functions
-}
module Utils
where
import Task
import Errors
import Control.Exception
import Data.Function
import Data.List
import System.Cmd
import System.Posix.Env
import System.Exit
import System.IO
import System.Directory
-- | Compare two tuples, key ordering
kvcompare :: Ord k => (k, a) -> (k, a) -> Bool
kvcompare (k1,_) (k2, _) = k1==k2
-- | Group list of tuples using keys
kvgroup ::Ord k => [(k, a)] -> [[(k, a)]]
kvgroup l = groupBy kvcompare (sortBy (compare `on` fst) l)
-- | It is fold for summing (key,value) lists with the same key in tuple
helper_func :: Num a => a -> [(Key, a)] -> (Key, a)
helper_func acc [(x,y)] = (x,acc+y)
helper_func acc ((x,y):xs) = helper_func (acc+y) xs
-- | All the functions below are used for invoking unix sort command
sort_cmd :: FilePath -> String -> String
sort_cmd filename sort_buffer_size =
"sort -k 1,1 -T . -S " ++ sort_buffer_size ++ " -o " ++ filename ++ " " ++ filename
disk_sort :: [String] -> IO String --TODO handle
disk_sort list_inputs = do
let merged_inputs = concat list_inputs --TODO
pwd <- getCurrentDirectory
let filename = pwd ++ "/sorted_inputs"
handle <- openFile filename ReadWriteMode
hPutStr handle merged_inputs --TODO large files
hFlush handle
hClose handle
unix_sort filename "10%"
readFile filename
unix_sort :: FilePath -> String -> IO ()
unix_sort filename sort_buffer_size = do
setEnv "LC_ALL" "C" True
let cmd = sort_cmd filename sort_buffer_size
exit_code <- system cmd
case exit_code of
ExitSuccess -> return ()
ExitFailure num -> throwIO SortingExcept
|
zuzia/haskell_worker
|
src/Utils.hs
|
bsd-3-clause
| 1,668 | 0 | 11 | 343 | 519 | 273 | 246 | 40 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Client.ClientStateT where
import Control.Lens (makeLenses)
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import Linear (V3(..))
import Client.ClientInfoT
import Client.FrameT
import Client.RefDefT
import qualified Constants
import Game.UserCmdT
import Render.ImageT
import Render.ModelT
import Sound.SfxT
import Types
makeLenses ''ClientStateT
newClientStateT :: ClientStateT
newClientStateT = ClientStateT
{ _csTimeOutCount = 0
, _csTimeDemoFrames = 0
, _csTimeDemoStart = 0
, _csRefreshPrepped = False
, _csSoundPrepped = False
, _csForceRefDef = False
, _csParseEntities = 0
, _csCmd = newUserCmdT
, _csCmds = V.replicate Constants.cmdBackup newUserCmdT
, _csCmdTime = UV.replicate Constants.cmdBackup 0
, _csPredictedOrigins = UV.replicate Constants.cmdBackup (V3 0 0 0)
, _csPredictedStep = 0
, _csPredictedStepTime = 0
, _csPredictedOrigin = V3 0 0 0
, _csPredictedAngles = V3 0 0 0
, _csPredictionError = V3 0 0 0
, _csFrame = newFrameT
, _csSurpressCount = 0
, _csFrames = V.replicate Constants.updateBackup newFrameT
, _csViewAngles = V3 0 0 0
, _csTime = 0
, _csLerpFrac = 0
, _csRefDef = newRefDefT
, _csVForward = V3 0 0 0
, _csVRight = V3 0 0 0
, _csVUp = V3 0 0 0
, _csLayout = ""
, _csInventory = UV.replicate Constants.maxItems 0
, _csCinematicFile = Nothing
, _csCinematicTime = 0
, _csCinematicFrame = 0
, _csCinematicPalette = "" -- size 768
, _csCinematicPaletteActive = False
, _csAttractLoop = False
, _csServerCount = 0
, _csGameDir = ""
, _csPlayerNum = 0
, _csConfigStrings = V.replicate Constants.maxConfigStrings ""
, _csModelDraw = V.replicate Constants.maxModels Nothing
, _csModelClip = V.replicate Constants.maxModels Nothing
, _csSoundPrecache = V.replicate Constants.maxSounds Nothing
, _csImagePrecache = V.replicate Constants.maxImages Nothing
, _csClientInfo = V.replicate Constants.maxClients newClientInfoT
, _csBaseClientInfo = newClientInfoT
}
|
ksaveljev/hake-2
|
src/Client/ClientStateT.hs
|
bsd-3-clause
| 2,760 | 0 | 9 | 1,081 | 531 | 315 | 216 | 62 | 1 |
import Codec.Pwdhash (pwdhash)
import Data.Char (isAscii, isPrint)
import System.Process (readProcess)
import Test.Framework (Test, defaultMain)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.QuickCheck (Property)
import Test.QuickCheck.Arbitrary (Arbitrary(..))
import Test.QuickCheck.Gen (listOf, suchThat)
import Test.QuickCheck.Monadic (assert, monadicIO, run)
newtype S = S String
deriving (Eq, Ord, Show, Read)
okS :: Char -> Bool
okS s = isAscii s && isPrint s
instance Arbitrary S where
arbitrary = S <$> (listOf $ arbitrary `suchThat` okS)
shrink (S s) = S <$> shrink s
execNode :: String -> String -> IO String
execNode password realm = readProcess "node" ["js/pwdhash.js", password, realm] ""
prop_regression :: S -> S -> Property
prop_regression password' realm' = monadicIO $ do
let S password = password'
S realm = realm'
run $ print (password, realm)
expected <- run $ fmap init $ execNode password realm
let actual = pwdhash password realm
assert $ actual == expected
tests :: [Test]
tests =
[ testProperty "regression" prop_regression
]
main :: IO ()
main = defaultMain tests
|
izuk/pwdhash
|
test/regression.hs
|
bsd-3-clause
| 1,151 | 2 | 11 | 195 | 426 | 224 | 202 | 31 | 1 |
module WaveSim.Menu
(runMainMenu,
drawMainMenu) where
import Graphics.UI.GLUT as GLUT
import Control.Monad.State
import Data.IORef
import Data.Maybe
import Paths_WaveSim
import WaveSim.Graphics
import WaveSim.Widgets
import WaveSim.Types
import WaveSim.TwoD
-- DEBUG
enterThreeD :: IORef WorldState -> IO ()
enterThreeD worldStateRef = putStrLn "Entering 3d."
-- END DEBUG
initMainMenu :: Config -> IO (Config)
initMainMenu cfg = do
let mainMenu' = mainMenu cfg
let twoDButton' = twoDButton mainMenu'
let threeDButton' = threeDButton mainMenu'
let background' = background mainMenu'
-- Missing butClickTex, for now
twoDButtonTex <- if isNothing (butTex twoDButton') == True
then liftIO $ loadTexture $ getDataFileName "data/2Dbutton.png"
else return $ fromJust $ butTex twoDButton'
threeDButtonTex <- if isNothing (butTex threeDButton') == True
then liftIO $ loadTexture $ getDataFileName "data/3Dbutton.png"
else return $ fromJust $ butTex threeDButton'
backTexture' <- if isNothing (backTex background') == True
then liftIO $ loadTexture $ getDataFileName "data/menu_back.png"
else return $ fromJust $ backTex background'
return $ cfg
{
mainMenu = mainMenu'
{
menuInitComplete = True,
twoDButton = twoDButton'
{
butTex = Just twoDButtonTex,
butClickCall = Just runTwoD
},
threeDButton = threeDButton'
{
butTex = Just threeDButtonTex,
butClickCall = Just enterThreeD
},
background = background' { backTex = Just backTexture' }
}
}
runMainMenu :: IORef WorldState -> IO ()
runMainMenu worldStateRef = do
worldState <- readIORef worldStateRef
-- Only initialize the main menu if we are displaying for the first time
let initMenu = do newcfg <- initMainMenu (configData worldState)
writeIORef worldStateRef (worldState {configData = newcfg})
newButton worldStateRef (twoDButton (mainMenu newcfg))
newButton worldStateRef (threeDButton (mainMenu newcfg))
unless (menuInitComplete (mainMenu (configData worldState))) initMenu
drawMainMenu :: IORef WorldState -> IO ()
drawMainMenu worldStateRef = do
worldState <- readIORef worldStateRef
-- Extract from world state
let cfgData = configData worldState
let menuData = mainMenu cfgData
-- References to the texture
let twoDTex = fromJust $ butTex (twoDButton menuData)
let threeDTex = fromJust $ butTex (threeDButton menuData)
let menuTex = fromJust $ backTex (background menuData)
drawTexture (backGeometry (background menuData)) menuTex 1.0
drawTexture (butGeometry (twoDButton menuData)) twoDTex 1.0
drawTexture (butGeometry (threeDButton menuData)) threeDTex 1.0
drawString (twoDTextLoc menuData) "2-Dimensional Display" (Color4 0 0 0 1) (fontName cfgData)
drawString (threeDTextLoc menuData) "3-Dimensional Display" (Color4 0 0 0 1) (fontName cfgData)
|
jethomas/WaveSim
|
src/WaveSim/Menu.hs
|
bsd-3-clause
| 3,267 | 0 | 16 | 919 | 816 | 402 | 414 | 60 | 4 |
module Sharc.Instruments.CelloPizzicato (celloPizzicato) where
import Sharc.Types
celloPizzicato :: Instr
celloPizzicato = Instr
"cello_pizzicato"
"Cello (pizzicato)"
(Legend "McGill" "1" "13")
(Range
(InstrRange
(HarmonicFreq 1 (Pitch 65.4 24 "c2"))
(Pitch 65.4 24 "c2")
(Amplitude 6017.35 (HarmonicFreq 92 (Pitch 65.406 24 "c2")) 0.0))
(InstrRange
(HarmonicFreq 136 (Pitch 10578.35 27 "d#2"))
(Pitch 587.33 62 "d5")
(Amplitude 207.65 (HarmonicFreq 2 (Pitch 103.826 32 "g#2")) 10153.0)))
[note0
,note1
,note2
,note3
,note4
,note5
,note6
,note7
,note8
,note9
,note10
,note11
,note12
,note13
,note14
,note15
,note16
,note17
,note18
,note19
,note20
,note21
,note22
,note23
,note24
,note25
,note26
,note27
,note28
,note29
,note30
,note31
,note32
,note33
,note34
,note35
,note36
,note37
,note38]
note0 :: Note
note0 = Note
(Pitch 65.406 24 "c2")
1
(Range
(NoteRange
(NoteRangeAmplitude 6017.35 92 0.0)
(NoteRangeHarmonicFreq 1 65.4))
(NoteRange
(NoteRangeAmplitude 130.81 2 2594.0)
(NoteRangeHarmonicFreq 155 10137.93)))
[Harmonic 1 0.982 300.23
,Harmonic 2 (-1.35) 2594.0
,Harmonic 3 (-2.439) 2508.42
,Harmonic 4 (-1.488) 541.65
,Harmonic 5 (-2.978) 197.11
,Harmonic 6 (-0.704) 230.77
,Harmonic 7 0.484 142.39
,Harmonic 8 (-2.247) 133.8
,Harmonic 9 2.4 10.79
,Harmonic 10 0.697 8.37
,Harmonic 11 (-1.886) 4.66
,Harmonic 12 2.386 4.35
,Harmonic 13 (-0.484) 6.05
,Harmonic 14 2.872 2.83
,Harmonic 15 (-3.072) 0.66
,Harmonic 16 0.195 1.54
,Harmonic 17 0.751 2.21
,Harmonic 18 1.469 0.51
,Harmonic 19 (-1.823) 0.83
,Harmonic 20 2.92 0.83
,Harmonic 21 (-2.975) 0.26
,Harmonic 22 (-2.02) 0.27
,Harmonic 23 2.476 0.26
,Harmonic 24 2.963 0.91
,Harmonic 25 1.892 0.15
,Harmonic 26 4.5e-2 0.45
,Harmonic 27 (-2.724) 0.1
,Harmonic 28 0.657 6.0e-2
,Harmonic 29 (-3.139) 0.28
,Harmonic 30 2.894 0.58
,Harmonic 31 2.478 0.54
,Harmonic 32 (-0.79) 0.57
,Harmonic 33 (-2.049) 0.15
,Harmonic 34 (-1.619) 8.0e-2
,Harmonic 35 1.832 0.11
,Harmonic 36 2.278 8.0e-2
,Harmonic 37 2.399 0.25
,Harmonic 38 (-2.981) 0.33
,Harmonic 39 (-2.864) 3.0e-2
,Harmonic 40 (-3.089) 9.0e-2
,Harmonic 41 (-2.702) 0.35
,Harmonic 42 (-1.877) 0.13
,Harmonic 43 0.2 0.27
,Harmonic 44 (-0.649) 8.0e-2
,Harmonic 45 2.702 0.35
,Harmonic 46 (-0.12) 0.17
,Harmonic 47 2.955 0.11
,Harmonic 48 1.844 7.0e-2
,Harmonic 49 1.251 0.15
,Harmonic 50 1.288 0.14
,Harmonic 51 (-0.854) 8.0e-2
,Harmonic 52 2.89 4.0e-2
,Harmonic 53 3.024 7.0e-2
,Harmonic 54 (-3.017) 7.0e-2
,Harmonic 55 0.906 0.12
,Harmonic 56 2.079 0.11
,Harmonic 57 2.382 3.0e-2
,Harmonic 58 (-0.212) 0.12
,Harmonic 59 1.428 9.0e-2
,Harmonic 60 1.211 0.14
,Harmonic 61 (-2.949) 9.0e-2
,Harmonic 62 0.703 0.14
,Harmonic 63 2.876 0.18
,Harmonic 64 1.202 4.0e-2
,Harmonic 65 2.918 5.0e-2
,Harmonic 66 (-0.315) 0.18
,Harmonic 67 2.22 3.0e-2
,Harmonic 68 1.04 0.25
,Harmonic 69 3.039 1.0e-2
,Harmonic 70 (-1.42) 8.0e-2
,Harmonic 71 1.573 9.0e-2
,Harmonic 72 (-0.984) 8.0e-2
,Harmonic 73 1.425 0.21
,Harmonic 74 0.662 7.0e-2
,Harmonic 75 (-1.468) 5.0e-2
,Harmonic 76 (-0.693) 0.13
,Harmonic 77 2.811 0.1
,Harmonic 78 1.012 0.18
,Harmonic 79 0.31 0.16
,Harmonic 80 1.806 0.16
,Harmonic 81 2.543 4.0e-2
,Harmonic 82 (-2.36) 4.0e-2
,Harmonic 83 2.052 8.0e-2
,Harmonic 84 5.5e-2 0.11
,Harmonic 85 (-2.834) 9.0e-2
,Harmonic 86 (-2.878) 6.0e-2
,Harmonic 87 0.22 9.0e-2
,Harmonic 88 2.845 6.0e-2
,Harmonic 89 1.077 0.1
,Harmonic 90 (-1.952) 6.0e-2
,Harmonic 91 (-2.709) 9.0e-2
,Harmonic 92 (-1.0) 0.0
,Harmonic 93 2.37 0.11
,Harmonic 94 0.743 9.0e-2
,Harmonic 95 (-2.766) 0.13
,Harmonic 96 (-1.509) 9.0e-2
,Harmonic 97 (-0.662) 4.0e-2
,Harmonic 98 (-0.206) 0.15
,Harmonic 99 (-1.714) 0.19
,Harmonic 100 1.158 0.14
,Harmonic 101 (-2.518) 0.1
,Harmonic 102 2.49 0.15
,Harmonic 103 (-0.415) 9.0e-2
,Harmonic 104 1.291 8.0e-2
,Harmonic 105 (-1.579) 8.0e-2
,Harmonic 106 1.341 9.0e-2
,Harmonic 107 0.155 0.14
,Harmonic 108 2.758 6.0e-2
,Harmonic 109 0.291 0.16
,Harmonic 110 (-2.526) 0.16
,Harmonic 111 2.51 5.0e-2
,Harmonic 112 (-2.706) 8.0e-2
,Harmonic 113 2.873 0.12
,Harmonic 114 0.766 0.15
,Harmonic 115 (-1.423) 8.0e-2
,Harmonic 116 (-2.707) 6.0e-2
,Harmonic 117 1.536 9.0e-2
,Harmonic 118 0.498 1.0e-2
,Harmonic 119 (-2.767) 4.0e-2
,Harmonic 120 (-1.171) 5.0e-2
,Harmonic 121 1.227 0.18
,Harmonic 122 2.82 3.0e-2
,Harmonic 123 2.697 4.0e-2
,Harmonic 124 1.109 7.0e-2
,Harmonic 125 0.582 7.0e-2
,Harmonic 126 (-2.77) 0.1
,Harmonic 127 (-2.167) 0.1
,Harmonic 128 (-1.318) 0.11
,Harmonic 129 2.5 0.2
,Harmonic 130 (-0.782) 5.0e-2
,Harmonic 131 1.844 0.12
,Harmonic 132 1.027 8.0e-2
,Harmonic 133 0.481 9.0e-2
,Harmonic 134 2.283 0.13
,Harmonic 135 (-1.291) 8.0e-2
,Harmonic 136 1.503 0.16
,Harmonic 137 3.08 5.0e-2
,Harmonic 138 0.929 7.0e-2
,Harmonic 139 1.34 0.1
,Harmonic 140 0.805 2.0e-2
,Harmonic 141 (-1.09) 8.0e-2
,Harmonic 142 1.562 0.13
,Harmonic 143 (-1.921) 3.0e-2
,Harmonic 144 2.763 9.0e-2
,Harmonic 145 (-1.15) 7.0e-2
,Harmonic 146 1.098 6.0e-2
,Harmonic 147 (-2.674) 4.0e-2
,Harmonic 148 1.063 7.0e-2
,Harmonic 149 0.804 5.0e-2
,Harmonic 150 0.534 3.0e-2
,Harmonic 151 (-1.198) 0.11
,Harmonic 152 0.385 0.27
,Harmonic 153 0.284 5.0e-2
,Harmonic 154 (-1.32) 7.0e-2
,Harmonic 155 (-0.751) 0.17]
note1 :: Note
note1 = Note
(Pitch 69.296 25 "c#2")
2
(Range
(NoteRange
(NoteRangeAmplitude 6929.6 100 0.0)
(NoteRangeHarmonicFreq 1 69.29))
(NoteRange
(NoteRangeAmplitude 207.88 3 2020.0)
(NoteRangeHarmonicFreq 141 9770.73)))
[Harmonic 1 (-2.819) 440.17
,Harmonic 2 (-2.412) 1293.77
,Harmonic 3 1.132 2020.0
,Harmonic 4 0.626 26.44
,Harmonic 5 0.532 261.12
,Harmonic 6 (-2.439) 120.32
,Harmonic 7 1.434 59.86
,Harmonic 8 (-0.812) 13.12
,Harmonic 9 (-1.079) 13.65
,Harmonic 10 2.097 7.5
,Harmonic 11 0.528 4.24
,Harmonic 12 (-2.338) 4.0
,Harmonic 13 1.031 2.99
,Harmonic 14 1.97 21.02
,Harmonic 15 1.105 5.31
,Harmonic 16 (-2.209) 2.38
,Harmonic 17 3.094 1.62
,Harmonic 18 (-1.806) 2.7
,Harmonic 19 (-1.433) 0.95
,Harmonic 20 (-1.598) 1.15
,Harmonic 21 2.839 1.06
,Harmonic 22 (-2.465) 0.41
,Harmonic 23 (-1.475) 1.07
,Harmonic 24 2.436 0.18
,Harmonic 25 0.595 7.0e-2
,Harmonic 26 2.618 5.0e-2
,Harmonic 27 2.764 0.14
,Harmonic 28 (-2.533) 0.18
,Harmonic 29 (-2.284) 0.1
,Harmonic 30 (-0.289) 0.2
,Harmonic 31 0.792 0.21
,Harmonic 32 (-1.795) 0.24
,Harmonic 33 (-1.298) 0.33
,Harmonic 34 2.104 0.16
,Harmonic 35 (-2.479) 0.16
,Harmonic 36 0.54 0.2
,Harmonic 37 (-0.195) 6.0e-2
,Harmonic 38 0.135 0.39
,Harmonic 39 (-0.475) 7.0e-2
,Harmonic 40 0.384 0.11
,Harmonic 41 1.769 9.0e-2
,Harmonic 42 (-0.721) 0.13
,Harmonic 43 (-1.956) 0.1
,Harmonic 44 (-1.451) 0.11
,Harmonic 45 (-2.039) 0.12
,Harmonic 46 (-2.144) 6.0e-2
,Harmonic 47 (-2.9) 0.13
,Harmonic 48 0.598 0.21
,Harmonic 49 (-1.479) 7.0e-2
,Harmonic 50 (-0.613) 0.19
,Harmonic 51 (-0.845) 0.1
,Harmonic 52 2.393 4.0e-2
,Harmonic 53 (-1.276) 0.15
,Harmonic 54 (-2.942) 0.1
,Harmonic 55 2.848 0.16
,Harmonic 56 (-2.0) 0.16
,Harmonic 57 (-2.639) 0.13
,Harmonic 58 (-1.703) 5.0e-2
,Harmonic 59 (-2.29) 0.13
,Harmonic 60 0.533 4.0e-2
,Harmonic 61 (-2.872) 0.18
,Harmonic 62 2.345 0.1
,Harmonic 63 0.65 0.13
,Harmonic 64 1.707 0.2
,Harmonic 65 (-0.446) 2.0e-2
,Harmonic 66 2.903 0.17
,Harmonic 67 2.462 0.13
,Harmonic 68 (-0.283) 2.0e-2
,Harmonic 69 0.734 2.0e-2
,Harmonic 70 (-0.7) 0.11
,Harmonic 71 (-0.947) 1.0e-2
,Harmonic 72 (-2.726) 7.0e-2
,Harmonic 73 1.904 7.0e-2
,Harmonic 74 (-1.198) 5.0e-2
,Harmonic 75 (-1.047) 3.0e-2
,Harmonic 76 1.585 7.0e-2
,Harmonic 77 3.067 8.0e-2
,Harmonic 78 0.923 4.0e-2
,Harmonic 79 1.791 0.16
,Harmonic 80 (-3.129) 0.1
,Harmonic 81 (-1.979) 6.0e-2
,Harmonic 82 (-0.677) 2.0e-2
,Harmonic 83 2.402 2.0e-2
,Harmonic 84 (-2.865) 2.0e-2
,Harmonic 85 (-2.623) 8.0e-2
,Harmonic 86 0.549 5.0e-2
,Harmonic 87 (-2.195) 7.0e-2
,Harmonic 88 0.706 0.1
,Harmonic 89 (-0.771) 0.1
,Harmonic 90 0.302 5.0e-2
,Harmonic 91 (-2.562) 9.0e-2
,Harmonic 92 0.93 8.0e-2
,Harmonic 93 2.964 0.12
,Harmonic 94 2.891 4.0e-2
,Harmonic 95 (-2.752) 0.12
,Harmonic 96 2.818 0.0
,Harmonic 97 2.409 3.0e-2
,Harmonic 98 (-2.395) 7.0e-2
,Harmonic 99 (-1.843) 9.0e-2
,Harmonic 100 (-2.01) 0.0
,Harmonic 101 (-2.018) 3.0e-2
,Harmonic 102 (-2.313) 7.0e-2
,Harmonic 103 (-0.236) 2.0e-2
,Harmonic 104 (-1.941) 3.0e-2
,Harmonic 105 2.507 2.0e-2
,Harmonic 106 3.6e-2 0.13
,Harmonic 107 (-1.521) 0.12
,Harmonic 108 2.62 8.0e-2
,Harmonic 109 0.582 0.12
,Harmonic 110 1.55 0.0
,Harmonic 111 0.231 7.0e-2
,Harmonic 112 (-2.35) 4.0e-2
,Harmonic 113 0.964 4.0e-2
,Harmonic 114 (-1.727) 9.0e-2
,Harmonic 115 (-0.93) 2.0e-2
,Harmonic 116 2.615 0.12
,Harmonic 117 1.419 0.21
,Harmonic 118 2.0e-2 0.14
,Harmonic 119 (-3.082) 5.0e-2
,Harmonic 120 1.053 0.13
,Harmonic 121 1.511 2.0e-2
,Harmonic 122 (-1.039) 3.0e-2
,Harmonic 123 2.387 5.0e-2
,Harmonic 124 0.969 2.0e-2
,Harmonic 125 (-0.295) 4.0e-2
,Harmonic 126 2.701 0.11
,Harmonic 127 (-1.174) 5.0e-2
,Harmonic 128 (-1.57) 5.0e-2
,Harmonic 129 2.492 0.1
,Harmonic 130 (-0.582) 9.0e-2
,Harmonic 131 1.442 7.0e-2
,Harmonic 132 2.751 6.0e-2
,Harmonic 133 2.639 8.0e-2
,Harmonic 134 0.989 4.0e-2
,Harmonic 135 1.789 8.0e-2
,Harmonic 136 9.0e-3 1.0e-2
,Harmonic 137 3.049 6.0e-2
,Harmonic 138 (-3.086) 0.13
,Harmonic 139 1.252 0.12
,Harmonic 140 (-2.68) 8.0e-2
,Harmonic 141 (-1.705) 5.0e-2]
note2 :: Note
note2 = Note
(Pitch 73.416 26 "d2")
3
(Range
(NoteRange
(NoteRangeAmplitude 5726.44 78 1.0e-2)
(NoteRangeHarmonicFreq 1 73.41))
(NoteRange
(NoteRangeAmplitude 146.83 2 3189.0)
(NoteRangeHarmonicFreq 135 9911.16)))
[Harmonic 1 (-0.748) 1076.52
,Harmonic 2 2.504 3189.0
,Harmonic 3 1.229 2521.94
,Harmonic 4 (-0.93) 464.38
,Harmonic 5 1.197 331.72
,Harmonic 6 (-1.003) 643.74
,Harmonic 7 (-2.484) 73.11
,Harmonic 8 (-1.401) 67.81
,Harmonic 9 (-2.377) 85.66
,Harmonic 10 2.68 36.41
,Harmonic 11 7.6e-2 12.21
,Harmonic 12 2.671 23.69
,Harmonic 13 (-2.505) 37.46
,Harmonic 14 (-1.338) 11.23
,Harmonic 15 (-0.687) 15.22
,Harmonic 16 (-0.123) 16.39
,Harmonic 17 0.82 9.29
,Harmonic 18 (-2.591) 11.65
,Harmonic 19 (-1.665) 7.45
,Harmonic 20 1.913 3.86
,Harmonic 21 3.073 4.37
,Harmonic 22 (-9.8e-2) 4.21
,Harmonic 23 (-0.984) 2.65
,Harmonic 24 0.448 0.13
,Harmonic 25 1.063 5.47
,Harmonic 26 0.666 1.18
,Harmonic 27 1.498 1.77
,Harmonic 28 (-0.777) 0.78
,Harmonic 29 (-1.425) 0.31
,Harmonic 30 (-0.423) 1.21
,Harmonic 31 3.087 0.68
,Harmonic 32 0.542 0.28
,Harmonic 33 (-1.655) 1.19
,Harmonic 34 (-1.532) 0.19
,Harmonic 35 2.202 0.71
,Harmonic 36 3.088 1.83
,Harmonic 37 (-2.187) 0.23
,Harmonic 38 (-1.616) 0.33
,Harmonic 39 2.715 0.97
,Harmonic 40 (-1.062) 1.07
,Harmonic 41 (-2.937) 0.45
,Harmonic 42 (-2.402) 0.23
,Harmonic 43 (-0.517) 0.27
,Harmonic 44 (-2.898) 0.16
,Harmonic 45 (-2.193) 0.56
,Harmonic 46 (-0.264) 0.11
,Harmonic 47 (-2.204) 0.3
,Harmonic 48 2.7 0.31
,Harmonic 49 3.023 0.18
,Harmonic 50 2.544 0.11
,Harmonic 51 1.06 0.12
,Harmonic 52 (-1.965) 0.39
,Harmonic 53 0.238 0.12
,Harmonic 54 (-1.956) 0.29
,Harmonic 55 0.591 0.13
,Harmonic 56 0.782 0.17
,Harmonic 57 (-0.802) 6.0e-2
,Harmonic 58 (-2.578) 0.31
,Harmonic 59 1.755 0.23
,Harmonic 60 (-0.505) 3.0e-2
,Harmonic 61 (-2.823) 7.0e-2
,Harmonic 62 (-2.989) 7.0e-2
,Harmonic 63 2.055 0.1
,Harmonic 64 2.296 0.12
,Harmonic 65 (-2.568) 4.0e-2
,Harmonic 66 (-2.982) 0.11
,Harmonic 67 0.282 0.13
,Harmonic 68 (-2.569) 0.1
,Harmonic 69 0.816 0.13
,Harmonic 70 1.55 8.0e-2
,Harmonic 71 2.975 7.0e-2
,Harmonic 72 (-0.97) 8.0e-2
,Harmonic 73 (-0.211) 6.0e-2
,Harmonic 74 (-0.321) 0.12
,Harmonic 75 (-2.411) 0.14
,Harmonic 76 (-1.219) 7.0e-2
,Harmonic 77 1.205 0.17
,Harmonic 78 (-2.381) 1.0e-2
,Harmonic 79 (-2.547) 5.0e-2
,Harmonic 80 (-1.568) 0.11
,Harmonic 81 1.58 0.1
,Harmonic 82 (-1.47) 9.0e-2
,Harmonic 83 1.718 0.17
,Harmonic 84 0.789 0.16
,Harmonic 85 (-0.922) 0.24
,Harmonic 86 (-2.549) 5.0e-2
,Harmonic 87 (-0.338) 0.13
,Harmonic 88 (-1.913) 5.0e-2
,Harmonic 89 2.712 0.17
,Harmonic 90 0.519 0.14
,Harmonic 91 2.437 0.18
,Harmonic 92 (-0.293) 7.0e-2
,Harmonic 93 (-2.315) 7.0e-2
,Harmonic 94 (-2.607) 0.11
,Harmonic 95 0.557 0.21
,Harmonic 96 2.08 0.11
,Harmonic 97 0.527 0.15
,Harmonic 98 (-2.538) 0.22
,Harmonic 99 (-1.292) 0.12
,Harmonic 100 1.526 0.12
,Harmonic 101 (-2.235) 0.17
,Harmonic 102 1.882 0.18
,Harmonic 103 (-1.081) 7.0e-2
,Harmonic 104 0.763 0.1
,Harmonic 105 (-0.888) 4.0e-2
,Harmonic 106 1.023 5.0e-2
,Harmonic 107 3.0 4.0e-2
,Harmonic 108 0.116 0.22
,Harmonic 109 (-2.231) 4.0e-2
,Harmonic 110 2.493 0.1
,Harmonic 111 1.658 8.0e-2
,Harmonic 112 (-2.831) 8.0e-2
,Harmonic 113 (-1.792) 0.14
,Harmonic 114 (-2.448) 2.0e-2
,Harmonic 115 1.039 0.15
,Harmonic 116 0.505 4.0e-2
,Harmonic 117 (-0.105) 4.0e-2
,Harmonic 118 2.509 0.19
,Harmonic 119 1.063 8.0e-2
,Harmonic 120 2.694 8.0e-2
,Harmonic 121 (-2.341) 0.13
,Harmonic 122 0.138 0.15
,Harmonic 123 (-2.339) 0.29
,Harmonic 124 2.456 0.12
,Harmonic 125 2.966 0.29
,Harmonic 126 2.309 5.0e-2
,Harmonic 127 1.648 9.0e-2
,Harmonic 128 2.958 0.1
,Harmonic 129 0.67 4.0e-2
,Harmonic 130 1.55 7.0e-2
,Harmonic 131 (-1.974) 0.2
,Harmonic 132 0.948 6.0e-2
,Harmonic 133 (-1.598) 6.0e-2
,Harmonic 134 (-1.55) 3.0e-2
,Harmonic 135 2.084 0.12]
note3 :: Note
note3 = Note
(Pitch 77.782 27 "d#2")
4
(Range
(NoteRange
(NoteRangeAmplitude 10422.78 134 1.0e-2)
(NoteRangeHarmonicFreq 1 77.78))
(NoteRange
(NoteRangeAmplitude 155.56 2 2397.0)
(NoteRangeHarmonicFreq 136 10578.35)))
[Harmonic 1 (-1.84) 1113.59
,Harmonic 2 0.552 2397.0
,Harmonic 3 (-1.629) 863.8
,Harmonic 4 (-1.95) 231.62
,Harmonic 5 1.471 25.98
,Harmonic 6 (-1.532) 21.63
,Harmonic 7 0.289 2.26
,Harmonic 8 3.05 2.52
,Harmonic 9 0.508 9.18
,Harmonic 10 2.139 9.08
,Harmonic 11 (-1.292) 11.74
,Harmonic 12 2.407 17.06
,Harmonic 13 1.026 24.67
,Harmonic 14 2.385 26.3
,Harmonic 15 1.266 10.47
,Harmonic 16 0.444 2.02
,Harmonic 17 (-0.669) 3.54
,Harmonic 18 (-1.108) 3.07
,Harmonic 19 (-1.789) 0.68
,Harmonic 20 (-1.86) 3.44
,Harmonic 21 1.693 0.46
,Harmonic 22 0.498 1.2
,Harmonic 23 2.828 0.5
,Harmonic 24 (-1.415) 0.63
,Harmonic 25 2.353 0.74
,Harmonic 26 (-6.1e-2) 0.48
,Harmonic 27 1.019 1.16
,Harmonic 28 1.905 1.0
,Harmonic 29 (-0.418) 0.25
,Harmonic 30 0.846 1.51
,Harmonic 31 (-3.011) 0.29
,Harmonic 32 (-1.403) 0.69
,Harmonic 33 1.683 0.69
,Harmonic 34 (-2.421) 0.32
,Harmonic 35 1.159 0.37
,Harmonic 36 0.346 0.12
,Harmonic 37 0.723 0.69
,Harmonic 38 1.349 0.23
,Harmonic 39 (-2.839) 0.53
,Harmonic 40 (-2.137) 0.5
,Harmonic 41 0.616 0.74
,Harmonic 42 (-1.665) 0.16
,Harmonic 43 2.0e-3 0.27
,Harmonic 44 2.566 0.14
,Harmonic 45 0.955 0.13
,Harmonic 46 1.659 0.1
,Harmonic 47 0.698 0.17
,Harmonic 48 0.889 3.0e-2
,Harmonic 49 1.704 0.2
,Harmonic 50 1.135 8.0e-2
,Harmonic 51 (-2.731) 4.0e-2
,Harmonic 52 (-0.462) 4.0e-2
,Harmonic 53 (-2.097) 7.0e-2
,Harmonic 54 (-1.367) 7.0e-2
,Harmonic 55 (-0.154) 0.1
,Harmonic 56 (-2.686) 8.0e-2
,Harmonic 57 2.529 6.0e-2
,Harmonic 58 2.134 9.0e-2
,Harmonic 59 2.419 0.12
,Harmonic 60 2.025 0.13
,Harmonic 61 1.872 0.12
,Harmonic 62 0.0 2.0e-2
,Harmonic 63 (-1.085) 0.19
,Harmonic 64 2.819 0.11
,Harmonic 65 (-1.361) 0.15
,Harmonic 66 (-1.281) 7.0e-2
,Harmonic 67 (-4.1e-2) 0.15
,Harmonic 68 (-0.497) 2.0e-2
,Harmonic 69 (-2.147) 9.0e-2
,Harmonic 70 (-1.815) 3.0e-2
,Harmonic 71 1.919 8.0e-2
,Harmonic 72 2.317 4.0e-2
,Harmonic 73 (-2.48) 0.16
,Harmonic 74 2.391 0.16
,Harmonic 75 1.848 7.0e-2
,Harmonic 76 (-1.73) 0.18
,Harmonic 77 (-1.099) 2.0e-2
,Harmonic 78 (-1.919) 2.0e-2
,Harmonic 79 (-2.559) 0.24
,Harmonic 80 1.795 9.0e-2
,Harmonic 81 (-0.967) 8.0e-2
,Harmonic 82 (-0.976) 0.16
,Harmonic 83 (-1.734) 0.13
,Harmonic 84 (-0.257) 0.12
,Harmonic 85 (-2.335) 0.1
,Harmonic 86 1.335 8.0e-2
,Harmonic 87 0.735 6.0e-2
,Harmonic 88 0.961 0.2
,Harmonic 89 (-0.274) 0.11
,Harmonic 90 (-1.982) 0.17
,Harmonic 91 2.16 7.0e-2
,Harmonic 92 (-1.814) 2.0e-2
,Harmonic 93 2.168 0.13
,Harmonic 94 1.031 6.0e-2
,Harmonic 95 (-1.665) 0.27
,Harmonic 96 2.95 0.12
,Harmonic 97 2.944 0.3
,Harmonic 98 (-1.035) 9.0e-2
,Harmonic 99 0.453 0.1
,Harmonic 100 (-1.877) 0.15
,Harmonic 101 (-2.302) 2.0e-2
,Harmonic 102 (-0.187) 0.12
,Harmonic 103 (-0.777) 0.12
,Harmonic 104 2.283 0.16
,Harmonic 105 (-1.544) 0.28
,Harmonic 106 2.23 2.0e-2
,Harmonic 107 (-2.255) 7.0e-2
,Harmonic 108 (-2.687) 0.14
,Harmonic 109 1.031 7.0e-2
,Harmonic 110 (-2.149) 0.1
,Harmonic 111 2.084 0.18
,Harmonic 112 (-1.878) 0.13
,Harmonic 113 (-0.693) 9.0e-2
,Harmonic 114 (-2.316) 0.2
,Harmonic 115 1.419 2.0e-2
,Harmonic 116 (-2.11) 8.0e-2
,Harmonic 117 2.495 0.12
,Harmonic 118 (-1.928) 0.11
,Harmonic 119 (-3.009) 3.0e-2
,Harmonic 120 1.849 0.16
,Harmonic 121 (-0.706) 3.0e-2
,Harmonic 122 (-2.231) 0.11
,Harmonic 123 (-0.993) 8.0e-2
,Harmonic 124 (-2.941) 0.14
,Harmonic 125 (-1.073) 0.13
,Harmonic 126 (-1.269) 4.0e-2
,Harmonic 127 1.705 7.0e-2
,Harmonic 128 (-0.266) 4.0e-2
,Harmonic 129 2.776 1.0e-2
,Harmonic 130 (-1.961) 0.11
,Harmonic 131 (-0.178) 2.0e-2
,Harmonic 132 1.846 5.0e-2
,Harmonic 133 (-0.948) 0.2
,Harmonic 134 (-3.015) 1.0e-2
,Harmonic 135 2.572 0.1
,Harmonic 136 (-1.088) 7.0e-2]
note4 :: Note
note4 = Note
(Pitch 82.407 28 "e2")
5
(Range
(NoteRange
(NoteRangeAmplitude 9229.58 112 1.0e-2)
(NoteRangeHarmonicFreq 1 82.4))
(NoteRange
(NoteRangeAmplitude 82.4 1 1288.0)
(NoteRangeHarmonicFreq 128 10548.09)))
[Harmonic 1 (-1.034) 1288.0
,Harmonic 2 2.133 940.93
,Harmonic 3 (-9.7e-2) 275.5
,Harmonic 4 (-0.382) 68.02
,Harmonic 5 (-1.34) 138.54
,Harmonic 6 (-0.552) 10.62
,Harmonic 7 (-1.434) 4.04
,Harmonic 8 2.461 1.83
,Harmonic 9 (-0.504) 3.48
,Harmonic 10 1.457 2.65
,Harmonic 11 (-0.744) 2.22
,Harmonic 12 (-1.603) 7.77
,Harmonic 13 0.46 3.55
,Harmonic 14 (-1.931) 5.13
,Harmonic 15 (-1.531) 1.35
,Harmonic 16 (-2.601) 0.35
,Harmonic 17 2.943 2.27
,Harmonic 18 0.19 0.58
,Harmonic 19 (-0.105) 0.72
,Harmonic 20 (-0.234) 0.65
,Harmonic 21 (-0.74) 0.95
,Harmonic 22 (-0.535) 0.99
,Harmonic 23 2.482 0.2
,Harmonic 24 0.142 0.25
,Harmonic 25 1.673 0.23
,Harmonic 26 2.367 0.21
,Harmonic 27 (-1.482) 0.18
,Harmonic 28 (-0.116) 0.33
,Harmonic 29 1.84 5.0e-2
,Harmonic 30 1.2 0.21
,Harmonic 31 2.808 0.21
,Harmonic 32 (-0.141) 0.16
,Harmonic 33 1.378 0.39
,Harmonic 34 (-0.12) 8.0e-2
,Harmonic 35 (-1.164) 0.12
,Harmonic 36 (-1.97) 0.1
,Harmonic 37 0.852 8.0e-2
,Harmonic 38 0.413 0.12
,Harmonic 39 3.8e-2 0.16
,Harmonic 40 1.954 0.11
,Harmonic 41 (-6.5e-2) 6.0e-2
,Harmonic 42 0.174 0.12
,Harmonic 43 (-2.053) 8.0e-2
,Harmonic 44 (-2.378) 0.2
,Harmonic 45 (-1.663) 0.21
,Harmonic 46 (-1.542) 0.15
,Harmonic 47 1.479 6.0e-2
,Harmonic 48 3.136 5.0e-2
,Harmonic 49 (-2.548) 0.16
,Harmonic 50 2.173 0.12
,Harmonic 51 (-2.664) 4.0e-2
,Harmonic 52 (-1.236) 0.39
,Harmonic 53 (-1.68) 0.15
,Harmonic 54 (-9.1e-2) 0.21
,Harmonic 55 (-1.906) 5.0e-2
,Harmonic 56 (-0.473) 0.15
,Harmonic 57 (-2.489) 8.0e-2
,Harmonic 58 0.671 0.19
,Harmonic 59 1.054 0.16
,Harmonic 60 (-1.854) 5.0e-2
,Harmonic 61 0.424 0.2
,Harmonic 62 (-2.449) 0.21
,Harmonic 63 (-1.555) 0.12
,Harmonic 64 0.34 8.0e-2
,Harmonic 65 (-2.001) 0.18
,Harmonic 66 (-1.367) 8.0e-2
,Harmonic 67 1.53 0.11
,Harmonic 68 (-1.912) 6.0e-2
,Harmonic 69 (-0.777) 6.0e-2
,Harmonic 70 1.312 0.13
,Harmonic 71 2.319 7.0e-2
,Harmonic 72 (-1.672) 0.1
,Harmonic 73 (-2.474) 7.0e-2
,Harmonic 74 (-2.574) 0.26
,Harmonic 75 (-1.695) 0.16
,Harmonic 76 (-1.806) 5.0e-2
,Harmonic 77 1.044 0.18
,Harmonic 78 0.669 0.25
,Harmonic 79 (-2.613) 0.1
,Harmonic 80 1.547 0.19
,Harmonic 81 (-1.539) 0.11
,Harmonic 82 2.359 5.0e-2
,Harmonic 83 (-2.318) 0.25
,Harmonic 84 2.703 0.2
,Harmonic 85 1.25 3.0e-2
,Harmonic 86 2.846 5.0e-2
,Harmonic 87 (-2.414) 2.0e-2
,Harmonic 88 (-2.822) 0.12
,Harmonic 89 0.562 0.12
,Harmonic 90 (-2.191) 3.0e-2
,Harmonic 91 0.422 0.24
,Harmonic 92 (-2.534) 0.12
,Harmonic 93 (-0.105) 5.0e-2
,Harmonic 94 (-2.726) 0.21
,Harmonic 95 (-1.522) 0.24
,Harmonic 96 1.883 0.32
,Harmonic 97 1.649 0.2
,Harmonic 98 (-0.937) 0.29
,Harmonic 99 0.953 0.31
,Harmonic 100 (-0.227) 0.39
,Harmonic 101 (-2.673) 0.14
,Harmonic 102 (-2.717) 4.0e-2
,Harmonic 103 0.67 0.14
,Harmonic 104 1.683 0.25
,Harmonic 105 1.132 9.0e-2
,Harmonic 106 0.943 0.21
,Harmonic 107 1.178 0.15
,Harmonic 108 1.598 1.0e-2
,Harmonic 109 0.901 0.12
,Harmonic 110 2.075 0.15
,Harmonic 111 (-0.189) 0.1
,Harmonic 112 (-1.774) 1.0e-2
,Harmonic 113 2.75 0.18
,Harmonic 114 (-1.859) 0.15
,Harmonic 115 (-2.693) 8.0e-2
,Harmonic 116 (-1.96) 7.0e-2
,Harmonic 117 0.762 2.0e-2
,Harmonic 118 2.197 0.13
,Harmonic 119 (-0.295) 0.12
,Harmonic 120 3.048 0.12
,Harmonic 121 (-1.925) 0.26
,Harmonic 122 (-0.535) 0.35
,Harmonic 123 (-0.941) 0.12
,Harmonic 124 2.771 0.12
,Harmonic 125 3.1 0.12
,Harmonic 126 (-2.382) 3.0e-2
,Harmonic 127 (-1.536) 0.13
,Harmonic 128 (-1.098) 0.21]
note5 :: Note
note5 = Note
(Pitch 87.307 29 "f2")
6
(Range
(NoteRange
(NoteRangeAmplitude 4452.65 51 2.0e-2)
(NoteRangeHarmonicFreq 1 87.3))
(NoteRange
(NoteRangeAmplitude 87.3 1 3882.0)
(NoteRangeHarmonicFreq 110 9603.77)))
[Harmonic 1 1.723 3882.0
,Harmonic 2 (-0.571) 1906.08
,Harmonic 3 2.079 297.26
,Harmonic 4 3.082 394.93
,Harmonic 5 (-0.527) 594.92
,Harmonic 6 2.546 29.22
,Harmonic 7 (-2.327) 34.76
,Harmonic 8 (-0.645) 22.43
,Harmonic 9 (-3.072) 18.93
,Harmonic 10 (-0.865) 7.48
,Harmonic 11 0.625 19.21
,Harmonic 12 1.0e-3 12.45
,Harmonic 13 (-2.468) 1.93
,Harmonic 14 0.671 0.69
,Harmonic 15 (-3.061) 4.59
,Harmonic 16 0.788 1.21
,Harmonic 17 (-2.207) 1.04
,Harmonic 18 1.264 2.79
,Harmonic 19 1.089 0.68
,Harmonic 20 (-9.0e-2) 1.14
,Harmonic 21 0.711 0.5
,Harmonic 22 (-2.273) 0.65
,Harmonic 23 (-0.927) 0.26
,Harmonic 24 0.615 0.6
,Harmonic 25 (-1.261) 0.33
,Harmonic 26 0.515 0.24
,Harmonic 27 (-2.951) 0.11
,Harmonic 28 (-1.453) 0.16
,Harmonic 29 1.268 9.0e-2
,Harmonic 30 3.5e-2 0.41
,Harmonic 31 1.191 0.33
,Harmonic 32 (-0.198) 0.57
,Harmonic 33 (-0.351) 0.6
,Harmonic 34 (-2.161) 0.26
,Harmonic 35 (-0.432) 0.21
,Harmonic 36 (-0.208) 6.0e-2
,Harmonic 37 (-0.73) 4.0e-2
,Harmonic 38 (-1.229) 0.34
,Harmonic 39 (-1.07) 0.11
,Harmonic 40 (-2.371) 6.0e-2
,Harmonic 41 (-0.773) 0.19
,Harmonic 42 (-2.34) 0.39
,Harmonic 43 1.8e-2 0.12
,Harmonic 44 (-0.641) 0.22
,Harmonic 45 0.661 5.0e-2
,Harmonic 46 (-2.611) 7.0e-2
,Harmonic 47 (-0.402) 0.29
,Harmonic 48 0.846 0.24
,Harmonic 49 2.397 6.0e-2
,Harmonic 50 1.842 0.1
,Harmonic 51 (-1.775) 2.0e-2
,Harmonic 52 (-0.803) 9.0e-2
,Harmonic 53 0.743 5.0e-2
,Harmonic 54 (-2.503) 5.0e-2
,Harmonic 55 (-1.115) 0.24
,Harmonic 56 (-0.298) 0.26
,Harmonic 57 3.064 0.11
,Harmonic 58 (-2.229) 0.14
,Harmonic 59 (-1.65) 5.0e-2
,Harmonic 60 0.779 8.0e-2
,Harmonic 61 (-2.41) 0.2
,Harmonic 62 2.593 5.0e-2
,Harmonic 63 2.38 0.1
,Harmonic 64 1.504 0.11
,Harmonic 65 (-0.979) 0.1
,Harmonic 66 (-1.626) 0.17
,Harmonic 67 (-0.374) 8.0e-2
,Harmonic 68 2.82 0.11
,Harmonic 69 2.354 0.31
,Harmonic 70 1.927 0.18
,Harmonic 71 (-0.471) 6.0e-2
,Harmonic 72 0.768 0.12
,Harmonic 73 1.306 0.27
,Harmonic 74 1.751 7.0e-2
,Harmonic 75 (-0.414) 9.0e-2
,Harmonic 76 (-5.7e-2) 0.17
,Harmonic 77 0.404 0.13
,Harmonic 78 (-0.828) 6.0e-2
,Harmonic 79 0.397 2.0e-2
,Harmonic 80 2.992 0.16
,Harmonic 81 2.42 0.2
,Harmonic 82 2.735 0.18
,Harmonic 83 (-0.738) 8.0e-2
,Harmonic 84 (-2.956) 0.14
,Harmonic 85 3.129 3.0e-2
,Harmonic 86 2.136 0.14
,Harmonic 87 1.637 4.0e-2
,Harmonic 88 (-2.406) 9.0e-2
,Harmonic 89 (-2.835) 0.21
,Harmonic 90 (-1.249) 7.0e-2
,Harmonic 91 2.371 6.0e-2
,Harmonic 92 0.52 7.0e-2
,Harmonic 93 (-1.216) 6.0e-2
,Harmonic 94 (-1.688) 8.0e-2
,Harmonic 95 0.987 0.12
,Harmonic 96 2.934 9.0e-2
,Harmonic 97 1.223 6.0e-2
,Harmonic 98 (-2.081) 4.0e-2
,Harmonic 99 (-0.622) 0.2
,Harmonic 100 (-1.383) 0.1
,Harmonic 101 (-0.464) 0.18
,Harmonic 102 3.012 0.22
,Harmonic 103 0.94 0.16
,Harmonic 104 (-1.1e-2) 3.0e-2
,Harmonic 105 1.362 7.0e-2
,Harmonic 106 (-1.493) 0.16
,Harmonic 107 3.137 0.13
,Harmonic 108 (-0.134) 0.14
,Harmonic 109 2.734 0.1
,Harmonic 110 (-2.997) 0.1]
note6 :: Note
note6 = Note
(Pitch 92.499 30 "f#2")
7
(Range
(NoteRange
(NoteRangeAmplitude 8417.4 91 3.0e-2)
(NoteRangeHarmonicFreq 1 92.49))
(NoteRange
(NoteRangeAmplitude 92.49 1 4814.0)
(NoteRangeHarmonicFreq 108 9989.89)))
[Harmonic 1 1.188 4814.0
,Harmonic 2 2.919 1830.23
,Harmonic 3 1.845 463.97
,Harmonic 4 0.964 334.24
,Harmonic 5 2.067 253.93
,Harmonic 6 2.525 74.3
,Harmonic 7 1.317 59.13
,Harmonic 8 0.517 39.29
,Harmonic 9 (-2.992) 17.12
,Harmonic 10 (-0.469) 43.95
,Harmonic 11 1.982 19.09
,Harmonic 12 1.266 7.04
,Harmonic 13 (-2.676) 4.26
,Harmonic 14 3.013 7.55
,Harmonic 15 (-0.425) 0.52
,Harmonic 16 (-1.372) 3.66
,Harmonic 17 (-0.155) 8.44
,Harmonic 18 2.28 3.59
,Harmonic 19 3.059 0.59
,Harmonic 20 (-1.216) 0.77
,Harmonic 21 (-0.704) 0.78
,Harmonic 22 2.027 1.97
,Harmonic 23 2.639 0.94
,Harmonic 24 0.311 1.63
,Harmonic 25 (-1.741) 1.03
,Harmonic 26 (-2.694) 0.16
,Harmonic 27 (-0.403) 1.25
,Harmonic 28 2.53 0.58
,Harmonic 29 2.513 1.48
,Harmonic 30 0.582 1.86
,Harmonic 31 (-1.788) 0.64
,Harmonic 32 (-1.465) 1.54
,Harmonic 33 0.864 0.44
,Harmonic 34 (-2.447) 0.45
,Harmonic 35 1.894 1.03
,Harmonic 36 (-2.274) 1.79
,Harmonic 37 (-0.23) 0.51
,Harmonic 38 (-2.514) 0.48
,Harmonic 39 (-3.016) 0.42
,Harmonic 40 (-0.459) 0.23
,Harmonic 41 2.838 0.64
,Harmonic 42 (-0.145) 0.24
,Harmonic 43 6.5e-2 8.0e-2
,Harmonic 44 (-0.488) 0.51
,Harmonic 45 (-0.934) 0.21
,Harmonic 46 (-2.082) 0.2
,Harmonic 47 (-1.243) 0.28
,Harmonic 48 1.482 0.51
,Harmonic 49 (-1.0) 0.9
,Harmonic 50 2.15 0.77
,Harmonic 51 1.945 0.53
,Harmonic 52 (-1.399) 1.02
,Harmonic 53 0.66 0.6
,Harmonic 54 (-2.323) 0.18
,Harmonic 55 (-0.981) 0.52
,Harmonic 56 1.81 0.22
,Harmonic 57 1.274 0.37
,Harmonic 58 2.659 0.37
,Harmonic 59 2.63 0.4
,Harmonic 60 0.479 0.37
,Harmonic 61 (-1.1) 0.54
,Harmonic 62 (-1.251) 0.23
,Harmonic 63 (-1.406) 0.18
,Harmonic 64 1.076 7.0e-2
,Harmonic 65 1.604 0.44
,Harmonic 66 (-2.315) 5.0e-2
,Harmonic 67 2.28 0.13
,Harmonic 68 0.542 0.35
,Harmonic 69 1.879 0.25
,Harmonic 70 3.124 0.56
,Harmonic 71 1.416 0.22
,Harmonic 72 (-0.707) 0.23
,Harmonic 73 0.309 0.3
,Harmonic 74 1.459 6.0e-2
,Harmonic 75 2.681 9.0e-2
,Harmonic 76 (-1.625) 0.25
,Harmonic 77 (-1.791) 8.0e-2
,Harmonic 78 1.867 0.17
,Harmonic 79 0.434 7.0e-2
,Harmonic 80 (-0.374) 0.2
,Harmonic 81 (-3.112) 0.31
,Harmonic 82 (-2.483) 0.25
,Harmonic 83 2.099 0.26
,Harmonic 84 1.844 0.13
,Harmonic 85 1.186 0.19
,Harmonic 86 (-0.742) 0.11
,Harmonic 87 3.086 0.13
,Harmonic 88 (-1.789) 0.54
,Harmonic 89 3.118 0.26
,Harmonic 90 2.218 0.11
,Harmonic 91 1.946 3.0e-2
,Harmonic 92 1.868 7.0e-2
,Harmonic 93 (-0.817) 0.14
,Harmonic 94 1.67 3.0e-2
,Harmonic 95 0.845 0.12
,Harmonic 96 2.001 0.11
,Harmonic 97 1.286 0.1
,Harmonic 98 (-1.843) 0.15
,Harmonic 99 (-1.792) 0.11
,Harmonic 100 0.701 8.0e-2
,Harmonic 101 3.121 8.0e-2
,Harmonic 102 0.462 0.19
,Harmonic 103 (-9.7e-2) 6.0e-2
,Harmonic 104 (-0.959) 0.27
,Harmonic 105 (-1.176) 0.12
,Harmonic 106 (-0.652) 0.12
,Harmonic 107 2.483 0.11
,Harmonic 108 (-2.891) 0.24]
note7 :: Note
note7 = Note
(Pitch 97.999 31 "g2")
8
(Range
(NoteRange
(NoteRangeAmplitude 4115.95 42 0.0)
(NoteRangeHarmonicFreq 1 97.99))
(NoteRange
(NoteRangeAmplitude 97.99 1 4475.0)
(NoteRangeHarmonicFreq 103 10093.89)))
[Harmonic 1 (-1.241) 4475.0
,Harmonic 2 (-2.022) 3170.3
,Harmonic 3 0.968 451.38
,Harmonic 4 (-3.5e-2) 99.79
,Harmonic 5 2.071 168.05
,Harmonic 6 3.139 43.53
,Harmonic 7 (-2.612) 6.25
,Harmonic 8 2.113 9.91
,Harmonic 9 (-0.331) 24.37
,Harmonic 10 (-2.967) 14.56
,Harmonic 11 2.874 1.45
,Harmonic 12 (-2.023) 1.35
,Harmonic 13 1.3e-2 0.25
,Harmonic 14 1.939 0.36
,Harmonic 15 2.234 0.34
,Harmonic 16 1.467 0.3
,Harmonic 17 1.849 0.41
,Harmonic 18 2.388 0.39
,Harmonic 19 (-1.278) 0.1
,Harmonic 20 (-3.024) 0.36
,Harmonic 21 1.295 0.17
,Harmonic 22 0.913 5.0e-2
,Harmonic 23 1.473 0.29
,Harmonic 24 1.191 0.4
,Harmonic 25 (-2.086) 0.16
,Harmonic 26 3.129 9.0e-2
,Harmonic 27 (-0.886) 0.13
,Harmonic 28 (-1.859) 0.61
,Harmonic 29 1.584 0.18
,Harmonic 30 1.812 0.57
,Harmonic 31 1.748 0.35
,Harmonic 32 2.9 0.22
,Harmonic 33 2.027 0.18
,Harmonic 34 2.891 0.1
,Harmonic 35 1.648 9.0e-2
,Harmonic 36 0.387 5.0e-2
,Harmonic 37 1.985 2.0e-2
,Harmonic 38 1.619 0.28
,Harmonic 39 1.366 0.11
,Harmonic 40 1.965 0.11
,Harmonic 41 1.284 0.12
,Harmonic 42 0.919 0.0
,Harmonic 43 1.785 0.17
,Harmonic 44 (-1.377) 0.11
,Harmonic 45 1.22 9.0e-2
,Harmonic 46 (-8.1e-2) 0.12
,Harmonic 47 2.274 7.0e-2
,Harmonic 48 (-7.8e-2) 3.0e-2
,Harmonic 49 1.59 0.17
,Harmonic 50 (-2.162) 0.12
,Harmonic 51 0.642 3.0e-2
,Harmonic 52 (-0.429) 0.14
,Harmonic 53 1.157 0.17
,Harmonic 54 (-3.097) 7.0e-2
,Harmonic 55 (-2.213) 0.2
,Harmonic 56 2.213 8.0e-2
,Harmonic 57 0.546 7.0e-2
,Harmonic 58 1.097 0.11
,Harmonic 59 1.147 5.0e-2
,Harmonic 60 1.409 1.0e-2
,Harmonic 61 1.088 0.14
,Harmonic 62 0.996 0.1
,Harmonic 63 1.052 9.0e-2
,Harmonic 64 1.19 6.0e-2
,Harmonic 65 (-0.614) 0.12
,Harmonic 66 (-3.055) 1.0e-2
,Harmonic 67 1.178 0.27
,Harmonic 68 0.573 0.11
,Harmonic 69 0.443 3.0e-2
,Harmonic 70 1.066 3.0e-2
,Harmonic 71 (-5.0e-2) 0.1
,Harmonic 72 (-1.593) 1.0e-2
,Harmonic 73 (-1.888) 6.0e-2
,Harmonic 74 1.753 0.13
,Harmonic 75 (-0.597) 0.14
,Harmonic 76 3.026 0.12
,Harmonic 77 1.341 0.13
,Harmonic 78 2.104 4.0e-2
,Harmonic 79 3.8e-2 6.0e-2
,Harmonic 80 (-1.608) 5.0e-2
,Harmonic 81 (-1.357) 0.14
,Harmonic 82 (-0.188) 0.17
,Harmonic 83 2.205 0.1
,Harmonic 84 (-1.148) 0.14
,Harmonic 85 (-0.219) 0.1
,Harmonic 86 (-1.179) 5.0e-2
,Harmonic 87 1.572 6.0e-2
,Harmonic 88 1.237 6.0e-2
,Harmonic 89 (-1.115) 1.0e-2
,Harmonic 90 (-1.159) 9.0e-2
,Harmonic 91 0.507 0.1
,Harmonic 92 (-2.679) 3.0e-2
,Harmonic 93 1.242 0.15
,Harmonic 94 1.169 0.1
,Harmonic 95 (-0.197) 0.15
,Harmonic 96 (-0.597) 6.0e-2
,Harmonic 97 1.369 6.0e-2
,Harmonic 98 1.931 7.0e-2
,Harmonic 99 0.968 8.0e-2
,Harmonic 100 (-0.868) 6.0e-2
,Harmonic 101 2.625 9.0e-2
,Harmonic 102 0.122 9.0e-2
,Harmonic 103 (-2.279) 0.15]
note8 :: Note
note8 = Note
(Pitch 103.826 32 "g#2")
9
(Range
(NoteRange
(NoteRangeAmplitude 5087.47 49 1.0e-2)
(NoteRangeHarmonicFreq 1 103.82))
(NoteRange
(NoteRangeAmplitude 207.65 2 10153.0)
(NoteRangeHarmonicFreq 96 9967.29)))
[Harmonic 1 (-2.038) 4330.21
,Harmonic 2 (-1.602) 10153.0
,Harmonic 3 (-1.078) 1003.27
,Harmonic 4 0.422 147.92
,Harmonic 5 2.095 161.72
,Harmonic 6 0.16 38.96
,Harmonic 7 2.906 70.14
,Harmonic 8 (-2.456) 23.18
,Harmonic 9 (-2.254) 121.03
,Harmonic 10 (-1.765) 19.03
,Harmonic 11 (-1.986) 10.52
,Harmonic 12 (-2.054) 11.68
,Harmonic 13 0.882 5.67
,Harmonic 14 (-2.359) 1.42
,Harmonic 15 (-0.947) 3.14
,Harmonic 16 (-2.975) 3.78
,Harmonic 17 1.346 1.54
,Harmonic 18 2.072 2.33
,Harmonic 19 (-1.841) 1.6
,Harmonic 20 (-2.303) 0.95
,Harmonic 21 1.626 1.03
,Harmonic 22 3.027 0.46
,Harmonic 23 (-0.976) 0.56
,Harmonic 24 (-2.085) 0.63
,Harmonic 25 2.196 0.79
,Harmonic 26 1.3e-2 0.2
,Harmonic 27 (-2.797) 0.12
,Harmonic 28 1.559 0.29
,Harmonic 29 2.212 0.32
,Harmonic 30 2.849 0.11
,Harmonic 31 3.034 0.16
,Harmonic 32 3.112 0.1
,Harmonic 33 2.487 0.29
,Harmonic 34 (-3.137) 0.18
,Harmonic 35 (-2.932) 0.3
,Harmonic 36 (-2.825) 0.28
,Harmonic 37 2.067 0.25
,Harmonic 38 1.837 0.24
,Harmonic 39 (-3.048) 0.13
,Harmonic 40 (-0.737) 0.12
,Harmonic 41 1.942 0.18
,Harmonic 42 (-1.005) 0.34
,Harmonic 43 (-0.619) 0.34
,Harmonic 44 1.729 0.17
,Harmonic 45 1.139 0.49
,Harmonic 46 1.89 0.68
,Harmonic 47 (-2.52) 0.2
,Harmonic 48 (-3.099) 0.22
,Harmonic 49 0.668 1.0e-2
,Harmonic 50 (-2.158) 0.15
,Harmonic 51 1.037 8.0e-2
,Harmonic 52 1.185 9.0e-2
,Harmonic 53 0.601 2.0e-2
,Harmonic 54 1.719 0.1
,Harmonic 55 2.223 0.16
,Harmonic 56 2.38 0.13
,Harmonic 57 1.59 9.0e-2
,Harmonic 58 1.055 0.17
,Harmonic 59 (-3.088) 0.18
,Harmonic 60 1.553 0.15
,Harmonic 61 0.533 7.0e-2
,Harmonic 62 (-2.582) 0.12
,Harmonic 63 0.291 0.1
,Harmonic 64 1.57 6.0e-2
,Harmonic 65 1.179 0.13
,Harmonic 66 2.83 0.12
,Harmonic 67 0.373 0.15
,Harmonic 68 2.462 0.12
,Harmonic 69 (-1.372) 0.19
,Harmonic 70 (-0.242) 5.0e-2
,Harmonic 71 (-1.87) 0.13
,Harmonic 72 2.42 7.0e-2
,Harmonic 73 (-0.797) 0.12
,Harmonic 74 0.536 0.1
,Harmonic 75 0.54 0.1
,Harmonic 76 (-2.654) 1.0e-2
,Harmonic 77 1.227 6.0e-2
,Harmonic 78 0.588 2.0e-2
,Harmonic 79 1.665 0.19
,Harmonic 80 0.512 8.0e-2
,Harmonic 81 1.049 0.18
,Harmonic 82 3.072 0.11
,Harmonic 83 (-1.797) 5.0e-2
,Harmonic 84 (-1.753) 7.0e-2
,Harmonic 85 (-1.217) 0.11
,Harmonic 86 (-2.293) 0.11
,Harmonic 87 0.719 0.14
,Harmonic 88 (-1.436) 9.0e-2
,Harmonic 89 0.356 0.12
,Harmonic 90 (-0.605) 7.0e-2
,Harmonic 91 (-0.389) 0.13
,Harmonic 92 (-6.9e-2) 0.18
,Harmonic 93 3.064 0.11
,Harmonic 94 2.904 0.2
,Harmonic 95 (-1.956) 0.1
,Harmonic 96 (-0.263) 0.19]
note9 :: Note
note9 = Note
(Pitch 110.0 33 "a2")
10
(Range
(NoteRange
(NoteRangeAmplitude 8580.0 78 3.0e-2)
(NoteRangeHarmonicFreq 1 110.0))
(NoteRange
(NoteRangeAmplitude 220.0 2 7763.0)
(NoteRangeHarmonicFreq 90 9900.0)))
[Harmonic 1 (-7.3e-2) 5483.36
,Harmonic 2 2.079 7763.0
,Harmonic 3 (-1.213) 833.44
,Harmonic 4 0.916 549.29
,Harmonic 5 (-0.454) 219.58
,Harmonic 6 0.389 57.48
,Harmonic 7 8.8e-2 53.79
,Harmonic 8 (-0.917) 81.61
,Harmonic 9 0.149 109.35
,Harmonic 10 1.473 52.87
,Harmonic 11 2.853 10.77
,Harmonic 12 (-1.694) 13.93
,Harmonic 13 (-0.824) 10.24
,Harmonic 14 2.23 8.29
,Harmonic 15 (-0.174) 17.52
,Harmonic 16 0.65 3.05
,Harmonic 17 (-1.186) 13.75
,Harmonic 18 1.148 6.54
,Harmonic 19 (-1.017) 4.73
,Harmonic 20 6.6e-2 4.81
,Harmonic 21 (-0.4) 0.96
,Harmonic 22 (-0.393) 3.39
,Harmonic 23 0.36 2.89
,Harmonic 24 1.204 1.2
,Harmonic 25 1.967 4.06
,Harmonic 26 1.115 0.52
,Harmonic 27 (-5.5e-2) 2.33
,Harmonic 28 1.11 1.38
,Harmonic 29 1.086 0.2
,Harmonic 30 2.311 1.34
,Harmonic 31 0.794 0.67
,Harmonic 32 3.111 0.97
,Harmonic 33 2.567 0.28
,Harmonic 34 (-3.11) 0.82
,Harmonic 35 0.373 0.54
,Harmonic 36 (-2.115) 0.48
,Harmonic 37 0.309 0.93
,Harmonic 38 (-3.035) 0.32
,Harmonic 39 (-2.699) 0.25
,Harmonic 40 (-1.156) 0.56
,Harmonic 41 1.629 0.87
,Harmonic 42 (-1.572) 1.05
,Harmonic 43 (-1.111) 0.34
,Harmonic 44 (-0.199) 0.89
,Harmonic 45 (-3.015) 0.86
,Harmonic 46 (-1.584) 0.38
,Harmonic 47 (-1.799) 0.68
,Harmonic 48 (-2.139) 0.14
,Harmonic 49 0.216 0.1
,Harmonic 50 (-0.112) 0.63
,Harmonic 51 (-2.26) 0.41
,Harmonic 52 (-2.258) 0.31
,Harmonic 53 (-2.683) 0.1
,Harmonic 54 (-1.152) 0.48
,Harmonic 55 1.049 0.81
,Harmonic 56 (-1.989) 0.26
,Harmonic 57 (-1.42) 0.13
,Harmonic 58 (-2.048) 0.15
,Harmonic 59 2.983 0.4
,Harmonic 60 (-3.007) 5.0e-2
,Harmonic 61 2.757 0.26
,Harmonic 62 1.623 0.16
,Harmonic 63 2.261 0.19
,Harmonic 64 (-1.831) 0.12
,Harmonic 65 (-1.378) 0.16
,Harmonic 66 (-1.936) 0.1
,Harmonic 67 (-3.006) 0.36
,Harmonic 68 (-2.203) 0.28
,Harmonic 69 1.055 0.48
,Harmonic 70 2.33 0.36
,Harmonic 71 2.131 0.13
,Harmonic 72 (-0.548) 0.18
,Harmonic 73 (-2.831) 0.42
,Harmonic 74 3.104 0.11
,Harmonic 75 1.254 8.0e-2
,Harmonic 76 (-1.874) 9.0e-2
,Harmonic 77 (-1.17) 0.21
,Harmonic 78 (-1.881) 3.0e-2
,Harmonic 79 1.167 4.0e-2
,Harmonic 80 (-2.322) 5.0e-2
,Harmonic 81 (-2.323) 0.18
,Harmonic 82 2.317 0.13
,Harmonic 83 (-1.332) 0.2
,Harmonic 84 2.125 8.0e-2
,Harmonic 85 (-1.224) 0.24
,Harmonic 86 1.628 0.18
,Harmonic 87 (-1.755) 0.25
,Harmonic 88 0.672 0.2
,Harmonic 89 (-0.367) 0.11
,Harmonic 90 3.036 0.25]
note10 :: Note
note10 = Note
(Pitch 116.541 34 "a#2")
11
(Range
(NoteRange
(NoteRangeAmplitude 7109.0 61 2.0e-2)
(NoteRangeHarmonicFreq 1 116.54))
(NoteRange
(NoteRangeAmplitude 233.08 2 4018.0)
(NoteRangeHarmonicFreq 86 10022.52)))
[Harmonic 1 (-1.764) 3210.33
,Harmonic 2 (-1.232) 4018.0
,Harmonic 3 (-0.833) 358.37
,Harmonic 4 (-1.362) 617.48
,Harmonic 5 (-1.585) 178.39
,Harmonic 6 2.171 62.09
,Harmonic 7 2.375 119.12
,Harmonic 8 1.101 72.44
,Harmonic 9 (-1.624) 18.25
,Harmonic 10 1.027 11.58
,Harmonic 11 0.944 8.33
,Harmonic 12 0.64 3.44
,Harmonic 13 (-1.564) 4.07
,Harmonic 14 1.774 8.22
,Harmonic 15 (-0.905) 1.26
,Harmonic 16 (-2.491) 3.3
,Harmonic 17 (-2.238) 3.25
,Harmonic 18 1.636 1.54
,Harmonic 19 (-0.206) 0.74
,Harmonic 20 2.772 0.87
,Harmonic 21 (-2.422) 1.43
,Harmonic 22 0.569 0.38
,Harmonic 23 (-2.306) 0.34
,Harmonic 24 3.139 0.47
,Harmonic 25 (-0.781) 0.43
,Harmonic 26 (-2.331) 0.53
,Harmonic 27 (-1.03) 0.19
,Harmonic 28 (-2.403) 0.38
,Harmonic 29 3.074 0.18
,Harmonic 30 1.739 0.16
,Harmonic 31 1.427 0.13
,Harmonic 32 0.887 0.2
,Harmonic 33 0.605 0.2
,Harmonic 34 (-2.308) 0.11
,Harmonic 35 2.296 0.15
,Harmonic 36 (-1.589) 4.0e-2
,Harmonic 37 (-2.829) 0.15
,Harmonic 38 (-2.311) 0.14
,Harmonic 39 0.838 0.27
,Harmonic 40 (-0.671) 9.0e-2
,Harmonic 41 1.491 0.1
,Harmonic 42 (-0.949) 0.2
,Harmonic 43 (-1.55) 0.15
,Harmonic 44 (-0.3) 0.25
,Harmonic 45 (-1.044) 0.1
,Harmonic 46 (-1.539) 0.33
,Harmonic 47 (-2.651) 2.0e-2
,Harmonic 48 (-1.959) 6.0e-2
,Harmonic 49 2.647 0.1
,Harmonic 50 (-1.873) 0.13
,Harmonic 51 (-2.013) 0.13
,Harmonic 52 0.752 0.13
,Harmonic 53 (-0.382) 0.11
,Harmonic 54 (-1.583) 7.0e-2
,Harmonic 55 0.873 0.1
,Harmonic 56 1.945 0.12
,Harmonic 57 (-6.5e-2) 0.19
,Harmonic 58 (-1.403) 0.11
,Harmonic 59 (-2.267) 0.15
,Harmonic 60 0.471 8.0e-2
,Harmonic 61 2.935 2.0e-2
,Harmonic 62 (-2.237) 5.0e-2
,Harmonic 63 0.578 0.25
,Harmonic 64 (-2.677) 0.12
,Harmonic 65 (-1.244) 0.49
,Harmonic 66 1.085 0.25
,Harmonic 67 1.082 0.16
,Harmonic 68 1.158 8.0e-2
,Harmonic 69 1.7e-2 0.19
,Harmonic 70 (-1.602) 0.37
,Harmonic 71 (-1.631) 0.12
,Harmonic 72 (-2.408) 0.2
,Harmonic 73 (-0.638) 0.28
,Harmonic 74 (-2.315) 4.0e-2
,Harmonic 75 (-2.1e-2) 7.0e-2
,Harmonic 76 0.349 0.16
,Harmonic 77 0.886 0.11
,Harmonic 78 (-0.858) 0.1
,Harmonic 79 0.704 0.1
,Harmonic 80 (-2.601) 7.0e-2
,Harmonic 81 (-2.343) 0.12
,Harmonic 82 (-2.196) 0.24
,Harmonic 83 (-2.331) 7.0e-2
,Harmonic 84 2.28 0.11
,Harmonic 85 1.556 6.0e-2
,Harmonic 86 2.414 7.0e-2]
note11 :: Note
note11 = Note
(Pitch 123.471 35 "b2")
12
(Range
(NoteRange
(NoteRangeAmplitude 5309.25 43 1.0e-2)
(NoteRangeHarmonicFreq 1 123.47))
(NoteRange
(NoteRangeAmplitude 123.47 1 2607.0)
(NoteRangeHarmonicFreq 80 9877.68)))
[Harmonic 1 (-1.62) 2607.0
,Harmonic 2 (-1.482) 2037.78
,Harmonic 3 (-0.924) 172.97
,Harmonic 4 1.735 320.18
,Harmonic 5 0.111 57.63
,Harmonic 6 0.218 10.45
,Harmonic 7 (-2.793) 37.01
,Harmonic 8 3.031 16.94
,Harmonic 9 0.629 25.5
,Harmonic 10 (-3.049) 3.7
,Harmonic 11 (-0.596) 7.29
,Harmonic 12 (-2.029) 2.25
,Harmonic 13 1.461 0.69
,Harmonic 14 (-4.0e-2) 0.78
,Harmonic 15 (-1.655) 0.44
,Harmonic 16 (-0.727) 0.25
,Harmonic 17 (-1.269) 0.37
,Harmonic 18 (-0.106) 1.36
,Harmonic 19 1.467 1.17
,Harmonic 20 0.116 1.0
,Harmonic 21 0.16 0.95
,Harmonic 22 (-2.105) 0.39
,Harmonic 23 (-3.104) 0.46
,Harmonic 24 (-1.262) 0.35
,Harmonic 25 (-0.879) 0.63
,Harmonic 26 (-1.606) 0.11
,Harmonic 27 (-1.711) 0.33
,Harmonic 28 2.37 0.11
,Harmonic 29 (-0.598) 0.27
,Harmonic 30 1.073 0.23
,Harmonic 31 (-2.698) 0.17
,Harmonic 32 1.128 6.0e-2
,Harmonic 33 1.8e-2 0.27
,Harmonic 34 (-1.862) 0.18
,Harmonic 35 1.299 7.0e-2
,Harmonic 36 (-1.646) 0.32
,Harmonic 37 2.182 0.11
,Harmonic 38 (-7.1e-2) 0.15
,Harmonic 39 (-0.961) 0.11
,Harmonic 40 (-1.621) 0.15
,Harmonic 41 1.975 8.0e-2
,Harmonic 42 0.363 0.14
,Harmonic 43 (-2.69) 1.0e-2
,Harmonic 44 1.549 0.12
,Harmonic 45 (-1.184) 7.0e-2
,Harmonic 46 2.427 0.1
,Harmonic 47 0.426 0.23
,Harmonic 48 (-0.698) 5.0e-2
,Harmonic 49 1.606 5.0e-2
,Harmonic 50 (-3.062) 7.0e-2
,Harmonic 51 1.375 6.0e-2
,Harmonic 52 (-0.54) 0.23
,Harmonic 53 (-2.284) 0.11
,Harmonic 54 2.977 1.0e-2
,Harmonic 55 2.533 0.11
,Harmonic 56 (-0.802) 0.19
,Harmonic 57 (-1.639) 9.0e-2
,Harmonic 58 (-0.881) 0.35
,Harmonic 59 1.014 0.32
,Harmonic 60 0.253 3.0e-2
,Harmonic 61 0.927 0.17
,Harmonic 62 0.139 0.28
,Harmonic 63 (-2.353) 6.0e-2
,Harmonic 64 (-0.915) 0.11
,Harmonic 65 2.7 2.0e-2
,Harmonic 66 2.568 0.15
,Harmonic 67 0.953 0.24
,Harmonic 68 2.658 0.26
,Harmonic 69 (-0.76) 0.15
,Harmonic 70 (-2.264) 0.22
,Harmonic 71 (-2.412) 0.11
,Harmonic 72 (-0.923) 0.12
,Harmonic 73 (-1.744) 0.1
,Harmonic 74 (-1.261) 0.17
,Harmonic 75 (-5.4e-2) 6.0e-2
,Harmonic 76 (-1.837) 0.1
,Harmonic 77 (-1.54) 0.49
,Harmonic 78 (-1.387) 0.21
,Harmonic 79 1.58 0.27
,Harmonic 80 (-2.801) 6.0e-2]
note12 :: Note
note12 = Note
(Pitch 130.813 36 "c3")
13
(Range
(NoteRange
(NoteRangeAmplitude 6671.46 51 1.0e-2)
(NoteRangeHarmonicFreq 1 130.81))
(NoteRange
(NoteRangeAmplitude 130.81 1 2954.0)
(NoteRangeHarmonicFreq 77 10072.6)))
[Harmonic 1 (-1.486) 2954.0
,Harmonic 2 (-1.268) 993.45
,Harmonic 3 (-1.44) 809.85
,Harmonic 4 (-2.058) 300.6
,Harmonic 5 2.388 37.35
,Harmonic 6 0.117 46.75
,Harmonic 7 1.179 21.3
,Harmonic 8 (-3.08) 11.97
,Harmonic 9 (-0.179) 9.02
,Harmonic 10 (-1.277) 7.95
,Harmonic 11 0.734 6.94
,Harmonic 12 1.555 2.53
,Harmonic 13 (-2.167) 2.79
,Harmonic 14 (-3.039) 1.2
,Harmonic 15 2.86 0.49
,Harmonic 16 1.399 0.98
,Harmonic 17 3.072 0.49
,Harmonic 18 2.57 1.09
,Harmonic 19 (-1.54) 1.13
,Harmonic 20 0.631 0.91
,Harmonic 21 (-2.87) 0.8
,Harmonic 22 0.641 1.17
,Harmonic 23 (-0.968) 0.69
,Harmonic 24 (-2.884) 1.16
,Harmonic 25 1.662 0.31
,Harmonic 26 2.303 0.75
,Harmonic 27 (-0.132) 0.11
,Harmonic 28 (-0.574) 0.8
,Harmonic 29 1.66 0.45
,Harmonic 30 1.183 0.48
,Harmonic 31 (-1.621) 0.59
,Harmonic 32 (-0.674) 0.21
,Harmonic 33 0.15 0.26
,Harmonic 34 (-1.429) 0.23
,Harmonic 35 1.469 0.15
,Harmonic 36 (-2.564) 0.44
,Harmonic 37 2.451 0.17
,Harmonic 38 0.102 0.14
,Harmonic 39 2.768 0.28
,Harmonic 40 0.862 6.0e-2
,Harmonic 41 (-1.506) 0.2
,Harmonic 42 (-2.607) 0.11
,Harmonic 43 (-0.721) 0.16
,Harmonic 44 1.072 2.0e-2
,Harmonic 45 0.823 0.18
,Harmonic 46 0.393 9.0e-2
,Harmonic 47 (-2.921) 0.13
,Harmonic 48 (-3.105) 6.0e-2
,Harmonic 49 0.14 0.17
,Harmonic 50 (-0.531) 4.0e-2
,Harmonic 51 3.074 1.0e-2
,Harmonic 52 (-0.179) 0.15
,Harmonic 53 (-0.164) 2.0e-2
,Harmonic 54 0.327 0.27
,Harmonic 55 (-1.725) 0.14
,Harmonic 56 0.59 0.13
,Harmonic 57 0.542 0.21
,Harmonic 58 (-3.11) 0.13
,Harmonic 59 (-0.691) 0.1
,Harmonic 60 2.036 0.14
,Harmonic 61 1.982 0.38
,Harmonic 62 (-1.054) 4.0e-2
,Harmonic 63 4.0e-3 0.14
,Harmonic 64 (-0.785) 2.0e-2
,Harmonic 65 (-2.707) 0.21
,Harmonic 66 (-0.392) 0.16
,Harmonic 67 (-1.355) 7.0e-2
,Harmonic 68 (-0.123) 0.2
,Harmonic 69 0.265 0.2
,Harmonic 70 (-0.833) 8.0e-2
,Harmonic 71 0.879 0.13
,Harmonic 72 1.874 8.0e-2
,Harmonic 73 (-0.776) 0.14
,Harmonic 74 (-0.416) 0.12
,Harmonic 75 (-2.055) 0.23
,Harmonic 76 (-2.332) 0.27
,Harmonic 77 1.111 0.11]
note13 :: Note
note13 = Note
(Pitch 138.591 37 "c#3")
14
(Range
(NoteRange
(NoteRangeAmplitude 9562.77 69 5.0e-2)
(NoteRangeHarmonicFreq 1 138.59))
(NoteRange
(NoteRangeAmplitude 138.59 1 3780.0)
(NoteRangeHarmonicFreq 72 9978.55)))
[Harmonic 1 (-1.808) 3780.0
,Harmonic 2 (-2.152) 426.42
,Harmonic 3 1.392 445.17
,Harmonic 4 1.762 59.27
,Harmonic 5 (-3.127) 364.85
,Harmonic 6 (-0.441) 72.1
,Harmonic 7 (-1.124) 189.53
,Harmonic 8 1.752 15.54
,Harmonic 9 2.133 22.33
,Harmonic 10 (-2.488) 1.54
,Harmonic 11 (-8.1e-2) 6.46
,Harmonic 12 2.328 4.29
,Harmonic 13 (-2.981) 4.58
,Harmonic 14 (-0.245) 1.91
,Harmonic 15 0.403 1.45
,Harmonic 16 0.926 2.7
,Harmonic 17 2.604 3.41
,Harmonic 18 (-2.934) 2.93
,Harmonic 19 (-2.147) 6.76
,Harmonic 20 (-2.833) 15.33
,Harmonic 21 2.996 3.7
,Harmonic 22 (-2.666) 1.21
,Harmonic 23 2.715 3.88
,Harmonic 24 1.6 3.86
,Harmonic 25 2.186 2.1
,Harmonic 26 (-3.125) 1.77
,Harmonic 27 (-2.422) 2.72
,Harmonic 28 (-1.887) 2.51
,Harmonic 29 (-1.512) 2.49
,Harmonic 30 (-1.776) 1.24
,Harmonic 31 0.174 0.91
,Harmonic 32 0.909 1.25
,Harmonic 33 1.729 0.91
,Harmonic 34 2.661 0.64
,Harmonic 35 2.625 2.16
,Harmonic 36 2.161 2.93
,Harmonic 37 1.521 1.79
,Harmonic 38 1.888 1.12
,Harmonic 39 1.764 1.48
,Harmonic 40 1.814 2.38
,Harmonic 41 (-2.748) 2.23
,Harmonic 42 (-1.906) 1.33
,Harmonic 43 (-1.009) 1.15
,Harmonic 44 (-0.224) 1.99
,Harmonic 45 1.055 1.05
,Harmonic 46 (-2.699) 0.8
,Harmonic 47 1.039 0.76
,Harmonic 48 0.915 0.97
,Harmonic 49 1.085 0.48
,Harmonic 50 0.961 0.43
,Harmonic 51 0.369 0.39
,Harmonic 52 1.115 0.44
,Harmonic 53 3.023 0.92
,Harmonic 54 (-2.954) 1.81
,Harmonic 55 (-2.574) 1.31
,Harmonic 56 (-1.668) 0.86
,Harmonic 57 (-2.073) 0.93
,Harmonic 58 (-2.219) 0.79
,Harmonic 59 (-0.964) 1.02
,Harmonic 60 (-0.954) 1.68
,Harmonic 61 (-1.096) 0.77
,Harmonic 62 (-0.299) 1.13
,Harmonic 63 0.656 0.87
,Harmonic 64 1.441 1.77
,Harmonic 65 2.016 1.77
,Harmonic 66 2.893 0.73
,Harmonic 67 (-1.303) 0.75
,Harmonic 68 (-0.782) 0.72
,Harmonic 69 1.329 5.0e-2
,Harmonic 70 1.677 0.84
,Harmonic 71 1.818 0.64
,Harmonic 72 1.782 0.6]
note14 :: Note
note14 = Note
(Pitch 146.832 38 "d3")
15
(Range
(NoteRange
(NoteRangeAmplitude 2496.14 17 3.0e-2)
(NoteRangeHarmonicFreq 1 146.83))
(NoteRange
(NoteRangeAmplitude 146.83 1 2313.0)
(NoteRangeHarmonicFreq 68 9984.57)))
[Harmonic 1 (-1.766) 2313.0
,Harmonic 2 (-1.386) 1937.19
,Harmonic 3 2.488 15.36
,Harmonic 4 1.314 275.23
,Harmonic 5 (-1.355) 68.55
,Harmonic 6 (-2.81) 11.52
,Harmonic 7 (-0.901) 11.17
,Harmonic 8 2.578 28.17
,Harmonic 9 2.186 8.7
,Harmonic 10 (-0.157) 4.09
,Harmonic 11 2.632 5.31
,Harmonic 12 (-0.176) 0.87
,Harmonic 13 (-3.7e-2) 1.24
,Harmonic 14 2.072 0.24
,Harmonic 15 2.802 0.74
,Harmonic 16 (-0.959) 0.36
,Harmonic 17 2.207 3.0e-2
,Harmonic 18 (-0.933) 0.17
,Harmonic 19 (-0.591) 0.16
,Harmonic 20 (-0.157) 0.12
,Harmonic 21 1.778 0.13
,Harmonic 22 (-0.396) 0.34
,Harmonic 23 1.445 0.16
,Harmonic 24 0.325 0.18
,Harmonic 25 (-0.3) 0.25
,Harmonic 26 (-2.397) 0.32
,Harmonic 27 (-2.693) 0.13
,Harmonic 28 0.264 0.36
,Harmonic 29 (-1.218) 0.32
,Harmonic 30 0.899 0.17
,Harmonic 31 1.591 9.0e-2
,Harmonic 32 2.502 0.15
,Harmonic 33 1.5e-2 0.28
,Harmonic 34 (-0.209) 0.12
,Harmonic 35 (-0.644) 0.11
,Harmonic 36 (-0.654) 0.11
,Harmonic 37 (-1.593) 0.11
,Harmonic 38 (-0.731) 0.17
,Harmonic 39 2.12 7.0e-2
,Harmonic 40 0.286 0.31
,Harmonic 41 1.69 0.2
,Harmonic 42 (-2.215) 0.16
,Harmonic 43 0.764 0.2
,Harmonic 44 (-1.195) 0.17
,Harmonic 45 6.6e-2 0.17
,Harmonic 46 (-2.988) 7.0e-2
,Harmonic 47 (-0.705) 0.34
,Harmonic 48 0.446 0.28
,Harmonic 49 (-2.3e-2) 6.0e-2
,Harmonic 50 1.587 5.0e-2
,Harmonic 51 (-1.454) 8.0e-2
,Harmonic 52 1.85 6.0e-2
,Harmonic 53 0.499 0.16
,Harmonic 54 0.101 0.16
,Harmonic 55 (-1.569) 0.12
,Harmonic 56 (-1.139) 6.0e-2
,Harmonic 57 (-0.44) 5.0e-2
,Harmonic 58 (-1.071) 0.2
,Harmonic 59 0.741 0.19
,Harmonic 60 2.471 0.1
,Harmonic 61 (-1.037) 0.19
,Harmonic 62 0.271 0.28
,Harmonic 63 0.123 7.0e-2
,Harmonic 64 (-1.94) 0.38
,Harmonic 65 1.58 0.1
,Harmonic 66 (-0.57) 0.12
,Harmonic 67 (-2.114) 0.15
,Harmonic 68 1.352 3.0e-2]
note15 :: Note
note15 = Note
(Pitch 155.563 39 "d#3")
16
(Range
(NoteRange
(NoteRangeAmplitude 9178.21 59 5.0e-2)
(NoteRangeHarmonicFreq 1 155.56))
(NoteRange
(NoteRangeAmplitude 155.56 1 3883.0)
(NoteRangeHarmonicFreq 64 9956.03)))
[Harmonic 1 (-1.654) 3883.0
,Harmonic 2 (-1.135) 3232.97
,Harmonic 3 (-2.768) 181.52
,Harmonic 4 (-0.999) 247.21
,Harmonic 5 (-2.36) 66.86
,Harmonic 6 (-1.041) 37.11
,Harmonic 7 2.414 97.86
,Harmonic 8 2.52 9.01
,Harmonic 9 2.434 1.82
,Harmonic 10 (-3.3e-2) 4.17
,Harmonic 11 (-1.935) 16.63
,Harmonic 12 2.491 4.45
,Harmonic 13 0.794 4.38
,Harmonic 14 (-1.077) 0.5
,Harmonic 15 1.186 0.93
,Harmonic 16 1.338 1.23
,Harmonic 17 (-5.1e-2) 0.18
,Harmonic 18 (-0.201) 1.3
,Harmonic 19 1.864 1.27
,Harmonic 20 3.005 0.89
,Harmonic 21 0.471 0.93
,Harmonic 22 (-1.499) 0.62
,Harmonic 23 1.105 0.1
,Harmonic 24 1.49 0.41
,Harmonic 25 0.72 0.25
,Harmonic 26 (-1.32) 0.32
,Harmonic 27 (-0.148) 0.52
,Harmonic 28 (-0.155) 0.11
,Harmonic 29 (-2.396) 0.18
,Harmonic 30 1.554 0.31
,Harmonic 31 2.636 0.15
,Harmonic 32 1.854 0.13
,Harmonic 33 3.037 0.28
,Harmonic 34 (-2.582) 0.14
,Harmonic 35 (-0.302) 0.23
,Harmonic 36 (-0.676) 0.11
,Harmonic 37 1.693 0.37
,Harmonic 38 1.488 0.12
,Harmonic 39 0.998 8.0e-2
,Harmonic 40 1.445 9.0e-2
,Harmonic 41 (-2.156) 0.24
,Harmonic 42 (-1.586) 6.0e-2
,Harmonic 43 (-1.743) 0.11
,Harmonic 44 (-1.869) 0.23
,Harmonic 45 (-9.0e-3) 0.18
,Harmonic 46 (-1.619) 0.22
,Harmonic 47 1.369 0.28
,Harmonic 48 (-0.169) 6.0e-2
,Harmonic 49 0.177 0.37
,Harmonic 50 (-2.908) 0.12
,Harmonic 51 0.334 0.18
,Harmonic 52 (-1.296) 0.33
,Harmonic 53 (-2.446) 0.22
,Harmonic 54 0.711 0.16
,Harmonic 55 0.799 0.21
,Harmonic 56 0.181 0.16
,Harmonic 57 (-0.689) 0.13
,Harmonic 58 1.215 0.18
,Harmonic 59 1.825 5.0e-2
,Harmonic 60 (-1.4e-2) 0.23
,Harmonic 61 (-1.434) 0.32
,Harmonic 62 9.6e-2 0.18
,Harmonic 63 (-0.751) 0.23
,Harmonic 64 0.965 0.23]
note16 :: Note
note16 = Note
(Pitch 164.814 40 "e3")
17
(Range
(NoteRange
(NoteRangeAmplitude 7416.63 45 0.0)
(NoteRangeHarmonicFreq 1 164.81))
(NoteRange
(NoteRangeAmplitude 164.81 1 4062.0)
(NoteRangeHarmonicFreq 59 9724.02)))
[Harmonic 1 1.374 4062.0
,Harmonic 2 (-1.115) 563.06
,Harmonic 3 (-2.2) 17.19
,Harmonic 4 1.585 122.58
,Harmonic 5 4.6e-2 17.13
,Harmonic 6 1.214 62.2
,Harmonic 7 (-0.63) 29.1
,Harmonic 8 2.502 28.25
,Harmonic 9 2.507 17.31
,Harmonic 10 (-6.1e-2) 17.22
,Harmonic 11 2.44 21.35
,Harmonic 12 9.7e-2 6.33
,Harmonic 13 (-2.736) 3.1
,Harmonic 14 3.128 1.48
,Harmonic 15 0.314 2.0e-2
,Harmonic 16 2.066 0.42
,Harmonic 17 (-2.596) 0.61
,Harmonic 18 (-2.562) 0.57
,Harmonic 19 0.567 0.43
,Harmonic 20 (-1.592) 0.17
,Harmonic 21 (-1.473) 0.27
,Harmonic 22 2.303 0.25
,Harmonic 23 0.52 0.29
,Harmonic 24 3.088 5.0e-2
,Harmonic 25 (-2.898) 0.17
,Harmonic 26 2.819 0.13
,Harmonic 27 0.931 6.0e-2
,Harmonic 28 0.503 0.15
,Harmonic 29 (-1.12) 0.12
,Harmonic 30 0.349 3.0e-2
,Harmonic 31 2.73 0.22
,Harmonic 32 1.618 0.26
,Harmonic 33 1.468 0.24
,Harmonic 34 (-1.126) 5.0e-2
,Harmonic 35 1.68 0.22
,Harmonic 36 1.369 8.0e-2
,Harmonic 37 (-0.139) 0.1
,Harmonic 38 1.579 0.13
,Harmonic 39 1.581 9.0e-2
,Harmonic 40 (-3.134) 0.1
,Harmonic 41 0.506 0.1
,Harmonic 42 0.875 0.18
,Harmonic 43 (-0.305) 0.12
,Harmonic 44 (-2.478) 3.0e-2
,Harmonic 45 1.72 0.0
,Harmonic 46 0.925 0.24
,Harmonic 47 (-1.174) 8.0e-2
,Harmonic 48 2.068 6.0e-2
,Harmonic 49 (-5.0e-3) 0.14
,Harmonic 50 (-2.082) 5.0e-2
,Harmonic 51 2.226 6.0e-2
,Harmonic 52 (-2.302) 3.0e-2
,Harmonic 53 (-1.932) 7.0e-2
,Harmonic 54 1.436 0.11
,Harmonic 55 (-2.758) 0.11
,Harmonic 56 (-1.888) 7.0e-2
,Harmonic 57 (-0.528) 2.0e-2
,Harmonic 58 1.534 0.13
,Harmonic 59 1.842 0.13]
note17 :: Note
note17 = Note
(Pitch 174.614 41 "f3")
18
(Range
(NoteRange
(NoteRangeAmplitude 9603.77 55 3.0e-2)
(NoteRangeHarmonicFreq 1 174.61))
(NoteRange
(NoteRangeAmplitude 174.61 1 5132.0)
(NoteRangeHarmonicFreq 60 10476.84)))
[Harmonic 1 (-1.165) 5132.0
,Harmonic 2 0.134 1073.77
,Harmonic 3 (-2.564) 541.39
,Harmonic 4 0.804 176.36
,Harmonic 5 2.801 100.69
,Harmonic 6 (-0.433) 57.36
,Harmonic 7 (-1.366) 19.96
,Harmonic 8 (-2.791) 10.09
,Harmonic 9 (-0.611) 4.28
,Harmonic 10 (-1.661) 0.84
,Harmonic 11 0.768 4.8
,Harmonic 12 2.731 7.15
,Harmonic 13 (-1.642) 15.78
,Harmonic 14 (-2.381) 20.06
,Harmonic 15 (-2.102) 5.39
,Harmonic 16 (-0.273) 8.42
,Harmonic 17 2.907 4.63
,Harmonic 18 (-0.796) 3.35
,Harmonic 19 (-1.858) 1.73
,Harmonic 20 0.659 0.65
,Harmonic 21 0.756 0.68
,Harmonic 22 (-2.57) 0.68
,Harmonic 23 1.519 0.36
,Harmonic 24 0.427 0.35
,Harmonic 25 2.556 0.36
,Harmonic 26 (-0.436) 0.54
,Harmonic 27 (-1.335) 0.14
,Harmonic 28 2.716 0.12
,Harmonic 29 1.21 0.22
,Harmonic 30 1.952 0.14
,Harmonic 31 (-2.285) 0.3
,Harmonic 32 2.062 0.34
,Harmonic 33 (-2.215) 6.0e-2
,Harmonic 34 1.193 0.15
,Harmonic 35 2.379 0.2
,Harmonic 36 1.855 4.0e-2
,Harmonic 37 1.66 0.11
,Harmonic 38 1.75 0.25
,Harmonic 39 (-1.854) 0.24
,Harmonic 40 2.699 0.35
,Harmonic 41 1.997 0.46
,Harmonic 42 (-2.73) 0.37
,Harmonic 43 0.895 0.2
,Harmonic 44 1.141 0.1
,Harmonic 45 (-0.451) 0.31
,Harmonic 46 0.226 0.27
,Harmonic 47 (-0.583) 0.13
,Harmonic 48 (-2.79) 0.32
,Harmonic 49 0.381 0.1
,Harmonic 50 (-0.654) 0.16
,Harmonic 51 (-2.78) 8.0e-2
,Harmonic 52 0.339 0.1
,Harmonic 53 2.046 0.13
,Harmonic 54 0.878 0.27
,Harmonic 55 1.175 3.0e-2
,Harmonic 56 0.735 0.27
,Harmonic 57 1.239 5.0e-2
,Harmonic 58 (-3.132) 7.0e-2
,Harmonic 59 1.223 0.18
,Harmonic 60 (-2.607) 0.22]
note18 :: Note
note18 = Note
(Pitch 184.997 42 "f#3")
19
(Range
(NoteRange
(NoteRangeAmplitude 7029.88 38 1.0e-2)
(NoteRangeHarmonicFreq 1 184.99))
(NoteRange
(NoteRangeAmplitude 184.99 1 4711.0)
(NoteRangeHarmonicFreq 52 9619.84)))
[Harmonic 1 (-1.741) 4711.0
,Harmonic 2 (-2.317) 154.31
,Harmonic 3 (-2.011) 203.03
,Harmonic 4 0.246 24.45
,Harmonic 5 0.926 114.76
,Harmonic 6 (-0.553) 26.75
,Harmonic 7 0.892 49.75
,Harmonic 8 (-0.863) 30.25
,Harmonic 9 2.088 14.42
,Harmonic 10 1.432 13.21
,Harmonic 11 2.486 1.93
,Harmonic 12 0.696 2.03
,Harmonic 13 (-1.205) 0.81
,Harmonic 14 (-2.482) 0.92
,Harmonic 15 (-2.82) 0.54
,Harmonic 16 (-1.904) 0.22
,Harmonic 17 (-0.497) 8.0e-2
,Harmonic 18 (-1.453) 2.0e-2
,Harmonic 19 (-2.255) 9.0e-2
,Harmonic 20 1.856 0.1
,Harmonic 21 (-1.439) 7.0e-2
,Harmonic 22 2.282 0.24
,Harmonic 23 (-2.199) 0.19
,Harmonic 24 (-1.708) 0.24
,Harmonic 25 2.475 0.35
,Harmonic 26 (-2.5) 0.18
,Harmonic 27 (-2.681) 0.16
,Harmonic 28 2.865 2.0e-2
,Harmonic 29 (-2.771) 0.23
,Harmonic 30 (-0.631) 7.0e-2
,Harmonic 31 (-1.535) 5.0e-2
,Harmonic 32 (-3.075) 0.16
,Harmonic 33 1.062 0.14
,Harmonic 34 (-1.343) 0.27
,Harmonic 35 (-2.285) 9.0e-2
,Harmonic 36 (-2.07) 5.0e-2
,Harmonic 37 1.536 0.19
,Harmonic 38 (-2.276) 1.0e-2
,Harmonic 39 (-1.782) 2.0e-2
,Harmonic 40 (-0.823) 6.0e-2
,Harmonic 41 2.4e-2 0.19
,Harmonic 42 (-2.066) 0.11
,Harmonic 43 (-1.934) 5.0e-2
,Harmonic 44 0.834 0.1
,Harmonic 45 0.182 0.18
,Harmonic 46 (-0.437) 0.14
,Harmonic 47 1.214 0.12
,Harmonic 48 (-0.915) 0.39
,Harmonic 49 (-2.21) 0.18
,Harmonic 50 1.085 6.0e-2
,Harmonic 51 (-2.814) 5.0e-2
,Harmonic 52 1.595 0.2]
note19 :: Note
note19 = Note
(Pitch 195.998 43 "g3")
20
(Range
(NoteRange
(NoteRangeAmplitude 5879.94 30 4.0e-2)
(NoteRangeHarmonicFreq 1 195.99))
(NoteRange
(NoteRangeAmplitude 195.99 1 5458.0)
(NoteRangeHarmonicFreq 51 9995.89)))
[Harmonic 1 1.724 5458.0
,Harmonic 2 (-0.602) 611.1
,Harmonic 3 2.523 225.92
,Harmonic 4 (-1.346) 34.21
,Harmonic 5 7.0e-2 49.72
,Harmonic 6 2.02 141.7
,Harmonic 7 2.438 54.04
,Harmonic 8 (-1.628) 45.89
,Harmonic 9 2.259 14.74
,Harmonic 10 (-1.039) 22.33
,Harmonic 11 0.737 2.59
,Harmonic 12 (-0.122) 1.95
,Harmonic 13 (-2.5e-2) 4.07
,Harmonic 14 (-1.351) 2.32
,Harmonic 15 1.297 0.39
,Harmonic 16 (-0.694) 0.53
,Harmonic 17 (-0.973) 0.61
,Harmonic 18 5.7e-2 0.28
,Harmonic 19 1.22 9.0e-2
,Harmonic 20 (-1.459) 0.26
,Harmonic 21 (-0.801) 0.87
,Harmonic 22 (-1.207) 0.3
,Harmonic 23 (-0.454) 0.52
,Harmonic 24 (-0.999) 0.49
,Harmonic 25 1.08 8.0e-2
,Harmonic 26 (-0.521) 0.14
,Harmonic 27 (-2.701) 0.27
,Harmonic 28 (-1.514) 0.27
,Harmonic 29 3.041 0.23
,Harmonic 30 (-0.627) 4.0e-2
,Harmonic 31 1.354 0.23
,Harmonic 32 0.982 0.13
,Harmonic 33 (-2.645) 0.32
,Harmonic 34 (-1.161) 9.0e-2
,Harmonic 35 (-1.918) 0.11
,Harmonic 36 (-3.101) 0.2
,Harmonic 37 (-2.262) 0.16
,Harmonic 38 (-1.389) 6.0e-2
,Harmonic 39 (-1.028) 6.0e-2
,Harmonic 40 2.847 0.14
,Harmonic 41 (-2.039) 0.29
,Harmonic 42 (-1.787) 0.11
,Harmonic 43 (-0.448) 0.13
,Harmonic 44 2.782 0.21
,Harmonic 45 (-0.896) 7.0e-2
,Harmonic 46 1.82 0.26
,Harmonic 47 (-2.442) 0.18
,Harmonic 48 (-2.099) 0.11
,Harmonic 49 (-2.46) 0.24
,Harmonic 50 (-0.842) 0.21
,Harmonic 51 2.893 5.0e-2]
note20 :: Note
note20 = Note
(Pitch 207.652 44 "g#3")
21
(Range
(NoteRange
(NoteRangeAmplitude 7267.82 35 1.0e-2)
(NoteRangeHarmonicFreq 1 207.65))
(NoteRange
(NoteRangeAmplitude 207.65 1 5142.0)
(NoteRangeHarmonicFreq 48 9967.29)))
[Harmonic 1 (-1.632) 5142.0
,Harmonic 2 (-2.861) 155.36
,Harmonic 3 (-1.078) 126.31
,Harmonic 4 (-3.105) 10.86
,Harmonic 5 1.679 15.66
,Harmonic 6 (-3.07) 17.18
,Harmonic 7 (-1.137) 15.16
,Harmonic 8 (-2.926) 8.83
,Harmonic 9 3.137 3.09
,Harmonic 10 (-0.687) 5.45
,Harmonic 11 2.3e-2 3.56
,Harmonic 12 1.569 0.43
,Harmonic 13 (-1.236) 1.03
,Harmonic 14 2.141 0.21
,Harmonic 15 (-0.917) 0.47
,Harmonic 16 (-2.61) 0.34
,Harmonic 17 0.962 0.43
,Harmonic 18 1.688 0.14
,Harmonic 19 (-2.749) 5.0e-2
,Harmonic 20 1.146 0.58
,Harmonic 21 2.005 6.0e-2
,Harmonic 22 (-1.132) 0.64
,Harmonic 23 (-0.366) 0.22
,Harmonic 24 5.6e-2 0.23
,Harmonic 25 0.27 4.0e-2
,Harmonic 26 (-0.411) 0.23
,Harmonic 27 (-0.319) 0.21
,Harmonic 28 (-1.0e-2) 0.36
,Harmonic 29 0.494 4.0e-2
,Harmonic 30 0.317 9.0e-2
,Harmonic 31 (-0.377) 6.0e-2
,Harmonic 32 (-0.463) 0.15
,Harmonic 33 0.222 0.13
,Harmonic 34 0.282 8.0e-2
,Harmonic 35 (-1.215) 1.0e-2
,Harmonic 36 (-0.218) 9.0e-2
,Harmonic 37 (-0.253) 0.19
,Harmonic 38 2.8e-2 0.14
,Harmonic 39 1.039 0.14
,Harmonic 40 (-0.6) 9.0e-2
,Harmonic 41 0.564 0.11
,Harmonic 42 (-0.423) 0.18
,Harmonic 43 (-1.523) 0.12
,Harmonic 44 (-0.393) 0.26
,Harmonic 45 (-0.372) 9.0e-2
,Harmonic 46 (-1.348) 0.18
,Harmonic 47 (-0.137) 0.12
,Harmonic 48 (-0.302) 0.23]
note21 :: Note
note21 = Note
(Pitch 220.0 45 "a3")
22
(Range
(NoteRange
(NoteRangeAmplitude 8800.0 40 2.0e-2)
(NoteRangeHarmonicFreq 1 220.0))
(NoteRange
(NoteRangeAmplitude 220.0 1 4886.0)
(NoteRangeHarmonicFreq 45 9900.0)))
[Harmonic 1 (-1.781) 4886.0
,Harmonic 2 (-2.873) 418.47
,Harmonic 3 2.3e-2 132.48
,Harmonic 4 (-0.15) 64.74
,Harmonic 5 2.852 115.52
,Harmonic 6 (-2.712) 79.98
,Harmonic 7 2.223 9.31
,Harmonic 8 (-0.839) 3.14
,Harmonic 9 0.138 9.69
,Harmonic 10 (-1.25) 2.6
,Harmonic 11 (-0.246) 1.59
,Harmonic 12 (-2.953) 2.9
,Harmonic 13 0.836 1.33
,Harmonic 14 1.641 0.92
,Harmonic 15 (-1.172) 0.84
,Harmonic 16 1.421 1.5
,Harmonic 17 (-2.872) 1.05
,Harmonic 18 1.131 0.35
,Harmonic 19 1.509 0.56
,Harmonic 20 (-2.233) 0.27
,Harmonic 21 (-2.633) 0.11
,Harmonic 22 (-0.276) 9.0e-2
,Harmonic 23 0.833 0.29
,Harmonic 24 1.047 0.14
,Harmonic 25 0.169 0.65
,Harmonic 26 1.262 0.62
,Harmonic 27 (-1.658) 0.13
,Harmonic 28 (-2.052) 0.91
,Harmonic 29 (-0.664) 0.25
,Harmonic 30 1.706 5.0e-2
,Harmonic 31 (-3.125) 8.0e-2
,Harmonic 32 0.321 0.12
,Harmonic 33 0.345 0.24
,Harmonic 34 0.141 0.1
,Harmonic 35 (-2.8e-2) 0.21
,Harmonic 36 0.221 0.14
,Harmonic 37 (-0.776) 0.35
,Harmonic 38 0.182 0.29
,Harmonic 39 1.066 9.0e-2
,Harmonic 40 1.733 2.0e-2
,Harmonic 41 0.579 7.0e-2
,Harmonic 42 (-1.283) 0.14
,Harmonic 43 1.91 0.17
,Harmonic 44 0.326 0.17
,Harmonic 45 0.207 0.16]
note22 :: Note
note22 = Note
(Pitch 233.082 46 "a#3")
23
(Range
(NoteRange
(NoteRangeAmplitude 6293.21 27 0.54)
(NoteRangeHarmonicFreq 1 233.08))
(NoteRange
(NoteRangeAmplitude 233.08 1 5761.0)
(NoteRangeHarmonicFreq 42 9789.44)))
[Harmonic 1 1.482 5761.0
,Harmonic 2 1.235 3012.13
,Harmonic 3 (-0.428) 164.89
,Harmonic 4 (-0.342) 441.47
,Harmonic 5 (-1.721) 184.11
,Harmonic 6 (-1.402) 58.43
,Harmonic 7 (-2.8) 201.28
,Harmonic 8 1.914 212.93
,Harmonic 9 0.332 143.14
,Harmonic 10 2.37 21.08
,Harmonic 11 0.988 150.73
,Harmonic 12 (-2.619) 69.45
,Harmonic 13 1.072 82.61
,Harmonic 14 (-3.098) 24.47
,Harmonic 15 1.611 51.1
,Harmonic 16 0.997 32.48
,Harmonic 17 2.208 4.62
,Harmonic 18 1.334 5.97
,Harmonic 19 (-1.479) 20.77
,Harmonic 20 (-0.983) 2.08
,Harmonic 21 0.139 1.58
,Harmonic 22 0.489 1.01
,Harmonic 23 (-0.687) 2.04
,Harmonic 24 0.464 1.38
,Harmonic 25 (-2.022) 0.92
,Harmonic 26 (-1.0) 0.66
,Harmonic 27 (-1.26) 0.54
,Harmonic 28 1.369 0.7
,Harmonic 29 (-1.36) 1.77
,Harmonic 30 0.77 1.37
,Harmonic 31 (-1.216) 2.51
,Harmonic 32 0.583 2.09
,Harmonic 33 1.166 1.27
,Harmonic 34 (-1.722) 0.75
,Harmonic 35 (-0.297) 1.86
,Harmonic 36 (-1.575) 2.8
,Harmonic 37 (-0.818) 1.41
,Harmonic 38 1.382 1.09
,Harmonic 39 (-0.371) 0.92
,Harmonic 40 1.051 0.64
,Harmonic 41 (-2.116) 0.95
,Harmonic 42 (-2.861) 1.32]
note23 :: Note
note23 = Note
(Pitch 246.942 47 "b3")
24
(Range
(NoteRange
(NoteRangeAmplitude 9877.68 40 0.13)
(NoteRangeHarmonicFreq 1 246.94))
(NoteRange
(NoteRangeAmplitude 246.94 1 3074.0)
(NoteRangeHarmonicFreq 40 9877.68)))
[Harmonic 1 1.81 3074.0
,Harmonic 2 (-0.198) 2104.25
,Harmonic 3 1.767 112.37
,Harmonic 4 0.849 861.0
,Harmonic 5 (-2.292) 166.09
,Harmonic 6 (-2.439) 15.61
,Harmonic 7 (-0.24) 146.99
,Harmonic 8 (-0.842) 113.35
,Harmonic 9 2.75 40.07
,Harmonic 10 (-1.061) 8.36
,Harmonic 11 0.506 63.5
,Harmonic 12 2.189 11.55
,Harmonic 13 0.937 10.54
,Harmonic 14 (-1.691) 15.51
,Harmonic 15 (-1.903) 5.14
,Harmonic 16 2.428 0.63
,Harmonic 17 (-2.482) 4.59
,Harmonic 18 0.962 4.28
,Harmonic 19 (-0.685) 3.14
,Harmonic 20 (-2.313) 0.89
,Harmonic 21 (-0.654) 2.28
,Harmonic 22 2.189 1.22
,Harmonic 23 0.347 0.78
,Harmonic 24 1.787 1.84
,Harmonic 25 (-0.451) 1.29
,Harmonic 26 1.874 0.27
,Harmonic 27 (-0.602) 1.29
,Harmonic 28 (-2.23) 1.1
,Harmonic 29 1.875 1.06
,Harmonic 30 1.183 2.83
,Harmonic 31 0.194 0.42
,Harmonic 32 2.755 1.96
,Harmonic 33 (-2.972) 0.56
,Harmonic 34 (-2.874) 1.18
,Harmonic 35 (-1.535) 0.39
,Harmonic 36 (-0.341) 1.45
,Harmonic 37 1.018 0.49
,Harmonic 38 2.131 1.1
,Harmonic 39 1.622 0.89
,Harmonic 40 2.073 0.13]
note24 :: Note
note24 = Note
(Pitch 261.626 48 "c4")
25
(Range
(NoteRange
(NoteRangeAmplitude 6279.02 24 7.0e-2)
(NoteRangeHarmonicFreq 1 261.62))
(NoteRange
(NoteRangeAmplitude 261.62 1 2411.0)
(NoteRangeHarmonicFreq 37 9680.16)))
[Harmonic 1 (-0.783) 2411.0
,Harmonic 2 (-1.184) 279.83
,Harmonic 3 (-0.48) 217.09
,Harmonic 4 1.989 183.96
,Harmonic 5 (-1.729) 202.67
,Harmonic 6 2.447 108.81
,Harmonic 7 (-1.335) 96.95
,Harmonic 8 (-3.5e-2) 65.99
,Harmonic 9 3.137 12.63
,Harmonic 10 (-1.961) 29.59
,Harmonic 11 (-1.814) 26.38
,Harmonic 12 (-2.832) 11.19
,Harmonic 13 2.576 6.27
,Harmonic 14 (-2.671) 28.86
,Harmonic 15 (-1.693) 4.49
,Harmonic 16 1.795 1.49
,Harmonic 17 0.414 12.47
,Harmonic 18 (-1.946) 3.75
,Harmonic 19 1.138 9.0e-2
,Harmonic 20 (-2.694) 0.86
,Harmonic 21 (-2.582) 0.9
,Harmonic 22 1.8e-2 0.96
,Harmonic 23 1.118 0.4
,Harmonic 24 1.526 7.0e-2
,Harmonic 25 (-0.415) 0.72
,Harmonic 26 0.632 0.45
,Harmonic 27 (-1.005) 0.41
,Harmonic 28 (-0.532) 0.17
,Harmonic 29 0.268 1.11
,Harmonic 30 2.624 1.36
,Harmonic 31 (-0.686) 0.34
,Harmonic 32 (-1.079) 0.66
,Harmonic 33 1.294 0.43
,Harmonic 34 0.927 0.29
,Harmonic 35 (-0.819) 0.28
,Harmonic 36 (-2.53) 0.6
,Harmonic 37 (-1.406) 0.27]
note25 :: Note
note25 = Note
(Pitch 277.183 49 "c#4")
26
(Range
(NoteRange
(NoteRangeAmplitude 9424.22 34 0.13)
(NoteRangeHarmonicFreq 1 277.18))
(NoteRange
(NoteRangeAmplitude 277.18 1 3303.0)
(NoteRangeHarmonicFreq 35 9701.4)))
[Harmonic 1 1.632 3303.0
,Harmonic 2 2.688 243.42
,Harmonic 3 1.276 28.74
,Harmonic 4 (-1.743) 71.0
,Harmonic 5 1.148 64.48
,Harmonic 6 (-0.788) 31.41
,Harmonic 7 0.361 15.57
,Harmonic 8 (-1.933) 51.64
,Harmonic 9 (-2.373) 5.85
,Harmonic 10 (-0.261) 30.49
,Harmonic 11 0.6 13.6
,Harmonic 12 2.59 8.96
,Harmonic 13 (-1.087) 2.7
,Harmonic 14 2.146 0.73
,Harmonic 15 (-0.679) 0.33
,Harmonic 16 (-2.841) 0.42
,Harmonic 17 (-2.826) 0.71
,Harmonic 18 (-2.956) 0.16
,Harmonic 19 2.62 0.18
,Harmonic 20 (-2.398) 0.69
,Harmonic 21 2.768 0.21
,Harmonic 22 (-0.929) 0.31
,Harmonic 23 (-2.88) 0.26
,Harmonic 24 0.0 0.24
,Harmonic 25 (-2.779) 0.21
,Harmonic 26 1.856 0.35
,Harmonic 27 1.688 0.36
,Harmonic 28 (-0.924) 0.51
,Harmonic 29 (-1.374) 0.3
,Harmonic 30 0.262 0.19
,Harmonic 31 1.854 0.18
,Harmonic 32 (-1.735) 0.34
,Harmonic 33 1.62 0.41
,Harmonic 34 0.938 0.13
,Harmonic 35 0.112 0.24]
note26 :: Note
note26 = Note
(Pitch 293.665 50 "d4")
27
(Range
(NoteRange
(NoteRangeAmplitude 9690.94 33 6.0e-2)
(NoteRangeHarmonicFreq 1 293.66))
(NoteRange
(NoteRangeAmplitude 293.66 1 4216.0)
(NoteRangeHarmonicFreq 33 9690.94)))
[Harmonic 1 1.699 4216.0
,Harmonic 2 (-2.226) 726.68
,Harmonic 3 (-2.54) 23.91
,Harmonic 4 (-0.433) 169.67
,Harmonic 5 1.939 91.98
,Harmonic 6 1.565 80.64
,Harmonic 7 1.055 132.75
,Harmonic 8 (-2.24) 30.98
,Harmonic 9 (-0.733) 74.94
,Harmonic 10 2.389 34.6
,Harmonic 11 (-1.938) 42.32
,Harmonic 12 2.331 23.7
,Harmonic 13 (-1.025) 7.02
,Harmonic 14 (-5.1e-2) 4.1
,Harmonic 15 0.465 12.07
,Harmonic 16 (-4.0e-3) 1.1
,Harmonic 17 1.932 1.3
,Harmonic 18 0.365 0.54
,Harmonic 19 1.986 0.55
,Harmonic 20 (-0.129) 0.41
,Harmonic 21 (-2.558) 0.24
,Harmonic 22 (-1.749) 0.85
,Harmonic 23 1.956 0.15
,Harmonic 24 (-2.738) 0.35
,Harmonic 25 (-3.106) 0.73
,Harmonic 26 (-1.511) 0.42
,Harmonic 27 2.731 0.72
,Harmonic 28 (-2.529) 0.91
,Harmonic 29 3.001 0.52
,Harmonic 30 1.894 0.27
,Harmonic 31 0.977 0.53
,Harmonic 32 2.927 0.21
,Harmonic 33 (-0.101) 6.0e-2]
note27 :: Note
note27 = Note
(Pitch 311.127 51 "d#4")
28
(Range
(NoteRange
(NoteRangeAmplitude 9644.93 31 4.0e-2)
(NoteRangeHarmonicFreq 1 311.12))
(NoteRange
(NoteRangeAmplitude 311.12 1 3358.0)
(NoteRangeHarmonicFreq 32 9956.06)))
[Harmonic 1 (-1.482) 3358.0
,Harmonic 2 2.543 142.88
,Harmonic 3 (-0.283) 92.92
,Harmonic 4 (-2.78) 27.44
,Harmonic 5 2.711 6.43
,Harmonic 6 (-1.543) 13.95
,Harmonic 7 1.684 7.96
,Harmonic 8 (-1.644) 0.85
,Harmonic 9 (-0.711) 3.05
,Harmonic 10 (-1.855) 0.38
,Harmonic 11 (-2.108) 1.09
,Harmonic 12 (-0.687) 0.16
,Harmonic 13 (-1.608) 0.38
,Harmonic 14 (-1.487) 0.31
,Harmonic 15 (-2.092) 0.24
,Harmonic 16 (-2.255) 0.22
,Harmonic 17 0.584 0.17
,Harmonic 18 (-1.517) 0.22
,Harmonic 19 (-2.467) 8.0e-2
,Harmonic 20 (-2.863) 0.28
,Harmonic 21 (-0.573) 0.78
,Harmonic 22 (-2.71) 0.21
,Harmonic 23 (-2.506) 0.16
,Harmonic 24 (-0.929) 0.38
,Harmonic 25 (-1.892) 0.44
,Harmonic 26 (-0.921) 0.28
,Harmonic 27 1.431 0.13
,Harmonic 28 (-1.679) 0.23
,Harmonic 29 (-0.853) 7.0e-2
,Harmonic 30 (-1.337) 0.25
,Harmonic 31 (-0.697) 4.0e-2
,Harmonic 32 (-0.257) 0.17]
note28 :: Note
note28 = Note
(Pitch 329.628 52 "e4")
29
(Range
(NoteRange
(NoteRangeAmplitude 7911.07 24 3.0e-2)
(NoteRangeHarmonicFreq 1 329.62))
(NoteRange
(NoteRangeAmplitude 329.62 1 3751.0)
(NoteRangeHarmonicFreq 30 9888.84)))
[Harmonic 1 1.609 3751.0
,Harmonic 2 2.566 113.87
,Harmonic 3 2.514 198.88
,Harmonic 4 0.667 174.83
,Harmonic 5 (-0.23) 22.65
,Harmonic 6 1.144 32.45
,Harmonic 7 0.357 1.34
,Harmonic 8 (-0.495) 42.44
,Harmonic 9 (-1.405) 13.02
,Harmonic 10 (-4.0e-3) 10.76
,Harmonic 11 (-2.142) 1.67
,Harmonic 12 (-1.494) 1.23
,Harmonic 13 2.222 0.83
,Harmonic 14 2.079 0.51
,Harmonic 15 2.004 1.97
,Harmonic 16 1.015 0.62
,Harmonic 17 2.478 0.51
,Harmonic 18 (-2.182) 0.87
,Harmonic 19 (-1.315) 0.72
,Harmonic 20 (-1.671) 0.77
,Harmonic 21 2.417 0.56
,Harmonic 22 (-2.533) 0.47
,Harmonic 23 (-2.333) 0.31
,Harmonic 24 1.585 3.0e-2
,Harmonic 25 2.932 0.31
,Harmonic 26 (-0.579) 0.16
,Harmonic 27 (-1.091) 0.37
,Harmonic 28 (-2.862) 0.26
,Harmonic 29 (-2.571) 0.39
,Harmonic 30 2.216 0.17]
note29 :: Note
note29 = Note
(Pitch 349.228 53 "f4")
30
(Range
(NoteRange
(NoteRangeAmplitude 6635.33 19 7.0e-2)
(NoteRangeHarmonicFreq 1 349.22))
(NoteRange
(NoteRangeAmplitude 349.22 1 2829.0)
(NoteRangeHarmonicFreq 28 9778.38)))
[Harmonic 1 1.648 2829.0
,Harmonic 2 (-0.159) 115.24
,Harmonic 3 0.473 33.25
,Harmonic 4 (-1.037) 16.24
,Harmonic 5 (-1.882) 10.24
,Harmonic 6 (-2.912) 15.56
,Harmonic 7 (-1.273) 2.09
,Harmonic 8 (-2.061) 9.06
,Harmonic 9 (-3.136) 0.84
,Harmonic 10 (-1.694) 1.58
,Harmonic 11 (-2.25) 0.57
,Harmonic 12 2.851 0.14
,Harmonic 13 (-2.84) 0.4
,Harmonic 14 (-2.247) 0.19
,Harmonic 15 (-2.071) 0.3
,Harmonic 16 2.677 0.29
,Harmonic 17 3.103 0.35
,Harmonic 18 (-2.418) 0.27
,Harmonic 19 (-2.802) 7.0e-2
,Harmonic 20 3.077 0.19
,Harmonic 21 (-2.451) 8.0e-2
,Harmonic 22 2.69 0.38
,Harmonic 23 (-2.296) 0.23
,Harmonic 24 2.88 0.13
,Harmonic 25 (-2.832) 0.16
,Harmonic 26 2.51 0.25
,Harmonic 27 (-2.482) 0.21
,Harmonic 28 3.109 0.22]
note30 :: Note
note30 = Note
(Pitch 369.994 54 "f#4")
31
(Range
(NoteRange
(NoteRangeAmplitude 7029.88 19 0.11)
(NoteRangeHarmonicFreq 1 369.99))
(NoteRange
(NoteRangeAmplitude 369.99 1 3567.0)
(NoteRangeHarmonicFreq 26 9619.84)))
[Harmonic 1 1.179 3567.0
,Harmonic 2 (-1.188) 43.12
,Harmonic 3 (-2.833) 339.92
,Harmonic 4 1.85 53.5
,Harmonic 5 2.117 173.22
,Harmonic 6 2.744 66.31
,Harmonic 7 2.908 23.22
,Harmonic 8 (-2.8e-2) 23.72
,Harmonic 9 1.924 14.58
,Harmonic 10 0.527 25.86
,Harmonic 11 2.105 3.38
,Harmonic 12 (-1.064) 27.01
,Harmonic 13 (-2.065) 2.95
,Harmonic 14 1.519 1.39
,Harmonic 15 (-3.026) 0.66
,Harmonic 16 1.771 1.37
,Harmonic 17 2.445 0.69
,Harmonic 18 0.24 1.19
,Harmonic 19 (-1.557) 0.11
,Harmonic 20 0.345 0.4
,Harmonic 21 (-1.227) 0.39
,Harmonic 22 3.049 0.68
,Harmonic 23 2.664 1.17
,Harmonic 24 2.55 0.8
,Harmonic 25 2.143 0.5
,Harmonic 26 (-2.215) 0.61]
note31 :: Note
note31 = Note
(Pitch 391.995 55 "g4")
32
(Range
(NoteRange
(NoteRangeAmplitude 6663.91 17 6.0e-2)
(NoteRangeHarmonicFreq 1 391.99))
(NoteRange
(NoteRangeAmplitude 391.99 1 672.0)
(NoteRangeHarmonicFreq 24 9407.88)))
[Harmonic 1 1.376 672.0
,Harmonic 2 2.839 42.19
,Harmonic 3 1.348 53.81
,Harmonic 4 (-2.048) 73.18
,Harmonic 5 0.357 24.35
,Harmonic 6 (-0.323) 33.38
,Harmonic 7 1.347 6.69
,Harmonic 8 (-0.235) 14.83
,Harmonic 9 (-1.978) 11.18
,Harmonic 10 2.535 1.58
,Harmonic 11 (-1.507) 4.49
,Harmonic 12 (-2.597) 1.09
,Harmonic 13 1.135 2.3
,Harmonic 14 0.318 0.75
,Harmonic 15 (-2.972) 0.45
,Harmonic 16 (-1.46) 0.2
,Harmonic 17 (-1.074) 6.0e-2
,Harmonic 18 (-1.752) 0.68
,Harmonic 19 (-1.833) 8.0e-2
,Harmonic 20 0.83 0.62
,Harmonic 21 0.909 0.29
,Harmonic 22 (-2.449) 0.58
,Harmonic 23 2.372 0.62
,Harmonic 24 (-2.655) 0.48]
note32 :: Note
note32 = Note
(Pitch 415.305 56 "g#4")
33
(Range
(NoteRange
(NoteRangeAmplitude 7475.49 18 0.21)
(NoteRangeHarmonicFreq 1 415.3))
(NoteRange
(NoteRangeAmplitude 415.3 1 3192.0)
(NoteRangeHarmonicFreq 24 9967.32)))
[Harmonic 1 1.726 3192.0
,Harmonic 2 0.708 74.54
,Harmonic 3 (-2.413) 232.96
,Harmonic 4 (-2.29) 35.96
,Harmonic 5 (-2.803) 22.19
,Harmonic 6 (-2.1e-2) 36.16
,Harmonic 7 1.086 56.63
,Harmonic 8 1.538 44.19
,Harmonic 9 (-1.164) 13.08
,Harmonic 10 (-1.486) 7.4
,Harmonic 11 (-1.905) 5.39
,Harmonic 12 1.504 3.01
,Harmonic 13 2.728 0.79
,Harmonic 14 (-2.212) 0.9
,Harmonic 15 (-2.409) 0.52
,Harmonic 16 (-2.156) 1.86
,Harmonic 17 2.898 0.55
,Harmonic 18 0.365 0.21
,Harmonic 19 (-2.044) 1.26
,Harmonic 20 2.014 0.67
,Harmonic 21 1.503 1.77
,Harmonic 22 2.538 1.02
,Harmonic 23 1.896 0.45
,Harmonic 24 1.905 0.3]
note33 :: Note
note33 = Note
(Pitch 440.0 57 "a4")
34
(Range
(NoteRange
(NoteRangeAmplitude 7920.0 18 0.2)
(NoteRangeHarmonicFreq 1 440.0))
(NoteRange
(NoteRangeAmplitude 440.0 1 3219.0)
(NoteRangeHarmonicFreq 22 9680.0)))
[Harmonic 1 (-1.564) 3219.0
,Harmonic 2 2.125 142.6
,Harmonic 3 0.695 27.06
,Harmonic 4 (-1.4) 48.39
,Harmonic 5 (-2.062) 39.22
,Harmonic 6 (-0.378) 10.45
,Harmonic 7 0.373 37.66
,Harmonic 8 (-2.525) 30.96
,Harmonic 9 0.736 1.2
,Harmonic 10 0.932 4.64
,Harmonic 11 2.828 1.55
,Harmonic 12 1.038 0.56
,Harmonic 13 1.733 1.18
,Harmonic 14 1.51 0.4
,Harmonic 15 0.213 0.5
,Harmonic 16 (-0.58) 0.64
,Harmonic 17 (-6.1e-2) 0.3
,Harmonic 18 1.739 0.2
,Harmonic 19 (-6.0e-3) 0.56
,Harmonic 20 (-0.736) 1.19
,Harmonic 21 1.369 0.71
,Harmonic 22 0.413 0.56]
note34 :: Note
note34 = Note
(Pitch 466.164 58 "a#4")
35
(Range
(NoteRange
(NoteRangeAmplitude 8857.11 19 6.0e-2)
(NoteRangeHarmonicFreq 1 466.16))
(NoteRange
(NoteRangeAmplitude 466.16 1 4797.0)
(NoteRangeHarmonicFreq 21 9789.44)))
[Harmonic 1 (-1.707) 4797.0
,Harmonic 2 (-0.119) 164.87
,Harmonic 3 (-1.875) 80.64
,Harmonic 4 (-2.409) 18.09
,Harmonic 5 3.088 17.77
,Harmonic 6 1.869 6.4
,Harmonic 7 (-2.531) 9.67
,Harmonic 8 (-1.428) 4.13
,Harmonic 9 (-0.523) 0.74
,Harmonic 10 (-2.2) 1.98
,Harmonic 11 (-0.888) 1.53
,Harmonic 12 (-0.577) 0.43
,Harmonic 13 (-2.267) 0.4
,Harmonic 14 0.522 0.34
,Harmonic 15 1.833 0.8
,Harmonic 16 0.674 0.21
,Harmonic 17 (-1.568) 1.06
,Harmonic 18 0.895 0.65
,Harmonic 19 (-0.852) 6.0e-2
,Harmonic 20 1.485 7.0e-2
,Harmonic 21 0.235 0.41]
note35 :: Note
note35 = Note
(Pitch 493.883 59 "b4")
36
(Range
(NoteRange
(NoteRangeAmplitude 6914.36 14 0.76)
(NoteRangeHarmonicFreq 1 493.88))
(NoteRange
(NoteRangeAmplitude 493.88 1 3678.0)
(NoteRangeHarmonicFreq 20 9877.66)))
[Harmonic 1 0.931 3678.0
,Harmonic 2 1.298 1998.4
,Harmonic 3 2.537 320.35
,Harmonic 4 (-0.426) 461.72
,Harmonic 5 1.112 90.52
,Harmonic 6 (-2.203) 43.09
,Harmonic 7 1.877 22.97
,Harmonic 8 (-1.04) 11.87
,Harmonic 9 (-2.288) 6.3
,Harmonic 10 (-1.592) 3.72
,Harmonic 11 2.591 2.42
,Harmonic 12 (-2.865) 3.59
,Harmonic 13 (-1.924) 1.5
,Harmonic 14 0.481 0.76
,Harmonic 15 3.131 2.19
,Harmonic 16 2.703 3.72
,Harmonic 17 2.819 3.81
,Harmonic 18 2.995 3.89
,Harmonic 19 (-2.282) 2.05
,Harmonic 20 1.548 1.17]
note36 :: Note
note36 = Note
(Pitch 523.251 60 "c5")
37
(Range
(NoteRange
(NoteRangeAmplitude 8895.26 17 0.79)
(NoteRangeHarmonicFreq 1 523.25))
(NoteRange
(NoteRangeAmplitude 523.25 1 4419.0)
(NoteRangeHarmonicFreq 18 9418.51)))
[Harmonic 1 0.872 4419.0
,Harmonic 2 2.142 2272.03
,Harmonic 3 (-2.213) 308.07
,Harmonic 4 1.008 375.64
,Harmonic 5 (-2.326) 125.29
,Harmonic 6 (-0.688) 6.79
,Harmonic 7 (-2.881) 58.66
,Harmonic 8 2.196 9.73
,Harmonic 9 (-2.39) 31.85
,Harmonic 10 2.306 12.42
,Harmonic 11 (-0.804) 8.38
,Harmonic 12 (-2.169) 4.76
,Harmonic 13 1.384 0.9
,Harmonic 14 (-3.059) 9.31
,Harmonic 15 0.833 4.94
,Harmonic 16 (-1.512) 3.48
,Harmonic 17 2.935 0.79
,Harmonic 18 (-2.573) 1.17]
note37 :: Note
note37 = Note
(Pitch 554.365 61 "c#5")
38
(Range
(NoteRange
(NoteRangeAmplitude 9424.2 17 1.7)
(NoteRangeHarmonicFreq 1 554.36))
(NoteRange
(NoteRangeAmplitude 554.36 1 3875.0)
(NoteRangeHarmonicFreq 17 9424.2)))
[Harmonic 1 (-2.036) 3875.0
,Harmonic 2 0.104 2940.19
,Harmonic 3 (-1.561) 864.12
,Harmonic 4 (-0.716) 420.22
,Harmonic 5 (-2.201) 561.42
,Harmonic 6 (-3.033) 177.41
,Harmonic 7 (-2.779) 49.02
,Harmonic 8 1.397 28.32
,Harmonic 9 1.006 7.59
,Harmonic 10 1.37 3.92
,Harmonic 11 (-1.119) 6.2
,Harmonic 12 (-2.509) 5.56
,Harmonic 13 (-1.661) 6.73
,Harmonic 14 (-0.15) 4.92
,Harmonic 15 (-1.135) 3.37
,Harmonic 16 1.047 6.96
,Harmonic 17 (-2.989) 1.7]
note38 :: Note
note38 = Note
(Pitch 587.33 62 "d5")
39
(Range
(NoteRange
(NoteRangeAmplitude 6460.63 11 3.02)
(NoteRangeHarmonicFreq 1 587.33))
(NoteRange
(NoteRangeAmplitude 587.33 1 3783.0)
(NoteRangeHarmonicFreq 18 10571.94)))
[Harmonic 1 (-1.29) 3783.0
,Harmonic 2 0.702 2113.65
,Harmonic 3 1.899 412.56
,Harmonic 4 0.46 294.96
,Harmonic 5 2.49 34.12
,Harmonic 6 (-1.909) 63.67
,Harmonic 7 (-2.276) 16.71
,Harmonic 8 (-2.403) 21.13
,Harmonic 9 0.968 14.14
,Harmonic 10 2.681 9.52
,Harmonic 11 0.794 3.02
,Harmonic 12 0.884 10.19
,Harmonic 13 2.755 4.31
,Harmonic 14 0.847 4.8
,Harmonic 15 0.413 18.42
,Harmonic 16 (-2.434) 4.2
,Harmonic 17 (-2.981) 6.75
,Harmonic 18 (-1.436) 6.07]
|
anton-k/sharc-timbre
|
src/Sharc/Instruments/CelloPizzicato.hs
|
bsd-3-clause
| 85,868 | 0 | 15 | 23,903 | 34,316 | 17,823 | 16,493 | 2,915 | 1 |
{-# OPTIONS_GHC -F -pgmF inch #-}
{-# LANGUAGE RankNTypes, GADTs, KindSignatures, ScopedTypeVariables #-}
module InchPrelude where
import Prelude hiding (subtract, even, odd, gcd, lcm, (^), (^^),
fromIntegral, realToFrac, sequence,
sequence_, mapM, mapM_, (=<<), id, const,
(.), flip, ($), ($!), (&&), (||), not,
otherwise, maybe, either, curry, uncurry,
until, asTypeOf, error, undefined, map, (++),
filter, concat, concatMap, head, tail, last,
init, null, length, (!!), foldl, foldl1,
scanl, scanl1, foldr, foldr1, scanr, scanr1,
iterate, repeat, replicate, take, drop,
splitAt, takeWhile, dropWhile, span, break,
lines, words, unlines, unwords, reverse, and,
or, any, all, elem, notElem, lookup, sum,
product, maximum, minimum, zip, zipWith,
zipWith3, cycle, map, fst, snd)
{-
class Eq' a where
(==.) :: a -> a -> Bool
(/=.) :: a -> a -> Bool
class (Eq' a) => Ord' a where
compare' :: a -> a -> Ordering
(<), (<=), (>=), (>) :: a -> a -> Bool
max', min' :: a -> a -> a
class Enum' a where
succ', pred' :: a -> a
toEnum' :: Int -> a
fromEnum' :: a -> Int
enumFrom' :: a -> [a] -- [n..]
enumFromThen' :: a -> a -> [a] -- [n,n'..]
enumFromTo' :: a -> a -> [a] -- [n..m]
enumFromThenTo' :: a -> a -> a -> [a] -- [n,n'..m]
class Bounded' a where
minBound' :: a
maxBound' :: a
-- Numeric classes
class (Eq a, Show a) => Num' a where
(+.), (-.), (*.) :: a -> a -> a
negate' :: a -> a
abs, signum :: a -> a
fromInteger' :: Integer -> a
class (Num a, Ord a) => Real' a where
toRational' :: a -> Rational
class (Real a, Enum a) => Integral' a where
quot', rem' :: a -> a -> a
div', mod' :: a -> a -> a
quotRem', divMod' :: a -> a -> (a,a)
toInteger' :: a -> Integer
class (Num a) => Fractional' a where
(/.) :: a -> a -> a
recip' :: a -> a
fromRational' :: Rational -> a
class (Fractional a) => Floating' a where
pi' :: a
exp', log', sqrt' :: a -> a
(**.), logBase' :: a -> a -> a
sin', cos', tan' :: a -> a
asin', acos', atan' :: a -> a
sinh', cosh', tanh' :: a -> a
asinh', acosh', atanh' :: a -> a
class (Real a, Fractional a) => RealFrac' a where
properFraction' :: forall b . (Integral b) => a -> (b,a)
truncate', round' :: forall b . (Integral b) => a -> b
ceiling', floor' :: forall b . (Integral b) => a -> b
class (RealFrac a, Floating a) => RealFloat' a where
floatRadix' :: a -> Integer
floatDigits' :: a -> Int
floatRange' :: a -> (Int,Int)
decodeFloat' :: a -> (Integer,Int)
encodeFloat' :: Integer -> Int -> a
exponent' :: a -> Int
significand' :: a -> a
scaleFloat' :: Int -> a -> a
isNaN', isInfinite', isDenormalized', isNegativeZero', isIEEE'
:: a -> Bool
atan2' :: a -> a -> a
-}
subtract :: Num a => a -> a -> a
subtract = flip (-)
even, odd :: (Eq a, Num a, Integral a) => a -> Bool
even n = (==) (rem n 2) 0
odd = (.) not even
gcd :: (Num a, Integral a) => a -> a -> a
gcd 0 0 = error "Prelude.gcd: gcd 0 0 is undefined"
gcd x y = gcd' (abs x) (abs y)
where gcd' x 0 = x
gcd' x y = gcd' y (rem x y)
lcm :: (Num a, Integral a) => a -> a -> a
lcm _ 0 = 0
lcm 0 _ = 0
lcm x y = abs ((quot x (gcd x y)) * y)
(^) :: (Num a, Num b, Eq b, Ord b, Integral b) => a -> b -> a
(^) x 0 = 1
(^) x n | (>) n 0 = f x (n-1) x
where
f :: a -> b -> a -> a
f _ 0 y = y
f x n y = g x n where
g x n | even n = g (x*x) (quot n 2)
| otherwise = f x (n-1) (x*y)
_ ^ _ = error "Prelude.^: negative exponent"
(^^) :: (Num a, Fractional a, Eq b, Ord b, Num b, Integral b) => a -> b -> a
(^^) x n | (>=) n 0 = (^) x n
| otherwise = recip (x^(-n))
fromIntegral :: (Integral a, Num b) => a -> b
fromIntegral = (.) fromInteger toInteger
realToFrac :: (Real a, Fractional b) => a -> b
realToFrac = (.) fromRational toRational
{-
class Functor f where
fmap :: (a -> b) -> f a -> f b
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
(>>) :: m a -> m b -> m b
return :: a -> m a
fail :: String -> m a
-}
sequence :: forall a (m :: * -> *) . Monad m => [m a] -> m [a]
sequence = foldr mcons (return [])
where mcons p q = (>>=) p (\x -> (>>=) q (\y -> return (x:y)))
sequence_ :: forall a (m :: * -> *) . Monad m => [m a] -> m ()
sequence_ = foldr (>>) (return ())
mapM :: forall a b (m :: * -> *) . Monad m => (a -> m b) -> [a] -> m [b]
mapM f as = sequence (map f as)
mapM_ :: forall a b (m :: * -> *) . Monad m => (a -> m b) -> [a] -> m ()
mapM_ f as = sequence_ (map f as)
(=<<) :: forall a b (m :: * -> *) . Monad m => (a -> m b) -> m a -> m b
(=<<) f x = (>>=) x f
-- data () = () deriving (Eq, Ord, Enum, Bounded)
id :: a -> a
id x = x
const :: a -> b -> a
const x _ = x
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g = \ x -> f (g x)
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y x
($), ($!) :: (a -> b) -> a -> b
($) f x = f x
($!) f x = seq x (f x)
-- built in
data Bool' where
False' :: Bool'
True' :: Bool'
deriving (Eq, Ord, Enum, Read, Show, Bounded)
(&&), (||) :: Bool -> Bool -> Bool
True && x = x
False && _ = False
True || _ = True
False || x = x
-- built in
not :: Bool -> Bool
not True = False
not False = True
otherwise :: Bool
otherwise = True
-- built in
data Maybe' :: * -> * where
Nothing' :: Maybe' a
Just' :: a -> Maybe' a
deriving (Eq, Ord, Read, Show)
maybe :: b -> (a -> b) -> Maybe a -> b
maybe n f Nothing = n
maybe n f (Just x) = f x
-- built in
data Either' :: * -> * -> * where
Left' :: a -> Either' a b
Right' :: b -> Either' a b
deriving (Eq, Ord, Read, Show)
either :: (a -> c) -> (b -> c) -> Either a b -> c
either f g (Left x) = f x
either f g (Right y) = g y
-- built in
data Ordering' where
LT' :: Ordering'
EQ' :: Ordering'
GT' :: Ordering'
deriving (Eq, Ord, Enum, Read, Show, Bounded)
numericEnumFrom' :: (Num a, Fractional a) => a -> [a]
numericEnumFromThen' :: (Num a, Fractional a) => a -> a -> [a]
numericEnumFromTo' :: (Num a, Fractional a, Ord a) => a -> a -> [a]
numericEnumFromThenTo' :: (Num a, Fractional a, Ord a) => a -> a -> a -> [a]
numericEnumFrom' = iterate (\ x -> x+1)
numericEnumFromThen' n m = iterate (\ x -> x +(m-n)) n
numericEnumFromTo' n m = takeWhile (\ x -> (<=) x ((/) (m+1) 2)) (numericEnumFrom' n)
numericEnumFromThenTo' n n' m = takeWhile p (numericEnumFromThen' n n')
where
p | (>=) n' n = (\ x -> (<=) x (m + ((/) (n'-n) 2)))
| otherwise = (\ x -> (>=) x (m + ((/) (n'-n) 2)))
-- data [a] = [] | a : [a] deriving (Eq, Ord)
-- data (a,b) = (a,b) deriving (Eq, Ord, Bounded)
fst :: (a,b) -> a
fst (x,y) = x
snd :: (a,b) -> b
snd (x,y) = y
curry :: ((a, b) -> c) -> a -> b -> c
curry f x y = f (x, y)
uncurry :: (a -> b -> c) -> ((a, b) -> c)
uncurry f p = f (fst p) (snd p)
until :: (a -> Bool) -> (a -> a) -> a -> a
until p f x
| p x = x
| otherwise = until p f (f x)
asTypeOf :: a -> a -> a
asTypeOf = const
error :: [Char] -> a
error = error
undefined :: a
undefined = error "Prelude.undefined"
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (++) xs ys
filter :: (a -> Bool) -> [a] -> [a]
filter p [] = []
filter p (x:xs) | p x = x : filter p xs
| otherwise = filter p xs
concat :: [[a]] -> [a]
concat xss = foldr (++) [] xss
concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = (.) concat (map f)
head :: [a] -> a
head (x:_) = x
head [] = error "Prelude.head: empty list"
tail :: [a] -> [a]
tail ((:) _ xs) = xs
tail [] = error "Prelude.tail: empty list"
last :: [a] -> a
last [x] = x
last ((:) _ xs) = last xs
last [] = error "Prelude.last: empty list"
init :: [a] -> [a]
init [x] = []
init (x:xs) = x : init xs
init [] = error "Prelude.init: empty list"
null :: [a] -> Bool
null [] = True
null ((:) _ _) = False
length :: [a] -> Integer
length [] = 0
length ((:) _ l) = 1 + length l
(!!) :: [a] -> Int -> a
(!!) xs n | (<) n 0 = error "Prelude.!!: negative index"
(!!) [] _ = error "Prelude.!!: index too large"
(!!) (x:_) 0 = x
(!!) (_:xs) n = (!!) xs (n-1)
foldl :: (a -> b -> a) -> a -> [b] -> a
foldl f z [] = z
foldl f z (x:xs) = foldl f (f z x) xs
foldl1 :: (a -> a -> a) -> [a] -> a
foldl1 f (x:xs) = foldl f x xs
foldl1 _ [] = error "Prelude.foldl1: empty list"
scanl :: (a -> b -> a) -> a -> [b] -> [a]
scanl f q xs = q : (case xs of
[] -> []
x:xs -> scanl f (f q x) xs
)
scanl1 :: (a -> a -> a) -> [a] -> [a]
scanl1 f (x:xs) = scanl f x xs
scanl1 _ [] = []
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr f z [] = z
foldr f z (x:xs) = f x (foldr f z xs)
foldr1 :: (a -> a -> a) -> [a] -> a
foldr1 f [x] = x
foldr1 f (x:xs) = f x (foldr1 f xs)
foldr1 _ [] = error "Prelude.foldr1: empty list"
scanr :: (a -> b -> b) -> b -> [a] -> [b]
scanr f q0 [] = [q0]
scanr f q0 (x:xs) = f x q : qs
where qs = scanr f q0 xs
q = head qs
scanr1 :: (a -> a -> a) -> [a] -> [a]
scanr1 f [] = []
scanr1 f [x] = [x]
scanr1 f (x:xs) = f x q : qs
where qs = scanr1 f xs
q = head qs
iterate :: (a -> a) -> a -> [a]
iterate f x = x : iterate f (f x)
repeat :: a -> [a]
repeat x = xs where xs = x:xs
replicate :: Integer -> a -> [a]
replicate n x = take n (repeat x)
cycle :: [a] -> [a]
cycle [] = error "Prelude.cycle: empty list"
cycle xs = xs' where xs' = (++) xs xs'
take :: Integer -> [a] -> [a]
take n _ | (<=) n 0 = []
take _ [] = []
take n (x:xs) = x : take (n-1) xs
drop :: Integer -> [a] -> [a]
drop n xs | (<=) n 0 = xs
drop _ [] = []
drop n ((:) _ xs) = drop (n-1) xs
splitAt :: Integer -> [a] -> ([a],[a])
splitAt n xs = (take n xs, drop n xs)
takeWhile :: (a -> Bool) -> [a] -> [a]
takeWhile p [] = []
takeWhile p (x:xs)
| p x = x : takeWhile p xs
| otherwise = []
dropWhile :: (a -> Bool) -> [a] -> [a]
dropWhile p [] = []
dropWhile p xs
| p (head xs) = dropWhile p (tail xs)
| otherwise = xs
span :: (a -> Bool) -> [a] -> ([a],[a])
span p [] = ([],[])
span p xs
| p (head xs) = (x:fst yszs, snd yszs)
| otherwise = ([],xs)
where yszs = span p (tail xs)
x = head xs
break :: (a -> Bool) -> [a] -> ([a],[a])
break p = span ((.) not p)
lines :: [Char] -> [[Char]]
lines "" = []
lines s = let ls' = break ((==) '\n') s
l = fst ls'
s' = snd ls'
in l : (case s' of
[] -> []
(_:s'') -> lines s''
)
words :: [Char] -> [[Char]]
words s = case dropWhile isSpace s of
"" -> []
s' -> w : words s''
where ws'' = break isSpace s'
w = fst ws''
s'' = snd ws''
where
isSpace ' ' = True
isSpace _ = False
unlines :: [[Char]] -> [Char]
unlines = concatMap (\ x -> (++) x "\n")
unwords :: [[Char]] -> [Char]
unwords [] = ""
unwords ws = foldr1 (\w s -> (++) w (' ':s)) ws
reverse :: [a] -> [a]
reverse = foldl (flip (:)) []
and :: [Bool] -> Bool
and = foldr (&&) True
or = foldr (||) False
any :: (a -> Bool) -> [a] -> Bool
any p = (.) or (map p)
all p = (.) and (map p)
elem, notElem :: (Eq a) => a -> [a] -> Bool
elem x = any ((==) x)
notElem x = all ((/=) x)
lookup :: (Eq a) => a -> [(a,b)] -> Maybe b
lookup key [] = Nothing
lookup key ((x,y):xys)
| (==) key x = Just y
| otherwise = lookup key xys
sum :: Num a => [a] -> a
sum = foldl (+) 0
product = foldl (*) 1
maximum :: Ord a => [a] -> a
maximum [] = error "Prelude.maximum: empty list"
maximum xs = foldl1 max xs
minimum [] = error "Prelude.minimum: empty list"
minimum xs = foldl1 min xs
zip :: [a] -> [b] -> [(a,b)]
zip = zipWith (,)
{-
zip3 :: [a] -> [b] -> [c] -> [(a,b,c)]
zip3 = zipWith3 (,,)
-}
zipWith :: (a->b->c) -> [a]->[b]->[c]
zipWith z (a:as) (b:bs)
= z a b : zipWith z as bs
zipWith _ _ _ = []
zipWith3 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
zipWith3 z (a:as) (b:bs) (c:cs)
= z a b c : zipWith3 z as bs cs
zipWith3 _ _ _ _ = []
{-
unzip :: [(a,b)] -> ([a],[b])
unzip = foldr (\(a,b) ~(as,bs) -> (a:as,b:bs)) ([],[])
unzip3 :: [(a,b,c)] -> ([a],[b],[c])
unzip3 = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
([],[],[])
-}
|
adamgundry/inch
|
examples/InchPrelude.hs
|
bsd-3-clause
| 15,705 | 10 | 16 | 6,981 | 5,739 | 3,126 | 2,613 | 295 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Data.List.NonEmpty where
import Data.Binary
import Data.Data
import qualified Data.List as L
import Text.PrettyPrint.GenericPretty
-- | A non-empty list
data NonEmpty a = NonEmpty
{ head :: a
, tail :: [a]
} deriving (Data, Eq, Generic, Show, Typeable)
toList :: NonEmpty a -> [a]
toList (NonEmpty x xs) = x:xs
fromList :: [a] -> Maybe (NonEmpty a)
fromList [] = Nothing
fromList (x:xs) = Just $ NonEmpty x xs
length :: NonEmpty a -> Int
length = L.length . toList
instance (Out a) => Out (NonEmpty a)
|
facebookarchive/lex-pass
|
src/Data/List/NonEmpty.hs
|
bsd-3-clause
| 595 | 0 | 9 | 115 | 217 | 121 | 96 | 19 | 1 |
{-# LANGUAGE TupleSections, TypeFamilies, FlexibleContexts, RankNTypes,
PackageImports #-}
module Data.Pipe.Core (
PipeClass(..), PipeChoice(..), (=@=), runPipe_, convert,
Pipe(..), finally, bracket ) where
import Control.Applicative
import Control.Monad
import Control.Exception.Lifted (onException)
import Control.Monad.Trans.Control
import "monads-tf" Control.Monad.Trans
import "monads-tf" Control.Monad.Error
import "monads-tf" Control.Monad.State
import "monads-tf" Control.Monad.Reader
import "monads-tf" Control.Monad.Writer
infixr 2 =@=
infixr 3 =$=
infixr 4 ++++, ||||
class PipeClass p where
runPipe :: Monad m => p i o m r -> m (Maybe r)
(=$=) :: Monad m => p a b m x -> p b c m y -> p a c m y
yield :: Monad m => o -> p i o m ()
await :: Monad m => p i o m (Maybe i)
onBreak :: Monad m => p i o m r -> m b -> p i o m r
onDone :: Monad m => p i o m r -> m b -> p i o m r
finalize :: Monad m => p i o m r -> m b -> p i o m r
mapMonad :: Monad m => (forall a . m a -> m a) -> p i o m r -> p i o m r
mapOut :: Monad m => (o -> o') -> p i o m r -> p i o' m r
mapIn :: Monad m => (i' -> i) -> p i o m r -> p i' o m r
p `finalize` f = p `onBreak` f `onDone` f
runPipe_ :: (PipeClass p, Monad m) => p i o m r -> m ()
runPipe_ = (>> return ()) . runPipe
convert :: (PipeClass p, Monad m, Monad (p a b m)) => (a -> b) -> p a b m ()
convert f = await >>= maybe (return ()) ((>> convert f) . yield . f)
-- | Minimal complete definition: 'appLeft'
class PipeClass pc => PipeChoice pc where
appLeft :: Monad m => pc b c m r -> pc (Either b d) (Either c d) m r
appRight :: Monad m => pc b c m r -> pc (Either d b) (Either d c) m r
(++++) :: Monad m =>
pc b c m r -> pc b' c' m r -> pc (Either b b') (Either c c') m r
(||||) :: Monad m => pc b d m r -> pc c d m r -> pc (Either b c) d m r
appRight f = mapIn mirror . mapOut mirror $ appLeft f
where
mirror (Left x) = Right x
mirror (Right y) = Left y
f ++++ g = appLeft f =$= appRight g
f |||| g = mapOut untag (f ++++ g)
where
untag (Left x) = x
untag (Right y) = y
data Pipe i o m r
= Ready (m ()) o (Pipe i o m r)
| Need (m ()) (Maybe i -> Pipe i o m r)
| Done (m ()) r
| Make (m ()) (m (Pipe i o m r))
instance PipeChoice Pipe where
appLeft (Ready f o p) = Ready f (Left o) $ appLeft p
appLeft (Need f p) = Need f $ \mei -> case mei of
Just (Left i) -> appLeft . p $ Just i
Just (Right i) -> yield (Right i) >> appLeft (Need f p)
_ -> appLeft $ p Nothing
appLeft (Done f r) = Done f r
appLeft (Make f p) = Make f $ appLeft `liftM` p
instance MonadWriter m => MonadWriter (Pipe i o m) where
type WriterType (Pipe i o m) = WriterType m
tell = lift . tell
listen (Ready f o p) = Ready f o $ listen p
listen (Need f p) = Need f $ \mi -> listen $ p mi
listen (Done f r) = Done f (r, mempty)
listen (Make f p) = Make f $ do
(p', l) <- listen p
return $ (, l) `liftM` p'
pass (Ready f o p) = Ready f o $ pass p
pass (Need f p) = Need f $ \mi -> pass $ p mi
pass (Done f (r, _)) = Done f r
pass (Make f p) = Make f $ do
pass `liftM` p
mapPipeM :: Monad m =>
(m (Pipe i o m a) -> m (Pipe i o m a)) -> Pipe i o m a -> Pipe i o m a
mapPipeM m (Ready f o p) = Ready f o $ mapPipeM m p
mapPipeM m (Need f p) = Need f $ \mi -> mapPipeM m $ p mi
mapPipeM _ (Done f r) = Done f r
mapPipeM m (Make f p) = Make f $ mapPipeM m `liftM` m p
instance MonadError m => MonadError (Pipe i o m) where
type ErrorType (Pipe i o m) = ErrorType m
throwError e = Make (return ()) $ throwError e
Ready f o p `catchError` c = Ready f o $ p `catchError` c
Need f p `catchError` c = Need f $ \mi -> p mi `catchError` c
Done f r `catchError` _ = Done f r
Make f p `catchError` c =
Make f . ((`catchError` c) `liftM`) $ p `catchError` (return . c)
finalizer :: Pipe i o m r -> m ()
finalizer (Ready f _ _) = f
finalizer (Need f _) = f
finalizer (Done f _) = f
finalizer (Make f _) = f
instance PipeClass Pipe where
runPipe (Done f r) = f >> return (Just r)
runPipe (Make _ m) = runPipe =<< m
runPipe _ = return Nothing
p =$= Make f m = Make f $ (p =$=) `liftM` m
p =$= Done f r = Done (finalizer p >> f) r
p =$= Ready f o p' = Ready f o $ p =$= p'
Need f n =$= p = Need f $ \i -> n i =$= p
Ready _ o p =$= Need _ n = p =$= n (Just o)
Done f r =$= Need f' n =
Done (return ()) r =$= Make f' (f >> return (n Nothing))
Make f m =$= p = Make f $ (=$= p) `liftM` m
yield x = Ready (return ()) x (return ())
await = Need (return ()) return
onBreak (Ready f0 o p) f = Ready (f0 >> f >> return ()) o $ onBreak p f
onBreak (Need f0 n) f = Need (f0 >> f >> return ()) $ \i -> onBreak (n i) f
onBreak (Done f0 r) _ = Done f0 r
onBreak (Make f0 m) f = Make (f0 >> f >> return ()) $ flip onBreak f `liftM` m
onDone (Ready f0 o p) f = Ready (voidM f0) o $ finalize p f
onDone (Need f0 n) f = Need (voidM f0) $ \i -> finalize (n i) f
onDone (Done f0 r) f = Done (f0 >> f >> return ()) r
onDone (Make f0 m) f = Make (voidM f0) $ flip finalize f `liftM` m
finalize (Ready f0 o p) f = Ready (f0 >> f >> return ()) o $ finalize p f
finalize (Need f0 n) f = Need (f0 >> f >> return ()) $ \i -> finalize (n i) f
finalize (Done f0 r) f = Done (f0 >> f >> return ()) r
finalize (Make f0 m) f = Make (f0 >> f >> return ()) $ flip finalize f `liftM` m
mapMonad k (Ready f o p) = Ready f o $ mapMonad k p
mapMonad k (Need f n) = Need f $ \i -> mapMonad k $ n i
mapMonad _ (Done f r) = Done f r
mapMonad k (Make f m) = Make f . k $ mapMonad k `liftM` m
mapOut c (Ready f o p) = Ready f (c o) $ mapOut c p
mapOut c (Need f p) = Need f $ \i -> mapOut c (p i)
mapOut _ (Done f r) = Done f r
mapOut c (Make f m) = Make f $ mapOut c `liftM` m
mapIn c (Ready f o p) = Ready f o $ mapIn c p
mapIn c (Need f p) = Need f $ \i -> mapIn c (p $ c <$> i)
mapIn _ (Done f r) = Done f r
mapIn c (Make f m) = Make f $ mapIn c `liftM` m
instance Monad m => Monad (Pipe i o m) where
Ready f o p >>= k = Ready f o $ p >>= k
Need f n >>= k = Need f $ n >=> k
-- Done f r >>= k = Make (return ()) $ f >> return (k r)
Done _ r >>= k = k r
Make f m >>= k = Make f $ (>>= k) `liftM` m
return = Done (return ())
instance Monad m => Functor (Pipe i o m) where
fmap = (=<<) . (return .)
instance Monad m => Applicative (Pipe i o m) where
pure = return
(<*>) = ap
instance MonadTrans (Pipe i o) where
lift = liftP
instance MonadIO m => MonadIO (Pipe i o m) where
liftIO = lift . liftIO
instance MonadState m => MonadState (Pipe i o m) where
type StateType (Pipe i o m) = StateType m
get = lift get
put = lift . put
instance MonadReader m => MonadReader (Pipe i o m) where
type EnvType (Pipe i o m) = EnvType m
ask = lift ask
local = mapPipeM . local
liftP :: Monad m => m a -> Pipe i o m a
liftP m = Make (return ()) $ Done (return ()) `liftM` m
bracket :: (MonadBaseControl IO m, PipeClass p, MonadTrans (p i o), Monad (p i o m)) =>
m a -> (a -> m b) -> (a -> p i o m r) -> p i o m r
bracket o c p = do
h <- lift o
p h `finally` void (c h)
finally :: (MonadBaseControl IO m, PipeClass p) => p i o m r -> m b -> p i o m r
finally p f = finalize (mapMonad (`onException` f) p) f
voidM :: Monad m => m a -> m ()
voidM = (>> return ())
passResult :: (PipeClass p, Monad m, Monad (p i (Either a r) m)) =>
p i a m r -> p i (Either a r) m ()
passResult s = mapOut Left s >>= yield . Right
recvResult :: (PipeClass p, PipeChoice p, Monad m,
Monad (p a o m), Monad (p r o m), Monad (p (Either a r) o m)) =>
p a o m r' -> p (Either a r) o m r
recvResult p =
(p >> return undefined) |||| (await >>= maybe (return undefined) return)
(=@=) :: (PipeClass p, PipeChoice p, Monad m, Monad (p i (Either a r) m),
Monad (p a o m), Monad (p r o m), Monad (p (Either a r) o m)) =>
p i a m r -> p a o m r' -> p i o m r
p1 =@= p2 = passResult p1 =$= recvResult p2
|
YoshikuniJujo/simple-pipe
|
src/Data/Pipe/Core.hs
|
bsd-3-clause
| 7,779 | 28 | 14 | 2,056 | 4,790 | 2,379 | 2,411 | 176 | 1 |
module Paths ( hseDirStructure
, cabalConfigLocation
, dotDirName
, constructDotDirName
, insidePathVar
, cachedCabalInstallPath
) where
import Data.List (intercalate)
import Distribution.Version (Version)
import System.Directory (getAppUserDataDirectory)
import System.FilePath ((</>))
import Util.IO (getEnvVar)
import Util.Cabal (prettyVersion)
import Types
import HsenvMonad
-- returns record containing paths to all important directories
-- inside virtual environment dir structure
hseDirStructure :: Hsenv DirStructure
hseDirStructure = do
parentDir <- asks envParentDir
dirName <- dotDirName
let hsEnvLocation = parentDir
hsEnvDirLocation = hsEnvLocation </> dirName
cabalDirLocation = hsEnvDirLocation </> "cabal"
ghcDirLocation = hsEnvDirLocation </> "ghc"
return DirStructure { hsEnv = hsEnvLocation
, hsEnvDir = hsEnvDirLocation
, ghcPackagePath = hsEnvDirLocation </> "ghc_pkg_db"
, cabalDir = cabalDirLocation
, cabalBinDir = cabalDirLocation </> "bin"
, hsEnvBinDir = hsEnvDirLocation </> "bin"
, ghcDir = ghcDirLocation
, ghcBinDir = ghcDirLocation </> "bin"
}
constructDotDirName :: Options -> String
constructDotDirName opts = maybe ".hsenv" (".hsenv_" ++) (hsEnvName opts)
-- directory name of hsEnvDir
dotDirName :: Hsenv String
dotDirName = do
opts <- ask
return $ constructDotDirName opts
-- returns location of cabal's config file inside virtual environment dir structure
cabalConfigLocation :: Hsenv FilePath
cabalConfigLocation = do
dirStructure <- hseDirStructure
return $ cabalDir dirStructure </> "config"
-- returns value of $PATH env variable to be used inside virtual environment
insidePathVar :: Hsenv String
insidePathVar = do
oldPathVar <- liftIO $ getEnvVar "PATH"
let oldPathVarSuffix = case oldPathVar of
Nothing -> ""
Just x -> ':' : x
dirStructure <- hseDirStructure
ghc <- asks ghcSource
let extraPathElems = case ghc of
System -> [cabalBinDir dirStructure]
_ -> [cabalBinDir dirStructure, ghcBinDir dirStructure]
return $ intercalate ":" extraPathElems ++ oldPathVarSuffix
-- returns path to ~/.hsenv dir
userHsenvDir :: Hsenv FilePath
userHsenvDir = liftIO $ getAppUserDataDirectory "hsenv"
-- returns path to ~/.hsenv/cache directory
userCacheDir :: Hsenv FilePath
userCacheDir = do
baseDir <- userHsenvDir
return $ baseDir </> "cache"
-- returns path to cached version of compiled binary for cabal-install
-- (depends on Cabal library version),
-- e.g. ~/.hsenv/cache/cabal-install/Cabal-0.14.0
cachedCabalInstallPath :: Version -> Hsenv FilePath
cachedCabalInstallPath cabalVersion = do
cacheDir <- userCacheDir
let cabInsCachePath = cacheDir </> "cabal-install"
return $ cabInsCachePath </> "Cabal-" ++ prettyVersion cabalVersion
|
Paczesiowa/hsenv
|
src/Paths.hs
|
bsd-3-clause
| 3,159 | 0 | 14 | 829 | 582 | 307 | 275 | 63 | 3 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
-- | Runners in various modes.
module Pos.Launcher.Runner
( -- * High level runners
runRealMode
-- * Exported for custom usage in CLI utils
, runServer
, elimRealMode
) where
import Universum
import Control.Concurrent.Async (race)
import qualified Control.Monad.Reader as Mtl
import Data.Default (Default)
import System.Exit (ExitCode (..))
import Pos.Chain.Block (HasBlockConfiguration, recoveryHeadersMessage,
streamWindow)
import Pos.Chain.Genesis as Genesis (Config (..))
import Pos.Chain.Txp (TxpConfiguration)
import Pos.Chain.Update (UpdateConfiguration, lastKnownBlockVersion,
updateConfiguration)
import Pos.Configuration (HasNodeConfiguration,
networkConnectionTimeout)
import Pos.Context.Context (NodeContext (..))
import Pos.Core.JsonLog (jsonLog)
import Pos.Crypto (ProtocolMagic)
import Pos.DB.Txp (MonadTxpLocal)
import Pos.Diffusion.Full (FullDiffusionConfiguration (..),
diffusionLayerFull)
import Pos.Infra.Diffusion.Types (Diffusion (..), DiffusionLayer (..),
hoistDiffusion)
import Pos.Infra.Network.Types (NetworkConfig (..),
topologyRoute53HealthCheckEnabled)
import Pos.Infra.Reporting.Ekg (EkgNodeMetrics (..),
registerEkgMetrics, withEkgServer)
import Pos.Infra.Reporting.Statsd (withStatsd)
import Pos.Infra.Shutdown (ShutdownContext, waitForShutdown)
import Pos.Launcher.Configuration (HasConfigurations)
import Pos.Launcher.Param (BaseParams (..), LoggingParams (..),
NodeParams (..))
import Pos.Launcher.Resource (NodeResources (..))
import Pos.Logic.Full (logicFull)
import Pos.Logic.Types (Logic, hoistLogic)
import Pos.Reporting.Production (ProductionReporterParams (..),
productionReporter)
import Pos.Util.CompileInfo (HasCompileInfo, compileInfo)
import Pos.Util.Trace (wlogTrace)
import Pos.Util.Trace.Named (appendName, fromTypeclassNamedTraceWlog)
import Pos.Web.Server (withRoute53HealthCheckApplication)
import Pos.WorkMode (RealMode, RealModeContext (..))
----------------------------------------------------------------------------
-- High level runners
----------------------------------------------------------------------------
-- | Run activity in something convertible to 'RealMode' and back.
runRealMode
:: forall ext a.
( Default ext
, HasCompileInfo
, HasConfigurations
, MonadTxpLocal (RealMode ext)
-- MonadTxpLocal is meh,
-- we can't remove @ext@ from @RealMode@ because
-- explorer and wallet use RealMode,
-- though they should use only @RealModeContext@
)
=> UpdateConfiguration
-> Genesis.Config
-> TxpConfiguration
-> NodeResources ext
-> (Diffusion (RealMode ext) -> RealMode ext a)
-> IO a
runRealMode uc genesisConfig txpConfig nr@NodeResources {..} act =
runServer
updateConfiguration
genesisConfig
ncNodeParams
(EkgNodeMetrics nrEkgStore)
ncShutdownContext
makeLogicIO
act'
where
NodeContext {..} = nrContext
NodeParams {..} = ncNodeParams
logic :: Logic (RealMode ext)
logic = logicFull genesisConfig txpConfig jsonLog
pm = configProtocolMagic genesisConfig
makeLogicIO :: Diffusion IO -> Logic IO
makeLogicIO diffusion = hoistLogic
(elimRealMode uc pm nr diffusion)
liftIO
logic
act' :: Diffusion IO -> IO a
act' diffusion =
let diffusion' = hoistDiffusion liftIO (elimRealMode uc pm nr diffusion) diffusion
in elimRealMode uc pm nr diffusion (act diffusion')
-- | RealMode runner: creates a JSON log configuration and uses the
-- resources provided to eliminate the RealMode, yielding an IO.
elimRealMode
:: forall t ext
. HasCompileInfo
=> UpdateConfiguration
-> ProtocolMagic
-> NodeResources ext
-> Diffusion IO
-> RealMode ext t
-> IO t
elimRealMode uc pm NodeResources {..} diffusion action = do
Mtl.runReaderT action rmc
where
NodeContext {..} = nrContext
NodeParams {..} = ncNodeParams
NetworkConfig {..} = ncNetworkConfig
LoggingParams {..} = bpLoggingParams npBaseParams
reporterParams = ProductionReporterParams
{ prpServers = npReportServers
, prpLoggerConfig = ncLoggerConfig
, prpCompileTimeInfo = compileInfo
-- Careful: this uses a CanLog IO instance from Wlog.Compatibility
-- which assumes you have set up some global logging state.
, prpTrace = wlogTrace "reporter"
, prpProtocolMagic = pm
}
rmc = RealModeContext
nrDBs
nrSscState
nrTxpState
nrDlgState
nrJsonLogConfig
lpDefaultName
nrContext
(productionReporter reporterParams diffusion)
uc
-- | "Batteries-included" server.
-- Bring up a full diffusion layer over a TCP transport and use it to run some
-- action. Also brings up ekg monitoring, route53 health check, statds,
-- according to parameters.
-- Uses magic Data.Reflection configuration for the protocol constants,
-- network connection timeout (nt-tcp), and, and the 'recoveryHeadersMessage'
-- number.
runServer
:: forall t
. (HasBlockConfiguration, HasNodeConfiguration)
=> UpdateConfiguration
-> Genesis.Config
-> NodeParams
-> EkgNodeMetrics
-> ShutdownContext
-> (Diffusion IO -> Logic IO)
-> (Diffusion IO -> IO t)
-> IO t
runServer uc genesisConfig NodeParams {..} ekgNodeMetrics shdnContext mkLogic act = exitOnShutdown $
diffusionLayerFull fdconf
npNetworkConfig
(Just ekgNodeMetrics)
mkLogic $ \diffusionLayer -> do
when npEnableMetrics (registerEkgMetrics ekgStore)
runDiffusionLayer diffusionLayer $
maybeWithRoute53 (healthStatus (diffusion diffusionLayer)) $
maybeWithEkg $
maybeWithStatsd $
-- The 'act' is in 'm', and needs a 'Diffusion m'. We can hoist
-- that, since 'm' is 'MonadIO'.
(act (diffusion diffusionLayer))
where
fdconf = FullDiffusionConfiguration
{ fdcProtocolMagic = configProtocolMagic genesisConfig
, fdcProtocolConstants = configProtocolConstants genesisConfig
, fdcRecoveryHeadersMessage = recoveryHeadersMessage
, fdcLastKnownBlockVersion = lastKnownBlockVersion uc
, fdcConvEstablishTimeout = networkConnectionTimeout
-- Use the Wlog.Compatibility name trace (magic CanLog IO instance)
, fdcTrace = appendName "diffusion" fromTypeclassNamedTraceWlog
, fdcStreamWindow = streamWindow
-- TODO should be configurable
, fdcBatchSize = 64
}
exitOnShutdown action = do
result <- race (waitForShutdown shdnContext) action
let
code = case result of
Left code' -> code'
Right _ -> ExitSuccess
exitWith code
ekgStore = enmStore ekgNodeMetrics
(hcHost, hcPort) = case npRoute53Params of
Nothing -> ("127.0.0.1", 3030)
Just (hst, prt) -> (decodeUtf8 hst, fromIntegral prt)
maybeWithRoute53 mStatus = case topologyRoute53HealthCheckEnabled (ncTopology npNetworkConfig) of
True -> withRoute53HealthCheckApplication mStatus hcHost hcPort
False -> identity
maybeWithEkg = case (npEnableMetrics, npEkgParams) of
(True, Just ekgParams) -> withEkgServer ekgParams ekgStore
_ -> identity
maybeWithStatsd = case (npEnableMetrics, npStatsdParams) of
(True, Just sdParams) -> withStatsd sdParams ekgStore
_ -> identity
|
input-output-hk/pos-haskell-prototype
|
lib/src/Pos/Launcher/Runner.hs
|
mit
| 8,232 | 0 | 17 | 2,295 | 1,523 | 855 | 668 | -1 | -1 |
module A where
import B
main = 'a' +++ 3
|
roberth/uu-helium
|
test/typeerrors/Strategies/A.hs
|
gpl-3.0
| 43 | 0 | 5 | 12 | 16 | 10 | 6 | 3 | 1 |
{-# LANGUAGE CPP #-}
{-|
Module : Idris.CmdOptions
Description : A parser for the CmdOptions for the Idris executable.
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE Arrows #-}
module Idris.CmdOptions
(
module Idris.CmdOptions
, opt
, getClient, getPkg, getPkgCheck, getPkgClean, getPkgMkDoc
, getPkgREPL, getPkgTest, getPort, getIBCSubDir
) where
import Idris.AbsSyntax (getClient, getIBCSubDir, getPkg, getPkgCheck,
getPkgClean, getPkgMkDoc, getPkgREPL, getPkgTest,
getPort, opt)
import Idris.AbsSyntaxTree
import Idris.Info (getIdrisVersion)
import IRTS.CodegenCommon
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Except (throwE)
import Control.Monad.Trans.Reader (ask)
import Data.Char
import Data.Maybe
#if MIN_VERSION_optparse_applicative(0,13,0)
import Data.Monoid ((<>))
#endif
import Options.Applicative
import Options.Applicative.Arrows
import Options.Applicative.Types (ReadM(..))
import Text.ParserCombinators.ReadP hiding (many, option)
import Safe (lastMay)
import qualified Text.PrettyPrint.ANSI.Leijen as PP
runArgParser :: IO [Opt]
runArgParser = do opts <- execParser $ info parser
(fullDesc
<> headerDoc (Just idrisHeader)
<> progDescDoc (Just idrisProgDesc)
<> footerDoc (Just idrisFooter)
)
return $ preProcOpts opts
where
idrisHeader = PP.hsep [PP.text "Idris version", PP.text getIdrisVersion, PP.text ", (C) The Idris Community 2016"]
idrisProgDesc = PP.vsep [PP.empty,
PP.text "Idris is a general purpose pure functional programming language with dependent",
PP.text "types. Dependent types allow types to be predicated on values, meaning that",
PP.text "some aspects of a program's behaviour can be specified precisely in the type.",
PP.text "It is compiled, with eager evaluation. Its features are influenced by Haskell",
PP.text "and ML.",
PP.empty,
PP.vsep $ map (PP.indent 4 . PP.text) [
"+ Full dependent types with dependent pattern matching",
"+ Simple case expressions, where-clauses, with-rule",
"+ Pattern matching let- and lambda-bindings",
"+ Overloading via Interfaces (Type class-like), Monad comprehensions",
"+ do-notation, idiom brackets",
"+ Syntactic conveniences for lists, tuples, dependent pairs",
"+ Totality checking",
"+ Coinductive types",
"+ Indentation significant syntax, Extensible syntax",
"+ Tactic based theorem proving (influenced by Coq)",
"+ Cumulative universes",
"+ Simple Foreign Function Interface",
"+ Hugs style interactive environment"
]]
idrisFooter = PP.vsep [PP.text "It is important to note that Idris is first and foremost a research tool",
PP.text "and project. Thus the tooling provided and resulting programs created",
PP.text "should not necessarily be seen as production ready nor for industrial use.",
PP.empty,
PP.text "More details over Idris can be found online here:",
PP.empty,
PP.indent 4 (PP.text "http://www.idris-lang.org/")]
pureArgParser :: [String] -> [Opt]
pureArgParser args = case getParseResult $ execParserPure (prefs idm) (info parser idm) args of
Just opts -> preProcOpts opts
Nothing -> []
parser :: Parser [Opt]
parser = runA $ proc () -> do
flags <- asA parseFlags -< ()
files <- asA (many $ argument (fmap Filename str) (metavar "FILES")) -< ()
A parseVersion >>> A helper -< (flags ++ files)
parseFlags :: Parser [Opt]
parseFlags = many $
flag' NoBanner (long "nobanner" <> help "Suppress the banner")
<|> flag' Quiet (short 'q' <> long "quiet" <> help "Quiet verbosity")
-- IDE Mode Specific Flags
<|> flag' Idemode (long "ide-mode" <> help "Run the Idris REPL with machine-readable syntax")
<|> flag' IdemodeSocket (long "ide-mode-socket" <> help "Choose a socket for IDE mode to listen on")
-- Client flags
<|> Client <$> strOption (long "client")
-- Logging Flags
<|> OLogging <$> option auto (long "log" <> metavar "LEVEL" <> help "Debugging log level")
<|> OLogCats <$> option (str >>= parseLogCats)
(long "logging-categories"
<> metavar "CATS"
<> help "Colon separated logging categories. Use --listlogcats to see list.")
-- Turn off things
<|> flag' NoBasePkgs (long "nobasepkgs" <> help "Do not use the given base package")
<|> flag' NoPrelude (long "noprelude" <> help "Do not use the given prelude")
<|> flag' NoBuiltins (long "nobuiltins" <> help "Do not use the builtin functions")
<|> flag' NoREPL (long "check" <> help "Typecheck only, don't start the REPL")
<|> Output <$> strOption (short 'o' <> long "output" <> metavar "FILE" <> help "Specify output file")
-- <|> flag' TypeCase (long "typecase")
<|> flag' Interface (long "interface" <> help "Generate interface files from ExportLists")
<|> flag' TypeInType (long "typeintype" <> help "Turn off Universe checking")
<|> flag' DefaultTotal (long "total" <> help "Require functions to be total by default")
<|> flag' DefaultPartial (long "partial")
<|> flag' WarnPartial (long "warnpartial" <> help "Warn about undeclared partial functions")
<|> flag' WarnReach (long "warnreach" <> help "Warn about reachable but inaccessible arguments")
<|> flag' NoCoverage (long "nocoverage")
<|> flag' ErrContext (long "errorcontext")
-- Show things
<|> flag' ShowAll (long "info" <> help "Display information about installation.")
<|> flag' ShowLoggingCats (long "listlogcats" <> help "Display logging categories")
<|> flag' ShowLibs (long "link" <> help "Display link flags")
<|> flag' ShowPkgs (long "listlibs" <> help "Display installed libraries")
<|> flag' ShowLibDir (long "libdir" <> help "Display library directory")
<|> flag' ShowDocDir (long "docdir" <> help "Display idrisdoc install directory")
<|> flag' ShowIncs (long "include" <> help "Display the includes flags")
<|> flag' (Verbose 3) (long "V2" <> help "Loudest verbosity")
<|> flag' (Verbose 2) (long "V1" <> help "Louder verbosity")
<|> flag' (Verbose 1) (short 'V' <> long "V0" <>long "verbose" <> help "Loud verbosity")
<|> IBCSubDir <$> strOption (long "ibcsubdir" <> metavar "FILE" <> help "Write IBC files into sub directory")
<|> ImportDir <$> strOption (short 'i' <> long "idrispath" <> help "Add directory to the list of import paths")
<|> SourceDir <$> strOption (long "sourcepath" <> help "Add directory to the list of source search paths")
<|> flag' WarnOnly (long "warn")
<|> Pkg <$> strOption (short 'p' <> long "package" <> help "Add package as a dependency")
<|> Port <$> option portReader (long "port" <> metavar "PORT" <> help "REPL TCP port - pass \"none\" to not bind any port")
-- Package commands
<|> PkgBuild <$> strOption (long "build" <> metavar "IPKG" <> help "Build package")
<|> PkgInstall <$> strOption (long "install" <> metavar "IPKG" <> help "Install package")
<|> PkgREPL <$> strOption (long "repl" <> metavar "IPKG" <> help "Launch REPL, only for executables")
<|> PkgClean <$> strOption (long "clean" <> metavar "IPKG" <> help "Clean package")
<|> (PkgDocBuild <$> strOption (long "mkdoc" <> metavar "IPKG" <> help "Generate IdrisDoc for package"))
<|> PkgDocInstall <$> strOption (long "installdoc" <> metavar "IPKG" <> help "Install IdrisDoc for package")
<|> PkgCheck <$> strOption (long "checkpkg" <> metavar "IPKG" <> help "Check package only")
<|> PkgTest <$> strOption (long "testpkg" <> metavar "IPKG" <> help "Run tests for package")
-- Interactive Editing Flags
<|> IndentWith <$> option auto (long "indent-with"
<> metavar "INDENT"
<> help "Indentation to use with :makewith (default 2)")
<|> IndentClause <$> option auto (long "indent-clause"
<> metavar "INDENT"
<> help "Indentation to use with :addclause (default 2)")
-- Misc options
<|> BCAsm <$> strOption (long "bytecode")
<|> flag' (OutputTy Raw) (short 'S' <> long "codegenonly" <> help "Do no further compilation of code generator output")
<|> flag' (OutputTy Object) (short 'c' <> long "compileonly" <> help "Compile to object files rather than an executable")
<|> DumpDefun <$> strOption (long "dumpdefuns")
<|> DumpCases <$> strOption (long "dumpcases")
<|> (UseCodegen . parseCodegen) <$> strOption (long "codegen"
<> metavar "TARGET"
<> help "Select code generator: C, Javascript, Node and bytecode are bundled with Idris")
<|> ((UseCodegen . Via JSONFormat) <$> strOption (long "portable-codegen"
<> metavar "TARGET"
<> help "Pass the name of the code generator. This option is for codegens that take JSON formatted IR."))
<|> CodegenArgs <$> strOption (long "cg-opt"
<> metavar "ARG"
<> help "Arguments to pass to code generator")
<|> EvalExpr <$> strOption (long "eval"
<> short 'e'
<> metavar "EXPR"
<> help "Evaluate an expression without loading the REPL")
<|> flag' (InterpretScript "Main.main") (long "execute" <> help "Execute as idris")
<|> InterpretScript <$> strOption (long "exec" <> metavar "EXPR" <> help "Execute as idris")
<|> ((Extension . getExt) <$> strOption (long "extension"
<> short 'X'
<> metavar "EXT"
<> help "Turn on language extension (TypeProviders or ErrorReflection)"))
-- Optimisation Levels
<|> flag' (OptLevel 3) (long "O3")
<|> flag' (OptLevel 2) (long "O2")
<|> flag' (OptLevel 1) (long "O1")
<|> flag' (OptLevel 0) (long "O0")
<|> flag' (AddOpt PETransform) (long "partial-eval")
<|> flag' (RemoveOpt PETransform) (long "no-partial-eval" <> help "Switch off partial evaluation, mainly for debugging purposes")
<|> OptLevel <$> option auto (short 'O' <> long "level")
<|> TargetTriple <$> strOption (long "target" <> metavar "TRIPLE" <> help "If supported the codegen will target the named triple.")
<|> TargetCPU <$> strOption (long "cpu" <> metavar "CPU" <> help "If supported the codegen will target the named CPU e.g. corei7 or cortex-m3")
-- Colour Options
<|> flag' (ColourREPL True) (long "colour" <> long "color" <> help "Force coloured output")
<|> flag' (ColourREPL False) (long "nocolour" <> long "nocolor" <> help "Disable coloured output")
<|> (UseConsoleWidth <$> option (str >>= parseConsoleWidth) (long "consolewidth" <> metavar "WIDTH" <> help "Select console width: auto, infinite, nat"))
<|> flag' DumpHighlights (long "highlight" <> help "Emit source code highlighting")
<|> flag' NoElimDeprecationWarnings (long "no-elim-deprecation-warnings" <> help "Disable deprecation warnings for %elim")
<|> flag' NoOldTacticDeprecationWarnings (long "no-tactic-deprecation-warnings" <> help "Disable deprecation warnings for the old tactic sublanguage")
where
getExt :: String -> LanguageExt
getExt s = fromMaybe (error ("Unknown extension " ++ s)) (maybeRead s)
maybeRead :: String -> Maybe LanguageExt
maybeRead = fmap fst . listToMaybe . reads
portReader :: ReadM REPLPort
portReader =
((ListenPort . fromIntegral) <$> auto) <|>
(ReadM $ do opt <- ask
if map toLower opt == "none"
then return $ DontListen
else lift $ throwE $ ErrorMsg $
"got " <> opt <> " expected port number or \"none\"")
parseVersion :: Parser (a -> a)
parseVersion = infoOption getIdrisVersion (short 'v' <> long "version" <> help "Print version information")
preProcOpts :: [Opt] -> [Opt]
preProcOpts (NoBuiltins : xs) = NoBuiltins : NoPrelude : preProcOpts xs
preProcOpts (Output s : xs) = Output s : NoREPL : preProcOpts xs
preProcOpts (BCAsm s : xs) = BCAsm s : NoREPL : preProcOpts xs
preProcOpts (x:xs) = x : preProcOpts xs
preProcOpts [] = []
parseCodegen :: String -> Codegen
parseCodegen "bytecode" = Bytecode
parseCodegen cg = Via IBCFormat (map toLower cg)
parseLogCats :: Monad m => String -> m [LogCat]
parseLogCats s =
case lastMay (readP_to_S doParse s) of
Just (xs, _) -> return xs
_ -> fail "Incorrect categories specified"
where
doParse :: ReadP [LogCat]
doParse = do
cs <- sepBy1 parseLogCat (char ':')
eof
return (concat cs)
parseLogCat :: ReadP [LogCat]
parseLogCat = (string (strLogCat IParse) *> return parserCats)
<|> (string (strLogCat IElab) *> return elabCats)
<|> (string (strLogCat ICodeGen) *> return codegenCats)
<|> (string (strLogCat ICoverage) *> return [ICoverage])
<|> (string (strLogCat IIBC) *> return [IIBC])
<|> (string (strLogCat IErasure) *> return [IErasure])
<|> parseLogCatBad
parseLogCatBad :: ReadP [LogCat]
parseLogCatBad = do
s <- look
fail $ "Category: " ++ s ++ " is not recognised."
parseConsoleWidth :: Monad m => String -> m ConsoleWidth
parseConsoleWidth "auto" = return AutomaticWidth
parseConsoleWidth "infinite" = return InfinitelyWide
parseConsoleWidth s =
case lastMay (readP_to_S integerReader s) of
Just (r, _) -> return $ ColsWide r
_ -> fail $ "Cannot parse: " ++ s
integerReader :: ReadP Int
integerReader = do
digits <- many1 $ satisfy isDigit
return $ read digits
|
jmitchell/Idris-dev
|
src/Idris/CmdOptions.hs
|
bsd-3-clause
| 15,359 | 1 | 109 | 4,835 | 3,571 | 1,746 | 1,825 | 220 | 2 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1998
\section[TypeRep]{Type - friends' interface}
Note [The Type-related module hierarchy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Class
TyCon imports Class
TypeRep
TysPrim imports TypeRep ( including mkTyConTy )
Kind imports TysPrim ( mainly for primitive kinds )
Type imports Kind
Coercion imports Type
-}
{-# LANGUAGE CPP, DeriveDataTypeable, DeriveFunctor, DeriveFoldable,
DeriveTraversable, DataKinds #-}
{-# OPTIONS_HADDOCK hide #-}
-- We expose the relevant stuff from this module via the Type module
module TypeRep (
TyThing(..),
Type(..),
TyLit(..),
KindOrType, Kind, SuperKind,
PredType, ThetaType, -- Synonyms
-- Functions over types
mkTyConTy, mkTyVarTy, mkTyVarTys,
isLiftedTypeKind, isSuperKind, isTypeVar, isKindVar,
-- Pretty-printing
pprType, pprParendType, pprTypeApp, pprTvBndr, pprTvBndrs,
pprTyThing, pprTyThingCategory, pprSigmaType,
pprTheta, pprForAll, pprUserForAll,
pprThetaArrowTy, pprClassPred,
pprKind, pprParendKind, pprTyLit, suppressKinds,
TyPrec(..), maybeParen, pprTcApp,
pprPrefixApp, pprArrowChain, ppr_type,
-- Free variables
tyVarsOfType, tyVarsOfTypes, closeOverKinds, varSetElemsKvsFirst,
-- * Tidying type related things up for printing
tidyType, tidyTypes,
tidyOpenType, tidyOpenTypes,
tidyOpenKind,
tidyTyVarBndr, tidyTyVarBndrs, tidyFreeTyVars,
tidyOpenTyVar, tidyOpenTyVars,
tidyTyVarOcc,
tidyTopType,
tidyKind,
-- Substitutions
TvSubst(..), TvSubstEnv
) where
#include "HsVersions.h"
import {-# SOURCE #-} DataCon( dataConTyCon )
import ConLike ( ConLike(..) )
import {-# SOURCE #-} Type( isPredTy ) -- Transitively pulls in a LOT of stuff, better to break the loop
-- friends:
import Var
import VarEnv
import VarSet
import Name
import BasicTypes
import TyCon
import Class
import CoAxiom
-- others
import PrelNames
import Outputable
import FastString
import Util
import DynFlags
import StaticFlags( opt_PprStyle_Debug )
-- libraries
import Data.List( mapAccumL, partition )
import qualified Data.Data as Data hiding ( TyCon )
{-
************************************************************************
* *
\subsection{The data type}
* *
************************************************************************
-}
-- | The key representation of types within the compiler
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Type
= TyVarTy Var -- ^ Vanilla type or kind variable (*never* a coercion variable)
| AppTy -- See Note [AppTy rep]
Type
Type -- ^ Type application to something other than a 'TyCon'. Parameters:
--
-- 1) Function: must /not/ be a 'TyConApp',
-- must be another 'AppTy', or 'TyVarTy'
--
-- 2) Argument type
| TyConApp -- See Note [AppTy rep]
TyCon
[KindOrType] -- ^ Application of a 'TyCon', including newtypes /and/ synonyms.
-- Invariant: saturated applications of 'FunTyCon' must
-- use 'FunTy' and saturated synonyms must use their own
-- constructors. However, /unsaturated/ 'FunTyCon's
-- do appear as 'TyConApp's.
-- Parameters:
--
-- 1) Type constructor being applied to.
--
-- 2) Type arguments. Might not have enough type arguments
-- here to saturate the constructor.
-- Even type synonyms are not necessarily saturated;
-- for example unsaturated type synonyms
-- can appear as the right hand side of a type synonym.
| FunTy
Type
Type -- ^ Special case of 'TyConApp': @TyConApp FunTyCon [t1, t2]@
-- See Note [Equality-constrained types]
| ForAllTy
Var -- Type or kind variable
Type -- ^ A polymorphic type
| LitTy TyLit -- ^ Type literals are similar to type constructors.
deriving (Data.Data, Data.Typeable)
-- NOTE: Other parts of the code assume that type literals do not contain
-- types or type variables.
data TyLit
= NumTyLit Integer
| StrTyLit FastString
deriving (Eq, Ord, Data.Data, Data.Typeable)
type KindOrType = Type -- See Note [Arguments to type constructors]
-- | The key type representing kinds in the compiler.
-- Invariant: a kind is always in one of these forms:
--
-- > FunTy k1 k2
-- > TyConApp PrimTyCon [...]
-- > TyVar kv -- (during inference only)
-- > ForAll ... -- (for top-level coercions)
type Kind = Type
-- | "Super kinds", used to help encode 'Kind's as types.
-- Invariant: a super kind is always of this form:
--
-- > TyConApp SuperKindTyCon ...
type SuperKind = Type
{-
Note [The kind invariant]
~~~~~~~~~~~~~~~~~~~~~~~~~
The kinds
# UnliftedTypeKind
OpenKind super-kind of *, #
can never appear under an arrow or type constructor in a kind; they
can only be at the top level of a kind. It follows that primitive TyCons,
which have a naughty pseudo-kind
State# :: * -> #
must always be saturated, so that we can never get a type whose kind
has a UnliftedTypeKind or ArgTypeKind underneath an arrow.
Nor can we abstract over a type variable with any of these kinds.
k :: = kk | # | ArgKind | (#) | OpenKind
kk :: = * | kk -> kk | T kk1 ... kkn
So a type variable can only be abstracted kk.
Note [Arguments to type constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Because of kind polymorphism, in addition to type application we now
have kind instantiation. We reuse the same notations to do so.
For example:
Just (* -> *) Maybe
Right * Nat Zero
are represented by:
TyConApp (PromotedDataCon Just) [* -> *, Maybe]
TyConApp (PromotedDataCon Right) [*, Nat, (PromotedDataCon Zero)]
Important note: Nat is used as a *kind* and not as a type. This can be
confusing, since type-level Nat and kind-level Nat are identical. We
use the kind of (PromotedDataCon Right) to know if its arguments are
kinds or types.
This kind instantiation only happens in TyConApp currently.
Note [Equality-constrained types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The type forall ab. (a ~ [b]) => blah
is encoded like this:
ForAllTy (a:*) $ ForAllTy (b:*) $
FunTy (TyConApp (~) [a, [b]]) $
blah
-------------------------------------
Note [PredTy]
-}
-- | A type of the form @p@ of kind @Constraint@ represents a value whose type is
-- the Haskell predicate @p@, where a predicate is what occurs before
-- the @=>@ in a Haskell type.
--
-- We use 'PredType' as documentation to mark those types that we guarantee to have
-- this kind.
--
-- It can be expanded into its representation, but:
--
-- * The type checker must treat it as opaque
--
-- * The rest of the compiler treats it as transparent
--
-- Consider these examples:
--
-- > f :: (Eq a) => a -> Int
-- > g :: (?x :: Int -> Int) => a -> Int
-- > h :: (r\l) => {r} => {l::Int | r}
--
-- Here the @Eq a@ and @?x :: Int -> Int@ and @r\l@ are all called \"predicates\"
type PredType = Type
-- | A collection of 'PredType's
type ThetaType = [PredType]
{-
(We don't support TREX records yet, but the setup is designed
to expand to allow them.)
A Haskell qualified type, such as that for f,g,h above, is
represented using
* a FunTy for the double arrow
* with a type of kind Constraint as the function argument
The predicate really does turn into a real extra argument to the
function. If the argument has type (p :: Constraint) then the predicate p is
represented by evidence of type p.
************************************************************************
* *
Simple constructors
* *
************************************************************************
These functions are here so that they can be used by TysPrim,
which in turn is imported by Type
-}
mkTyVarTy :: TyVar -> Type
mkTyVarTy = TyVarTy
mkTyVarTys :: [TyVar] -> [Type]
mkTyVarTys = map mkTyVarTy -- a common use of mkTyVarTy
-- | Create the plain type constructor type which has been applied to no type arguments at all.
mkTyConTy :: TyCon -> Type
mkTyConTy tycon = TyConApp tycon []
-- Some basic functions, put here to break loops eg with the pretty printer
isLiftedTypeKind :: Kind -> Bool
isLiftedTypeKind (TyConApp tc []) = tc `hasKey` liftedTypeKindTyConKey
isLiftedTypeKind _ = False
-- | Is this a super-kind (i.e. a type-of-kinds)?
isSuperKind :: Type -> Bool
isSuperKind (TyConApp skc []) = skc `hasKey` superKindTyConKey
isSuperKind _ = False
isTypeVar :: Var -> Bool
isTypeVar v = isTKVar v && not (isSuperKind (varType v))
isKindVar :: Var -> Bool
isKindVar v = isTKVar v && isSuperKind (varType v)
{-
************************************************************************
* *
Free variables of types and coercions
* *
************************************************************************
-}
tyVarsOfType :: Type -> VarSet
-- ^ NB: for type synonyms tyVarsOfType does /not/ expand the synonym
-- tyVarsOfType returns free variables of a type, including kind variables.
tyVarsOfType (TyVarTy v) = unitVarSet v
tyVarsOfType (TyConApp _ tys) = tyVarsOfTypes tys
tyVarsOfType (LitTy {}) = emptyVarSet
tyVarsOfType (FunTy arg res) = tyVarsOfType arg `unionVarSet` tyVarsOfType res
tyVarsOfType (AppTy fun arg) = tyVarsOfType fun `unionVarSet` tyVarsOfType arg
tyVarsOfType (ForAllTy tyvar ty) = delVarSet (tyVarsOfType ty) tyvar
`unionVarSet` tyVarsOfType (tyVarKind tyvar)
tyVarsOfTypes :: [Type] -> TyVarSet
tyVarsOfTypes = mapUnionVarSet tyVarsOfType
closeOverKinds :: TyVarSet -> TyVarSet
-- Add the kind variables free in the kinds
-- of the tyvars in the given set
closeOverKinds tvs
= foldVarSet (\tv ktvs -> tyVarsOfType (tyVarKind tv) `unionVarSet` ktvs)
tvs tvs
varSetElemsKvsFirst :: VarSet -> [TyVar]
-- {k1,a,k2,b} --> [k1,k2,a,b]
varSetElemsKvsFirst set
= kvs ++ tvs
where
(kvs, tvs) = partition isKindVar (varSetElems set)
{-
************************************************************************
* *
TyThing
* *
************************************************************************
Despite the fact that DataCon has to be imported via a hi-boot route,
this module seems the right place for TyThing, because it's needed for
funTyCon and all the types in TysPrim.
Note [ATyCon for classes]
~~~~~~~~~~~~~~~~~~~~~~~~~
Both classes and type constructors are represented in the type environment
as ATyCon. You can tell the difference, and get to the class, with
isClassTyCon :: TyCon -> Bool
tyConClass_maybe :: TyCon -> Maybe Class
The Class and its associated TyCon have the same Name.
-}
-- | A global typecheckable-thing, essentially anything that has a name.
-- Not to be confused with a 'TcTyThing', which is also a typecheckable
-- thing but in the *local* context. See 'TcEnv' for how to retrieve
-- a 'TyThing' given a 'Name'.
data TyThing
= AnId Id
| AConLike ConLike
| ATyCon TyCon -- TyCons and classes; see Note [ATyCon for classes]
| ACoAxiom (CoAxiom Branched)
deriving (Eq, Ord)
instance Outputable TyThing where
ppr = pprTyThing
pprTyThing :: TyThing -> SDoc
pprTyThing thing = pprTyThingCategory thing <+> quotes (ppr (getName thing))
pprTyThingCategory :: TyThing -> SDoc
pprTyThingCategory (ATyCon tc)
| isClassTyCon tc = ptext (sLit "Class")
| otherwise = ptext (sLit "Type constructor")
pprTyThingCategory (ACoAxiom _) = ptext (sLit "Coercion axiom")
pprTyThingCategory (AnId _) = ptext (sLit "Identifier")
pprTyThingCategory (AConLike (RealDataCon _)) = ptext (sLit "Data constructor")
pprTyThingCategory (AConLike (PatSynCon _)) = ptext (sLit "Pattern synonym")
instance NamedThing TyThing where -- Can't put this with the type
getName (AnId id) = getName id -- decl, because the DataCon instance
getName (ATyCon tc) = getName tc -- isn't visible there
getName (ACoAxiom cc) = getName cc
getName (AConLike cl) = getName cl
{-
************************************************************************
* *
Substitutions
Data type defined here to avoid unnecessary mutual recursion
* *
************************************************************************
-}
-- | Type substitution
--
-- #tvsubst_invariant#
-- The following invariants must hold of a 'TvSubst':
--
-- 1. The in-scope set is needed /only/ to
-- guide the generation of fresh uniques
--
-- 2. In particular, the /kind/ of the type variables in
-- the in-scope set is not relevant
--
-- 3. The substitution is only applied ONCE! This is because
-- in general such application will not reach a fixed point.
data TvSubst
= TvSubst InScopeSet -- The in-scope type and kind variables
TvSubstEnv -- Substitutes both type and kind variables
-- See Note [Apply Once]
-- and Note [Extending the TvSubstEnv]
-- | A substitution of 'Type's for 'TyVar's
-- and 'Kind's for 'KindVar's
type TvSubstEnv = TyVarEnv Type
-- A TvSubstEnv is used both inside a TvSubst (with the apply-once
-- invariant discussed in Note [Apply Once]), and also independently
-- in the middle of matching, and unification (see Types.Unify)
-- So you have to look at the context to know if it's idempotent or
-- apply-once or whatever
{-
Note [Apply Once]
~~~~~~~~~~~~~~~~~
We use TvSubsts to instantiate things, and we might instantiate
forall a b. ty
\with the types
[a, b], or [b, a].
So the substitution might go [a->b, b->a]. A similar situation arises in Core
when we find a beta redex like
(/\ a /\ b -> e) b a
Then we also end up with a substitution that permutes type variables. Other
variations happen to; for example [a -> (a, b)].
***************************************************
*** So a TvSubst must be applied precisely once ***
***************************************************
A TvSubst is not idempotent, but, unlike the non-idempotent substitution
we use during unifications, it must not be repeatedly applied.
Note [Extending the TvSubst]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See #tvsubst_invariant# for the invariants that must hold.
This invariant allows a short-cut when the TvSubstEnv is empty:
if the TvSubstEnv is empty --- i.e. (isEmptyTvSubt subst) holds ---
then (substTy subst ty) does nothing.
For example, consider:
(/\a. /\b:(a~Int). ...b..) Int
We substitute Int for 'a'. The Unique of 'b' does not change, but
nevertheless we add 'b' to the TvSubstEnv, because b's kind does change
This invariant has several crucial consequences:
* In substTyVarBndr, we need extend the TvSubstEnv
- if the unique has changed
- or if the kind has changed
* In substTyVar, we do not need to consult the in-scope set;
the TvSubstEnv is enough
* In substTy, substTheta, we can short-circuit when the TvSubstEnv is empty
************************************************************************
* *
Pretty-printing types
Defined very early because of debug printing in assertions
* *
************************************************************************
@pprType@ is the standard @Type@ printer; the overloaded @ppr@ function is
defined to use this. @pprParendType@ is the same, except it puts
parens around the type, except for the atomic cases. @pprParendType@
works just by setting the initial context precedence very high.
Note [Precedence in types]
~~~~~~~~~~~~~~~~~~~~~~~~~~
We don't keep the fixity of type operators in the operator. So the pretty printer
operates the following precedene structre:
Type constructor application binds more tightly than
Oerator applications which bind more tightly than
Function arrow
So we might see a :+: T b -> c
meaning (a :+: (T b)) -> c
Maybe operator applications should bind a bit less tightly?
Anyway, that's the current story, and it is used consistently for Type and HsType
-}
data TyPrec -- See Note [Prededence in types]
= TopPrec -- No parens
| FunPrec -- Function args; no parens for tycon apps
| TyOpPrec -- Infix operator
| TyConPrec -- Tycon args; no parens for atomic
deriving( Eq, Ord )
maybeParen :: TyPrec -> TyPrec -> SDoc -> SDoc
maybeParen ctxt_prec inner_prec pretty
| ctxt_prec < inner_prec = pretty
| otherwise = parens pretty
------------------
pprType, pprParendType :: Type -> SDoc
pprType ty = ppr_type TopPrec ty
pprParendType ty = ppr_type TyConPrec ty
pprTyLit :: TyLit -> SDoc
pprTyLit = ppr_tylit TopPrec
pprKind, pprParendKind :: Kind -> SDoc
pprKind = pprType
pprParendKind = pprParendType
------------
pprClassPred :: Class -> [Type] -> SDoc
pprClassPred clas tys = pprTypeApp (classTyCon clas) tys
------------
pprTheta :: ThetaType -> SDoc
pprTheta [pred] = ppr_type TopPrec pred -- I'm in two minds about this
pprTheta theta = parens (sep (punctuate comma (map (ppr_type TopPrec) theta)))
pprThetaArrowTy :: ThetaType -> SDoc
pprThetaArrowTy [] = empty
pprThetaArrowTy [pred] = ppr_type TyOpPrec pred <+> darrow
-- TyOpPrec: Num a => a -> a does not need parens
-- bug (a :~: b) => a -> b currently does
-- Trac # 9658
pprThetaArrowTy preds = parens (fsep (punctuate comma (map (ppr_type TopPrec) preds)))
<+> darrow
-- Notice 'fsep' here rather that 'sep', so that
-- type contexts don't get displayed in a giant column
-- Rather than
-- instance (Eq a,
-- Eq b,
-- Eq c,
-- Eq d,
-- Eq e,
-- Eq f,
-- Eq g,
-- Eq h,
-- Eq i,
-- Eq j,
-- Eq k,
-- Eq l) =>
-- Eq (a, b, c, d, e, f, g, h, i, j, k, l)
-- we get
--
-- instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i,
-- Eq j, Eq k, Eq l) =>
-- Eq (a, b, c, d, e, f, g, h, i, j, k, l)
------------------
instance Outputable Type where
ppr ty = pprType ty
instance Outputable TyLit where
ppr = pprTyLit
------------------
-- OK, here's the main printer
ppr_type :: TyPrec -> Type -> SDoc
ppr_type _ (TyVarTy tv) = ppr_tvar tv
ppr_type p (TyConApp tc tys) = pprTyTcApp p tc tys
ppr_type p (LitTy l) = ppr_tylit p l
ppr_type p ty@(ForAllTy {}) = ppr_forall_type p ty
ppr_type p (AppTy t1 t2) = maybeParen p TyConPrec $
ppr_type FunPrec t1 <+> ppr_type TyConPrec t2
ppr_type p fun_ty@(FunTy ty1 ty2)
| isPredTy ty1
= ppr_forall_type p fun_ty
| otherwise
= pprArrowChain p (ppr_type FunPrec ty1 : ppr_fun_tail ty2)
where
-- We don't want to lose synonyms, so we mustn't use splitFunTys here.
ppr_fun_tail (FunTy ty1 ty2)
| not (isPredTy ty1) = ppr_type FunPrec ty1 : ppr_fun_tail ty2
ppr_fun_tail other_ty = [ppr_type TopPrec other_ty]
ppr_forall_type :: TyPrec -> Type -> SDoc
ppr_forall_type p ty
= maybeParen p FunPrec $ ppr_sigma_type True ty
-- True <=> we always print the foralls on *nested* quantifiers
-- Opt_PrintExplicitForalls only affects top-level quantifiers
-- False <=> we don't print an extra-constraints wildcard
ppr_tvar :: TyVar -> SDoc
ppr_tvar tv -- Note [Infix type variables]
= parenSymOcc (getOccName tv) (ppr tv)
ppr_tylit :: TyPrec -> TyLit -> SDoc
ppr_tylit _ tl =
case tl of
NumTyLit n -> integer n
StrTyLit s -> text (show s)
-------------------
ppr_sigma_type :: Bool -> Type -> SDoc
-- First Bool <=> Show the foralls unconditionally
-- Second Bool <=> Show an extra-constraints wildcard
ppr_sigma_type show_foralls_unconditionally ty
= sep [ if show_foralls_unconditionally
then pprForAll tvs
else pprUserForAll tvs
, pprThetaArrowTy ctxt
, pprType tau ]
where
(tvs, rho) = split1 [] ty
(ctxt, tau) = split2 [] rho
split1 tvs (ForAllTy tv ty) = split1 (tv:tvs) ty
split1 tvs ty = (reverse tvs, ty)
split2 ps (ty1 `FunTy` ty2) | isPredTy ty1 = split2 (ty1:ps) ty2
split2 ps ty = (reverse ps, ty)
pprSigmaType :: Type -> SDoc
pprSigmaType ty = ppr_sigma_type False ty
pprUserForAll :: [TyVar] -> SDoc
-- Print a user-level forall; see Note [When to print foralls]
pprUserForAll tvs
= sdocWithDynFlags $ \dflags ->
ppWhen (any tv_has_kind_var tvs || gopt Opt_PrintExplicitForalls dflags) $
pprForAll tvs
where
tv_has_kind_var tv = not (isEmptyVarSet (tyVarsOfType (tyVarKind tv)))
pprForAll :: [TyVar] -> SDoc
pprForAll [] = empty
pprForAll tvs = forAllLit <+> pprTvBndrs tvs <> dot
pprTvBndrs :: [TyVar] -> SDoc
pprTvBndrs tvs = sep (map pprTvBndr tvs)
pprTvBndr :: TyVar -> SDoc
pprTvBndr tv
| isLiftedTypeKind kind = ppr_tvar tv
| otherwise = parens (ppr_tvar tv <+> dcolon <+> pprKind kind)
where
kind = tyVarKind tv
{-
Note [When to print foralls]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mostly we want to print top-level foralls when (and only when) the user specifies
-fprint-explicit-foralls. But when kind polymorphism is at work, that suppresses
too much information; see Trac #9018.
So I'm trying out this rule: print explicit foralls if
a) User specifies -fprint-explicit-foralls, or
b) Any of the quantified type variables has a kind
that mentions a kind variable
This catches common situations, such as a type siguature
f :: m a
which means
f :: forall k. forall (m :: k->*) (a :: k). m a
We really want to see both the "forall k" and the kind signatures
on m and a. The latter comes from pprTvBndr.
Note [Infix type variables]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
With TypeOperators you can say
f :: (a ~> b) -> b
and the (~>) is considered a type variable. However, the type
pretty-printer in this module will just see (a ~> b) as
App (App (TyVarTy "~>") (TyVarTy "a")) (TyVarTy "b")
So it'll print the type in prefix form. To avoid confusion we must
remember to parenthesise the operator, thus
(~>) a b -> b
See Trac #2766.
-}
pprTypeApp :: TyCon -> [Type] -> SDoc
pprTypeApp tc tys = pprTyTcApp TopPrec tc tys
-- We have to use ppr on the TyCon (not its name)
-- so that we get promotion quotes in the right place
pprTyTcApp :: TyPrec -> TyCon -> [Type] -> SDoc
-- Used for types only; so that we can make a
-- special case for type-level lists
pprTyTcApp p tc tys
| tc `hasKey` ipTyConKey
, [LitTy (StrTyLit n),ty] <- tys
= maybeParen p FunPrec $
char '?' <> ftext n <> ptext (sLit "::") <> ppr_type TopPrec ty
| tc `hasKey` consDataConKey
, [_kind,ty1,ty2] <- tys
= sdocWithDynFlags $ \dflags ->
if gopt Opt_PrintExplicitKinds dflags then pprTcApp p ppr_type tc tys
else pprTyList p ty1 ty2
| otherwise
= pprTcApp p ppr_type tc tys
pprTcApp :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> SDoc
-- Used for both types and coercions, hence polymorphism
pprTcApp _ pp tc [ty]
| tc `hasKey` listTyConKey = pprPromotionQuote tc <> brackets (pp TopPrec ty)
| tc `hasKey` parrTyConKey = pprPromotionQuote tc <> paBrackets (pp TopPrec ty)
pprTcApp p pp tc tys
| Just sort <- tyConTuple_maybe tc
, tyConArity tc == length tys
= pprTupleApp p pp tc sort tys
| Just dc <- isPromotedDataCon_maybe tc
, let dc_tc = dataConTyCon dc
, Just tup_sort <- tyConTuple_maybe dc_tc
, let arity = tyConArity dc_tc -- E.g. 3 for (,,) k1 k2 k3 t1 t2 t3
ty_args = drop arity tys -- Drop the kind args
, ty_args `lengthIs` arity -- Result is saturated
= pprPromotionQuote tc <>
(tupleParens tup_sort $ pprWithCommas (pp TopPrec) ty_args)
| otherwise
= sdocWithDynFlags (pprTcApp_help p pp tc tys)
pprTupleApp :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> TupleSort -> [a] -> SDoc
-- Print a saturated tuple
pprTupleApp p pp tc sort tys
| null tys
, ConstraintTuple <- sort
= if opt_PprStyle_Debug then ptext (sLit "(%%)")
else maybeParen p FunPrec $
ptext (sLit "() :: Constraint")
| otherwise
= pprPromotionQuote tc <>
tupleParens sort (pprWithCommas (pp TopPrec) tys)
pprTcApp_help :: TyPrec -> (TyPrec -> a -> SDoc) -> TyCon -> [a] -> DynFlags -> SDoc
-- This one has accss to the DynFlags
pprTcApp_help p pp tc tys dflags
| not (isSymOcc (nameOccName (tyConName tc)))
= pprPrefixApp p (ppr tc) (map (pp TyConPrec) tys_wo_kinds)
| [ty1,ty2] <- tys_wo_kinds -- Infix, two arguments;
-- we know nothing of precedence though
= pprInfixApp p pp (ppr tc) ty1 ty2
| tc `hasKey` liftedTypeKindTyConKey
|| tc `hasKey` unliftedTypeKindTyConKey
= ASSERT( null tys ) ppr tc -- Do not wrap *, # in parens
| otherwise
= pprPrefixApp p (parens (ppr tc)) (map (pp TyConPrec) tys_wo_kinds)
where
tys_wo_kinds = suppressKinds dflags (tyConKind tc) tys
------------------
suppressKinds :: DynFlags -> Kind -> [a] -> [a]
-- Given the kind of a TyCon, and the args to which it is applied,
-- suppress the args that are kind args
-- C.f. Note [Suppressing kinds] in IfaceType
suppressKinds dflags kind xs
| gopt Opt_PrintExplicitKinds dflags = xs
| otherwise = suppress kind xs
where
suppress (ForAllTy _ kind) (_ : xs) = suppress kind xs
suppress (FunTy _ res) (x:xs) = x : suppress res xs
suppress _ xs = xs
----------------
pprTyList :: TyPrec -> Type -> Type -> SDoc
-- Given a type-level list (t1 ': t2), see if we can print
-- it in list notation [t1, ...].
pprTyList p ty1 ty2
= case gather ty2 of
(arg_tys, Nothing) -> char '\'' <> brackets (fsep (punctuate comma
(map (ppr_type TopPrec) (ty1:arg_tys))))
(arg_tys, Just tl) -> maybeParen p FunPrec $
hang (ppr_type FunPrec ty1)
2 (fsep [ colon <+> ppr_type FunPrec ty | ty <- arg_tys ++ [tl]])
where
gather :: Type -> ([Type], Maybe Type)
-- (gather ty) = (tys, Nothing) means ty is a list [t1, .., tn]
-- = (tys, Just tl) means ty is of form t1:t2:...tn:tl
gather (TyConApp tc tys)
| tc `hasKey` consDataConKey
, [_kind, ty1,ty2] <- tys
, (args, tl) <- gather ty2
= (ty1:args, tl)
| tc `hasKey` nilDataConKey
= ([], Nothing)
gather ty = ([], Just ty)
----------------
pprInfixApp :: TyPrec -> (TyPrec -> a -> SDoc) -> SDoc -> a -> a -> SDoc
pprInfixApp p pp pp_tc ty1 ty2
= maybeParen p TyOpPrec $
sep [pp TyOpPrec ty1, pprInfixVar True pp_tc <+> pp TyOpPrec ty2]
pprPrefixApp :: TyPrec -> SDoc -> [SDoc] -> SDoc
pprPrefixApp p pp_fun pp_tys
| null pp_tys = pp_fun
| otherwise = maybeParen p TyConPrec $
hang pp_fun 2 (sep pp_tys)
----------------
pprArrowChain :: TyPrec -> [SDoc] -> SDoc
-- pprArrowChain p [a,b,c] generates a -> b -> c
pprArrowChain _ [] = empty
pprArrowChain p (arg:args) = maybeParen p FunPrec $
sep [arg, sep (map (arrow <+>) args)]
{-
************************************************************************
* *
\subsection{TidyType}
* *
************************************************************************
Tidying is here because it has a special case for FlatSkol
-}
-- | This tidies up a type for printing in an error message, or in
-- an interface file.
--
-- It doesn't change the uniques at all, just the print names.
tidyTyVarBndrs :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyTyVarBndrs env tvs = mapAccumL tidyTyVarBndr env tvs
tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
tidyTyVarBndr tidy_env@(occ_env, subst) tyvar
= case tidyOccName occ_env occ1 of
(tidy', occ') -> ((tidy', subst'), tyvar')
where
subst' = extendVarEnv subst tyvar tyvar'
tyvar' = setTyVarKind (setTyVarName tyvar name') kind'
name' = tidyNameOcc name occ'
kind' = tidyKind tidy_env (tyVarKind tyvar)
where
name = tyVarName tyvar
occ = getOccName name
-- System Names are for unification variables;
-- when we tidy them we give them a trailing "0" (or 1 etc)
-- so that they don't take precedence for the un-modified name
-- Plus, indicating a unification variable in this way is a
-- helpful clue for users
occ1 | isSystemName name = mkTyVarOcc (occNameString occ ++ "0")
| otherwise = occ
---------------
tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
-- ^ Add the free 'TyVar's to the env in tidy form,
-- so that we can tidy the type they are free in
tidyFreeTyVars (full_occ_env, var_env) tyvars
= fst (tidyOpenTyVars (full_occ_env, var_env) (varSetElems tyvars))
---------------
tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
---------------
tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
-- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
-- using the environment if one has not already been allocated. See
-- also 'tidyTyVarBndr'
tidyOpenTyVar env@(_, subst) tyvar
= case lookupVarEnv subst tyvar of
Just tyvar' -> (env, tyvar') -- Already substituted
Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
---------------
tidyTyVarOcc :: TidyEnv -> TyVar -> TyVar
tidyTyVarOcc (_, subst) tv
= case lookupVarEnv subst tv of
Nothing -> tv
Just tv' -> tv'
---------------
tidyTypes :: TidyEnv -> [Type] -> [Type]
tidyTypes env tys = map (tidyType env) tys
---------------
tidyType :: TidyEnv -> Type -> Type
tidyType _ (LitTy n) = LitTy n
tidyType env (TyVarTy tv) = TyVarTy (tidyTyVarOcc env tv)
tidyType env (TyConApp tycon tys) = let args = tidyTypes env tys
in args `seqList` TyConApp tycon args
tidyType env (AppTy fun arg) = (AppTy $! (tidyType env fun)) $! (tidyType env arg)
tidyType env (FunTy fun arg) = (FunTy $! (tidyType env fun)) $! (tidyType env arg)
tidyType env (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
where
(envp, tvp) = tidyTyVarBndr env tv
---------------
-- | Grabs the free type variables, tidies them
-- and then uses 'tidyType' to work over the type itself
tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
tidyOpenType env ty
= (env', tidyType (trimmed_occ_env, var_env) ty)
where
(env'@(_, var_env), tvs') = tidyOpenTyVars env (varSetElems (tyVarsOfType ty))
trimmed_occ_env = initTidyOccEnv (map getOccName tvs')
-- The idea here was that we restrict the new TidyEnv to the
-- _free_ vars of the type, so that we don't gratuitously rename
-- the _bound_ variables of the type.
---------------
tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
---------------
-- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
tidyTopType :: Type -> Type
tidyTopType ty = tidyType emptyTidyEnv ty
---------------
tidyOpenKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
tidyOpenKind = tidyOpenType
tidyKind :: TidyEnv -> Kind -> Kind
tidyKind = tidyType
|
acowley/ghc
|
compiler/types/TypeRep.hs
|
bsd-3-clause
| 33,171 | 0 | 17 | 8,969 | 5,257 | 2,828 | 2,429 | 367 | 4 |
{-# OPTIONS -Wall #-}
-----------------------------------------------------------------------------
-- |
-- Module : Test.Environment
-- Copyright : (c) 2008 Duncan Coutts, Benedikt Huber
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides access to the environment variables used for testing, and provides
-- them in form of a TestConfig datum.
--
-- `envHelpDoc' says:
--
-- Influental environment variables:
-- CTEST_TMPDIR the temporary directory to write test reports to
-- CTEST_LOGFILE the log file [default = <stderr>]
-- CTEST_REPORT_FILE file to write test reports to [default = CTEST_TMPDIR/report.dat]
-- CTEST_DEBUG whether to print debug messages [default = False]
-- CTEST_KEEP_INTERMEDIATE whether to keep intermediate files [default = False]
-----------------------------------------------------------------------------
module Language.C.Test.Environment (
-- * Test Configurations
TestConfig(..),
envHelpDoc,
getEnvFlag,getEnvConfig,
-- * Process cpp arguments
isPreprocessedFile,MungeResult(..),mungeCcArgs,
)
where
import Control.Monad (liftM)
import Data.Char (toLower)
import Data.List (isPrefixOf, isSuffixOf)
import qualified Data.Map as Map
import System.IO
import System.Environment
import System.FilePath (combine)
import Text.PrettyPrint
-- | Takes a list of additional environment variable descriptions, and produces a document providing help
-- on the influental environment variables.
envHelpDoc :: [(String, (String, Maybe String ))] -> Doc
envHelpDoc addEnvHelp
= text "Influental environment variables:" $+$
(nest 4 . vcat . map varInfo) (envHelp ++ addEnvHelp)
where
varInfo (var, (descr, def)) = text var $$ nest 30 (prettyDescr descr def)
prettyDescr descr def = text descr <> prettyDef def
prettyDef Nothing = empty
prettyDef (Just def) = text $ " [default = " ++ def ++ "]"
envHelp :: [(String, (String, Maybe String))]
envHelp = [ vi tmpdirEnvVar "the temporary directory to write test reports to" Nothing,
vi logfileEnvVar "the log file" (Just "<stderr>"),
vi reportFileEnvVar "file to write test reports to" (Just (tmpdirEnvVar++"/report.dat")),
vi debugEnvVar "whether to print debug messages" (Just ("False")),
vi keepImEnvVar "whether to keep intermediate files" (Just ("False"))
]
where vi envVar varDescr varDef = (envVar, (varDescr, varDef))
data TestConfig = TestConfig
{
debug :: String -> IO (),
logger :: String -> IO (),
keepIntermediate :: Bool,
tmpDir :: FilePath
}
tmpdirEnvVar :: String
tmpdirEnvVar = "CTEST_TMPDIR"
logfileEnvVar :: String
logfileEnvVar = "CTEST_LOGFILE"
reportFileEnvVar :: String
reportFileEnvVar = "CTEST_REPORT_FILE"
debugEnvVar :: String
debugEnvVar = "CTEST_DEBUG"
keepImEnvVar :: String
keepImEnvVar = "CTEST_KEEP_INTERMEDIATE"
defaultReportFile :: String
defaultReportFile = "report.dat"
getEnvConfig :: IO (TestConfig, FilePath)
getEnvConfig = do
environ <- liftM Map.fromList getEnvironment
-- get log dir, result file and debug flag
tmpdir <- getEnv tmpdirEnvVar
let resultFile = maybe (combine tmpdir defaultReportFile) id $ Map.lookup reportFileEnvVar environ
let debugFlag = maybe False (const True) $ Map.lookup debugEnvVar environ
let keepIm = maybe False (const True) $ Map.lookup keepImEnvVar environ
let logFile = maybe Nothing Just $ Map.lookup logfileEnvVar environ
let config = TestConfig {
debug = debugAction debugFlag,
logger = logAction logFile,
tmpDir = tmpdir,
keepIntermediate = keepIm
}
return (config,resultFile)
where
debugAction False = \_ -> return ()
debugAction True = hPutStr stderr . ("[DEBUG] "++)
logAction Nothing = hPutStr stderr
logAction (Just logFile) = appendFile logFile
getEnvFlag :: String -> IO Bool
getEnvFlag envVar = do
envFlag <- getEnv envVar `catch` \_ -> return "0"
return $ case envFlag of
_ | envFlag == "" || envFlag == "0" || "f" `isPrefixOf` (map toLower envFlag) -> False
| otherwise -> True
isPreprocessedFile :: String -> Bool
isPreprocessedFile = (".i" `isSuffixOf`)
data MungeResult = Unknown String | Ignore | Groked [FilePath] [String]
mungeCcArgs :: [String] -> MungeResult
mungeCcArgs = mungeArgs [] []
mungeArgs :: [String] -> [String] -> [String] -> MungeResult
mungeArgs _accum [] [] = Unknown "No .c / .hc / .i source file given"
mungeArgs accum cfiles [] = Groked cfiles (reverse accum)
-- ignore preprocessing - only calls
mungeArgs _accum _cfiles ("-E":_) = Ignore
-- ignore make-rule creation
mungeArgs _accum _cfiles ("-M":_) = Ignore
-- strip outfile
mungeArgs accum cfiles ("-o":_outfile:args) = mungeArgs accum cfiles args
mungeArgs accum cfiles (cfile':args)
| ".c" `isSuffixOf` cfile'
|| ".hc" `isSuffixOf` cfile'
|| ".i" `isSuffixOf` cfile' =
mungeArgs accum (cfile':cfiles) args
mungeArgs _accum _cfiles (cfile':_)
| ".S" `isSuffixOf` cfile' = Ignore
mungeArgs accum cfiles (arg:args) = mungeArgs (arg:accum) cfiles args
|
jthornber/language-c-ejt
|
test-framework/Language/C/Test/Environment.hs
|
bsd-3-clause
| 5,373 | 0 | 18 | 1,197 | 1,279 | 694 | 585 | 89 | 3 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
-}
{-# LANGUAGE CPP #-}
module IfaceSyn (
module IfaceType,
IfaceDecl(..), IfaceFamTyConFlav(..), IfaceClassOp(..), IfaceAT(..),
IfaceConDecl(..), IfaceConDecls(..), IfaceEqSpec,
IfaceExpr(..), IfaceAlt, IfaceLetBndr(..),
IfaceBinding(..), IfaceConAlt(..),
IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..),
IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget,
IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..),
IfaceBang(..), IfaceAxBranch(..),
IfaceTyConParent(..),
-- Misc
ifaceDeclImplicitBndrs, visibleIfConDecls,
ifaceDeclFingerprints,
-- Free Names
freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst,
-- Pretty printing
pprIfaceExpr,
pprIfaceDecl,
ShowSub(..), ShowHowMuch(..)
) where
#include "HsVersions.h"
import IfaceType
import PprCore() -- Printing DFunArgs
import Demand
import Class
import NameSet
import CoAxiom ( BranchIndex, Role )
import Name
import CostCentre
import Literal
import ForeignCall
import Annotations( AnnPayload, AnnTarget )
import BasicTypes
import Outputable
import FastString
import Module
import SrcLoc
import Fingerprint
import Binary
import BooleanFormula ( BooleanFormula )
import HsBinds
import TyCon (Role (..))
import StaticFlags (opt_PprStyle_Debug)
import Util( filterOut )
import InstEnv
import Control.Monad
import System.IO.Unsafe
import Data.Maybe (isJust)
infixl 3 &&&
{-
************************************************************************
* *
Declarations
* *
************************************************************************
-}
type IfaceTopBndr = OccName
-- It's convenient to have an OccName in the IfaceSyn, altough in each
-- case the namespace is implied by the context. However, having an
-- OccNames makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints
-- very convenient.
--
-- We don't serialise the namespace onto the disk though; rather we
-- drop it when serialising and add it back in when deserialising.
data IfaceDecl
= IfaceId { ifName :: IfaceTopBndr,
ifType :: IfaceType,
ifIdDetails :: IfaceIdDetails,
ifIdInfo :: IfaceIdInfo }
| IfaceData { ifName :: IfaceTopBndr, -- Type constructor
ifCType :: Maybe CType, -- C type for CAPI FFI
ifTyVars :: [IfaceTvBndr], -- Type variables
ifRoles :: [Role], -- Roles
ifCtxt :: IfaceContext, -- The "stupid theta"
ifCons :: IfaceConDecls, -- Includes new/data/data family info
ifRec :: RecFlag, -- Recursive or not?
ifPromotable :: Bool, -- Promotable to kind level?
ifGadtSyntax :: Bool, -- True <=> declared using
-- GADT syntax
ifParent :: IfaceTyConParent -- The axiom, for a newtype,
-- or data/newtype family instance
}
| IfaceSynonym { ifName :: IfaceTopBndr, -- Type constructor
ifTyVars :: [IfaceTvBndr], -- Type variables
ifRoles :: [Role], -- Roles
ifSynKind :: IfaceKind, -- Kind of the *rhs* (not of
-- the tycon)
ifSynRhs :: IfaceType }
| IfaceFamily { ifName :: IfaceTopBndr, -- Type constructor
ifTyVars :: [IfaceTvBndr], -- Type variables
ifFamKind :: IfaceKind, -- Kind of the *rhs* (not of
-- the tycon)
ifFamFlav :: IfaceFamTyConFlav }
| IfaceClass { ifCtxt :: IfaceContext, -- Superclasses
ifName :: IfaceTopBndr, -- Name of the class TyCon
ifTyVars :: [IfaceTvBndr], -- Type variables
ifRoles :: [Role], -- Roles
ifFDs :: [FunDep FastString], -- Functional dependencies
ifATs :: [IfaceAT], -- Associated type families
ifSigs :: [IfaceClassOp], -- Method signatures
ifMinDef :: BooleanFormula IfLclName, -- Minimal complete definition
ifRec :: RecFlag -- Is newtype/datatype associated
-- with the class recursive?
}
| IfaceAxiom { ifName :: IfaceTopBndr, -- Axiom name
ifTyCon :: IfaceTyCon, -- LHS TyCon
ifRole :: Role, -- Role of axiom
ifAxBranches :: [IfaceAxBranch] -- Branches
}
| IfacePatSyn { ifName :: IfaceTopBndr, -- Name of the pattern synonym
ifPatIsInfix :: Bool,
ifPatMatcher :: (IfExtName, Bool),
ifPatBuilder :: Maybe (IfExtName, Bool),
-- Everything below is redundant,
-- but needed to implement pprIfaceDecl
ifPatUnivTvs :: [IfaceTvBndr],
ifPatExTvs :: [IfaceTvBndr],
ifPatProvCtxt :: IfaceContext,
ifPatReqCtxt :: IfaceContext,
ifPatArgs :: [IfaceType],
ifPatTy :: IfaceType }
data IfaceTyConParent
= IfNoParent
| IfDataInstance IfExtName
IfaceTyCon
IfaceTcArgs
data IfaceFamTyConFlav
= IfaceOpenSynFamilyTyCon
| IfaceClosedSynFamilyTyCon IfExtName -- name of associated axiom
[IfaceAxBranch] -- for pretty printing purposes only
| IfaceAbstractClosedSynFamilyTyCon
| IfaceBuiltInSynFamTyCon -- for pretty printing purposes only
data IfaceClassOp = IfaceClassOp IfaceTopBndr DefMethSpec IfaceType
-- Nothing => no default method
-- Just False => ordinary polymorphic default method
-- Just True => generic default method
data IfaceAT = IfaceAT -- See Class.ClassATItem
IfaceDecl -- The associated type declaration
(Maybe IfaceType) -- Default associated type instance, if any
-- This is just like CoAxBranch
data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars :: [IfaceTvBndr]
, ifaxbLHS :: IfaceTcArgs
, ifaxbRoles :: [Role]
, ifaxbRHS :: IfaceType
, ifaxbIncomps :: [BranchIndex] }
-- See Note [Storing compatibility] in CoAxiom
data IfaceConDecls
= IfAbstractTyCon Bool -- c.f TyCon.AbstractTyCon
| IfDataFamTyCon -- Data family
| IfDataTyCon [IfaceConDecl] -- Data type decls
| IfNewTyCon IfaceConDecl -- Newtype decls
data IfaceConDecl
= IfCon {
ifConOcc :: IfaceTopBndr, -- Constructor name
ifConWrapper :: Bool, -- True <=> has a wrapper
ifConInfix :: Bool, -- True <=> declared infix
-- The universal type variables are precisely those
-- of the type constructor of this data constructor
-- This is *easy* to guarantee when creating the IfCon
-- but it's not so easy for the original TyCon/DataCon
-- So this guarantee holds for IfaceConDecl, but *not* for DataCon
ifConExTvs :: [IfaceTvBndr], -- Existential tyvars
ifConEqSpec :: IfaceEqSpec, -- Equality constraints
ifConCtxt :: IfaceContext, -- Non-stupid context
ifConArgTys :: [IfaceType], -- Arg types
ifConFields :: [IfaceTopBndr], -- ...ditto... (field labels)
ifConStricts :: [IfaceBang]} -- Empty (meaning all lazy),
-- or 1-1 corresp with arg tys
type IfaceEqSpec = [(IfLclName,IfaceType)]
data IfaceBang -- This corresponds to an HsImplBang; that is, the final
-- implementation decision about the data constructor arg
= IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion
data IfaceClsInst
= IfaceClsInst { ifInstCls :: IfExtName, -- See comments with
ifInstTys :: [Maybe IfaceTyCon], -- the defn of ClsInst
ifDFun :: IfExtName, -- The dfun
ifOFlag :: OverlapFlag, -- Overlap flag
ifInstOrph :: IsOrphan } -- See Note [Orphans] in InstEnv
-- There's always a separate IfaceDecl for the DFun, which gives
-- its IdInfo with its full type and version number.
-- The instance declarations taken together have a version number,
-- and we don't want that to wobble gratuitously
-- If this instance decl is *used*, we'll record a usage on the dfun;
-- and if the head does not change it won't be used if it wasn't before
-- The ifFamInstTys field of IfaceFamInst contains a list of the rough
-- match types
data IfaceFamInst
= IfaceFamInst { ifFamInstFam :: IfExtName -- Family name
, ifFamInstTys :: [Maybe IfaceTyCon] -- See above
, ifFamInstAxiom :: IfExtName -- The axiom
, ifFamInstOrph :: IsOrphan -- Just like IfaceClsInst
}
data IfaceRule
= IfaceRule {
ifRuleName :: RuleName,
ifActivation :: Activation,
ifRuleBndrs :: [IfaceBndr], -- Tyvars and term vars
ifRuleHead :: IfExtName, -- Head of lhs
ifRuleArgs :: [IfaceExpr], -- Args of LHS
ifRuleRhs :: IfaceExpr,
ifRuleAuto :: Bool,
ifRuleOrph :: IsOrphan -- Just like IfaceClsInst
}
data IfaceAnnotation
= IfaceAnnotation {
ifAnnotatedTarget :: IfaceAnnTarget,
ifAnnotatedValue :: AnnPayload
}
type IfaceAnnTarget = AnnTarget OccName
-- Here's a tricky case:
-- * Compile with -O module A, and B which imports A.f
-- * Change function f in A, and recompile without -O
-- * When we read in old A.hi we read in its IdInfo (as a thunk)
-- (In earlier GHCs we used to drop IdInfo immediately on reading,
-- but we do not do that now. Instead it's discarded when the
-- ModIface is read into the various decl pools.)
-- * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *)
-- and so gives a new version.
data IfaceIdInfo
= NoInfo -- When writing interface file without -O
| HasInfo [IfaceInfoItem] -- Has info, and here it is
data IfaceInfoItem
= HsArity Arity
| HsStrictness StrictSig
| HsInline InlinePragma
| HsUnfold Bool -- True <=> isStrongLoopBreaker is true
IfaceUnfolding -- See Note [Expose recursive functions]
| HsNoCafRefs
-- NB: Specialisations and rules come in separately and are
-- only later attached to the Id. Partial reason: some are orphans.
data IfaceUnfolding
= IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding
-- Possibly could eliminate the Bool here, the information
-- is also in the InlinePragma.
| IfCompulsory IfaceExpr -- Only used for default methods, in fact
| IfInlineRule Arity -- INLINE pragmas
Bool -- OK to inline even if *un*-saturated
Bool -- OK to inline even if context is boring
IfaceExpr
| IfDFunUnfold [IfaceBndr] [IfaceExpr]
-- We only serialise the IdDetails of top-level Ids, and even then
-- we only need a very limited selection. Notably, none of the
-- implicit ones are needed here, because they are not put it
-- interface files
data IfaceIdDetails
= IfVanillaId
| IfRecSelId IfaceTyCon Bool
| IfDFunId
{-
Note [Versioning of instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See [http://ghc.haskell.org/trac/ghc/wiki/Commentary/Compiler/RecompilationAvoidance#Instances]
************************************************************************
* *
Functions over declarations
* *
************************************************************************
-}
visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl]
visibleIfConDecls (IfAbstractTyCon {}) = []
visibleIfConDecls IfDataFamTyCon = []
visibleIfConDecls (IfDataTyCon cs) = cs
visibleIfConDecls (IfNewTyCon c) = [c]
ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName]
-- *Excludes* the 'main' name, but *includes* the implicitly-bound names
-- Deeply revolting, because it has to predict what gets bound,
-- especially the question of whether there's a wrapper for a datacon
-- See Note [Implicit TyThings] in HscTypes
-- N.B. the set of names returned here *must* match the set of
-- TyThings returned by HscTypes.implicitTyThings, in the sense that
-- TyThing.getOccName should define a bijection between the two lists.
-- This invariant is used in LoadIface.loadDecl (see note [Tricky iface loop])
-- The order of the list does not matter.
ifaceDeclImplicitBndrs IfaceData {ifCons = IfAbstractTyCon {}} = []
-- Newtype
ifaceDeclImplicitBndrs (IfaceData {ifName = tc_occ,
ifCons = IfNewTyCon (
IfCon { ifConOcc = con_occ })})
= -- implicit newtype coercion
(mkNewTyCoOcc tc_occ) : -- JPM: newtype coercions shouldn't be implicit
-- data constructor and worker (newtypes don't have a wrapper)
[con_occ, mkDataConWorkerOcc con_occ]
ifaceDeclImplicitBndrs (IfaceData {ifName = _tc_occ,
ifCons = IfDataTyCon cons })
= -- for each data constructor in order,
-- data constructor, worker, and (possibly) wrapper
concatMap dc_occs cons
where
dc_occs con_decl
| has_wrapper = [con_occ, work_occ, wrap_occ]
| otherwise = [con_occ, work_occ]
where
con_occ = ifConOcc con_decl -- DataCon namespace
wrap_occ = mkDataConWrapperOcc con_occ -- Id namespace
work_occ = mkDataConWorkerOcc con_occ -- Id namespace
has_wrapper = ifConWrapper con_decl -- This is the reason for
-- having the ifConWrapper field!
ifaceDeclImplicitBndrs (IfaceClass {ifCtxt = sc_ctxt, ifName = cls_tc_occ,
ifSigs = sigs, ifATs = ats })
= -- (possibly) newtype coercion
co_occs ++
-- data constructor (DataCon namespace)
-- data worker (Id namespace)
-- no wrapper (class dictionaries never have a wrapper)
[dc_occ, dcww_occ] ++
-- associated types
[ifName at | IfaceAT at _ <- ats ] ++
-- superclass selectors
[mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++
-- operation selectors
[op | IfaceClassOp op _ _ <- sigs]
where
n_ctxt = length sc_ctxt
n_sigs = length sigs
co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ]
| otherwise = []
dcww_occ = mkDataConWorkerOcc dc_occ
dc_occ = mkClassDataConOcc cls_tc_occ
is_newtype = n_sigs + n_ctxt == 1 -- Sigh
ifaceDeclImplicitBndrs _ = []
-- -----------------------------------------------------------------------------
-- The fingerprints of an IfaceDecl
-- We better give each name bound by the declaration a
-- different fingerprint! So we calculate the fingerprint of
-- each binder by combining the fingerprint of the whole
-- declaration with the name of the binder. (#5614, #7215)
ifaceDeclFingerprints :: Fingerprint -> IfaceDecl -> [(OccName,Fingerprint)]
ifaceDeclFingerprints hash decl
= (ifName decl, hash) :
[ (occ, computeFingerprint' (hash,occ))
| occ <- ifaceDeclImplicitBndrs decl ]
where
computeFingerprint' =
unsafeDupablePerformIO
. computeFingerprint (panic "ifaceDeclFingerprints")
{-
************************************************************************
* *
Expressions
* *
************************************************************************
-}
data IfaceExpr
= IfaceLcl IfLclName
| IfaceExt IfExtName
| IfaceType IfaceType
| IfaceCo IfaceCoercion
| IfaceTuple TupleSort [IfaceExpr] -- Saturated; type arguments omitted
| IfaceLam IfaceLamBndr IfaceExpr
| IfaceApp IfaceExpr IfaceExpr
| IfaceCase IfaceExpr IfLclName [IfaceAlt]
| IfaceECase IfaceExpr IfaceType -- See Note [Empty case alternatives]
| IfaceLet IfaceBinding IfaceExpr
| IfaceCast IfaceExpr IfaceCoercion
| IfaceLit Literal
| IfaceFCall ForeignCall IfaceType
| IfaceTick IfaceTickish IfaceExpr -- from Tick tickish E
data IfaceTickish
= IfaceHpcTick Module Int -- from HpcTick x
| IfaceSCC CostCentre Bool Bool -- from ProfNote
| IfaceSource RealSrcSpan String -- from SourceNote
-- no breakpoints: we never export these into interface files
type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr)
-- Note: IfLclName, not IfaceBndr (and same with the case binder)
-- We reconstruct the kind/type of the thing from the context
-- thus saving bulk in interface files
data IfaceConAlt = IfaceDefault
| IfaceDataAlt IfExtName
| IfaceLitAlt Literal
data IfaceBinding
= IfaceNonRec IfaceLetBndr IfaceExpr
| IfaceRec [(IfaceLetBndr, IfaceExpr)]
-- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too
-- It's used for *non-top-level* let/rec binders
-- See Note [IdInfo on nested let-bindings]
data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo
{-
Note [Empty case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In IfaceSyn an IfaceCase does not record the types of the alternatives,
unlike CorSyn Case. But we need this type if the alternatives are empty.
Hence IfaceECase. See Note [Empty case alternatives] in CoreSyn.
Note [Expose recursive functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For supercompilation we want to put *all* unfoldings in the interface
file, even for functions that are recursive (or big). So we need to
know when an unfolding belongs to a loop-breaker so that we can refrain
from inlining it (except during supercompilation).
Note [IdInfo on nested let-bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Occasionally we want to preserve IdInfo on nested let bindings. The one
that came up was a NOINLINE pragma on a let-binding inside an INLINE
function. The user (Duncan Coutts) really wanted the NOINLINE control
to cross the separate compilation boundary.
In general we retain all info that is left by CoreTidy.tidyLetBndr, since
that is what is seen by importing module with --make
************************************************************************
* *
Printing IfaceDecl
* *
************************************************************************
-}
pprAxBranch :: SDoc -> IfaceAxBranch -> SDoc
-- The TyCon might be local (just an OccName), or this might
-- be a branch for an imported TyCon, so it would be an ExtName
-- So it's easier to take an SDoc here
pprAxBranch pp_tc (IfaceAxBranch { ifaxbTyVars = tvs
, ifaxbLHS = pat_tys
, ifaxbRHS = rhs
, ifaxbIncomps = incomps })
= hang (pprUserIfaceForAll tvs)
2 (hang pp_lhs 2 (equals <+> ppr rhs))
$+$
nest 2 maybe_incomps
where
pp_lhs = hang pp_tc 2 (pprParendIfaceTcArgs pat_tys)
maybe_incomps = ppUnless (null incomps) $ parens $
ptext (sLit "incompatible indices:") <+> ppr incomps
instance Outputable IfaceAnnotation where
ppr (IfaceAnnotation target value) = ppr target <+> colon <+> ppr value
instance HasOccName IfaceClassOp where
occName (IfaceClassOp n _ _) = n
instance HasOccName IfaceConDecl where
occName = ifConOcc
instance HasOccName IfaceDecl where
occName = ifName
instance Outputable IfaceDecl where
ppr = pprIfaceDecl showAll
data ShowSub
= ShowSub
{ ss_ppr_bndr :: OccName -> SDoc -- Pretty-printer for binders in IfaceDecl
-- See Note [Printing IfaceDecl binders]
, ss_how_much :: ShowHowMuch }
data ShowHowMuch
= ShowHeader -- Header information only, not rhs
| ShowSome [OccName] -- [] <=> Print all sub-components
-- (n:ns) <=> print sub-component 'n' with ShowSub=ns
-- elide other sub-components to "..."
-- May 14: the list is max 1 element long at the moment
| ShowIface -- Everything including GHC-internal information (used in --show-iface)
showAll :: ShowSub
showAll = ShowSub { ss_how_much = ShowIface, ss_ppr_bndr = ppr }
ppShowIface :: ShowSub -> SDoc -> SDoc
ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc
ppShowIface _ _ = Outputable.empty
ppShowRhs :: ShowSub -> SDoc -> SDoc
ppShowRhs (ShowSub { ss_how_much = ShowHeader }) _ = Outputable.empty
ppShowRhs _ doc = doc
showSub :: HasOccName n => ShowSub -> n -> Bool
showSub (ShowSub { ss_how_much = ShowHeader }) _ = False
showSub (ShowSub { ss_how_much = ShowSome (n:_) }) thing = n == occName thing
showSub (ShowSub { ss_how_much = _ }) _ = True
{-
Note [Printing IfaceDecl binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The binders in an IfaceDecl are just OccNames, so we don't know what module they
come from. But when we pretty-print a TyThing by converting to an IfaceDecl
(see PprTyThing), the TyThing may come from some other module so we really need
the module qualifier. We solve this by passing in a pretty-printer for the
binders.
When printing an interface file (--show-iface), we want to print
everything unqualified, so we can just print the OccName directly.
-}
ppr_trim :: [Maybe SDoc] -> [SDoc]
-- Collapse a group of Nothings to a single "..."
ppr_trim xs
= snd (foldr go (False, []) xs)
where
go (Just doc) (_, so_far) = (False, doc : so_far)
go Nothing (True, so_far) = (True, so_far)
go Nothing (False, so_far) = (True, ptext (sLit "...") : so_far)
isIfaceDataInstance :: IfaceTyConParent -> Bool
isIfaceDataInstance IfNoParent = False
isIfaceDataInstance _ = True
pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc
-- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi
-- See Note [Pretty-printing TyThings] in PprTyThing
pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype,
ifCtxt = context, ifTyVars = tc_tyvars,
ifRoles = roles, ifCons = condecls,
ifParent = parent, ifRec = isrec,
ifGadtSyntax = gadt,
ifPromotable = is_prom })
| gadt_style = vcat [ pp_roles
, pp_nd <+> pp_lhs <+> pp_where
, nest 2 (vcat pp_cons)
, nest 2 $ ppShowIface ss pp_extra ]
| otherwise = vcat [ pp_roles
, hang (pp_nd <+> pp_lhs) 2 (add_bars pp_cons)
, nest 2 $ ppShowIface ss pp_extra ]
where
is_data_instance = isIfaceDataInstance parent
gadt_style = gadt || any (not . isVanillaIfaceConDecl) cons
cons = visibleIfConDecls condecls
pp_where = ppWhen (gadt_style && not (null cons)) $ ptext (sLit "where")
pp_cons = ppr_trim (map show_con cons) :: [SDoc]
pp_lhs = case parent of
IfNoParent -> pprIfaceDeclHead context ss tycon tc_tyvars
_ -> ptext (sLit "instance") <+> pprIfaceTyConParent parent
pp_roles
| is_data_instance = Outputable.empty
| otherwise = pprRoles (== Representational) (pprPrefixIfDeclBndr ss tycon)
tc_tyvars roles
-- Don't display roles for data family instances (yet)
-- See discussion on Trac #8672.
add_bars [] = Outputable.empty
add_bars (c:cs) = sep ((equals <+> c) : map (char '|' <+>) cs)
ok_con dc = showSub ss dc || any (showSub ss) (ifConFields dc)
show_con dc
| ok_con dc = Just $ pprIfaceConDecl ss gadt_style mk_user_con_res_ty dc
| otherwise = Nothing
mk_user_con_res_ty :: IfaceEqSpec -> ([IfaceTvBndr], SDoc)
-- See Note [Result type of a data family GADT]
mk_user_con_res_ty eq_spec
| IfDataInstance _ tc tys <- parent
= (con_univ_tvs, pprIfaceType (IfaceTyConApp tc (substIfaceTcArgs gadt_subst tys)))
| otherwise
= (con_univ_tvs, sdocWithDynFlags (ppr_tc_app gadt_subst))
where
gadt_subst = mkFsEnv eq_spec
done_univ_tv (tv,_) = isJust (lookupFsEnv gadt_subst tv)
con_univ_tvs = filterOut done_univ_tv tc_tyvars
ppr_tc_app gadt_subst dflags
= pprPrefixIfDeclBndr ss tycon
<+> sep [ pprParendIfaceType (substIfaceTyVar gadt_subst tv)
| (tv,_kind) <- stripIfaceKindVars dflags tc_tyvars ]
pp_nd = case condecls of
IfAbstractTyCon d -> ptext (sLit "abstract") <> ppShowIface ss (parens (ppr d))
IfDataFamTyCon -> ptext (sLit "data family")
IfDataTyCon _ -> ptext (sLit "data")
IfNewTyCon _ -> ptext (sLit "newtype")
pp_extra = vcat [pprCType ctype, pprRec isrec, pp_prom]
pp_prom | is_prom = ptext (sLit "Promotable")
| otherwise = Outputable.empty
pprIfaceDecl ss (IfaceClass { ifATs = ats, ifSigs = sigs, ifRec = isrec
, ifCtxt = context, ifName = clas
, ifTyVars = tyvars, ifRoles = roles
, ifFDs = fds })
= vcat [ pprRoles (== Nominal) (pprPrefixIfDeclBndr ss clas) tyvars roles
, ptext (sLit "class") <+> pprIfaceDeclHead context ss clas tyvars
<+> pprFundeps fds <+> pp_where
, nest 2 (vcat [vcat asocs, vcat dsigs, pprec])]
where
pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (ptext (sLit "where"))
asocs = ppr_trim $ map maybeShowAssoc ats
dsigs = ppr_trim $ map maybeShowSig sigs
pprec = ppShowIface ss (pprRec isrec)
maybeShowAssoc :: IfaceAT -> Maybe SDoc
maybeShowAssoc asc@(IfaceAT d _)
| showSub ss d = Just $ pprIfaceAT ss asc
| otherwise = Nothing
maybeShowSig :: IfaceClassOp -> Maybe SDoc
maybeShowSig sg
| showSub ss sg = Just $ pprIfaceClassOp ss sg
| otherwise = Nothing
pprIfaceDecl ss (IfaceSynonym { ifName = tc
, ifTyVars = tv
, ifSynRhs = mono_ty })
= hang (ptext (sLit "type") <+> pprIfaceDeclHead [] ss tc tv <+> equals)
2 (sep [pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau])
where
(tvs, theta, tau) = splitIfaceSigmaTy mono_ty
pprIfaceDecl ss (IfaceFamily { ifName = tycon, ifTyVars = tyvars
, ifFamFlav = rhs, ifFamKind = kind })
= vcat [ hang (text "type family" <+> pprIfaceDeclHead [] ss tycon tyvars <+> dcolon)
2 (ppr kind <+> ppShowRhs ss (pp_rhs rhs))
, ppShowRhs ss (nest 2 (pp_branches rhs)) ]
where
pp_rhs IfaceOpenSynFamilyTyCon = ppShowIface ss (ptext (sLit "open"))
pp_rhs IfaceAbstractClosedSynFamilyTyCon = ppShowIface ss (ptext (sLit "closed, abstract"))
pp_rhs (IfaceClosedSynFamilyTyCon _ (_:_)) = ptext (sLit "where")
pp_rhs IfaceBuiltInSynFamTyCon = ppShowIface ss (ptext (sLit "built-in"))
pp_rhs _ = panic "pprIfaceDecl syn"
pp_branches (IfaceClosedSynFamilyTyCon ax brs)
= vcat (map (pprAxBranch (pprPrefixIfDeclBndr ss tycon)) brs)
$$ ppShowIface ss (ptext (sLit "axiom") <+> ppr ax)
pp_branches _ = Outputable.empty
pprIfaceDecl _ (IfacePatSyn { ifName = name, ifPatBuilder = builder,
ifPatUnivTvs = univ_tvs, ifPatExTvs = ex_tvs,
ifPatProvCtxt = prov_ctxt, ifPatReqCtxt = req_ctxt,
ifPatArgs = arg_tys,
ifPatTy = pat_ty} )
= pprPatSynSig name is_bidirectional
(pprUserIfaceForAll tvs)
(pprIfaceContextMaybe prov_ctxt)
(pprIfaceContextMaybe req_ctxt)
(pprIfaceType ty)
where
is_bidirectional = isJust builder
tvs = univ_tvs ++ ex_tvs
ty = foldr IfaceFunTy pat_ty arg_tys
pprIfaceDecl ss (IfaceId { ifName = var, ifType = ty,
ifIdDetails = details, ifIdInfo = info })
= vcat [ hang (pprPrefixIfDeclBndr ss var <+> dcolon)
2 (pprIfaceSigmaType ty)
, ppShowIface ss (ppr details)
, ppShowIface ss (ppr info) ]
pprIfaceDecl _ (IfaceAxiom { ifName = name, ifTyCon = tycon
, ifAxBranches = branches })
= hang (ptext (sLit "axiom") <+> ppr name <> dcolon)
2 (vcat $ map (pprAxBranch (ppr tycon)) branches)
pprCType :: Maybe CType -> SDoc
pprCType Nothing = Outputable.empty
pprCType (Just cType) = ptext (sLit "C type:") <+> ppr cType
-- if, for each role, suppress_if role is True, then suppress the role
-- output
pprRoles :: (Role -> Bool) -> SDoc -> [IfaceTvBndr] -> [Role] -> SDoc
pprRoles suppress_if tyCon tyvars roles
= sdocWithDynFlags $ \dflags ->
let froles = suppressIfaceKinds dflags tyvars roles
in ppUnless (all suppress_if roles || null froles) $
ptext (sLit "type role") <+> tyCon <+> hsep (map ppr froles)
pprRec :: RecFlag -> SDoc
pprRec NonRecursive = Outputable.empty
pprRec Recursive = ptext (sLit "RecFlag: Recursive")
pprInfixIfDeclBndr, pprPrefixIfDeclBndr :: ShowSub -> OccName -> SDoc
pprInfixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ
= pprInfixVar (isSymOcc occ) (ppr_bndr occ)
pprPrefixIfDeclBndr (ShowSub { ss_ppr_bndr = ppr_bndr }) occ
= parenSymOcc occ (ppr_bndr occ)
instance Outputable IfaceClassOp where
ppr = pprIfaceClassOp showAll
pprIfaceClassOp :: ShowSub -> IfaceClassOp -> SDoc
pprIfaceClassOp ss (IfaceClassOp n dm ty) = hang opHdr 2 (pprIfaceSigmaType ty)
where opHdr = pprPrefixIfDeclBndr ss n
<+> ppShowIface ss (ppr dm) <+> dcolon
instance Outputable IfaceAT where
ppr = pprIfaceAT showAll
pprIfaceAT :: ShowSub -> IfaceAT -> SDoc
pprIfaceAT ss (IfaceAT d mb_def)
= vcat [ pprIfaceDecl ss d
, case mb_def of
Nothing -> Outputable.empty
Just rhs -> nest 2 $
ptext (sLit "Default:") <+> ppr rhs ]
instance Outputable IfaceTyConParent where
ppr p = pprIfaceTyConParent p
pprIfaceTyConParent :: IfaceTyConParent -> SDoc
pprIfaceTyConParent IfNoParent
= Outputable.empty
pprIfaceTyConParent (IfDataInstance _ tc tys)
= sdocWithDynFlags $ \dflags ->
let ftys = stripKindArgs dflags tys
in pprIfaceTypeApp tc ftys
pprIfaceDeclHead :: IfaceContext -> ShowSub -> OccName -> [IfaceTvBndr] -> SDoc
pprIfaceDeclHead context ss tc_occ tv_bndrs
= sdocWithDynFlags $ \ dflags ->
sep [ pprIfaceContextArr context
, pprPrefixIfDeclBndr ss tc_occ
<+> pprIfaceTvBndrs (stripIfaceKindVars dflags tv_bndrs) ]
isVanillaIfaceConDecl :: IfaceConDecl -> Bool
isVanillaIfaceConDecl (IfCon { ifConExTvs = ex_tvs
, ifConEqSpec = eq_spec
, ifConCtxt = ctxt })
= (null ex_tvs) && (null eq_spec) && (null ctxt)
pprIfaceConDecl :: ShowSub -> Bool
-> (IfaceEqSpec -> ([IfaceTvBndr], SDoc))
-> IfaceConDecl -> SDoc
pprIfaceConDecl ss gadt_style mk_user_con_res_ty
(IfCon { ifConOcc = name, ifConInfix = is_infix,
ifConExTvs = ex_tvs,
ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys,
ifConStricts = stricts, ifConFields = labels })
| gadt_style = pp_prefix_con <+> dcolon <+> ppr_ty
| otherwise = ppr_fields tys_w_strs
where
tys_w_strs :: [(IfaceBang, IfaceType)]
tys_w_strs = zip stricts arg_tys
pp_prefix_con = pprPrefixIfDeclBndr ss name
(univ_tvs, pp_res_ty) = mk_user_con_res_ty eq_spec
ppr_ty = pprIfaceForAllPart (univ_tvs ++ ex_tvs) ctxt pp_tau
-- A bit gruesome this, but we can't form the full con_tau, and ppr it,
-- because we don't have a Name for the tycon, only an OccName
pp_tau = case map pprParendIfaceType arg_tys ++ [pp_res_ty] of
(t:ts) -> fsep (t : map (arrow <+>) ts)
[] -> panic "pp_con_taus"
ppr_bang IfNoBang = ppWhen opt_PprStyle_Debug $ char '_'
ppr_bang IfStrict = char '!'
ppr_bang IfUnpack = ptext (sLit "{-# UNPACK #-}")
ppr_bang (IfUnpackCo co) = ptext (sLit "! {-# UNPACK #-}") <>
pprParendIfaceCoercion co
pprParendBangTy (bang, ty) = ppr_bang bang <> pprParendIfaceType ty
pprBangTy (bang, ty) = ppr_bang bang <> ppr ty
maybe_show_label (lbl,bty)
| showSub ss lbl = Just (pprPrefixIfDeclBndr ss lbl <+> dcolon <+> pprBangTy bty)
| otherwise = Nothing
ppr_fields [ty1, ty2]
| is_infix && null labels
= sep [pprParendBangTy ty1, pprInfixIfDeclBndr ss name, pprParendBangTy ty2]
ppr_fields fields
| null labels = pp_prefix_con <+> sep (map pprParendBangTy fields)
| otherwise = pp_prefix_con <+> (braces $ sep $ punctuate comma $ ppr_trim $
map maybe_show_label (zip labels fields))
instance Outputable IfaceRule where
ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs })
= sep [hsep [doubleQuotes (ftext name), ppr act,
ptext (sLit "forall") <+> pprIfaceBndrs bndrs],
nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args),
ptext (sLit "=") <+> ppr rhs])
]
instance Outputable IfaceClsInst where
ppr (IfaceClsInst { ifDFun = dfun_id, ifOFlag = flag
, ifInstCls = cls, ifInstTys = mb_tcs})
= hang (ptext (sLit "instance") <+> ppr flag
<+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs))
2 (equals <+> ppr dfun_id)
instance Outputable IfaceFamInst where
ppr (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
, ifFamInstAxiom = tycon_ax})
= hang (ptext (sLit "family instance") <+>
ppr fam <+> pprWithCommas (brackets . ppr_rough) mb_tcs)
2 (equals <+> ppr tycon_ax)
ppr_rough :: Maybe IfaceTyCon -> SDoc
ppr_rough Nothing = dot
ppr_rough (Just tc) = ppr tc
{-
Note [Result type of a data family GADT]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data family T a
data instance T (p,q) where
T1 :: T (Int, Maybe c)
T2 :: T (Bool, q)
The IfaceDecl actually looks like
data TPr p q where
T1 :: forall p q. forall c. (p~Int,q~Maybe c) => TPr p q
T2 :: forall p q. (p~Bool) => TPr p q
To reconstruct the result types for T1 and T2 that we
want to pretty print, we substitute the eq-spec
[p->Int, q->Maybe c] in the arg pattern (p,q) to give
T (Int, Maybe c)
Remember that in IfaceSyn, the TyCon and DataCon share the same
universal type variables.
----------------------------- Printing IfaceExpr ------------------------------------
-}
instance Outputable IfaceExpr where
ppr e = pprIfaceExpr noParens e
noParens :: SDoc -> SDoc
noParens pp = pp
pprParendIfaceExpr :: IfaceExpr -> SDoc
pprParendIfaceExpr = pprIfaceExpr parens
-- | Pretty Print an IfaceExpre
--
-- The first argument should be a function that adds parens in context that need
-- an atomic value (e.g. function args)
pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc
pprIfaceExpr _ (IfaceLcl v) = ppr v
pprIfaceExpr _ (IfaceExt v) = ppr v
pprIfaceExpr _ (IfaceLit l) = ppr l
pprIfaceExpr _ (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty)
pprIfaceExpr _ (IfaceType ty) = char '@' <+> pprParendIfaceType ty
pprIfaceExpr _ (IfaceCo co) = text "@~" <+> pprParendIfaceCoercion co
pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app [])
pprIfaceExpr _ (IfaceTuple c as) = tupleParens c (interpp'SP as)
pprIfaceExpr add_par i@(IfaceLam _ _)
= add_par (sep [char '\\' <+> sep (map pprIfaceLamBndr bndrs) <+> arrow,
pprIfaceExpr noParens body])
where
(bndrs,body) = collect [] i
collect bs (IfaceLam b e) = collect (b:bs) e
collect bs e = (reverse bs, e)
pprIfaceExpr add_par (IfaceECase scrut ty)
= add_par (sep [ ptext (sLit "case") <+> pprIfaceExpr noParens scrut
, ptext (sLit "ret_ty") <+> pprParendIfaceType ty
, ptext (sLit "of {}") ])
pprIfaceExpr add_par (IfaceCase scrut bndr [(con, bs, rhs)])
= add_par (sep [ptext (sLit "case")
<+> pprIfaceExpr noParens scrut <+> ptext (sLit "of")
<+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow,
pprIfaceExpr noParens rhs <+> char '}'])
pprIfaceExpr add_par (IfaceCase scrut bndr alts)
= add_par (sep [ptext (sLit "case")
<+> pprIfaceExpr noParens scrut <+> ptext (sLit "of")
<+> ppr bndr <+> char '{',
nest 2 (sep (map ppr_alt alts)) <+> char '}'])
pprIfaceExpr _ (IfaceCast expr co)
= sep [pprParendIfaceExpr expr,
nest 2 (ptext (sLit "`cast`")),
pprParendIfaceCoercion co]
pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body)
= add_par (sep [ptext (sLit "let {"),
nest 2 (ppr_bind (b, rhs)),
ptext (sLit "} in"),
pprIfaceExpr noParens body])
pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body)
= add_par (sep [ptext (sLit "letrec {"),
nest 2 (sep (map ppr_bind pairs)),
ptext (sLit "} in"),
pprIfaceExpr noParens body])
pprIfaceExpr add_par (IfaceTick tickish e)
= add_par (pprIfaceTickish tickish <+> pprIfaceExpr noParens e)
ppr_alt :: (IfaceConAlt, [IfLclName], IfaceExpr) -> SDoc
ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs,
arrow <+> pprIfaceExpr noParens rhs]
ppr_con_bs :: IfaceConAlt -> [IfLclName] -> SDoc
ppr_con_bs con bs = ppr con <+> hsep (map ppr bs)
ppr_bind :: (IfaceLetBndr, IfaceExpr) -> SDoc
ppr_bind (IfLetBndr b ty info, rhs)
= sep [hang (ppr b <+> dcolon <+> ppr ty) 2 (ppr info),
equals <+> pprIfaceExpr noParens rhs]
------------------
pprIfaceTickish :: IfaceTickish -> SDoc
pprIfaceTickish (IfaceHpcTick m ix)
= braces (text "tick" <+> ppr m <+> ppr ix)
pprIfaceTickish (IfaceSCC cc tick scope)
= braces (pprCostCentreCore cc <+> ppr tick <+> ppr scope)
pprIfaceTickish (IfaceSource src _names)
= braces (pprUserRealSpan True src)
------------------
pprIfaceApp :: IfaceExpr -> [SDoc] -> SDoc
pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun $
nest 2 (pprParendIfaceExpr arg) : args
pprIfaceApp fun args = sep (pprParendIfaceExpr fun : args)
------------------
instance Outputable IfaceConAlt where
ppr IfaceDefault = text "DEFAULT"
ppr (IfaceLitAlt l) = ppr l
ppr (IfaceDataAlt d) = ppr d
------------------
instance Outputable IfaceIdDetails where
ppr IfVanillaId = Outputable.empty
ppr (IfRecSelId tc b) = ptext (sLit "RecSel") <+> ppr tc
<+> if b
then ptext (sLit "<naughty>")
else Outputable.empty
ppr IfDFunId = ptext (sLit "DFunId")
instance Outputable IfaceIdInfo where
ppr NoInfo = Outputable.empty
ppr (HasInfo is) = ptext (sLit "{-") <+> pprWithCommas ppr is
<+> ptext (sLit "-}")
instance Outputable IfaceInfoItem where
ppr (HsUnfold lb unf) = ptext (sLit "Unfolding")
<> ppWhen lb (ptext (sLit "(loop-breaker)"))
<> colon <+> ppr unf
ppr (HsInline prag) = ptext (sLit "Inline:") <+> ppr prag
ppr (HsArity arity) = ptext (sLit "Arity:") <+> int arity
ppr (HsStrictness str) = ptext (sLit "Strictness:") <+> pprIfaceStrictSig str
ppr HsNoCafRefs = ptext (sLit "HasNoCafRefs")
instance Outputable IfaceUnfolding where
ppr (IfCompulsory e) = ptext (sLit "<compulsory>") <+> parens (ppr e)
ppr (IfCoreUnfold s e) = (if s
then ptext (sLit "<stable>")
else Outputable.empty)
<+> parens (ppr e)
ppr (IfInlineRule a uok bok e) = sep [ptext (sLit "InlineRule")
<+> ppr (a,uok,bok),
pprParendIfaceExpr e]
ppr (IfDFunUnfold bs es) = hang (ptext (sLit "DFun:") <+> sep (map ppr bs) <> dot)
2 (sep (map pprParendIfaceExpr es))
{-
************************************************************************
* *
Finding the Names in IfaceSyn
* *
************************************************************************
This is used for dependency analysis in MkIface, so that we
fingerprint a declaration before the things that depend on it. It
is specific to interface-file fingerprinting in the sense that we
don't collect *all* Names: for example, the DFun of an instance is
recorded textually rather than by its fingerprint when
fingerprinting the instance, so DFuns are not dependencies.
-}
freeNamesIfDecl :: IfaceDecl -> NameSet
freeNamesIfDecl (IfaceId _s t d i) =
freeNamesIfType t &&&
freeNamesIfIdInfo i &&&
freeNamesIfIdDetails d
freeNamesIfDecl d@IfaceData{} =
freeNamesIfTvBndrs (ifTyVars d) &&&
freeNamesIfaceTyConParent (ifParent d) &&&
freeNamesIfContext (ifCtxt d) &&&
freeNamesIfConDecls (ifCons d)
freeNamesIfDecl d@IfaceSynonym{} =
freeNamesIfTvBndrs (ifTyVars d) &&&
freeNamesIfType (ifSynRhs d) &&&
freeNamesIfKind (ifSynKind d) -- IA0_NOTE: because of promotion, we
-- return names in the kind signature
freeNamesIfDecl d@IfaceFamily{} =
freeNamesIfTvBndrs (ifTyVars d) &&&
freeNamesIfFamFlav (ifFamFlav d) &&&
freeNamesIfKind (ifFamKind d) -- IA0_NOTE: because of promotion, we
-- return names in the kind signature
freeNamesIfDecl d@IfaceClass{} =
freeNamesIfTvBndrs (ifTyVars d) &&&
freeNamesIfContext (ifCtxt d) &&&
fnList freeNamesIfAT (ifATs d) &&&
fnList freeNamesIfClsSig (ifSigs d)
freeNamesIfDecl d@IfaceAxiom{} =
freeNamesIfTc (ifTyCon d) &&&
fnList freeNamesIfAxBranch (ifAxBranches d)
freeNamesIfDecl d@IfacePatSyn{} =
unitNameSet (fst (ifPatMatcher d)) &&&
maybe emptyNameSet (unitNameSet . fst) (ifPatBuilder d) &&&
freeNamesIfTvBndrs (ifPatUnivTvs d) &&&
freeNamesIfTvBndrs (ifPatExTvs d) &&&
freeNamesIfContext (ifPatProvCtxt d) &&&
freeNamesIfContext (ifPatReqCtxt d) &&&
fnList freeNamesIfType (ifPatArgs d) &&&
freeNamesIfType (ifPatTy d)
freeNamesIfAxBranch :: IfaceAxBranch -> NameSet
freeNamesIfAxBranch (IfaceAxBranch { ifaxbTyVars = tyvars
, ifaxbLHS = lhs
, ifaxbRHS = rhs }) =
freeNamesIfTvBndrs tyvars &&&
freeNamesIfTcArgs lhs &&&
freeNamesIfType rhs
freeNamesIfIdDetails :: IfaceIdDetails -> NameSet
freeNamesIfIdDetails (IfRecSelId tc _) = freeNamesIfTc tc
freeNamesIfIdDetails _ = emptyNameSet
-- All other changes are handled via the version info on the tycon
freeNamesIfFamFlav :: IfaceFamTyConFlav -> NameSet
freeNamesIfFamFlav IfaceOpenSynFamilyTyCon = emptyNameSet
freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon ax br)
= unitNameSet ax &&& fnList freeNamesIfAxBranch br
freeNamesIfFamFlav IfaceAbstractClosedSynFamilyTyCon = emptyNameSet
freeNamesIfFamFlav IfaceBuiltInSynFamTyCon = emptyNameSet
freeNamesIfContext :: IfaceContext -> NameSet
freeNamesIfContext = fnList freeNamesIfType
freeNamesIfAT :: IfaceAT -> NameSet
freeNamesIfAT (IfaceAT decl mb_def)
= freeNamesIfDecl decl &&&
case mb_def of
Nothing -> emptyNameSet
Just rhs -> freeNamesIfType rhs
freeNamesIfClsSig :: IfaceClassOp -> NameSet
freeNamesIfClsSig (IfaceClassOp _n _dm ty) = freeNamesIfType ty
freeNamesIfConDecls :: IfaceConDecls -> NameSet
freeNamesIfConDecls (IfDataTyCon c) = fnList freeNamesIfConDecl c
freeNamesIfConDecls (IfNewTyCon c) = freeNamesIfConDecl c
freeNamesIfConDecls _ = emptyNameSet
freeNamesIfConDecl :: IfaceConDecl -> NameSet
freeNamesIfConDecl c
= freeNamesIfTvBndrs (ifConExTvs c) &&&
freeNamesIfContext (ifConCtxt c) &&&
fnList freeNamesIfType (ifConArgTys c) &&&
fnList freeNamesIfType (map snd (ifConEqSpec c)) -- equality constraints
freeNamesIfKind :: IfaceType -> NameSet
freeNamesIfKind = freeNamesIfType
freeNamesIfTcArgs :: IfaceTcArgs -> NameSet
freeNamesIfTcArgs (ITC_Type t ts) = freeNamesIfType t &&& freeNamesIfTcArgs ts
freeNamesIfTcArgs (ITC_Kind k ks) = freeNamesIfKind k &&& freeNamesIfTcArgs ks
freeNamesIfTcArgs ITC_Nil = emptyNameSet
freeNamesIfType :: IfaceType -> NameSet
freeNamesIfType (IfaceTyVar _) = emptyNameSet
freeNamesIfType (IfaceAppTy s t) = freeNamesIfType s &&& freeNamesIfType t
freeNamesIfType (IfaceTyConApp tc ts) =
freeNamesIfTc tc &&& freeNamesIfTcArgs ts
freeNamesIfType (IfaceLitTy _) = emptyNameSet
freeNamesIfType (IfaceForAllTy tv t) =
freeNamesIfTvBndr tv &&& freeNamesIfType t
freeNamesIfType (IfaceFunTy s t) = freeNamesIfType s &&& freeNamesIfType t
freeNamesIfType (IfaceDFunTy s t) = freeNamesIfType s &&& freeNamesIfType t
freeNamesIfCoercion :: IfaceCoercion -> NameSet
freeNamesIfCoercion (IfaceReflCo _ t) = freeNamesIfType t
freeNamesIfCoercion (IfaceFunCo _ c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceTyConAppCo _ tc cos)
= freeNamesIfTc tc &&& fnList freeNamesIfCoercion cos
freeNamesIfCoercion (IfaceAppCo c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceForAllCo tv co)
= freeNamesIfTvBndr tv &&& freeNamesIfCoercion co
freeNamesIfCoercion (IfaceCoVarCo _)
= emptyNameSet
freeNamesIfCoercion (IfaceAxiomInstCo ax _ cos)
= unitNameSet ax &&& fnList freeNamesIfCoercion cos
freeNamesIfCoercion (IfaceUnivCo _ _ t1 t2)
= freeNamesIfType t1 &&& freeNamesIfType t2
freeNamesIfCoercion (IfaceSymCo c)
= freeNamesIfCoercion c
freeNamesIfCoercion (IfaceTransCo c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceNthCo _ co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceLRCo _ co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceInstCo co ty)
= freeNamesIfCoercion co &&& freeNamesIfType ty
freeNamesIfCoercion (IfaceSubCo co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceAxiomRuleCo _ax tys cos)
-- the axiom is just a string, so we don't count it as a name.
= fnList freeNamesIfType tys &&&
fnList freeNamesIfCoercion cos
freeNamesIfTvBndrs :: [IfaceTvBndr] -> NameSet
freeNamesIfTvBndrs = fnList freeNamesIfTvBndr
freeNamesIfBndr :: IfaceBndr -> NameSet
freeNamesIfBndr (IfaceIdBndr b) = freeNamesIfIdBndr b
freeNamesIfBndr (IfaceTvBndr b) = freeNamesIfTvBndr b
freeNamesIfLetBndr :: IfaceLetBndr -> NameSet
-- Remember IfaceLetBndr is used only for *nested* bindings
-- The IdInfo can contain an unfolding (in the case of
-- local INLINE pragmas), so look there too
freeNamesIfLetBndr (IfLetBndr _name ty info) = freeNamesIfType ty
&&& freeNamesIfIdInfo info
freeNamesIfTvBndr :: IfaceTvBndr -> NameSet
freeNamesIfTvBndr (_fs,k) = freeNamesIfKind k
-- kinds can have Names inside, because of promotion
freeNamesIfIdBndr :: IfaceIdBndr -> NameSet
freeNamesIfIdBndr = freeNamesIfTvBndr
freeNamesIfIdInfo :: IfaceIdInfo -> NameSet
freeNamesIfIdInfo NoInfo = emptyNameSet
freeNamesIfIdInfo (HasInfo i) = fnList freeNamesItem i
freeNamesItem :: IfaceInfoItem -> NameSet
freeNamesItem (HsUnfold _ u) = freeNamesIfUnfold u
freeNamesItem _ = emptyNameSet
freeNamesIfUnfold :: IfaceUnfolding -> NameSet
freeNamesIfUnfold (IfCoreUnfold _ e) = freeNamesIfExpr e
freeNamesIfUnfold (IfCompulsory e) = freeNamesIfExpr e
freeNamesIfUnfold (IfInlineRule _ _ _ e) = freeNamesIfExpr e
freeNamesIfUnfold (IfDFunUnfold bs es) = fnList freeNamesIfBndr bs &&& fnList freeNamesIfExpr es
freeNamesIfExpr :: IfaceExpr -> NameSet
freeNamesIfExpr (IfaceExt v) = unitNameSet v
freeNamesIfExpr (IfaceFCall _ ty) = freeNamesIfType ty
freeNamesIfExpr (IfaceType ty) = freeNamesIfType ty
freeNamesIfExpr (IfaceCo co) = freeNamesIfCoercion co
freeNamesIfExpr (IfaceTuple _ as) = fnList freeNamesIfExpr as
freeNamesIfExpr (IfaceLam (b,_) body) = freeNamesIfBndr b &&& freeNamesIfExpr body
freeNamesIfExpr (IfaceApp f a) = freeNamesIfExpr f &&& freeNamesIfExpr a
freeNamesIfExpr (IfaceCast e co) = freeNamesIfExpr e &&& freeNamesIfCoercion co
freeNamesIfExpr (IfaceTick _ e) = freeNamesIfExpr e
freeNamesIfExpr (IfaceECase e ty) = freeNamesIfExpr e &&& freeNamesIfType ty
freeNamesIfExpr (IfaceCase s _ alts)
= freeNamesIfExpr s &&& fnList fn_alt alts &&& fn_cons alts
where
fn_alt (_con,_bs,r) = freeNamesIfExpr r
-- Depend on the data constructors. Just one will do!
-- Note [Tracking data constructors]
fn_cons [] = emptyNameSet
fn_cons ((IfaceDefault ,_,_) : xs) = fn_cons xs
fn_cons ((IfaceDataAlt con,_,_) : _ ) = unitNameSet con
fn_cons (_ : _ ) = emptyNameSet
freeNamesIfExpr (IfaceLet (IfaceNonRec bndr rhs) body)
= freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs &&& freeNamesIfExpr body
freeNamesIfExpr (IfaceLet (IfaceRec as) x)
= fnList fn_pair as &&& freeNamesIfExpr x
where
fn_pair (bndr, rhs) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs
freeNamesIfExpr _ = emptyNameSet
freeNamesIfTc :: IfaceTyCon -> NameSet
freeNamesIfTc tc = unitNameSet (ifaceTyConName tc)
-- ToDo: shouldn't we include IfaceIntTc & co.?
freeNamesIfRule :: IfaceRule -> NameSet
freeNamesIfRule (IfaceRule { ifRuleBndrs = bs, ifRuleHead = f
, ifRuleArgs = es, ifRuleRhs = rhs })
= unitNameSet f &&&
fnList freeNamesIfBndr bs &&&
fnList freeNamesIfExpr es &&&
freeNamesIfExpr rhs
freeNamesIfFamInst :: IfaceFamInst -> NameSet
freeNamesIfFamInst (IfaceFamInst { ifFamInstFam = famName
, ifFamInstAxiom = axName })
= unitNameSet famName &&&
unitNameSet axName
freeNamesIfaceTyConParent :: IfaceTyConParent -> NameSet
freeNamesIfaceTyConParent IfNoParent = emptyNameSet
freeNamesIfaceTyConParent (IfDataInstance ax tc tys)
= unitNameSet ax &&& freeNamesIfTc tc &&& freeNamesIfTcArgs tys
-- helpers
(&&&) :: NameSet -> NameSet -> NameSet
(&&&) = unionNameSet
fnList :: (a -> NameSet) -> [a] -> NameSet
fnList f = foldr (&&&) emptyNameSet . map f
{-
Note [Tracking data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a case expression
case e of { C a -> ...; ... }
You might think that we don't need to include the datacon C
in the free names, because its type will probably show up in
the free names of 'e'. But in rare circumstances this may
not happen. Here's the one that bit me:
module DynFlags where
import {-# SOURCE #-} Packages( PackageState )
data DynFlags = DF ... PackageState ...
module Packages where
import DynFlags
data PackageState = PS ...
lookupModule (df :: DynFlags)
= case df of
DF ...p... -> case p of
PS ... -> ...
Now, lookupModule depends on DynFlags, but the transitive dependency
on the *locally-defined* type PackageState is not visible. We need
to take account of the use of the data constructor PS in the pattern match.
************************************************************************
* *
Binary instances
* *
************************************************************************
-}
instance Binary IfaceDecl where
put_ bh (IfaceId name ty details idinfo) = do
putByte bh 0
put_ bh (occNameFS name)
put_ bh ty
put_ bh details
put_ bh idinfo
put_ bh (IfaceData a1 a2 a3 a4 a5 a6 a7 a8 a9 a10) = do
putByte bh 2
put_ bh (occNameFS a1)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh a10
put_ bh (IfaceSynonym a1 a2 a3 a4 a5) = do
putByte bh 3
put_ bh (occNameFS a1)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh (IfaceFamily a1 a2 a3 a4) = do
putByte bh 4
put_ bh (occNameFS a1)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh (IfaceClass a1 a2 a3 a4 a5 a6 a7 a8 a9) = do
putByte bh 5
put_ bh a1
put_ bh (occNameFS a2)
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh (IfaceAxiom a1 a2 a3 a4) = do
putByte bh 6
put_ bh (occNameFS a1)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh (IfacePatSyn name a2 a3 a4 a5 a6 a7 a8 a9 a10) = do
putByte bh 7
put_ bh (occNameFS name)
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh a10
get bh = do
h <- getByte bh
case h of
0 -> do name <- get bh
ty <- get bh
details <- get bh
idinfo <- get bh
occ <- return $! mkVarOccFS name
return (IfaceId occ ty details idinfo)
1 -> error "Binary.get(TyClDecl): ForeignType"
2 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
a10 <- get bh
occ <- return $! mkTcOccFS a1
return (IfaceData occ a2 a3 a4 a5 a6 a7 a8 a9 a10)
3 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
occ <- return $! mkTcOccFS a1
return (IfaceSynonym occ a2 a3 a4 a5)
4 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
occ <- return $! mkTcOccFS a1
return (IfaceFamily occ a2 a3 a4)
5 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
occ <- return $! mkClsOccFS a2
return (IfaceClass a1 occ a3 a4 a5 a6 a7 a8 a9)
6 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
occ <- return $! mkTcOccFS a1
return (IfaceAxiom occ a2 a3 a4)
7 -> do a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
a10 <- get bh
occ <- return $! mkDataOccFS a1
return (IfacePatSyn occ a2 a3 a4 a5 a6 a7 a8 a9 a10)
_ -> panic (unwords ["Unknown IfaceDecl tag:", show h])
instance Binary IfaceFamTyConFlav where
put_ bh IfaceOpenSynFamilyTyCon = putByte bh 0
put_ bh (IfaceClosedSynFamilyTyCon ax br) = putByte bh 1 >> put_ bh ax
>> put_ bh br
put_ bh IfaceAbstractClosedSynFamilyTyCon = putByte bh 2
put_ _ IfaceBuiltInSynFamTyCon
= pprPanic "Cannot serialize IfaceBuiltInSynFamTyCon, used for pretty-printing only" Outputable.empty
get bh = do { h <- getByte bh
; case h of
0 -> return IfaceOpenSynFamilyTyCon
1 -> do { ax <- get bh
; br <- get bh
; return (IfaceClosedSynFamilyTyCon ax br) }
_ -> return IfaceAbstractClosedSynFamilyTyCon }
instance Binary IfaceClassOp where
put_ bh (IfaceClassOp n def ty) = do
put_ bh (occNameFS n)
put_ bh def
put_ bh ty
get bh = do
n <- get bh
def <- get bh
ty <- get bh
occ <- return $! mkVarOccFS n
return (IfaceClassOp occ def ty)
instance Binary IfaceAT where
put_ bh (IfaceAT dec defs) = do
put_ bh dec
put_ bh defs
get bh = do
dec <- get bh
defs <- get bh
return (IfaceAT dec defs)
instance Binary IfaceAxBranch where
put_ bh (IfaceAxBranch a1 a2 a3 a4 a5) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
return (IfaceAxBranch a1 a2 a3 a4 a5)
instance Binary IfaceConDecls where
put_ bh (IfAbstractTyCon d) = putByte bh 0 >> put_ bh d
put_ bh IfDataFamTyCon = putByte bh 1
put_ bh (IfDataTyCon cs) = putByte bh 2 >> put_ bh cs
put_ bh (IfNewTyCon c) = putByte bh 3 >> put_ bh c
get bh = do
h <- getByte bh
case h of
0 -> liftM IfAbstractTyCon $ get bh
1 -> return IfDataFamTyCon
2 -> liftM IfDataTyCon $ get bh
_ -> liftM IfNewTyCon $ get bh
instance Binary IfaceConDecl where
put_ bh (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
return (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9)
instance Binary IfaceBang where
put_ bh IfNoBang = putByte bh 0
put_ bh IfStrict = putByte bh 1
put_ bh IfUnpack = putByte bh 2
put_ bh (IfUnpackCo co) = putByte bh 3 >> put_ bh co
get bh = do
h <- getByte bh
case h of
0 -> do return IfNoBang
1 -> do return IfStrict
2 -> do return IfUnpack
_ -> do { a <- get bh; return (IfUnpackCo a) }
instance Binary IfaceClsInst where
put_ bh (IfaceClsInst cls tys dfun flag orph) = do
put_ bh cls
put_ bh tys
put_ bh dfun
put_ bh flag
put_ bh orph
get bh = do
cls <- get bh
tys <- get bh
dfun <- get bh
flag <- get bh
orph <- get bh
return (IfaceClsInst cls tys dfun flag orph)
instance Binary IfaceFamInst where
put_ bh (IfaceFamInst fam tys name orph) = do
put_ bh fam
put_ bh tys
put_ bh name
put_ bh orph
get bh = do
fam <- get bh
tys <- get bh
name <- get bh
orph <- get bh
return (IfaceFamInst fam tys name orph)
instance Binary IfaceRule where
put_ bh (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
return (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8)
instance Binary IfaceAnnotation where
put_ bh (IfaceAnnotation a1 a2) = do
put_ bh a1
put_ bh a2
get bh = do
a1 <- get bh
a2 <- get bh
return (IfaceAnnotation a1 a2)
instance Binary IfaceIdDetails where
put_ bh IfVanillaId = putByte bh 0
put_ bh (IfRecSelId a b) = putByte bh 1 >> put_ bh a >> put_ bh b
put_ bh IfDFunId = putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> return IfVanillaId
1 -> do { a <- get bh; b <- get bh; return (IfRecSelId a b) }
_ -> return IfDFunId
instance Binary IfaceIdInfo where
put_ bh NoInfo = putByte bh 0
put_ bh (HasInfo i) = putByte bh 1 >> lazyPut bh i -- NB lazyPut
get bh = do
h <- getByte bh
case h of
0 -> return NoInfo
_ -> liftM HasInfo $ lazyGet bh -- NB lazyGet
instance Binary IfaceInfoItem where
put_ bh (HsArity aa) = putByte bh 0 >> put_ bh aa
put_ bh (HsStrictness ab) = putByte bh 1 >> put_ bh ab
put_ bh (HsUnfold lb ad) = putByte bh 2 >> put_ bh lb >> put_ bh ad
put_ bh (HsInline ad) = putByte bh 3 >> put_ bh ad
put_ bh HsNoCafRefs = putByte bh 4
get bh = do
h <- getByte bh
case h of
0 -> liftM HsArity $ get bh
1 -> liftM HsStrictness $ get bh
2 -> do lb <- get bh
ad <- get bh
return (HsUnfold lb ad)
3 -> liftM HsInline $ get bh
_ -> return HsNoCafRefs
instance Binary IfaceUnfolding where
put_ bh (IfCoreUnfold s e) = do
putByte bh 0
put_ bh s
put_ bh e
put_ bh (IfInlineRule a b c d) = do
putByte bh 1
put_ bh a
put_ bh b
put_ bh c
put_ bh d
put_ bh (IfDFunUnfold as bs) = do
putByte bh 2
put_ bh as
put_ bh bs
put_ bh (IfCompulsory e) = do
putByte bh 3
put_ bh e
get bh = do
h <- getByte bh
case h of
0 -> do s <- get bh
e <- get bh
return (IfCoreUnfold s e)
1 -> do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (IfInlineRule a b c d)
2 -> do as <- get bh
bs <- get bh
return (IfDFunUnfold as bs)
_ -> do e <- get bh
return (IfCompulsory e)
instance Binary IfaceExpr where
put_ bh (IfaceLcl aa) = do
putByte bh 0
put_ bh aa
put_ bh (IfaceType ab) = do
putByte bh 1
put_ bh ab
put_ bh (IfaceCo ab) = do
putByte bh 2
put_ bh ab
put_ bh (IfaceTuple ac ad) = do
putByte bh 3
put_ bh ac
put_ bh ad
put_ bh (IfaceLam (ae, os) af) = do
putByte bh 4
put_ bh ae
put_ bh os
put_ bh af
put_ bh (IfaceApp ag ah) = do
putByte bh 5
put_ bh ag
put_ bh ah
put_ bh (IfaceCase ai aj ak) = do
putByte bh 6
put_ bh ai
put_ bh aj
put_ bh ak
put_ bh (IfaceLet al am) = do
putByte bh 7
put_ bh al
put_ bh am
put_ bh (IfaceTick an ao) = do
putByte bh 8
put_ bh an
put_ bh ao
put_ bh (IfaceLit ap) = do
putByte bh 9
put_ bh ap
put_ bh (IfaceFCall as at) = do
putByte bh 10
put_ bh as
put_ bh at
put_ bh (IfaceExt aa) = do
putByte bh 11
put_ bh aa
put_ bh (IfaceCast ie ico) = do
putByte bh 12
put_ bh ie
put_ bh ico
put_ bh (IfaceECase a b) = do
putByte bh 13
put_ bh a
put_ bh b
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
return (IfaceLcl aa)
1 -> do ab <- get bh
return (IfaceType ab)
2 -> do ab <- get bh
return (IfaceCo ab)
3 -> do ac <- get bh
ad <- get bh
return (IfaceTuple ac ad)
4 -> do ae <- get bh
os <- get bh
af <- get bh
return (IfaceLam (ae, os) af)
5 -> do ag <- get bh
ah <- get bh
return (IfaceApp ag ah)
6 -> do ai <- get bh
aj <- get bh
ak <- get bh
return (IfaceCase ai aj ak)
7 -> do al <- get bh
am <- get bh
return (IfaceLet al am)
8 -> do an <- get bh
ao <- get bh
return (IfaceTick an ao)
9 -> do ap <- get bh
return (IfaceLit ap)
10 -> do as <- get bh
at <- get bh
return (IfaceFCall as at)
11 -> do aa <- get bh
return (IfaceExt aa)
12 -> do ie <- get bh
ico <- get bh
return (IfaceCast ie ico)
13 -> do a <- get bh
b <- get bh
return (IfaceECase a b)
_ -> panic ("get IfaceExpr " ++ show h)
instance Binary IfaceTickish where
put_ bh (IfaceHpcTick m ix) = do
putByte bh 0
put_ bh m
put_ bh ix
put_ bh (IfaceSCC cc tick push) = do
putByte bh 1
put_ bh cc
put_ bh tick
put_ bh push
put_ bh (IfaceSource src name) = do
putByte bh 2
put_ bh (srcSpanFile src)
put_ bh (srcSpanStartLine src)
put_ bh (srcSpanStartCol src)
put_ bh (srcSpanEndLine src)
put_ bh (srcSpanEndCol src)
put_ bh name
get bh = do
h <- getByte bh
case h of
0 -> do m <- get bh
ix <- get bh
return (IfaceHpcTick m ix)
1 -> do cc <- get bh
tick <- get bh
push <- get bh
return (IfaceSCC cc tick push)
2 -> do file <- get bh
sl <- get bh
sc <- get bh
el <- get bh
ec <- get bh
let start = mkRealSrcLoc file sl sc
end = mkRealSrcLoc file el ec
name <- get bh
return (IfaceSource (mkRealSrcSpan start end) name)
_ -> panic ("get IfaceTickish " ++ show h)
instance Binary IfaceConAlt where
put_ bh IfaceDefault = putByte bh 0
put_ bh (IfaceDataAlt aa) = putByte bh 1 >> put_ bh aa
put_ bh (IfaceLitAlt ac) = putByte bh 2 >> put_ bh ac
get bh = do
h <- getByte bh
case h of
0 -> return IfaceDefault
1 -> liftM IfaceDataAlt $ get bh
_ -> liftM IfaceLitAlt $ get bh
instance Binary IfaceBinding where
put_ bh (IfaceNonRec aa ab) = putByte bh 0 >> put_ bh aa >> put_ bh ab
put_ bh (IfaceRec ac) = putByte bh 1 >> put_ bh ac
get bh = do
h <- getByte bh
case h of
0 -> do { aa <- get bh; ab <- get bh; return (IfaceNonRec aa ab) }
_ -> do { ac <- get bh; return (IfaceRec ac) }
instance Binary IfaceLetBndr where
put_ bh (IfLetBndr a b c) = do
put_ bh a
put_ bh b
put_ bh c
get bh = do a <- get bh
b <- get bh
c <- get bh
return (IfLetBndr a b c)
instance Binary IfaceTyConParent where
put_ bh IfNoParent = putByte bh 0
put_ bh (IfDataInstance ax pr ty) = do
putByte bh 1
put_ bh ax
put_ bh pr
put_ bh ty
get bh = do
h <- getByte bh
case h of
0 -> return IfNoParent
_ -> do
ax <- get bh
pr <- get bh
ty <- get bh
return $ IfDataInstance ax pr ty
|
green-haskell/ghc
|
compiler/iface/IfaceSyn.hs
|
bsd-3-clause
| 70,422 | 76 | 27 | 23,566 | 17,337 | 8,624 | 8,713 | 1,343 | 11 |
-- | Types used separate to GHCi vanilla.
module GhciTypes where
import Data.Time
import GHC
import Intero.Compat
import Outputable
-- | Info about a module. This information is generated every time a
-- module is loaded.
data ModInfo =
ModInfo {modinfoSummary :: !ModSummary
-- ^ Summary generated by GHC. Can be used to access more
-- information about the module.
,modinfoSpans :: ![SpanInfo]
-- ^ Generated set of information about all spans in the
-- module that correspond to some kind of identifier for
-- which there will be type info and/or location info.
,modinfoInfo :: !ModuleInfo
-- ^ Again, useful from GHC for accessing information
-- (exports, instances, scope) from a module.
,modinfoLastUpdate :: !UTCTime
-- ^ Last time the module was updated.
,modinfoImports :: ![LImportDecl StageReaderName]
-- ^ Import declarations within this module.
,modinfoLocation :: !SrcSpan
-- ^ The location of the module
}
-- | Type of some span of source code. Most of these fields are
-- unboxed but Haddock doesn't show that.
data SpanInfo =
SpanInfo {spaninfoStartLine :: {-# UNPACK #-} !Int
-- ^ Start line of the span.
,spaninfoStartCol :: {-# UNPACK #-} !Int
-- ^ Start column of the span.
,spaninfoEndLine :: {-# UNPACK #-} !Int
-- ^ End line of the span (absolute).
,spaninfoEndCol :: {-# UNPACK #-} !Int
-- ^ End column of the span (absolute).
,spaninfoType :: !(Maybe Type)
-- ^ A pretty-printed representation fo the type.
,spaninfoVar :: !(Maybe Id)
-- ^ The actual 'Var' associated with the span, if
-- any. This can be useful for accessing a variety of
-- information about the identifier such as module,
-- locality, definition location, etc.
}
instance Outputable SpanInfo where
ppr (SpanInfo sl sc el ec ty v) =
(int sl Outputable.<>
text ":" Outputable.<>
int sc Outputable.<>
text "-") Outputable.<>
(int el Outputable.<>
text ":" Outputable.<>
int ec Outputable.<>
text ": ") Outputable.<>
(ppr v Outputable.<>
text " :: " Outputable.<>
ppr ty)
|
chrisdone/intero
|
src/GhciTypes.hs
|
bsd-3-clause
| 2,371 | 0 | 12 | 731 | 305 | 173 | 132 | 48 | 0 |
{-----------------------------------------------------------------------------
A LIBRARY OF MEMOIZATION COMBINATORS
15th September 1999
Byron Cook
OGI
This Hugs module implements several flavors of memoization functions,
as described in Haskell Workshop 1997.
-----------------------------------------------------------------------------}
module Hugs.Memo(
memo,
memoN,
memoFix,
memoFixN,
cache,
cacheN,
cacheFix,
cacheFixN
) where
import Hugs.ST
-- import Hugs.IOExts (unsafePtrEq)
-- import Debug.Trace (trace)
memo :: (a -> b) -> (a -> b)
memoN :: Int -> (a -> b) -> (a -> b)
memoFix :: ((a -> b) -> (a -> b)) -> (a -> b)
memoFixN :: Int -> ((a -> b) -> (a -> b)) -> (a -> b)
cache :: (a -> b) -> (a -> b)
cacheN :: Int -> (a -> b) -> (a -> b)
cacheFix :: ((a -> b) -> (a -> b)) -> (a -> b)
cacheFixN :: Int -> ((a -> b) -> (a -> b)) -> (a -> b)
----------------------------------------------------------------
-- Memoization Functions (memo-tables are hash-tables)
----------------------------------------------------------------
memo = memoN defaultSize
memoN = mkMemo eql hash
memoFix = memoFixN defaultSize
memoFixN n f = let g = f h
h = memoN n g
in g
----------------------------------------------------------------
-- Caching Functions (memo-tables are caches)
----------------------------------------------------------------
cache = cacheN defaultSize
cacheN = mkCache eql hash
cacheFix = cacheFixN defaultSize
cacheFixN n f = let g = f h
h = cacheN n g
in g
----------------------------------------------------------------
-- Type synonyms
----------------------------------------------------------------
type TaintedEq a = a -> a -> ST Mem Bool
type HashTable a b = STArray Mem Int [(a,b)]
type Cache a b = STArray Mem Int (Maybe (a,b))
type HashSize = Int
type HashFunc a = a -> ST Mem Int
type Mem = ()
----------------------------------------------------------------
-- Foundation functions
----------------------------------------------------------------
defaultSize :: HashSize
defaultSize = 40
memoize :: ST Mem t -> (t -> a -> b -> ST Mem b) ->
(a -> b) -> a -> b
memoize new access f = {-trace "memoize" $-} unsafeRunST $ do
t <- new
return (\x -> unsafeRunST $ access t x (f x))
mkMemo :: TaintedEq a -> HashFunc a -> Int -> (a -> c) -> (a -> c)
mkCache :: TaintedEq a -> HashFunc a -> Int -> (a -> c) -> (a -> c)
mkCache e h sz = memoize (newCache sz) (accessCache e h sz)
mkMemo e h sz = memoize (newHash sz) (accessHash e h sz)
----------------------------------------------------------------
-- Hash and Cache Tables
----------------------------------------------------------------
accessHash :: TaintedEq a ->
HashFunc a ->
Int ->
HashTable a b ->
a -> b -> ST Mem b
accessHash equal h sz table x v = do
hv' <- h x
let hv = hv' `mod` sz
l <- readSTArray table hv
find l l hv
where find l [] hv = {-trace "miss " $-} do
u <- writeSTArray table hv ((x,v):l)
case u of {() -> return v}
find l ((x',v'):xs) hv = do
a <- equal x x'
if a then {-trace "hit "-} (return $ v')
else find l xs hv
newHash :: Int -> ST Mem (HashTable a b)
newHash n = newSTArray (0,n) []
accessCache :: TaintedEq a ->
HashFunc a ->
Int ->
Cache a b ->
a -> b -> ST Mem b
accessCache equal h sz table x v = do
hv' <- h x
let hv = hv' `mod` sz
l <- readSTArray table hv
case l of
Nothing -> do u <- writeSTArray table hv (Just (x,v))
case u of {() -> return v}
Just (x',y) -> do e <- equal x' x
if e then return y
else do u <- writeSTArray table hv (Just (x,v))
case u of {() -> return v}
newCache :: Int -> ST Mem (Cache a b)
newCache n = newSTArray (0,n) Nothing
------------------------------------------------------------------
-- These functions are bad --- dont pay attention to them
-- lisp style eql --- as described in "Lazy-memo functions"
primitive eql "IOEql" :: a -> a -> ST Mem Bool
-- a `eql` b = return (a `unsafePtrEq` b)
-- hash based on addresses (or values if the arg is a base type)
primitive hash "IOHash" :: a -> ST Mem Int
------------------------------------------------------------------
|
kaoskorobase/mescaline
|
resources/hugs/packages/hugsbase/Hugs/Memo.hs
|
gpl-3.0
| 4,725 | 6 | 20 | 1,399 | 1,410 | 743 | 667 | -1 | -1 |
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude
, BangPatterns
, RankNTypes
, MagicHash
, UnboxedTuples
#-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : GHC.IO
-- Copyright : (c) The University of Glasgow 1994-2002
-- License : see libraries/base/LICENSE
--
-- Maintainer : [email protected]
-- Stability : internal
-- Portability : non-portable (GHC Extensions)
--
-- Definitions for the 'IO' monad and its friends.
--
-----------------------------------------------------------------------------
module GHC.IO (
IO(..), unIO, failIO, liftIO,
unsafePerformIO, unsafeInterleaveIO,
unsafeDupablePerformIO, unsafeDupableInterleaveIO,
noDuplicate,
-- To and from from ST
stToIO, ioToST, unsafeIOToST, unsafeSTToIO,
FilePath,
catchException, catchAny, throwIO,
mask, mask_, uninterruptibleMask, uninterruptibleMask_,
MaskingState(..), getMaskingState,
unsafeUnmask,
onException, bracket, finally, evaluate
) where
import GHC.Base
import GHC.ST
import GHC.Exception
import GHC.Show
import {-# SOURCE #-} GHC.IO.Exception ( userError )
-- ---------------------------------------------------------------------------
-- The IO Monad
{-
The IO Monad is just an instance of the ST monad, where the state is
the real world. We use the exception mechanism (in GHC.Exception) to
implement IO exceptions.
NOTE: The IO representation is deeply wired in to various parts of the
system. The following list may or may not be exhaustive:
Compiler - types of various primitives in PrimOp.lhs
RTS - forceIO (StgMiscClosures.hc)
- catchzh_fast, (un)?blockAsyncExceptionszh_fast, raisezh_fast
(Exceptions.hc)
- raiseAsync (Schedule.c)
Prelude - GHC.IO.lhs, and several other places including
GHC.Exception.lhs.
Libraries - parts of hslibs/lang.
--SDM
-}
liftIO :: IO a -> State# RealWorld -> STret RealWorld a
liftIO (IO m) = \s -> case m s of (# s', r #) -> STret s' r
failIO :: String -> IO a
failIO s = IO (raiseIO# (toException (userError s)))
-- ---------------------------------------------------------------------------
-- Coercions between IO and ST
-- | A monad transformer embedding strict state transformers in the 'IO'
-- monad. The 'RealWorld' parameter indicates that the internal state
-- used by the 'ST' computation is a special one supplied by the 'IO'
-- monad, and thus distinct from those used by invocations of 'runST'.
stToIO :: ST RealWorld a -> IO a
stToIO (ST m) = IO m
ioToST :: IO a -> ST RealWorld a
ioToST (IO m) = (ST m)
-- This relies on IO and ST having the same representation modulo the
-- constraint on the type of the state
--
unsafeIOToST :: IO a -> ST s a
unsafeIOToST (IO io) = ST $ \ s -> (unsafeCoerce# io) s
unsafeSTToIO :: ST s a -> IO a
unsafeSTToIO (ST m) = IO (unsafeCoerce# m)
-- ---------------------------------------------------------------------------
-- Unsafe IO operations
{-|
This is the \"back door\" into the 'IO' monad, allowing
'IO' computation to be performed at any time. For
this to be safe, the 'IO' computation should be
free of side effects and independent of its environment.
If the I\/O computation wrapped in 'unsafePerformIO' performs side
effects, then the relative order in which those side effects take
place (relative to the main I\/O trunk, or other calls to
'unsafePerformIO') is indeterminate. Furthermore, when using
'unsafePerformIO' to cause side-effects, you should take the following
precautions to ensure the side effects are performed as many times as
you expect them to be. Note that these precautions are necessary for
GHC, but may not be sufficient, and other compilers may require
different precautions:
* Use @{\-\# NOINLINE foo \#-\}@ as a pragma on any function @foo@
that calls 'unsafePerformIO'. If the call is inlined,
the I\/O may be performed more than once.
* Use the compiler flag @-fno-cse@ to prevent common sub-expression
elimination being performed on the module, which might combine
two side effects that were meant to be separate. A good example
is using multiple global variables (like @test@ in the example below).
* Make sure that the either you switch off let-floating (@-fno-full-laziness@), or that the
call to 'unsafePerformIO' cannot float outside a lambda. For example,
if you say:
@
f x = unsafePerformIO (newIORef [])
@
you may get only one reference cell shared between all calls to @f@.
Better would be
@
f x = unsafePerformIO (newIORef [x])
@
because now it can't float outside the lambda.
It is less well known that
'unsafePerformIO' is not type safe. For example:
> test :: IORef [a]
> test = unsafePerformIO $ newIORef []
>
> main = do
> writeIORef test [42]
> bang <- readIORef test
> print (bang :: [Char])
This program will core dump. This problem with polymorphic references
is well known in the ML community, and does not arise with normal
monadic use of references. There is no easy way to make it impossible
once you use 'unsafePerformIO'. Indeed, it is
possible to write @coerce :: a -> b@ with the
help of 'unsafePerformIO'. So be careful!
-}
unsafePerformIO :: IO a -> a
unsafePerformIO m = unsafeDupablePerformIO (noDuplicate >> m)
{-|
This version of 'unsafePerformIO' is more efficient
because it omits the check that the IO is only being performed by a
single thread. Hence, when you use 'unsafeDupablePerformIO',
there is a possibility that the IO action may be performed multiple
times (on a multiprocessor), and you should therefore ensure that
it gives the same results each time. It may even happen that one
of the duplicated IO actions is only run partially, and then interrupted
in the middle without an exception being raised. Therefore, functions
like 'bracket' cannot be used safely within 'unsafeDupablePerformIO'.
@since 4.4.0.0
-}
{-# NOINLINE unsafeDupablePerformIO #-}
-- See Note [unsafeDupablePerformIO is NOINLINE]
unsafeDupablePerformIO :: IO a -> a
unsafeDupablePerformIO (IO m) = lazy (case m realWorld# of (# _, r #) -> r)
-- See Note [unsafeDupablePerformIO has a lazy RHS]
-- Note [unsafeDupablePerformIO is NOINLINE]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Why do we NOINLINE unsafeDupablePerformIO? See the comment with
-- GHC.ST.runST. Essentially the issue is that the IO computation
-- inside unsafePerformIO must be atomic: it must either all run, or
-- not at all. If we let the compiler see the application of the IO
-- to realWorld#, it might float out part of the IO.
-- Note [unsafeDupablePerformIO has a lazy RHS]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- Why is there a call to 'lazy' in unsafeDupablePerformIO?
-- If we don't have it, the demand analyser discovers the following strictness
-- for unsafeDupablePerformIO: C(U(AV))
-- But then consider
-- unsafeDupablePerformIO (\s -> let r = f x in
-- case writeIORef v r s of (# s1, _ #) ->
-- (# s1, r #) )
-- The strictness analyser will find that the binding for r is strict,
-- (because of uPIO's strictness sig), and so it'll evaluate it before
-- doing the writeIORef. This actually makes libraries/base/tests/memo002
-- get a deadlock, where we specifically wanted to write a lazy thunk
-- into the ref cell.
--
-- Solution: don't expose the strictness of unsafeDupablePerformIO,
-- by hiding it with 'lazy'
-- But see discussion in Trac #9390 (comment:33)
{-|
'unsafeInterleaveIO' allows 'IO' computation to be deferred lazily.
When passed a value of type @IO a@, the 'IO' will only be performed
when the value of the @a@ is demanded. This is used to implement lazy
file reading, see 'System.IO.hGetContents'.
-}
{-# INLINE unsafeInterleaveIO #-}
unsafeInterleaveIO :: IO a -> IO a
unsafeInterleaveIO m = unsafeDupableInterleaveIO (noDuplicate >> m)
-- We used to believe that INLINE on unsafeInterleaveIO was safe,
-- because the state from this IO thread is passed explicitly to the
-- interleaved IO, so it cannot be floated out and shared.
--
-- HOWEVER, if the compiler figures out that r is used strictly here,
-- then it will eliminate the thunk and the side effects in m will no
-- longer be shared in the way the programmer was probably expecting,
-- but can be performed many times. In #5943, this broke our
-- definition of fixIO, which contains
--
-- ans <- unsafeInterleaveIO (takeMVar m)
--
-- after inlining, we lose the sharing of the takeMVar, so the second
-- time 'ans' was demanded we got a deadlock. We could fix this with
-- a readMVar, but it seems wrong for unsafeInterleaveIO to sometimes
-- share and sometimes not (plus it probably breaks the noDuplicate).
-- So now, we do not inline unsafeDupableInterleaveIO.
{-# NOINLINE unsafeDupableInterleaveIO #-}
unsafeDupableInterleaveIO :: IO a -> IO a
unsafeDupableInterleaveIO (IO m)
= IO ( \ s -> let
r = case m s of (# _, res #) -> res
in
(# s, r #))
{-|
Ensures that the suspensions under evaluation by the current thread
are unique; that is, the current thread is not evaluating anything
that is also under evaluation by another thread that has also executed
'noDuplicate'.
This operation is used in the definition of 'unsafePerformIO' to
prevent the IO action from being executed multiple times, which is usually
undesirable.
-}
noDuplicate :: IO ()
noDuplicate = IO $ \s -> case noDuplicate# s of s' -> (# s', () #)
-- -----------------------------------------------------------------------------
-- | File and directory names are values of type 'String', whose precise
-- meaning is operating system dependent. Files can be opened, yielding a
-- handle which can then be used to operate on the contents of that file.
type FilePath = String
-- -----------------------------------------------------------------------------
-- Primitive catch and throwIO
{-
catchException used to handle the passing around of the state to the
action and the handler. This turned out to be a bad idea - it meant
that we had to wrap both arguments in thunks so they could be entered
as normal (remember IO returns an unboxed pair...).
Now catch# has type
catch# :: IO a -> (b -> IO a) -> IO a
(well almost; the compiler doesn't know about the IO newtype so we
have to work around that in the definition of catchException below).
-}
catchException :: Exception e => IO a -> (e -> IO a) -> IO a
catchException (IO io) handler = IO $ catch# io handler'
where handler' e = case fromException e of
Just e' -> unIO (handler e')
Nothing -> raiseIO# e
catchAny :: IO a -> (forall e . Exception e => e -> IO a) -> IO a
catchAny (IO io) handler = IO $ catch# io handler'
where handler' (SomeException e) = unIO (handler e)
-- | A variant of 'throw' that can only be used within the 'IO' monad.
--
-- Although 'throwIO' has a type that is an instance of the type of 'throw', the
-- two functions are subtly different:
--
-- > throw e `seq` x ===> throw e
-- > throwIO e `seq` x ===> x
--
-- The first example will cause the exception @e@ to be raised,
-- whereas the second one won\'t. In fact, 'throwIO' will only cause
-- an exception to be raised when it is used within the 'IO' monad.
-- The 'throwIO' variant should be used in preference to 'throw' to
-- raise an exception within the 'IO' monad because it guarantees
-- ordering with respect to other 'IO' operations, whereas 'throw'
-- does not.
throwIO :: Exception e => e -> IO a
throwIO e = IO (raiseIO# (toException e))
-- -----------------------------------------------------------------------------
-- Controlling asynchronous exception delivery
-- Applying 'block' to a computation will
-- execute that computation with asynchronous exceptions
-- /blocked/. That is, any thread which
-- attempts to raise an exception in the current thread with 'Control.Exception.throwTo' will be
-- blocked until asynchronous exceptions are unblocked again. There\'s
-- no need to worry about re-enabling asynchronous exceptions; that is
-- done automatically on exiting the scope of
-- 'block'.
--
-- Threads created by 'Control.Concurrent.forkIO' inherit the blocked
-- state from the parent; that is, to start a thread in blocked mode,
-- use @block $ forkIO ...@. This is particularly useful if you need to
-- establish an exception handler in the forked thread before any
-- asynchronous exceptions are received.
block :: IO a -> IO a
block (IO io) = IO $ maskAsyncExceptions# io
-- To re-enable asynchronous exceptions inside the scope of
-- 'block', 'unblock' can be
-- used. It scopes in exactly the same way, so on exit from
-- 'unblock' asynchronous exception delivery will
-- be disabled again.
unblock :: IO a -> IO a
unblock = unsafeUnmask
unsafeUnmask :: IO a -> IO a
unsafeUnmask (IO io) = IO $ unmaskAsyncExceptions# io
blockUninterruptible :: IO a -> IO a
blockUninterruptible (IO io) = IO $ maskUninterruptible# io
-- | Describes the behaviour of a thread when an asynchronous
-- exception is received.
data MaskingState
= Unmasked -- ^ asynchronous exceptions are unmasked (the normal state)
| MaskedInterruptible
-- ^ the state during 'mask': asynchronous exceptions are masked, but blocking operations may still be interrupted
| MaskedUninterruptible
-- ^ the state during 'uninterruptibleMask': asynchronous exceptions are masked, and blocking operations may not be interrupted
deriving (Eq,Show)
-- | Returns the 'MaskingState' for the current thread.
getMaskingState :: IO MaskingState
getMaskingState = IO $ \s ->
case getMaskingState# s of
(# s', i #) -> (# s', case i of
0# -> Unmasked
1# -> MaskedUninterruptible
_ -> MaskedInterruptible #)
onException :: IO a -> IO b -> IO a
onException io what = io `catchException` \e -> do _ <- what
throwIO (e :: SomeException)
-- | Executes an IO computation with asynchronous
-- exceptions /masked/. That is, any thread which attempts to raise
-- an exception in the current thread with 'Control.Exception.throwTo'
-- will be blocked until asynchronous exceptions are unmasked again.
--
-- The argument passed to 'mask' is a function that takes as its
-- argument another function, which can be used to restore the
-- prevailing masking state within the context of the masked
-- computation. For example, a common way to use 'mask' is to protect
-- the acquisition of a resource:
--
-- > mask $ \restore -> do
-- > x <- acquire
-- > restore (do_something_with x) `onException` release
-- > release
--
-- This code guarantees that @acquire@ is paired with @release@, by masking
-- asynchronous exceptions for the critical parts. (Rather than write
-- this code yourself, it would be better to use
-- 'Control.Exception.bracket' which abstracts the general pattern).
--
-- Note that the @restore@ action passed to the argument to 'mask'
-- does not necessarily unmask asynchronous exceptions, it just
-- restores the masking state to that of the enclosing context. Thus
-- if asynchronous exceptions are already masked, 'mask' cannot be used
-- to unmask exceptions again. This is so that if you call a library function
-- with exceptions masked, you can be sure that the library call will not be
-- able to unmask exceptions again. If you are writing library code and need
-- to use asynchronous exceptions, the only way is to create a new thread;
-- see 'Control.Concurrent.forkIOWithUnmask'.
--
-- Asynchronous exceptions may still be received while in the masked
-- state if the masked thread /blocks/ in certain ways; see
-- "Control.Exception#interruptible".
--
-- Threads created by 'Control.Concurrent.forkIO' inherit the
-- 'MaskingState' from the parent; that is, to start a thread in the
-- 'MaskedInterruptible' state,
-- use @mask_ $ forkIO ...@. This is particularly useful if you need
-- to establish an exception handler in the forked thread before any
-- asynchronous exceptions are received. To create a a new thread in
-- an unmasked state use 'Control.Concurrent.forkIOUnmasked'.
--
mask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
-- | Like 'mask', but does not pass a @restore@ action to the argument.
mask_ :: IO a -> IO a
-- | Like 'mask', but the masked computation is not interruptible (see
-- "Control.Exception#interruptible"). THIS SHOULD BE USED WITH
-- GREAT CARE, because if a thread executing in 'uninterruptibleMask'
-- blocks for any reason, then the thread (and possibly the program,
-- if this is the main thread) will be unresponsive and unkillable.
-- This function should only be necessary if you need to mask
-- exceptions around an interruptible operation, and you can guarantee
-- that the interruptible operation will only block for a short period
-- of time.
--
uninterruptibleMask :: ((forall a. IO a -> IO a) -> IO b) -> IO b
-- | Like 'uninterruptibleMask', but does not pass a @restore@ action
-- to the argument.
uninterruptibleMask_ :: IO a -> IO a
mask_ io = mask $ \_ -> io
mask io = do
b <- getMaskingState
case b of
Unmasked -> block $ io unblock
_ -> io id
uninterruptibleMask_ io = uninterruptibleMask $ \_ -> io
uninterruptibleMask io = do
b <- getMaskingState
case b of
Unmasked -> blockUninterruptible $ io unblock
MaskedInterruptible -> blockUninterruptible $ io block
MaskedUninterruptible -> io id
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
r <- restore (thing a) `onException` after a
_ <- after a
return r
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
-- | Evaluate the argument to weak head normal form.
--
-- 'evaluate' is typically used to uncover any exceptions that a lazy value
-- may contain, and possibly handle them.
--
-- 'evaluate' only evaluates to /weak head normal form/. If deeper
-- evaluation is needed, the @force@ function from @Control.DeepSeq@
-- may be handy:
--
-- > evaluate $ force x
--
-- There is a subtle difference between @'evaluate' x@ and @'return' '$!' x@,
-- analogous to the difference between 'throwIO' and 'throw'. If the lazy
-- value @x@ throws an exception, @'return' '$!' x@ will fail to return an
-- 'IO' action and will throw an exception instead. @'evaluate' x@, on the
-- other hand, always produces an 'IO' action; that action will throw an
-- exception upon /execution/ iff @x@ throws an exception upon /evaluation/.
--
-- The practical implication of this difference is that due to the
-- /imprecise exceptions/ semantics,
--
-- > (return $! error "foo") >> error "bar"
--
-- may throw either @"foo"@ or @"bar"@, depending on the optimizations
-- performed by the compiler. On the other hand,
--
-- > evaluate (error "foo") >> error "bar"
--
-- is guaranteed to throw @"foo"@.
--
-- The rule of thumb is to use 'evaluate' to force or handle exceptions in
-- lazy values. If, on the other hand, you are forcing a lazy value for
-- efficiency reasons only and do not care about exceptions, you may
-- use @'return' '$!' x@.
evaluate :: a -> IO a
evaluate a = IO $ \s -> seq# a s -- NB. see #2273, #5129
|
urbanslug/ghc
|
libraries/base/GHC/IO.hs
|
bsd-3-clause
| 20,246 | 67 | 15 | 4,282 | 1,812 | 1,046 | 766 | 125 | 3 |
module Foo.Bar where
baz = 6
|
RefactoringTools/HaRe
|
test/testdata/cabal/cabal4/src/Foo/Bar.hs
|
bsd-3-clause
| 30 | 0 | 4 | 7 | 11 | 7 | 4 | 2 | 1 |
{-# LANGUAGE DeriveTraversable #-}
module T9069 where
import Data.Foldable
import Data.Traversable
data Trivial a = Trivial a
deriving (Functor,Foldable,Traversable)
|
olsner/ghc
|
testsuite/tests/deriving/should_compile/T9069.hs
|
bsd-3-clause
| 171 | 0 | 6 | 24 | 40 | 24 | 16 | 6 | 0 |
-- Problem 7
--Listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
--What is the 10001st prime number?
import Primes
euler7 = nthPrime 10001
nthPrime :: Int -> Int
nthPrime n = nthPrime' 0 n
nthPrime' :: Int -> Int -> Int
nthPrime' cur nth
| nth == 0 = cur
| otherwise = nthPrime' (nextPrime $ cur) (nth - 1)
|
RossMeikleham/Project-Euler-Haskell
|
07.hs
|
mit
| 368 | 0 | 8 | 87 | 98 | 50 | 48 | 8 | 1 |
-- | The Plan provides a notation to describe the simulated network
-- traffic in terms of Patterns and Activities.
module SyntheticWeb.Plan
( Plan (..)
, Bytes
, Weight (..)
, Pattern (..)
, Activity (..)
, Duration (..)
, Rate (..)
, Download (..)
, Upload (..)
, Size (..)
, Header (..)
, parsePlan
, writePlan
, toTuple
) where
import SyntheticWeb.Plan.Header
import SyntheticWeb.Plan.Parser
import SyntheticWeb.Plan.Types
import SyntheticWeb.Plan.Writer
|
kosmoskatten/synthetic-web
|
src/SyntheticWeb/Plan.hs
|
mit
| 572 | 0 | 5 | 183 | 116 | 81 | 35 | 19 | 0 |
{-# LANGUAGE ConstrainedClassMethods #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
module Yesod.Auth.Simple (
YesodAuthSimple(..),
authSimple,
loginR,
registerR,
setPasswordR,
resetPasswordR,
resetPasswordEmailSentR,
setPasswordTokenR,
confirmR,
userExistsR,
registerSuccessR,
confirmationEmailSentR
) where
import Prelude hiding (concat, length)
import Yesod.Auth
import qualified Data.Text.Encoding as TE
import qualified Crypto.Hash.MD5 as H
import Data.ByteString.Base16 as B16
import Data.Text.Encoding (encodeUtf8, decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Text (Text, unpack, pack, concat, splitOn, toLower, length)
import Yesod.Core
import qualified Crypto.PasswordStore as PS
import Text.Email.Validate (canonicalizeEmail)
import Yesod.Form
import Data.Time (UTCTime, getCurrentTime, addUTCTime, diffUTCTime)
import qualified Web.ClientSession as CS
import qualified Data.ByteString.Base64.URL as B64Url
import qualified Data.ByteString.Base64 as B64
import Data.ByteString (ByteString)
import Data.Maybe (fromJust)
import GHC.Generics
import Network.HTTP.Types (status400)
import Text.Blaze (toMarkup, Markup)
data Passwords = Passwords {
pass1 :: Text,
pass2 :: Text
} deriving (Show, Generic)
instance FromJSON Passwords
loginR :: AuthRoute
loginR = PluginR "simple" ["login"]
registerR :: AuthRoute
registerR = PluginR "simple" ["register"]
confirmationEmailSentR :: AuthRoute
confirmationEmailSentR = PluginR "simple" ["confirmation-email-sent"]
registerSuccessR :: AuthRoute
registerSuccessR = PluginR "simple" ["register-success"]
userExistsR :: AuthRoute
userExistsR = PluginR "simple" ["user-exists"]
confirmR :: Text -> AuthRoute
confirmR token = PluginR "simple" ["confirm", token]
setPasswordR :: AuthRoute
setPasswordR = PluginR "simple" ["set-password"]
setPasswordTokenR :: Text -> AuthRoute
setPasswordTokenR token = PluginR "simple" ["set-password", token]
resetPasswordR :: AuthRoute
resetPasswordR = PluginR "simple" ["reset-password"]
resetPasswordEmailSentR :: AuthRoute
resetPasswordEmailSentR = PluginR "simple" ["reset-password-email-sent"]
type Email = Text
type VerUrl = Text
type SaltedPass = Text
class (YesodAuth site, PathPiece (AuthSimpleId site) ) => YesodAuthSimple site where
type AuthSimpleId site
sendVerifyEmail :: Email -> VerUrl -> AuthHandler site ()
sendVerifyEmail = printVerificationEmail
sendResetPasswordEmail :: Email -> VerUrl -> AuthHandler site ()
sendResetPasswordEmail = printResetPasswordEmail
getUserId :: Email -> AuthHandler site (Maybe (AuthSimpleId site))
getUserPassword :: AuthSimpleId site -> AuthHandler site SaltedPass
getUserModified :: AuthSimpleId site -> AuthHandler site UTCTime
insertUser :: Email -> Text -> AuthHandler site (Maybe (AuthSimpleId site))
updateUserPassword :: AuthSimpleId site -> Text -> AuthHandler site ()
afterPasswordRoute :: site -> Route site
loginTemplate :: Maybe Text -> WidgetFor site ()
registerTemplate :: Maybe Text -> WidgetFor site ()
resetPasswordTemplate :: Maybe Text -> WidgetFor site ()
confirmTemplate :: Route site -> Email -> Maybe Text -> WidgetFor site ()
confirmationEmailSentTemplate :: WidgetFor site ()
resetPasswordEmailSentTemplate :: WidgetFor site ()
registerSuccessTemplate :: WidgetFor site ()
userExistsTemplate :: WidgetFor site ()
invalidTokenTemplate :: Text -> WidgetFor site ()
setPasswordTemplate :: Route site -> Maybe Text -> WidgetFor site ()
onPasswordUpdated :: AuthHandler site ()
onPasswordUpdated = setMessage "Password has been updated"
loginHandlerRedirect :: (Route Auth -> Route site) -> WidgetFor site ()
loginHandlerRedirect toParent = redirectTemplate toParent
authSimple :: YesodAuthSimple m => AuthPlugin m
authSimple = AuthPlugin "simple" dispatch loginHandlerRedirect
dispatch :: YesodAuthSimple master => Text -> [Text] -> AuthHandler master TypedContent
dispatch "GET" ["register"] = getRegisterR >>= sendResponse
dispatch "POST" ["register"] = postRegisterR >>= sendResponse
dispatch "GET" ["confirm", token] = getConfirmR token >>= sendResponse
dispatch "POST" ["confirm", token] = postConfirmR token >>= sendResponse
dispatch "GET" ["confirmation-email-sent"] = getConfirmationEmailSentR >>= sendResponse
dispatch "GET" ["register-success"] = getRegisterSuccessR >>= sendResponse
dispatch "GET" ["user-exists"] = getUserExistsR >>= sendResponse
dispatch "GET" ["login"] = getLoginR >>= sendResponse
dispatch "POST" ["login"] = postLoginR >>= sendResponse
dispatch "GET" ["set-password"] = getSetPasswordR >>= sendResponse
dispatch "PUT" ["set-password"] = putSetPasswordR >>= sendResponse
dispatch "GET" ["set-password", token] = getSetPasswordTokenR token >>= sendResponse
dispatch "PUT" ["set-password", token] = putSetPasswordTokenR token >>= sendResponse
dispatch "GET" ["reset-password"] = getResetPasswordR >>= sendResponse
dispatch "POST" ["reset-password"] = postResetPasswordR >>= sendResponse
dispatch "GET" ["reset-password-email-sent"] = getResetPasswordEmailSentR >>= sendResponse
dispatch _ _ = notFound
getRegisterR :: YesodAuthSimple master => AuthHandler master Html
getRegisterR = do
mErr <- getError
authLayout $ do
setTitle $ addDomainToTitle "Register a new account"
registerTemplate mErr
getResetPasswordR :: YesodAuthSimple master => AuthHandler master Html
getResetPasswordR = do
mErr <- getError
authLayout $ do
setTitle $ addDomainToTitle "Reset password"
resetPasswordTemplate mErr
getLoginR :: YesodAuthSimple master => AuthHandler master Html
getLoginR = do
mErr <- getError
authLayout $ do
setTitle $ addDomainToTitle "Login"
loginTemplate mErr
postRegisterR :: YesodAuthSimple master => AuthHandler master Html
postRegisterR = do
clearError
email <- runInputPost $ ireq textField "email"
mEmail <- validateAndNormalizeEmail email
tp <- getRouteToParent
case mEmail of
Just email' -> do
token <- liftIO $ encryptRegisterToken email'
renderUrl <- getUrlRender
let url = renderUrl $ tp $ confirmR token
sendVerifyEmail email' url
redirect $ tp $ confirmationEmailSentR
Nothing -> do
setError "Invalid email address"
redirect $ tp $ registerR
postResetPasswordR :: YesodAuthSimple master => AuthHandler master Html
postResetPasswordR = do
clearError
email <- runInputPost $ ireq textField "email"
mUid <- getUserId $ normalizeEmail email
tp <- getRouteToParent
case mUid of
Just uid -> do
modified <- getUserModified uid
token <- encryptPasswordResetToken uid modified
renderUrl <- getUrlRender
let url = renderUrl $ tp $ setPasswordTokenR token
sendResetPasswordEmail email url
redirect $ tp $ resetPasswordEmailSentR
Nothing -> do
setError "Email not found"
redirect $ tp $ resetPasswordR
getConfirmR :: YesodAuthSimple master => Text -> AuthHandler master Html
getConfirmR token = do
res <- liftIO $ verifyRegisterToken token
case res of
Left msg -> invalidTokenHandler msg
Right email -> confirmHandlerHelper token email
invalidTokenHandler :: YesodAuthSimple master => Text -> AuthHandler master Html
invalidTokenHandler msg =
authLayout $ do
setTitle $ addDomainToTitle "Invalid key"
invalidTokenTemplate msg
confirmHandlerHelper :: YesodAuthSimple master => Text -> Email -> AuthHandler master Html
confirmHandlerHelper token email = do
tp <- getRouteToParent
confirmHandler (tp $ confirmR token) email
confirmHandler :: YesodAuthSimple master => Route master -> Email -> AuthHandler master Html
confirmHandler registerUrl email = do
mErr <- getError
authLayout $ do
setTitle $ addDomainToTitle "Confirm account"
confirmTemplate registerUrl email mErr
postConfirmR :: YesodAuthSimple master => Text -> AuthHandler master Html
postConfirmR token = do
clearError
(pass1, pass2) <- runInputPost $ (,)
<$> ireq textField "password1"
<*> ireq textField "password2"
res <- liftIO $ verifyRegisterToken token
case res of
Left msg -> invalidTokenHandler msg
Right email -> createUser token email pass1 pass2
createUser :: YesodAuthSimple master => Text -> Email -> Text -> Text -> AuthHandler master Html
createUser token email pass1 pass2
| pass1 /= pass2 = do
setError "Passwords does not match"
confirmHandlerHelper token email
| otherwise = do
case checkPasswordStrength pass1 of
Left msg -> do
setError msg
confirmHandlerHelper token email
Right _ -> do
salted <- liftIO $ saltPass pass1
mUid <- insertUser email salted
tp <- getRouteToParent
case mUid of
Just uid -> do
let creds = Creds "simple" (toPathPiece uid) []
setCreds False creds
redirect $ tp $ registerSuccessR
Nothing ->
redirect $ tp $ userExistsR
getConfirmationEmailSentR :: YesodAuthSimple master => AuthHandler master Html
getConfirmationEmailSentR = do
authLayout $ do
setTitle $ addDomainToTitle "Confirmation email sent"
confirmationEmailSentTemplate
getResetPasswordEmailSentR :: YesodAuthSimple master => AuthHandler master Html
getResetPasswordEmailSentR = do
authLayout $ do
setTitle $ addDomainToTitle "Reset password email sent"
resetPasswordEmailSentTemplate
getRegisterSuccessR :: YesodAuthSimple master => AuthHandler master Html
getRegisterSuccessR = do
authLayout $ do
setTitle $ addDomainToTitle "Account created"
registerSuccessTemplate
getUserExistsR :: YesodAuthSimple master => AuthHandler master Html
getUserExistsR = do
authLayout $ do
setTitle $ addDomainToTitle "User already exists"
userExistsTemplate
checkPasswordStrength :: Text -> Either Text ()
checkPasswordStrength x
| length x >= 6 = Right ()
| otherwise = Left "Password must be at least six characters"
normalizeEmail :: Text -> Text
normalizeEmail = toLower
validateAndNormalizeEmail :: YesodAuthSimple master => Text -> AuthHandler master (Maybe Text)
validateAndNormalizeEmail email = do
case canonicalizeEmail $ encodeUtf8 email of
Just bytes ->
return $ Just $ normalizeEmail $ decodeUtf8With lenientDecode bytes
Nothing -> return Nothing
getError :: YesodAuthSimple master => AuthHandler master (Maybe Text)
getError = do
mErr <- lookupSession "error"
clearError
return mErr
setError :: YesodAuthSimple master => Text -> AuthHandler master ()
setError = setSession "error"
clearError :: YesodAuthSimple master => AuthHandler master ()
clearError = deleteSession "error"
postLoginR :: YesodAuthSimple master => AuthHandler master TypedContent
postLoginR = do
clearError
(email, pass) <- runInputPost $ (,)
<$> ireq textField "email"
<*> ireq textField "password"
mUid <- getUserId email
case mUid of
Just uid -> do
realPass <- getUserPassword uid
case isValidPass pass realPass of
True -> do
let creds = Creds "simple" (toPathPiece uid) []
setCredsRedirect creds
False -> wrongEmailOrPasswordRedirect
_ -> wrongEmailOrPasswordRedirect
wrongEmailOrPasswordRedirect :: YesodAuthSimple master => AuthHandler master TypedContent
wrongEmailOrPasswordRedirect = do
tp <- getRouteToParent
setError "Wrong email or password"
redirect $ tp $ loginR
requireUserId :: YesodAuthSimple master => AuthHandler master (AuthId master)
requireUserId = do
mUid <- maybeAuthId
tp <- getRouteToParent
case mUid of
Just uid -> return uid
Nothing -> redirect $ tp $ loginR
toSimpleAuthId :: forall c a. (PathPiece c, PathPiece a) => a -> c
toSimpleAuthId = fromJust . fromPathPiece . toPathPiece
getSetPasswordR :: YesodAuthSimple master => AuthHandler master Html
getSetPasswordR = do
_ <- requireUserId
tp <- getRouteToParent
mErr <- getError
authLayout $ do
setTitle $ addDomainToTitle "Set password"
setPasswordTemplate (tp setPasswordR) mErr
getSetPasswordTokenR :: YesodAuthSimple master => Text -> AuthHandler master Html
getSetPasswordTokenR token = do
res <- verifyPasswordResetToken token
case res of
Left msg -> invalidTokenHandler msg
Right _ -> do
tp <- getRouteToParent
mErr <- getError
authLayout $ do
setTitle $ addDomainToTitle "Set password"
setPasswordTemplate (tp $ setPasswordTokenR token) mErr
putSetPasswordTokenR :: YesodAuthSimple master => Text -> AuthHandler master Value
putSetPasswordTokenR token = do
clearError
passwords <- requireCheckJsonBody :: AuthHandler master Passwords
res <- verifyPasswordResetToken token
case res of
Left msg -> sendResponseStatus status400 $ object ["message" .= msg]
Right uid -> setPassword uid passwords
putSetPasswordR :: YesodAuthSimple master => AuthHandler master Value
putSetPasswordR = do
clearError
uid <- requireUserId
passwords <- requireCheckJsonBody :: AuthHandler master Passwords
setPassword (toSimpleAuthId uid) passwords
setPassword :: YesodAuthSimple master => AuthSimpleId master -> Passwords -> AuthHandler master Value
setPassword uid passwords
| (pass1 passwords) /= (pass2 passwords) = do
let msg = "Passwords does not match" :: Text
sendResponseStatus status400 $ object ["message" .= msg]
| otherwise = do
case checkPasswordStrength (pass1 passwords) of
Left msg ->
sendResponseStatus status400 $ object ["message" .= msg]
Right _ -> do
salted <- liftIO $ saltPass (pass1 passwords)
_ <- updateUserPassword uid salted
onPasswordUpdated
let creds = Creds "simple" (toPathPiece uid) []
setCreds False creds
return $ object []
saltLength :: Int
saltLength = 5
-- | Salt a password with a randomly generated salt.
saltPass :: Text -> IO Text
saltPass = fmap (decodeUtf8With lenientDecode)
. flip PS.makePassword 17
. encodeUtf8
saltPass' :: String -> String -> String
saltPass' salt pass =
salt ++ unpack (TE.decodeUtf8 $ B16.encode $ H.hash $ TE.encodeUtf8 $ pack $ salt ++ pass)
isValidPass :: Text -- ^ cleartext password
-> SaltedPass -- ^ salted password
-> Bool
isValidPass ct salted =
PS.verifyPassword (encodeUtf8 ct) (encodeUtf8 salted) || isValidPass' ct salted
isValidPass' :: Text -- ^ cleartext password
-> SaltedPass -- ^ salted password
-> Bool
isValidPass' clear' salted' =
let salt = take saltLength salted
in salted == saltPass' salt clear
where
clear = unpack clear'
salted = unpack salted'
verifyRegisterToken :: Text -> IO (Either Text Email)
verifyRegisterToken token = do
res <- decryptRegisterToken token
case res of
Left msg -> return $ Left msg
Right (expires, email) -> do
now <- getCurrentTime
case diffUTCTime expires now > 0 of
True -> return $ Right email
False -> return $ Left "Verification key has expired"
verifyPasswordResetToken :: YesodAuthSimple master => Text -> AuthHandler master (Either Text (AuthSimpleId master))
verifyPasswordResetToken token = do
res <- decryptPasswordResetToken token
case res of
Left msg -> return $ Left msg
Right (expires, modified, uid) -> do
modifiedCurrent <- getUserModified uid
now <- liftIO getCurrentTime
case diffUTCTime expires now > 0 && modified == modifiedCurrent of
True -> return $ Right uid
False -> return $ Left "Key has expired"
getDefaultKey :: IO CS.Key
getDefaultKey = CS.getKey "config/client_session_key.aes"
encryptPasswordResetToken :: YesodAuthSimple master => AuthSimpleId master -> UTCTime -> AuthHandler master Text
encryptPasswordResetToken uid modified = do
expires <- liftIO $ addUTCTime 3600 <$> getCurrentTime
key <- liftIO $ getDefaultKey
let cleartext = concat [pack $ show expires, "|", pack $ show modified, "|", toPathPiece uid]
ciphertext <- liftIO $ CS.encryptIO key $ encodeUtf8 cleartext
return $ encodeToken ciphertext
decryptPasswordResetToken :: YesodAuthSimple master => Text -> AuthHandler master (Either Text (UTCTime, UTCTime, AuthSimpleId master))
decryptPasswordResetToken ciphertext = do
key <- liftIO getDefaultKey
case CS.decrypt key (decodeToken ciphertext) of
Just bytes -> do
let cleartext = decodeUtf8With lenientDecode bytes
let [expires, modified, uid] = splitOn "|" cleartext
return $ Right (
read $ unpack expires :: UTCTime,
read $ unpack modified :: UTCTime,
fromJust $ fromPathPiece uid)
Nothing ->
return $ Left "Failed to decode key"
encryptRegisterToken :: Email -> IO Text
encryptRegisterToken email = do
expires <- addUTCTime 86400 <$> getCurrentTime
key <- getDefaultKey
let cleartext = concat [pack $ show expires, "|", email]
ciphertext <- CS.encryptIO key $ encodeUtf8 cleartext
return $ encodeToken ciphertext
decryptRegisterToken :: Text -> IO (Either Text (UTCTime, Email))
decryptRegisterToken ciphertext = do
key <- getDefaultKey
case CS.decrypt key (decodeToken ciphertext) of
Just bytes -> do
let cleartext = decodeUtf8With lenientDecode bytes
let [expires, email] = splitOn "|" cleartext
return $ Right (read $ unpack expires :: UTCTime, email)
Nothing ->
return $ Left "Failed to decode key"
-- Re-encode to url-safe base64
encodeToken :: ByteString -> Text
encodeToken = decodeUtf8With lenientDecode . B64Url.encode . B64.decodeLenient
-- Re-encode to regular base64
decodeToken :: Text -> ByteString
decodeToken = B64.encode . B64Url.decodeLenient . encodeUtf8
printVerificationEmail :: YesodAuthSimple master => Email -> VerUrl -> AuthHandler master ()
printVerificationEmail email verurl =
liftIO $ putStrLn $ unpack $ concat ["Sending verify email to: ", email, " url: ", verurl]
printResetPasswordEmail :: YesodAuthSimple master => Email -> VerUrl -> AuthHandler master ()
printResetPasswordEmail email verurl =
liftIO $ putStrLn $ unpack $ concat ["Sending reset password email to: ", email, " url: ", verurl]
redirectTemplate :: YesodAuthSimple master => (Route Auth -> Route master) -> WidgetFor master ()
redirectTemplate toParent =
[whamlet|$newline never
<script>window.location = "@{toParent loginR}";
<p>Content has moved, click
<a href="@{toParent loginR}">here
|]
-- TODO: Get this function through a type class method or something
addDomainToTitle :: Text -> Markup
addDomainToTitle title = toMarkup $ title <> " - glot.io"
|
prasmussen/glot-www
|
Yesod/Auth/Simple.hs
|
mit
| 19,722 | 0 | 23 | 4,506 | 5,142 | 2,508 | 2,634 | 437 | 3 |
module Grammar.Greek.Morph.ShouldElide.Round where
import Control.Lens (over)
import Data.Either.Validation
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Grammar.Common
import Grammar.Greek.Morph.Aspirate
import Grammar.Greek.Morph.Forms.Eliding
import Grammar.Greek.Morph.Types
import Grammar.Greek.Script.Types
import Grammar.Greek.Script.Word
data InvalidElisionForm =
InvalidElisionForm (CoreWord :* Elision :* InitialAspiration)
deriving (Show)
data InvalidElisionCandidate =
InvalidElisionCandidate (CoreWord :* ShouldElide :* InitialAspiration)
deriving (Show)
elide
:: CoreWord :* InitialAspiration
-> CoreWord :* InitialAspiration
elide (CoreWord asp ss [] :^ nasp) | ((Syllable fc _) : rss) <- reverse ss = CoreWord asp (reverse rss) (f fc) :^ nasp
where
f = case nasp of
HasInitialAspiration -> aspirateList
NoInitialAspiration -> id
elide x = x
reverseElisionForms :: Map
(CoreWord :* InitialAspiration)
(CoreWord :* InitialAspiration)
reverseElisionForms = Map.fromList $ do
ws <- elidingForms
nasp <- [ NoInitialAspiration, HasInitialAspiration ]
let form = ws :^ nasp
return (elide form, form)
shouldElide :: Round InvalidElisionForm InvalidElisionCandidate
(CoreWord :* Elision :* InitialAspiration)
(CoreWord :* ShouldElide :* InitialAspiration)
shouldElide = Round (over _Failure pure . to) (over _Failure pure . from)
where
to (w :^ IsElided :^ nasp)
| Just (w' :^ nasp') <- Map.lookup (w :^ nasp) reverseElisionForms
= Success $ w' :^ ShouldElide :^ nasp'
to (w :^ NotElided :^ nasp) = Success $ w :^ ShouldNotElide :^ nasp
to x = Failure $ InvalidElisionForm x
from (w :^ ShouldElide :^ nasp) =
let w' :^ nasp' = elide $ w :^ nasp
in Success $ w' :^ IsElided :^ nasp'
from (w :^ ShouldNotElide :^ nasp) = Success $ w :^ NotElided :^ nasp
from x = Failure $ InvalidElisionCandidate x
|
ancientlanguage/haskell-analysis
|
greek-morph/src/Grammar/Greek/Morph/ShouldElide/Round.hs
|
mit
| 1,910 | 0 | 13 | 330 | 630 | 335 | 295 | -1 | -1 |
module Val where
import Data.List
import Language
import Parser
import Heap
fst3 (a, b, c) = a
snd3 (a, b, c) = b
thrd3 (a, b, c) = c
data Point4 = Top4 --All elements and entire spine defined
| SpineStrict --Entire Spine defined, but some elements may be _|_
| Inf --Spine either has a bottom or is infinite
| Bottom4 --No elements and no spine
deriving Show
data Val = Top | Bottom --For Flat Domains
| Val4 Point4 --For Lists
| Var String --Variables in expressions
| Fun String --Function names
| Constr Int Int [Val] --Constructors
| Ap Val [Val] --Vectorised Applications
| Let Bool [(String, Val)] Val
| Case Val [VAlt]
deriving Show
type VAlt = (Int, [String], Val)
--Apply a function to the next level 'down' of an expression
descendVal :: (Val -> Val) -> Val -> Val
descendVal f (Constr t a flds) = Constr t a $ map f flds
descendVal f (Ap a bs) = Ap (f a) (map f bs)
descendVal f (Let is bndgs expr) = Let is bndgs' (f expr)
where bndgs' = [(n, f rhs) | (n, rhs) <- bndgs]
descendVal f (Case sub alts) = Case (f sub) alts'
where alts' = [(i, args, f expr) | (i, args, expr) <- alts]
descendVal f e = e
--All the free variables of an Expression
freeVariables :: Val -> [String]
freeVariables val = nub $ go [] val
where
go vars (Case e alts) = go vars e ++ concat [go (snd3 alt ++ vars) (thrd3 alt) | alt <- alts]
go vars (Let ir bnds expr) = let newVars = map fst bnds ++ vars
in go newVars expr ++ concatMap (go newVars . snd) bnds
go vars (Var name) = [name | name `notElem` vars]
go vars (Ap a bs) = go vars a ++ concatMap (go vars) bs
go vars e = vars
|
jmct/IterativeCompiler
|
frontend/Val.hs
|
mit
| 1,855 | 0 | 13 | 607 | 667 | 363 | 304 | 39 | 5 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ExistentialQuantification #-}
-- |
-- Module : System.Wlog.Parser
-- Copyright : (c) Serokell, 2016
-- License : GPL-3 (see the file LICENSE)
-- Maintainer : Serokell <[email protected]>
-- Stability : experimental
-- Portability : POSIX, GHC
--
-- Parser for configuring and initializing logger from YAML file.
-- Logger configuration should look like this:
--
-- > rotation: # [optional] parameters for logging rotation
-- > logLimit: 1024 # max size of log file in bytes
-- > keepFiles: 3 # number of files with logs to keep including current one
-- > loggerTree:
-- > severity: Warning+ # severities for «root» logger
-- > node: # logger named «node»
-- > severity: Warning+ # severities for logger «node»
-- > comm: # logger named «node.comm»
-- > severity: Info+ # severity for logger «node.comm»
-- > file: patak.jpg # messages will be also printed to patak.jpg
--
-- And this configuration corresponds two loggers with 'LoggerName'`s
-- @node@ and @node.comm@.
module System.Wlog.Launcher
( buildAndSetupYamlLogging
, defaultConfig
, launchFromFile
, launchSimpleLogging
, launchWithConfig
, parseLoggerConfig
, setupLogging
) where
import Universum
import Control.Exception (throwIO)
import Data.Time (UTCTime)
import Data.Yaml (decodeFileEither)
import Lens.Micro.Platform (zoom, (.=), (?=))
import System.Directory (createDirectoryIfMissing)
import System.FilePath ((</>))
import System.Wlog.Formatter (centiUtcTimeF, stdoutFormatter, stdoutFormatterTimeRounded)
import System.Wlog.IOLogger (addHandler, removeAllHandlers, setPrefix, setSeveritiesMaybe,
updateGlobalLogger)
import System.Wlog.LoggerConfig (HandlerWrap (..), LoggerConfig (..), LoggerTree (..), fromScratch,
lcConsoleAction, lcShowTime, lcTree, ltSeverity, productionB,
zoomLogger)
import System.Wlog.LoggerName (LoggerName)
import System.Wlog.LoggerNameBox (LoggerNameBox, usingLoggerName)
import System.Wlog.LogHandler (LogHandler (setFormatter))
import System.Wlog.LogHandler.Roller (rotationFileHandler)
import System.Wlog.LogHandler.Simple (defaultHandleAction, fileHandler)
import System.Wlog.Severity (Severities, debugPlus, warningPlus)
import System.Wlog.Terminal (initTerminalLogging)
import qualified Data.HashMap.Strict as HM hiding (HashMap)
data HandlerFabric
= forall h . LogHandler h => HandlerFabric (FilePath -> Severities -> IO h)
-- | This function traverses 'LoggerConfig' initializing all subloggers
-- with 'Severities' and redirecting output in file handlers.
-- See 'LoggerConfig' for more details.
setupLogging :: MonadIO m => Maybe (UTCTime -> Text) -> LoggerConfig -> m ()
setupLogging mTimeFunction LoggerConfig{..} = do
liftIO $ createDirectoryIfMissing True handlerPrefix
whenJust consoleAction $ \customTerminalAction ->
initTerminalLogging timeF
customTerminalAction
isShowTime
isShowTid
_lcTermSeverityOut
_lcTermSeverityErr
liftIO $ setPrefix _lcLogsDirectory
processLoggers mempty _lcTree
where
handlerPrefix = fromMaybe "." _lcLogsDirectory
logMapper = appEndo _lcMapper
timeF = fromMaybe centiUtcTimeF mTimeFunction
isShowTime = getAny _lcShowTime
isShowTid = getAny _lcShowTid
consoleAction = getLast _lcConsoleAction
handlerFabric :: HandlerFabric
handlerFabric = case _lcRotation of
Nothing -> HandlerFabric fileHandler
Just rot -> HandlerFabric $ rotationFileHandler rot
processLoggers :: MonadIO m => LoggerName -> LoggerTree -> m ()
processLoggers parent LoggerTree{..} = do
-- This prevents logger output to appear in terminal
unless (parent == mempty && isNothing consoleAction) $
setSeveritiesMaybe parent _ltSeverity
forM_ _ltFiles $ \HandlerWrap{..} -> liftIO $ do
let fileSeverities = fromMaybe debugPlus _ltSeverity
let handlerPath = handlerPrefix </> _hwFilePath
case handlerFabric of
HandlerFabric fabric -> do
let handlerCreator = fabric handlerPath fileSeverities
let defFmt = (`setFormatter` stdoutFormatter timeF isShowTime isShowTid)
let roundFmt r = (`setFormatter` stdoutFormatterTimeRounded timeF r)
let fmt = maybe defFmt roundFmt _hwRounding
thisLoggerHandler <- fmt <$> handlerCreator
updateGlobalLogger parent $ addHandler thisLoggerHandler
for_ (HM.toList _ltSubloggers) $ \(loggerName, loggerConfig) -> do
let thisLogger = parent <> logMapper loggerName
processLoggers thisLogger loggerConfig
-- | Parses logger config from given file path.
parseLoggerConfig :: MonadIO m => FilePath -> m LoggerConfig
parseLoggerConfig loggerConfigPath =
liftIO $ join $ either throwIO return <$> decodeFileEither loggerConfigPath
-- | Applies given builder to parsed logger config and initializes logging.
buildAndSetupYamlLogging :: MonadIO m => LoggerConfig -> FilePath -> m ()
buildAndSetupYamlLogging configBuilder loggerConfigPath = do
cfg@LoggerConfig{..} <- parseLoggerConfig loggerConfigPath
let builtConfig = cfg <> configBuilder
setupLogging Nothing builtConfig
-- | Sets up given logging configurations,
-- runs the action with the given 'LoggerName'.
launchWithConfig :: (MonadIO m, MonadMask m)
=> LoggerConfig
-> LoggerName
-> LoggerNameBox m a
-> m a
launchWithConfig config loggerName action =
bracket_
(setupLogging Nothing config)
removeAllHandlers
(usingLoggerName loggerName action)
-- | Initializes logging using given 'FilePath' to logger configurations,
-- runs the action with the given 'LoggerName'.
launchFromFile :: (MonadIO m, MonadMask m)
=> FilePath
-> LoggerName
-> LoggerNameBox m a
-> m a
launchFromFile filename loggerName action =
bracket_
(buildAndSetupYamlLogging productionB filename)
removeAllHandlers
(usingLoggerName loggerName action)
{- | Default logging configuration with the given 'LoggerName'.
Enabled flags:
- 'ltSeverity' of the root logger is set to 'warningPlus'
('System.Wlog.Severity.Warning' and upper)
- 'ltSeverity' for the given logger is set to 'debugPlus' ('System.Wlog.Severity.Debug' and upper)
- 'lcShowTime' is set to 'Any True' which means that time is shown in the log messages.
- 'lcConsoleAction' is set to 'defaultHandleAction' which turns the console output on.
==== __/Example/__
@ defaultConfig "example"@ will produce such configurations:
@
rotation: null
showTid: false
showTime: true
printOutput: true
logTree:
_ltSubloggers:
example:
_ltSubloggers: {}
_ltSeverity:
- Debug
- Info
- Notice
- Warning
- Error
_ltFiles: []
_ltSeverity:
- Warning
- Error
_ltFiles: []
termSeveritiesOut: null
filePrefix: null
termSeveritiesErr: null
@
-}
defaultConfig :: LoggerName -> LoggerConfig
defaultConfig loggerName = fromScratch $ do
lcShowTime .= Any True
lcConsoleAction .= Last (Just defaultHandleAction)
zoom lcTree $ do
ltSeverity ?= warningPlus
zoomLogger loggerName $
ltSeverity ?= debugPlus
{- | Set ups the logging with 'defaultConfig' and runs the action with the given 'LoggerName'.
==== __/Example/__
Here we can see very simple working example of logging:
@
ghci> __:{__
ghci| __launchSimpleLogging "app" $ do__
ghci| __logDebug "Debug message"__
ghci| __putStrLn "Usual printing"__
ghci| __logInfo "Job's done!"__
ghci| __:}__
[app:DEBUG] [2017-12-07 11:25:06.47 UTC] Debug message
Usual printing
[app:INFO] [2017-12-07 11:25:06.47 UTC] Job's done!
@
-}
launchSimpleLogging :: (MonadIO m, MonadMask m)
=> LoggerName
-> LoggerNameBox m a
-> m a
launchSimpleLogging loggerName = launchWithConfig (defaultConfig loggerName) loggerName
|
serokell/log-warper
|
src/System/Wlog/Launcher.hs
|
mit
| 8,527 | 0 | 23 | 2,167 | 1,276 | 683 | 593 | -1 | -1 |
-- code related to Loday's "Arithmetree"
module Loday where
import Data.List
import Bijections
import Catalan
import Tamari
import Permutohedra
import qualified Lambda as Lam
lsumv :: Tree -> Tree -> [Tree]
rsumv :: Tree -> Tree -> [Tree]
sumv :: Tree -> Tree -> [Tree]
lsumv x L = [x]
lsumv (B xL xR) y = [B xL z | z <- sumv xR y]
lsumv L y = [] -- [y]
rsumv L y = [y]
rsumv x (B yL yR) = [B z yR | z <- sumv x yL]
rsumv x L = [] -- [x]
sumv x y = union (lsumv x y) (rsumv x y)
lsumt :: [Tree] -> [Tree] -> [Tree]
rsumt :: [Tree] -> [Tree] -> [Tree]
sumt :: [Tree] -> [Tree] -> [Tree]
lsumt xs ys = foldr union [] [lsumv x y | x <- xs, y <- ys]
rsumt xs ys = foldr union [] [rsumv x y | x <- xs, y <- ys]
sumt xs ys = foldr union [] [sumv x y | x <- xs, y <- ys]
tol (Lam.TVar _) = [B L L]
tol (Lam.TFn a b) = lsumt (tor a) (tol b)
tor (Lam.TVar _) = [B L L]
tor (Lam.TFn a b) = rsumt (tor b) (tol a)
conj30 :: Int -> [Int]
conj30 n =
let ts = Lam.allcNPTnb True (n+1) in
let tps = map Lam.synthClosedNormal ts in
map (\t -> length (tol t)) tps
toVec :: Tree -> [Int]
toVec L = []
toVec (B t1 t2) =
let w1 = toVec t1 in
let w2 = toVec t2 in
let i = length w1 in
let j = length w2 in
let n = i+j in
w1 ++ [n+1] ++ map (+i) w2
toPerm :: Tree -> Perm
toPerm t = zip [1..nodes t] (toVec t)
-- from Aguiar and Livernet, "The associative operad and the weak order on the symmetric groups"
fromPerm :: Perm -> Tree
fromPerm [] = L
fromPerm p =
let n = length (dom p) in
let j = act (inv p) n in
let w = map (act p) [1..n] in
let (wL,_:wR) = splitAt (j-1) w in
B (fromPerm $ stdToPerm $ stdize wL) (fromPerm $ stdToPerm $ stdize wR)
-- [length $ [(t1,t2) | t1 <- binary_trees n, t2 <- binary_trees n, perm_le (toPerm t1) (toPerm t2)] | n <- [0..]] == [1,1,3,13,68,399,2530,...] == A000260
-- [length $ [(w,t) | w <- permute [1..n], t <- binary_trees n, perm_le w (toPerm t)] | n <- [0..]] == [1,1,3,14,85,621,5236,...] == A088716?
-- [length $ [(t,w) | w <- permute [1..n], t <- binary_trees n, perm_le (toPerm t) w] | n <- [0..]] == [1,1,3,15,105,945,10395,...] == A001147?
-- [length $ [(w,t) | w <- permute [1..n], t <- binary_trees n, tamari_seq [] (fromPerm w) t] | n <- [0..]] == [1,1,3,15,105,945,10395,...] == A001147?
|
noamz/linlam-gos
|
src/Loday.hs
|
mit
| 2,265 | 0 | 18 | 526 | 972 | 496 | 476 | 51 | 1 |
module ProjectEuler.Problem77
( problem
) where
import Petbox
import Math.NumberTheory.Primes.Testing (isPrime)
import ProjectEuler.Types
problem :: Problem
problem = pureProblem 77 Solved result
numParts :: Int -> Int -> [ [Int] ]
numParts m n
| n > m = []
| n == m = [ [n] | isPrime (fromIntegral m)]
| not (isPrime (fromIntegral n)) = []
| otherwise = do
n' <- takeWhile (<= n) primes
xs <- numParts (m-n) n'
pure $ n:xs
countParts :: Int -> [] [Int]
countParts x = [1..x] >>= numParts x
result :: Int
result = firstSuchThat ((> 5000) . length . countParts) [1..]
|
Javran/Project-Euler
|
src/ProjectEuler/Problem77.hs
|
mit
| 617 | 0 | 12 | 152 | 272 | 142 | 130 | 20 | 1 |
{-# LANGUAGE OverloadedStrings, TypeSynonymInstances, FlexibleInstances #-}
module Galua.Debugger.PrettySource
( Line, lexChunk, omittedLine
, NameId(..), LocatedExprName
, lineToJSON
) where
import AlexTools(Lexeme(..))
import Language.Lua.Annotated.Lexer
( llexNamedWithWhiteSpace,SourcePos(..),SourceRange(..)
, dropWhiteSpace )
import Language.Lua.Annotated.Parser(parseTokens,chunk)
import qualified Language.Lua.Token as L
import Galua.FunId(FunId)
import Galua.Names.Find (chunkLocations,LocatedExprName(..))
import Galua.Debugger.View.Utils (exportFID)
import Data.Function(on)
import Data.List(groupBy,sortBy)
import qualified Data.ByteString as BS
import Data.Vector (Vector)
import qualified Data.Vector as Vector
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Text.Encoding(decodeUtf8With)
import Data.Text.Encoding.Error(lenientDecode)
import qualified Data.Aeson as JS
import Data.Aeson (ToJSON(..), (.=))
type LexToken = Lexeme L.Token
newtype Line = Line [Token]
deriving Show
data Token = Token TokenType -- What sort of token is this
Text -- The actual text of the token
(Maybe NameId) -- A name token, may refer to stuff
[NameId] -- Part of these names
(Maybe FunId) -- Does it refer to a function
deriving Show
data TokenType = Keyword | Operator | Symbol | Ident | Literal
| Comment | WhiteSpace | Error
deriving Show
omittedLine :: Line
omittedLine = Line [Token Comment "..." Nothing [] Nothing]
lexChunk :: Int -> String -> BS.ByteString ->
(Vector Line, Map NameId LocatedExprName)
lexChunk chunkId name bytes =
( Vector.fromList
$ map (Line . map token)
$ groupBy ((==) `on` aTokLine)
$ addFunIds functionNames
$ addNames names
$ concatMap splitTok
$ tokens
, nameMap
)
where
txt = decodeUtf8With lenientDecode bytes
tokens = llexNamedWithWhiteSpace name txt
(flatNames, functionNames) =
case parseTokens chunk (dropWhiteSpace tokens) of
Left _err -> ([],[])
Right b -> chunkLocations chunkId b
names = map (sortBy (compare `on` endIx))
$ groupBy ((==) `on` startIx)
$ sortBy (compare `on` startIx) flatNames
nameMap = Map.fromList [ (nameId x, x) | x <- flatNames ]
class Rng t where
getRange :: t -> SourceRange
instance Rng LexToken where
getRange = lexemeRange
instance Rng LocatedExprName where
getRange = exprPos
instance Rng AnnotToken where
getRange (AnnotToken a _ _ _) = getRange a
startIx :: Rng t => t -> Int
startIx = sourceIndex . sourceFrom . getRange
endIx :: Rng t => t -> Int
endIx = sourceIndex . sourceTo . getRange
data AnnotToken = AnnotToken LexToken (Maybe NameId) [NameId] (Maybe FunId)
aTokLine :: AnnotToken -> Int
aTokLine = sourceLine . sourceFrom . getRange
-- | Identifies a specific occurance of a name.
-- We use the start and end character positions to identify the name.
-- Note that something like @a.b.c@ is also considered a name, so
-- names may be nested.
data NameId = NameId !Int !Int
deriving (Show,Eq,Ord)
nameId :: LocatedExprName -> NameId
nameId e = NameId (startIx e) (endIx e)
setFunId :: FunId -> AnnotToken -> AnnotToken
setFunId funId (AnnotToken a b c _) = AnnotToken a b c (Just funId)
addFunIds :: [FunId] -> [AnnotToken] -> [AnnotToken]
addFunIds [] ys = ys
addFunIds _ [] = [] -- not good, but keep going
addFunIds xxs@(funId:xs) (y:ys)
| isFunction y = setFunId funId y : addFunIds xs ys
| otherwise = y : addFunIds xxs ys
isFunction :: AnnotToken -> Bool
isFunction (AnnotToken t _ _ _) = lexemeToken t == L.TokFunction
addNames :: [ [LocatedExprName] ] -> [LexToken] -> [ AnnotToken ]
addNames = go []
where
annot t mb stack = AnnotToken t (nameId <$> mb) (map nameId stack) Nothing
-- ensure top of the stack, if any, is active
go (s : stack) ns (t : ts)
| endIx s < startIx t = go stack ns (t : ts)
-- shouldn't happen but here for completenes, and no warnings
go stack ([] : nss) ts = go stack nss ts
-- n is not active, use the stack
go st@(s : stack) nss@((n : _) : _) (t : ts)
| startIx n > endIx t =
annot t (Just s) st : go (s : stack) nss ts
-- no more names, use the stack
go st@(s : stack) [] (t : ts) =
annot t (Just s) st : go (s : stack) [] ts
-- n is not active, no stack
go [] nss@((n : _) : _) (t : ts)
| startIx n > endIx t =
annot t Nothing [] : go [] nss ts
-- no more names or stack, just copy token.
go [] [] (t : ts) =
annot t Nothing [] : go [] [] ts
-- new active name
go stack ((n:ns) : nss) (t : ts) =
let stack' = n : ns ++ stack
in annot t (Just n) stack' : go stack' nss ts
go _ _ [] = []
lineToJSON :: (NameId -> Bool) -> Line -> JS.Value
lineToJSON inScope (Line ts) = toJSON $ map (tokenToJSON inScope) ts
tokenToJSON :: (NameId -> Bool) -> Token -> JS.Value
tokenToJSON inScope (Token x y t cs funId) =
JS.object [ "token" .= x
, "lexeme" .= y
, "name" .= (link <$> t)
, "names" .= cs
, "funid" .= (exportFID <$> funId)
]
where
link z = JS.object [ "ref" .= z, "active" .= inScope z ]
instance ToJSON NameId where
toJSON (NameId x y) = toJSON (show x ++ "_" ++ show y)
instance ToJSON TokenType where
toJSON l = toJSON
$ case l of
Keyword -> "keyword" :: Text
Operator -> "operator"
Symbol -> "symbol"
Ident -> "identifier"
Literal -> "literal"
Comment -> "comment"
WhiteSpace -> "white_space"
Error -> "error"
--------------------------------------------------------------------------------
-- | String and comment tokens may span multiple lines, so we split them
-- into multiple tokens---one per line.
splitTok :: LexToken -> [LexToken]
splitTok = split
where
split tok =
case Text.break (== '\n') (lexemeText tok) of
(as,bs)
| Text.null bs -> if Text.null as then [] else [tok]
| otherwise ->
let rng = lexemeRange tok
from = sourceFrom rng
to = sourceFrom rng
len = Text.length as
ix = sourceIndex from + len
to' = from { sourceColumn = sourceColumn from + len
, sourceIndex = ix
}
from' = from { sourceColumn = 1
, sourceLine = sourceLine from + 1
, sourceIndex = ix + 2
-- the char after the \n
}
t1 = tok { lexemeText = as
, lexemeRange = SourceRange from to'
}
t2 = tok { lexemeText = Text.tail bs
, lexemeRange = SourceRange from' to
}
in t1 : split t2
token :: AnnotToken -> Token
token (AnnotToken tok ns cs funId) =
Token (tokenType tok) (lexemeText tok) ns cs funId
tokenType :: LexToken -> TokenType
tokenType tok =
case lexemeToken tok of
L.TokPlus -> Operator
L.TokMinus -> Operator
L.TokStar -> Operator
L.TokSlash -> Operator
L.TokPercent -> Operator
L.TokExp -> Operator
L.TokEqual -> Operator
L.TokNotequal -> Operator
L.TokLEq -> Operator
L.TokGEq -> Operator
L.TokLT -> Operator
L.TokGT -> Operator
L.TokAssign -> Operator
L.TokDDot -> Operator
L.TokDLT -> Operator
L.TokDGT -> Operator
L.TokAmpersand -> Operator
L.TokPipe -> Operator
L.TokDSlash -> Operator
L.TokTilde -> Operator
L.TokSh -> Operator
L.TokColon -> Operator
L.TokDot -> Operator
L.TokAnd -> Keyword
L.TokBreak -> Keyword
L.TokDo -> Keyword
L.TokElse -> Keyword
L.TokElseIf -> Keyword
L.TokEnd -> Keyword
L.TokFalse -> Keyword
L.TokFor -> Keyword
L.TokFunction -> Keyword
L.TokGoto -> Keyword
L.TokIf -> Keyword
L.TokIn -> Keyword
L.TokLocal -> Keyword
L.TokNil -> Keyword
L.TokNot -> Keyword
L.TokOr -> Keyword
L.TokRepeat -> Keyword
L.TokReturn -> Keyword
L.TokThen -> Keyword
L.TokTrue -> Keyword
L.TokUntil -> Keyword
L.TokWhile -> Keyword
L.TokInt -> Literal
L.TokFloat -> Literal
L.TokSLit -> Literal
L.TokIdent -> Ident
L.TokLParen -> Symbol
L.TokRParen -> Symbol
L.TokLBrace -> Symbol
L.TokRBrace -> Symbol
L.TokLBracket -> Symbol
L.TokRBracket -> Symbol
L.TokDColon -> Symbol
L.TokSemic -> Symbol
L.TokComma -> Symbol
L.TokEllipsis -> Symbol
L.TokComment -> Comment
L.TokWhiteSpace -> WhiteSpace
L.TokUnexpected -> Error
L.TokUntermString -> Error
L.TokUntermComment -> Error
|
GaloisInc/galua
|
galua-dbg/src/Galua/Debugger/PrettySource.hs
|
mit
| 9,648 | 0 | 18 | 3,216 | 2,841 | 1,512 | 1,329 | 230 | 64 |
module Game.ChutesAndLadders.Player where
import Data.Function (on)
import Data.List ((\\), groupBy, sortBy)
import Data.Ord (comparing)
import Text.PrettyPrint.Boxes
import Game.ChutesAndLadders.Cli (printPaddingN, promptNumber, promptPlayerName)
import Game.ChutesAndLadders.Types
import Game.ChutesAndLadders.Util
characters = ["♘", "☃", "☺", "✿", "❤", "☼", "☁", "✝", "❀", "★"]
-- groups players by currentIndex
groupPlayers ps = groupBy f ps' where
ps' = sortBy (comparing currentIndex) ps
f = (==) `on` currentIndex
-- filters nullBox boxes out of a collection of boxes
noNulls :: [Box] -> [Box]
noNulls xs = filter f xs where
f x = not $ and [cols x == 0, rows x == 0]
makePlayers :: Int -> IO [Player]
makePlayers count = makePlayers' 1 count characters where
makePlayers' x z cs | x > z = return []
| otherwise = do
player <- makePlayer x cs
printPaddingN 2
cs' <- return $ cs \\ [character player]
fmap (player :) $ makePlayers' (x+1) z cs'
makePlayer :: Int -> [Character] -> IO Player
makePlayer x cs = do
name <- promptPlayerName x
printPaddingN 1
char <- selectCharacter cs
return Player { number = x, name = name, character = char, currentIndex = -1 }
selectCharacter :: [Character] -> IO Character
selectCharacter cs =
let mx = length cs
cs' = concatMap f $ zip [1..mx] cs
f (i, x) = concat [show i, ") ", x, " "]
p = concat ["Enter choice (1-", show mx, ")"]
in do
putStrLn "As what character would you like play?"
putStrLn cs'
x <- promptNumber p 1 mx
return $ cs !! (x-1)
playerBoxes :: [Player] -> [(Int, Box)]
playerBoxes ps = map f ps' where
ps' = groupPlayers ps
f x = foldr g (0, nullBox) x
g x acc = (currentIndex x, punctuateH left (char ' ') . noNulls $ boxes x ++ [snd acc])
|
rjregenold/chutes-and-ladders
|
Game/ChutesAndLadders/Player.hs
|
mit
| 1,832 | 0 | 13 | 407 | 721 | 379 | 342 | 45 | 1 |
module GHCJS.DOM.Worker (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/Worker.hs
|
mit
| 36 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
bmiTell :: (RealFloat a) => a -> a -> String
bmiTell weight height
| bmi <= skinny = "You're underweight, you emo, you!"
| bmi <= normal = "You're supposedly normal. Pffft, I bet you're ugly!"
| bmi <= fat = "You're fat! Lose some weight, fatty!"
| otherwise = "You're a whale, congratulations!"
where bmi = weight / height ^ 2
skinny = 18.5
normal = 25.0
fat = 30.0
calcBmis :: (RealFloat a) => [(a, a)] -> [a]
calcBmis xs = [bmi w h | (w, h) <- xs]
where bmi weight height = weight / height ^ 2
|
skywind3000/language
|
haskell/bmi.hs
|
mit
| 572 | 0 | 8 | 176 | 188 | 98 | 90 | 13 | 1 |
module Import.NoFoundation
( module Import
) where
import ClassyPrelude.Yesod as Import hiding (languages)
import Model as Import
import Settings as Import
import Settings.StaticFiles as Import
import Yesod.Auth as Import
import Yesod.Core.Types as Import (loggerSet)
import Yesod.Default.Config2 as Import
|
prasmussen/glot-www
|
Import/NoFoundation.hs
|
mit
| 364 | 0 | 5 | 95 | 70 | 50 | 20 | 9 | 0 |
{-# LANGUAGE TemplateHaskell #-}
module Jumpie.GameState where
import Jumpie.GameObject
import Jumpie.Player
import ClassyPrelude
import Jumpie.Types
import Jumpie.Platforms
import Control.Lens.TH
import Control.Lens((^.))
import Control.Lens.Getter(to,Getter)
import Wrench.Time
data GameState = GameState {
_gsSections :: [Platforms]
, _gsOtherObjects :: [GameObject]
, _gsPlayer :: Player
, _gsGameOver :: Bool
, _gsCameraPosition :: PointReal
, _gsMaxDeadline :: TimeTicks
}
$(makeClassy ''GameState)
gsAllObjects :: Getter GameState [GameObject]
gsAllObjects = to (\gs -> gs ^. gsPlayerPacked : (gs ^. gsOtherObjects <> (ObjectPlatform <$> (concat (gs ^. gsSections)))))
gsPlayerPacked :: Getter GameState GameObject
gsPlayerPacked = to (ObjectPlayer . (^. gsPlayer))
|
pmiddend/jumpie
|
lib/Jumpie/GameState.hs
|
gpl-3.0
| 814 | 0 | 16 | 133 | 227 | 134 | 93 | 23 | 1 |
module Lamdu.Sugar.Convert.TaggedList where
import Lamdu.Sugar.Types.Parts
import Lamdu.Sugar.Types.Tag
import Lamdu.Prelude
convert :: Applicative o => i (TagChoice name o) -> [TaggedItem name i o a] -> TaggedList name i o a
convert addFirst items =
TaggedList
{ _tlAddFirst = addFirst
, _tlItems =
case items of
[] -> Nothing
(x:xs) ->
Just TaggedListBody
{ _tlHead = x
, _tlTail =
-- Reordering action will be added in OrderTags phase
xs <&> (`TaggedSwappableItem` pure ())
}
}
|
lamdu/lamdu
|
src/Lamdu/Sugar/Convert/TaggedList.hs
|
gpl-3.0
| 604 | 0 | 16 | 198 | 161 | 91 | 70 | 16 | 2 |
{-# LANGUAGE TemplateHaskell #-}
module Dsgen.TestCards where
import Control.Monad(liftM)
import Control.Monad.Error
import Data.ConfigFile
import Test.HUnit
import Test.QuickCheck
import Test.QuickCheck.All
import Dsgen.Cards
import Dsgen.TestHelpers
{- Test definitions -}
amountReadTest = TestCase $ do
assertEqual "\"Variable\" read failed"
Variable
(read "Variable" :: Amount)
assertEqual "\"FixedAmount 1\" read failed"
(FixedAmount 1)
(read "1" :: Amount)
readCardTest = TestCase $ do
cpE <- runErrorT $ readstring emptyCP sampleCardConfigString
either (\x -> error "ConfigFile parsing failed")
(\cp -> do
card <- runErrorT $ readCard (cp { optionxform = id}) "Test"
assertEqual "Card read failed"
(Right sampleCard)
card)
cpE
{- Test list -}
hunitTests = TestList [
TestLabel "Amount read test" amountReadTest,
TestLabel "readCard test" readCardTest
]
quickCheckTests = $quickCheckAll
{- Sample data -}
sampleCard = Card {
cardName = "Test",
cardSource = Dominion,
cardCost = FixedAmount 1,
cardPotionCost = FixedAmount 0,
cardCategories = [Action, Attack],
cardPlusCards = FixedAmount 0,
cardPlusActions = Variable,
cardPlusBuys = FixedAmount 1,
cardPlusCoins = FixedAmount 6,
cardBlocksAttacks = False,
cardGivesCurses = True,
cardGainsCards = True,
cardTrashesCards = False,
cardTrashesItself = False,
cardInteractive = True,
cardComplexity = High
}
sampleCardConfigString = unlines [
"[Test]",
"source = Dominion",
"cost = 1",
"potionCost = 0",
"categories = [Action, Attack]",
"plusCards = 0",
"plusActions = Variable",
"plusBuys = 1",
"plusCoins = 6",
"blocksAttacks = False",
"givesCurses = True",
"gainsCards = True",
"trashesCards = False",
"trashesItself = False",
"interactive = True",
"complexity = High"
]
{- QuickCheck definitions for types -}
instance Arbitrary Card where
arbitrary = do
name <- cardNameGen
source <- arbitrary
cost <- arbitrary
potionCost <- arbitrary
categories <- subset [Action, Attack, Reaction, Duration,
Treasure, Victory, Looter]
plusCards <- arbitrary
plusActions <- arbitrary
plusBuys <- arbitrary
plusCoins <- arbitrary
blocksAttacks <- arbitrary
givesCurses <- arbitrary
gainsCards <- arbitrary
trashesCards <- arbitrary
trashesItself <- arbitrary
interactive <- arbitrary
complexity <- arbitrary
return Card {
cardName = name,
cardSource = source,
cardCost = cost,
cardPotionCost = potionCost,
cardCategories = categories,
cardPlusCards = plusCards,
cardPlusActions = plusActions,
cardPlusBuys = plusBuys,
cardPlusCoins = plusCoins,
cardBlocksAttacks = blocksAttacks,
cardGivesCurses = givesCurses,
cardGainsCards = gainsCards,
cardTrashesCards = trashesCards,
cardTrashesItself = trashesItself,
cardInteractive = interactive,
cardComplexity = complexity
}
instance Arbitrary CardSource where
arbitrary = elements [Dominion, Intrigue, Seaside, Alchemy,
Prosperity, Cornucopia, Hinterlands, DarkAges,
Guilds, EnvoyPromo, BlackMarketPromo, StashPromo,
WalledVillagePromo, GovernorPromo, Custom]
instance Arbitrary Amount where
arbitrary = do
n <- choose (-1, 10) :: Gen Int
return $ if n == -1 then Variable else FixedAmount n
instance Arbitrary CardCategory where
arbitrary = elements [Action, Attack, Reaction, Duration,
Treasure, Victory, Looter]
instance Arbitrary CardComplexity where
arbitrary = elements [Low, Medium, High]
{- Helper methods -}
cardNameGen :: Gen String
cardNameGen = frequency [(1, return "Moat"),
(204, listOf1 $ elements (['A'..'Z'] ++ ['a'..'z']))]
|
pshendry/dsgen
|
testsuite/Dsgen/TestCards.hs
|
gpl-3.0
| 4,439 | 0 | 18 | 1,453 | 917 | 517 | 400 | 117 | 1 |
module Main(main) where
import Data.Bits(bit,testBit)
import Data.Char(chr,ord)
import Data.List(splitAt)
import System.Environment(getArgs)
import Interp(apply,arity)
import ParseBodies(parseBodies)
import ParseSigs(parseSigs)
import Tokenizer(tokenize)
main :: IO ()
main = do
stdinText <- getContents
interpArgs <- getArgs
let (files,fn,argFiles) = parseArgs interpArgs []
stdinBits = textToBits stdinText
sigs <- readSources files []
args <- readArgs stdinBits argFiles []
let defs = parseBodies sigs
let nils = []:nils
let result = apply defs fn (take (arity defs fn) (args ++ stdinBits:nils))
putStr (bitsToStr result)
parseArgs ("-":fn:args) files = (reverse files,fn,args)
parseArgs ["-"] files = (reverse files,defaultFn files,[])
parseArgs (file:args) files = parseArgs args (file:files)
parseArgs [] files = (reverse files,defaultFn files,[])
defaultFn (fn:_) =
(fst . (break (=='.')) . reverse . fst . (break (=='/')) . reverse) fn
readSources [] sigs = return sigs
readSources (file:files) sigs = do
text <- readFile file
let s = sigs ++ ((parseSigs . tokenize) text)
readSources files s
readArgs _ [] args = return (reverse args)
readArgs stdinBits ("-":files) args =
readArgs stdinBits files (stdinBits:args)
readArgs stdinBits (file:files) args = do
text <- readFile file
readArgs stdinBits files (textToBits text:args)
textToBits text = foldl (++) [] (map charToBits text) where
charToBits char = map (testBit (ord char)) [7,6..0]
bitsToStr [] = []
bitsToStr bits =
let (byte,rest) = splitAt 8 bits
bitToInt flag index = if flag then bit index else 0
bitsToChar bs = chr (foldl (+) 0 (zipWith bitToInt bs [7,6..0]))
in
bitsToChar byte : bitsToStr rest
|
qpliu/esolang
|
01_/hs/interp/hi01_.hs
|
gpl-3.0
| 1,787 | 0 | 15 | 358 | 805 | 412 | 393 | 46 | 2 |
{-# LANGUAGE
Rank2Types
, OverloadedStrings
, DeriveFunctor
, ScopedTypeVariables
, TemplateHaskell
#-}
module Rasa.Internal.Range
( Coord
, Coord'(..)
, overRow
, overCol
, overBoth
, coordRow
, coordCol
, Offset(..)
, asCoord
, clampCoord
, clampRange
, Range(..)
, CrdRange
, range
, rStart
, rEnd
, sizeOf
, sizeOfR
, moveRange
, moveRangeByN
, moveCursorByN
, moveCursor
, Span(..)
, combineSpans
, clamp
, beforeC
, afterC
) where
import Rasa.Internal.Text
import Control.Lens
import Data.Monoid
import Data.List
import Data.Bifunctor
import Data.Biapplicative
import Data.Bitraversable
import Data.Bifoldable
import qualified Yi.Rope as Y
-- | This represents a range between two coordinates ('Coord')
data Range a b = Range
{ _rStart :: a
, _rEnd :: b
} deriving (Eq)
makeLenses ''Range
instance (Show a, Show b) => Show (Range a b) where
show (Range a b) = "(Range (start " ++ show a ++ ") (end " ++ show b ++ "))"
instance Bifunctor Range where
bimap f g (Range a b) = Range (f a) (g b)
instance Bifoldable Range where
bifoldMap f g (Range a b) = f a `mappend` g b
instance Bitraversable Range where
bitraverse f g (Range a b) = Range <$> f a <*> g b
instance (Ord a, Ord b) => Ord (Range a b) where
Range start end <= Range start' end'
| end == end' = start <= start'
| otherwise = end <= end'
-- | (Coord Row Column) represents a char in a block of text. (zero indexed)
-- e.g. Coord 0 0 is the first character in the text,
-- Coord 2 1 is the second character of the third row
data Coord' a b = Coord
{ _coordRow::a
, _coordCol::b
} deriving (Eq)
makeLenses ''Coord'
instance (Show a, Show b) => Show (Coord' a b) where
show (Coord a b) = "(Coord (row " ++ show a ++ ") (col " ++ show b ++ "))"
-- | A type alias to 'Coord'' which specializes the types to integers.
type Coord = Coord' Int Int
-- | A type alias to 'Range'' which specializes the types to 'Coord's.
type CrdRange = Range Coord Coord
instance Bifunctor Coord' where
bimap f g (Coord a b) = Coord (f a) (g b)
-- | Applies a function over the row of a 'Coord'
overRow :: (Int -> Int) -> Coord -> Coord
overRow = first
-- | Applies a function over the column of a 'Coord'
overCol :: (Int -> Int) -> Coord -> Coord
overCol = second
-- | Applies a function over both functors in any 'Bifunctor'.
overBoth :: Bifunctor f => (a -> b) -> f a a -> f b b
overBoth f = bimap f f
instance Biapplicative Coord' where
bipure = Coord
Coord f g <<*>> Coord a b = Coord (f a) (g b)
instance (Ord a, Ord b) => Ord (Coord' a b) where
Coord a b <= Coord a' b'
| a < a' = True
| a > a' = False
| otherwise = b <= b'
-- | An 'Offset' represents an exact position in a file as a number of characters from the start.
newtype Offset =
Offset Int
deriving (Show, Eq)
-- | A span which maps a piece of Monoidal data over a range.
data Span a b =
Span a b
deriving (Show, Eq, Functor)
instance Bifunctor Span where
bimap f g (Span a b) = Span (f a) (g b)
-- | Moves a 'Range' by a given 'Coord'
-- It may be unintuitive, but for (Coord row col) a given range will be moved down by row and to the right by col.
moveRange :: Coord -> CrdRange -> CrdRange
moveRange amt = overBoth (moveCursor amt)
-- | Moves a range forward by the given amount
moveRangeByN :: Int -> CrdRange -> CrdRange
moveRangeByN amt = overBoth (moveCursorByN amt)
-- | Moves a 'Coord' forward by the given amount of columns
moveCursorByN :: Int -> Coord -> Coord
moveCursorByN amt = overCol (+amt)
-- | Adds the rows and columns of the given two 'Coord's.
moveCursor :: Coord -> Coord -> Coord
moveCursor = biliftA2 (+) (+)
instance (Num a, Num b) => Num (Coord' a b) where
Coord row col + Coord row' col' = Coord (row + row') (col + col')
Coord row col - Coord row' col' = Coord (row - row') (col - col')
Coord row col * Coord row' col' = Coord (row * row') (col * col')
abs (Coord row col) = Coord (abs row) (abs col)
fromInteger i = Coord 0 (fromInteger i)
signum (Coord row col) = Coord (signum row) (signum col)
-- | Given the text you're operating over, creates an iso from an 'Offset' to a 'Coord'.
asCoord :: Y.YiString -> Iso' Offset Coord
asCoord txt = iso (toCoord txt) (toOffset txt)
-- | Given the text you're operating over, converts a 'Coord' to an 'Offset'.
toOffset :: Y.YiString -> Coord -> Offset
toOffset txt (Coord row col) = Offset $ lenRows + col
where
lenRows = Y.length . Y.concat . take row . Y.lines' $ txt
-- | Given the text you're operating over, converts an 'Offset' to a 'Coord'.
toCoord :: Y.YiString -> Offset -> Coord
toCoord txt (Offset offset) = Coord numRows numColumns
where
numRows = Y.countNewLines . Y.take offset $ txt
numColumns = (offset -) . Y.length . Y.concat . take numRows . Y.lines' $ txt
-- | This will restrict a given 'Coord' to a valid one which lies within the given text.
clampCoord :: Y.YiString -> Coord -> Coord
clampCoord txt (Coord row col) =
Coord (clamp 0 maxRow row) (clamp 0 maxColumn col)
where
maxRow = Y.countNewLines txt
selectedRow = fst . Y.splitAtLine 1 . snd . Y.splitAtLine row $ txt
maxColumn = Y.length selectedRow
-- | This will restrict a given 'Range' to a valid one which lies within the given text.
clampRange :: Y.YiString -> CrdRange -> CrdRange
clampRange txt = overBoth (clampCoord txt)
-- | A Helper only used when combining many spans.
data Marker
= Start
| End
deriving (Show, Eq)
type ID = Int
-- | Combines a list of spans containing some monoidal data into a list of offsets with
-- with the data that applies from each Offset forwards.
combineSpans
:: forall a.
Monoid a
=> [Span CrdRange a] -> [(Coord, a)]
combineSpans spans = combiner [] $ sortOn (view _3) (splitStartEnd idSpans)
where
idSpans :: [(ID, Span CrdRange a)]
idSpans = zip [1 ..] spans
splitStartEnd :: [(ID, Span CrdRange a)] -> [(Marker, ID, Coord, a)]
splitStartEnd [] = []
splitStartEnd ((i, Span (Range s e) d):rest) =
(Start, i, s, d) : (End, i, e, d) : splitStartEnd rest
withoutId :: ID -> [(ID, a)] -> [(ID, a)]
withoutId i = filter ((/= i) . fst)
combiner :: [(ID, a)] -> [(Marker, ID, Coord, a)] -> [(Coord, a)]
combiner _ [] = []
combiner cur ((Start, i, crd, mData):rest) =
let dataSum = foldMap snd cur <> mData
newData = (i, mData) : cur
in (crd, dataSum) : combiner newData rest
combiner cur ((End, i, crd, _):rest) =
let dataSum = foldMap snd newData
newData = withoutId i cur
in (crd, dataSum) : combiner newData rest
-- | @clamp min max val@ restricts val to be within min and max (inclusive)
clamp :: Int -> Int -> Int -> Int
clamp mn mx n
| n < mn = mn
| n > mx = mx
| otherwise = n
-- | Returns the number of rows and columns that a 'Range' spans as a 'Coord'
sizeOfR :: CrdRange -> Coord
sizeOfR (Range start end) = end - start
-- | Returns the number of rows and columns that a chunk of text spans as a 'Coord'
sizeOf :: Y.YiString -> Coord
sizeOf txt = Coord (Y.countNewLines txt) (Y.length (txt ^. asLines . _last))
-- | A lens over text before a given 'Coord'
beforeC :: Coord -> Lens' Y.YiString Y.YiString
beforeC c@(Coord row col) = lens getter setter
where getter txt = let (before, after) = Y.splitAtLine row $ txt
in before <> Y.take col after
setter old new = let suffix = old ^. afterC c
in new <> suffix
-- | A lens over text after a given 'Coord'
afterC :: Coord -> Lens' Y.YiString Y.YiString
afterC c@(Coord row col) = lens getter setter
where getter txt = Y.drop col . snd . Y.splitAtLine row $ txt
setter old new = let prefix = old ^. beforeC c
in prefix <> new
-- | A lens over text which is encompassed by a 'Range'
range :: CrdRange -> Lens' Y.YiString Y.YiString
range (Range start end) = lens getter setter
where getter = view (beforeC end . afterC start)
setter old new = result
where
setBefore = old & beforeC end .~ new
result = old & afterC start .~ setBefore
|
ChrisPenner/rasa
|
rasa/src/Rasa/Internal/Range.hs
|
gpl-3.0
| 8,165 | 0 | 13 | 1,962 | 2,698 | 1,417 | 1,281 | -1 | -1 |
module GameOver where
import DataTypes
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Game
-- | Update the gameover screen.
updateGameOver :: Float -> AsteroidsGame -> AsteroidsGame
updateGameOver seconds game = game
-- | Handle the key events on the gameover screen.
handleGameOverKeys :: Event -> AsteroidsGame -> AsteroidsGame
handleGameOverKeys (EventKey (Char 'q') _ _ _) game = game {gameMode = Menu}
handleGameOverKeys _ game = game
-- | Display the gameover screen.
gameOverRender :: AsteroidsGame -> Picture
gameOverRender game = color white (pictures
[
translate (-350) 280 (text "-------"),
translate (-350) 200 (text "|.GameOver.|"),
translate (-350) 120 (text "-------"),
scale (0.3) (0.3) (translate (-1000) (60) (text "Press 'q' to return to MainMenu"))
])
|
kareem2048/Asteroids
|
GameOver.hs
|
gpl-3.0
| 801 | 0 | 13 | 126 | 236 | 129 | 107 | 16 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EMR.ListBootstrapActions
-- Copyright : (c) 2013-2014 Brendan Hay <[email protected]>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Provides information about the bootstrap actions associated with a cluster.
--
-- <http://docs.aws.amazon.com/ElasticMapReduce/latest/API/API_ListBootstrapActions.html>
module Network.AWS.EMR.ListBootstrapActions
(
-- * Request
ListBootstrapActions
-- ** Request constructor
, listBootstrapActions
-- ** Request lenses
, lbaClusterId
, lbaMarker
-- * Response
, ListBootstrapActionsResponse
-- ** Response constructor
, listBootstrapActionsResponse
-- ** Response lenses
, lbarBootstrapActions
, lbarMarker
) where
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.EMR.Types
import qualified GHC.Exts
data ListBootstrapActions = ListBootstrapActions
{ _lbaClusterId :: Text
, _lbaMarker :: Maybe Text
} deriving (Eq, Ord, Read, Show)
-- | 'ListBootstrapActions' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lbaClusterId' @::@ 'Text'
--
-- * 'lbaMarker' @::@ 'Maybe' 'Text'
--
listBootstrapActions :: Text -- ^ 'lbaClusterId'
-> ListBootstrapActions
listBootstrapActions p1 = ListBootstrapActions
{ _lbaClusterId = p1
, _lbaMarker = Nothing
}
-- | The cluster identifier for the bootstrap actions to list .
lbaClusterId :: Lens' ListBootstrapActions Text
lbaClusterId = lens _lbaClusterId (\s a -> s { _lbaClusterId = a })
-- | The pagination token that indicates the next set of results to retrieve .
lbaMarker :: Lens' ListBootstrapActions (Maybe Text)
lbaMarker = lens _lbaMarker (\s a -> s { _lbaMarker = a })
data ListBootstrapActionsResponse = ListBootstrapActionsResponse
{ _lbarBootstrapActions :: List "BootstrapActions" Command
, _lbarMarker :: Maybe Text
} deriving (Eq, Read, Show)
-- | 'ListBootstrapActionsResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'lbarBootstrapActions' @::@ ['Command']
--
-- * 'lbarMarker' @::@ 'Maybe' 'Text'
--
listBootstrapActionsResponse :: ListBootstrapActionsResponse
listBootstrapActionsResponse = ListBootstrapActionsResponse
{ _lbarBootstrapActions = mempty
, _lbarMarker = Nothing
}
-- | The bootstrap actions associated with the cluster .
lbarBootstrapActions :: Lens' ListBootstrapActionsResponse [Command]
lbarBootstrapActions =
lens _lbarBootstrapActions (\s a -> s { _lbarBootstrapActions = a })
. _List
-- | The pagination token that indicates the next set of results to retrieve .
lbarMarker :: Lens' ListBootstrapActionsResponse (Maybe Text)
lbarMarker = lens _lbarMarker (\s a -> s { _lbarMarker = a })
instance ToPath ListBootstrapActions where
toPath = const "/"
instance ToQuery ListBootstrapActions where
toQuery = const mempty
instance ToHeaders ListBootstrapActions
instance ToJSON ListBootstrapActions where
toJSON ListBootstrapActions{..} = object
[ "ClusterId" .= _lbaClusterId
, "Marker" .= _lbaMarker
]
instance AWSRequest ListBootstrapActions where
type Sv ListBootstrapActions = EMR
type Rs ListBootstrapActions = ListBootstrapActionsResponse
request = post "ListBootstrapActions"
response = jsonResponse
instance FromJSON ListBootstrapActionsResponse where
parseJSON = withObject "ListBootstrapActionsResponse" $ \o -> ListBootstrapActionsResponse
<$> o .:? "BootstrapActions" .!= mempty
<*> o .:? "Marker"
instance AWSPager ListBootstrapActions where
page rq rs
| stop (rs ^. lbarMarker) = Nothing
| otherwise = (\x -> rq & lbaMarker ?~ x)
<$> (rs ^. lbarMarker)
|
dysinger/amazonka
|
amazonka-emr/gen/Network/AWS/EMR/ListBootstrapActions.hs
|
mpl-2.0
| 4,688 | 0 | 12 | 1,015 | 656 | 385 | 271 | 74 | 1 |
module Codewars.Lambda4fun.ParseHtmlColor where
-- module A where
import Codewars.Lambda4fun.ParseHtmlColor.PresetColors (presetColors)
import Data.Char (toLower, digitToInt)
import Data.List (insert)
import Data.Map.Strict (Map, fromList, (!))
parseHtmlColor :: String -> Map Char Int
parseHtmlColor ('#':t) = fromList $ parseCssColor t
parseHtmlColor s = parseHtmlColor $ presetColors ! (map toLower s)
--
dti = digitToInt
parseCssColor :: String -> [(Char, Int)]
parseCssColor [r1, r2, g1, g2, b1, b2] = [('r', dti r2 + 16 * dti r1), ('g', dti g2 + 16 * dti g1), ('b', dti b2 + 16 * dti b1)]
parseCssColor [r, g, b] = [('r', 17 * dti r), ('g', 17 * dti g), ('b', 17 * dti b)]
|
ice1000/OI-codes
|
codewars/1-100/arse-html-slash-css-colors.hs
|
agpl-3.0
| 690 | 0 | 9 | 119 | 306 | 175 | 131 | 12 | 1 |
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE GADTs #-}
-- For later examples
{-# LANGUAGE TypeOperators, DataKinds, FlexibleContexts #-}
-- ** Freer Monad and Extensible interpreters
module Tutorial2_Orig where
import OpenUnion52
-- Review our general way to give meaning to effectful computations
data Comp req a where
Val :: a -> Comp req a
E :: req x -> (x -> Comp req a) -> Comp req a
-- Effect signature
{-
ask :: Comp (Get e) e
ask = E Get Val
runReader :: e -> Comp (Get e) a -> a
runReader e (Val x) = x
runReader e (E Get k) = runReader e $ k e
bind :: Comp req a -> (a -> Comp req b) -> Comp req b
bind (Val x) f = f x
bind (E r k) f = E r (\x -> bind (k x) f)
-- More convenient notation
-- rlExp2 =
-- bind ask $ \x ->
-- bind ask $ \y ->
-- Val (x + y + 1)
-- renaming Val and bind, so to get the benefit of the do notation
instance Monad (Comp req) where
return = Val
(>>=) = bind
-- Simpler composition modes
rlExp2 = do
x <- ask
y <- ask
return (x + y + 1)
rlExp3 = do
x <- rlExp2
y <- ask
return (x * y - 1)
_ = runReader 2 rlExp3 :: Int
-- ** Monad, or Freer Monad!
-- (a less optimal instance thereof)
-- Other interpreters
feedAll :: [e] -> Comp (Get e) a -> Maybe a
feedAll _ (Val a) = Just a
feedAll [] _ = Nothing
feedAll (h : t) (E Get k) = feedAll t (k h)
_ = feedAll [2,3,4] rlExp3 :: Maybe Int
-- Another effect, Put
data Put o x where
Put :: o -> Put o ()
send :: req x -> Comp req x
send req = E req return
tell :: o -> Comp (Put o) ()
tell x = send (Put x)
wrExp m = do
tell "a"
x <- m
tell (show x)
tell "end"
runWriter :: Comp (Put o) x -> ([o],x)
_ = runWriter (wrExp (return 1))
-- QUIZ: What other Writer interpreters to write?
-- Several effects
{-
rwExp' = do
tell "begin"
x <- rlExp3
tell "end"
return x
-}
-- rxExp0' x = if x then rlExp3 else (do {tell "1"; return (0::Int)})
-- Internal choice!
data Sum r1 r2 x where
L :: r1 x -> Sum r1 r2 x
R :: r2 x -> Sum r1 r2 x
injL :: Comp r1 x -> Comp (Sum r1 r2) x
injL (Val x) = Val x
injL (E r k) = E (L r) (injL . k)
injR :: Comp r2 x -> Comp (Sum r1 r2) x
injR (Val x) = Val x
injR (E r k) = E (R r) (injR . k)
rxExp0 x = if x then injL rlExp3 else (injR (do {tell "1"; return (0::Int)}))
rwExp = do
injR $ tell "begin"
x <- injL $ rlExp3
injR $ tell "end"
return x
-- How to interpret? Need projections
-- runReaderL
_ = runReaderL 2 rwExp
-- Interpreter composition
-- Doing injR and injL, etc. is impractical
-- Need a better idea.
-- Suggestions?
-- EDLS, p8, 1st full paragraph
-- -----------------------------------------------------------------------
-- Open Union interface
{-
type Union (r :: [* -> *]) a
class Member (t :: k) (r :: [k])
inj :: Member t r => t v -> Union r v
prj :: Member t r => Union r v -> Maybe (t v)
decomp :: Union (t:r) v -> Either (Union r v) (t v)
The type of inj/prj really shows the union as a (multi)set.
decomp imposes the ordering. Dissatisfaction. What we really need
is something like the local instances with the closure seamntics.
And Haskell almost has what we need! (Implicit parameters).
-}
injC :: Member req r => Comp req x -> Comp (Union r) x
injC (Val x) = Val x
injC (E r k) = E (inj r) (injC . k)
runReaderC :: e -> Comp (Union (Get e ': r)) a -> Comp (Union r) a
rwExpC = do
injC $ tell "begin"
x <- injC $ rlExp3
injC $ tell "end"
return (x::Int)
-- What is the inferred type?
xx = runReaderC (2::Int) rwExpC
-- What is the inferred type?
-- Handling two effects at the same time
runState :: e -> Comp (Union (Get e ': Put e ': r)) a -> Comp (Union r) a
ts11 = do
injC $ tell (10 ::Int)
x <- injC ask
return (x::Int)
-- Inferred type?
-- Putting injC inside ask/tell to ease the notation
x2 = (runState (0::Int) ts11)
-- What now?
ts21 = do
injC $ tell (10::Int)
x <- injC ask
injC $ tell (20::Int)
y <- injC ask
return (x+y)
-}
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/conference/2017-09-cufp-effects/src/Tutorial2_Orig.hs
|
unlicense
| 3,966 | 0 | 10 | 1,008 | 68 | 41 | 27 | 8 | 0 |
module binDec where
binDec :: [Int] -> Int
binDec (x:[]) = x
binDec (x:y) = x + binDec y * 2
|
tonilopezmr/Learning-Haskell
|
Exercises/2/Exercise_2.hs
|
apache-2.0
| 96 | 11 | 7 | 24 | 61 | 33 | 28 | -1 | -1 |
-----------------------------------------------------------------------------
-- Copyright 2019, Ideas project team. This file is distributed under the
-- terms of the Apache License 2.0. For more information, see the files
-- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution.
-----------------------------------------------------------------------------
-- |
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable (depends on ghc)
--
-----------------------------------------------------------------------------
module Ideas.Text.OpenMath.Object
( OMOBJ(..), getOMVs, xml2omobj, omobj2xml
) where
import Data.Char
import Data.Generics.Uniplate.Direct hiding (children)
import Data.List (nub)
import Data.Maybe
import Ideas.Text.OpenMath.Symbol
import Ideas.Text.XML
-- internal representation for OpenMath objects
data OMOBJ = OMI Integer
| OMF Double
| OMV String
| OMS Symbol
| OMA [OMOBJ]
| OMBIND OMOBJ [String] OMOBJ
deriving (Show, Eq)
instance ToXML OMOBJ where
toXML = omobj2xml
instance InXML OMOBJ where
fromXML = either fail return . xml2omobj
instance Uniplate OMOBJ where
uniplate omobj =
case omobj of
OMA xs -> plate OMA ||* xs
OMBIND a ss b -> plate OMBIND |* a |- ss |* b
_ -> plate omobj
getOMVs :: OMOBJ -> [String]
getOMVs omobj = nub [ x | OMV x <- universe omobj ]
----------------------------------------------------------
-- conversion functions: XML <-> OMOBJ
xml2omobj :: XML -> Either String OMOBJ
xml2omobj xmlTop
| name xmlTop == "OMOBJ" =
case children xmlTop of
[x] -> rec x
_ -> fail "invalid omobj"
| otherwise = fail "expected an OMOBJ tag"
where
rec xml =
case name xml of
"OMA" -> do
ys <- mapM rec (children xml)
return (OMA ys)
"OMS" | emptyContent xml -> do
let mcd = case findAttribute "cd" xml of
Just "unknown" -> Nothing
this -> this
n <- findAttribute "name" xml
return (OMS (mcd, n))
"OMI" | name xml == "OMI" ->
case readInt (getData xml) of
Just i -> return (OMI (toInteger i))
_ -> fail "invalid integer in OMI"
"OMF" | emptyContent xml -> do
s <- findAttribute "dec" xml
case readDouble s of
Just nr -> return (OMF nr)
_ -> fail "invalid floating-point in OMF"
"OMV" | emptyContent xml -> do
s <- findAttribute "name" xml
return (OMV s)
"OMBIND" ->
case children xml of
[x1, x2, x3] -> do
y1 <- rec x1
y2 <- recOMBVAR x2
y3 <- rec x3
return (OMBIND y1 y2 y3)
_ -> fail "invalid ombind"
_ -> fail ("invalid tag " ++ name xml)
recOMBVAR xml
| name xml == "OMBVAR" =
let f (Right (OMV s)) = return s
f this = fail $ "expected tag OMV in OMBVAR, but found " ++ show this
in mapM (f . rec) (children xml)
| otherwise =
fail ("expected tag OMVAR, but found " ++ show (name xml))
omobj2xml :: OMOBJ -> XML
omobj2xml object = makeXML "OMOBJ" $ mconcat
[ "xmlns" .=. "http://www.openmath.org/OpenMath"
, "version" .=. "2.0"
, "cdbase" .=. "http://www.openmath.org/cd"
, rec object
]
where
rec :: OMOBJ -> XMLBuilder
rec omobj =
case omobj of
OMI i -> element "OMI" [text i]
OMF f -> element "OMF" ["dec" .=. show f]
OMV v -> element "OMV" ["name" .=. v]
OMA xs -> element "OMA" (map rec xs)
OMS s -> element "OMS"
[ "cd" .=. fromMaybe "unknown" (dictionary s)
, "name" .=. symbolName s
]
OMBIND x ys z -> element "OMBIND"
[ rec x
, element "OMBVAR" (map (rec . OMV) ys)
, rec z
]
readInt :: String -> Maybe Integer
readInt s = case reads s of
[(n, xs)] | all isSpace xs -> Just n
_ -> Nothing
readDouble :: String -> Maybe Double
readDouble s = case reads s of
[(n, xs)] | all isSpace xs -> Just n
_ -> Nothing
|
ideas-edu/ideas
|
src/Ideas/Text/OpenMath/Object.hs
|
apache-2.0
| 4,566 | 0 | 19 | 1,655 | 1,263 | 617 | 646 | 101 | 13 |
{-# LANGUAGE OverloadedStrings #-}
import Data.Text -- Using Text to test the integer-simple flag handling with stack
import Lib1
import Lib2
main :: IO ()
main = do
printGreeting $ hello $ unpack "world"
|
prezi/gradle-haskell-plugin
|
src/test-projects/test1-with-text/app/src/main/haskell/Main.hs
|
apache-2.0
| 209 | 0 | 8 | 38 | 43 | 23 | 20 | 7 | 1 |
chk t d =
let a = foldl (\ a (s:f:_) -> a + (f-s) ) 0 d
in
if a >= t
then "OK"
else show (t-a)
ans ([0]:_) = []
ans ([t]:[n]:x) =
let d = take n x
r = chk t d
y = drop n x
in
r:ans y
main = do
c <- getContents
let i = map (map read) $ map words $ lines c :: [[Int]]
o = ans i
mapM_ putStrLn o
|
a143753/AOJ
|
0238.hs
|
apache-2.0
| 343 | 0 | 14 | 131 | 240 | 121 | 119 | 16 | 2 |
{-# LANGUAGE DefaultSignatures #-}
{- |
Module : Data.Mono
Description : Monomorphic functor, foldable, traversable and monad.
Copyright : (c) Paweł Nowak
License : Apache v2.0
Maintainer : [email protected]
Stability : experimental
Portability : portable
It turns out that Control.Lens does exactly what this module was supposed to do and does it better.
-}
module Data.Mono where
import Data.Monoid
import Data.Maybe
import Data.Functor.Identity
import Data.Functor.Constant
import Control.Applicative
class MonoFunctor f e where
omap :: (e -> e) -> f -> f
default omap :: MonoTraversable f e => (e -> e) -> f -> f
omap f = runIdentity . otraverse (Identity . f)
class MonoFoldable f e where
-- | Map each element of the structure to a monoid, and combine the results.
ofoldMap :: Monoid m => (e -> m) -> f -> m
default ofoldMap :: (MonoTraversable f e, Monoid m) => (e -> m) -> f -> m
ofoldMap f = getConstant . otraverse (Constant . f)
-- | Right-associative fold of a structure.
ofoldr :: (e -> b -> b) -> b -> f -> b
ofoldr f z t = appEndo (ofoldMap (Endo . f) t) z
-- | Right-associative fold of a structure, but with strict application of the operator.
ofoldr' :: (e -> b -> b) -> b -> f -> b
ofoldr' f z0 xs = ofoldl f' id xs z0
where f' k x z = k $! f x z
-- | Left-associative fold of a structure.
ofoldl :: (b -> e -> b) -> b -> f -> b
ofoldl f z t = appEndo (getDual (ofoldMap (Dual . Endo . flip f) t)) z
-- | Left-associative fold of a structure, but with strict application of the operator.
ofoldl' :: (b -> e -> b) -> b -> f -> b
ofoldl' f z0 xs = ofoldr f' id xs z0
where f' x k z = k $! f z x
-- | A variant of 'foldr' that has no base case, and thus may only be applied to non-empty structures.
ofoldr1 :: (e -> e -> e) -> f -> e
ofoldr1 f xs = fromMaybe (error "ofoldr1: empty structure")
(ofoldr mf Nothing xs)
where
mf x Nothing = Just x
mf x (Just y) = Just (f x y)
-- | A variant of 'foldl' that has no base case, and thus may only be applied to non-empty structures.
ofoldl1 :: (e -> e -> e) -> f -> e
ofoldl1 f xs = fromMaybe (error "ofoldl1: empty structure")
(ofoldl mf Nothing xs)
where
mf Nothing y = Just y
mf (Just x) y = Just (f x y)
class (MonoFunctor t e, MonoFoldable t e) => MonoTraversable t e where
-- | Map each element of a structure to an action,
-- evaluate these actions from left to right, and collect the results.
otraverse :: Applicative f => (e -> f e) -> t -> f t
class MonoMonadBase f e where
oreturn :: e -> f
class (MonoFunctor f e, MonoMonadBase f e) => MonoMonad m f e where
(@>>=) :: m -> (e -> f) -> m
|
pawel-n/haskell-lib
|
Data/Mono.hs
|
apache-2.0
| 2,814 | 0 | 14 | 779 | 835 | 432 | 403 | -1 | -1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Text.Megaparsec.ExprSpec (spec) where
import Data.Monoid ((<>))
import Test.Hspec
import Test.Hspec.Megaparsec
import Test.Hspec.Megaparsec.AdHoc
import Test.QuickCheck
import Text.Megaparsec
import Text.Megaparsec.Char
import Text.Megaparsec.Expr
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>), (<*), (<*>), (*>), pure)
#endif
spec :: Spec
spec =
describe "makeExprParser" $ do
context "when given valid rendered AST" $
it "can parse it back" $
property $ \node -> do
let s = showNode node
prs expr s `shouldParse` node
prs' expr s `succeedsLeaving` ""
context "when stream in empty" $
it "signals correct parse error" $
prs (expr <* eof) "" `shouldFailWith` err posI (ueof <> elabel "term")
context "when term is missing" $
it "signals correct parse error" $ do
let p = expr <* eof
prs p "-" `shouldFailWith` err (posN 1 "-") (ueof <> elabel "term")
prs p "(" `shouldFailWith` err (posN 1 "(") (ueof <> elabel "term")
prs p "*" `shouldFailWith` err posI (utok '*' <> elabel "term")
context "operator is missing" $
it "signals correct parse error" $
property $ \a b -> do
let p = expr <* eof
a' = inParens a
n = length a' + 1
s = a' ++ " " ++ inParens b
c = s !! n
if c == '-'
then prs p s `shouldParse` Sub a b
else prs p s `shouldFailWith`
err (posN n s) (utok c <> eeof <> elabel "operator")
-- Algebraic structures to build abstract syntax tree of our expression.
data Node
= Val Integer -- ^ literal value
| Neg Node -- ^ negation (prefix unary)
| Fac Node -- ^ factorial (postfix unary)
| Mod Node Node -- ^ modulo
| Sum Node Node -- ^ summation (addition)
| Sub Node Node -- ^ subtraction
| Pro Node Node -- ^ product
| Div Node Node -- ^ division
| Exp Node Node -- ^ exponentiation
deriving (Eq, Show)
instance Enum Node where
fromEnum (Val _) = 0
fromEnum (Neg _) = 0
fromEnum (Fac _) = 0
fromEnum (Mod _ _) = 0
fromEnum (Exp _ _) = 1
fromEnum (Pro _ _) = 2
fromEnum (Div _ _) = 2
fromEnum (Sum _ _) = 3
fromEnum (Sub _ _) = 3
toEnum _ = error "Oops!"
instance Ord Node where
x `compare` y = fromEnum x `compare` fromEnum y
showNode :: Node -> String
showNode (Val x) = show x
showNode n@(Neg x) = "-" ++ showGT n x
showNode n@(Fac x) = showGT n x ++ "!"
showNode n@(Mod x y) = showGE n x ++ " % " ++ showGE n y
showNode n@(Sum x y) = showGT n x ++ " + " ++ showGE n y
showNode n@(Sub x y) = showGT n x ++ " - " ++ showGE n y
showNode n@(Pro x y) = showGT n x ++ " * " ++ showGE n y
showNode n@(Div x y) = showGT n x ++ " / " ++ showGE n y
showNode n@(Exp x y) = showGE n x ++ " ^ " ++ showGT n y
showGT :: Node -> Node -> String
showGT parent node = (if node > parent then showCmp else showNode) node
showGE :: Node -> Node -> String
showGE parent node = (if node >= parent then showCmp else showNode) node
showCmp :: Node -> String
showCmp node = (if fromEnum node == 0 then showNode else inParens) node
inParens :: Node -> String
inParens x = "(" ++ showNode x ++ ")"
instance Arbitrary Node where
arbitrary = sized arbitraryN0
arbitraryN0 :: Int -> Gen Node
arbitraryN0 n = frequency [ (1, Mod <$> leaf <*> leaf)
, (9, arbitraryN1 n) ]
where leaf = arbitraryN1 (n `div` 2)
arbitraryN1 :: Int -> Gen Node
arbitraryN1 n =
frequency [ (1, Neg <$> arbitraryN2 n)
, (1, Fac <$> arbitraryN2 n)
, (7, arbitraryN2 n)]
arbitraryN2 :: Int -> Gen Node
arbitraryN2 0 = Val . getNonNegative <$> arbitrary
arbitraryN2 n = elements [Sum,Sub,Pro,Div,Exp] <*> leaf <*> leaf
where leaf = arbitraryN0 (n `div` 2)
-- Some helpers are put here since we don't want to depend on
-- "Text.Megaparsec.Lexer".
lexeme :: Parser a -> Parser a
lexeme p = p <* hidden space
symbol :: String -> Parser String
symbol = lexeme . string
parens :: Parser a -> Parser a
parens = between (symbol "(") (symbol ")")
integer :: Parser Integer
integer = lexeme (read <$> some digitChar <?> "integer")
-- Here we use a table of operators that makes use of all features of
-- 'makeExprParser'. Then we generate abstract syntax tree (AST) of complex
-- but valid expressions and render them to get their textual
-- representation.
expr :: Parser Node
expr = makeExprParser term table
term :: Parser Node
term = parens expr <|> (Val <$> integer) <?> "term"
table :: [[Operator Parser Node]]
table =
[ [ Prefix (symbol "-" *> pure Neg)
, Postfix (symbol "!" *> pure Fac)
, InfixN (symbol "%" *> pure Mod) ]
, [ InfixR (symbol "^" *> pure Exp) ]
, [ InfixL (symbol "*" *> pure Pro)
, InfixL (symbol "/" *> pure Div) ]
, [ InfixL (symbol "+" *> pure Sum)
, InfixL (symbol "-" *> pure Sub)] ]
|
recursion-ninja/megaparsec
|
tests/Text/Megaparsec/ExprSpec.hs
|
bsd-2-clause
| 5,030 | 0 | 18 | 1,346 | 1,839 | 954 | 885 | 122 | 2 |
-- The Timber compiler <timber-lang.org>
--
-- Copyright 2008-2009 Johan Nordlander <[email protected]>
-- 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 names of the copyright holder and any identified
-- contributors, nor the names of their affiliations, may be used to
-- endorse or promote products derived from this software without
-- specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE 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 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 Syntax2Core where
import Common
import Syntax
import Control.Monad
import qualified Core
import PP
syntax2core m = s2c m
-- translate a module in the empty environment
s2c :: Module -> M s Core.Module
s2c (Module v is ds ps) = do (xs,ts,ws,bss) <- s2cDecls env0 ds [] [] [] [] []
return (Core.Module v is' xs ts ws bss)
where env0 = Env { sigs = [] }
is' = [(b,n) | Import b n <- is]
-- type signature environments
data Env = Env { sigs :: Map Name Type }
addSigs te env = env { sigs = te ++ sigs env }
-- Syntax to Core translation of declarations ========================================================
-- Translate top-level declarations, accumulating signature environment env, kind environment ke,
-- type declarations ts, instance names ws, bindings bs as well as default declarations xs
s2cDecls env [] ke ts ws bss xs = do bss <- s2cBindsList env (reverse bss)
ke' <- mapM s2cKSig (impl_ke `zip` repeat KWild)
xs' <- mapM s2cDefault xs
let ds = Core.Types (reverse ke ++ ke') (reverse ts)
return (xs', ds, ws, bss)
where impl_ke = dom ts \\ dom ke
s2cDecls env (DKSig c k : ds) ke ts ws bss xs
= do ck <- s2cKSig (c,k)
s2cDecls env ds (ck:ke) ts ws bss xs
s2cDecls env (DData c vs bts cs : ds) ke ts ws bss xs
= do bts <- mapM s2cQualType bts
cs <- mapM s2cConstr cs
s2cDecls env' ds ke ((c,Core.DData vs bts cs):ts) ws bss xs
where env' = addSigs (teConstrs c vs cs) env
s2cDecls env (DRec isC c vs bts ss : ds) ke ts ws bss xs
= do bts <- mapM s2cQualType bts
sss <- mapM s2cSig ss
s2cDecls env' ds ke ((c,Core.DRec isC vs bts (concat sss)):ts) ws bss xs
where env' = addSigs (teSigs c vs ss) env
s2cDecls env (DType c vs t : ds) ke ts ws bss xs
= do t <- s2cType t
s2cDecls env ds ke ((c,Core.DType vs t):ts) ws bss xs
s2cDecls env (DInstance vs : ds) ke ts ws bss xs
= s2cDecls env ds ke ts (ws++vs) bss xs
s2cDecls env (DDefault d : ds) ke ts ws bss xs
= s2cDecls env ds ke ts ws bss (d ++ xs)
s2cDecls env (DBind bs : ds) ke ts ws bss xs
= s2cDecls env ds ke ts ws (bs:bss) xs
s2cBindsList env [] = return []
s2cBindsList env (bs:bss) = do (te,bs) <- s2cBinds env bs
bss <- s2cBindsList (addSigs te env) bss
return (bs:bss)
s2cDefault (Default t a b) = return (Default t a b)
s2cDefault (Derive n t) = do t <- s2cQualType t
return (Derive n t)
--translate a constructor declaration
s2cConstr (Constr c ts ps) = do ts <- mapM s2cQualType ts
(qs,ke) <- s2cQuals ps
return (c, Core.Constr ts qs ke)
-- translate a field declaration
s2cSig (Sig vs qt) = s2cTSig vs qt
-- add suppressed wildcard kind
pVar v = PKind v KWild
-- buld a signature environment for data constructors cs in type declaration tc vs
teConstrs tc vs cs = map f cs
where t0 = foldl TAp (TCon tc) (map TVar vs)
f (Constr c ts ps) = (c,TQual (tFun ts t0) (ps ++ map pVar vs))
-- build a signature environment for record selectors ss in type declaration tc vs
teSigs tc vs ss = concat (map f ss)
where t0 = foldl TAp (TCon tc) (map TVar vs)
f (Sig ws (TQual t ps)) = ws `zip` repeat (TQual (TFun [t0] t) (ps ++ map pVar vs))
f (Sig ws t) = ws `zip` repeat (TQual (TFun [t0] t) (map pVar vs))
-- Signatures =========================================================================
-- translate a type signature
s2cTSig vs t = do ts <- mapM (s2cQualType . const t) vs
return (vs `zip` ts)
-- Types ==============================================================================
-- translate a qualified type scheme
s2cQualType (TQual t qs) = do (ps,ke) <- s2cQuals qs
t <- s2cRhoType t
return (Core.Scheme t ps ke)
s2cQualType t = s2cQualType (TQual t [])
-- translate a rank-N function type
s2cRhoType (TFun ts t) = do ts <- mapM s2cQualType ts
t <- s2cRhoType t
return (Core.F ts t)
s2cRhoType t = liftM Core.R (s2cType t)
-- translate a monomorphic type
s2cType (TSub t t') = s2cType (TFun [t] t')
s2cType (TFun ts t) = do ts <- mapM s2cType ts
t <- s2cType t
return (Core.TFun ts t)
s2cType (TAp t t') = liftM2 Core.TAp (s2cType t) (s2cType t')
s2cType (TCon c) = return (Core.TId c)
s2cType (TVar v) = return (Core.TId v)
s2cType (TWild) = do k <- newKVar
Core.newTVar k
-- translate qualifiers, separating predicates from kind signatures along the way
s2cQuals qs = s2c [] [] qs
where
s2c ps ke [] = return (reverse ps, reverse ke)
s2c ps ke (PKind v k : qs) = do k <- s2cKind k
s2c ps ((v,k) : ke) qs
s2c ps ke (PType t : qs) = do p <- s2cQualType t
s2c (p : ps) ke qs
-- Kinds ==============================================================================
-- translate a kind
s2cKind Star = return Star
s2cKind KWild = newKVar
s2cKind (KFun k k') = liftM2 KFun (s2cKind k) (s2cKind k')
s2cKSig (v,k) = do k <- s2cKind k
return (v,k)
-- Expressions and bindings ============================================================
-- the translated default case alternative
dflt = [(Core.PWild, Core.EVar (prim Fail))]
-- translate a case alternative, inheriting type signature t top-down
s2cA env t (Alt (ELit l) (RExp e)) = do e' <- s2cEc env t e
return (Core.PLit l, e')
s2cA env t (Alt (ECon c) (RExp e)) = do e' <- s2cEc env (TFun ts t) e
return (Core.PCon c, e')
where ts = splitArgs (lookupT c env)
-- translate a record field
s2cF env (Field s e) = do e <- s2cEc env (snd (splitT (lookupT s env))) e
return (s,e)
-- split bindings bs into type signatures and equations
splitBinds bs = s2cB [] [] bs
where
s2cB sigs eqs [] = (reverse sigs, reverse eqs)
s2cB sigs eqs (BSig vs t : bs) = s2cB (vs `zip` repeat t ++ sigs) eqs bs
s2cB sigs eqs (BEqn (LFun v []) (RExp e) : bs)
= s2cB sigs ((v,e):eqs) bs
-- translate equation eqs in the scope of corresponding signatures sigs
s2cBinds env bs = do (ts,es) <- fmap unzip (mapM s2cEqn eqs)
let te = vs `zip` ts
te' <- s2cTE te
return (te, Core.Binds isRec te' (vs `zip` es))
where (sigs,eqs) = splitBinds bs
vs = dom eqs
isRec = not (null (filter (not . isPatTemp) vs `intersect` evars (rng eqs)))
env' = addSigs sigs env
s2cEqn (v,e) = case lookup v sigs of
Nothing -> s2cEi env' e
Just t -> do e <- s2cEc env' t' e
return (t,e)
where t' = if explicit (annot v) then expl t else peel t
-- Expressions, inherit mode ===============================================================
-- translate an expression, inheriting type signature t top-down
s2cEc env t (ELam ps e) = do e' <- s2cEc (addSigs te env) t' e
te' <- s2cTE te
return (Core.ELam te' e')
where (te,t') = mergeT ps t
s2cEc env _ (EAp e1 e2) = do (t,e1) <- s2cEi env e1
let (t1,_) = splitT t
e2 <- s2cEc env (peel t1) e2
return (Core.eAp2 e1 [e2])
s2cEc env t (ELet bs e) = do (te',bs') <- s2cBinds env bs
e' <- s2cEc (addSigs te' env) t e
return (Core.ELet bs' e')
s2cEc env t (ECase e alts) = do e <- s2cEc env TWild e
alts <- mapM (s2cA env t) alts
return (Core.ECase e (alts++dflt))
s2cEc env t (ESelect e s) = do e <- s2cEc env (peel t1) e
return (Core.ESel e s)
where (t1,_) = splitT (lookupT s env)
s2cEc env t (ECon c) = return (Core.ECon c)
s2cEc env t (EVar v) = return (Core.EVar v)
s2cEc env t (ELit l) = return (Core.ELit l)
s2cEc env _ e = s2cE env e
-- Expressions, agnostic mode ================================================================
-- translate an expression whose type cannot be rank-N polymorphic
-- (i.e., no point inheriting nor synthesizing signatures)
s2cE env (ERec (Just (c,_)) eqs) = do eqs <- mapM (s2cF env) eqs
return (Core.ERec c eqs)
s2cE env (EAct (Just x) [SExp e]) = do (_,e) <- s2cEi env e
return (Core.EAct (Core.EVar x) e)
s2cE env (EReq (Just x) [SExp e]) = do (_,e) <- s2cEi env e
return (Core.EReq (Core.EVar x) e)
s2cE env (EDo (Just x) Nothing ss) = do c <- s2cS env ss
t <- s2cType TWild
return (Core.EDo x t c)
s2cE env (ETempl (Just x) Nothing ss) = do c <- s2cS (addSigs te env) ss
t <- s2cType TWild
te' <- s2cTE te
return (Core.ETempl x t te' c)
where
vs = assignedVars ss
te = sigs ss
sigs [] = []
sigs (SAss (ESig (EVar v) t) _ :ss) = (v,t) : sigs ss
sigs (SAss (EVar v) _:ss) = (v,TWild) : sigs ss
sigs (_ : ss) = sigs ss
s2cE env e = internalError "s2cE: did not expect" e
-- Statements ==================================================================================
-- translate a statement list
s2cS env [] = return (Core.CRet (Core.ECon (prim UNITTERM)))
s2cS env [SRet e] = do (t,e') <- s2cEi env e
return (Core.CRet e')
s2cS env [SExp e] = do (t,e') <- s2cEi env e
return (Core.CExp e')
s2cS env (SGen (ESig (EVar v) t) e :ss) = do t' <- s2cType t
e' <- s2cEc env TWild e
c <- s2cS (addSigs [(v,t)] env) ss
return (Core.CGen v t' e' c)
s2cS env (SGen (EVar v) e : ss) = do (_,e') <- s2cEi env e
t <- s2cType TWild
c <- s2cS env ss
return (Core.CGen v t e' c)
s2cS env (SAss (ESig v t) e : ss) = s2cS env (SAss v e : ss)
s2cS env (SAss (EVar v) e : ss) = do e' <- s2cEc env (lookupT v env) e
c <- s2cS env ss
return (Core.CAss v e' c)
s2cS env (SBind bs : ss) = do (te',bs') <- s2cBinds env bs
c <- s2cS (addSigs te' env) ss
return (Core.CLet bs' c)
-- Expressions, synthesize mode ================================================================
-- translate an expression, synthesize type signature bottom-up
s2cEi env (ELam ps e) = do (t,e') <- s2cEi (addSigs te env) e
te' <- s2cTE te
return (TFun (rng te) t, Core.ELam te' e')
where (te,_) = mergeT ps TWild
s2cEi env (EAp e1 e2) = do (t,e1) <- s2cEi env e1
let (t1,t2) = splitT t
e2 <- s2cEc env (peel t1) e2
return (t2, Core.eAp2 e1 [e2])
s2cEi env (ELet bs e) = do (te',bs') <- s2cBinds env bs
(t,e') <- s2cEi (addSigs te' env) e
return (t, Core.ELet bs' e')
s2cEi env (ECase e alts) = do e <- s2cEc env TWild e
alts <- mapM (s2cA env TWild) alts
return (TWild, Core.ECase e (alts++dflt))
s2cEi env (ESelect e s) = do e <- s2cEc env (peel t1) e
return (t2, Core.ESel e s)
where (t1,t2) = splitT (lookupT s env)
s2cEi env (ECon c) = return (lookupT c env, Core.ECon c)
s2cEi env (EVar v) = return (lookupT v env, Core.EVar v)
s2cEi env (ELit l) = return (TWild, Core.ELit l)
s2cEi env e = do e' <- s2cE env e
return (TWild, e')
-- Misc ====================================================================================
-- translate type enviroment te
s2cTE te = mapM s2cVT te
where s2cVT (v,t) = do t <- s2cQualType t
return (v,t)
-- split a function type into domain (one parameter only) and range
-- if not a function type, fail gracefully (error will be caught later by real type-checker)
splitT (TFun [t] t') = (t, t')
splitT (TFun (t:ts) t') = (t, TFun ts t')
splitT TWild = (TWild,TWild)
splitT _ = (TWild,TWild)
-- return the domain of a function type (all immediate parameters)
splitArgs (TFun ts t) = ts
splitArgs t = []
-- merge any signatures in patterns ps with domain of type t, pair with range of t
mergeT ps t = (zipWith f ts ps, t')
where (ts,t') = split (length ps) t
f t (EVar v) = (v,t)
f t (ESig (EVar v) t') = (v,t')
f t e = internalError "mergeT: did not expect" e
split 0 t = ([],t)
split n t = (t1:ts,t')
where (t1,t2) = splitT t
(ts,t') = split (n-1) t2
-- find and instantate the type signature for x if present, otherwise return _
lookupT x env = case lookup x (sigs env) of
Nothing -> TWild
Just t -> peel t
-- peel off the outermost qualifiers of a type, replacing all bound variables with _
peel (TQual t ps) = mkWild (bvars ps) t
peel t = t
-- turn class and subtype predicates into explicit function arguments, and peel off the quantifiers
expl (TQual t ps) = mkWild (bvars ps) (TFun ts t)
where ts = [ t | PType t <- ps ]
-- replace all variables vs in a type by _
mkWild vs (TQual t ps) = TQual (mkWild vs' t) (map (mkWild' vs') ps)
where vs' = vs \\ bvars ps
mkWild vs (TAp t t') = TAp (mkWild vs t) (mkWild vs t')
mkWild vs (TFun ts t) = TFun (map (mkWild vs) ts) (mkWild vs t)
mkWild vs (TSub t t') = TSub (mkWild vs t) (mkWild vs t')
mkWild vs (TList t) = TList (mkWild vs t)
mkWild vs (TTup ts) = TTup (map (mkWild vs) ts)
mkWild vs (TVar v)
| v `elem` vs = TWild
mkWild vs t = t
-- replace all variables vs in a predicate by _
mkWild' vs (PType t) = PType (mkWild vs t)
mkWild' vs p = p
-- Checking whether bindings are recursive
checkRecBinds (Core.Binds _ te es@[(x,e)])
= Core.Binds (x `elem` evars e) te es
checkRecBinds (Core.Binds _ te es)
= Core.Binds True te es
|
UBMLtonGroup/timberc
|
src/Syntax2Core.hs
|
bsd-3-clause
| 19,496 | 0 | 15 | 8,396 | 5,869 | 2,914 | 2,955 | 241 | 4 |
{-# LANGUAGE TupleSections #-}
module Magic.BoosterPack
( genPack
) where
import Magic.Card
import Prelude
import System.Random
import System.Random.Shuffle
import Control.Applicative ((<$>))
import Control.Monad
genPack :: [Card] -> IO [RealCard]
genPack cards = do
isMythic <- (==1) <$> getStdRandom (randomR (1 :: Int, 8))
isFoil <- (==1) <$> getStdRandom (randomR (1 :: Int, 4))
f <- map foil <$> if isFoil then take 1 <$> shuffleM cards else return []
r <- map nonFoil <$> take 1 <$> shuffleM (if isMythic then mythic else rare)
u <- map nonFoil <$> take 3 <$> shuffleM uncommon
c <- map nonFoil <$> if isFoil then take 9 <$> shuffleM common else take 10 <$> shuffleM common
l <- map nonFoil <$> take 1 <$> shuffleM land
return $ f ++ r ++ u ++ c ++ l
where
mythic = filter (withRarity MythicRare) $ cards
rare = filter (withRarity Rare) $ cards
uncommon = filter (withRarity Uncommon) $ cards
common = filter (not . fLand) . filter (withRarity Common) $ cards
land = filter fLand $ cards
fLand x = withCardType Land x && withSupertype Basic x
-- vim: set expandtab:
|
mkut/libmtg
|
Magic/BoosterPack.hs
|
bsd-3-clause
| 1,156 | 0 | 12 | 272 | 448 | 226 | 222 | 25 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ImpredicativeTypes #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- | An exchange type that broadcasts all incomings 'Post' messages.
module Control.Distributed.Process.Execution.Exchange.Broadcast
(
broadcastExchange
, broadcastExchangeT
, broadcastClient
, bindToBroadcaster
, BroadcastExchange
) where
import Control.Concurrent.STM (STM, atomically)
import Control.Concurrent.STM.TChan
( TChan
, newBroadcastTChanIO
, dupTChan
, readTChan
, writeTChan
)
import Control.DeepSeq (NFData)
import Control.Distributed.Process
( Process
, MonitorRef
, ProcessMonitorNotification(..)
, ProcessId
, SendPort
, processNodeId
, getSelfPid
, getSelfNode
, liftIO
, newChan
, sendChan
, unsafeSend
, unsafeSendChan
, receiveWait
, match
, matchIf
, die
, handleMessage
, Match
)
import qualified Control.Distributed.Process as P
import Control.Distributed.Process.Serializable()
import Control.Distributed.Process.Execution.Exchange.Internal
( startExchange
, configureExchange
, Message(..)
, Exchange(..)
, ExchangeType(..)
, applyHandlers
)
import Control.Distributed.Process.Extras.Internal.Types
( Channel
, ServerDisconnected(..)
)
import Control.Distributed.Process.Extras.Internal.Unsafe -- see [note: pcopy]
( PCopy
, pCopy
, pUnwrap
, matchChanP
, InputStream(Null)
, newInputStream
)
import Control.Monad (forM_, void)
import Data.Accessor
( Accessor
, accessor
, (^:)
)
import Data.Binary
import qualified Data.Foldable as Foldable (toList)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Typeable (Typeable)
import GHC.Generics
-- newtype RoutingTable r =
-- RoutingTable { routes :: (Map String (Map ProcessId r)) }
-- [note: BindSTM, BindPort and safety]
-- We keep these two /bind types/ separate, since only one of them
-- is truly serializable. The risk of unifying them is that at some
-- later time a maintainer might not realise that BindSTM cannot be
-- sent over the wire due to our use of PCopy.
--
data BindPort = BindPort { portClient :: !ProcessId
, portSend :: !(SendPort Message)
} deriving (Typeable, Generic)
instance Binary BindPort where
instance NFData BindPort where
data BindSTM =
BindSTM { stmClient :: !ProcessId
, stmSend :: !(SendPort (PCopy (InputStream Message)))
} deriving (Typeable)
{- | forall r. (Routable r) =>
BindR { client :: !ProcessId
, key :: !String
, chanC :: !r
}
deriving (Typeable, Generic)
-}
data OutputStream =
WriteChan (SendPort Message)
| WriteSTM (Message -> STM ())
-- | WriteP ProcessId
| NoWrite
deriving (Typeable)
data Binding = Binding { outputStream :: !OutputStream
, inputStream :: !(InputStream Message)
}
| PidBinding !ProcessId
deriving (Typeable)
data BindOk = BindOk
deriving (Typeable, Generic)
instance Binary BindOk where
instance NFData BindOk where
data BindFail = BindFail !String
deriving (Typeable, Generic)
instance Binary BindFail where
instance NFData BindFail where
data BindPlease = BindPlease
deriving (Typeable, Generic)
instance Binary BindPlease where
instance NFData BindPlease where
type BroadcastClients = Map ProcessId Binding
data BroadcastEx =
BroadcastEx { _routingTable :: !BroadcastClients
, channel :: !(TChan Message)
}
type BroadcastExchange = ExchangeType BroadcastEx
--------------------------------------------------------------------------------
-- Starting/Running the Exchange --
--------------------------------------------------------------------------------
-- | Start a new /broadcast exchange/ and return a handle to the exchange.
broadcastExchange :: Process Exchange
broadcastExchange = broadcastExchangeT >>= startExchange
-- | The 'ExchangeType' of a broadcast exchange. Can be combined with the
-- @startSupervisedRef@ and @startSupervised@ APIs.
--
broadcastExchangeT :: Process BroadcastExchange
broadcastExchangeT = do
ch <- liftIO newBroadcastTChanIO
return $ ExchangeType { name = "BroadcastExchange"
, state = BroadcastEx Map.empty ch
, configureEx = apiConfigure
, routeEx = apiRoute
}
--------------------------------------------------------------------------------
-- Client Facing API --
--------------------------------------------------------------------------------
-- | Create a binding to the given /broadcast exchange/ for the calling process
-- and return an 'InputStream' that can be used in the @expect@ and
-- @receiveWait@ family of messaging primitives. This form of client interaction
-- helps avoid cluttering the caller's mailbox with 'Message' data, since the
-- 'InputChannel' provides a separate input stream (in a similar fashion to
-- a typed channel).
-- Example:
--
-- > is <- broadcastClient ex
-- > msg <- receiveWait [ matchInputStream is ]
-- > handleMessage (payload msg)
--
broadcastClient :: Exchange -> Process (InputStream Message)
broadcastClient ex@Exchange{..} = do
myNode <- getSelfNode
us <- getSelfPid
if processNodeId pid == myNode -- see [note: pcopy]
then do (sp, rp) <- newChan
configureExchange ex $ pCopy (BindSTM us sp)
mRef <- P.monitor pid
P.finally (receiveWait [ matchChanP rp
, handleServerFailure mRef ])
(P.unmonitor mRef)
else do (sp, rp) <- newChan :: Process (Channel Message)
configureExchange ex $ BindPort us sp
mRef <- P.monitor pid
P.finally (receiveWait [
match (\(_ :: BindOk) -> return $ newInputStream $ Left rp)
, match (\(f :: BindFail) -> die f)
, handleServerFailure mRef
])
(P.unmonitor mRef)
-- | Bind the calling process to the given /broadcast exchange/. For each
-- 'Message' the exchange receives, /only the payload will be sent/
-- to the calling process' mailbox.
--
-- Example:
--
-- (producer)
-- > post ex "Hello"
--
-- (consumer)
-- > bindToBroadcaster ex
-- > expect >>= liftIO . putStrLn
--
bindToBroadcaster :: Exchange -> Process ()
bindToBroadcaster ex@Exchange{..} = do
us <- getSelfPid
configureExchange ex $ (BindPlease, us)
--------------------------------------------------------------------------------
-- Exchage Definition/State & API Handlers --
--------------------------------------------------------------------------------
apiRoute :: BroadcastEx -> Message -> Process BroadcastEx
apiRoute ex@BroadcastEx{..} msg = do
liftIO $ atomically $ writeTChan channel msg
forM_ (Foldable.toList _routingTable) $ routeToClient msg
return ex
where
routeToClient m (PidBinding p) = P.forward (payload m) p
routeToClient m b@(Binding _ _) = writeToStream (outputStream b) m
-- TODO: implement unbind!!?
apiConfigure :: BroadcastEx -> P.Message -> Process BroadcastEx
apiConfigure ex msg = do
-- for unsafe / non-serializable message passing hacks, see [note: pcopy]
applyHandlers ex msg $ [ \m -> handleMessage m (handleBindPort ex)
, \m -> handleBindSTM ex m
, \m -> handleMessage m (handleBindPlease ex)
, \m -> handleMessage m (handleMonitorSignal ex)
, (const $ return $ Just ex)
]
where
handleBindPlease ex' (BindPlease, p) = do
case lookupBinding ex' p of
Nothing -> return $ (routingTable ^: Map.insert p (PidBinding p)) ex'
Just _ -> return ex'
handleMonitorSignal bx (ProcessMonitorNotification _ p _) =
return $ (routingTable ^: Map.delete p) bx
handleBindSTM ex'@BroadcastEx{..} msg' = do
bind' <- pUnwrap msg' :: Process (Maybe BindSTM) -- see [note: pcopy]
case bind' of
Nothing -> return Nothing
Just s -> do
let binding = lookupBinding ex' (stmClient s)
case binding of
Nothing -> createBinding ex' s >>= \ex'' -> handleBindSTM ex'' msg'
Just b -> sendBinding (stmSend s) b >> return (Just ex')
createBinding bEx'@BroadcastEx{..} BindSTM{..} = do
void $ P.monitor stmClient
nch <- liftIO $ atomically $ dupTChan channel
let istr = newInputStream $ Right (readTChan nch)
let ostr = NoWrite -- we write to our own channel, not the broadcast
let bnd = Binding ostr istr
return $ (routingTable ^: Map.insert stmClient bnd) bEx'
sendBinding sp' bs = unsafeSendChan sp' $ pCopy (inputStream bs)
handleBindPort :: BroadcastEx -> BindPort -> Process BroadcastEx
handleBindPort x@BroadcastEx{..} BindPort{..} = do
let binding = lookupBinding x portClient
case binding of
Just _ -> unsafeSend portClient (BindFail "DuplicateBinding") >> return x
Nothing -> do
let istr = Null
let ostr = WriteChan portSend
let bound = Binding ostr istr
void $ P.monitor portClient
unsafeSend portClient BindOk
return $ (routingTable ^: Map.insert portClient bound) x
lookupBinding BroadcastEx{..} k = Map.lookup k $ _routingTable
{- [note: pcopy]
We rely on risky techniques here, in order to allow for sharing useful
data that is not really serializable. For Cloud Haskell generally, this is
a bad idea, since we want message passing to work both locally and in a
distributed setting. In this case however, what we're really attempting is
an optimisation, since we only use unsafe PCopy based techniques when dealing
with exchange clients residing on our (local) node.
The PCopy mechanism is defined in the (aptly named) "Unsafe" module.
-}
-- TODO: move handleServerFailure into Primitives.hs
writeToStream :: OutputStream -> Message -> Process ()
writeToStream (WriteChan sp) = sendChan sp -- see [note: safe remote send]
writeToStream (WriteSTM stm) = liftIO . atomically . stm
writeToStream NoWrite = const $ return ()
{-# INLINE writeToStream #-}
{- [note: safe remote send]
Although we go to great lengths here to avoid serialization and/or copying
overheads, there are some activities for which we prefer to play it safe.
Chief among these is delivering messages to remote clients. Thankfully, our
unsafe @sendChan@ primitive will crash the caller/sender if there are any
encoding problems, however it is only because we /know/ for certain that
our recipient is remote, that we've chosen to write via a SendPort in the
first place! It makes sense therefore, to use the safe @sendChan@ operation
here, since for a remote call we /cannot/ avoid the overhead of serialization
anyway.
-}
handleServerFailure :: MonitorRef -> Match (InputStream Message)
handleServerFailure mRef =
matchIf (\(ProcessMonitorNotification r _ _) -> r == mRef)
(\(ProcessMonitorNotification _ _ d) -> die $ ServerDisconnected d)
routingTable :: Accessor BroadcastEx BroadcastClients
routingTable = accessor _routingTable (\r e -> e { _routingTable = r })
|
haskell-distributed/distributed-process-execution
|
src/Control/Distributed/Process/Execution/Exchange/Broadcast.hs
|
bsd-3-clause
| 11,854 | 0 | 20 | 2,900 | 2,249 | 1,211 | 1,038 | 225 | 5 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module Test.ZM.ADT.StoreProtocol.Ke83859e52e9a (StoreProtocol(..)) where
import qualified Prelude(Eq,Ord,Show)
import qualified GHC.Generics
import qualified Flat
import qualified Data.Model
import qualified Test.ZM.ADT.SHAKE128_48.K9f214799149b
data StoreProtocol a = Save a
| Solve (Test.ZM.ADT.SHAKE128_48.K9f214799149b.SHAKE128_48 a)
| Solved (Test.ZM.ADT.SHAKE128_48.K9f214799149b.SHAKE128_48 a) a
deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat)
instance ( Data.Model.Model a ) => Data.Model.Model ( StoreProtocol a )
|
tittoassini/typed
|
test/Test/ZM/ADT/StoreProtocol/Ke83859e52e9a.hs
|
bsd-3-clause
| 672 | 0 | 9 | 111 | 168 | 105 | 63 | 13 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Network.XmlRpc.Wai (waiXmlRpcServer) where
import Control.Monad.IO.Class
import Control.Monad.Error
import Network.HTTP.Types
import qualified Network.Wai as W
import Data.Conduit (($$), ($=), (=$))
import qualified Data.Conduit as C
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.List as CL
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BC
import qualified Data.ByteString.Lazy.Char8 as LBC
import Data.Monoid
import qualified Blaze.ByteString.Builder as BL
import qualified Network.XmlRpc.Server as XR
import qualified Network.XmlRpc.Internals as XRI
handlerSink :: [(String, XR.XmlRpcMethod)] -> C.Sink ByteString (C.ResourceT IO) W.Response
handlerSink ms = C.sinkState mempty push close
where
push builder input = return $ C.StateProcessing (builder <> BL.fromByteString input)
close :: BL.Builder -> C.ResourceT IO W.Response
close builder = do let bs = BL.toByteString builder
ebody <- liftIO $ runErrorT $ dispatch $ BC.unpack bs
case ebody of
Left e -> do liftIO $ putStrLn e
return $ W.responseLBS internalServerError500 [] $ LBC.pack ""
Right body -> do liftIO $ LBC.putStrLn body
return $ W.responseLBS ok200 [] body
dispatch :: String -> XRI.Err IO LBC.ByteString
dispatch req = do call <- XRI.parseCall req
result <- XR.methods ms call
let res = XRI.renderResponse result
return res
waiXmlRpcServer :: [(String, XR.XmlRpcMethod)] -> W.Application
waiXmlRpcServer ms = app
where
app :: W.Request -> C.ResourceT IO W.Response
app req = (W.requestBody req) $$ (handlerSink ms)
|
akiochiai/haxr-wai
|
Network/XmlRpc/Wai.hs
|
bsd-3-clause
| 2,000 | 0 | 17 | 588 | 552 | 303 | 249 | 38 | 2 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, GADTs #-}
-- | The @esqueleto@ EDSL (embedded domain specific language).
-- This module replaces @Database.Persist@, so instead of
-- importing that module you should just import this one:
--
-- @
-- -- For a module using just esqueleto.
-- import Database.Esqueleto
-- @
--
-- If you need to use @persistent@'s default support for queries
-- as well, either import it qualified:
--
-- @
-- -- For a module that mostly uses esqueleto.
-- import Database.Esqueleto
-- import qualified Database.Persistent as P
-- @
--
-- or import @esqueleto@ itself qualified:
--
-- @
-- -- For a module uses esqueleto just on some queries.
-- import Database.Persistent
-- import qualified Database.Esqueleto as E
-- @
--
-- Other than identifier name clashes, @esqueleto@ does not
-- conflict with @persistent@ in any way.
module Database.Esqueleto
( -- * Setup
-- $setup
-- * Introduction
-- $introduction
-- * Getting started
-- $gettingstarted
-- * @esqueleto@'s Language
Esqueleto( where_, on, groupBy, orderBy, rand, asc, desc, limit, offset
, distinct, distinctOn, don, distinctOnOrderBy, having, locking
, sub_select, sub_selectDistinct, (^.), (?.)
, val, isNothing, just, nothing, joinV, countRows, count, not_
, (==.), (>=.), (>.), (<=.), (<.), (!=.), (&&.), (||.)
, (+.), (-.), (/.), (*.)
, random_, round_, ceiling_, floor_
, min_, max_, sum_, avg_, castNum, castNumM
, coalesce, coalesceDefault
, lower_, like, ilike, (%), concat_, (++.)
, subList_select, subList_selectDistinct, valList
, in_, notIn, exists, notExists
, set, (=.), (+=.), (-=.), (*=.), (/=.)
, case_ )
, when_
, then_
, else_
, from
, Value(..)
, unValue
, ValueList(..)
, OrderBy
, DistinctOn
, LockingKind(..)
-- ** Joins
, InnerJoin(..)
, CrossJoin(..)
, LeftOuterJoin(..)
, RightOuterJoin(..)
, FullOuterJoin(..)
, OnClauseWithoutMatchingJoinException(..)
-- * SQL backend
, SqlQuery
, SqlExpr
, SqlEntity
, select
, selectDistinct
, selectSource
, selectDistinctSource
, delete
, deleteCount
, update
, updateCount
, insertSelect
, insertSelectDistinct
, (<#)
, (<&>)
-- * RDBMS-specific modules
-- $rdbmsSpecificModules
-- * Helpers
, valkey
, valJ
-- * Re-exports
-- $reexports
, deleteKey
, module Database.Esqueleto.Internal.PersistentImport
) where
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Trans.Reader (ReaderT)
import Data.Int (Int64)
import Database.Esqueleto.Internal.Language
import Database.Esqueleto.Internal.Sql
import Database.Esqueleto.Internal.PersistentImport
import qualified Database.Persist
-- $setup
--
-- If you're already using @persistent@, then you're ready to use
-- @esqueleto@, no further setup is needed. If you're just
-- starting a new project and would like to use @esqueleto@, take
-- a look at @persistent@'s book first
-- (<http://www.yesodweb.com/book/persistent>) to learn how to
-- define your schema.
----------------------------------------------------------------------
-- $introduction
--
-- The main goals of @esqueleto@ are to:
--
-- * Be easily translatable to SQL. When you take a look at a
-- @esqueleto@ query, you should be able to know exactly how
-- the SQL query will end up. (As opposed to being a
-- relational algebra EDSL such as HaskellDB, which is
-- non-trivial to translate into SQL.)
--
-- * Support the mostly used SQL features. We'd like you to be
-- able to use @esqueleto@ for all of your queries, no
-- exceptions. Send a pull request or open an issue on our
-- project page (<https://github.com/prowdsponsor/esqueleto>) if
-- there's anything missing that you'd like to see.
--
-- * Be as type-safe as possible. We strive to provide as many
-- type checks as possible. If you get bitten by some invalid
-- code that type-checks, please open an issue on our project
-- page so we can take a look.
--
-- However, it is /not/ a goal to be able to write portable SQL.
-- We do not try to hide the differences between DBMSs from you,
-- and @esqueleto@ code that works for one database may not work
-- on another. This is a compromise we have to make in order to
-- give you as much control over the raw SQL as possible without
-- losing too much convenience. This also means that you may
-- type-check a query that doesn't work on your DBMS.
----------------------------------------------------------------------
-- $gettingstarted
--
-- We like clean, easy-to-read EDSLs. However, in order to
-- achieve this goal we've used a lot of type hackery, leading to
-- some hard-to-read type signatures. On this section, we'll try
-- to build some intuition about the syntax.
--
-- For the following examples, we'll use this example schema:
--
-- @
-- share [mkPersist sqlSettings, mkMigrate \"migrateAll\"] [persist|
-- Person
-- name String
-- age Int Maybe
-- deriving Eq Show
-- BlogPost
-- title String
-- authorId PersonId
-- deriving Eq Show
-- Follow
-- follower PersonId
-- followed PersonId
-- deriving Eq Show
-- |]
-- @
--
-- Most of @esqueleto@ was created with @SELECT@ statements in
-- mind, not only because they're the most common but also
-- because they're the most complex kind of statement. The most
-- simple kind of @SELECT@ would be:
--
-- @
-- SELECT *
-- FROM Person
-- @
--
-- In @esqueleto@, we may write the same query above as:
--
-- @
-- do people <- 'select' $
-- 'from' $ \\person -> do
-- return person
-- liftIO $ mapM_ (putStrLn . personName . entityVal) people
-- @
--
-- The expression above has type @SqlPersist m ()@, while
-- @people@ has type @[Entity Person]@. The query above will be
-- translated into exactly the same query we wrote manually, but
-- instead of @SELECT *@ it will list all entity fields (using
-- @*@ is not robust). Note that @esqueleto@ knows that we want
-- an @Entity Person@ just because of the @personName@ that we're
-- printing later.
--
-- However, most of the time we need to filter our queries using
-- @WHERE@. For example:
--
-- @
-- SELECT *
-- FROM Person
-- WHERE Person.name = \"John\"
-- @
--
-- In @esqueleto@, we may write the same query above as:
--
-- @
-- 'select' $
-- 'from' $ \\p -> do
-- 'where_' (p '^.' PersonName '==.' 'val' \"John\")
-- return p
-- @
--
-- Although @esqueleto@'s code is a bit more noisy, it's has
-- almost the same structure (save from the @return@). The
-- @('^.')@ operator is used to project a field from an entity.
-- The field name is the same one generated by @persistent@'s
-- Template Haskell functions. We use 'val' to lift a constant
-- Haskell value into the SQL query.
--
-- Another example would be:
--
-- @
-- SELECT *
-- FROM Person
-- WHERE Person.age >= 18
-- @
--
-- In @esqueleto@, we may write the same query above as:
--
-- @
-- 'select' $
-- 'from' $ \\p -> do
-- 'where_' (p '^.' PersonAge '>=.' 'just' ('val' 18))
-- return p
-- @
--
-- Since @age@ is an optional @Person@ field, we use 'just' lift
-- @'val' 18 :: SqlExpr (Value Int)@ into @just ('val' 18) ::
-- SqlExpr (Value (Maybe Int))@.
--
-- Implicit joins are represented by tuples. For example, to get
-- the list of all blog posts and their authors, we could write:
--
-- @
-- SELECT BlogPost.*, Person.*
-- FROM BlogPost, Person
-- WHERE BlogPost.authorId = Person.id
-- ORDER BY BlogPost.title ASC
-- @
--
-- In @esqueleto@, we may write the same query above as:
--
-- @
-- 'select' $
-- 'from' $ \\(b, p) -> do
-- 'where_' (b '^.' BlogPostAuthorId '==.' p '^.' PersonId)
-- 'orderBy' ['asc' (b '^.' BlogPostTitle)]
-- return (b, p)
-- @
--
-- However, we may want your results to include people who don't
-- have any blog posts as well using a @LEFT OUTER JOIN@:
--
-- @
-- SELECT Person.*, BlogPost.*
-- FROM Person LEFT OUTER JOIN BlogPost
-- ON Person.id = BlogPost.authorId
-- ORDER BY Person.name ASC, BlogPost.title ASC
-- @
--
-- In @esqueleto@, we may write the same query above as:
--
-- @
-- 'select' $
-- 'from' $ \\(p `'LeftOuterJoin`` mb) -> do
-- 'on' ('just' (p '^.' PersonId) '==.' mb '?.' BlogPostAuthorId)
-- 'orderBy' ['asc' (p '^.' PersonName), 'asc' (mb '?.' BlogPostTitle)]
-- return (p, mb)
-- @
--
-- On a @LEFT OUTER JOIN@ the entity on the right hand side may
-- not exist (i.e. there may be a @Person@ without any
-- @BlogPost@s), so while @p :: SqlExpr (Entity Person)@, we have
-- @mb :: SqlExpr (Maybe (Entity BlogPost))@. The whole
-- expression above has type @SqlPersist m [(Entity Person, Maybe
-- (Entity BlogPost))]@. Instead of using @(^.)@, we used
-- @('?.')@ to project a field from a @Maybe (Entity a)@.
--
-- We are by no means limited to joins of two tables, nor by
-- joins of different tables. For example, we may want a list
-- the @Follow@ entity:
--
-- @
-- SELECT P1.*, Follow.*, P2.*
-- FROM Person AS P1
-- INNER JOIN Follow ON P1.id = Follow.follower
-- INNER JOIN P2 ON P2.id = Follow.followed
-- @
--
-- In @esqueleto@, we may write the same query above as:
--
-- @
-- 'select' $
-- 'from' $ \\(p1 `'InnerJoin`` f `'InnerJoin`` p2) -> do
-- 'on' (p2 '^.' PersonId '==.' f '^.' FollowFollowed)
-- 'on' (p1 '^.' PersonId '==.' f '^.' FollowFollower)
-- return (p1, f, p2)
-- @
--
-- /Note carefully that the order of the ON clauses is/
-- /reversed!/ You're required to write your 'on's in reverse
-- order because that helps composability (see the documentation
-- of 'on' for more details).
--
-- We also currently support @UPDATE@ and @DELETE@ statements.
-- For example:
--
-- @
-- do 'update' $ \\p -> do
-- 'set' p [ PersonName '=.' 'val' \"João\" ]
-- 'where_' (p '^.' PersonName '==.' 'val' \"Joao\")
-- 'delete' $
-- 'from' $ \\p -> do
-- 'where_' (p '^.' PersonAge '<.' 'just' ('val' 14))
-- @
--
-- The results of queries can also be used for insertions.
-- In @SQL@, we might write the following, inserting a new blog
-- post for every user:
--
-- @
-- INSERT INTO BlogPost
-- SELECT ('Group Blog Post', id)
-- FROM Person
-- @
--
-- In @esqueleto@, we may write the same query above as:
--
-- @
-- 'insertSelect' $ 'from' $ \\p->
-- return $ BlogPost '<#' \"Group Blog Post\" '<&>' (p '^.' PersonId)
-- @
--
-- Individual insertions can be performed through Persistent's
-- 'insert' function, reexported for convenience.
----------------------------------------------------------------------
-- $reexports
--
-- We re-export many symbols from @persistent@ for convenince:
--
-- * \"Store functions\" from "Database.Persist".
--
-- * Everything from "Database.Persist.Class" except for
-- @PersistQuery@ and @delete@ (use 'deleteKey' instead).
--
-- * Everything from "Database.Persist.Types" except for
-- @Update@, @SelectOpt@, @BackendSpecificFilter@ and @Filter@.
--
-- * Everything from "Database.Persist.Sql" except for
-- @deleteWhereCount@ and @updateWhereCount@.
----------------------------------------------------------------------
-- $rdbmsSpecificModules
--
-- There are many differences between SQL syntax and functions
-- supported by different RDBMSs. Since version 2.2.8,
-- @esqueleto@ includes modules containing functions that are
-- specific to a given RDBMS.
--
-- * PostgreSQL: "Database.Esqueleto.PostgreSQL".
--
-- In order to use these functions, you need to explicitly import
-- their corresponding modules, they're not re-exported here.
----------------------------------------------------------------------
-- | @valkey i = 'val' . 'toSqlKey'@
-- (<https://github.com/prowdsponsor/esqueleto/issues/9>).
valkey :: (Esqueleto query expr backend, ToBackendKey SqlBackend entity, PersistField (Key entity)) =>
Int64 -> expr (Value (Key entity))
valkey = val . toSqlKey
-- | @valJ@ is like @val@ but for something that is already a @Value@. The use
-- case it was written for was, given a @Value@ lift the @Key@ for that @Value@
-- into the query expression in a type safe way. However, the implementation is
-- more generic than that so we call it @valJ@.
--
-- Its important to note that the input entity and the output entity are
-- constrained to be the same by the type signature on the function
-- (<https://github.com/prowdsponsor/esqueleto/pull/69>).
--
-- /Since: 1.4.2/
valJ :: (Esqueleto query expr backend, PersistField (Key entity)) =>
Value (Key entity) -> expr (Value (Key entity))
valJ = val . unValue
----------------------------------------------------------------------
-- | Synonym for 'Database.Persist.Store.delete' that does not
-- clash with @esqueleto@'s 'delete'.
deleteKey :: ( PersistStore (PersistEntityBackend val)
, MonadIO m
, PersistEntity val )
=> Key val -> ReaderT (PersistEntityBackend val) m ()
deleteKey = Database.Persist.delete
|
krisajenkins/esqueleto
|
src/Database/Esqueleto.hs
|
bsd-3-clause
| 13,004 | 0 | 11 | 2,601 | 931 | 766 | 165 | 73 | 1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.NV.TextureShader2
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/NV/texture_shader2.txt NV_texture_shader2> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.NV.TextureShader2 (
-- * Enums
gl_DOT_PRODUCT_TEXTURE_3D_NV
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
|
phaazon/OpenGLRaw
|
src/Graphics/Rendering/OpenGL/Raw/NV/TextureShader2.hs
|
bsd-3-clause
| 661 | 0 | 4 | 78 | 37 | 31 | 6 | 3 | 0 |
module Main where
import Haste
import Haste.Concurrent
main = concurrent $ do
ctr <- newEmptyMVar
forkIO $ updater ctr
counter ctr 0
-- | This thread counts.
counter :: MVar Int -> Int -> CIO ()
counter ctr startval =
go startval
where
go n = do
putMVar ctr n
wait 1000
go (n+1)
-- | This thread updates the GUI.
updater :: MVar Int -> CIO ()
updater ctr =
withElem "counter" $ go
where
go e = do
x <- takeMVar ctr
setProp e "innerHTML" (show x)
go e
|
joelburget/haste-compiler
|
examples/concurrency/counter.hs
|
bsd-3-clause
| 516 | 0 | 11 | 156 | 193 | 90 | 103 | 21 | 1 |
module Database.Hitcask.Hint where
import Database.Hitcask.Types
import Database.Hitcask.Logs
import Database.Hitcask.Put
import qualified Data.ByteString.Char8 as B
import Data.Serialize.Put
import System.IO(hFlush, hClose)
import System.FilePath
writeHint :: HintFile -> Key -> ValueLocation -> IO ()
writeHint (LogFile h _) key loc = do
B.hPut h (hint key loc)
hFlush h
hint :: Key -> ValueLocation -> B.ByteString
hint key (ValueLocation f vs vp ts) = runPut $ do
putInt32 vs
putInt32 vp
putInt32 ts
putWithLength f
putInt32 (B.length key)
putByteString key
putWithLength :: String -> Put
putWithLength s = do
putInt32 (B.length packed)
putByteString packed
where packed = B.pack s
createHintFile :: FilePath -> IO HintFile
createHintFile fp = openLogFile (fp ++ ".hint")
hintFileFor :: MergedLog -> IO HintFile
hintFileFor = openLogFile . hintFilePathFor
hintFilePathFor :: MergedLog -> FilePath
hintFilePathFor l = root </> ts ++ ".hitcask.data.hint"
where root = dropFileName $ path l
ts = show $ getTimestamp $ path l
closeHint :: HintFile -> IO ()
closeHint = hClose . handle
|
tcrayford/hitcask
|
Database/Hitcask/Hint.hs
|
bsd-3-clause
| 1,125 | 0 | 11 | 199 | 387 | 196 | 191 | 35 | 1 |
{-# LANGUAGE CPP #-}
module Gre where
import Control.Monad
import Data.Binary.Put
import Data.Bits
import qualified Data.ByteString.Lazy as B
import Text.ParserCombinators.Parsec
import Text.ParserCombinators.Parsec.Perm
import Util
import Packet
import Lexer
#ifdef HRWS_TEST
import Debug.Trace
import Test.QuickCheck hiding ((.&.))
import Test.Framework (Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Text.Printf
#endif
parseGrePkt :: Parser Packet -> Parser GrePkt
parseGrePkt f = permute
(tuple <$?> (0x3000, parseIntAttribute "flags")
<|?> (0x0800, parseIntAttribute "protocol")
<|?> (0xcafecafe, parseIntAttribute "key")
<|?> (0, try (parseIntAttribute "seq"))
<|?> ([PPayload defaultPayload], parsePayload f))
where
tuple fl prot k s =
GrePkt (Gre fl prot k s)
greDecl :: Parser Packet -> Parser Packet
greDecl f = do
symbol "gre"
g <- parseGrePkt f
return (PGre g)
greWriteHdr :: Gre -> Put
greWriteHdr p = do
putWord16be (greFlags p)
putWord16be (greProtocol p)
-- Optional Key Field
when (greFlags p .&. 0x2000 == 0x2000) $
putWord32be $ greKey p
when (greFlags p .&. 0x1000 == 0x1000) $
putWord32be $ greSeq p
greWrite :: Gre -> Maybe Packet -> B.ByteString -> Put
greWrite h _ bs = do
greWriteHdr h
putLazyByteString bs
instance PacketWriteable GrePkt where packetWrite p = greWrite (grePktHeader p)
#ifdef HRWS_TEST
{- Unit Tests -}
instance Arbitrary Gre where
arbitrary = do
f <- arbitrary
p <- arbitrary
k <- arbitrary
s <- arbitrary
return (Gre f p k s)
testValidParse :: String -> (Gre -> Bool) -> Bool
testValidParse str fn =
case parse (dummyParsePacket greDecl) "packet parse" str of
Left err -> trace (show err) False
Right val -> fn $ testGrePkt val
testGreDefault :: () -> Bool
testGreDefault _ = let cmp f = defaultGre == f in
testValidParse "(gre)" cmp
testGrePkt :: Packet -> Gre
testGrePkt (PGre f) = grePktHeader f
testGrePkt _ = error "Unexpected packet type"
testGrePacket :: Gre -> Bool
testGrePacket pkt =
let cmp p = pkt == p in
testValidParse (printf "(gre flags=%d protocol=%d key=%d seq=%d)" (greFlags pkt)
(greProtocol pkt) (greKey pkt) (greSeq pkt)) cmp
testGreWrite :: () -> Bool
testGreWrite _ =
let expPkt = B.pack [0x30, 0x00, 0x08, 0x00, 0x12, 0x34, 0x56, 0x78, 0xaa, 0xaa, 0xaa, 0xaa] in
let cmp p = runPut (greWrite p Nothing B.empty) == expPkt in
testValidParse "(gre flags=0x3000 protocol=0x0800 key=0x12345678 seq=0xaaaaaaaa)" cmp
greTests :: [Test]
greTests = [
testProperty "GRE: Default Packet" testGreDefault,
testProperty "GRE: Packet" testGrePacket,
testProperty "GRE: Write" testGreWrite
]
#endif
|
karknu/rws
|
src/Gre.hs
|
bsd-3-clause
| 2,773 | 0 | 15 | 579 | 910 | 464 | 446 | 38 | 1 |
module StringCalculator
( implementations
, calculate
) where
import qualified StringCalculator.AST as AST
implementations :: [(String, String -> Either String Rational)]
implementations = [("AST", AST.calculate)]
calculate = AST.calculate
|
danstiner/infix-string-calculator
|
src/StringCalculator.hs
|
bsd-3-clause
| 255 | 0 | 8 | 43 | 66 | 41 | 25 | 7 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.