code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
main = do
rs <- sequence [getLine, getLine, getLine]
print rs
|
fabriceleal/learn-you-a-haskell
|
09/sequence.hs
|
mit
| 72
| 0
| 9
| 21
| 31
| 15
| 16
| 3
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
module Abt.Types.View
( View(..)
, View0
, _ViewOp
, mapView
) where
import Abt.Class.HEq1
import Abt.Types.Nat
import Data.Profunctor
import Data.Typeable hiding (Refl)
import Data.Vinyl
-- | @v@ is the type of variables; @o@ is the type of operators parameterized
-- by arities; @n@ is the "higher type"/valence of the term (i.e. a term has
-- @n=0@, a single binding has @n=1@, etc.); @phi@ is the functor which
-- interprets the inner structure of the view.
--
data View (v :: *) (o :: [Nat] -> *) (n :: Nat) (phi :: Nat -> *) where
V :: v -> View0 v o phi
(:\) :: v -> phi n -> View v o ('S n) phi
(:$) :: o ns -> Rec phi ns -> View0 v o phi
deriving instance Typeable View
infixl 2 :$
-- | First order term views.
--
type View0 v o phi = View v o 'Z phi
-- | Views are a (higher) functor.
--
mapView
:: (forall j . phi j -> psi j) -- ^ a natural transformation @phi -> psi@
-> View v o n phi -- ^ a view at @phi@
-> View v o n psi
mapView η = \case
V v -> V v
v :\ e -> v :\ η e
o :$ es -> o :$ η <<$>> es
-- | A prism to extract arguments from a proposed operator.
--
-- @
-- '_ViewOp' :: 'HEq1' o => o ns -> Prism' ('View0' v o phi) ('Rec' phi ns)
-- @
--
_ViewOp
:: ( Choice p
, Applicative f
, HEq1 o
)
=> o ns
-> p (Rec phi ns) (f (Rec phi ns))
-> p (View0 v o phi) (f (View0 v o phi))
_ViewOp o = dimap fro (either pure (fmap (o :$))) . right'
where
fro = \case
o' :$ es | Just Refl <- heq1 o o' -> Right es
e -> Left e
|
jonsterling/hs-abt
|
src/Abt/Types/View.hs
|
mit
| 1,710
| 0
| 14
| 419
| 523
| 289
| 234
| 43
| 3
|
module MemoryTestImport
( EmbeddedState (..)
, StreamEmbeddedState
, GlobalStreamEmbeddedState
, emptyEmbeddedState
, setEventMap
, setProjectionMap
) where
import Eventful.ProjectionCache.Memory
import Eventful.Store.Memory
import Eventful.UUID
data EmbeddedState state event key position
= EmbeddedState
{ _embeddedDummyArgument :: Int
, embeddedEventMap :: EventMap event
, embeddedProjectionMap :: ProjectionMap key position state
}
type StreamEmbeddedState state event = EmbeddedState state event UUID EventVersion
type GlobalStreamEmbeddedState state event key = EmbeddedState state event key SequenceNumber
emptyEmbeddedState :: EmbeddedState state event key position
emptyEmbeddedState = EmbeddedState 100 emptyEventMap emptyProjectionMap
setEventMap :: EmbeddedState state event key position -> EventMap event -> EmbeddedState state event key position
setEventMap state' eventMap = state' { embeddedEventMap = eventMap }
setProjectionMap
:: EmbeddedState state event key position
-> ProjectionMap key position state
-> EmbeddedState state event key position
setProjectionMap state' projectionMap = state' { embeddedProjectionMap = projectionMap }
|
jdreaver/eventful
|
eventful-memory/tests/MemoryTestImport.hs
|
mit
| 1,192
| 0
| 9
| 172
| 255
| 143
| 112
| 26
| 1
|
------------------------------------------------------------------------
-- |
-- Module : Haskal.ShelImports
-- License : GPL
--
------------------------------------------------------------------------
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 2 of the
-- License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
-- 02110-1301, USA.
module Haskal.ShellImports
( Command
, Cmd
, Program
, Marshal ( .. )
, DoIO
, io
, runCommand
, ( # )
, (-.)
, (>|)
, (&>|)
, (>|<)
) where
import Haskal.Command
import Haskal.Marshal
|
juhp/haskal
|
src/Haskal/ShellImports.hs
|
gpl-2.0
| 1,133
| 0
| 5
| 203
| 88
| 68
| 20
| 15
| 0
|
module Groups.Terms where
import Notes hiding (cyclic, inverse)
makeDefs
[ "magma"
, "semigroup"
, "monoid"
, "group"
, "neutral element"
, "subgroup"
, "trivial subgroup"
, "inverse"
, "cyclic"
, "generator"
, "order"
, "square"
, "square root"
, "quotient group"
]
makeThms
[ "inverse unique"
, "inverse of applied operation"
, "subgroup same identity"
, "generated set is group"
, "trivial subgroups"
, "element order divides group order"
, "square root unique in finite odd group"
, "finite odd group root computation"
]
|
NorfairKing/the-notes
|
src/Groups/Terms.hs
|
gpl-2.0
| 637
| 0
| 6
| 196
| 96
| 60
| 36
| -1
| -1
|
{-# LANGUAGE CPP #-}
{-
Copyright (C) 2009 John MacFarlane <jgm@berkeley.edu>,
Anton van Straaten <anton@appsolutions.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- Functions for content conversion.
-}
module Network.Gitit.ContentTransformer
(
-- * ContentTransformer runners
runPageTransformer
, runFileTransformer
-- * Gitit responders
, showRawPage
, showFileAsText
, showPage
, exportPage
, showHighlightedSource
, showFile
, preview
, applyPreCommitPlugins
-- * Cache support for transformers
, cacheHtml
, cachedHtml
-- * Content retrieval combinators
, rawContents
-- * Response-generating combinators
, textResponse
, mimeFileResponse
, mimeResponse
, exportPandoc
, applyWikiTemplate
-- * Content-type transformation combinators
, pageToWikiPandoc
, pageToPandoc
, pandocToHtml
, highlightSource
-- * Content or context augmentation combinators
, applyPageTransforms
, wikiDivify
, addPageTitleToPandoc
, addMathSupport
, addScripts
-- * ContentTransformer context API
, getFileName
, getPageName
, getLayout
, getParams
, getCacheable
-- * Pandoc and wiki content conversion support
, inlinesToURL
, inlinesToString
)
where
import Control.Exception (throwIO, catch)
import Control.Monad.State
import Control.Monad.Reader (ask)
import Data.Maybe (isNothing, mapMaybe)
import Network.Gitit.Cache (lookupCache, cacheContents)
import Network.Gitit.Export (exportFormats)
import Network.Gitit.Framework
import Network.Gitit.Layout
import Network.Gitit.Page (stringToPage)
import Network.Gitit.Server
import Network.Gitit.State
import Network.Gitit.Types
import Network.URI (isUnescapedInURI)
import Network.URL (encString)
import Prelude hiding (catch)
import System.FilePath
import Text.HTML.SanitizeXSS (sanitizeBalance)
import Text.Highlighting.Kate
import Text.Pandoc hiding (MathML, WebTeX, MathJax)
import Text.XHtml hiding ( (</>), dir, method, password, rev )
#if MIN_VERSION_blaze_html(0,5,0)
import Text.Blaze.Html.Renderer.String as Blaze ( renderHtml )
#else
import Text.Blaze.Renderer.String as Blaze ( renderHtml )
#endif
import qualified Data.Text as T
import qualified Data.Set as Set
import qualified Data.ByteString as S (concat)
import qualified Data.ByteString.Lazy as L (toChunks, fromChunks)
import qualified Data.FileStore as FS
import qualified Text.Pandoc as Pandoc
--
-- ContentTransformer runners
--
runTransformer :: ToMessage a
=> (String -> String)
-> ContentTransformer a
-> GititServerPart a
runTransformer pathFor xform = withData $ \params -> do
page <- getPage
cfg <- getConfig
evalStateT xform Context{ ctxFile = pathFor page
, ctxLayout = defaultPageLayout{
pgPageName = page
, pgTitle = page
, pgPrintable = pPrintable params
, pgMessages = pMessages params
, pgRevision = pRevision params
, pgLinkToFeed = useFeed cfg }
, ctxCacheable = True
, ctxTOC = tableOfContents cfg
, ctxBirdTracks = showLHSBirdTracks cfg
, ctxCategories = []
, ctxMeta = [] }
-- | Converts a @ContentTransformer@ into a @GititServerPart@;
-- specialized to wiki pages.
runPageTransformer :: ToMessage a
=> ContentTransformer a
-> GititServerPart a
runPageTransformer = runTransformer pathForPage
-- | Converts a @ContentTransformer@ into a @GititServerPart@;
-- specialized to non-pages.
runFileTransformer :: ToMessage a
=> ContentTransformer a
-> GititServerPart a
runFileTransformer = runTransformer id
--
-- Gitit responders
--
-- | Responds with raw page source.
showRawPage :: Handler
showRawPage = runPageTransformer rawTextResponse
-- | Responds with raw source (for non-pages such as source
-- code files).
showFileAsText :: Handler
showFileAsText = runFileTransformer rawTextResponse
-- | Responds with rendered wiki page.
showPage :: Handler
showPage = runPageTransformer htmlViaPandoc
-- | Responds with page exported into selected format.
exportPage :: Handler
exportPage = runPageTransformer exportViaPandoc
-- | Responds with highlighted source code.
showHighlightedSource :: Handler
showHighlightedSource = runFileTransformer highlightRawSource
-- | Responds with non-highlighted source code.
showFile :: Handler
showFile = runFileTransformer (rawContents >>= mimeFileResponse)
-- | Responds with rendered page derived from form data.
preview :: Handler
preview = runPageTransformer $
liftM (filter (/= '\r') . pRaw) getParams >>=
contentsToPage >>=
pageToWikiPandoc >>=
pandocToHtml >>=
return . toResponse . renderHtmlFragment
-- | Applies pre-commit plugins to raw page source, possibly
-- modifying it.
applyPreCommitPlugins :: String -> GititServerPart String
applyPreCommitPlugins = runPageTransformer . applyPreCommitTransforms
--
-- Top level, composed transformers
--
-- | Responds with raw source.
rawTextResponse :: ContentTransformer Response
rawTextResponse = rawContents >>= textResponse
-- | Responds with a wiki page in the format specified
-- by the @format@ parameter.
exportViaPandoc :: ContentTransformer Response
exportViaPandoc = rawContents >>=
maybe mzero return >>=
contentsToPage >>=
pageToWikiPandoc >>=
exportPandoc
-- | Responds with a wiki page. Uses the cache when
-- possible and caches the rendered page when appropriate.
htmlViaPandoc :: ContentTransformer Response
htmlViaPandoc = cachedHtml `mplus`
(rawContents >>=
maybe mzero return >>=
contentsToPage >>=
pageToWikiPandoc >>=
addMathSupport >>=
pandocToHtml >>=
wikiDivify >>=
applyWikiTemplate >>=
cacheHtml)
-- | Responds with highlighted source code in a wiki
-- page template. Uses the cache when possible and
-- caches the rendered page when appropriate.
highlightRawSource :: ContentTransformer Response
highlightRawSource =
cachedHtml `mplus`
(updateLayout (\l -> l { pgTabs = [ViewTab,HistoryTab] }) >>
rawContents >>=
highlightSource >>=
applyWikiTemplate >>=
cacheHtml)
--
-- Cache support for transformers
--
-- | Caches a response (actually just the response body) on disk,
-- unless the context indicates that the page is not cacheable.
cacheHtml :: Response -> ContentTransformer Response
cacheHtml resp' = do
params <- getParams
file <- getFileName
cacheable <- getCacheable
cfg <- lift getConfig
when (useCache cfg && cacheable && isNothing (pRevision params) && not (pPrintable params)) $
lift $ cacheContents file $ S.concat $ L.toChunks $ rsBody resp'
return resp'
-- | Returns cached page if available, otherwise mzero.
cachedHtml :: ContentTransformer Response
cachedHtml = do
file <- getFileName
params <- getParams
cfg <- lift getConfig
if useCache cfg && not (pPrintable params) && isNothing (pRevision params)
then do mbCached <- lift $ lookupCache file
let emptyResponse = setContentType "text/html; charset=utf-8" . toResponse $ ()
maybe mzero (\(_modtime, contents) -> lift . ok $ emptyResponse{rsBody = L.fromChunks [contents]}) mbCached
else mzero
--
-- Content retrieval combinators
--
-- | Returns raw file contents.
rawContents :: ContentTransformer (Maybe String)
rawContents = do
params <- getParams
file <- getFileName
fs <- lift getFileStore
let rev = pRevision params
liftIO $ catch (liftM Just $ FS.retrieve fs file rev)
(\e -> if e == FS.NotFound then return Nothing else throwIO e)
--
-- Response-generating combinators
--
-- | Converts raw contents to a text/plain response.
textResponse :: Maybe String -> ContentTransformer Response
textResponse Nothing = mzero -- fail quietly if file not found
textResponse (Just c) = mimeResponse c "text/plain; charset=utf-8"
-- | Converts raw contents to a response that is appropriate with
-- a mime type derived from the page's extension.
mimeFileResponse :: Maybe String -> ContentTransformer Response
mimeFileResponse Nothing = error "Unable to retrieve file contents."
mimeFileResponse (Just c) =
mimeResponse c =<< lift . getMimeTypeForExtension . takeExtension =<< getFileName
mimeResponse :: Monad m
=> String -- ^ Raw contents for response body
-> String -- ^ Mime type
-> m Response
mimeResponse c mimeType =
return . setContentType mimeType . toResponse $ c
-- | Converts Pandoc to response using format specified in parameters.
exportPandoc :: Pandoc -> ContentTransformer Response
exportPandoc doc = do
params <- getParams
page <- getPageName
cfg <- lift getConfig
let format = pFormat params
case lookup format (exportFormats cfg) of
Nothing -> error $ "Unknown export format: " ++ format
Just writer -> lift (writer page doc)
-- | Adds the sidebar, page tabs, and other elements of the wiki page
-- layout to the raw content.
applyWikiTemplate :: Html -> ContentTransformer Response
applyWikiTemplate c = do
Context { ctxLayout = layout } <- get
lift $ formattedPage layout c
--
-- Content-type transformation combinators
--
-- | Converts Page to Pandoc, applies page transforms, and adds page
-- title.
pageToWikiPandoc :: Page -> ContentTransformer Pandoc
pageToWikiPandoc page' =
pageToWikiPandoc' page' >>= addPageTitleToPandoc (pageTitle page')
pageToWikiPandoc' :: Page -> ContentTransformer Pandoc
pageToWikiPandoc' = applyPreParseTransforms >=>
pageToPandoc >=> applyPageTransforms
-- | Converts source text to Pandoc using default page type.
pageToPandoc :: Page -> ContentTransformer Pandoc
pageToPandoc page' = do
modifyContext $ \ctx -> ctx{ ctxTOC = pageTOC page'
, ctxCategories = pageCategories page'
, ctxMeta = pageMeta page' }
return $ readerFor (pageFormat page') (pageLHS page') (pageText page')
-- | Converts contents of page file to Page object.
contentsToPage :: String -> ContentTransformer Page
contentsToPage s = do
cfg <- lift getConfig
pn <- getPageName
return $ stringToPage cfg pn s
-- | Converts pandoc document to HTML.
pandocToHtml :: Pandoc -> ContentTransformer Html
pandocToHtml pandocContents = do
base' <- lift getWikiBase
toc <- liftM ctxTOC get
bird <- liftM ctxBirdTracks get
cfg <- lift getConfig
return $ primHtml $ T.unpack .
(if xssSanitize cfg then sanitizeBalance else id) . T.pack $
writeHtmlString def{
writerStandalone = True
, writerTemplate = "$if(toc)$<div id=\"TOC\">\n$toc$\n</div>\n$endif$\n$body$"
, writerHTMLMathMethod =
case mathMethod cfg of
MathML -> Pandoc.MathML Nothing
WebTeX u -> Pandoc.WebTeX u
MathJax u -> Pandoc.MathJax u
_ -> JsMath (Just $ base' ++
"/js/jsMath/easy/load.js")
, writerTableOfContents = toc
, writerExtensions = if bird
then Set.insert
Ext_literate_haskell
$ writerExtensions def
else writerExtensions def
-- note: javascript obfuscation gives problems on preview
, writerEmailObfuscation = ReferenceObfuscation
} pandocContents
-- | Returns highlighted source code.
highlightSource :: Maybe String -> ContentTransformer Html
highlightSource Nothing = mzero
highlightSource (Just source) = do
file <- getFileName
let formatOpts = defaultFormatOpts { numberLines = True, lineAnchors = True }
case languagesByExtension $ takeExtension file of
[] -> mzero
(l:_) -> return $ primHtml $ Blaze.renderHtml
$ formatHtmlBlock formatOpts
$! highlightAs l $ filter (/='\r') source
--
-- Plugin combinators
--
getPageTransforms :: ContentTransformer [Pandoc -> PluginM Pandoc]
getPageTransforms = liftM (mapMaybe pageTransform) $ queryGititState plugins
where pageTransform (PageTransform x) = Just x
pageTransform _ = Nothing
getPreParseTransforms :: ContentTransformer [String -> PluginM String]
getPreParseTransforms = liftM (mapMaybe preParseTransform) $
queryGititState plugins
where preParseTransform (PreParseTransform x) = Just x
preParseTransform _ = Nothing
getPreCommitTransforms :: ContentTransformer [String -> PluginM String]
getPreCommitTransforms = liftM (mapMaybe preCommitTransform) $
queryGititState plugins
where preCommitTransform (PreCommitTransform x) = Just x
preCommitTransform _ = Nothing
-- | @applyTransform a t@ applies the transform @t@ to input @a@.
applyTransform :: a -> (a -> PluginM a) -> ContentTransformer a
applyTransform inp transform = do
context <- get
conf <- lift getConfig
user <- lift getLoggedInUser
fs <- lift getFileStore
req <- lift askRq
let pluginData = PluginData{ pluginConfig = conf
, pluginUser = user
, pluginRequest = req
, pluginFileStore = fs }
(result', context') <- liftIO $ runPluginM (transform inp) pluginData context
put context'
return result'
-- | Applies all the page transform plugins to a Pandoc document.
applyPageTransforms :: Pandoc -> ContentTransformer Pandoc
applyPageTransforms c = do
xforms <- getPageTransforms
foldM applyTransform c (wikiLinksTransform : xforms)
-- | Applies all the pre-parse transform plugins to a Page object.
applyPreParseTransforms :: Page -> ContentTransformer Page
applyPreParseTransforms page' = getPreParseTransforms >>= foldM applyTransform (pageText page') >>=
(\t -> return page'{ pageText = t })
-- | Applies all the pre-commit transform plugins to a raw string.
applyPreCommitTransforms :: String -> ContentTransformer String
applyPreCommitTransforms c = getPreCommitTransforms >>= foldM applyTransform c
--
-- Content or context augmentation combinators
--
-- | Puts rendered page content into a wikipage div, adding
-- categories.
wikiDivify :: Html -> ContentTransformer Html
wikiDivify c = do
categories <- liftM ctxCategories get
base' <- lift getWikiBase
let categoryLink ctg = li (anchor ! [href $ base' ++ "/_category/" ++ ctg] << ctg)
let htmlCategories = if null categories
then noHtml
else thediv ! [identifier "categoryList"] << ulist << map categoryLink categories
return $ thediv ! [identifier "wikipage"] << [c, htmlCategories]
-- | Adds page title to a Pandoc document.
addPageTitleToPandoc :: String -> Pandoc -> ContentTransformer Pandoc
addPageTitleToPandoc title' (Pandoc _ blocks) = do
updateLayout $ \layout -> layout{ pgTitle = title' }
return $ if null title'
then Pandoc (Meta [] [] []) blocks
else Pandoc (Meta [Str title'] [] []) blocks
-- | Adds javascript links for math support.
addMathSupport :: a -> ContentTransformer a
addMathSupport c = do
conf <- lift getConfig
updateLayout $ \l ->
case mathMethod conf of
JsMathScript -> addScripts l ["jsMath/easy/load.js"]
MathML -> addScripts l ["MathMLinHTML.js"]
WebTeX _ -> l
MathJax u -> addScripts l [u]
RawTeX -> l
return c
-- | Adds javascripts to page layout.
addScripts :: PageLayout -> [String] -> PageLayout
addScripts layout scriptPaths =
layout{ pgScripts = scriptPaths ++ pgScripts layout }
--
-- ContentTransformer context API
--
getParams :: ContentTransformer Params
getParams = lift (withData return)
getFileName :: ContentTransformer FilePath
getFileName = liftM ctxFile get
getPageName :: ContentTransformer String
getPageName = liftM (pgPageName . ctxLayout) get
getLayout :: ContentTransformer PageLayout
getLayout = liftM ctxLayout get
getCacheable :: ContentTransformer Bool
getCacheable = liftM ctxCacheable get
-- | Updates the layout with the result of applying f to the current layout
updateLayout :: (PageLayout -> PageLayout) -> ContentTransformer ()
updateLayout f = do
ctx <- get
let l = ctxLayout ctx
put ctx { ctxLayout = f l }
--
-- Pandoc and wiki content conversion support
--
readerFor :: PageType -> Bool -> String -> Pandoc
readerFor pt lhs =
let defPS = def{ readerSmart = True
, readerExtensions = if lhs
then Set.insert Ext_literate_haskell
$ readerExtensions def
else readerExtensions def }
in case pt of
RST -> readRST defPS
Markdown -> readMarkdown defPS
LaTeX -> readLaTeX defPS
HTML -> readHtml defPS
Textile -> readTextile defPS
wikiLinksTransform :: Pandoc -> PluginM Pandoc
wikiLinksTransform pandoc
= do cfg <- liftM pluginConfig ask -- Can't use askConfig from Interface due to circular dependencies.
return (bottomUp (convertWikiLinks cfg) pandoc)
-- | Convert links with no URL to wikilinks.
convertWikiLinks :: Config -> Inline -> Inline
convertWikiLinks cfg (Link ref ("", "")) | useAbsoluteUrls cfg =
Link ref (baseUrl cfg </> inlinesToURL ref, "Go to wiki page")
convertWikiLinks _cfg (Link ref ("", "")) =
Link ref (inlinesToURL ref, "Go to wiki page")
convertWikiLinks _cfg x = x
-- | Derives a URL from a list of Pandoc Inline elements.
inlinesToURL :: [Inline] -> String
inlinesToURL = encString False isUnescapedInURI . inlinesToString
-- | Convert a list of inlines into a string.
inlinesToString :: [Inline] -> String
inlinesToString = concatMap go
where go x = case x of
Str s -> s
Emph xs -> concatMap go xs
Strong xs -> concatMap go xs
Strikeout xs -> concatMap go xs
Superscript xs -> concatMap go xs
Subscript xs -> concatMap go xs
SmallCaps xs -> concatMap go xs
Quoted DoubleQuote xs -> '"' : (concatMap go xs ++ "\"")
Quoted SingleQuote xs -> '\'' : (concatMap go xs ++ "'")
Cite _ xs -> concatMap go xs
Code _ s -> s
Space -> " "
LineBreak -> " "
Math DisplayMath s -> "$$" ++ s ++ "$$"
Math InlineMath s -> "$" ++ s ++ "$"
RawInline "tex" s -> s
RawInline _ _ -> ""
Link xs _ -> concatMap go xs
Image xs _ -> concatMap go xs
Note _ -> ""
|
thielema/gitit
|
Network/Gitit/ContentTransformer.hs
|
gpl-2.0
| 20,423
| 0
| 18
| 5,681
| 4,081
| 2,123
| 1,958
| 375
| 20
|
{- |
Module : $EmptyHeader$
Description : <optional short description entry>
Copyright : (c) <Authors or Affiliations>
License : GPLv2 or higher, see LICENSE.txt
Maintainer : <email>
Stability : unstable | experimental | provisional | stable | frozen
Portability : portable | non-portable (<reason>)
<optional description>
-}
module Main where
import Parsec
import ParsecExpr
import Logic
import Grothendieck
import Parser
--import StaticAnalysis
import Dynamic
data L1 = L1 deriving Show
data L2 = L2 deriving Show
instance Typeable L1 where typeOf _ = mkAppTy (mkTyCon "L1") []
instance Typeable L2 where typeOf _ = mkAppTy (mkTyCon "L2") []
instance Language L1 where language_name _ = "L1"
instance Language L2 where language_name _ = "L2"
data B1 = B1 deriving (Show, Eq)
data B2 = B2 deriving (Show, Eq)
instance Typeable B1 where typeOf _ = mkAppTy (mkTyCon "B1") []
instance Typeable B2 where typeOf _ = mkAppTy (mkTyCon "B2") []
instance Category L1 B1 B1 where
identity = undefined
o = undefined
dom = undefined
cod = undefined
instance Category L2 B2 B2 where
identity = undefined
o = undefined
dom = undefined
cod = undefined
instance Syntax L1 B1 B1 B1 B1 where
parse_basic_spec _ =
do string "{}"
spaces
return B1
parse_symbol_mapping _ =
do string "m"
spaces
return B1
parse_sentence = undefined
instance Syntax L2 B2 B2 B2 B2 where
parse_basic_spec _ =
do string "#"
spaces
return B2
parse_symbol_mapping _ =
do string "n"
spaces
return B2
parse_sentence = undefined
instance StaticAnalysis L1 B1 B1 B1 B1 B1 where
basic_analysis _ sig b = Just (sig,[])
stat_symbol_mapping = undefined
instance StaticAnalysis L2 B2 B2 B2 B2 B2 where
basic_analysis _ sig b = Just (sig,[])
stat_symbol_mapping = undefined
instance Logic L1 B1 B1 B1 B1 B1 where
empty_signature _ = B1
map_sentence = undefined
prover = undefined
instance Logic L2 B2 B2 B2 B2 B2 where
empty_signature _ = B2
map_sentence = undefined
prover = undefined
{-
th1 = (G_theory L1 (B1,[]))
sp1 = (Basic_spec (G_basic_spec L1 B1))
sp2 = (Basic_spec (G_basic_spec L2 B2))
-}
t1 = Logic_translation L1 L2 (\B1 -> B2) (\B1 -> B2) (\_ -> \B1 -> Just B2) (\_ -> \B2 -> Just B1)
logicGraph = ([("L1",G_logic L1),("L2",G_logic L2)],
[("T1",G_LTR t1)])
instance Eq AnyLogic where
(G_logic i1) == (G_logic (i2::id2)) =
case (coerce i1)::Maybe id2 of
Just _ -> True
_ -> False
instance Show AnyLogic where
show id = case lookup id (map (\(x,y) -> (y,x)) (fst logicGraph)) of
Nothing -> "???"
Just s -> "Logic: "++ s
p s = do let output = hetParse logicGraph s
putStrLn (show output)
main = do putStrLn "Enter spec\n"
s <- readLn
p s
|
nevrenato/Hets_Fork
|
mini/Main.hs
|
gpl-2.0
| 2,971
| 0
| 12
| 816
| 909
| 467
| 442
| -1
| -1
|
months = [31,28,31,30,31,30,31,31,30,31,30,31]
leapmonths = [31,29,31,30,31,30,31,31,30,31,30,31]
sumMonths :: [Int] -> [Int]
sumMonths x = _sumMonths x 0
_sumMonths :: [Int] -> Int -> [Int]
_sumMonths (x:xs) acc = (x+acc):(_sumMonths xs (acc+x))
_sumMonths [] _ = []
sm = init (1 : map (succ) (sumMonths months))
lm = init (1 : map (succ) (sumMonths leapmonths))
isSun :: Int -> Int -> Bool
isSun day year
| isLeap year =
if day `elem` lm && (((day + start) `mod` 7) == 0) then True else False
| otherwise = if day `elem` sm && (((day + start) `mod` 7) == 0) then True else False
where start = startDay year
startDay :: Int -> Int
startDay year
| year == 1900 = 1
| year > 1900 = (1 + sum [numDays y | y <- [1900..(year - 1)]]) `mod` 7
isLeap year = (year `mod` 4 == 0) && year /= 1900
numDays year
| isLeap year = 366
| otherwise = 365
totalNum :: Int
totalNum = length $ filter (uncurry isSun) [(d,y) | d <- [1..366], y <- [1901..2000]]
main = do
putStrLn "HI"
print (totalNum)
|
Daphron/project-euler
|
p19.hs
|
gpl-3.0
| 1,045
| 0
| 15
| 251
| 595
| 325
| 270
| 28
| 3
|
module Postfix where
begin f = f []
push vm x f = f (x:vm)
add (x:y:vm) f = f (x+y:vm)
end = head
|
KenetJervet/mapensee
|
haskell/problems/SimplePostfix.hs
|
gpl-3.0
| 102
| 0
| 8
| 28
| 79
| 41
| 38
| 5
| 1
|
{-
hbot - a simple Haskell chat bot for Hipchat
Copyright (C) 2014 Louis J. Scoras
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module Main where
--------------------------------------------------------------------------------
import Control.Applicative ( (<$>), (<*>) )
import System.Environment ( getEnv )
import Hbot.Server
main :: IO ()
main = app =<< ps
where
ps = AppParams <$> fmap read (getEnv "PORT")
<*> getEnv "ROOM"
<*> getEnv "PREFIX"
<*> getEnv "AUTH_TOKEN"
|
ljsc/hbot
|
Main.hs
|
gpl-3.0
| 1,202
| 0
| 13
| 324
| 100
| 56
| 44
| 10
| 1
|
{-# LANGUAGE CPP, PackageImports #-}
#if __GLASGOW_HASKELL__ >= 701
{-# LANGUAGE Safe #-}
#endif
-- | The module "Foreign.C.Error" facilitates C-specific error
-- handling of @errno@.
module Foreign.C.Error (
-- * Haskell representations of @errno@ values
Errno(..), -- instance: Eq
-- ** Common @errno@ symbols
-- | Different operating systems and\/or C libraries often support
-- different values of @errno@. This module defines the common values,
-- but due to the open definition of 'Errno' users may add definitions
-- which are not predefined.
eOK, e2BIG, eACCES, eADDRINUSE, eADDRNOTAVAIL, eADV, eAFNOSUPPORT, eAGAIN,
eALREADY, eBADF, eBADMSG, eBADRPC, eBUSY, eCHILD, eCOMM, eCONNABORTED,
eCONNREFUSED, eCONNRESET, eDEADLK, eDESTADDRREQ, eDIRTY, eDOM, eDQUOT,
eEXIST, eFAULT, eFBIG, eFTYPE, eHOSTDOWN, eHOSTUNREACH, eIDRM, eILSEQ,
eINPROGRESS, eINTR, eINVAL, eIO, eISCONN, eISDIR, eLOOP, eMFILE, eMLINK,
eMSGSIZE, eMULTIHOP, eNAMETOOLONG, eNETDOWN, eNETRESET, eNETUNREACH,
eNFILE, eNOBUFS, eNODATA, eNODEV, eNOENT, eNOEXEC, eNOLCK, eNOLINK,
eNOMEM, eNOMSG, eNONET, eNOPROTOOPT, eNOSPC, eNOSR, eNOSTR, eNOSYS,
eNOTBLK, eNOTCONN, eNOTDIR, eNOTEMPTY, eNOTSOCK, eNOTTY, eNXIO,
eOPNOTSUPP, ePERM, ePFNOSUPPORT, ePIPE, ePROCLIM, ePROCUNAVAIL,
ePROGMISMATCH, ePROGUNAVAIL, ePROTO, ePROTONOSUPPORT, ePROTOTYPE,
eRANGE, eREMCHG, eREMOTE, eROFS, eRPCMISMATCH, eRREMOTE, eSHUTDOWN,
eSOCKTNOSUPPORT, eSPIPE, eSRCH, eSRMNT, eSTALE, eTIME, eTIMEDOUT,
eTOOMANYREFS, eTXTBSY, eUSERS, eWOULDBLOCK, eXDEV,
-- ** 'Errno' functions
-- :: Errno
isValidErrno, -- :: Errno -> Bool
-- access to the current thread's "errno" value
--
getErrno, -- :: IO Errno
resetErrno, -- :: IO ()
-- conversion of an "errno" value into IO error
--
errnoToIOError, -- :: String -- location
-- -> Errno -- errno
-- -> Maybe Handle -- handle
-- -> Maybe String -- filename
-- -> IOError
-- throw current "errno" value
--
throwErrno, -- :: String -> IO a
-- ** Guards for IO operations that may fail
throwErrnoIf, -- :: (a -> Bool) -> String -> IO a -> IO a
throwErrnoIf_, -- :: (a -> Bool) -> String -> IO a -> IO ()
throwErrnoIfRetry, -- :: (a -> Bool) -> String -> IO a -> IO a
throwErrnoIfRetry_, -- :: (a -> Bool) -> String -> IO a -> IO ()
throwErrnoIfMinus1, -- :: Num a
-- => String -> IO a -> IO a
throwErrnoIfMinus1_, -- :: Num a
-- => String -> IO a -> IO ()
throwErrnoIfMinus1Retry,
-- :: Num a
-- => String -> IO a -> IO a
throwErrnoIfMinus1Retry_,
-- :: Num a
-- => String -> IO a -> IO ()
throwErrnoIfNull, -- :: String -> IO (Ptr a) -> IO (Ptr a)
throwErrnoIfNullRetry,-- :: String -> IO (Ptr a) -> IO (Ptr a)
throwErrnoIfRetryMayBlock,
throwErrnoIfRetryMayBlock_,
throwErrnoIfMinus1RetryMayBlock,
throwErrnoIfMinus1RetryMayBlock_,
throwErrnoIfNullRetryMayBlock,
throwErrnoPath,
throwErrnoPathIf,
throwErrnoPathIf_,
throwErrnoPathIfNull,
throwErrnoPathIfMinus1,
throwErrnoPathIfMinus1_,
) where
import "base" Foreign.C.Error
|
jwiegley/ghc-release
|
libraries/haskell2010/Foreign/C/Error.hs
|
gpl-3.0
| 3,560
| 0
| 5
| 1,079
| 444
| 312
| 132
| 44
| 0
|
-- FINISHED
shiftedDiff :: String -> String -> Int
shiftedDiff a b = n
where
k = length a
rots = map (\i -> (i, rotate i a)) [0..k]
rots' = filter (\(i, str) -> str == b) $ rots
n = case rots' of
[] -> -1
_ -> minimum $ map fst rots'
rotate :: Int -> [a] -> [a]
rotate n = foldr (.) id (replicate n rotateOne)
where
rotateOne [] = []
rotateOne xs = reverse . (\(a : as) -> as ++ [a]) . reverse $ xs
|
friedbrice/codewars
|
haskell/Rotation.hs
|
gpl-3.0
| 441
| 0
| 13
| 134
| 233
| 125
| 108
| 12
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{-|
Module : Web.HTTP.Redmine
Description : An API Library for the Redmine Bug Tracker
Copyright : (c) Pavan Rikhi, 2014
License : GPL-3
Maintainer : pavan@sleepanarchy.com
Stability : experimental
Portability : POSIX
Redmine is a library for interacting with the API for Redmine, a bug
tracker written in Ruby.
Actions are run in the 'Redmine' Monad, which should be supplied with
a 'RedmineConfig'. You will need to override the default 'redAPI' and
'redURL' Config fields.
The following actions are currently supported:
* Fetching All Projects
* Fetching All/Personal Issues
* Fetching All Issue Statuses
* Fetching a Specific Issue Status by Name or Id
* Updating an Issue [TODO: more heavylifting in the library(less user code)]
* Add/Remove Watchers from Images
This is not intended to be a complete API library, just what is required
for `hkredmine`. However, it _could_ be a complete API library,
contributions are welcome...
-}
module Web.HTTP.Redmine
(
-- * Redmine Monad
Redmine
, runRedmine
, RedmineConfig(..)
, defaultRedmineConfig
, redmineLeft
, redmineDecode
, redmineMVar
, redmineTakeMVar
-- * Redmine Types
, IssueFilter
-- ** ID Types
, ProjectId
, ProjectIdent
, IssueId
, VersionId
-- ** Redmine Objects
, Project(..)
, Projects(..)
, Issue(..)
, Issues(..)
, Status(..)
, Activity(..)
, Tracker(..)
, Priority(..)
, Category(..)
, User(..)
, Version(..)
-- * Redmine API Functions
-- ** Projects
, getProjects
, getProjectFromIdent
-- ** Issues
, getIssues
, getVersionsIssues
, getIssue
, updateIssue
, createIssue
-- ** Issue Statuses
, getStatuses
, getStatusFromName
, getStatusFromId
-- ** Issue Categories
, getCategories
, getCategoryFromName
, createCategory
-- ** Trackers
, getTrackers
, getTrackerFromName
-- ** Versions
, getVersions
, getVersion
, getNextVersionDue
-- ** Time Entries
, getActivities
, getActivityFromName
, addTimeEntry
-- ** Priorities
, getPriorities
, getPriorityFromName
-- ** Misc
, getCurrentUser
, addWatcher
, removeWatcher
-- * Formatting
, projectDetail
, issueDetail
, versionDetail
, projectsTable
, issuesTable
, versionTable
) where
import qualified Data.ByteString.Char8 as BC (pack)
import qualified Data.ByteString.Lazy as LB (ByteString)
import qualified Data.List as L (find, sortBy)
import Control.Monad ((>=>), when, void)
import Data.Aeson (FromJSON, object, (.=), encode)
import Data.Function (on)
import Data.Maybe (isJust, isNothing, fromJust)
import Data.Time.Clock (DiffTime)
import Safe (headMay)
import Web.HTTP.Redmine.Client
import Web.HTTP.Redmine.Format
import Web.HTTP.Redmine.Monad
import Web.HTTP.Redmine.Types
-- Projects
-- | Retrieve all 'Projects'.
getProjects :: Redmine [Project]
getProjects = do Projects ps <- getEndPoint GetProjects []
return ps
-- | Attempt to retrieve a 'Project' from a given 'ProjedtIdent'. String
-- versions of a 'ProjectId' are also accepted.
getProjectFromIdent :: ProjectIdent -> Redmine Project
getProjectFromIdent pIdent = do
maybeProject <- getItemFromField getProjects (\p ->
pIdent `elem` [ projectIdentifier p
, show $ projectId p ])
when (isNothing maybeProject) $ redmineLeft "Not a valid Project Identifier."
return $ fromJust maybeProject
-- Issues
-- | Retrieve a set of Issues based on an 'IssueFilter'
getIssues :: IssueFilter -> Redmine [Issue]
getIssues f = do
Issues is <- getEndPoint GetIssues f
return is
-- | Retrieve all 'Issues' of a 'Project'
getProjectsIssues :: ProjectId -> IssueFilter -> Redmine [Issue]
getProjectsIssues pID f = do
Issues is <- getEndPoint (GetProjectsIssues pID) f
return is
-- | Retrieve an 'Issue'.
getIssue :: IssueId -> Redmine Issue
getIssue issueID = getEndPoint (GetIssue issueID) []
-- | Update an 'Issue'. Currently, you must manually create the request's
-- JSON object.
updateIssue :: IssueId -> LB.ByteString -> Redmine ()
updateIssue issueID = putEndPoint $ UpdateIssue issueID
-- | Create an 'Issue'. Make and encode the JSON object yourself.
createIssue :: LB.ByteString -> Redmine Issue
createIssue = postEndPoint GetIssues >=> redmineDecode
-- Statuses
-- | Retrieve all available statuses.
getStatuses :: Redmine [Status]
getStatuses = do (Statuses ss) <- getEndPoint GetStatuses []
return ss
-- | Retrieve the 'Status' with the given name.
getStatusFromName :: String -> Redmine (Maybe Status)
getStatusFromName name = getStatusFromField ((== name) . statusName)
-- | Retrieve the 'Status' with the given id.
getStatusFromId :: Integer -> Redmine (Maybe Status)
getStatusFromId i = getStatusFromField ((== i) . statusId)
-- | Retrieve the 'Status' using the given predicate.
getStatusFromField :: (Status -> Bool) -> Redmine (Maybe Status)
getStatusFromField = getItemFromField getStatuses
-- | Search a 'Redmine' type using the given predicate.
getItemFromField :: FromJSON a => Redmine [a] -> (a -> Bool) -> Redmine (Maybe a)
getItemFromField items p = fmap (L.find p) items
-- Time Entries
-- | Retrieve a list of all Time Entry Activities.
getActivities :: Redmine [Activity]
getActivities = do (Activities as) <- getEndPoint GetActivites []
return as
-- | Retrieve a 'Activity' given a 'activityName'
getActivityFromName :: String -> Redmine (Maybe Activity)
getActivityFromName name = getItemFromField getActivities ((== name) . activityName)
-- | Submit a new Time Entry.
addTimeEntry :: IssueId -> DiffTime -> Activity -> String -> Redmine ()
addTimeEntry i dt a comment = void $ postEndPoint GetTimeEntries postData
where hours = fromIntegral (round dt :: Integer) / 3600.0
postData = encode $ object
[ "time_entry" .= object [ "issue_id" .= i
, "hours" .= (hours :: Double)
, "activity_id" .= activityId a
, "comments" .= comment
] ]
-- Trackers
-- | Retrieve a list of all Trackers.
getTrackers :: Redmine [Tracker]
getTrackers = do Trackers ts <- getEndPoint GetTrackers []
return ts
-- | Retrieve a 'Tracker' given it's 'trackerName'.
getTrackerFromName :: String -> Redmine (Maybe Tracker)
getTrackerFromName name = getItemFromField getTrackers ((== name) . trackerName)
-- Priorities
-- | Retrieve a list of all Priorities.
getPriorities :: Redmine [Priority]
getPriorities = do Priorities ps <- getEndPoint GetPriorities []
return ps
-- | Retrieve a 'Priority' given it's 'priorityName'.
getPriorityFromName :: String -> Redmine (Maybe Priority)
getPriorityFromName name = getItemFromField getPriorities ((== name) . priorityName)
-- Categories
-- | Retrieve a list of every 'Category' in a 'Project'.
getCategories :: ProjectId -> Redmine [Category]
getCategories p = do Categories cs <- getEndPoint (GetCategories p) []
return cs
-- | Retrieve a 'Category' from a 'ProjectId' and a 'categoryName'.
getCategoryFromName :: ProjectId -> String -> Redmine (Maybe Category)
getCategoryFromName p name = getItemFromField (getCategories p) ((== name) . categoryName)
-- | Create a category from a JSON object.
createCategory :: ProjectId -> LB.ByteString -> Redmine Category
createCategory pId = postEndPoint (GetCategories pId) >=> redmineDecode
-- Users
-- | Retrieve the current 'User'.
getCurrentUser :: Redmine User
getCurrentUser = getEndPoint GetCurrentUser []
-- Watching
-- | Add a watcher to an 'Issue'.
addWatcher :: IssueId -> User -> Redmine ()
addWatcher i user = void $ postEndPoint (AddWatcher i) postData
where postData = encode $ object [ "user_id" .= userId user ]
-- | Remove a watcher from an 'Issue'.
removeWatcher :: IssueId -> User -> Redmine ()
removeWatcher i user = deleteEndPoint $ RemoveWatcher i $ userId user
-- Versions
-- | Retrieve all 'Versions' of a 'Project' from the 'projectId'.
getVersions :: ProjectId -> Redmine [Version]
getVersions p = do Versions vs <- getEndPoint (GetVersions p) []
return vs
-- | Retrieve all 'Versions' from all 'Projects'.
getAllVersions :: Redmine [Version]
getAllVersions = do Projects ps <- getEndPoint GetProjects []
let projectIds = map projectId ps
vs <- mapM getVersions projectIds
return $ concat vs
-- | Retrieve a 'Version' from it's id.
getVersion :: VersionId -> Redmine Version
getVersion v = do versions <- getAllVersions
let versionIds = map versionId versions
if v `elem` versionIds
then getEndPoint (GetVersion v) []
else redmineLeft "Version does not exist."
-- | Retrieve all 'Issues' of a 'Version'.
getVersionsIssues :: Version -> IssueFilter -> Redmine [Issue]
getVersionsIssues v f = getProjectsIssues (versionProjectId v) $ f ++
[ ("fixed_version_id", BC.pack . show $ versionId v) ]
-- | Retrieve the next open 'Version' of a 'Project' with the soonest
-- 'versionDueDate'.
getNextVersionDue :: ProjectId -> Redmine (Maybe Version)
getNextVersionDue p = do
vs <- getVersions p
return . headMay . L.sortBy (compare `on` versionDueDate)
. filter ((== "open") . versionStatus)
. filter (isJust . versionDueDate) $ vs
|
prikhi/hkredmine
|
src/Web/HTTP/Redmine.hs
|
gpl-3.0
| 10,696
| 0
| 14
| 3,260
| 1,996
| 1,083
| 913
| 167
| 2
|
{-# LANGUAGE CPP #-}
-- |
-- Module : Main
-- Copyright : (C) 2007 Bryan O'Sullivan
-- (C) 2012-2018 Jens Petersen
--
-- Maintainer : Jens Petersen <petersen@fedoraproject.org>
-- Stability : alpha
-- Portability : portable
--
-- Explanation: Main entry point for building RPM packages.
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
module Main where
#if (defined(MIN_VERSION_base) && MIN_VERSION_base(4,13,0))
#else
import Control.Applicative ((<|>)
#if (defined(MIN_VERSION_base) && MIN_VERSION_base(4,8,0))
#else
, (<$>), (<*>)
#endif
)
#endif
import Distribution.Text (simpleParse)
import Distribution.Verbosity (normal, silent)
#if !MIN_VERSION_simple_cmd_args(0,1,7)
import Options.Applicative (maybeReader)
#endif
import System.IO (BufferMode(LineBuffering), hSetBuffering, stdout)
import Commands.BuildDep (builddep)
import Commands.Depends (depends, Depends (..))
import Commands.Diff (diff)
import Commands.Install (install)
import Commands.Refresh (refresh)
import Commands.RpmBuild (rpmBuild_)
import Commands.Spec (createSpecFile_)
import Commands.Update (update)
import PackageUtils (RpmStage (..))
import Paths_cabal_rpm (version)
import Types
import SimpleCabal (PackageIdentifier(..))
import SimpleCmdArgs
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
simpleCmdArgs (Just version) "Cabal-rpm tool"
"RPM package tool for Haskell Stackage/Hackage packages" $
subcommands
[ Subcommand "spec" "Generate a spec file" $
createSpecFile_ <$> ignoreMissing <*> quietOpt <*> flags <*> testsuite <*> force <*> pkgtype <*> fmap toSubpkgStream subpackage <*> pkgVerSpecifier
, Subcommand "srpm" "Generate an srpm" $
rpmBuild_ Source <$> verboseRpmbuild <*> flags <*> pkgtype <*> subpackage <*> pkgVerSpecifier
, Subcommand "prep" "Unpack source" $
rpmBuild_ Prep <$> verboseRpmbuild <*> flags <*> pkgtype <*> subpackage <*> pkgVerSpecifier
, Subcommand "local" "Build rpm package locally" $
rpmBuild_ Binary <$> quietRpmbuild <*> flags <*> pkgtype <*> subpackage <*> pkgVerSpecifier
, Subcommand "build" "Alias for 'local' - builds rpm locally" $
rpmBuild_ Binary <$> quietRpmbuild <*> flags <*> pkgtype <*> subpackage <*> pkgVerSpecifier
, Subcommand "builddep" "Install build dependencies with dnf" $
builddep <$> flags <*> pkgVerSpecifier
, Subcommand "install" "Build and install recursively" $
install <$> flags <*> pkgtype <*> subpackage <*> pkgVerSpecifier
-- should be (optional versionArg) not pkgid
, Subcommand "diff" "Diff with pristine generated spec file" $
diff <$> flags <*> pkgtype <*> pkgVerSpecifier
, Subcommand "depends" "List Haskell dependencies" $
depends Depends <$> flags <*> pkgVerSpecifier
, Subcommand "requires" "List buildrequires for package" $
depends Requires <$> flags <*> pkgVerSpecifier
, Subcommand "missingdeps" "List dependencies not available" $
depends Missing <$> flags <*> pkgVerSpecifier
-- should be just Maybe PackageName
, Subcommand "refresh" "Refresh spec file to latest packaging" $
refresh <$> dryrun <*> pkgtype <*> pkgVerSpecifier
, Subcommand "update" "Update package to latest version" $
update <$> pkgVerSpecifier
]
where
pkgId :: Parser (Maybe PackageIdentifier)
pkgId = optional (argumentWith (maybeReader simpleParse) "PKG[VER]")
stream :: Parser (Maybe Stream)
stream = optional (optionWith auto 's' "stream" "STREAM" "Stackage stream or Hackage")
flags :: Parser Flags
flags = optionalWith auto 'f' "flag" "[(String,Bool)]" "Set or disable Cabal flags" []
quietRpmbuild = switchWith 'q' "quiet" "Quiet rpmbuild output"
verboseRpmbuild = flagWith True False 'v' "verbose" "Verbose rpmbuild output"
testsuite :: Parser Bool
testsuite = switchWith 'T' "tests" "Force enabling the test-suite (even if deps missing)"
force :: Parser Bool
force = switchWith 'F' "force" "Force overwriting existing of any .spec file"
dryrun = switchWith 'n' "dry-run" "Just show patch"
ignoreMissing = switchWith 'm' "ignore-missing" "Don't check for deps of missing deps"
-- quietOpt :: Parser Verbosity
quietOpt = flagWith normal silent 'q' "quiet" "Silence Cabal"
pkgtype :: Parser PackageType
pkgtype =
flagWith' StandalonePkg 't' "standalone" "Create a standalone package that uses cabal-install to build and install" <|>
flagWith DefaultPkg BinaryPkg 'b' "binary" "Make the base package name to be the Haskell package name"
subpackage :: Parser Bool
subpackage = switchWith 'S' "subpackage" "Subpackage missing Haskell dependencies"
pkgVerSpecifier :: Parser (Maybe PackageVersionSpecifier)
pkgVerSpecifier = streamPkgToPVS <$> stream <*> pkgId
toSubpkgStream :: Bool -> Maybe (Maybe Stream)
toSubpkgStream False = Nothing
toSubpkgStream True = Just Nothing
|
juhp/cabal-rpm
|
src/Main.hs
|
gpl-3.0
| 5,198
| 1
| 19
| 1,018
| 955
| 506
| 449
| 79
| 2
|
module Cards where
import DataTypes
( Action (AddToField, Choose, Destroy, DestroyOne, Draw),
Aura (IncreaseAttack),
Card (Card),
CardEffects,
CardType (Creature, Spell),
PlayerCreature (PlayerCreature),
activePlayer,
)
import qualified DataTypes as T
noEffects :: CardEffects
noEffects = mempty
onPlay :: Action -> CardEffects
onPlay action = noEffects {T.onPlay = [action]}
onTurnEnd :: Action -> CardEffects
onTurnEnd action = noEffects {T.onTurnEnd = [action]}
onActivate :: Action -> CardEffects
onActivate action = noEffects {T.onActivate = [action]}
whileOnField :: Aura -> CardEffects
whileOnField aura = noEffects {T.whileOnField = [aura]}
creature id name power effects = Card (Creature power) id name $ onPlay (AddToField thisCard) <> effects
where
thisCard = creature id name power effects
spell = Card Spell
dog = creature "1" "Dog" 1500 noEffects
cat = creature "2" "Cat" 500 noEffects
catOrDog = spell "3" "Cat or Dog?" (onPlay $ Choose [AddToField dog, AddToField cat])
dragon = creature "4" "Dragon" 2500 (onPlay $ AddToField dragonEgg)
dragonEgg = creature "5" "Dragon Egg" 0 (onTurnEnd (AddToField dragon) <> onTurnEnd (Destroy (activePlayer . #field) dragonEgg))
catFactory = creature "6" "Cat Factory" 500 (onActivate $ AddToField cat)
masterOfGreed = creature "7" "Master of Greed" 500 (onActivate (DestroyOne $ activePlayer . #field) <> onActivate (Draw activePlayer))
buff = creature "8" "Mr. Buff" 0 (whileOnField (IncreaseAttack 500))
defaultPlayerCreature = PlayerCreature "1" 7
|
MoritzR/CurseOfDestiny
|
src/Cards.hs
|
gpl-3.0
| 1,556
| 0
| 12
| 261
| 503
| 277
| 226
| -1
| -1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.ToolResults.Projects.Histories.Executions.Steps.PerfSampleSeries.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets a PerfSampleSeries. May return any of the following error code(s):
-- - NOT_FOUND - The specified PerfSampleSeries does not exist
--
-- /See:/ <https://firebase.google.com/docs/test-lab/ Cloud Tool Results API Reference> for @toolresults.projects.histories.executions.steps.perfSampleSeries.get@.
module Network.Google.Resource.ToolResults.Projects.Histories.Executions.Steps.PerfSampleSeries.Get
(
-- * REST Resource
ProjectsHistoriesExecutionsStepsPerfSampleSeriesGetResource
-- * Creating a Request
, projectsHistoriesExecutionsStepsPerfSampleSeriesGet
, ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet
-- * Request Lenses
, phespssgExecutionId
, phespssgStepId
, phespssgHistoryId
, phespssgProjectId
, phespssgSampleSeriesId
) where
import Network.Google.Prelude
import Network.Google.ToolResults.Types
-- | A resource alias for @toolresults.projects.histories.executions.steps.perfSampleSeries.get@ method which the
-- 'ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet' request conforms to.
type ProjectsHistoriesExecutionsStepsPerfSampleSeriesGetResource
=
"toolresults" :>
"v1beta3" :>
"projects" :>
Capture "projectId" Text :>
"histories" :>
Capture "historyId" Text :>
"executions" :>
Capture "executionId" Text :>
"steps" :>
Capture "stepId" Text :>
"perfSampleSeries" :>
Capture "sampleSeriesId" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] PerfSampleSeries
-- | Gets a PerfSampleSeries. May return any of the following error code(s):
-- - NOT_FOUND - The specified PerfSampleSeries does not exist
--
-- /See:/ 'projectsHistoriesExecutionsStepsPerfSampleSeriesGet' smart constructor.
data ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet =
ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet'
{ _phespssgExecutionId :: !Text
, _phespssgStepId :: !Text
, _phespssgHistoryId :: !Text
, _phespssgProjectId :: !Text
, _phespssgSampleSeriesId :: !Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'phespssgExecutionId'
--
-- * 'phespssgStepId'
--
-- * 'phespssgHistoryId'
--
-- * 'phespssgProjectId'
--
-- * 'phespssgSampleSeriesId'
projectsHistoriesExecutionsStepsPerfSampleSeriesGet
:: Text -- ^ 'phespssgExecutionId'
-> Text -- ^ 'phespssgStepId'
-> Text -- ^ 'phespssgHistoryId'
-> Text -- ^ 'phespssgProjectId'
-> Text -- ^ 'phespssgSampleSeriesId'
-> ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet
projectsHistoriesExecutionsStepsPerfSampleSeriesGet pPhespssgExecutionId_ pPhespssgStepId_ pPhespssgHistoryId_ pPhespssgProjectId_ pPhespssgSampleSeriesId_ =
ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet'
{ _phespssgExecutionId = pPhespssgExecutionId_
, _phespssgStepId = pPhespssgStepId_
, _phespssgHistoryId = pPhespssgHistoryId_
, _phespssgProjectId = pPhespssgProjectId_
, _phespssgSampleSeriesId = pPhespssgSampleSeriesId_
}
-- | A tool results execution ID.
phespssgExecutionId :: Lens' ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet Text
phespssgExecutionId
= lens _phespssgExecutionId
(\ s a -> s{_phespssgExecutionId = a})
-- | A tool results step ID.
phespssgStepId :: Lens' ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet Text
phespssgStepId
= lens _phespssgStepId
(\ s a -> s{_phespssgStepId = a})
-- | A tool results history ID.
phespssgHistoryId :: Lens' ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet Text
phespssgHistoryId
= lens _phespssgHistoryId
(\ s a -> s{_phespssgHistoryId = a})
-- | The cloud project
phespssgProjectId :: Lens' ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet Text
phespssgProjectId
= lens _phespssgProjectId
(\ s a -> s{_phespssgProjectId = a})
-- | A sample series id
phespssgSampleSeriesId :: Lens' ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet Text
phespssgSampleSeriesId
= lens _phespssgSampleSeriesId
(\ s a -> s{_phespssgSampleSeriesId = a})
instance GoogleRequest
ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet
where
type Rs
ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet
= PerfSampleSeries
type Scopes
ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet
= '["https://www.googleapis.com/auth/cloud-platform"]
requestClient
ProjectsHistoriesExecutionsStepsPerfSampleSeriesGet'{..}
= go _phespssgProjectId _phespssgHistoryId
_phespssgExecutionId
_phespssgStepId
_phespssgSampleSeriesId
(Just AltJSON)
toolResultsService
where go
= buildClient
(Proxy ::
Proxy
ProjectsHistoriesExecutionsStepsPerfSampleSeriesGetResource)
mempty
|
brendanhay/gogol
|
gogol-toolresults/gen/Network/Google/Resource/ToolResults/Projects/Histories/Executions/Steps/PerfSampleSeries/Get.hs
|
mpl-2.0
| 6,175
| 0
| 20
| 1,382
| 624
| 370
| 254
| 113
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.CloudSearch.Stats.Session.SearchApplications.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Get the # of search sessions, % of successful sessions with a click
-- query statistics for search application. **Note:** This API requires a
-- standard end user account to execute.
--
-- /See:/ <https://developers.google.com/cloud-search/docs/guides/ Cloud Search API Reference> for @cloudsearch.stats.session.searchapplications.get@.
module Network.Google.Resource.CloudSearch.Stats.Session.SearchApplications.Get
(
-- * REST Resource
StatsSessionSearchApplicationsGetResource
-- * Creating a Request
, statsSessionSearchApplicationsGet
, StatsSessionSearchApplicationsGet
-- * Request Lenses
, sssagFromDateMonth
, sssagXgafv
, sssagUploadProtocol
, sssagFromDateDay
, sssagAccessToken
, sssagUploadType
, sssagFromDateYear
, sssagName
, sssagToDateDay
, sssagToDateYear
, sssagToDateMonth
, sssagCallback
) where
import Network.Google.CloudSearch.Types
import Network.Google.Prelude
-- | A resource alias for @cloudsearch.stats.session.searchapplications.get@ method which the
-- 'StatsSessionSearchApplicationsGet' request conforms to.
type StatsSessionSearchApplicationsGetResource =
"v1" :>
"stats" :>
"session" :>
Capture "name" Text :>
QueryParam "fromDate.month" (Textual Int32) :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "fromDate.day" (Textual Int32) :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "fromDate.year" (Textual Int32) :>
QueryParam "toDate.day" (Textual Int32) :>
QueryParam "toDate.year" (Textual Int32) :>
QueryParam "toDate.month" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON]
GetSearchApplicationSessionStatsResponse
-- | Get the # of search sessions, % of successful sessions with a click
-- query statistics for search application. **Note:** This API requires a
-- standard end user account to execute.
--
-- /See:/ 'statsSessionSearchApplicationsGet' smart constructor.
data StatsSessionSearchApplicationsGet =
StatsSessionSearchApplicationsGet'
{ _sssagFromDateMonth :: !(Maybe (Textual Int32))
, _sssagXgafv :: !(Maybe Xgafv)
, _sssagUploadProtocol :: !(Maybe Text)
, _sssagFromDateDay :: !(Maybe (Textual Int32))
, _sssagAccessToken :: !(Maybe Text)
, _sssagUploadType :: !(Maybe Text)
, _sssagFromDateYear :: !(Maybe (Textual Int32))
, _sssagName :: !Text
, _sssagToDateDay :: !(Maybe (Textual Int32))
, _sssagToDateYear :: !(Maybe (Textual Int32))
, _sssagToDateMonth :: !(Maybe (Textual Int32))
, _sssagCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'StatsSessionSearchApplicationsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sssagFromDateMonth'
--
-- * 'sssagXgafv'
--
-- * 'sssagUploadProtocol'
--
-- * 'sssagFromDateDay'
--
-- * 'sssagAccessToken'
--
-- * 'sssagUploadType'
--
-- * 'sssagFromDateYear'
--
-- * 'sssagName'
--
-- * 'sssagToDateDay'
--
-- * 'sssagToDateYear'
--
-- * 'sssagToDateMonth'
--
-- * 'sssagCallback'
statsSessionSearchApplicationsGet
:: Text -- ^ 'sssagName'
-> StatsSessionSearchApplicationsGet
statsSessionSearchApplicationsGet pSssagName_ =
StatsSessionSearchApplicationsGet'
{ _sssagFromDateMonth = Nothing
, _sssagXgafv = Nothing
, _sssagUploadProtocol = Nothing
, _sssagFromDateDay = Nothing
, _sssagAccessToken = Nothing
, _sssagUploadType = Nothing
, _sssagFromDateYear = Nothing
, _sssagName = pSssagName_
, _sssagToDateDay = Nothing
, _sssagToDateYear = Nothing
, _sssagToDateMonth = Nothing
, _sssagCallback = Nothing
}
-- | Month of date. Must be from 1 to 12.
sssagFromDateMonth :: Lens' StatsSessionSearchApplicationsGet (Maybe Int32)
sssagFromDateMonth
= lens _sssagFromDateMonth
(\ s a -> s{_sssagFromDateMonth = a})
. mapping _Coerce
-- | V1 error format.
sssagXgafv :: Lens' StatsSessionSearchApplicationsGet (Maybe Xgafv)
sssagXgafv
= lens _sssagXgafv (\ s a -> s{_sssagXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sssagUploadProtocol :: Lens' StatsSessionSearchApplicationsGet (Maybe Text)
sssagUploadProtocol
= lens _sssagUploadProtocol
(\ s a -> s{_sssagUploadProtocol = a})
-- | Day of month. Must be from 1 to 31 and valid for the year and month.
sssagFromDateDay :: Lens' StatsSessionSearchApplicationsGet (Maybe Int32)
sssagFromDateDay
= lens _sssagFromDateDay
(\ s a -> s{_sssagFromDateDay = a})
. mapping _Coerce
-- | OAuth access token.
sssagAccessToken :: Lens' StatsSessionSearchApplicationsGet (Maybe Text)
sssagAccessToken
= lens _sssagAccessToken
(\ s a -> s{_sssagAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sssagUploadType :: Lens' StatsSessionSearchApplicationsGet (Maybe Text)
sssagUploadType
= lens _sssagUploadType
(\ s a -> s{_sssagUploadType = a})
-- | Year of date. Must be from 1 to 9999.
sssagFromDateYear :: Lens' StatsSessionSearchApplicationsGet (Maybe Int32)
sssagFromDateYear
= lens _sssagFromDateYear
(\ s a -> s{_sssagFromDateYear = a})
. mapping _Coerce
-- | The resource id of the search application session stats, in the
-- following format: searchapplications\/{application_id}
sssagName :: Lens' StatsSessionSearchApplicationsGet Text
sssagName
= lens _sssagName (\ s a -> s{_sssagName = a})
-- | Day of month. Must be from 1 to 31 and valid for the year and month.
sssagToDateDay :: Lens' StatsSessionSearchApplicationsGet (Maybe Int32)
sssagToDateDay
= lens _sssagToDateDay
(\ s a -> s{_sssagToDateDay = a})
. mapping _Coerce
-- | Year of date. Must be from 1 to 9999.
sssagToDateYear :: Lens' StatsSessionSearchApplicationsGet (Maybe Int32)
sssagToDateYear
= lens _sssagToDateYear
(\ s a -> s{_sssagToDateYear = a})
. mapping _Coerce
-- | Month of date. Must be from 1 to 12.
sssagToDateMonth :: Lens' StatsSessionSearchApplicationsGet (Maybe Int32)
sssagToDateMonth
= lens _sssagToDateMonth
(\ s a -> s{_sssagToDateMonth = a})
. mapping _Coerce
-- | JSONP
sssagCallback :: Lens' StatsSessionSearchApplicationsGet (Maybe Text)
sssagCallback
= lens _sssagCallback
(\ s a -> s{_sssagCallback = a})
instance GoogleRequest
StatsSessionSearchApplicationsGet
where
type Rs StatsSessionSearchApplicationsGet =
GetSearchApplicationSessionStatsResponse
type Scopes StatsSessionSearchApplicationsGet =
'["https://www.googleapis.com/auth/cloud_search",
"https://www.googleapis.com/auth/cloud_search.stats",
"https://www.googleapis.com/auth/cloud_search.stats.indexing"]
requestClient StatsSessionSearchApplicationsGet'{..}
= go _sssagName _sssagFromDateMonth _sssagXgafv
_sssagUploadProtocol
_sssagFromDateDay
_sssagAccessToken
_sssagUploadType
_sssagFromDateYear
_sssagToDateDay
_sssagToDateYear
_sssagToDateMonth
_sssagCallback
(Just AltJSON)
cloudSearchService
where go
= buildClient
(Proxy ::
Proxy StatsSessionSearchApplicationsGetResource)
mempty
|
brendanhay/gogol
|
gogol-cloudsearch/gen/Network/Google/Resource/CloudSearch/Stats/Session/SearchApplications/Get.hs
|
mpl-2.0
| 8,694
| 0
| 23
| 2,065
| 1,309
| 744
| 565
| 184
| 1
|
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
module Main (module Main) where
|
lspitzner/brittany
|
data/Test455.hs
|
agpl-3.0
| 146
| 0
| 4
| 16
| 11
| 8
| 3
| 1
| 0
|
module Libaddutil.Colors
where
data Color
= Color Int Int Int
deriving (Show, Eq, Read)
isValidColor :: Color -> Bool
isValidColor (Color r g b) = (r >= 0 && g >= 0 && b >= 0 &&
r <= 255 && g <= 255 && b <= 255)
|
anttisalonen/freekick
|
haskell/addutil/Libaddutil/Colors.hs
|
agpl-3.0
| 256
| 0
| 16
| 92
| 108
| 57
| 51
| 7
| 1
|
{-
Created : 2014 Nov 07 (Fri) 17:05:07 by Harold Carr.
Last Modified : 2014 Nov 08 (Sat) 14:28:05 by Harold Carr.
-}
import Test.HUnit as T
import Test.HUnit.Util as U
-- HOMEWORK 6
------------------------------------------------------------------------------
-- EXERCISE 0
e00 f p xs = [f x | x <- xs , p x]
e01 f p xs = map p (map f xs)
e02 f p xs = filter p (map f xs)
e03 f p xs = map f (filter p xs)
e04 f p xs = map f (takeWhile p xs)
e0 :: [Test]
e0 = U.tt "e0"
[
e00 (*10) even [1..8::Int]
---------------
-- , e01 (*10) even [1..8::Int] -- wrong result type
-- , e02 (*10) even [1..8::Int] -- wrong result because function applied in wrong order
, e03 (*10) even [1..8::Int]
-- , e04 (*10) even [1..8::Int] -- doesn't consider all possible xs
]
[20,40,60,80]
------------------------------------------------------------------------------
-- EXERCISE 1
e1 :: [Test]
e1 = U.tt "e1"
[
all even [2,4,6::Int]
, not (all even [2,3,6::Int])
-----------------
-- 1
, and (map even [2,4,6::Int])
, not (and (map even [2,3,6::Int]))
-- 2
-- , map even (and [2,4,6::Int]) -- wrong type to and
-- 3
, (and . map even) [2,4,6::Int]
, not ((and . map even) [2,3,6::Int])
-- 4
, (not . any (not . even)) [2,4,6::Int]
, not ((not . any (not . even)) [2,3,6::Int])
-- 5
-- , (map even . and) [2,4,6::Int] -- wrong type to and
-- 6
, foldl (&&) True (map even [2,4,6::Int])
, not (foldl (&&) True (map even [2,3,6::Int]))
-- 7 - incorrect base value
-- 8
, (foldl (&&) True . map even) [2,4,6::Int]
, not ((foldl (&&) True . map even) [2,3,6::Int])
]
True
------------------------------------------------------------------------------
-- EXERCISE 2
e2 :: [Test]
e2 = U.tt "e2"
[ any odd [2,3,6::Int]
, not (any odd [2,4,6::Int])
--------------
-- 1
-- , (map odd . or) [2,3,6::Int] -- wrong type to or
-- 2
, (or . map odd) [2,3,6::Int]
, not ((or . map odd) [2,4,6::Int])
-- 3
, length (filter odd [2,3,6::Int]) > 0
, not (length (filter odd [2,4,6::Int]) > 0)
-- 4
, (not . null. dropWhile (not . odd)) [2,3,6::Int]
, not ((not . null. dropWhile (not . odd)) [2,4,6::Int])
-- 5
-- , (null . filter odd) [2,3,6::Int] -- wrong result
-- 6
, not (all (\x -> not (odd x)) [2,3,6::Int])
, not (not (all (\x -> not (odd x)) [2,4,6::Int]))
-- 7
, foldr (\x acc -> (odd x) || acc) False [2,3,6::Int]
, not (foldr (\x acc -> (odd x) || acc) False [2,4,6::Int])
-- 8
, foldr (||) True (map odd [2,3,6::Int])
-- , not (foldr (||) True (map odd [2,4,6::Int])) -- wrong base
]
True
------------------------------------------------------------------------------
-- EXERCISE 3
e34 p = foldl (\acc x -> if p x then x : acc else acc) []
e3 :: [Test]
e3 = U.tt "e3"
[ takeWhile odd [1,3,4,5::Int]
------------
-- , e34 odd [1,3,4,5::Int] -- wrong result
]
[1,3]
------------------------------------------------------------------------------
-- EXERCISE 4
e41 _ [] = []
e41 p (x:xs)
| p x = e41 p xs
| otherwise = x:xs
e42 _ [] = []
e42 p (x:xs)
| p x = e42 p xs
| otherwise = xs
e4 :: [Test]
e4 = U.tt "e4"
[ dropWhile even [2,4,6,7,8,9,10::Int]
-----------
, e41 even [2,4,6,7,8,9,10::Int]
-- , e42 even [2,4,6,7,8,9,10::Int] -- misses element
]
[7,8,9,10]
------------------------------------------------------------------------------
-- EXERCISE 5
e5 :: [Test]
e5 = U.tt "e5"
[ map (*10) [1,2,3::Int]
--------
-- 1
-- , foldr (\x xs -> xs ++ [(*10) x]) [] [1,2,3::Int] -- reverse order
-- 3
-- , foldl (\xs x -> (*10) x : xs) [] [1,2,3::Int] -- reverse order
-- 4
, foldl (\xs x -> xs ++ [(*10) x]) [] [1,2,3::Int]
]
[10,20,30]
------------------------------------------------------------------------------
-- EXERCISE 6
e6 :: [Test]
e6 = U.tt "e6"
[ filter even [1,2,3::Int]
--------
-- 1
, foldl (\xs x -> if even x then x : xs else xs) [] [1,2,3::Int]
-- 2
, foldr (\x xs -> if even x then x : xs else xs) [] [1,2,3::Int]
-- 3
-- , foldr (\x xs -> if even x then xs ++ x else [x]) [] [1,2,3::Int] -- fails typecheck
-- 4
-- , foldl (\x xs -> if even x then xs ++ [x] else xs) [] [1,2,3::Int] -- fails type chck
]
[2]
------------------------------------------------------------------------------
-- EXERCISE 7
e71 = foldr (\x y -> 10 * x + y) 0
e72 = foldl (\x y -> x + 10 * y) 0
e73 = foldl (\x y -> 10 * x + y) 0
e74 = foldr (\x y -> x + 10 * y) 0
e7t f = map f [ [2,3,4,5::Int], [], [0,0,0,0] ]
e7 :: [Test]
e7 = U.tt "e7"
[
-- e7t e71 -- wrong
-- e7t e72 -- wrong
e7t e73
-- e7t e74 -- reversed
]
[2345,0,0]
------------------------------------------------------------------------------
-- EXERCISE 8
-- does not type check because functions of different types
-- sumSqEven = compose [sum, map (^2), filter even]
compose :: [a -> a] -> (a -> a)
compose = foldr (.) id
------------------------------------------------------------------------------
-- EXERCISE 9
fc :: Show a => (a,b) -> String
fc (x,_) = show x
c93 :: ((a, b) -> c) -> a -> b -> c
c93 f = \x y -> f (x,y)
-- c94 f = \(x,y) -> f x y
e9 :: [Test]
e9 = U.tt "e9"
[ (curry fc) (1::Int) 'c'
, (c93 fc) (1::Int) 'c'
]
"1"
------------------------------------------------------------------------------
-- EXERCISE 10
uc101 :: (a -> b -> c) -> (a, b) -> c
uc101 f = \(x,y) -> f x y
e10 :: [Test]
e10 = U.tt "e10"
[ uncurry (+) (1,2::Int)
, uc101 (+) (1,2::Int)
]
3
------------------------------------------------------------------------------
-- EXERCISE 11
unfold :: (b -> Bool) -> (b -> a) -> (b -> b) -> b -> [a]
unfold p h t x
| p x = []
| otherwise = h x : unfold p h t (t x)
type Bit = Int
int2bin :: Int -> [Bit]
int2bin 0 = []
int2bin n = n `mod` 2 : int2bin (n `div` 2)
int2bin' :: Int -> [Bit]
int2bin' = unfold (== 0) (`mod` 2) (`div` 2)
e11a :: [Test]
e11a = U.tt "e11a"
[ (int2bin 13)
, (int2bin' 13)
]
[1,0,1,1]
e11b :: [Test]
e11b = U.tt "e11b"
[ (int2bin (-0))
, (int2bin' (-0))
]
[]
e11c :: [Test]
e11c = U.tt "e11c"
[ (int2bin 2)
, (int2bin' 2)
]
[0, 1]
chop8 :: [Bit] -> [[Bit]]
chop8 [] = []
chop8 bits = take 8 bits : chop8 (drop 8 bits)
e11d :: [Test]
e11d = U.tt "e11d"
[ chop8 (int2bin 61680)
-- 2
, unfold null (take 8) (drop 8) (int2bin 61680)
]
[[0,0,0,0,1,1,1,1],[0,0,0,0,1,1,1,1]]
------------------------------------------------------------------------------
-- EXERCISE 12
f12 = \x -> x * 10 + 1
e12 :: [Test]
e12 = U.tt "e12"
[ map f12 [1,2,3::Int]
-- 3
, unfold null (f12 . head) tail [1,2,3::Int]
]
[11,21,31]
------------------------------------------------------------------------------
-- EXERCISE 13
e13 :: [Test]
e13 = U.tt "e13"
[ take 4 (iterate (^2) 2)
-- 1
, take 4 (unfold (const False) id (^2) 2)
]
[2,4,16,256]
------------------------------------------------------------------------------
-- EXERCISE 14
-- associativity
------------------------------------------------------------------------------
-- EXERCISE 15
-- 4th choice is bad
------------------------------------------------------------------------------
-- EXERCISE 16
e16 :: [Test]
e16 = U.tt "e16"
[
-- 1
{-
(==)
((filter even . map (*10)) [1,2,3,4::Int])
((map (*10) . filter even) [1,2,3,4::Int])
-- 2
, (==)
(filter even [1,2,3,4::Int])
(filter (not . even) [1,2,3,4::Int])
-}
-- 3
(==)
((filter even . filter even) [1,2,3,4::Int])
( filter even [1,2,3,4::Int])
]
True
------------------------------------------------------------------------------
-- EXERCISE 17
-- reverse (map f xs) = map f (reverse xs)
------------------------------------------------------------------------------
-- EXERCISE 18
-- reverse (xs ++ ys) = reverse ys ++ reverse xs
------------------------------------------------------------------------------
-- EXERCISE 19
-- produces a finite list
-- take 10 [1 ..]
------------------------------------------------------------------------------
-- EXERCISE 20
-- sum is NOT a higher-order function
------------------------------------------------------------------------------
-- EXERCISE 21
-- map is NOT an overloaded function
-- I got this wrong - I was thinking of fmap
-- so I chose that map is not a function with two arguments
-- which I think is a correct choice - all haskell functions take ONE argument
------------------------------------------------------------------------------
-- EXERCISE 22
-- foldr is NOT an overloaded function
------------------------------------------------------------------------------
-- EXERCISE 23
-- take is a polymorphic function
-- I got this wrong - I said length is a curried function
-- I think I'm getting the definition of curry mixed up
------------------------------------------------------------------------------
-- EXERCISE 24
-- f x = x > 3 is overloaded
-- I got this wrong - I said f = \x -> x
------------------------------------------------------------------------------
-- EXERCISE 25
-- take 4 (iterate (+1) 1) == [1,2,3,4]
------------------------------------------------------------------------------
-- EXERCISE 26
-- takeWhile even [2, 4, 5, 6, 7, 8] == [2,4]
------------------------------------------------------------------------------
-- EXERCISE 27
-- zip [1, 2] ['a', 'b', 'c'] == [(1,'a'),(2,'b')]
------------------------------------------------------------------------------
-- EXERCISE 28
-- foldr (-) 0 [1, 2, 3, 4] == (-2)
------------------------------------------------------------------------------
-- EXERCISE 29
-- filter even (map (+1) [1..5]) == [2,4,6]
------------------------------------------------------------------------------
-- EXERCISE 30
e30 :: [Test]
e30 = U.tt "e30"
[ filter even (map (+1) [1,2,3,4,5::Int])
----------------
-- 4
, [(+1) x|x <- [1,2,3,4,5::Int], even ((+1) x)]
]
[2,4,6]
------------------------------------------------------------------------------
-- EXERCISE 31
-- succ n
type Church a = (a -> a) -> a -> a
-- zero,one,two,two2,two3 :: Church Int
zero,one,two,three :: (Int -> Int) -> Int -> Int
zero = \s z -> z
one = \s z -> s z
two = \s z -> s (s z)
three = \s z -> s (s (s z))
churchToInt,c2i :: (Num a, Num b) => ((a -> a) -> b -> t) -> t
-- church number succ 0
churchToInt x = x (+1) 0
c2i = churchToInt
e31a :: [Test]
e31a = U.tt "e31a"
[ (c2i two)
, (\s z -> s (s z)) (+1) 0
, (+1) ((+1) 0)
]
2
churchToString,c2s :: ((String -> String) -> String -> t) -> t
churchToString x = x ('*':) ""
c2s = churchToString
twoS :: Church String
twoS = \s z -> s (s z)
e31b :: [Test]
e31b = U.tt "e31b"
[ (c2s twoS)
, ('*':) ('*':"")
]
"**"
add :: (t2 -> t1 -> t) -> (t2 -> t3 -> t1) -> t2 -> t3 -> t
add x y = \s z -> x s (y s z)
-- http://en.wikipedia.org/wiki/Church_encoding
-- f^(m+n) x = f^m (f^n x)
addW = \m n f x -> m f (n f x)
addWeta = \m n f -> m f . (n f)
e31c :: [Test]
e31c = U.tt "e31c"
[ c2i two + c2i one
, two (+1) 0 + c2i one
, two (+1) (c2i one)
, two (+1) (one (+1) 0)
, (\s z -> two s (one s z)) (+1) 0 -- beta expansion
, add two one (+1) 0
, c2i (add two one)
]
3
-- HC
succ1 x = add x one
succ2 x = \s z -> x s (one s z)
succ3 x = \s z -> x s ((\s z -> s z) s z)
succ4 = \x s z -> x s (s z)
-- wikipedia
succW1 = \n f x -> f (n f x)
succW1eta = \n f -> f . (n f)
succW2 = \x s z -> s (x s z) -- alpha
-- mult
-- wikipedia
-- f^(m*n) x = (f^n)^m x
multW :: (t1 -> t2 -> t) -> (t3 -> t1) -> t3 -> t2 -> t
multW = \m n f x -> m (n f) x
multWeta :: (t1 -> t) -> (t2 -> t1) -> t2 -> t
multWeta = \m n f -> m (n f)
-- edX
multEdx x y = \s z -> (x . y) s z
expW :: (a -> b) -> (b -> c) -> a -> c
expW = \m n -> n . m
e31d :: [Test]
e31d = U.tt "e31d"
[ c2i (addW three three)
, c2i (succ4 (succW1 (succW2 three)))
, c2i (multW three two)
, c2i (expW two three)
]
6
------------------------------------------------------------------------------
main :: IO Counts
main =
T.runTestTT $ T.TestList $ e0 ++ e1 ++ e2 ++ e3 ++ e4 ++ e5 ++ e6 ++ e7 ++ e9 ++
e10 ++
e11a ++ e11b ++ e11c ++ e11d ++
e12 ++e13 ++ e16 ++
e30 ++
e31a ++ e31b ++ e31c ++ e31d
-- End of file.
|
haroldcarr/learn-haskell-coq-ml-etc
|
haskell/course/2014-10-edx-delft-fp101x-intro-to-fp-erik-meijer/hw06.hs
|
unlicense
| 13,380
| 12
| 28
| 3,794
| 4,645
| 2,599
| 2,046
| 226
| 3
|
module AlecSequences.A279965Spec (main, spec) where
import Test.Hspec
import AlecSequences.A279965 (a279965)
main :: IO ()
main = hspec spec
spec :: Spec
spec = describe "A279965" $
it "correctly computes the first 20 elements" $
take 20 (map a279965 [1..]) `shouldBe` expectedValue where
expectedValue = [0,1,1,1,3,1,2,1,5,2,2,2,5,3,4,3,4,3,8,4]
|
peterokagey/haskellOEIS
|
test/AlecSequences/A279965Spec.hs
|
apache-2.0
| 361
| 0
| 10
| 59
| 160
| 95
| 65
| 10
| 1
|
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
module Level3 where
-- Imports
import Data.List
import Data.Either
-- Data types
data Term = Constant String | Variable String
deriving (Show, Eq)
type Atom = (String, [Term])
type Clause = (Atom, [Atom])
type Program = [Clause]
type Query = [Atom]
type Substitution = (Term, Term)
-- -- -- Test Data -- -- --
-- taken from Level2, with a few changes
query1 :: Query
query1 = [ -- Desired output unknown
("p", [Variable "X", Variable "Y"])
]
program1 :: Program
program1 = [
(("p", [Variable "X", Variable "Y"]),
[("r", [Constant "b"]), ("s", [Variable "X"]), ("t", [Variable "X"])]),
(("q", [Variable "Y", Variable "Z"]),
[("r", [Variable "Z", Variable "Y"]), ("t", [Variable "Y"])]),
(("r", [Constant "a"]), []),
(("r", [Constant "b"]), []),
(("r", [Constant "c"]), []),
(("s", [Variable "Z"]), [("r", [Variable "Z"])]),
(("s", [Constant "d"]), []),
(("t", [Constant "b"]), []),
(("t", [Constant "d"]), [])]
-- Royal Family example, where any clauses with a not() statements
-- have been omitted.
royalfamily :: Program
royalfamily = [
(("mother",[Constant "emma",Constant "wilhelmina"]), []),
(("mother",[Constant "wilhelmina",Constant "juliana"]), []),
(("mother",[Constant "juliana",Constant "beatrix"]), []),
(("mother",[Constant "juliana",Constant "margriet"]), []),
(("mother",[Constant "juliana",Constant "irene"]), []),
(("mother",[Constant "juliana",Constant "christina"]), []),
(("mother",[Constant "margriet",Constant "maurits"]), []),
(("mother",[Constant "margriet",Constant "bernhard_jr"]), []),
(("mother",[Constant "margriet",Constant "pieter_christiaan"]), []),
(("mother",[Constant "margriet",Constant "floris"]), []),
(("mother",[Constant "beatrix",Constant "alexander"]), []),
(("mother",[Constant "beatrix",Constant "friso"]), []),
(("mother",[Constant "beatrix",Constant "constantijn"]), []),
(("mother",[Constant "maxima",Constant "amalia"]), []),
(("mother",[Constant "maxima",Constant "alexia"]), []),
(("mother",[Constant "maxima",Constant "ariane"]), []),
(("husband",[Constant "bernhard",Constant "juliana"]), []),
(("husband",[Constant "claus",Constant "beatrix"]), []),
(("husband",[Constant "pieter",Constant "margriet"]), []),
(("husband",[Constant "alexander",Constant "maxima"]), []),
(("husband",[Constant "friso",Constant "mabel"]), []),
(("husband",[Constant "constantijn",Constant "laurentien"]), []),
(("female",[Constant "irene"]), []),
(("female",[Constant "christina"]), []),
(("female",[Constant "amalia"]), []),
(("female",[Constant "alexia"]), []),
(("female",[Constant "ariane"]), []),
(("female",[Variable "X"]), [("mother", [Variable "X",Variable "_"])]),
(("female",[Variable "X"]), [("husband",[Variable "_",Variable "X"])]),
(("male",[Constant "maurits"]), []),
(("male",[Constant "bernhard_jr"]), []),
(("male",[Constant "pieter_christiaan"]), []),
(("male",[Constant "floris"]), []),
(("male",[Variable "X"]), [("husband", [Variable "X", Variable "_"])]),
(("father", [Variable "X", Variable "Y"]), [("husband", [Variable "X", Variable "Z"]), ("mother", [Variable "Z", Variable "Y"])]),
(("child", [Variable "X", Variable "Y"]), [("father", [Variable "Y", Variable "X"])]),
(("child", [Variable "X", Variable "Y"]), [("mother", [Variable "Y", Variable "X"])]),
(("grandfather", [Variable "X", Variable "Y"]), [("child", [Variable "Y", Variable "Z"]), ("father", [Variable "X", Variable "Z"])])
]
-- Functions
{-|
Substitution operation in type classes
Usage:
a <~ Substitution
-}
class Substitute a where
(<~) :: a -> Substitution -> a
instance Substitute Term where
-- | Substitute a variable with a Term
term <~ (original@(Variable _), replacement)
| term == original = replacement
| otherwise = term
-- | Substitute a constant with a Term
term <~ (original@(Constant _), replacement)
| term == original && original == replacement = replacement
| original == replacement = term
| otherwise = error "Cannot substitute a constant"
instance Substitute [Term] where
-- | Substitute in a list of Terms
terms <~ substitution = map (<~ substitution) terms
instance Substitute Atom where
-- | Substitute in an Atom
(predicate, terms) <~ substitution = (predicate, terms <~ substitution)
instance Substitute [Atom] where
-- | Substitute in a list of Atoms
atoms <~ substitution = map (<~ substitution) atoms
instance Substitute Clause where
-- | Substitute in a Clause
(atom, atoms) <~ substitution
= (atom <~ substitution, atoms <~ substitution)
instance Substitute Program where
-- | Substitute in a Program
program <~ substitution = map (<~ substitution) program
-- -- -- -- - - -- -- -- --
-- -- Rename function -- --
-- -- -- -- - - -- -- -- --
-- |rename: Renames variables in the source program to fix variable collisions.
-- This one uses substitutions.
-- Arguments:
-- Program: Program which needs the substitutions.
-- Query: Query which may or may not contain duplicate used variables.
rename :: Program -> Query -> Program
rename program query = foldl (<~) program (getSubstitutions program query)
getSubstitutions :: Program -> Query -> [Substitution]
getSubstitutions program query = zip (nub $ intersect programvars queryvars) (map (\x -> Variable x) newVarNames)
where
programvars = [x | let z = (map (fst) program) ++ (concat $ map (snd) program), let y = concat $ map (snd) z, x@(Variable _) <- y]
queryvars = [x | let y = concat $ map (snd) query, x@(Variable _) <- y]
newVarNames = getNewVarNames varNames (program ++ [(("_query", [Constant "a"]), query)])
-- |getNewVarNames: Retrieves a list of strings found in [String] not found in any variable in the Program.
getNewVarNames :: [String] -> Program -> [String]
getNewVarNames [] program = error "No free name found in seed"
getNewVarNames (name:seed) program | elem name (map getstr $ concat variables)
= getNewVarNames seed program
| otherwise
= name : getNewVarNames seed program
where
getstr (Variable str) = str
getstr (Constant str) = str
variables = concat $ map clausevars program
clausevars = (\((name, variable),atoms) -> variable : (map atomvars atoms) )
atomvars = (\(name, variable) -> variable)
-- |varNames: Generates an infinite list like ["A","B",..,"AA","AB",..]
varNames :: [String]
varNames = [empty ++ [abc] | empty <- "" : varNames, abc <- ['A'..'Z']]
{-|
Unify function
Finds a list of substitutions to unify two atoms.
Usage:
unify Atom Atom
-}
unify :: Atom -> Atom -> [Substitution]
unify (_,[]) _ = error "Cannot unify: empty atom"
unify _ (_,[]) = error "Cannot unify: empty atom"
unify atom1 atom2
| length (snd atom1) /= length (snd atom2) = error "Cannot unify: atoms of different lengths"
| otherwise = unify' atom1 atom2
where
unify' :: Atom -> Atom -> [Substitution]
unify' (_,[]) (_,[]) = []
unify' (predicate1, (term1Head@(Constant _):term1Tail)) (predicate2, (term2Head@(Constant _):term2Tail))
| predicate1 /= predicate2 = error "Cannot unify: nonequal predicates"
| term1Head == term2Head = unification : (unify' atom1 atom2)
| otherwise = error "Cannot unify: nonequal constants"
where
unification = (term1Head, term2Head)
atom1 = (predicate1, term1Tail) <~ unification
atom2 = (predicate2, term2Tail) <~ unification
unify' (predicate1, (term1Head@(Variable _):term1Tail)) (predicate2, (term2Head@(Constant _):term2Tail))
| predicate1 == predicate2 = unification : (unify' atom1 atom2)
| otherwise = error "Cannot unify: nonequal predicates"
where
unification = (term1Head, term2Head)
atom1 = (predicate1, term1Tail) <~ unification
atom2 = (predicate2, term2Tail) <~ unification
unify' (predicate1, (term1Head@(Constant _):term1Tail)) (predicate2, (term2Head@(Variable _):term2Tail))
| predicate1 == predicate2 = unification : (unify' atom1 atom2)
| otherwise = error "Cannot unify: nonequal predicates"
where
unification = (term2Head, term1Head)
atom1 = (predicate1, term1Tail) <~ unification
atom2 = (predicate2, term2Tail) <~ unification
unify' (predicate1, (term1Head@(Variable _):term1Tail)) (predicate2, (term2Head@(Variable _):term2Tail))
| predicate1 == predicate2 = unification : (unify' atom1 atom2)
| otherwise = error "Cannot unify: nonequal predicates"
where
unification = (term2Head, term1Head)
atom1 = (predicate1, term1Tail) <~ unification
atom2 = (predicate2, term2Tail) <~ unification
{-|
Can unify function
Determines if a function can be unified.
Usage:
unify Atom Atom
-}
(<?>) :: Atom -> Atom -> Bool
(_,[]) <?> _ = False
_ <?> (_,[]) = False
atom1 <?> atom2
| length (snd atom1) /= length (snd atom2) = False
| otherwise = all (==True) $ unify' atom1 atom2
where
unify' :: Atom -> Atom -> [Bool]
unify' (_,[]) (_,[]) = []
unify' (predicate1, (term1Head@(Constant _):term1Tail)) (predicate2, (term2Head@(Constant _):term2Tail))
| predicate1 /= predicate2 = [False]
| term1Head == term2Head = True : (unify' atom1 atom2)
| otherwise = [False]
where
unification = (term1Head, term2Head)
atom1 = (predicate1, term1Tail) <~ unification
atom2 = (predicate2, term2Tail) <~ unification
unify' (predicate1, (term1Head@(Variable _):term1Tail)) (predicate2, (term2Head@(Constant _):term2Tail))
| predicate1 == predicate2 = True : (unify' atom1 atom2)
| otherwise = [False]
where
unification = (term1Head, term2Head)
atom1 = (predicate1, term1Tail) <~ unification
atom2 = (predicate2, term2Tail) <~ unification
unify' (predicate1, (term1Head@(Constant _):term1Tail)) (predicate2, (term2Head@(Variable _):term2Tail))
| predicate1 == predicate2 = True : (unify' atom1 atom2)
| otherwise = [False]
where
unification = (term2Head, term1Head)
atom1 = (predicate1, term1Tail) <~ unification
atom2 = (predicate2, term2Tail) <~ unification
unify' (predicate1, (term1Head@(Variable _):term1Tail)) (predicate2, (term2Head@(Variable _):term2Tail))
| predicate1 == predicate2 = True : (unify' atom1 atom2)
| otherwise = [False]
where
unification = (term2Head, term1Head)
atom1 = (predicate1, term1Tail) <~ unification
atom2 = (predicate2, term2Tail) <~ unification
{-|
evalMulti wrapper function
renames the input and trims the output
-}
evalMulti :: Program -> Query -> [Either Bool [Substitution]]
evalMulti [] _ = error "Empty program"
evalMulti _ [] = error "Empty query"
evalMulti program query | null $ rightsRes = filter (isLeft) res
| otherwise = rightsRes
where
res = eval (rename program query) query
trimmed = trim res
rightsRes = filter (isRight) trimmed
vars = [x | let y = concat $ map (snd) query, x@(Variable _) <- y]
trim :: [Either Bool [Substitution]] -> [Either Bool [Substitution]]
trim [] = []
trim ((Right x):xs) | null $ trim' x = trim xs
| otherwise = Right (trim' x) : trim xs
trim ((Left x):xs) = trim xs
trim' :: [Substitution] -> [Substitution]
trim' [] = []
trim' (x@(term1@(Variable _), term2@(Variable _)):xs)
| elem term1 vars && elem term2 vars = x : (trim' xs)
| otherwise = trim' xs
trim' (x@(term1@(Variable _), (Constant _)):xs)
| elem term1 vars = x : (trim' xs)
| otherwise = trim' xs
trim' (_:xs) = trim' xs
{-|
eval function
evaluates the input
-}
eval :: Program -> Query -> [Either Bool [Substitution]]
eval [] _ = [Left False]
eval _ [] = [Left True]
eval program query@(queryAtomHead:queryAtoms)
| null res = [Left False]
| otherwise = foldr (\(f,s) a -> [f] ++ ( s) ++ a) [] res
where
res = [(Right unification, evals)|
clause@(clauseAtom, clauseAtoms) <- program,
-- trace ("query: "++ (show queryAtomHead) ++ " -> " ++ (show queryAtoms) ++ " rule: " ++ (show clauseAtom) ++ " -> "++ (show clauseAtoms))
queryAtomHead <?> clauseAtom,
let unification = unify queryAtomHead clauseAtom,
let evals = eval program ((foldl (<~) clauseAtoms unification) ++ (foldl (<~) queryAtoms unification)),
evals /= [Left False]
]
|
wouwouwou/2017_module_8
|
src/haskell/FP_project_Martijn/Level3.hs
|
apache-2.0
| 14,180
| 0
| 16
| 4,195
| 4,701
| 2,610
| 2,091
| 209
| 6
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QGLContext_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:32
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Opengl.QGLContext_h (
QchooseContext_h(..)
,Qcreate_h(..)
,QdoneCurrent_h(..)
,QmakeCurrent_h(..)
,QswapBuffers_h(..)
) where
import Qtc.Enums.Base
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Qtc.Classes.Opengl_h
import Qtc.ClassTypes.Opengl
import Foreign.Marshal.Array
instance QunSetUserMethod (QGLContext ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLContext_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QGLContext_unSetUserMethod" qtc_QGLContext_unSetUserMethod :: Ptr (TQGLContext a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QGLContextSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLContext_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QGLContext ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLContext_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QGLContextSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLContext_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QGLContext ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLContext_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QGLContextSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QGLContext_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QGLContext ()) (QGLContext x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGLContext setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGLContext_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGLContext_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGLContext_setUserMethod" qtc_QGLContext_setUserMethod :: Ptr (TQGLContext a) -> CInt -> Ptr (Ptr (TQGLContext x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QGLContext :: (Ptr (TQGLContext x0) -> IO ()) -> IO (FunPtr (Ptr (TQGLContext x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QGLContext_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGLContextSc a) (QGLContext x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QGLContext setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QGLContext_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGLContext_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QGLContext ()) (QGLContext x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGLContext setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGLContext_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGLContext_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGLContext_setUserMethodVariant" qtc_QGLContext_setUserMethodVariant :: Ptr (TQGLContext a) -> CInt -> Ptr (Ptr (TQGLContext x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGLContext :: (Ptr (TQGLContext x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQGLContext x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QGLContext_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QGLContextSc a) (QGLContext x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QGLContext setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QGLContext_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QGLContext_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QGLContext ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGLContext_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QGLContext_unSetHandler" qtc_QGLContext_unSetHandler :: Ptr (TQGLContext a) -> CWString -> IO (CBool)
instance QunSetHandler (QGLContextSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QGLContext_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QGLContext ()) (QGLContext x0 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGLContext1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGLContext1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGLContext_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> IO (CBool)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGLContext_setHandler1" qtc_QGLContext_setHandler1 :: Ptr (TQGLContext a) -> CWString -> Ptr (Ptr (TQGLContext x0) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGLContext1 :: (Ptr (TQGLContext x0) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGLContext x0) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGLContext1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGLContextSc a) (QGLContext x0 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGLContext1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGLContext1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGLContext_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> IO (CBool)
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QGLContext ()) (QGLContext x0 -> QGLContext t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGLContext2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGLContext2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGLContext_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> Ptr (TQGLContext t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGLContext_setHandler2" qtc_QGLContext_setHandler2 :: Ptr (TQGLContext a) -> CWString -> Ptr (Ptr (TQGLContext x0) -> Ptr (TQGLContext t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGLContext2 :: (Ptr (TQGLContext x0) -> Ptr (TQGLContext t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQGLContext x0) -> Ptr (TQGLContext t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QGLContext2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGLContextSc a) (QGLContext x0 -> QGLContext t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGLContext2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGLContext2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGLContext_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> Ptr (TQGLContext t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
class QchooseContext_h x0 x1 where
chooseContext_h :: x0 -> x1 -> IO (Bool)
instance QchooseContext_h (QGLContext ()) (()) where
chooseContext_h x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_chooseContext cobj_x0
foreign import ccall "qtc_QGLContext_chooseContext" qtc_QGLContext_chooseContext :: Ptr (TQGLContext a) -> IO CBool
instance QchooseContext_h (QGLContextSc a) (()) where
chooseContext_h x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_chooseContext cobj_x0
instance QchooseContext_h (QGLContext ()) ((QGLContext t1)) where
chooseContext_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_chooseContext1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_chooseContext1" qtc_QGLContext_chooseContext1 :: Ptr (TQGLContext a) -> Ptr (TQGLContext t1) -> IO CBool
instance QchooseContext_h (QGLContextSc a) ((QGLContext t1)) where
chooseContext_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_chooseContext1 cobj_x0 cobj_x1
class Qcreate_h x0 x1 where
create_h :: x0 -> x1 -> IO (Bool)
instance Qcreate_h (QGLContext ()) (()) where
create_h x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_create cobj_x0
foreign import ccall "qtc_QGLContext_create" qtc_QGLContext_create :: Ptr (TQGLContext a) -> IO CBool
instance Qcreate_h (QGLContextSc a) (()) where
create_h x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_create cobj_x0
instance Qcreate_h (QGLContext ()) ((QGLContext t1)) where
create_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QGLContext_create1" qtc_QGLContext_create1 :: Ptr (TQGLContext a) -> Ptr (TQGLContext t1) -> IO CBool
instance Qcreate_h (QGLContextSc a) ((QGLContext t1)) where
create_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QGLContext_create1 cobj_x0 cobj_x1
instance QsetHandler (QGLContext ()) (QGLContext x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGLContext3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGLContext3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGLContext_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QGLContext_setHandler3" qtc_QGLContext_setHandler3 :: Ptr (TQGLContext a) -> CWString -> Ptr (Ptr (TQGLContext x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QGLContext3 :: (Ptr (TQGLContext x0) -> IO ()) -> IO (FunPtr (Ptr (TQGLContext x0) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QGLContext3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QGLContextSc a) (QGLContext x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QGLContext3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QGLContext3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QGLContext_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQGLContext x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
class QdoneCurrent_h x0 x1 where
doneCurrent_h :: x0 -> x1 -> IO ()
instance QdoneCurrent_h (QGLContext ()) (()) where
doneCurrent_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_doneCurrent cobj_x0
foreign import ccall "qtc_QGLContext_doneCurrent" qtc_QGLContext_doneCurrent :: Ptr (TQGLContext a) -> IO ()
instance QdoneCurrent_h (QGLContextSc a) (()) where
doneCurrent_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_doneCurrent cobj_x0
class QmakeCurrent_h x0 x1 where
makeCurrent_h :: x0 -> x1 -> IO ()
instance QmakeCurrent_h (QGLContext ()) (()) where
makeCurrent_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_makeCurrent cobj_x0
foreign import ccall "qtc_QGLContext_makeCurrent" qtc_QGLContext_makeCurrent :: Ptr (TQGLContext a) -> IO ()
instance QmakeCurrent_h (QGLContextSc a) (()) where
makeCurrent_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_makeCurrent cobj_x0
class QswapBuffers_h x0 x1 where
swapBuffers_h :: x0 -> x1 -> IO ()
instance QswapBuffers_h (QGLContext ()) (()) where
swapBuffers_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_swapBuffers cobj_x0
foreign import ccall "qtc_QGLContext_swapBuffers" qtc_QGLContext_swapBuffers :: Ptr (TQGLContext a) -> IO ()
instance QswapBuffers_h (QGLContextSc a) (()) where
swapBuffers_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QGLContext_swapBuffers cobj_x0
|
uduki/hsQt
|
Qtc/Opengl/QGLContext_h.hs
|
bsd-2-clause
| 21,547
| 0
| 18
| 4,756
| 7,008
| 3,363
| 3,645
| -1
| -1
|
module Import
( module Prelude
, module Yesod
, module Foundation
, module Settings.StaticFiles
, module Settings.Development
, module Data.Monoid
, module Control.Applicative
, Text
#if __GLASGOW_HASKELL__ < 704
, (<>)
#endif
, TorrentName (..)
, iso8601, rfc822, localTimeToZonedTime, fromHex, toHex, isHex
) where
import Prelude hiding (writeFile, readFile, head, tail, init, last)
import Yesod hiding (Route(..))
import Foundation
import Data.Monoid (Monoid (mappend, mempty, mconcat))
import Control.Applicative ((<$>), (<*>), pure)
import Data.Text (Text)
import Settings.StaticFiles
import Settings.Development
import PathPieces
import Utils
#if __GLASGOW_HASKELL__ < 704
infixr 5 <>
(<>) :: Monoid m => m -> m -> m
(<>) = mappend
#endif
|
jannschu/bitlove-ui
|
Import.hs
|
bsd-2-clause
| 797
| 0
| 7
| 154
| 217
| 146
| 71
| 25
| 1
|
import Control.Monad
import Data.Array
import qualified Data.Foldable as Fld
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Sequence as Seq
(<|) = (Seq.<|)
(|>) = (Seq.|>)
(><) = (Seq.><)
data Ph a = EmptyPh | Ph a [Ph a] deriving Show
singPh x = Ph x []
minPh (Ph x _) = x
mergePh x EmptyPh = x
mergePh EmptyPh x = x
mergePh x@(Ph a as) y@(Ph b bs) =
if a < b
then Ph a (y : as)
else Ph b (x : bs)
insertPh x e = x `mergePh` (singPh e)
delminPh (Ph _ xs) = mergePPh xs
mergePPh [] = EmptyPh
mergePPh [x] = x
mergePPh (x : y : rest) = (x `mergePh` y) `mergePh` (mergePPh rest)
findKPh 1 x = minPh x
findKPh k x = findKPh (pred k) (delminPh x)
readEdge :: IO (Int, Int)
readEdge = do
estr <- getLine
let (a : b : _) = map read (words estr)
return (a, b)
calc n parents children sals = stats
where
stats = array (1, n) (prc 1)
prc n =
let chs = children ! n
mine = foldl mergePh (foldl mergePh EmptyPh (map (\c -> singPh (sals ! c, c)) chs)) (map (stats !) chs)
in
(chs >>= prc) ++ [(n, mine)]
tst 0 _ _ = return ()
tst q d' stats = do
qstr <- getLine
let (v : k : _) = map read (words qstr)
let d = snd $ findKPh k (stats ! (v + d'))
putStrLn (show d)
tst (pred q) d stats
main = do
pstr <- getLine
let (n : q : _) = map read (words pstr)
es <- mapM (const readEdge) [1 .. pred n]
let parents = array (2, n) es
let mchildren = Map.fromListWith (><) (map (\(a, b) -> (b, Seq.singleton a)) es)
let children = array (1, n) (map (\x -> (x, Fld.toList $ if x `Map.member` mchildren then fromJust $ x `Map.lookup` mchildren else Seq.empty)) [1 .. n])
sstr <- getLine
let sals = array (1, n) (zip [1 ..] (map (read :: String -> Int) (words sstr)))
let stats = calc n parents children sals
tst q 0 stats
|
pbl64k/HackerRank-Contests
|
2014-06-20-FP/BoleynSalary/bs.ph.hs
|
bsd-2-clause
| 1,915
| 2
| 19
| 561
| 1,021
| 537
| 484
| 54
| 2
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeApplication
, getApplicationDev
, makeFoundation
) where
import Import
import Settings
import Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Network.Wai.Middleware.RequestLogger
( mkRequestLogger, outputFormat, OutputFormat (..), IPAddrSource (..), destination
)
import qualified Network.Wai.Middleware.RequestLogger as RequestLogger
import qualified Database.Persist
import Database.Persist.Sql (runMigration)
import Network.HTTP.Client.Conduit (newManager)
import Control.Monad.Logger (runLoggingT)
import Control.Concurrent (forkIO, threadDelay)
import System.Log.FastLogger (newStdoutLoggerSet, defaultBufSize, flushLogStr)
import Network.Wai.Logger (clockDateCacher)
import Data.Default (def)
import Yesod.Core.Types (loggerSet, Logger (Logger))
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Home
import Handler.About
import Handler.AccountCreate
import Handler.AccountLogin
import Handler.AccountLogout
import Handler.User
import Handler.UserVideo
import Handler.AccountEdit
import Handler.VideoUpload
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeApplication :: AppConfig DefaultEnv Extra -> IO (Application, LogFunc)
makeApplication conf = do
foundation <- makeFoundation conf
-- Initialize the logging middleware
logWare <- mkRequestLogger def
{ outputFormat =
if development
then Detailed True
else Apache FromSocket
, destination = RequestLogger.Logger $ loggerSet $ appLogger foundation
}
-- Create the WAI application and apply middlewares
app <- toWaiAppPlain foundation
let logFunc = messageLoggerSource foundation (appLogger foundation)
return (logWare $ defaultMiddlewaresNoLogging app, logFunc)
-- | Loads up any necessary settings, creates your foundation datatype, and
-- performs some initialization.
makeFoundation :: AppConfig DefaultEnv Extra -> IO App
makeFoundation conf = do
manager <- newManager
s <- staticSite
dbconf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf)
Database.Persist.loadConfig >>=
Database.Persist.applyEnv
p <- Database.Persist.createPoolConfig (dbconf :: Settings.PersistConf)
loggerSet' <- newStdoutLoggerSet defaultBufSize
(getter, updater) <- clockDateCacher
-- If the Yesod logger (as opposed to the request logger middleware) is
-- used less than once a second on average, you may prefer to omit this
-- thread and use "(updater >> getter)" in place of "getter" below. That
-- would update the cache every time it is used, instead of every second.
let updateLoop = do
threadDelay 1000000
updater
flushLogStr loggerSet'
updateLoop
_ <- forkIO updateLoop
let logger = Yesod.Core.Types.Logger loggerSet' getter
foundation = App conf s p manager dbconf logger
-- Perform database migration using our application's logging settings.
runLoggingT
(Database.Persist.runPool dbconf (runMigration migrateAll) p)
(messageLoggerSource foundation logger)
return foundation
-- for yesod devel
getApplicationDev :: IO (Int, Application)
getApplicationDev =
defaultDevelApp loader (fmap fst . makeApplication)
where
loader = Yesod.Default.Config.loadConfig (configSettings Development)
{ csParseExtra = parseExtra
}
|
pharpend/lambdatube
|
Application.hs
|
bsd-3-clause
| 3,989
| 0
| 13
| 767
| 693
| 384
| 309
| -1
| -1
|
{-# LANGUAGE CPP #-}
module Distribution.Client.Dependency.Modular.Cycles (
detectCyclesPhase
) where
import Prelude hiding (cycle)
import Control.Monad
import Control.Monad.Reader
import Data.Graph (SCC)
import Data.Set (Set)
import qualified Data.Graph as Gr
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.Traversable as T
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Distribution.Client.Dependency.Modular.Dependency
import Distribution.Client.Dependency.Modular.Flag
import Distribution.Client.Dependency.Modular.Package
import Distribution.Client.Dependency.Modular.Tree
import qualified Distribution.Client.Dependency.Modular.ConflictSet as CS
type DetectCycles = Reader (ConflictSet QPN)
-- | Find and reject any solutions that are cyclic
detectCyclesPhase :: Tree QGoalReasonChain -> Tree QGoalReasonChain
detectCyclesPhase = (`runReader` CS.empty) . cata go
where
-- Most cases are simple; we just need to remember which choices we made
go :: TreeF QGoalReasonChain (DetectCycles (Tree QGoalReasonChain)) -> DetectCycles (Tree QGoalReasonChain)
go (PChoiceF qpn gr cs) = PChoice qpn gr <$> local (CS.insert $ P qpn) (T.sequence cs)
go (FChoiceF qfn gr w m cs) = FChoice qfn gr w m <$> local (CS.insert $ F qfn) (T.sequence cs)
go (SChoiceF qsn gr w cs) = SChoice qsn gr w <$> local (CS.insert $ S qsn) (T.sequence cs)
go (GoalChoiceF cs) = GoalChoice <$> (T.sequence cs)
go (FailF cs reason) = return $ Fail cs reason
-- We check for cycles only if we have actually found a solution
-- This minimizes the number of cycle checks we do as cycles are rare
go (DoneF revDeps) = do
fullSet <- ask
return $ case findCycles fullSet revDeps of
Nothing -> Done revDeps
Just relSet -> Fail relSet CyclicDependencies
-- | Given the reverse dependency map from a 'Done' node in the tree, as well
-- as the full conflict set containing all decisions that led to that 'Done'
-- node, check if the solution is cyclic. If it is, return the conflict set
-- containing all decisions that could potentially break the cycle.
findCycles :: ConflictSet QPN -> RevDepMap -> Maybe (ConflictSet QPN)
findCycles fullSet revDeps = do
guard $ not (null cycles)
return $ relevantConflictSet (Set.fromList (concat cycles)) fullSet
where
cycles :: [[QPN]]
cycles = [vs | Gr.CyclicSCC vs <- scc]
scc :: [SCC QPN]
scc = Gr.stronglyConnComp . map aux . Map.toList $ revDeps
aux :: (QPN, [(comp, QPN)]) -> (QPN, QPN, [QPN])
aux (fr, to) = (fr, fr, map snd to)
-- | Construct the relevant conflict set given the full conflict set that
-- lead to this decision and the set of packages involved in the cycle
relevantConflictSet :: Set QPN -> ConflictSet QPN -> ConflictSet QPN
relevantConflictSet cycle = CS.filter isRelevant
where
isRelevant :: Var QPN -> Bool
isRelevant (P qpn) = qpn `Set.member` cycle
isRelevant (F (FN (PI qpn _i) _fn)) = qpn `Set.member` cycle
isRelevant (S (SN (PI qpn _i) _sn)) = qpn `Set.member` cycle
|
gbaz/cabal
|
cabal-install/Distribution/Client/Dependency/Modular/Cycles.hs
|
bsd-3-clause
| 3,218
| 0
| 13
| 695
| 877
| 478
| 399
| 48
| 7
|
module Codex.Meetup.M1.RPS (
) where
|
adarqui/Codex
|
src/Codex/Meetup/M1/RPS.hs
|
bsd-3-clause
| 37
| 0
| 3
| 5
| 11
| 8
| 3
| 1
| 0
|
{-# LANGUAGE ScopedTypeVariables, BangPatterns #-}
module TestFSM4 where
import System.IO
import Control.Monad.State
import Control.Exception
data UserInput = UIActionSumTwoNumbers | UIActionQuit | UIInt Int | UIAny
data AppOut = AOEnd String | AOLink App | AOMessage String App
type UserState = [Int]
type NodeId = String
data App = Await {
name :: NodeId,
message :: String,
parser :: String -> Maybe UserInput,
handler :: UserInput -> StateT UserState IO AppOut
} | Yield {
name :: NodeId,
next :: StateT UserState IO AppOut
}
start = Await {
name = "start",
message = "What do you want to do?",
parser = \ i -> case i of
"quit" -> Just UIActionQuit
"sum" -> Just UIActionSumTwoNumbers
_ -> Nothing
,
handler = \e -> case e of
UIActionSumTwoNumbers -> return $ AOLink getANumber
UIActionQuit -> return $ AOEnd "Goodbye!"
}
getANumber = Await {
name = "getANumber",
message = "Enter a number",
parser = fmap UIInt . readMaybe,
handler = \e -> case e of
UIInt i -> do
is <- get
let is' = i:is
put is'
return $ if length is' == 2 then AOLink sumTwoNumbers else AOMessage "Thanks ..." getANumber
}
sumTwoNumbers = Yield {
name = "sumTwoNumbers",
next = do
is <- get
return $ AOEnd ("And the sum is " ++ show (sum is))
}
getApp :: NodeId -> App
getApp "start" = start
getApp "getANumber" = getANumber
getApp "sumTwoNumbers" = sumTwoNumbers
getApp n = error $ "No state found for " ++ n
run :: App -> UserInput -> UserState -> IO (AppOut, UserState)
run (Await _ _ _ handler) = runStateT . handler
run (Yield _ next) = const $ runStateT next
run' :: App -> UserInput -> UserState -> IO ()
run' oApp e userState = do
(mApp, userState') <- run oApp e userState
case mApp of
AOEnd message -> writeFile "./temp" "" >> print message
AOLink app -> writeFile "./temp" (show (name app, userState')) >> go userState' app
AOMessage message app -> writeFile "./temp" (show (name app, userState')) >> print message >> go userState' app
where
go :: UserState -> App -> IO ()
go _ a@Await{} = print (message a)
go u a@(Yield _ handler) = run' a UIAny u
runApp :: App -> String -> UserState -> IO ()
runApp oApp input userState = case parser oApp input of
Nothing -> print "Invalid Input"
Just e -> run' oApp e userState
main = do
stFile <- readFileMaybe "./temp"
case (stFile >>= readMaybe) :: Maybe (NodeId, UserState) of
Nothing -> do
let app = start
print $ message app
input <- getLine
runApp start input []
Just (nodeId, userState) -> do
input <- getLine
runApp (getApp nodeId) input userState
-- utils
readMaybe :: (Read a) => String -> Maybe a
readMaybe s = case reads s of
[] -> Nothing
[(a, _)] -> Just a
readFileMaybe :: String -> IO (Maybe String)
readFileMaybe path = do
stFile <- try $ readAFile path
case stFile of
Left (e :: IOException) -> return Nothing
Right !f -> return $ Just f
readAFile :: String -> IO String
readAFile path = do
inFile <- openFile path ReadMode
contents <- hGetContents inFile
contents `seq` hClose inFile
return contents
|
homam/fsm-conversational-ui
|
src/TestFSM4.hs
|
bsd-3-clause
| 3,156
| 0
| 16
| 744
| 1,173
| 593
| 580
| 91
| 4
|
import Mapnik.Setup (defaultMapnikMainWith)
import Distribution.PackageDescription
main = defaultMapnikMainWith $ \bi -> bi {
extraLibs = "mapnik-wkt":"mapnik_vector_tile_impl":"mapnik":"z":extraLibs bi
}
|
albertov/hs-mapnik
|
vectortile/Setup.hs
|
bsd-3-clause
| 211
| 0
| 12
| 24
| 57
| 31
| 26
| 4
| 1
|
module Abstract.Impl.Libs.Queue.MVar.Internal (
QueueMVar{-,
queueMVar,
mkQueue'MVar
-}
) where
import Control.Exception
import Control.Concurrent
import Control.Concurrent.MVar
import Abstract.Interfaces.Queue
data QueueMVar t = QueueMVar {
_conn :: MVar t
}
{-
mkQueue'MVar :: QueueMVar t -> IO (Queue IO t)
mkQueue'MVar qrw = do
mv <- newEmptyMVar
return $ buildQueue $ qrw { _conn = mv }
enqueue' :: QueueMVar t -> t -> IO ()
enqueue' w t = do
v <- putMVar (_conn w) t
return $ case v of
(Left _) -> throw OperationFailed
(Right _) -> ()
-}
|
adarqui/Abstract-Impl-Libs
|
src/Abstract/Impl/Libs/Queue/MVar/Internal.hs
|
bsd-3-clause
| 563
| 0
| 9
| 108
| 58
| 38
| 20
| 8
| 0
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE MultiWayIf #-}
module QCommon.CBuf where
import Control.Lens (use, (.=), (%=), (-=))
import Control.Monad (when, liftM)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import QCommon.SizeBufT
import Types
import QuakeState
import qualified QCommon.SZ as SZ
import {-# SOURCE #-} qualified QCommon.Com as Com
import {-# SOURCE #-} qualified Game.Cmd as Cmd
initialize :: Quake ()
initialize = do
bufData <- use $ globals.gCmdTextBuf
SZ.init (globals.gCmdText) bufData 8192
addEarlyCommands :: Bool -> Quake ()
addEarlyCommands clear = do
c <- Com.argc
findAddCommand c 0
where findAddCommand c i = do
s <- Com.argv i
if s /= "+set"
then when (i + 1 < c) $ findAddCommand c (i + 1)
else do
v1 <- Com.argv (i + 1)
v2 <- Com.argv (i + 2)
addText $ "set " `B.append` v1 `B.append` " " `B.append` v2 `B.append` "\n"
when clear $ do
Com.clearArgv i
Com.clearArgv (i+1)
Com.clearArgv (i+2)
when (i + 3 < c) $ findAddCommand c (i + 3)
addLateCommands :: Quake Bool
addLateCommands = do
argc <- Com.argc
-- build the combined string to parse from
argsLength <- mapM (liftM B.length . Com.argv) [1..argc-1]
if sum argsLength == 0
then return False
else do
text <- liftM (B.intercalate " ") (mapM Com.argv [1..argc-1])
-- pull out the commands
let build = pullOutCommands text (B.length text) 0 ""
ret = B.length build /= 0
when ret $ addText build
return ret
where pullOutCommands :: B.ByteString -> Int -> Int -> B.ByteString -> B.ByteString
pullOutCommands txt len idx accum
| idx >= len = accum
| txt `BC.index` idx == '+' =
let command = BC.takeWhile (\ch -> ch /= '+' && ch /= '-') (B.drop (idx + 1) txt)
commandLen = B.length command
in pullOutCommands txt len (idx + commandLen) (accum `B.append` command `B.append` "\n")
| otherwise = pullOutCommands txt len (idx + 1) accum
execute :: Quake ()
execute = do
globals.gAliasCount .= 0
curSize <- use $ globals.gCmdText.sbCurSize
text <- use $ globals.gCmdText.sbData
when (curSize /= 0) $ doStuff text curSize 0 0
where doStuff :: B.ByteString -> Int -> Int -> Int -> Quake ()
doStuff text curSize idx quotes =
if | idx == curSize -> do
globals.gCmdText.sbCurSize .= 0
Cmd.executeString text
wait <- use $ globals.gCmdWait
when wait $ globals.gCmdWait .= False
| BC.index text idx == '"' ->
doStuff text curSize (idx + 1) (quotes + 1)
| (BC.index text idx == ';' && even quotes) || BC.index text idx == '\n' -> do
let line = B.take idx text -- do not include ';' or '\n'
if idx == curSize
then globals.gCmdText.sbCurSize .= 0
else do
globals.gCmdText.sbCurSize -= idx + 1
globals.gCmdText.sbData %= B.drop (idx + 1)
Cmd.executeString line
wait <- use $ globals.gCmdWait
if wait
-- skip out while text still remains in buffer, leaving
-- it for next frame
then globals.gCmdWait .= False
else do
newText <- use $ globals.gCmdText.sbData
newCurSize <- use $ globals.gCmdText.sbCurSize
when (newCurSize /= 0) $ doStuff newText newCurSize 0 0
| otherwise -> doStuff text curSize (idx + 1) quotes
addText :: B.ByteString -> Quake ()
addText text = do
let len = B.length text
curSize <- use $ globals.gCmdText.sbCurSize
maxSize <- use $ globals.gCmdText.sbMaxSize
if curSize + len >= maxSize
then Com.printf "Cbuf.addText: overflow\n"
else SZ.write (globals.gCmdText) text (B.length text)
insertText :: B.ByteString -> Quake ()
insertText text = do
templen <- use $ globals.gCmdText.sbCurSize
-- copy off an commands still remaining in the exec buffer
tmp <- if templen /= 0
then do
txt <- use $ globals.gCmdText.sbData
SZ.clear (globals.gCmdText)
return $ B.take templen txt
else return ""
-- add the entire text of the file
addText text
when (templen /= 0) $ SZ.write (globals.gCmdText) tmp templen
copyToDefer :: Quake ()
copyToDefer = do
buf <- use $ globals.gCmdTextBuf
curSize <- use $ globals.gCmdText.sbCurSize
globals.gDeferTextBuf .= B.take curSize buf
globals.gCmdText.sbCurSize .= 0
executeText :: Int -> B.ByteString -> Quake ()
executeText _ _ = io (putStrLn "CBuf.executeText") >> undefined -- TODO
insertFromDefer :: Quake ()
insertFromDefer = do
buf <- use $ globals.gDeferTextBuf
insertText buf
globals.gDeferTextBuf .= ""
|
ksaveljev/hake-2
|
src/QCommon/CBuf.hs
|
bsd-3-clause
| 5,200
| 0
| 17
| 1,719
| 1,673
| 834
| 839
| -1
| -1
|
{-|
Module : DeepControl.Monad.Morph
Description : Deepened the usual Control.Monad.Morph module.
Copyright : 2013 Gabriel Gonzalez,
(c) 2015 KONISHI Yohsuke
License : BSD-style (see the LICENSE file in the distribution)
Maintainer : ocean0yohsuke@gmail.com
Stability : experimental
Portability : ---
This module enables you to program in Monad-Morphic style for much __deeper__ level than the usual @Control.Monad.Morph@ module expresses.
You would realize exactly what __/much deeper level/__ means by reading the example codes, which are attached on the page bottom.
-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeSynonymInstances #-}
module DeepControl.Monad.Morph (
module Control.Monad.Morph,
-- * SinkT
SinkT(..), sinkT2, sinkT3, sinkT4,
-- * Level-1
-- ** trans-map
(|>|), (|<|),
-- ** trans-sequence
(|>~),
-- ** trans-cover
(|*|),
-- ** trans-fish
(|>=>),
-- * Level-2
-- ** trans-bind
(|>>=),
-- ** trans-sequence
(|>>~),
-- ** trans-fish
(|>>=>),
-- ** trans-map
(|>>|), (|<<|),
-- ** trans-cover
(|**|),
(|-*|),
-- * Level-3
-- ** trans-bind
(|>>>=),
-- ** trans-sequence
(|>>>~),
-- ** trans-fish
(|>>>=>),
-- ** trans-map
(|>>>|), (|<<<|),
-- ** trans-cover
(|***|),
(|--*|),
(|-**|), (|*-*|),
-- * Level-4
-- ** trans-bind
(|>>>>=),
-- ** trans-sequence
(|>>>>~),
-- ** trans-map
(|>>>>|), (|<<<<|),
-- ** trans-cover
(|****|),
(|---*|),
(|--**|), (|-*-*|), (|*--*|),
(|-***|), (|*-**|), (|**-*|),
-- * Level-5
-- ** trans-bind
(|>>>>>=),
-- ** trans-sequence
(|>>>>>~),
-- ** trans-map
(|>>>>>|), (|<<<<<|),
-- ** trans-cover
(|*****|),
(|----*|),
(|---**|), (|--*-*|), (|-*--*|), (|*---*|),
(|--***|), (|-*-**|), (|*--**|), (|*-*-*|), (|-**-*|), (|**--*|),
(|-****|), (|*-***|), (|**-**|), (|***-*|),
-- * Level-2 example: trans-map
-- $Example
-- * Level-2 example: trans-cover and trans-bind
-- $Example-2
) where
import DeepControl.Applicative
import DeepControl.Monad.Trans
import DeepControl.Traversable
import Control.Monad.Except (Except, ExceptT (..), runExcept,
runExceptT)
import Control.Monad.Identity (Identity (..))
import Control.Monad.List (ListT (..))
import Control.Monad.Morph
import Control.Monad.Trans.Identity (IdentityT (..))
import Control.Monad.Trans.Maybe (MaybeT (..))
import Control.Monad.Writer (Writer, WriterT (..), runWriter)
import Data.Monoid
-------------------------------------------------------------------------------
-- SinkT
class (MonadTrans s) => SinkT s where
-- | Alalog to @'DeepControl.Traversable.sink'@.
--
-- >>> sinkT $ MaybeT (ListT (Right [Just 1]))
-- ListT (MaybeT (Right (Just [1])))
--
-- >>> sinkT $ MaybeT (ListT (ExceptT (Identity (Right [Just 1]))))
-- ListT (MaybeT (ExceptT (Identity (Right (Just [1])))))
--
sinkT :: (Monad m, MMonad t,
MonadTrans_ x t, Traversable x) =>
s (t m) a -> t (s m) a
instance SinkT IdentityT where
sinkT (IdentityT x) = trans . IdentityT . untrans $ x
instance SinkT MaybeT where
sinkT (MaybeT x) = trans . MaybeT . (sink|$>) . untrans $ x
instance SinkT ListT where
sinkT (ListT x) = trans . ListT . (sink|$>) . untrans $ x
instance SinkT (ExceptT e) where
sinkT (ExceptT x) = trans . ExceptT . (sink|$>) . untrans $ x
instance (Monoid w) => SinkT (WriterT w) where
sinkT (WriterT x) = trans . WriterT . (sinkToTuple|$>) . untrans $ x
where
sinkToTuple :: (Functor m, Traversable m, Monoid w) => m (a, w) -> (m a, w)
sinkToTuple = flipTuple . sink . (flipTuple|$>)
flipTuple (x,y) = (y,x)
-- | Alalog to @'DeepControl.Traversable.sink2'@.
--
-- >>> sinkT2 $ MaybeT (ListT (ExceptT (Identity (Right [Just 1]))))
-- ListT (ExceptT (MaybeT (Identity (Just (Right [1])))))
--
sinkT2 :: (Monad m, Monad (s (t2 m)), Monad (t2 m),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2,
SinkT s, MMonad t1, MMonad t2) =>
s (t1 (t2 m)) a -> t1 (t2 (s m)) a
sinkT2 = (sinkT|>|) . sinkT
sinkT3
:: (Monad m, Monad (s (t2 (t3 m))), Monad (s (t3 m)), Monad (t2 (t3 m)), Monad (t3 m),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2, MonadTrans_ x3 t3, Traversable x3,
SinkT s, MMonad t1, MMonad t2, MMonad t3) =>
s (t1 (t2 (t3 m))) a -> t1 (t2 (t3 (s m))) a
sinkT3 = (sinkT2|>|) . sinkT
sinkT4
:: (Monad m, Monad (s (t2 (t3 (t4 m)))), Monad (s (t3 (t4 m))), Monad (s (t4 m)), Monad (t2 (t3 (t4 m))), Monad (t3 (t4 m)), Monad (t4 m),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2, MonadTrans_ x3 t3, Traversable x3, MonadTrans_ x4 t4, Traversable x4,
MMonad t1, MMonad t2, MMonad t3, MMonad t4, SinkT s) =>
s (t1 (t2 (t3 (t4 m)))) a -> t1 (t2 (t3 (t4 (s m)))) a
sinkT4 = (sinkT3|>|) . sinkT
-------------------------------------------------------------------------------
-- Level-1 functions
infixl 4 |>|
-- | Alias to @'hoist'@.
(|>|) :: (Monad m, MFunctor t) => (forall a . m a -> n a) -> t m b -> t n b
(|>|) = hoist
infixl 4 |<|
-- | Equivalent to (|>|) with the arguments flipped.
(|<|) :: (Monad m, MFunctor t) => t m b -> (forall a . m a -> n a) -> t n b
(|<|) l r = hoist r l
infixl 5 |*|
-- | Alias to @'lift'@
(|*|) :: (Monad m, MonadTrans t) => m a -> t m a
(|*|) = lift
infixr 3 |>=>
(|>=>) :: (Monad m3, MMonad t) => (forall a. m1 a -> t m2 a) -> (forall b. m2 b -> t m3 b) -> m1 c -> t m3 c
(|>=>) = (>|>)
infixr 3 |>~
(|>~) :: (Monad n, MMonad t1) => t1 m b -> (forall a. t1 n a) -> t1 n b
m |>~ k = m |>= \_ -> k
-------------------------------------------------------------------------------
-- Level-2 functions
infixr 3 |>>=
-- | The level-2 trans-bind function, analogous to ('>>=')
(|>>=) :: (Monad n, Monad m, Monad (t2 n), Monad (t2 (t2 n)),
MonadTrans_ x t1, Traversable x,
MMonad t1, MMonad t2, SinkT t2) =>
t1 (t2 m) b -> (forall a. m a -> t1 (t2 n) a) -> t1 (t2 n) b
m |>>= f = m |>= \x -> squash |>| (sinkT $ f |>| x)
infixr 3 |>>~
(|>>~) :: (Monad n, Monad m, Monad (t2 n), Monad (t2 (t2 n)),
MonadTrans_ x t1, Traversable x,
MMonad t1, MMonad t2, SinkT t2) =>
t1 (t2 m) b -> (forall a. t1 (t2 n) a) -> t1 (t2 n) b
m |>>~ k = m |>>= \_ -> k
infixr 3 |>>=>
(|>>=>) :: (Monad m3, Monad m2, Monad (t2 m3), Monad (t2 (t2 m3)),
MonadTrans_ x t1, Traversable x,
MMonad t1, MMonad t2, SinkT t2) =>
(forall a. m1 a -> t1 (t2 m2) a) -> (forall b. m2 b -> t1 (t2 m3) b) -> m1 c -> t1 (t2 m3) c
f |>>=> g = \x -> f x |>>= g
infixl 4 |>>|
(|>>|) :: (Monad m, Monad (t2 m), MFunctor t1, MFunctor t2) =>
(forall a . m a -> n a) -> t1 (t2 m) b -> t1 (t2 n) b
(|>>|) f g = (f |>|) |>| g
infixl 4 |<<|
(|<<|) :: (Monad m, Monad (t2 m), MFunctor t1, MFunctor t2) =>
t1 (t2 m) b -> (forall a . m a -> n a) -> t1 (t2 n) b
(|<<|) f g = (g |>|) |>| f
infixl 5 |**|
(|**|) :: (Monad m, MonadTrans t1, MonadTrans t2, Monad (t2 m)) => m a -> t1 (t2 m) a
(|**|) = (|*|) . (|*|)
infixl 5 |-*|
(|-*|) :: (Monad m, MonadTrans t1, MonadTrans t2, MFunctor t1) => t1 m a -> t1 (t2 m) a
(|-*|) = ((|*|) |>|)
-------------------------------------------------------------------------------
-- Level-3 functions
infixr 3 |>>>=
(|>>>=) ::
(Monad n, Monad (t3 n), Monad m, Monad (t3 m),
Monad (t2 (t3 n)), Monad (t2 (t3 (t3 n))), Monad (t3 (t3 n)), Monad (t3 (t2 (t3 n))), Monad (t2 (t2 (t3 n))),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2,
SinkT t2, SinkT t3,
MMonad t1, MMonad t2, MMonad t3) =>
t1 (t2 (t3 m)) b -> (forall a. m a -> t1 (t2 (t3 n)) a) -> t1 (t2 (t3 n)) b
m |>>>= f = m |>>= \x -> squash |>>| (sinkT2 $ f |>| x)
infixr 3 |>>>~
(|>>>~) ::
(Monad n, Monad (t3 n), Monad m, Monad (t3 m),
Monad (t2 (t3 n)), Monad (t2 (t3 (t3 n))), Monad (t3 (t3 n)), Monad (t3 (t2 (t3 n))), Monad (t2 (t2 (t3 n))),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2,
SinkT t2, SinkT t3,
MMonad t1, MMonad t2, MMonad t3) =>
t1 (t2 (t3 m)) b -> (forall a. t1 (t2 (t3 n)) a) -> t1 (t2 (t3 n)) b
m |>>>~ k = m |>>>= \_ -> k
infixr 3 |>>>=>
(|>>>=>) :: (Monad m3, Monad m2, Monad (t2 m3), Monad (t2 (t2 m3)), Monad (t2 (t2 (t3 m3))), Monad (t2 (t3 m3)), Monad (t2 (t3 (t3 m3))),
Monad (t3 m3), Monad (t3 m2), Monad (t3 (t2 (t3 m3))), Monad (t3 (t3 m3)),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2,
MMonad t1, MMonad t2, MMonad t3, SinkT t2, SinkT t3) =>
(forall a. m1 a -> t1 (t2 (t3 m2)) a) -> (forall b. m2 b -> t1 (t2 (t3 m3)) b) -> m1 c -> t1 (t2 (t3 m3)) c
f |>>>=> g = \x -> f x |>>>= g
infixl 4 |>>>|
(|>>>|) :: (Monad m, Monad (t3 m), Monad (t2 (t3 m)), MFunctor t1, MFunctor t2, MFunctor t3) =>
(forall a . m a -> n a) -> t1 (t2 (t3 m)) b -> t1 (t2 (t3 n)) b
(|>>>|) f g = (f |>|) |>>| g
infixl 4 |<<<|
(|<<<|) :: (Monad m, Monad (t3 m), Monad (t2 (t3 m)), MFunctor t1, MFunctor t2, MFunctor t3) =>
t1 (t2 (t3 m)) b -> (forall a . m a -> n a) -> t1 (t2 (t3 n)) b
(|<<<|) f g = (g |>|) |>>| f
infixl 5 |***|
(|***|) :: (Monad m, Monad (t2 (t3 m)), Monad (t3 m),
MonadTrans t1, MonadTrans t2, MonadTrans t3) =>
m a -> t1 (t2 (t3 m)) a
(|***|) = (|*|) . (|**|)
infixl 5 |--*|
(|--*|) :: (Monad m, Monad (t2 m),
MonadTrans t1, MonadTrans t2, MonadTrans t3,
MFunctor t1, MFunctor t2) =>
t1 (t2 m) a -> t1 (t2 (t3 m)) a
(|--*|) = ((|*|) |>>|)
infixl 5 |-**|, |*-*|
(|-**|) :: (Monad m, Monad (t2 (t3 m)), Monad (t3 m),
MonadTrans t1, MonadTrans t2, MonadTrans t3,
MFunctor t1) =>
t1 m a -> t1 (t2 (t3 m)) a
(|-**|) = ((|**|) |>|)
(|*-*|) :: (Monad m, Monad (t3 m), Monad (t2 (t3 m)),
MonadTrans t1, MonadTrans t2, MonadTrans t3,
MFunctor t2) =>
t2 m a -> t1 (t2 (t3 m)) a
(|*-*|) = (|*|) . ((|*|) |>|)
-------------------------------------------------------------------------------
-- Level-4 functions
infixr 4 |>>>>=
(|>>>>=) ::
(Monad n, Monad (t4 n), Monad (t4 m), Monad m,
Monad (t2 (t3 (t4 n))), Monad (t2 (t3 (t4 (t4 n)))), Monad (t2 (t2 (t3 (t4 n)))),
Monad (t3 (t4 n)), Monad (t3 (t4 (t4 n))), Monad (t4 (t4 n)), Monad (t4 (t2 (t3 (t4 n)))), Monad (t2 (t3 (t3 (t4 n)))), Monad (t4 (t3 (t4 n))),
Monad (t2 (t4 n)), Monad (t3 (t2 (t3 (t4 n)))), Monad (t3 (t3 (t4 n))), Monad (t3 (t4 m)),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2, MonadTrans_ x3 t3, Traversable x3,
SinkT t2, SinkT t3, SinkT t4,
MMonad t1, MMonad t2, MMonad t3, MMonad t4) =>
t1 (t2 (t3 (t4 m))) b -> (forall a. m a -> t1 (t2 (t3 (t4 n))) a) -> t1 (t2 (t3 (t4 n))) b
m |>>>>= f = m |>>>= \x -> squash |>>>| (sinkT3 $ f |>| x)
infixr 3 |>>>>~
(|>>>>~) ::
(Monad n, Monad (t4 n), Monad (t4 m), Monad m,
Monad (t2 (t3 (t4 n))), Monad (t2 (t3 (t4 (t4 n)))), Monad (t2 (t2 (t3 (t4 n)))),
Monad (t3 (t4 n)), Monad (t3 (t4 (t4 n))), Monad (t4 (t4 n)), Monad (t4 (t2 (t3 (t4 n)))), Monad (t2 (t3 (t3 (t4 n)))), Monad (t4 (t3 (t4 n))),
Monad (t2 (t4 n)), Monad (t3 (t2 (t3 (t4 n)))), Monad (t3 (t3 (t4 n))), Monad (t3 (t4 m)),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2, MonadTrans_ x3 t3, Traversable x3,
SinkT t2, SinkT t3, SinkT t4,
MMonad t1, MMonad t2, MMonad t3, MMonad t4) =>
t1 (t2 (t3 (t4 m))) b -> (forall a. t1 (t2 (t3 (t4 n))) a) -> t1 (t2 (t3 (t4 n))) b
m |>>>>~ k = m |>>>>= \_ -> k
infixl 4 |>>>>|
(|>>>>|) :: (Monad m, Monad (t4 m), Monad (t3 (t4 m)), Monad (t2 (t3 (t4 m))), MFunctor t1, MFunctor t2, MFunctor t3, MFunctor t4) =>
(forall a . m a -> n a) -> t1 (t2 (t3 (t4 m))) b -> t1 (t2 (t3 (t4 n))) b
(|>>>>|) f g = (f |>|) |>>>| g
infixl 4 |<<<<|
(|<<<<|) :: (Monad m, Monad (t4 m), Monad (t3 (t4 m)), Monad (t2 (t3 (t4 m))), MFunctor t1, MFunctor t2, MFunctor t3, MFunctor t4) =>
t1 (t2 (t3 (t4 m))) b -> (forall a . m a -> n a) -> t1 (t2 (t3 (t4 n))) b
(|<<<<|) f g = (g |>|) |>>>| f
infixl 5 |****|
(|****|) :: (Monad m, Monad (t2 (t3 (t4 m))), Monad (t3 (t4 m)), Monad (t4 m),
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4) =>
m a -> t1 (t2 (t3 (t4 m))) a
(|****|) = (|*|) . (|***|)
infixl 5 |---*|
(|---*|) :: (Monad m, Monad (t2 (t3 m)), Monad (t3 m),
MFunctor t1, MFunctor t2, MFunctor t3,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4) =>
t1 (t2 (t3 m)) a -> t1 (t2 (t3 (t4 m))) a
(|---*|) = ((|*|) |>>>|)
infixl 5 |--**|, |-*-*|
(|--**|) :: (Monad m, Monad (t2 m), Monad (t4 m),
MFunctor t1, MFunctor t2,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4) =>
t1 (t2 m) a -> t1 (t2 (t3 (t4 m))) a
(|--**|) = ((|**|) |>>|)
(|-*-*|) :: (Monad m, Monad (t3 m), Monad (t3 (t4 m)), Monad (t4 m),
MFunctor t1, MFunctor t3,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4) =>
t1 (t3 m) a -> t1 (t2 (t3 (t4 m))) a
(|-*-*|) = ((|*-*|) |>|)
(|*--*|) :: (Monad m, Monad (t3 m), Monad (t2 (t3 (t4 m))), Monad (t2 (t3 m)),
MFunctor t2, MFunctor t3,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4) =>
t2 (t3 m) a -> t1 (t2 (t3 (t4 m))) a
(|*--*|) = (|*|) . (|--*|)
infixl 5 |-***|, |*-**|, |**-*|
(|-***|) :: (Monad m, Monad (t3 (t4 m)), Monad (t4 m),
MFunctor t1,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4) =>
t1 m a -> t1 (t2 (t3 (t4 m))) a
(|-***|) = ((|***|) |>|)
(|*-**|) :: (Monad m, Monad (t2 (t3 (t4 m))), Monad (t3 (t4 m)), Monad (t4 m),
MFunctor t2,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4) =>
t2 m a -> t1 (t2 (t3 (t4 m))) a
(|*-**|) = (|*|) . (|-**|)
(|**-*|) :: (Monad m, Monad (t2 (t3 (t4 m))), Monad (t3 (t4 m)),
MFunctor t3,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4) =>
t3 m a -> t1 (t2 (t3 (t4 m))) a
(|**-*|) = (|**|) . (|-*|)
-------------------------------------------------------------------------------
-- Level-5 functions
infixr 4 |>>>>>=
(|>>>>>=) ::
(Monad n, Monad m, Monad (t5 n), Monad (t5 m),
Monad (t2 (t3 (t4 (t5 n)))), Monad (t2 (t3 (t4 (t5 (t5 n))))), Monad (t3 (t4 (t5 n))), Monad (t3 (t4 (t5 (t5 n)))),
Monad (t4 (t5 n)), Monad (t4 (t5 (t5 n))), Monad (t5 (t2 (t3 (t4 (t5 n))))), Monad (t5 (t5 n)), Monad (t5 (t3 (t4 (t5 n)))),
Monad (t2 (t2 (t3 (t4 (t5 n))))), Monad (t5 (t4 (t5 n))), Monad (t2 (t3 (t3 (t4 (t5 n))))), Monad (t2 (t3 (t4 (t4 (t5 n))))),
Monad (t2 (t4 (t5 n))), Monad (t3 (t2 (t3 (t4 (t5 n))))), Monad (t3 (t3 (t4 (t5 n)))), Monad (t3 (t4 (t4 (t5 n)))),
Monad (t3 (t4 (t5 m))), Monad (t4 (t2 (t3 (t4 (t5 n))))), Monad (t4 (t3 (t4 (t5 n)))), Monad (t4 (t4 (t5 n))), Monad (t4 (t5 m)),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2, MonadTrans_ x3 t3, Traversable x3, MonadTrans_ x4 t4, Traversable x4,
SinkT t2, SinkT t3, SinkT t4, SinkT t5,
MMonad t1, MMonad t2, MMonad t3, MMonad t4, MMonad t5) =>
t1 (t2 (t3 (t4 (t5 m)))) b -> (forall a. m a -> t1 (t2 (t3 (t4 (t5 n)))) a) -> t1 (t2 (t3 (t4 (t5 n)))) b
m |>>>>>= f = m |>>>>= \x -> squash |>>>>| (sinkT4 $ f |>| x)
infixr 3 |>>>>>~
(|>>>>>~) ::
(Monad n, Monad m, Monad (t5 n), Monad (t5 m),
Monad (t2 (t3 (t4 (t5 n)))), Monad (t2 (t3 (t4 (t5 (t5 n))))), Monad (t3 (t4 (t5 n))), Monad (t3 (t4 (t5 (t5 n)))),
Monad (t4 (t5 n)), Monad (t4 (t5 (t5 n))), Monad (t5 (t2 (t3 (t4 (t5 n))))), Monad (t5 (t5 n)), Monad (t5 (t3 (t4 (t5 n)))),
Monad (t2 (t2 (t3 (t4 (t5 n))))), Monad (t5 (t4 (t5 n))), Monad (t2 (t3 (t3 (t4 (t5 n))))), Monad (t2 (t3 (t4 (t4 (t5 n))))),
Monad (t2 (t4 (t5 n))), Monad (t3 (t2 (t3 (t4 (t5 n))))), Monad (t3 (t3 (t4 (t5 n)))), Monad (t3 (t4 (t4 (t5 n)))),
Monad (t3 (t4 (t5 m))), Monad (t4 (t2 (t3 (t4 (t5 n))))), Monad (t4 (t3 (t4 (t5 n)))), Monad (t4 (t4 (t5 n))), Monad (t4 (t5 m)),
MonadTrans_ x1 t1, Traversable x1, MonadTrans_ x2 t2, Traversable x2, MonadTrans_ x3 t3, Traversable x3, MonadTrans_ x4 t4, Traversable x4,
SinkT t2, SinkT t3, SinkT t4, SinkT t5,
MMonad t1, MMonad t2, MMonad t3, MMonad t4, MMonad t5) =>
t1 (t2 (t3 (t4 (t5 m)))) b -> (forall a. t1 (t2 (t3 (t4 (t5 n)))) a) -> t1 (t2 (t3 (t4 (t5 n)))) b
m |>>>>>~ k = m |>>>>>= \_ -> k
infixl 4 |>>>>>|
(|>>>>>|) :: (Monad m, Monad (t5 m), Monad (t4 (t5 m)), Monad (t3 (t4 (t5 m))), Monad (t2 (t3 (t4 (t5 m)))), MFunctor t1, MFunctor t2, MFunctor t3, MFunctor t4, MFunctor t5) =>
(forall a . m a -> n a) -> t1 (t2 (t3 (t4 (t5 m)))) b -> t1 (t2 (t3 (t4 (t5 n)))) b
(|>>>>>|) f g = (f |>|) |>>>>| g
infixl 4 |<<<<<|
(|<<<<<|) :: (Monad m, Monad (t5 m), Monad (t4 (t5 m)), Monad (t3 (t4 (t5 m))), Monad (t2 (t3 (t4 (t5 m)))), MFunctor t1, MFunctor t2, MFunctor t3, MFunctor t4, MFunctor t5) =>
t1 (t2 (t3 (t4 (t5 m)))) b -> (forall a . m a -> n a) -> t1 (t2 (t3 (t4 (t5 n)))) b
(|<<<<<|) f g = (g |>|) |>>>>| f
infixl 5 |*****|
(|*****|) :: (Monad m, Monad (t2 (t3 (t4 (t5 m)))), Monad (t3 (t4 (t5 m))), Monad (t4 (t5 m)), Monad (t5 m),
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
m a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|*****|) = (|*|) . (|****|)
infixl 5 |----*|
(|----*|) :: (Monad m, Monad (t2 (t3 (t4 m))), Monad (t3 (t4 m)), Monad (t4 m),
MFunctor t1, MFunctor t2, MFunctor t3, MFunctor t4,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t1 (t2 (t3 (t4 m))) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|----*|) = ((|*|) |>>>>|)
infixl 5 |---**|, |--*-*|, |-*--*|, |*---*|
(|---**|) :: (Monad m, Monad (t2 (t3 m)), Monad (t3 m), Monad (t5 m),
MFunctor t1, MFunctor t2, MFunctor t3,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t1 (t2 (t3 m)) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|---**|) = ((|**|) |>>>|)
(|--*-*|) :: (Monad m, Monad (t2 (t4 m)), Monad (t4 m), Monad (t4 (t5 m)), Monad (t5 m),
MFunctor t1, MFunctor t2, MFunctor t4,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t1 (t2 (t4 m)) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|--*-*|) = ((|*-*|) |>>|)
(|-*--*|) :: (Monad m, Monad (t3 (t4 m)), Monad (t4 m), Monad (t3 (t4 (t5 m))),
MFunctor t1, MFunctor t3, MFunctor t4,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t1 (t3 (t4 m)) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|-*--*|) = ((|*--*|) |>|)
(|*---*|) :: (Monad m, Monad (t3 (t4 m)), Monad (t4 m), Monad (t2 (t3 (t4 (t5 m)))),
MFunctor t2, MFunctor t3, MFunctor t4,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t2 (t3 (t4 m)) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|*---*|) = (|*|) . (|---*|)
infixl 5 |--***|, |-*-**|, |*--**|, |*-*-*|, |-**-*|, |**--*|
(|--***|) :: (Monad m, Monad (t2 m), Monad (t4 (t5 m)), Monad (t5 m),
MFunctor t1, MFunctor t2,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t1 (t2 m) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|--***|) = ((|***|) |>>|)
(|-*-**|) :: (Monad m, Monad (t3 m), Monad (t3 (t4 (t5 m))), Monad (t4 (t5 m)), Monad (t5 m),
MFunctor t1, MFunctor t3,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t1 (t3 m) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|-*-**|) = ((|*-**|) |>|)
(|*--**|) :: (Monad m, Monad (t3 m), Monad (t2 (t3 (t4 (t5 m)))), Monad (t5 m),
MFunctor t2, MFunctor t3,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t2 (t3 m) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|*--**|) = (|*|) . (|--**|)
(|*-*-*|) :: (Monad m, Monad (t4 m), Monad (t2 (t3 (t4 (t5 m)))), Monad (t4 (t5 m)), Monad (t5 m),
MFunctor t2, MFunctor t4,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t2 (t4 m) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|*-*-*|) = (|*|) . (|-*-*|)
(|-**-*|) :: (Monad m, Monad (t4 m), Monad (t3 (t4 (t5 m))), Monad (t4 (t5 m)), Monad (t5 m),
MFunctor t1, MFunctor t4,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t1 (t4 m) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|-**-*|) = (|-*|) . (|-*-*|)
(|**--*|) :: (Monad m, Monad (t4 m), Monad (t2 (t3 (t4 (t5 m)))), Monad (t3 (t4 (t5 m))), Monad (t3 (t4 m)),
MFunctor t3, MFunctor t4,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t3 (t4 m) a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|**--*|) = (|*|) . (|*--*|)
infixl 5 |-****|, |*-***|, |**-**|, |***-*|
(|-****|) :: (Monad m, Monad (t3 (t4 (t5 m))), Monad (t4 (t5 m)), Monad (t5 m),
MFunctor t1,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t1 m a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|-****|) = ((|****|) |>|)
(|*-***|) :: (Monad m, Monad (t2 (t3 (t4 (t5 m)))), Monad (t4 (t5 m)), Monad (t5 m),
MFunctor t2,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t2 m a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|*-***|) = (|*|) . (|-***|)
(|**-**|) :: (Monad m, Monad (t2 (t3 (t4 (t5 m)))), Monad (t3 (t4 (t5 m))), Monad (t4 (t5 m)), Monad (t5 m),
MFunctor t3,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t3 m a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|**-**|) = (|**|) . (|-**|)
(|***-*|) :: (Monad m, Monad (t2 (t3 (t4 (t5 m)))), Monad (t3 (t4 (t5 m))), Monad (t4 (t5 m)),
MFunctor t4,
MonadTrans t1, MonadTrans t2, MonadTrans t3, MonadTrans t4, MonadTrans t5) =>
t4 m a -> t1 (t2 (t3 (t4 (t5 m)))) a
(|***-*|) = (|***|) . (|-*|)
----------------------------------------------------------------------
-- Examples
{- $Example
Here is a monad morph example how to use trans-map functions.
>import DeepControl.Monad.Morph
>import DeepControl.Monad.Trans.State
>import DeepControl.Monad.Trans.Writer
>
>-- i.e. :: StateT Int Identity ()
>tick :: State Int ()
>tick = modify (+1)
>
>tock :: StateT Int IO ()
>tock = do
> generalize |>| tick :: (Monad m) => StateT Int m () -- (|>|) is the level-1 trans-map function, analogous to (|$>)
> (|*|) $ putStrLn "Tock!" :: (MonadTrans t) => t IO ()
>
>-- λ> runStateT tock 0
>-- Tock!
>-- ((),1)
>
>-- i.e. :: StateT Int (WriterT [Int] Identity) ()
>save :: StateT Int (Writer [Int]) ()
>save = do
> n <- get
> (|*|) $ tell [n]
>
>program :: StateT Int (WriterT [Int] IO) ()
>program = replicateM_ 4 $ do
> (|*|) |>| tock
> :: (MonadTrans t) => StateT Int (t IO) ()
> generalize |>>| save -- (|>>|) is the level-2 trans-map function, analogous to (|$>>)
> :: (Monad m) => StateT Int (WriterT [Int] m ) ()
>
>-- λ> execWriterT (runStateT program 0)
>-- Tock!
>-- Tock!
>-- Tock!
>-- Tock!
>-- [1,2,3,4]
-}
{- $Example-2
Here is a monad morph example how to use trans-cover and trans-bind functions.
>import DeepControl.Monad ((>-))
>import DeepControl.Monad.Morph ((|>=), (|>>=), (|*|), (|-*|))
>import DeepControl.Monad.Trans.Except
>
>import Control.Exception (IOException, try)
>import Control.Monad.Trans.Maybe
>
>-----------------------------------------------
>-- Level-1
>
>check :: IO a ->
> ExceptT IOException IO a -- ExceptT-IO monad
>check io = ExceptT $ (try io)
>
>viewFile :: IO () -- IO monad
>viewFile = do
> str <- readFile "test.txt"
> putStr str
>
>program :: ExceptT IOException IO () -- ExceptT-IO monad
>program = (|*|) viewFile |>= check -- (|*|) is the level-1 trans-cover function, alias to 'lift' and analogous to (.*)
> -- (|>=) is the level-1 trans-bind function, analogous to (>>=)
>
>calc_program :: IO (Either IOException ())
>calc_program = runExceptT $ program
>
>-- > calc_program
>-- Left test.txt: openFile: does not exist (No such file or directory)
>
>-----------------------------------------------
>-- Level-2
>
>viewFile2 :: String ->
> MaybeT IO () -- MaybeT-IO monad
>viewFile2 filename = do
> guard (filename /= "")
> str <- (|*|) $ readFile filename
> (|*|) $ putStr str
>
>program2 :: String ->
> (ExceptT IOException (MaybeT IO)) () -- ExceptT-MaybeT-IO monad
>program2 filename =
> (|*|) (viewFile2 filename) |>>= \x -> -- (|>>=) is the level-2 trans-bind function, analogous to (>>=)
> (|-*|) $ check x -- (|-*|) is a level-2 trans-cover function, analogous to (-*)
>
>calc_program2 :: String -> IO (Maybe (Either IOException ()))
>calc_program2 filename = runMaybeT . runExceptT $ program2 filename
>
>-- > calc_program2 "test.txt"
>-- Just (Left test.txt: openFile: does not exist (No such file or directory))
>-- > calc_program2 ""
>-- Nothing
-}
|
ocean0yohsuke/deepcontrol
|
DeepControl/Monad/Morph.hs
|
bsd-3-clause
| 26,023
| 0
| 19
| 7,014
| 12,486
| 6,611
| 5,875
| 378
| 1
|
{- | Grammar construction combinators.
A grammar in grempa consists of a number of rules and an entry rule.
Constructing a grammar is similar to doing it in BNF, but the grammars
also have the information of what semantic action to take when a production
has been found, which is used by the parsers that can be generated from the
grammars.
Rules, constructed with the 'rule' function, consist of lists of productions.
A production in Grempa starts with a function which acts as the semantic
action to be taken when that production has been parsed. After the '<@>'
operator follows what the production accepts, which consists of a number of
grammar symbols (terminals (tokens) or non-terminals (grammar rules)).
The two combinator functions that construct productions come in two flavours
each: One that signals that the result from parsing the symbol to the right
of it should be used in the semantic action function and one that signals
that it should not:
@action '<@>' symbol =@ An action function followed by a symbol
@action '<@' symbol =@ An action function followed by a symbol which will
not be used when taking the semantic action of the
production.
@prod '<#>' symbol = @A production followed by a symbol
@prod '<#' symbol = @A production followed by a symbol which will not be
used when taking the semantic action of the
production.
The grammars have the type @'Grammar' t a@, which tells us that the grammar
describes a language operating on @[t]@ returning @a@.
Grammars can be recursively defined by using recursive do-notation.
-}
{-# LANGUAGE RecursiveDo, TypeFamilies #-}
module Data.Parser.Grempa.Grammar
( module Data.Parser.Grempa.Grammar.Typed
, module Data.Parser.Grempa.Grammar.Levels
, several0, several, severalInter0, severalInter, cons
) where
import Data.Typeable
import Data.Parser.Grempa.Grammar.Typed
(Grammar, rule, Symbol(..), ToSym(..), (<#>), (<#), (<@>), (<@), epsilon)
import Data.Parser.Grempa.Grammar.Levels
-- | Create a new rule which consists of 0 or more of the argument symbol.
-- Example: @several0 x@ matches @x x ... x@
--
-- Creates one new rule.
several0 :: (ToSym s x, ToSymT s x ~ a, Typeable a, Typeable s)
=> x -> Grammar s [a]
several0 x = do
rec
xs <- rule [epsilon []
,(:) <@> x <#> xs]
return xs
-- | Return a new rule which consists of 1 or more of the argument symbol.
-- Example: @several x@ matches @x x ... x@
--
-- Creates one new rule.
several :: (ToSym s x, ToSymT s x ~ a, Typeable a, Typeable s)
=> x -> Grammar s [a]
several x = do
rec
xs <- rule [(:[]) <@> x
,(:) <@> x <#> xs ]
return xs
-- | Create a new rule which consists of a list of size 0 or more interspersed
-- with a symbol.
-- Example: @severalInter0 ';' x@ matches @x ';' x ';' ... ';' x@
-- If @x :: a@ then the result is of type @[a]@.
--
-- Creates two new rules.
severalInter0 :: ( ToSym s x, ToSymT s x ~ a
, ToSym s t, ToSymT s t ~ s
, Typeable a, Typeable s)
=> t -> x -> Grammar s [a]
severalInter0 tok x = do
rec
xs <- rule [(:[]) <@> x
,(:) <@> x <# tok <#> xs]
res <- rule [epsilon []
,id <@> xs]
return res
-- | Return a new rule which consists of a list of size 1 or more interspersed
-- with a symbol.
-- Example: @severalInter ';' x@ matches @x ';' x ';' ... ';' x@
--
-- Creates one new rule.
severalInter :: ( ToSym s x, ToSymT s x ~ a
, ToSym s t, ToSymT s t ~ s
, Typeable a, Typeable s)
=> t -> x -> Grammar s [a]
severalInter tok x = do
rec
xs <- rule [ (:[]) <@> x
, (:) <@> x <# tok <#> xs]
return xs
-- | Takes two symbols and combines them with @(:)@.
--
-- Creates one new rule.
--
-- This can for example be used instead of using both 'several' and 'several0'
-- on the same symbol, as that will create three new rules, whereas the
-- equivalent using 'cons' will only create two new rules. Example
-- transformation:
--
-- > xs0 <- several0 x
-- > xs <- several x
-- > ==>
-- > xs0 <- several0 x
-- > xs <- x `cons` xs0
cons :: ( ToSym s x, ToSymT s x ~ a
, ToSym s xs, ToSymT s xs ~ [a]
, Typeable a, Typeable s)
=> x -- ^ Symbol of type @a@
-> xs -- ^ Symbol of type @[a]@
-> Grammar s [a]
cons x xs = rule [(:) <@> x <#> xs]
|
ollef/Grempa
|
Data/Parser/Grempa/Grammar.hs
|
bsd-3-clause
| 4,644
| 0
| 14
| 1,342
| 759
| 425
| 334
| 50
| 1
|
module Language.Hakaru.Util.Coda where
import Statistics.Autocorrelation
import qualified Data.Packed.Vector as V
import qualified Data.Vector.Generic as G
effectiveSampleSize :: [Double] -> Double
effectiveSampleSize samples = n / (1 + 2*(G.sum rho))
where n = fromIntegral (V.dim vec)
vec = V.fromList samples
cov = autocovariance vec
rho = G.map (/ G.head cov) cov
|
zaxtax/hakaru-old
|
Language/Hakaru/Util/Coda.hs
|
bsd-3-clause
| 396
| 0
| 10
| 78
| 131
| 75
| 56
| 10
| 1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
-- To generate the golden files use a script similiar to this one
-- > ghc -ilib -isrc -itests tests/RegressionTests.hs -e 'writeGoldFile example9 "example9" defaultOptions'
-- > ghc -ilib -isrc -itests tests/RegressionTests.hs -e 'writeGoldFile example9 "example9_native" nativeOpts'
import Test.Tasty
import Test.Tasty.Golden.Advanced
import Test.Tasty.QuickCheck
import qualified Prelude
import Feldspar
import Feldspar.Mutable
import Feldspar.Vector
import Feldspar.Compiler
import Feldspar.Compiler.Plugin
import Feldspar.Compiler.ExternalProgram (compileFile)
import Control.Applicative hiding (empty)
import Control.Monad
import Control.Monad.Error (liftIO)
import Data.Monoid ((<>))
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy as LB
import qualified Data.ByteString.Lazy.Search as LB
import System.Process
import Text.Printf
#if MIN_VERSION_tasty_golden(2,3,0)
vgReadFiles :: String -> IO LB.ByteString
vgReadFiles base = liftM LB.concat $ mapM (LB.readFile . (base<>)) [".h",".c"]
#else
vgReadFiles :: String -> ValueGetter r LB.ByteString
vgReadFiles base = liftM LB.concat $ mapM (vgReadFile . (base<>)) [".h",".c"]
#endif
example9 :: Data Int32 -> Data Int32
example9 a = condition (a<5) (3*(a+20)) (30*(a+20))
-- Compile and load example9 as c_example9 (using plugins)
loadFun ['example9]
topLevelConsts :: Data Index -> Data Index -> Data Index
topLevelConsts a b = condition (a<5) (d ! (b+5)) (c ! (b+5))
where
c = value [1,2,3,4,5] :: Data [Index]
d = value [2,3,4,5,6] :: Data [Index]
pairParam :: (Data Index, Data Index) -> Data Index
pairParam (x, _) = x
pairParam2 :: (Data Int16, Data Int16) ->
((Data Int16, Data Int16), (Data Int16, Data Int16))
pairParam2 c = (c, c)
-- One test starting.
metrics :: Pull1 IntN -> Pull1 IntN
-> Pull DIM1 (Pull DIM1 (Data Index, Data Index)) -> Pull DIM1 (Pull1 IntN)
metrics s _ = scan (columnMetrics s) initialMetrics
initialMetrics :: Pull1 IntN
initialMetrics = replicate1 8 (-32678)
columnMetrics :: Pull1 IntN -> Pull1 IntN -> Pull DIM1 (Data Index, Data Index)
-> Pull1 IntN
columnMetrics s prev zf = zipWith (metricFast prev) zf s
metricFast :: Pull1 IntN -> (Data Index, Data Index) -> Data IntN -> Data IntN
metricFast prev (z, _) _ = prev !! z
-- End one test.
copyPush :: Pull1 Index -> DPush DIM1 Index
copyPush v = let pv = toPush v in pv ++ pv
-- scanlPush :: DPush sh WordN -> Pull1 WordN -> Push (DPush WordN)
-- scanlPush = scanl const
concatV :: Pull DIM1 (Pull1 IntN) -> DPush DIM1 IntN
concatV xs = fromZero $ fold (++) empty xs
loadFun ['concatV]
complexWhileCond :: Data Int32 -> (Data Int32, Data Int32)
complexWhileCond y = whileLoop (0,y) (\(a,b) -> ((\a b -> a * a /= b * b) a (b-a))) (\(a,b) -> (a+1,b))
-- One test starting
divConq3 :: Pull DIM1 (Data IntN) -> DPush DIM1 IntN
divConq3 xs = concatV $ pmap (map (+1)) (segment 1024 xs)
pmap :: (Syntax a, Syntax b) => (a -> b) -> Pull DIM1 a -> Pull DIM1 b
pmap f = map await . force . map (future . f)
-- Note. @segment@ expects the length of @xs@ to be a multiple of @l@
segment :: Syntax a => Data Length -> Pull DIM1 a -> Pull DIM1 (Pull DIM1 a)
segment l xs = indexed1 clen (\ix -> take l $ drop (ix*l) xs)
where clen = length xs `div` l
loadFun ['divConq3]
-- End one test.
-- | We rewrite `return x >>= \_ -> return y` into `return x >> return y`
-- This test ensures that we can still `return x` in the first action.
bindToThen :: Data Index -> Data Index
bindToThen y = runMutable $ do
ref <- newRef y
_ <- getRef ref
getRef ref
switcher :: Data Word8 -> Data Bool -> Data Word8
switcher i = switch (value 0) [(true,i), (false,2)]
ivartest :: Data Index -> Data Index
ivartest a = share (future (a+1)) $ \a' -> await a' * 2
ivartest2 :: (Data Index, Data Index) -> (Data Index, Data Index)
ivartest2 a = share (future a) $ \a' -> await a'
arrayInStruct :: Data [Length] -> Data [Length]
arrayInStruct a = snd $ whileLoop (getLength a, a) (\(n,_) -> (n>0)) (\(n,a) -> (n-1, parallel (getLength a) (\ i -> a!i + 5)))
arrayInStructInStruct :: Data (Length, (Length, [Length])) -> Data (Length, (Length, [Length]))
arrayInStructInStruct x = x
fut1 :: Future (Data IntN) -> Future (Data IntN)
fut1 x = forLoop 20 x (\_ e -> future $ force $ await e)
not1 :: Data Bool -> Data Bool
not1 x = not x
issue128_ex1 :: Data WordN -> Data WordN
issue128_ex1 a = share (switch 45 [(1,10)] a) $ \b -> (1==a ? b $ a)
issue128_ex2 :: Data WordN -> Data WordN
issue128_ex2 a = share (switch 45 [(1,20)] a) $ \b -> (2==a ? b $ a)
issue128_ex3 :: Data WordN -> Data WordN
issue128_ex3 a = switch 45 [(1,10)] a + (2==a ? 2 $ a)
noinline1 :: Data Bool -> Data Bool
noinline1 x = noInline $ not x
tests :: TestTree
tests = testGroup "RegressionTests" [compilerTests, externalProgramTests]
prop_concatV = forAll (vectorOf 3 (choose (0,5))) $ \ls ->
forAll (mapM (\l -> vectorOf l arbitrary) ls) $ \xss ->
Prelude.concat xss === c_concatV xss
prop_divConq3 = forAll (choose (1,3)) $ \l ->
forAll (vectorOf (l*1024) arbitrary) $ \xs ->
map (+1) xs === c_divConq3 xs
compilerTests :: TestTree
compilerTests = testGroup "Compiler-RegressionTests"
[ testProperty "example9 (plugin)" $ eval example9 ==== c_example9
, testProperty "concatV (plugin)" prop_concatV
-- , testProperty "divConq3 (plugin)" prop_divConq3
, mkGoldTest example9 "example9" defaultOptions
, mkGoldTest pairParam "pairParam" defaultOptions
, mkGoldTest pairParam "pairParam_ret" nativeRetOpts
, mkGoldTest pairParam2 "pairParam2" defaultOptions
, mkGoldTest concatV "concatV" defaultOptions
, mkGoldTest complexWhileCond "complexWhileCond" defaultOptions
, mkGoldTest topLevelConsts "topLevelConsts" defaultOptions
, mkGoldTest topLevelConsts "topLevelConsts_native" nativeOpts
, mkGoldTest topLevelConsts "topLevelConsts_sics" sicsOptions2
, mkGoldTest metrics "metrics" defaultOptions
-- , mkGoldTest scanlPush "scanlPush" defaultOptions
, mkGoldTest divConq3 "divConq3" defaultOptions
, mkGoldTest ivartest "ivartest" defaultOptions
, mkGoldTest ivartest2 "ivartest2" defaultOptions
, mkGoldTest arrayInStruct "arrayInStruct" defaultOptions
, mkGoldTest arrayInStructInStruct "arrayInStructInStruct" defaultOptions
, mkGoldTest fut1 "fut1" defaultOptions
, mkGoldTest fut1 "fut1_ret" nativeRetOpts
, mkGoldTest not1 "not1" defaultOptions
, mkGoldTest not1 "not1_ret" nativeRetOpts
, mkGoldTest issue128_ex1 "issue128_ex1" defaultOptions
, mkGoldTest issue128_ex2 "issue128_ex2" defaultOptions
, mkGoldTest issue128_ex3 "issue128_ex3" defaultOptions
, mkGoldTest noinline1 "noinline1" defaultOptions
-- Build tests.
, mkBuildTest pairParam "pairParam" defaultOptions
, mkBuildTest pairParam "pairParam_ret" nativeRetOpts
, mkBuildTest concatV "concatV" defaultOptions
, mkBuildTest topLevelConsts "topLevelConsts" defaultOptions
, mkBuildTest topLevelConsts "topLevelConsts_native" nativeOpts
, mkBuildTest topLevelConsts "topLevelConsts_sics" sicsOptions2
, mkBuildTest metrics "metrics" defaultOptions
, mkBuildTest copyPush "copyPush" defaultOptions
-- , mkBuildTest scanlPush "scanlPush" defaultOptions
, mkBuildTest divConq3 "divConq3" defaultOptions
, testProperty "bindToThen" (\y -> eval bindToThen y === y)
, mkGoldTest switcher "switcher" defaultOptions
, mkBuildTest ivartest "ivartest" defaultOptions
, mkBuildTest ivartest2 "ivartest2" defaultOptions
, mkBuildTest arrayInStruct "arrayInStruct" defaultOptions
, mkBuildTest arrayInStructInStruct "arrayInStructInStruct" defaultOptions
, mkBuildTest fut1 "fut1" defaultOptions
, mkBuildTest fut1 "fut1_ret" nativeRetOpts
, mkBuildTest not1 "not1" defaultOptions
, mkBuildTest not1 "not1_ret" nativeRetOpts
, mkBuildTest issue128_ex1 "issue128_ex1" defaultOptions
, mkBuildTest issue128_ex2 "issue128_ex2" defaultOptions
, mkBuildTest issue128_ex3 "issue128_ex3" defaultOptions
, mkBuildTest noinline1 "noinline1" defaultOptions
]
externalProgramTests :: TestTree
externalProgramTests = testGroup "ExternalProgram-RegressionTests"
[ mkParseTest "example9" defaultOptions
, mkParseTest "pairParam" defaultOptions
, mkParseTest "pairParam_ret" defaultOptions
, mkParseTest "pairParam2" defaultOptions
, mkParseTest "concatV" defaultOptions
, mkParseTest "complexWhileCond" defaultOptions
, mkParseTest "topLevelConsts" defaultOptions
, mkParseTest "topLevelConsts_native" nativeOpts
, mkParseTest "topLevelConsts_sics" sicsOptions
-- TODO: Enable when encodeType does not include sizes in struct names.
-- , mkParseTest "metrics" defaultOptions
-- , mkParseTest "scanlPush" defaultOptions
-- Still incomplete reconstruction of futures.
, mkParseTest "divConq3" defaultOptions
, mkParseTest "switcher" defaultOptions
, mkParseTest "ivartest" defaultOptions
, mkParseTest "ivartest2" defaultOptions
, mkParseTest "arrayInStruct" defaultOptions
, mkParseTest "arrayInStructInStruct" defaultOptions
, mkParseTest "not1" defaultOptions
, mkParseTest "not1_ret" defaultOptions
]
main :: IO ()
main = defaultMain tests
-- Helper functions
testDir, goldDir :: Prelude.FilePath
testDir = "tests/"
goldDir = "tests/gold/"
nativeOpts :: Options
nativeOpts = defaultOptions{useNativeArrays=True}
nativeRetOpts :: Options
nativeRetOpts = defaultOptions{useNativeReturns=True}
writeGoldFile :: Syntax a => a -> Prelude.FilePath -> Options -> IO ()
writeGoldFile fun n = compile fun (goldDir <> n) n
mkGoldTest fun n opts = do
let ref = goldDir <> n
new = testDir <> n
act = compile fun new n opts
cmp = simpleCmp $ printf "Files '%s' and '%s' differ" ref new
upd = LB.writeFile ref
goldenTest n (vgReadFiles ref) (liftIO act >> vgReadFiles new) cmp upd
simpleCmp :: Prelude.Eq a => String -> a -> a -> IO (Maybe String)
simpleCmp e x y =
return $ if x Prelude.== y then Nothing else Just e
mkParseTest n opts = do
let ref = goldDir <> n
new = testDir <> "ep-" <> n
act = compileFile ref new opts
cmp = fuzzyCmp $ printf "Files '%s' and '%s' differ" ref new
upd = LB.writeFile ref
goldenTest n (vgReadFiles ref) (liftIO act >> vgReadFiles new) cmp upd
fuzzyCmp :: String -> LB.ByteString -> LB.ByteString -> IO (Maybe String)
fuzzyCmp e x y =
return $ if x Prelude.== (filterEp y) then Nothing else Just e
-- Removes "EP-"-related prefixes from the generated output.
filterEp :: LB.ByteString -> LB.ByteString
filterEp xs = LB.replace (B.pack "TESTS_EP-") (B.pack "TESTS_") xs'
where xs' = LB.replace (B.pack "#include \"ep-") (B.pack "#include \"") xs
mkBuildTest fun n opts = do
let new = testDir <> n <> "_build_test"
cfile = new <> ".c"
act = do compile fun new n opts
(_,so,se) <- readProcessWithExitCode "ghc" [cfile, "-c", "-optc -Ilib/Feldspar/C", "-optc -std=c99", "-Wall"] ""
return $ so <> se
cmp _ _ = return Nothing
upd _ = return ()
goldenTest n (return "") (liftIO act >> return "") cmp upd
|
emwap/feldspar-compiler
|
tests/RegressionTests.hs
|
bsd-3-clause
| 11,428
| 0
| 14
| 2,224
| 3,512
| 1,828
| 1,684
| 209
| 2
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE RecordWildCards #-}
module Distribution.Client.GlobalFlags (
GlobalFlags(..)
, defaultGlobalFlags
, RepoContext(..)
, withRepoContext
) where
import Distribution.Client.Types
( Repo(..), RemoteRepo(..) )
import Distribution.Compat.Semigroup
( Semigroup((<>)) )
import Distribution.Simple.Setup
( Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe )
import Distribution.Utils.NubList
( NubList, fromNubList )
import Distribution.Client.HttpUtils
( HttpTransport, configureTransport )
import Distribution.Verbosity
( Verbosity )
import Distribution.Simple.Utils
( info )
import Control.Concurrent
( MVar, newMVar, modifyMVar )
import Control.Exception
( throwIO )
import Control.Monad
( when )
import System.FilePath
( (</>) )
import Network.URI
( uriScheme, uriPath )
import Data.Map
( Map )
import qualified Data.Map as Map
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid
( Monoid(..) )
#endif
import qualified Hackage.Security.Client as Sec
import qualified Hackage.Security.Util.Path as Sec
import qualified Hackage.Security.Util.Pretty as Sec
import qualified Hackage.Security.Client.Repository.Cache as Sec
import qualified Hackage.Security.Client.Repository.Local as Sec.Local
import qualified Hackage.Security.Client.Repository.Remote as Sec.Remote
import qualified Distribution.Client.Security.HTTP as Sec.HTTP
-- ------------------------------------------------------------
-- * Global flags
-- ------------------------------------------------------------
-- | Flags that apply at the top level, not to any sub-command.
data GlobalFlags = GlobalFlags {
globalVersion :: Flag Bool,
globalNumericVersion :: Flag Bool,
globalConfigFile :: Flag FilePath,
globalSandboxConfigFile :: Flag FilePath,
globalConstraintsFile :: Flag FilePath,
globalRemoteRepos :: NubList RemoteRepo, -- ^ Available Hackage servers.
globalCacheDir :: Flag FilePath,
globalLocalRepos :: NubList FilePath,
globalLogsDir :: Flag FilePath,
globalWorldFile :: Flag FilePath,
globalRequireSandbox :: Flag Bool,
globalIgnoreSandbox :: Flag Bool,
globalIgnoreExpiry :: Flag Bool, -- ^ Ignore security expiry dates
globalHttpTransport :: Flag String
}
defaultGlobalFlags :: GlobalFlags
defaultGlobalFlags = GlobalFlags {
globalVersion = Flag False,
globalNumericVersion = Flag False,
globalConfigFile = mempty,
globalSandboxConfigFile = mempty,
globalConstraintsFile = mempty,
globalRemoteRepos = mempty,
globalCacheDir = mempty,
globalLocalRepos = mempty,
globalLogsDir = mempty,
globalWorldFile = mempty,
globalRequireSandbox = Flag False,
globalIgnoreSandbox = Flag False,
globalIgnoreExpiry = Flag False,
globalHttpTransport = mempty
}
instance Monoid GlobalFlags where
mempty = GlobalFlags {
globalVersion = mempty,
globalNumericVersion = mempty,
globalConfigFile = mempty,
globalSandboxConfigFile = mempty,
globalConstraintsFile = mempty,
globalRemoteRepos = mempty,
globalCacheDir = mempty,
globalLocalRepos = mempty,
globalLogsDir = mempty,
globalWorldFile = mempty,
globalRequireSandbox = mempty,
globalIgnoreSandbox = mempty,
globalIgnoreExpiry = mempty,
globalHttpTransport = mempty
}
mappend = (<>)
instance Semigroup GlobalFlags where
a <> b = GlobalFlags {
globalVersion = combine globalVersion,
globalNumericVersion = combine globalNumericVersion,
globalConfigFile = combine globalConfigFile,
globalSandboxConfigFile = combine globalConfigFile,
globalConstraintsFile = combine globalConstraintsFile,
globalRemoteRepos = combine globalRemoteRepos,
globalCacheDir = combine globalCacheDir,
globalLocalRepos = combine globalLocalRepos,
globalLogsDir = combine globalLogsDir,
globalWorldFile = combine globalWorldFile,
globalRequireSandbox = combine globalRequireSandbox,
globalIgnoreSandbox = combine globalIgnoreSandbox,
globalIgnoreExpiry = combine globalIgnoreExpiry,
globalHttpTransport = combine globalHttpTransport
}
where combine field = field a `mappend` field b
-- ------------------------------------------------------------
-- * Repo context
-- ------------------------------------------------------------
-- | Access to repositories
data RepoContext = RepoContext {
-- | All user-specified repositories
repoContextRepos :: [Repo]
-- | Get the HTTP transport
--
-- The transport will be initialized on the first call to this function.
--
-- NOTE: It is important that we don't eagerly initialize the transport.
-- Initializing the transport is not free, and especially in contexts where
-- we don't know a-priori whether or not we need the transport (for instance
-- when using cabal in "nix mode") incurring the overhead of transport
-- initialization on _every_ invocation (eg @cabal build@) is undesirable.
, repoContextGetTransport :: IO HttpTransport
-- | Get the (initialized) secure repo
--
-- (the 'Repo' type itself is stateless and must remain so, because it
-- must be serializable)
, repoContextWithSecureRepo :: forall a.
Repo
-> (forall down. Sec.Repository down -> IO a)
-> IO a
-- | Should we ignore expiry times (when checking security)?
, repoContextIgnoreExpiry :: Bool
}
-- | Wrapper around 'Repository', hiding the type argument
data SecureRepo = forall down. SecureRepo (Sec.Repository down)
withRepoContext :: Verbosity -> GlobalFlags -> (RepoContext -> IO a) -> IO a
withRepoContext verbosity globalFlags = \callback -> do
transportRef <- newMVar Nothing
let httpLib = Sec.HTTP.transportAdapter
verbosity
(getTransport transportRef)
initSecureRepos verbosity httpLib secureRemoteRepos $ \secureRepos' ->
callback RepoContext {
repoContextRepos = allRemoteRepos ++ localRepos
, repoContextGetTransport = getTransport transportRef
, repoContextWithSecureRepo = withSecureRepo secureRepos'
, repoContextIgnoreExpiry = fromFlagOrDefault False
(globalIgnoreExpiry globalFlags)
}
where
secureRemoteRepos =
[ (remote, cacheDir)
| RepoSecure remote cacheDir <- allRemoteRepos ]
allRemoteRepos =
[ case remoteRepoSecure remote of
Just True -> RepoSecure remote cacheDir
_otherwise -> RepoRemote remote cacheDir
| remote <- fromNubList $ globalRemoteRepos globalFlags
, let cacheDir = fromFlag (globalCacheDir globalFlags)
</> remoteRepoName remote ]
localRepos =
[ RepoLocal local
| local <- fromNubList $ globalLocalRepos globalFlags ]
getTransport :: MVar (Maybe HttpTransport) -> IO HttpTransport
getTransport transportRef =
modifyMVar transportRef $ \mTransport -> do
transport <- case mTransport of
Just tr -> return tr
Nothing -> configureTransport
verbosity
(flagToMaybe (globalHttpTransport globalFlags))
return (Just transport, transport)
withSecureRepo :: Map Repo SecureRepo
-> Repo
-> (forall down. Sec.Repository down -> IO a)
-> IO a
withSecureRepo secureRepos repo callback =
case Map.lookup repo secureRepos of
Just (SecureRepo secureRepo) -> callback secureRepo
Nothing -> throwIO $ userError "repoContextWithSecureRepo: unknown repo"
-- | Initialize the provided secure repositories
--
-- Assumed invariant: `remoteRepoSecure` should be set for all these repos.
initSecureRepos :: forall a. Verbosity
-> Sec.HTTP.HttpLib
-> [(RemoteRepo, FilePath)]
-> (Map Repo SecureRepo -> IO a)
-> IO a
initSecureRepos verbosity httpLib repos callback = go Map.empty repos
where
go :: Map Repo SecureRepo -> [(RemoteRepo, FilePath)] -> IO a
go !acc [] = callback acc
go !acc ((r,cacheDir):rs) = do
cachePath <- Sec.makeAbsolute $ Sec.fromFilePath cacheDir
initSecureRepo verbosity httpLib r cachePath $ \r' ->
go (Map.insert (RepoSecure r cacheDir) r' acc) rs
-- | Initialize the given secure repo
--
-- The security library has its own concept of a "local" repository, distinct
-- from @cabal-install@'s; these are secure repositories, but live in the local
-- file system. We use the convention that these repositories are identified by
-- URLs of the form @file:/path/to/local/repo@.
initSecureRepo :: Verbosity
-> Sec.HTTP.HttpLib
-> RemoteRepo -- ^ Secure repo ('remoteRepoSecure' assumed)
-> Sec.Path Sec.Absolute -- ^ Cache dir
-> (SecureRepo -> IO a) -- ^ Callback
-> IO a
initSecureRepo verbosity httpLib RemoteRepo{..} cachePath = \callback -> do
withRepo $ \r -> do
requiresBootstrap <- Sec.requiresBootstrap r
when requiresBootstrap $ Sec.uncheckClientErrors $
Sec.bootstrap r
(map Sec.KeyId remoteRepoRootKeys)
(Sec.KeyThreshold (fromIntegral remoteRepoKeyThreshold))
callback $ SecureRepo r
where
-- Initialize local or remote repo depending on the URI
withRepo :: (forall down. Sec.Repository down -> IO a) -> IO a
withRepo callback | uriScheme remoteRepoURI == "file:" = do
dir <- Sec.makeAbsolute $ Sec.fromFilePath (uriPath remoteRepoURI)
Sec.Local.withRepository dir
cache
Sec.hackageRepoLayout
Sec.hackageIndexLayout
logTUF
callback
withRepo callback =
Sec.Remote.withRepository httpLib
[remoteRepoURI]
Sec.Remote.defaultRepoOpts
cache
Sec.hackageRepoLayout
Sec.hackageIndexLayout
logTUF
callback
cache :: Sec.Cache
cache = Sec.Cache {
cacheRoot = cachePath
, cacheLayout = Sec.cabalCacheLayout
}
-- We display any TUF progress only in verbose mode, including any transient
-- verification errors. If verification fails, then the final exception that
-- is thrown will of course be shown.
logTUF :: Sec.LogMessage -> IO ()
logTUF = info verbosity . Sec.pretty
|
lukexi/cabal
|
cabal-install/Distribution/Client/GlobalFlags.hs
|
bsd-3-clause
| 11,342
| 0
| 19
| 3,232
| 2,033
| 1,140
| 893
| 214
| 4
|
{-# LANGUAGE QuasiQuotes, ScopedTypeVariables #-}
{-# OPTIONS -fno-warn-name-shadowing #-}
module Atomo.Kernel.Particle (load) where
import Atomo
load :: VM ()
load = do
[$p|(p: Particle) call: (targets: List)|] =:::
[$e|(p complete: targets) dispatch|]
[$p|(p: Particle) name|] =: do
((PMSingle n :: Particle Value)) <- here "p" >>= getV
return (string n)
[$p|(p: Particle) names|] =: do
((PMKeyword ns _ :: Particle Value)) <- here "p" >>= getV
return $ list (map string ns)
[$p|(p: Particle) values|] =: do
((PMKeyword _ mvs) :: Particle Value) <- here "p" >>= getV
return . list $
map
(maybe (particle "none") (keyParticleN ["ok"] . (:[])))
mvs
[$p|(p: Particle) type|] =: do
(p :: Particle Value) <- here "p" >>= getV
case p of
PMKeyword {} -> return (particle "keyword")
PMSingle {} -> return (particle "single")
[$p|(p: Particle) complete: (targets: List)|] =: do
(p :: Particle Value) <- here "p" >>= getV
vs <- getList [$e|targets|]
case p of
PMKeyword ns mvs ->
let blanks = length (filter (== Nothing) mvs)
in
if blanks > length vs
then throwError (ParticleArity blanks (length vs))
else return . Message . keyword ns $ completeKP mvs vs
PMSingle n ->
if null vs
then throwError (ParticleArity 1 0)
else return . Message . single n $ head vs
[$p|c define: (p: Particle) on: v with: (targets: List) as: e|] =: do
(p :: Particle Value) <- here "p" >>= getV
v <- here "v"
ts <- getList [$e|targets|]
e <- here "e"
c <- here "c"
let toPattern (Pattern p) = p
toPattern v = PMatch v
others = map toPattern ts
main = toPattern v
ids <- gets primitives
obj <- targets' ids main
pat <-
matchable $
case p of
PMKeyword ns _ ->
keyword ns (main:others)
PMSingle n ->
single n main
let m =
case e of
Expression e' -> Responder pat c e'
_ -> Slot pat v
forM_ obj $ \o ->
defineOn (Reference o) m
return (particle "ok")
[$p|c define: (p: Particle) on: (targets: List) as: v|] =: do
(p :: Particle Value) <- here "p" >>= getV
vs <- getList [$e|targets|]
v <- here "v"
c <- here "c"
let targets =
map (\v ->
case v of
Pattern p -> p
_ -> PMatch v) vs
expr =
case v of
Expression e -> e
_ -> Primitive Nothing v
withTop c $ do
case p of
PMKeyword ns _ ->
define (keyword ns targets) expr
PMSingle n ->
define (single n (head targets)) expr
return (particle "ok")
|
Mathnerd314/atomo
|
src/Atomo/Kernel/Particle.hs
|
bsd-3-clause
| 3,301
| 12
| 20
| 1,461
| 1,272
| 598
| 674
| 85
| 11
|
-----------------------------------------------------------------------------
-- |
-- Module : Data.SBV.Examples.CodeGeneration.GCD
-- Copyright : (c) Levent Erkok
-- License : BSD3
-- Maintainer : erkokl@gmail.com
-- Stability : experimental
--
-- Computing GCD symbolically, and generating C code for it. This example
-- illustrates symbolic termination related issues when programming with
-- SBV, when the termination of a recursive algorithm crucially depends
-- on the value of a symbolic variable. The technique we use is to statically
-- enforce termination by using a recursion depth counter.
-----------------------------------------------------------------------------
module Data.SBV.Examples.CodeGeneration.GCD where
import Data.SBV
import Data.SBV.Tools.CodeGen
-----------------------------------------------------------------------------
-- * Computing GCD
-----------------------------------------------------------------------------
-- | The symbolic GCD algorithm, over two 8-bit numbers. We define @sgcd a 0@ to
-- be @a@ for all @a@, which implies @sgcd 0 0 = 0@. Note that this is essentially
-- Euclid's algorithm, except with a recursion depth counter. We need the depth
-- counter since the algorithm is not /symbolically terminating/, as we don't have
-- a means of determining that the second argument (@b@) will eventually reach 0 in a symbolic
-- context. Hence we stop after 12 iterations. Why 12? We've empirically determined that this
-- algorithm will recurse at most 12 times for arbitrary 8-bit numbers. Of course, this is
-- a claim that we shall prove below.
sgcd :: SWord8 -> SWord8 -> SWord8
sgcd a b = go a b 12
where go :: SWord8 -> SWord8 -> SWord8 -> SWord8
go x y c = ite (c .== 0 ||| y .== 0) -- stop if y is 0, or if we reach the recursion depth
x
(go y y' (c-1))
where (_, y') = x `sQuotRem` y
-----------------------------------------------------------------------------
-- * Verification
-----------------------------------------------------------------------------
{- $VerificationIntro
We prove that 'sgcd' does indeed compute the common divisor of the given numbers.
Our predicate takes @x@, @y@, and @k@. We show that what 'sgcd' returns is indeed a common divisor,
and it is at least as large as any given @k@, provided @k@ is a common divisor as well.
-}
-- | We have:
--
-- >>> prove sgcdIsCorrect
-- Q.E.D.
sgcdIsCorrect :: SWord8 -> SWord8 -> SWord8 -> SBool
sgcdIsCorrect x y k = ite (y .== 0) -- if y is 0
(k' .== x) -- then k' must be x, nothing else to prove by definition
(isCommonDivisor k' &&& -- otherwise, k' is a common divisor and
(isCommonDivisor k ==> k' .>= k)) -- if k is a common divisor as well, then k' is at least as large as k
where k' = sgcd x y
isCommonDivisor a = z1 .== 0 &&& z2 .== 0
where (_, z1) = x `sQuotRem` a
(_, z2) = y `sQuotRem` a
-----------------------------------------------------------------------------
-- * Code generation
-----------------------------------------------------------------------------
{- $VerificationIntro
Now that we have proof our 'sgcd' implementation is correct, we can go ahead
and generate C code for it.
-}
-- | This call will generate the required C files. The following is the function
-- body generated for 'sgcd'. (We are not showing the generated header, @Makefile@,
-- and the driver programs for brevity.) Note that the generated function is
-- a constant time algorithm for GCD. It is not necessarily fastest, but it will take
-- precisely the same amount of time for all values of @x@ and @y@.
--
-- > /* File: "sgcd.c". Automatically generated by SBV. Do not edit! */
-- >
-- > #include <stdio.h>
-- > #include <stdlib.h>
-- > #include <inttypes.h>
-- > #include <stdint.h>
-- > #include <stdbool.h>
-- > #include "sgcd.h"
-- >
-- > SWord8 sgcd(const SWord8 x, const SWord8 y)
-- > {
-- > const SWord8 s0 = x;
-- > const SWord8 s1 = y;
-- > const SBool s3 = s1 == 0;
-- > const SWord8 s4 = (s1 == 0) ? s0 : (s0 % s1);
-- > const SWord8 s5 = s3 ? s0 : s4;
-- > const SBool s6 = 0 == s5;
-- > const SWord8 s7 = (s5 == 0) ? s1 : (s1 % s5);
-- > const SWord8 s8 = s6 ? s1 : s7;
-- > const SBool s9 = 0 == s8;
-- > const SWord8 s10 = (s8 == 0) ? s5 : (s5 % s8);
-- > const SWord8 s11 = s9 ? s5 : s10;
-- > const SBool s12 = 0 == s11;
-- > const SWord8 s13 = (s11 == 0) ? s8 : (s8 % s11);
-- > const SWord8 s14 = s12 ? s8 : s13;
-- > const SBool s15 = 0 == s14;
-- > const SWord8 s16 = (s14 == 0) ? s11 : (s11 % s14);
-- > const SWord8 s17 = s15 ? s11 : s16;
-- > const SBool s18 = 0 == s17;
-- > const SWord8 s19 = (s17 == 0) ? s14 : (s14 % s17);
-- > const SWord8 s20 = s18 ? s14 : s19;
-- > const SBool s21 = 0 == s20;
-- > const SWord8 s22 = (s20 == 0) ? s17 : (s17 % s20);
-- > const SWord8 s23 = s21 ? s17 : s22;
-- > const SBool s24 = 0 == s23;
-- > const SWord8 s25 = (s23 == 0) ? s20 : (s20 % s23);
-- > const SWord8 s26 = s24 ? s20 : s25;
-- > const SBool s27 = 0 == s26;
-- > const SWord8 s28 = (s26 == 0) ? s23 : (s23 % s26);
-- > const SWord8 s29 = s27 ? s23 : s28;
-- > const SBool s30 = 0 == s29;
-- > const SWord8 s31 = (s29 == 0) ? s26 : (s26 % s29);
-- > const SWord8 s32 = s30 ? s26 : s31;
-- > const SBool s33 = 0 == s32;
-- > const SWord8 s34 = (s32 == 0) ? s29 : (s29 % s32);
-- > const SWord8 s35 = s33 ? s29 : s34;
-- > const SBool s36 = 0 == s35;
-- > const SWord8 s37 = s36 ? s32 : s35;
-- > const SWord8 s38 = s33 ? s29 : s37;
-- > const SWord8 s39 = s30 ? s26 : s38;
-- > const SWord8 s40 = s27 ? s23 : s39;
-- > const SWord8 s41 = s24 ? s20 : s40;
-- > const SWord8 s42 = s21 ? s17 : s41;
-- > const SWord8 s43 = s18 ? s14 : s42;
-- > const SWord8 s44 = s15 ? s11 : s43;
-- > const SWord8 s45 = s12 ? s8 : s44;
-- > const SWord8 s46 = s9 ? s5 : s45;
-- > const SWord8 s47 = s6 ? s1 : s46;
-- > const SWord8 s48 = s3 ? s0 : s47;
-- >
-- > return s48;
-- > }
genGCDInC :: IO ()
genGCDInC = compileToC Nothing "sgcd" $ do
x <- cgInput "x"
y <- cgInput "y"
cgReturn $ sgcd x y
|
josefs/sbv
|
Data/SBV/Examples/CodeGeneration/GCD.hs
|
bsd-3-clause
| 6,362
| 0
| 11
| 1,607
| 451
| 290
| 161
| 24
| 1
|
module Utils
( linkedForkIO
, whenJust
) where
import Control.Concurrent.Async
-- | Sparks off a new thread like 'forkIO', but links it with the current
-- thread, such that if the new thread raises an exception, that exception will
-- be re-thrown in the current thread.
linkedForkIO :: IO a -> IO ()
linkedForkIO action = async action >>= link
-- | Do something with a value inside a 'Maybe', unless it is 'Nothing'
-- in which case do nothing.
whenJust :: Monad m => Maybe t -> (t -> m ()) -> m ()
whenJust vM action = case vM of
Just v -> action v
Nothing -> return ()
|
javgh/bridgewalker
|
src/Utils.hs
|
bsd-3-clause
| 636
| 0
| 11
| 174
| 132
| 68
| 64
| 10
| 2
|
#define IncludedcastShift
castShift :: RString -> RString -> RString -> RString -> List Integer -> Proof
{-@ castShift :: tg:RString -> xi:RString -> yi:RString -> zi:RString
-> yis:List (GoodIndex yi tg)
-> {map (castGoodIndexRight tg (xi <+> yi) zi) (map (shiftStringRight tg xi yi) yis) == map (shiftStringRight tg xi (yi <+> zi)) (map (castGoodIndexRight tg yi zi) yis)} @-}
castShift tg xi yi zi yis
= map (castGoodIndexRight tg (xi <+> yi) zi) (map (shiftStringRight tg xi yi) yis)
==. map (shiftStringRight tg xi yi) yis
? mapCastId tg (xi <+> yi) zi (map (shiftStringRight tg xi yi) yis)
==. map (shiftStringRight tg xi ((<+>) yi zi)) (map (castGoodIndexRight tg yi zi) yis)
? (mapShiftIndex tg xi yi zi yis &&& mapCastId tg yi zi yis)
*** QED
{-@ mapShiftIndex :: tg:RString -> xi:RString -> yi:RString -> zi:RString -> xs:List (GoodIndex yi tg)
-> {map (shiftStringRight tg xi yi) xs == map (shiftStringRight tg xi (yi <+> zi)) xs} / [llen xs] @-}
mapShiftIndex :: RString -> RString -> RString -> RString -> List Integer -> Proof
mapShiftIndex tg xi yi zi N
= map (shiftStringRight tg xi yi) N ==. N ==. map (shiftStringRight tg xi (yi <+> zi)) N *** QED
*** QED
mapShiftIndex tg xi yi zi zs@(C i0 is0)
= let is = cast (mapCastId tg yi zi is0) $ map (castGoodIndexRight tg yi zi) is0
i = castGoodIndexRight tg yi zi i0 in
map (shiftStringRight tg xi yi) (C i is)
==. C (shiftStringRight tg xi yi i) (map (shiftStringRight tg xi yi) is)
==. C (shift (stringLen xi) i) (map (shiftStringRight tg xi yi) is)
==. C (shiftStringRight tg xi (yi <+> zi) i) (map (shiftStringRight tg xi yi) is)
==. C (shiftStringRight tg xi (yi <+> zi) i) (map (shiftStringRight tg xi (yi <+> zi)) is)
? mapShiftIndex tg xi yi zi is
==. map (shiftStringRight tg xi (yi <+> zi)) (C i is)
*** QED
|
nikivazou/verified_string_matching
|
src/Proofs/castShift.hs
|
bsd-3-clause
| 1,895
| 19
| 12
| 438
| 669
| 344
| 325
| 23
| 1
|
module Text.Atom.Tests where
import Data.Maybe (isJust)
import Test.Framework (Test, mutuallyExclusive, testGroup)
import Test.HUnit (Assertion, assertBool)
import Test.Framework.Providers.HUnit (testCase)
import Text.Atom.Feed
import Text.Feed.Export
import Text.Feed.Import
import Text.Feed.Query
import Text.Feed.Types
import Text.XML.Light
import Paths_feed
atomTests :: Test
atomTests = testGroup "Text.Atom"
[ mutuallyExclusive $ testGroup "Atom"
[ testFullAtomParse
, testAtomAlternate
]
]
testFullAtomParse :: Test
testFullAtomParse = testCase "parse a complete atom file" testAtom
where
testAtom :: Assertion
testAtom = do
putStrLn . ppTopElement . xmlFeed =<< parseFeedFromFile =<< getDataFileName "tests/files/atom.xml"
assertBool "OK" True
testAtomAlternate :: Test
testAtomAlternate = testCase "*unspecified* link relation means 'alternate'" testAlt
where
testAlt :: Assertion
testAlt =
let nullent = nullEntry "" (TextString "") ""
item = AtomItem nullent { entryLinks = [nullLink ""] }
in assertBool "unspecified means alternate" $ isJust $ getItemLink item
|
danfran/feed
|
tests/Text/Atom/Tests.hs
|
bsd-3-clause
| 1,165
| 0
| 15
| 220
| 274
| 153
| 121
| 30
| 1
|
{-# LINE 1 "GHC.Event.KQueue.hsc" #-}
{-# LANGUAGE Trustworthy #-}
{-# LINE 2 "GHC.Event.KQueue.hsc" #-}
{-# LANGUAGE CApiFFI
, GeneralizedNewtypeDeriving
, NoImplicitPrelude
, RecordWildCards
, BangPatterns
#-}
module GHC.Event.KQueue
(
new
, available
) where
import qualified GHC.Event.Internal as E
{-# LINE 18 "GHC.Event.KQueue.hsc" #-}
{-# LINE 19 "GHC.Event.KQueue.hsc" #-}
import GHC.Base
new :: IO E.Backend
new = errorWithoutStackTrace "KQueue back end not implemented for this platform"
available :: Bool
available = False
{-# INLINE available #-}
{-# LINE 295 "GHC.Event.KQueue.hsc" #-}
|
phischu/fragnix
|
builtins/base/GHC.Event.KQueue.hs
|
bsd-3-clause
| 671
| 0
| 6
| 153
| 65
| 43
| 22
| 17
| 1
|
{-|
Use etherium to access PKI information.
-}
module Urbit.Vere.Dawn where
import Urbit.Arvo.Common
import Urbit.Arvo.Event hiding (Address)
import Urbit.Prelude hiding (Call, rights, to)
import Data.Bits (xor)
import Data.List (nub)
import Data.Text (splitOn)
import Network.Ethereum.Account
import Network.Ethereum.Api.Eth
import Network.Ethereum.Api.Provider
import Network.Ethereum.Api.Types hiding (blockNumber)
import Network.Ethereum.Web3
import Network.HTTP.Client.TLS
import qualified Crypto.Hash.SHA256 as SHA256
import qualified Crypto.Hash.SHA512 as SHA512
import qualified Crypto.Sign.Ed25519 as Ed
import qualified Data.Binary as B
import qualified Data.ByteArray as BA
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C
import qualified Network.Ethereum.Ens as Ens
import qualified Network.HTTP.Client as C
import qualified Urbit.Azimuth as AZ
import qualified Urbit.Ob as Ob
-- During boot, use the infura provider
provider = HttpProvider
"https://mainnet.infura.io/v3/196a7f37c7d54211b4a07904ec73ad87"
-- Conversion Utilities --------------------------------------------------------
-- Takes the web3's bytes representation and changes the endianness.
bytes32ToBS :: BytesN 32 -> ByteString
bytes32ToBS = reverse . BA.pack . BA.unpack
toBloq :: Quantity -> Bloq
toBloq = fromIntegral . unQuantity
passFromEth :: BytesN 32 -> BytesN 32 -> UIntN 32 -> Pass
passFromEth enc aut sut | sut /= 1 =
Pass (Ed.PublicKey mempty) (Ed.PublicKey mempty)
passFromEth enc aut sut =
Pass (decode aut) (decode enc)
where
decode = Ed.PublicKey . bytes32ToBS
clanFromShip :: Ship -> Ob.Class
clanFromShip = Ob.clan . Ob.patp . fromIntegral
shipSein :: Ship -> Ship
shipSein = Ship . fromIntegral . Ob.fromPatp . Ob.sein . Ob.patp . fromIntegral
renderShip :: Ship -> Text
renderShip = Ob.renderPatp . Ob.patp . fromIntegral
-- Data Validation -------------------------------------------------------------
-- Derive public key structure from the key derivation seed structure
ringToPass :: Ring -> Pass
ringToPass Ring{..} = Pass{..}
where
passCrypt = decode ringCrypt
passSign = decode ringSign
decode = fst . fromJust . Ed.createKeypairFromSeed_
fromJust = \case
Nothing -> error "Invalid seed passed to createKeypairFromSeed"
Just x -> x
-- Azimuth Functions -----------------------------------------------------------
-- Perform a request to azimuth at a certain block number
withAzimuth :: Quantity
-> Address
-> DefaultAccount Web3 a
-> Web3 a
withAzimuth bloq azimuth action =
withAccount () $
withParam (to .~ azimuth) $
withParam (block .~ BlockWithNumber bloq)
action
-- Retrieves the EthPoint information for an individual point.
retrievePoint :: Quantity -> Address -> Ship -> Web3 EthPoint
retrievePoint bloq azimuth ship =
withAzimuth bloq azimuth $ do
(encryptionKey,
authenticationKey,
hasSponsor,
active,
escapeRequested,
sponsor,
escapeTo,
cryptoSuite,
keyRevision,
continuityNum) <- AZ.points (fromIntegral ship)
let escapeState = if escapeRequested
then Just $ Ship $ fromIntegral escapeTo
else Nothing
-- The hoon version also sets this to all 0s and then does nothing with it.
let epOwn = (0, 0, 0, 0)
let epNet = if not active
then Nothing
else Just
( fromIntegral keyRevision
, passFromEth encryptionKey authenticationKey cryptoSuite
, fromIntegral continuityNum
, (hasSponsor, Ship (fromIntegral sponsor))
, escapeState
)
-- TODO: wtf?
let epKid = case clanFromShip ship of
Ob.Galaxy -> Just (0, setToHoonSet mempty)
Ob.Star -> Just (0, setToHoonSet mempty)
_ -> Nothing
pure EthPoint{..}
-- Retrieves information about all the galaxies from Ethereum.
retrieveGalaxyTable :: Quantity -> Address -> Web3 (Map Ship (Rift, Life, Pass))
retrieveGalaxyTable bloq azimuth =
withAzimuth bloq azimuth $ mapFromList <$> mapM getRow [0..255]
where
getRow idx = do
(encryptionKey, authenticationKey, _, _, _, _, _, cryptoSuite,
keyRev, continuity) <- AZ.points idx
pure ( fromIntegral idx
, ( fromIntegral continuity
, fromIntegral keyRev
, passFromEth encryptionKey authenticationKey cryptoSuite
)
)
-- Reads the three Ames domains from Ethereum, removing duplicates
readAmesDomains :: Quantity -> Address -> Web3 [Turf]
readAmesDomains bloq azimuth =
withAzimuth bloq azimuth $ nub <$> mapM getTurf [0..2]
where
getTurf idx =
Turf . fmap Cord . reverse . splitOn "." <$> AZ.dnsDomains idx
validateShipAndGetImmediateSponsor :: Quantity -> Address -> Seed -> Web3 Ship
validateShipAndGetImmediateSponsor block azimuth (Seed ship life ring oaf) =
case clanFromShip ship of
Ob.Comet -> validateComet
Ob.Moon -> validateMoon
_ -> validateRest
where
validateComet = do
-- A comet address is the fingerprint of the keypair
let shipFromPass = cometFingerprint $ ringToPass ring
when (ship /= shipFromPass) $
fail ("comet name doesn't match fingerprint " ++ show ship ++ " vs " ++
show shipFromPass)
when (life /= 1) $
fail ("comet can never be re-keyed")
pure (shipSein ship)
validateMoon = do
-- TODO: The current code in zuse does nothing, but we should be able to
-- try to validate the oath against the current as exists planet on
-- chain.
pure $ shipSein ship
validateRest = do
putStrLn ("boot: retrieving " ++ renderShip ship ++ "'s public keys")
whoP <- retrievePoint block azimuth ship
case epNet whoP of
Nothing -> fail "ship not keyed"
Just (netLife, pass, contNum, (hasSponsor, who), _) -> do
when (netLife /= life) $
fail ("keyfile life mismatch; keyfile claims life " ++
show life ++ ", but Azimuth claims life " ++
show netLife)
when ((ringToPass ring) /= pass) $
fail "keyfile does not match blockchain"
-- TODO: The hoon code does a breach check, but the C code never
-- supplies the data necessary for it to function.
pure who
-- Walk through the sponsorship chain retrieving the actual sponsorship chain
-- as it exists on Ethereum.
getSponsorshipChain :: Quantity -> Address -> Ship -> Web3 [(Ship,EthPoint)]
getSponsorshipChain block azimuth = loop
where
loop ship = do
putStrLn ("boot: retrieving keys for sponsor " ++ renderShip ship)
ethPoint <- retrievePoint block azimuth ship
case (clanFromShip ship, epNet ethPoint) of
(Ob.Comet, _) -> fail "Comets cannot be sponsors"
(Ob.Moon, _) -> fail "Moons cannot be sponsors"
(_, Nothing) ->
fail $ unpack ("Ship " ++ renderShip ship ++ " not booted")
(Ob.Galaxy, Just _) -> pure [(ship, ethPoint)]
(_, Just (_, _, _, (False, _), _)) ->
fail $ unpack ("Ship " ++ renderShip ship ++ " has no sponsor")
(_, Just (_, _, _, (True, sponsor), _)) -> do
chain <- loop sponsor
pure $ chain ++ [(ship, ethPoint)]
-- Produces either an error or a validated boot event structure.
dawnVent :: Seed -> RIO e (Either Text Dawn)
dawnVent dSeed@(Seed ship life ring oaf) = do
ret <- runWeb3' provider $ do
block <- blockNumber
putStrLn ("boot: ethereum block #" ++ tshow block)
putStrLn "boot: retrieving azimuth contract"
azimuth <- withAccount () $ Ens.resolve "azimuth.eth"
immediateSponsor <- validateShipAndGetImmediateSponsor block azimuth dSeed
dSponsor <- getSponsorshipChain block azimuth immediateSponsor
putStrLn "boot: retrieving galaxy table"
dCzar <- mapToHoonMap <$> retrieveGalaxyTable block azimuth
putStrLn "boot: retrieving network domains"
dTurf <- readAmesDomains block azimuth
let dBloq = toBloq block
let dNode = Nothing
pure $ MkDawn{..}
case ret of
Left x -> pure $ Left $ tshow x
Right y -> pure $ Right y
dawnCometList :: RIO e [Ship]
dawnCometList = do
-- Get the jamfile with the list of stars accepting comets right now.
manager <- io $ C.newManager tlsManagerSettings
request <- io $ C.parseRequest "https://bootstrap.urbit.org/comet-stars.jam"
response <- io $ C.httpLbs (C.setRequestCheckStatus request) manager
let body = toStrict $ C.responseBody response
noun <- cueBS body & either throwIO pure
fromNounErr noun & either (throwIO . uncurry ParseErr) pure
-- Comet Mining ----------------------------------------------------------------
mix :: BS.ByteString -> BS.ByteString -> BS.ByteString
mix a b = BS.pack $ loop (BS.unpack a) (BS.unpack b)
where
loop [] [] = []
loop a [] = a
loop [] b = b
loop (x:xs) (y:ys) = (xor x y) : loop xs ys
shas :: BS.ByteString -> BS.ByteString -> BS.ByteString
shas salt = SHA256.hash . mix salt . SHA256.hash
shaf :: BS.ByteString -> BS.ByteString -> BS.ByteString
shaf salt ruz = (mix a b)
where
haz = shas salt ruz
a = (take 16 haz)
b = (drop 16 haz)
cometFingerprintBS :: Pass -> ByteString
cometFingerprintBS = (shaf $ C.pack "bfig") . passToBS
cometFingerprint :: Pass -> Ship
cometFingerprint = Ship . B.decode . fromStrict . reverse . cometFingerprintBS
tryMineComet :: Set Ship -> Word64 -> Maybe Seed
tryMineComet ships seed =
if member shipSponsor ships
then Just $ Seed shipName 1 ring Nothing
else Nothing
where
-- Hash the incoming seed into a 64 bytes.
baseHash = SHA512.hash $ toStrict $ B.encode seed
signSeed = (take 32 baseHash)
ringSeed = (drop 32 baseHash)
ring = Ring signSeed ringSeed
pass = ringToPass ring
shipName = cometFingerprint pass
shipSponsor = shipSein shipName
mineComet :: Set Ship -> Word64 -> Seed
mineComet ships = loop
where
loop eny =
case (tryMineComet ships eny) of
Nothing -> loop (eny + 1)
Just x -> x
|
ngzax/urbit
|
pkg/hs/urbit-king/lib/Urbit/Vere/Dawn.hs
|
mit
| 10,356
| 0
| 20
| 2,615
| 2,761
| 1,431
| 1,330
| -1
| -1
|
#!/usr/bin/env runhaskell
-- simplifyprof.hs somefile.prof
-- filter uninteresting fields from GHC profile output
-- tested with GHC 6.8
-- Simon Michael 2007,2008
import Data.List
import System.Environment
import Text.Printf
main = do
args <- getArgs
let f = head args
s <- readFile f
let ls = lines s
let (firstpart, secondpart) = break ("individual inherited" `isInfixOf`) ls
putStr $ unlines firstpart
let fields = map getfields $ filter (not . null) $ drop 2 secondpart
let maxnamelen = maximum $ map (length . head) fields
let fmt = "%-" ++ show maxnamelen ++ "s %10s %5s %6s %9s %10s"
putStrLn $ showheading fmt
putStr $ unlines $ map (format fmt) fields
getfields s = name:rest
where
space = takeWhile (==' ') s
fields = words s
name = space ++ head fields
rest = drop 3 fields
showheading fmt = format fmt ["cost centre","entries","%time","%alloc","%time-inh","%alloc-inh"]
format fmt (s1:s2:s3:s4:s5:s6:[]) = printf fmt s1 s2 s3 s4 s5 s6
|
Lainepress/hledger
|
tools/simplifyprof.hs
|
gpl-3.0
| 1,007
| 3
| 14
| 215
| 361
| 179
| 182
| 22
| 1
|
{-# LANGUAGE FlexibleInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-
Simple.hs - Things for making Tidal extra-simple to use, originally made for 8 year olds.
Copyright (C) 2020, Alex McLean and contributors
This library is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
-}
module Sound.Tidal.Simple where
import Sound.Tidal.Control (chop, hurry)
import Sound.Tidal.Core ((#), (|*), (<~), silence, rev)
import Sound.Tidal.Params (crush, gain, pan, speed, s)
import Sound.Tidal.ParseBP (parseBP_E)
import Sound.Tidal.Pattern (ControlPattern)
import GHC.Exts ( IsString(..) )
instance {-# OVERLAPPING #-} IsString ControlPattern where
fromString = s . parseBP_E
crunch :: ControlPattern -> ControlPattern
crunch = (# crush 3)
scratch :: ControlPattern -> ControlPattern
scratch = rev . chop 32
louder :: ControlPattern -> ControlPattern
louder = (|* gain 1.2)
quieter :: ControlPattern -> ControlPattern
quieter = (|* gain 0.8)
silent :: ControlPattern -> ControlPattern
silent = const silence
skip :: ControlPattern -> ControlPattern
skip = (0.25 <~)
left :: ControlPattern -> ControlPattern
left = (# pan 0)
right :: ControlPattern -> ControlPattern
right = (# pan 1)
higher :: ControlPattern -> ControlPattern
higher = (|* speed 1.5)
lower :: ControlPattern -> ControlPattern
lower = (|* speed 0.75)
faster :: ControlPattern -> ControlPattern
faster = hurry 2
slower :: ControlPattern -> ControlPattern
slower = hurry 0.5
|
bgold-cosmos/Tidal
|
src/Sound/Tidal/Simple.hs
|
gpl-3.0
| 2,046
| 41
| 6
| 363
| 386
| 216
| 170
| 35
| 1
|
{-# LANGUAGE OverloadedStrings #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.CloudWatch.Types
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.AWS.CloudWatch.Types
(
-- * Service Configuration
cloudWatch
-- * Errors
, _LimitExceededFault
, _InvalidNextToken
, _InternalServiceFault
, _InvalidParameterValueException
, _InvalidFormatFault
, _MissingRequiredParameterException
, _InvalidParameterCombinationException
, _ResourceNotFound
-- * ComparisonOperator
, ComparisonOperator (..)
-- * HistoryItemType
, HistoryItemType (..)
-- * StandardUnit
, StandardUnit (..)
-- * StateValue
, StateValue (..)
-- * Statistic
, Statistic (..)
-- * AlarmHistoryItem
, AlarmHistoryItem
, alarmHistoryItem
, ahiAlarmName
, ahiHistoryItemType
, ahiHistoryData
, ahiHistorySummary
, ahiTimestamp
-- * Datapoint
, Datapoint
, datapoint
, dSampleCount
, dMaximum
, dAverage
, dMinimum
, dSum
, dUnit
, dTimestamp
-- * Dimension
, Dimension
, dimension
, dName
, dValue
-- * DimensionFilter
, DimensionFilter
, dimensionFilter
, dfValue
, dfName
-- * Metric
, Metric
, metric
, mMetricName
, mNamespace
, mDimensions
-- * MetricAlarm
, MetricAlarm
, metricAlarm
, maAlarmName
, maStateUpdatedTimestamp
, maPeriod
, maAlarmDescription
, maEvaluationPeriods
, maMetricName
, maNamespace
, maComparisonOperator
, maOKActions
, maStateValue
, maThreshold
, maAlarmConfigurationUpdatedTimestamp
, maActionsEnabled
, maInsufficientDataActions
, maStateReason
, maStateReasonData
, maDimensions
, maAlarmARN
, maAlarmActions
, maUnit
, maStatistic
-- * MetricDatum
, MetricDatum
, metricDatum
, mdValue
, mdDimensions
, mdUnit
, mdTimestamp
, mdStatisticValues
, mdMetricName
-- * StatisticSet
, StatisticSet
, statisticSet
, ssSampleCount
, ssSum
, ssMinimum
, ssMaximum
) where
import Network.AWS.CloudWatch.Types.Product
import Network.AWS.CloudWatch.Types.Sum
import Network.AWS.Prelude
import Network.AWS.Sign.V4
-- | API version '2010-08-01' of the Amazon CloudWatch SDK configuration.
cloudWatch :: Service
cloudWatch =
Service
{ _svcAbbrev = "CloudWatch"
, _svcSigner = v4
, _svcPrefix = "monitoring"
, _svcVersion = "2010-08-01"
, _svcEndpoint = defaultEndpoint cloudWatch
, _svcTimeout = Just 70
, _svcCheck = statusSuccess
, _svcError = parseXMLError
, _svcRetry = retry
}
where
retry =
Exponential
{ _retryBase = 5.0e-2
, _retryGrowth = 2
, _retryAttempts = 5
, _retryCheck = check
}
check e
| has (hasCode "ThrottlingException" . hasStatus 400) e =
Just "throttling_exception"
| has (hasCode "Throttling" . hasStatus 400) e = Just "throttling"
| has (hasStatus 503) e = Just "service_unavailable"
| has (hasStatus 500) e = Just "general_server_error"
| has (hasStatus 509) e = Just "limit_exceeded"
| otherwise = Nothing
-- | The quota for alarms for this customer has already been reached.
_LimitExceededFault :: AsError a => Getting (First ServiceError) a ServiceError
_LimitExceededFault = _ServiceError . hasStatus 400 . hasCode "LimitExceeded"
-- | The next token specified is invalid.
_InvalidNextToken :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidNextToken = _ServiceError . hasStatus 400 . hasCode "InvalidNextToken"
-- | Indicates that the request processing has failed due to some unknown
-- error, exception, or failure.
_InternalServiceFault :: AsError a => Getting (First ServiceError) a ServiceError
_InternalServiceFault =
_ServiceError . hasStatus 500 . hasCode "InternalServiceError"
-- | Bad or out-of-range value was supplied for the input parameter.
_InvalidParameterValueException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidParameterValueException =
_ServiceError . hasStatus 400 . hasCode "InvalidParameterValue"
-- | Data was not syntactically valid JSON.
_InvalidFormatFault :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidFormatFault = _ServiceError . hasStatus 400 . hasCode "InvalidFormat"
-- | An input parameter that is mandatory for processing the request is not
-- supplied.
_MissingRequiredParameterException :: AsError a => Getting (First ServiceError) a ServiceError
_MissingRequiredParameterException =
_ServiceError . hasStatus 400 . hasCode "MissingParameter"
-- | Parameters that must not be used together were used together.
_InvalidParameterCombinationException :: AsError a => Getting (First ServiceError) a ServiceError
_InvalidParameterCombinationException =
_ServiceError . hasStatus 400 . hasCode "InvalidParameterCombination"
-- | The named resource does not exist.
_ResourceNotFound :: AsError a => Getting (First ServiceError) a ServiceError
_ResourceNotFound = _ServiceError . hasStatus 404 . hasCode "ResourceNotFound"
|
fmapfmapfmap/amazonka
|
amazonka-cloudwatch/gen/Network/AWS/CloudWatch/Types.hs
|
mpl-2.0
| 5,501
| 0
| 13
| 1,285
| 935
| 535
| 400
| 133
| 1
|
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
-- | This module defines the kinds of vectors that occur in SL and VSL programs.
module Database.DSH.Common.Vector
( ColName
, RelationalVector(..)
, DagVector
, vectorNodes
, updateVector
, DVec(..)
, RVec(..)
, KVec(..)
, SVec(..)
, FVec(..)
) where
import Data.Aeson.TH
import qualified Data.Vector as V
import Database.Algebra.Dag.Common
type ColName = String
--------------------------------------------------------------------------------
-- Abstractions over data vectors
-- | Concrete relational encodings of segment vectors have to provide
-- segment-key relations (foreign-key relations) between outer and inner vectors
-- as well as payload columns.
class RelationalVector v where
rvKeyCols :: v -> [ColName]
rvRefCols :: v -> [ColName]
rvItemCols :: v -> V.Vector ColName
-- | Common properties of data vectors that are represented by a DAG
-- plan of operators.
class DagVector v where
-- | Return all graph nodes which represent the vector.
vectorNodes :: v -> [AlgNode]
-- | Replace a node in the vector
updateVector :: AlgNode -> AlgNode -> v -> v
--------------------------------------------------------------------------------
-- Abstract vector types for vectorization
-- | An abstract segment data vector
newtype DVec = DVec AlgNode
deriving (Show, Read)
instance DagVector DVec where
vectorNodes (DVec q) = [q]
updateVector n1 n2 (DVec q)
| q == n1 = DVec n2
| otherwise = DVec q
-- | Replication vectors.
newtype RVec = RVec AlgNode deriving (Show)
-- | Rekeying vectors.
newtype KVec = KVec AlgNode deriving (Show)
-- | Filtering vectors.
newtype FVec = FVec AlgNode deriving (Show)
-- | Sorting vectors.
newtype SVec = SVec AlgNode deriving (Show)
$(deriveJSON defaultOptions ''RVec)
$(deriveJSON defaultOptions ''KVec)
$(deriveJSON defaultOptions ''SVec)
$(deriveJSON defaultOptions ''FVec)
$(deriveJSON defaultOptions ''DVec)
|
ulricha/dsh
|
src/Database/DSH/Common/Vector.hs
|
bsd-3-clause
| 2,123
| 0
| 9
| 443
| 413
| 238
| 175
| 41
| 0
|
{-# LANGUAGE TypeOperators #-}
module BarnesHutPar ( bhStep )
where
import Data.Array.Parallel.Unlifted.Distributed
import Data.Array.Parallel.Unlifted.Parallel
import Data.Array.Parallel.Unlifted.Sequential
import Data.Array.Parallel.Base ( (:*:)(..), sndS, uncurryS )
import BarnesHutGen
{-# NOINLINE bhStep #-}
bhStep (dx, dy, particles) = accs
where
accs = calcAccel bhTree (flattenSU particles)
bhTree = splitPointsLPar (singletonU ((0.0 :*: 0.0) :*: (dx :*: dy)))
particles
-- Phase 1: building the tree
--
-- Split massPoints according to their locations in the quadrants
--
splitPoints:: BoundingBox -> UArr MassPoint -> SUArr MassPoint
splitPoints (ll@(llx :*: lly) :*: ru@(rux :*: ruy)) particles
| noOfPoints == 0 = singletonSU particles
| otherwise = singletonSU lls +:+^ singletonSU lus +:+^ singletonSU rus +:+^ singletonSU rls
where
noOfPoints = lengthU particles
lls = filterUP (inBox (ll :*: mid)) particles
lus = filterUP (inBox ((llx :*: midy) :*: (midx :*: ruy ))) particles
rus = filterUP (inBox (mid :*: ru )) particles
rls = filterUP (inBox ((midx :*: lly) :*: (rux :*: midy))) particles
mid@(midx :*: midy) = ((llx + rux)/2.0) :*: ((lly + ruy)/2.0)
splitPointsLPar:: UArr BoundingBox -> SUArr MassPoint -> BHTree
splitPointsLPar bboxes particless
| lengthSU multiparticles == 0 = [(centroids, toUSegd emptyU)]
| otherwise = (centroids, segdSU multiparticles) :
(splitPointsLPar newBoxes multiparticles)
where
-- calculate centroid of each segment
centroids =
calcCentroids $ segmentArrU nonEmptySegd $ flattenSU particless
-- remove empty segments
multiPointFlags = mapUP ((>1)) $ lengthsSU particless
multiparticles = (splitPointsL' llbb lubb rubb rlbb) $
packCUP multiPointFlags particless
bboxes' = packUP bboxes multiPointFlags
nonEmptySegd = filterUP ((>0)) $ lengthsSU particless
-- split each box in four sub-boxes
newBoxes = merge4 llbb lubb rubb rlbb
lls :*: rus = unzipU bboxes'
llxs :*: llys = unzipU lls
ruxs :*: ruys = unzipU rus
midxs = zipWithUP mid llxs ruxs
midys = zipWithUP mid llys ruys
llbb = zipU (zipU llxs llys) (zipU midxs midys)
lubb = zipU (zipU llxs midys) (zipU midxs ruys)
rubb = zipU (zipU midxs midys) (zipU ruxs ruys)
rlbb = zipU (zipU midxs llys) (zipU ruxs midys)
mid a b = (a+b)/2
{-
llbb = mapUP makells bboxes'
lubb = mapUP makelus bboxes'
rubb = mapUP makerus bboxes'
rlbb = mapUP makerls bboxes'
makells (ll@(llx :*: lly) :*: ru@(rux :*: ruy)) =
ll :*: (((llx + rux)/2.0) :*: (((lly + ruy)/2.0)))
makelus (ll@(llx :*: lly) :*: ru@(rux :*: ruy)) =
(llx :*: ((lly + ruy)/2.0)) :*: (((llx + rux)/2.0) :*: ruy )
makerus (ll@(llx :*: lly) :*: ru@(rux :*: ruy)) =
(((llx + rux)/2.0) :*: ((lly + ruy)/2.0)) :*: ru
makerls (ll@(llx :*: lly) :*: ru@(rux :*: ruy)) =
((((llx + rux)/2.0) :*: lly) :*: (rux :*: ((lly + ruy)/2.0)))
-}
splitPointsL':: UArr BoundingBox ->
UArr BoundingBox ->
UArr BoundingBox ->
UArr BoundingBox ->
SUArr MassPoint ->
SUArr MassPoint
splitPointsL' llbb lubb rubb rlbb particless
| particlessLen == 0 = particless
| otherwise = orderedPoints
where
-- each segment split into four subsegments with particles located in
-- the four quadrants
orderedPoints =
segmentArrU newLengths $
flattenSU $ llsPs ^+:+^ lusPs ^+:+^ rusPs ^+:+^ rlsPs
particlessLen = lengthSU particless
pssSegd = segdSU particless
pssLens = lengthsSU particless
{-
llsPs = sndSU $ filterSUP (uncurryS inBox)
(zipSU (replicateSUP pssSegd llbb) particless)
lusPs = sndSU $ filterSUP (uncurryS inBox)
(zipSU (replicateSUP pssSegd lubb) particless)
rusPs = sndSU $ filterSUP (uncurryS inBox)
(zipSU (replicateSUP pssSegd rubb) particless)
rlsPs = sndSU $ filterSUP (uncurryS inBox)
(zipSU (replicateSUP pssSegd rlbb) particless)
-}
llsPs = sndSU
. filterSUP (uncurryS inBox)
$ zipSU (replicateSUP pssSegd llbb) particless
lusPs = sndSU
. filterSUP (uncurryS inBox)
$ zipSU (replicateSUP pssSegd lubb) particless
rusPs = sndSU
. filterSUP (uncurryS inBox)
$ zipSU (replicateSUP pssSegd rubb) particless
rlsPs = sndSU
. filterSUP (uncurryS inBox)
$ zipSU (replicateSUP pssSegd rlbb) particless
newLengths =
merge4 (lengthsSU llsPs) (lengthsSU lusPs)
(lengthsSU rusPs) (lengthsSU rlsPs)
-- Calculate centroid of each subarray
--
calcCentroids:: SUArr MassPoint -> UArr MassPoint
calcCentroids orderedPoints = centroids
where
ms = foldSUP (+) 0.0 $ sndSU orderedPoints
centroids = zipWithUP div' ms $
foldSUP pairP (0.0 :*: 0.0) $
zipWithSUP multCoor orderedPoints
(replicateSUP (segdSU orderedPoints) ms)
div' m (x :*: y) = ((x/m :*: y/m) :*: m)
multCoor ((x :*: y) :*: _) m = (m * x :*: m * y)
pairP (x1 :*: y1) (x2 :*: y2) = ((x1+x2) :*: (y1 + y2))
-- phase 2:
-- calculating the velocities
calcAccel:: BHTree -> UArr MassPoint -> UArr (Double :*: Double)
calcAccel [] particles
| lengthU particles == 0 = emptyU
| otherwise = error $ "calcVelocity: reached empty tree" ++ (show particles)
calcAccel ((centroids, segd) :trees) particles = closeAccel
where
closeAccel = splitApplyU particlesClose
((calcAccel trees) . sndU )
calcFarAccel
(zipU
(flattenSU $ replicateCU (lengthU particles) centroids)
(flattenSU
$ replicateSUP
(lengthsToUSegd
$ replicateUP (lengthU particles) (lengthU centroids))
particles))
particlesClose (((x1 :*: y1):*: _) :*: ((x2 :*: y2) :*: _)) =
(x1-x2)^2 + (y1-y2)^2 < eClose
calcFarAccel:: UArr (MassPoint :*: MassPoint) -> UArr Accel
{-# INLINE calcFarAccel #-}
calcFarAccel = mapUP accel
--
--
accel:: MassPoint :*: MassPoint -> Accel
{-# INLINE accel #-}
accel (((x1:*: y1) :*: m) :*:
((x2:*: y2) :*: _)) | r < epsilon = (0.0 :*: 0.0)
| otherwise = (aabs * dx / r :*: aabs * dy / r)
where
rsqr = (dx * dx) + (dy * dy)
r = sqrt rsqr
dx = x1 - x2
dy = y1 - y2
aabs = m / rsqr
-- assumes all arr have the same length
-- result [a11, a21, a31, a41, a12, a22....]
merge4:: UA a => UArr a -> UArr a -> UArr a -> UArr a -> UArr a
{-# INLINE merge4 #-}
merge4 a1 a2 a3 a4 = concatSU
$ singletonsSU a1 ^+:+^ singletonsSU a2
^+:+^ singletonsSU a3 ^+:+^ singletonsSU a4
{-
merge4 a1 a2 a3 a4 =
combineU flags3 (combineU flags2 (combineU flags1 a1 a2) a3) a4
where
flags1 = mapUP even $ enumFromToUP 0 (2 * len-1)
flags2 = mapUP (\x -> mod x 3 /= 2) $ enumFromToUP 0 (3 * len-1)
flags3 = mapUP (\x -> mod x 4 /= 3) $ enumFromToUP 0 (4 * len-1)
len = lengthU a1
-}
-- checks if particle is in box (excluding left and lower border)
inBox:: BoundingBox -> MassPoint -> Bool
{-# INLINE inBox #-}
inBox ((ll@(llx :*: lly) :*: ru@(rux :*: ruy))) ((px :*: py) :*: _) =
(px > llx) && (px <= rux) && (py > lly) && (py <= ruy)
splitApplyU:: (UA e, UA e') => (e -> Bool) -> (UArr e -> UArr e') -> (UArr e -> UArr e') -> UArr e -> UArr e'
{-# INLINE splitApplyU #-}
splitApplyU p f1 f2 xsArr = combineUP flags res1 res2
where
flags = mapUP p xsArr
res1 = f1 $ packUP xsArr flags
res2 = f2 $ packUP xsArr (mapUP not flags)
splitApplySU:: (UA e, UA e') => UArr Bool -> (SUArr e -> SUArr e') -> (SUArr e -> SUArr e') -> SUArr e -> SUArr e'
{-# INLINE splitApplySU #-}
splitApplySU flags f1 f2 xssArr = combineCUP flags res1 res2
where
res1 = f1 $ packCUP flags xssArr
res2 = f2 $ packCUP (mapUP not flags) xssArr
|
mainland/dph
|
icebox/examples/barnesHut/BarnesHutPar.hs
|
bsd-3-clause
| 8,711
| 0
| 17
| 2,830
| 2,278
| 1,181
| 1,097
| 135
| 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.IAM.PutGroupPolicy
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Adds (or updates) an inline policy document that is embedded in the specified
-- group.
--
-- A user can also have managed policies attached to it. To attach a managed
-- policy to a group, use 'AttachGroupPolicy'. To create a new managed policy, use 'CreatePolicy'. For information about policies, refer to <http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html Managed Policies andInline Policies> in the /Using IAM/ guide.
--
-- For information about limits on the number of inline policies that you can
-- embed in a group, see <http://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html Limitations on IAM Entities> in the /Using IAM/ guide.
--
-- Because policy documents can be large, you should use POST rather than GET
-- when calling 'PutGroupPolicy'. For general information about using the Query
-- API with IAM, go to <http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html Making Query Requests> in the /Using IAM/ guide.
--
-- <http://docs.aws.amazon.com/IAM/latest/APIReference/API_PutGroupPolicy.html>
module Network.AWS.IAM.PutGroupPolicy
(
-- * Request
PutGroupPolicy
-- ** Request constructor
, putGroupPolicy
-- ** Request lenses
, pgpGroupName
, pgpPolicyDocument
, pgpPolicyName
-- * Response
, PutGroupPolicyResponse
-- ** Response constructor
, putGroupPolicyResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.IAM.Types
import qualified GHC.Exts
data PutGroupPolicy = PutGroupPolicy
{ _pgpGroupName :: Text
, _pgpPolicyDocument :: Text
, _pgpPolicyName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'PutGroupPolicy' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'pgpGroupName' @::@ 'Text'
--
-- * 'pgpPolicyDocument' @::@ 'Text'
--
-- * 'pgpPolicyName' @::@ 'Text'
--
putGroupPolicy :: Text -- ^ 'pgpGroupName'
-> Text -- ^ 'pgpPolicyName'
-> Text -- ^ 'pgpPolicyDocument'
-> PutGroupPolicy
putGroupPolicy p1 p2 p3 = PutGroupPolicy
{ _pgpGroupName = p1
, _pgpPolicyName = p2
, _pgpPolicyDocument = p3
}
-- | The name of the group to associate the policy with.
pgpGroupName :: Lens' PutGroupPolicy Text
pgpGroupName = lens _pgpGroupName (\s a -> s { _pgpGroupName = a })
-- | The policy document.
pgpPolicyDocument :: Lens' PutGroupPolicy Text
pgpPolicyDocument =
lens _pgpPolicyDocument (\s a -> s { _pgpPolicyDocument = a })
-- | The name of the policy document.
pgpPolicyName :: Lens' PutGroupPolicy Text
pgpPolicyName = lens _pgpPolicyName (\s a -> s { _pgpPolicyName = a })
data PutGroupPolicyResponse = PutGroupPolicyResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'PutGroupPolicyResponse' constructor.
putGroupPolicyResponse :: PutGroupPolicyResponse
putGroupPolicyResponse = PutGroupPolicyResponse
instance ToPath PutGroupPolicy where
toPath = const "/"
instance ToQuery PutGroupPolicy where
toQuery PutGroupPolicy{..} = mconcat
[ "GroupName" =? _pgpGroupName
, "PolicyDocument" =? _pgpPolicyDocument
, "PolicyName" =? _pgpPolicyName
]
instance ToHeaders PutGroupPolicy
instance AWSRequest PutGroupPolicy where
type Sv PutGroupPolicy = IAM
type Rs PutGroupPolicy = PutGroupPolicyResponse
request = post "PutGroupPolicy"
response = nullResponse PutGroupPolicyResponse
|
romanb/amazonka
|
amazonka-iam/gen/Network/AWS/IAM/PutGroupPolicy.hs
|
mpl-2.0
| 4,522
| 0
| 9
| 955
| 474
| 293
| 181
| 60
| 1
|
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Main where
-------------------------------------------------------------------------------
import Control.Category
import Control.Lens
import Control.Monad
import qualified Data.ByteString.Char8 as B
import qualified Data.Conduit as C
import qualified Data.Conduit.List as C
import Data.CSV.Conduit
import Data.Default
import Prelude hiding (id, (.))
-------------------------------------------------------------------------------
import Hadron.Controller
-------------------------------------------------------------------------------
main :: IO ()
main = hadoopMain app (LocalRun def) RSReRun
-- notice how path is a file
source = do
t <- binaryDirTap "data" (== "data/sample.csv")
return $ t & proto %~ (csvProtocol def . )
-- notice how path is a folder
target = tap "data/wordFrequency" (csvProtocol def)
truncated = tap "data/truncated.csv" (csvProtocol def)
-- notice how output is a file
wordCountTarget = tap "data/wordCount.csv" (csvProtocol def)
mr1 :: MapReduce (Row B.ByteString) (Row B.ByteString)
mr1 = MapReduce def pSerialize mapper' Nothing (Left reducer')
-------------------------------------------------------------------------------
mapper':: Mapper (Row B.ByteString) B.ByteString Int
mapper' = C.concatMap (map (\w -> (w, 1 :: Int)) . concatMap B.words)
reducer' :: Reducer B.ByteString Int (Row B.ByteString)
reducer' = do
(!w, !cnt) <- C.fold (\ (_, !cnt) (k, !x) -> (k, cnt + x)) ("", 0)
C.yield [w, B.pack . show $ cnt]
-------------------------------------------------------------------------------
-- | Count the number of words in mr1 output
mr2 :: MapReduce (Row B.ByteString) (Row B.ByteString)
mr2 = MapReduce def pSerialize m Nothing (Left r)
where
m :: Mapper (Row B.ByteString) String Int
m = C.map (const $ ("count", 1))
r :: Reducer (String) Int (Row B.ByteString)
r = do
cnt <- C.fold (\ !m (_, !i) -> m + i) 0
C.yield ["Total Count", (B.pack . show) cnt]
mr3 :: MapReduce (Row B.ByteString) (Row B.ByteString)
mr3 = MapReduce opts pSerialize m Nothing r
where
opts = def & mroNumReduce .~ Just 0
m = C.map (\ v -> ((), map (B.take 5) v) )
r = Right (C.map id)
app :: Controller ()
app = do
src <- source
connect mr1 [src] target (Just "Counting word frequency")
connect mr2 [target] wordCountTarget (Just "Counting words")
connect mr3 [target] truncated (Just "Truncating all fields")
|
dmjio/hadron
|
examples/WordCountLocal.hs
|
bsd-3-clause
| 2,722
| 0
| 14
| 587
| 815
| 437
| 378
| 50
| 1
|
{-# LANGUAGE DeriveGeneric, OverloadedStrings, LambdaCase, ScopedTypeVariables, TupleSections #-}
module Client ( startSessions
, runTest
, closeSession
, Server(..)
, Session
, sessionName
) where
import Control.Concurrent (forkIO)
import Control.Concurrent.Lifted
import Control.Concurrent.Chan.Lifted
import Control.Concurrent.MVar.Lifted
import Control.Exception.Lifted
import Control.Monad.IO.Class
import Data.Maybe
import Data.Monoid
import Data.Time.Clock
import qualified Test.WebDriver as WD
import qualified Test.WebDriver.Class as WD
import Data.Text (Text)
import qualified Data.Text as T
import Types
data Server = Server { serverPort :: Int
, wdScript :: Text
}
data Session = Session { sessionName :: String
, sessionQueue :: (Chan (Maybe ( FilePath
, FilePath
, [String]
, MVar (Maybe (StdioResult,Integer))
)))
}
wdConfig :: Text -> Int -> WD.Browser -> WD.WDConfig
wdConfig host port browser =
WD.defaultConfig { WD.wdHost = T.unpack host
, WD.wdPort = port
, WD.wdCapabilities = caps
}
where
caps = WD.defaultCaps { WD.javascriptEnabled = Just True
, WD.browser = browser
}
startSessions :: Server -> Text -> Int -> IO [Session]
startSessions server host port = do
sessions <- mapM (startSession server host port)
[ ("Firefox", WD.firefox)
, ("Chrome", WD.chrome)
, ("Internet Explorer", WD.ie)
, ("Opera", WD.opera)
, ("Safari", WD.Browser "safari")
]
return (catMaybes sessions)
startSession :: Server -> Text -> Int -> (String, WD.Browser) -> IO (Maybe Session)
startSession server host port (bname, browser) = do
mv <- newEmptyMVar
_ <- forkIO (sess mv `catch` \(_::SomeException) -> putMVar mv Nothing)
takeMVar mv
where
-- cfg = wdConfig host port browser
sess mv = WD.runSession (wdConfig host port browser) $
WD.finallyClose $ do
WD.setScriptTimeout 300000
WD.setPageLoadTimeout 300000
WD.openPage (serverUrl server "empty.html")
ch <- liftIO newChan
let s = Session bname ch
liftIO $ putMVar mv (Just s)
runSessionChan server s
closeSession :: Session -> IO ()
closeSession s = writeChan (sessionQueue s) Nothing
runTest :: FilePath -> FilePath -> [String] -> Session -> IO (Maybe (StdioResult, Integer))
runTest dir page args sess = do
res <- newEmptyMVar
writeChan (sessionQueue sess) (Just (dir, page, args, res))
readMVar res
serverUrl :: Server -> String -> String
serverUrl s e = "http://127.0.0.1:" <> show (serverPort s) <> "/" <> e
runSessionChan :: forall wd. (MonadIO wd, WD.WebDriver wd)
=> Server
-> Session
-> wd ()
runSessionChan server sess =
liftIO (readChan $ sessionQueue sess) >>= \x -> case x of
Just (dir, page, args, res) -> (processCommand dir page args res `catch` handler)
`finally`
(liftIO (tryPutMVar res Nothing) >> runSessionChan server sess)
Nothing -> liftIO (putStrLn $ "closing session " ++ sessionName sess)
where
handler :: SomeException -> wd ()
handler e = liftIO . putStrLn $ "exception running test in " ++
sessionName sess ++ "\n" ++ show e
processCommand dir page args res = do
t0 <- liftIO getCurrentTime
WD.openPage (serverUrl server (dir <> "/" <> page))
r <- WD.asyncJS [WD.JSArg args, WD.JSArg (serverUrl server dir)] (wdScript server)
t1 <- liftIO getCurrentTime
liftIO (putMVar res (fmap (,round (1000 * diffUTCTime t1 t0)) r))
WD.openPage (serverUrl server "empty.html")
|
seereason/ghcjs
|
test/Client.hs
|
mit
| 4,350
| 0
| 18
| 1,579
| 1,215
| 641
| 574
| 87
| 2
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="es-ES">
<title>Bug Tracker</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/bugtracker/src/main/javahelp/org/zaproxy/zap/extension/bugtracker/resources/help_es_ES/helpset_es_ES.hs
|
apache-2.0
| 956
| 82
| 52
| 156
| 390
| 206
| 184
| -1
| -1
|
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="ko-KR">
<title>Active Scan Rules - Beta | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
thc202/zap-extensions
|
addOns/ascanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/ascanrulesBeta/resources/help_ko_KR/helpset_ko_KR.hs
|
apache-2.0
| 985
| 83
| 53
| 162
| 403
| 212
| 191
| -1
| -1
|
{-+
Auxiliary E structure functions.
-}
module HsExpUtil where
import HsExpStruct
import HsIdent
import SrcLoc1(SrcLoc)
--import HsAssoc
import HsExpMaps(mapEI, accEI)
import MUtils(( # ))
-- Auxiliary type used during parsing&printing, not part of the abstract syntax:
data HsStmtAtom e p ds
= HsGeneratorAtom SrcLoc p e
| HsQualifierAtom e
| HsLetStmtAtom ds
| HsLastAtom e
deriving (Eq, Show)
atoms2Stmt [HsQualifierAtom e] = return (HsLast e)
atoms2Stmt (HsGeneratorAtom s p e : ss) = HsGenerator s p e # atoms2Stmt ss
atoms2Stmt (HsLetStmtAtom ds : ss) = HsLetStmt ds # atoms2Stmt ss
atoms2Stmt (HsQualifierAtom e : ss) = HsQualifier e # atoms2Stmt ss
atoms2Stmt _ = fail "last statement in a 'do' expression must be an expression"
getStmtList (HsGenerator l p e s) = HsGeneratorAtom l p e : getStmtList s
getStmtList (HsQualifier e s) = HsQualifierAtom e : getStmtList s
getStmtList (HsLetStmt ds s) = HsLetStmtAtom ds : getStmtList s
getStmtList (HsLast e) = [HsLastAtom e]
isHsIdVar e =
case e of
HsId (HsVar n) -> Just n
_ -> Nothing
{-
isPatternE iscon isvar pef pe =
case pe of
HsId (HsVar n) -> True
HsTuple es -> all pef es
HsWildCard -> True
HsApp e1 e2 | iscon e1 -> pef e2
| isvar e1 -> False
| otherwise -> pef e1 && pef e2
HsList es -> all pef es
HsInfixApp e1 (HsCon op) e2 -> pef e1 && pef e2
HsParen e -> pef e
HsAsPat n e -> pef e
HsRecConstr con fields -> True
_ -> False
-}
{-
isFundefLhsE pef fdf pe p =
case pe of
HsParen e -> fdf e p
HsId (HsVar n) -> p
HsApp l r -> pef r && fdf l True
HsInfixApp l (HsVar n) r -> pef l && pef r
_ -> False
-}
{-+
Finds all of the free variables in an E structure.
-}
{-
freeVarsE fve e =
case e of
HsId (HsVar n) -> [n]
_ -> accEI (const id) (++) (++) (++) (++) (++)
(mapEI id fve (const []) (const [])
(const []) (const [])
e)
[]
-}
{- Obsolete...
reassociateE isinfix make undo rae rap rads env (HsInfixApp a op1 b) =
let f = getHSName op1
a' = rae env a
in
if isinfix a' then
let (op2, c, d) = undo a'
g = getHSName op2
in
if (getPrec env f) > (getPrec env g) ||
((getPrec env f == getPrec env g) &&
(getAssoc env f == HsAssocRight &&
getAssoc env g == HsAssocRight))
then
HsInfixApp c op2 (rae env (make d op1 b))
else
HsInfixApp a' op1 (rae env b)
else
HsInfixApp a' op1 b
reassociateE isinfix make undo rae rap rads env e =
mapEI id (rae env) (rap env) (rads env) id id e
-}
{-
removeParensE make rp e =
case e of
HsParen e' -> rp e'
_ -> make $ mapEI id rp id id id id e
-}
|
forste/haReFork
|
tools/base/AST/HsExpUtil.hs
|
bsd-3-clause
| 3,071
| 0
| 10
| 1,118
| 358
| 186
| 172
| 25
| 2
|
{-# LANGUAGE DataKinds, KindSignatures, PolyKinds, GADTs, ExistentialQuantification #-}
module T6049 where
import Data.Kind (Type)
data SMaybe :: (k -> Type) -> Maybe k -> Type where
SNothing :: forall k (s :: k -> Type). SMaybe s Nothing
SJust :: forall k (s :: k -> Type) (a :: k). SMaybe s (Just a)
|
sdiehl/ghc
|
testsuite/tests/polykinds/T6049.hs
|
bsd-3-clause
| 313
| 0
| 9
| 65
| 105
| 62
| 43
| 6
| 0
|
import Data.Sequence -- needs to be compiled with -DTESTING for use here
import Control.Applicative (Applicative(..))
import Control.Arrow ((***))
import Data.Foldable (Foldable(..), toList, all, sum)
import Data.Functor ((<$>), (<$))
import Data.Maybe
import Data.Monoid (Monoid(..))
import Data.Traversable (Traversable(traverse), sequenceA)
import Prelude hiding (
null, length, take, drop, splitAt,
foldl, foldl1, foldr, foldr1, scanl, scanl1, scanr, scanr1,
filter, reverse, replicate, zip, zipWith, zip3, zipWith3,
all, sum)
import qualified Prelude
import qualified Data.List
import Test.QuickCheck hiding ((><))
import Test.QuickCheck.Poly
import Test.Framework
import Test.Framework.Providers.QuickCheck2
main :: IO ()
main = defaultMainWithOpts
[ testProperty "fmap" prop_fmap
, testProperty "(<$)" prop_constmap
, testProperty "foldr" prop_foldr
, testProperty "foldr1" prop_foldr1
, testProperty "foldl" prop_foldl
, testProperty "foldl1" prop_foldl1
, testProperty "(==)" prop_equals
, testProperty "compare" prop_compare
, testProperty "mappend" prop_mappend
, testProperty "singleton" prop_singleton
, testProperty "(<|)" prop_cons
, testProperty "(|>)" prop_snoc
, testProperty "(><)" prop_append
, testProperty "fromList" prop_fromList
, testProperty "replicate" prop_replicate
, testProperty "replicateA" prop_replicateA
, testProperty "replicateM" prop_replicateM
, testProperty "iterateN" prop_iterateN
, testProperty "unfoldr" prop_unfoldr
, testProperty "unfoldl" prop_unfoldl
, testProperty "null" prop_null
, testProperty "length" prop_length
, testProperty "viewl" prop_viewl
, testProperty "viewr" prop_viewr
, testProperty "scanl" prop_scanl
, testProperty "scanl1" prop_scanl1
, testProperty "scanr" prop_scanr
, testProperty "scanr1" prop_scanr1
, testProperty "tails" prop_tails
, testProperty "inits" prop_inits
, testProperty "takeWhileL" prop_takeWhileL
, testProperty "takeWhileR" prop_takeWhileR
, testProperty "dropWhileL" prop_dropWhileL
, testProperty "dropWhileR" prop_dropWhileR
, testProperty "spanl" prop_spanl
, testProperty "spanr" prop_spanr
, testProperty "breakl" prop_breakl
, testProperty "breakr" prop_breakr
, testProperty "partition" prop_partition
, testProperty "filter" prop_filter
, testProperty "sort" prop_sort
, testProperty "sortBy" prop_sortBy
, testProperty "unstableSort" prop_unstableSort
, testProperty "unstableSortBy" prop_unstableSortBy
, testProperty "index" prop_index
, testProperty "adjust" prop_adjust
, testProperty "update" prop_update
, testProperty "take" prop_take
, testProperty "drop" prop_drop
, testProperty "splitAt" prop_splitAt
, testProperty "elemIndexL" prop_elemIndexL
, testProperty "elemIndicesL" prop_elemIndicesL
, testProperty "elemIndexR" prop_elemIndexR
, testProperty "elemIndicesR" prop_elemIndicesR
, testProperty "findIndexL" prop_findIndexL
, testProperty "findIndicesL" prop_findIndicesL
, testProperty "findIndexR" prop_findIndexR
, testProperty "findIndicesR" prop_findIndicesR
, testProperty "foldlWithIndex" prop_foldlWithIndex
, testProperty "foldrWithIndex" prop_foldrWithIndex
, testProperty "mapWithIndex" prop_mapWithIndex
, testProperty "reverse" prop_reverse
, testProperty "zip" prop_zip
, testProperty "zipWith" prop_zipWith
, testProperty "zip3" prop_zip3
, testProperty "zipWith3" prop_zipWith3
, testProperty "zip4" prop_zip4
, testProperty "zipWith4" prop_zipWith4
] opts
where
opts = mempty { ropt_test_options = Just $ mempty { topt_maximum_generated_tests = Just 500
, topt_maximum_unsuitable_generated_tests = Just 500
}
}
------------------------------------------------------------------------
-- Arbitrary
------------------------------------------------------------------------
instance Arbitrary a => Arbitrary (Seq a) where
arbitrary = Seq <$> arbitrary
shrink (Seq x) = map Seq (shrink x)
instance Arbitrary a => Arbitrary (Elem a) where
arbitrary = Elem <$> arbitrary
instance (Arbitrary a, Sized a) => Arbitrary (FingerTree a) where
arbitrary = sized arb
where
arb :: (Arbitrary a, Sized a) => Int -> Gen (FingerTree a)
arb 0 = return Empty
arb 1 = Single <$> arbitrary
arb n = deep <$> arbitrary <*> arb (n `div` 2) <*> arbitrary
shrink (Deep _ (One a) Empty (One b)) = [Single a, Single b]
shrink (Deep _ pr m sf) =
[deep pr' m sf | pr' <- shrink pr] ++
[deep pr m' sf | m' <- shrink m] ++
[deep pr m sf' | sf' <- shrink sf]
shrink (Single x) = map Single (shrink x)
shrink Empty = []
instance (Arbitrary a, Sized a) => Arbitrary (Node a) where
arbitrary = oneof [
node2 <$> arbitrary <*> arbitrary,
node3 <$> arbitrary <*> arbitrary <*> arbitrary]
shrink (Node2 _ a b) =
[node2 a' b | a' <- shrink a] ++
[node2 a b' | b' <- shrink b]
shrink (Node3 _ a b c) =
[node2 a b, node2 a c, node2 b c] ++
[node3 a' b c | a' <- shrink a] ++
[node3 a b' c | b' <- shrink b] ++
[node3 a b c' | c' <- shrink c]
instance Arbitrary a => Arbitrary (Digit a) where
arbitrary = oneof [
One <$> arbitrary,
Two <$> arbitrary <*> arbitrary,
Three <$> arbitrary <*> arbitrary <*> arbitrary,
Four <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary]
shrink (One a) = map One (shrink a)
shrink (Two a b) = [One a, One b]
shrink (Three a b c) = [Two a b, Two a c, Two b c]
shrink (Four a b c d) = [Three a b c, Three a b d, Three a c d, Three b c d]
------------------------------------------------------------------------
-- Valid trees
------------------------------------------------------------------------
class Valid a where
valid :: a -> Bool
instance Valid (Elem a) where
valid _ = True
instance Valid (Seq a) where
valid (Seq xs) = valid xs
instance (Sized a, Valid a) => Valid (FingerTree a) where
valid Empty = True
valid (Single x) = valid x
valid (Deep s pr m sf) =
s == size pr + size m + size sf && valid pr && valid m && valid sf
instance (Sized a, Valid a) => Valid (Node a) where
valid node = size node == sum (fmap size node) && all valid node
instance Valid a => Valid (Digit a) where
valid = all valid
{--------------------------------------------------------------------
The general plan is to compare each function with a list equivalent.
Each operation should produce a valid tree representing the same
sequence as produced by its list counterpart on corresponding inputs.
(The list versions are often lazier, but these properties ignore
strictness.)
--------------------------------------------------------------------}
-- utilities for partial conversions
infix 4 ~=
(~=) :: Eq a => Maybe a -> a -> Bool
(~=) = maybe (const False) (==)
-- Partial conversion of an output sequence to a list.
toList' :: Seq a -> Maybe [a]
toList' xs
| valid xs = Just (toList xs)
| otherwise = Nothing
toListList' :: Seq (Seq a) -> Maybe [[a]]
toListList' xss = toList' xss >>= mapM toList'
toListPair' :: (Seq a, Seq b) -> Maybe ([a], [b])
toListPair' (xs, ys) = (,) <$> toList' xs <*> toList' ys
-- instances
prop_fmap :: Seq Int -> Bool
prop_fmap xs =
toList' (fmap f xs) ~= map f (toList xs)
where f = (+100)
prop_constmap :: A -> Seq A -> Bool
prop_constmap x xs =
toList' (x <$ xs) ~= map (const x) (toList xs)
prop_foldr :: Seq A -> Bool
prop_foldr xs =
foldr f z xs == Prelude.foldr f z (toList xs)
where
f = (:)
z = []
prop_foldr1 :: Seq Int -> Property
prop_foldr1 xs =
not (null xs) ==> foldr1 f xs == Data.List.foldr1 f (toList xs)
where f = (-)
prop_foldl :: Seq A -> Bool
prop_foldl xs =
foldl f z xs == Prelude.foldl f z (toList xs)
where
f = flip (:)
z = []
prop_foldl1 :: Seq Int -> Property
prop_foldl1 xs =
not (null xs) ==> foldl1 f xs == Data.List.foldl1 f (toList xs)
where f = (-)
prop_equals :: Seq OrdA -> Seq OrdA -> Bool
prop_equals xs ys =
(xs == ys) == (toList xs == toList ys)
prop_compare :: Seq OrdA -> Seq OrdA -> Bool
prop_compare xs ys =
compare xs ys == compare (toList xs) (toList ys)
prop_mappend :: Seq A -> Seq A -> Bool
prop_mappend xs ys =
toList' (mappend xs ys) ~= toList xs ++ toList ys
-- * Construction
{-
toList' empty ~= []
-}
prop_singleton :: A -> Bool
prop_singleton x =
toList' (singleton x) ~= [x]
prop_cons :: A -> Seq A -> Bool
prop_cons x xs =
toList' (x <| xs) ~= x : toList xs
prop_snoc :: Seq A -> A -> Bool
prop_snoc xs x =
toList' (xs |> x) ~= toList xs ++ [x]
prop_append :: Seq A -> Seq A -> Bool
prop_append xs ys =
toList' (xs >< ys) ~= toList xs ++ toList ys
prop_fromList :: [A] -> Bool
prop_fromList xs =
toList' (fromList xs) ~= xs
-- ** Repetition
prop_replicate :: NonNegative Int -> A -> Bool
prop_replicate (NonNegative m) x =
toList' (replicate n x) ~= Prelude.replicate n x
where n = m `mod` 10000
prop_replicateA :: NonNegative Int -> Bool
prop_replicateA (NonNegative m) =
traverse toList' (replicateA n a) ~= sequenceA (Prelude.replicate n a)
where
n = m `mod` 10000
a = Action 1 0 :: M Int
prop_replicateM :: NonNegative Int -> Bool
prop_replicateM (NonNegative m) =
traverse toList' (replicateM n a) ~= sequence (Prelude.replicate n a)
where
n = m `mod` 10000
a = Action 1 0 :: M Int
-- ** Iterative construction
prop_iterateN :: NonNegative Int -> Int -> Bool
prop_iterateN (NonNegative m) x =
toList' (iterateN n f x) ~= Prelude.take n (Prelude.iterate f x)
where
n = m `mod` 10000
f = (+1)
prop_unfoldr :: [A] -> Bool
prop_unfoldr z =
toList' (unfoldr f z) ~= Data.List.unfoldr f z
where
f [] = Nothing
f (x:xs) = Just (x, xs)
prop_unfoldl :: [A] -> Bool
prop_unfoldl z =
toList' (unfoldl f z) ~= Data.List.reverse (Data.List.unfoldr (fmap swap . f) z)
where
f [] = Nothing
f (x:xs) = Just (xs, x)
swap (x,y) = (y,x)
-- * Deconstruction
-- ** Queries
prop_null :: Seq A -> Bool
prop_null xs =
null xs == Prelude.null (toList xs)
prop_length :: Seq A -> Bool
prop_length xs =
length xs == Prelude.length (toList xs)
-- ** Views
prop_viewl :: Seq A -> Bool
prop_viewl xs =
case viewl xs of
EmptyL -> Prelude.null (toList xs)
x :< xs' -> valid xs' && toList xs == x : toList xs'
prop_viewr :: Seq A -> Bool
prop_viewr xs =
case viewr xs of
EmptyR -> Prelude.null (toList xs)
xs' :> x -> valid xs' && toList xs == toList xs' ++ [x]
-- * Scans
prop_scanl :: [A] -> Seq A -> Bool
prop_scanl z xs =
toList' (scanl f z xs) ~= Data.List.scanl f z (toList xs)
where f = flip (:)
prop_scanl1 :: Seq Int -> Property
prop_scanl1 xs =
not (null xs) ==> toList' (scanl1 f xs) ~= Data.List.scanl1 f (toList xs)
where f = (-)
prop_scanr :: [A] -> Seq A -> Bool
prop_scanr z xs =
toList' (scanr f z xs) ~= Data.List.scanr f z (toList xs)
where f = (:)
prop_scanr1 :: Seq Int -> Property
prop_scanr1 xs =
not (null xs) ==> toList' (scanr1 f xs) ~= Data.List.scanr1 f (toList xs)
where f = (-)
-- * Sublists
prop_tails :: Seq A -> Bool
prop_tails xs =
toListList' (tails xs) ~= Data.List.tails (toList xs)
prop_inits :: Seq A -> Bool
prop_inits xs =
toListList' (inits xs) ~= Data.List.inits (toList xs)
-- ** Sequential searches
-- We use predicates with varying density.
prop_takeWhileL :: Positive Int -> Seq Int -> Bool
prop_takeWhileL (Positive n) xs =
toList' (takeWhileL p xs) ~= Prelude.takeWhile p (toList xs)
where p x = x `mod` n == 0
prop_takeWhileR :: Positive Int -> Seq Int -> Bool
prop_takeWhileR (Positive n) xs =
toList' (takeWhileR p xs) ~= Prelude.reverse (Prelude.takeWhile p (Prelude.reverse (toList xs)))
where p x = x `mod` n == 0
prop_dropWhileL :: Positive Int -> Seq Int -> Bool
prop_dropWhileL (Positive n) xs =
toList' (dropWhileL p xs) ~= Prelude.dropWhile p (toList xs)
where p x = x `mod` n == 0
prop_dropWhileR :: Positive Int -> Seq Int -> Bool
prop_dropWhileR (Positive n) xs =
toList' (dropWhileR p xs) ~= Prelude.reverse (Prelude.dropWhile p (Prelude.reverse (toList xs)))
where p x = x `mod` n == 0
prop_spanl :: Positive Int -> Seq Int -> Bool
prop_spanl (Positive n) xs =
toListPair' (spanl p xs) ~= Data.List.span p (toList xs)
where p x = x `mod` n == 0
prop_spanr :: Positive Int -> Seq Int -> Bool
prop_spanr (Positive n) xs =
toListPair' (spanr p xs) ~= (Prelude.reverse *** Prelude.reverse) (Data.List.span p (Prelude.reverse (toList xs)))
where p x = x `mod` n == 0
prop_breakl :: Positive Int -> Seq Int -> Bool
prop_breakl (Positive n) xs =
toListPair' (breakl p xs) ~= Data.List.break p (toList xs)
where p x = x `mod` n == 0
prop_breakr :: Positive Int -> Seq Int -> Bool
prop_breakr (Positive n) xs =
toListPair' (breakr p xs) ~= (Prelude.reverse *** Prelude.reverse) (Data.List.break p (Prelude.reverse (toList xs)))
where p x = x `mod` n == 0
prop_partition :: Positive Int -> Seq Int -> Bool
prop_partition (Positive n) xs =
toListPair' (partition p xs) ~= Data.List.partition p (toList xs)
where p x = x `mod` n == 0
prop_filter :: Positive Int -> Seq Int -> Bool
prop_filter (Positive n) xs =
toList' (filter p xs) ~= Prelude.filter p (toList xs)
where p x = x `mod` n == 0
-- * Sorting
prop_sort :: Seq OrdA -> Bool
prop_sort xs =
toList' (sort xs) ~= Data.List.sort (toList xs)
prop_sortBy :: Seq (OrdA, B) -> Bool
prop_sortBy xs =
toList' (sortBy f xs) ~= Data.List.sortBy f (toList xs)
where f (x1, _) (x2, _) = compare x1 x2
prop_unstableSort :: Seq OrdA -> Bool
prop_unstableSort xs =
toList' (unstableSort xs) ~= Data.List.sort (toList xs)
prop_unstableSortBy :: Seq OrdA -> Bool
prop_unstableSortBy xs =
toList' (unstableSortBy compare xs) ~= Data.List.sort (toList xs)
-- * Indexing
prop_index :: Seq A -> Property
prop_index xs =
not (null xs) ==> forAll (choose (0, length xs-1)) $ \ i ->
index xs i == toList xs !! i
prop_adjust :: Int -> Int -> Seq Int -> Bool
prop_adjust n i xs =
toList' (adjust f i xs) ~= adjustList f i (toList xs)
where f = (+n)
prop_update :: Int -> A -> Seq A -> Bool
prop_update i x xs =
toList' (update i x xs) ~= adjustList (const x) i (toList xs)
prop_take :: Int -> Seq A -> Bool
prop_take n xs =
toList' (take n xs) ~= Prelude.take n (toList xs)
prop_drop :: Int -> Seq A -> Bool
prop_drop n xs =
toList' (drop n xs) ~= Prelude.drop n (toList xs)
prop_splitAt :: Int -> Seq A -> Bool
prop_splitAt n xs =
toListPair' (splitAt n xs) ~= Prelude.splitAt n (toList xs)
adjustList :: (a -> a) -> Int -> [a] -> [a]
adjustList f i xs =
[if j == i then f x else x | (j, x) <- Prelude.zip [0..] xs]
-- ** Indexing with predicates
-- The elem* tests have poor coverage, but for find* we use predicates
-- of varying density.
prop_elemIndexL :: A -> Seq A -> Bool
prop_elemIndexL x xs =
elemIndexL x xs == Data.List.elemIndex x (toList xs)
prop_elemIndicesL :: A -> Seq A -> Bool
prop_elemIndicesL x xs =
elemIndicesL x xs == Data.List.elemIndices x (toList xs)
prop_elemIndexR :: A -> Seq A -> Bool
prop_elemIndexR x xs =
elemIndexR x xs == listToMaybe (Prelude.reverse (Data.List.elemIndices x (toList xs)))
prop_elemIndicesR :: A -> Seq A -> Bool
prop_elemIndicesR x xs =
elemIndicesR x xs == Prelude.reverse (Data.List.elemIndices x (toList xs))
prop_findIndexL :: Positive Int -> Seq Int -> Bool
prop_findIndexL (Positive n) xs =
findIndexL p xs == Data.List.findIndex p (toList xs)
where p x = x `mod` n == 0
prop_findIndicesL :: Positive Int -> Seq Int -> Bool
prop_findIndicesL (Positive n) xs =
findIndicesL p xs == Data.List.findIndices p (toList xs)
where p x = x `mod` n == 0
prop_findIndexR :: Positive Int -> Seq Int -> Bool
prop_findIndexR (Positive n) xs =
findIndexR p xs == listToMaybe (Prelude.reverse (Data.List.findIndices p (toList xs)))
where p x = x `mod` n == 0
prop_findIndicesR :: Positive Int -> Seq Int -> Bool
prop_findIndicesR (Positive n) xs =
findIndicesR p xs == Prelude.reverse (Data.List.findIndices p (toList xs))
where p x = x `mod` n == 0
-- * Folds
prop_foldlWithIndex :: [(Int, A)] -> Seq A -> Bool
prop_foldlWithIndex z xs =
foldlWithIndex f z xs == Data.List.foldl (uncurry . f) z (Data.List.zip [0..] (toList xs))
where f ys n y = (n,y):ys
prop_foldrWithIndex :: [(Int, A)] -> Seq A -> Bool
prop_foldrWithIndex z xs =
foldrWithIndex f z xs == Data.List.foldr (uncurry f) z (Data.List.zip [0..] (toList xs))
where f n y ys = (n,y):ys
-- * Transformations
prop_mapWithIndex :: Seq A -> Bool
prop_mapWithIndex xs =
toList' (mapWithIndex f xs) ~= map (uncurry f) (Data.List.zip [0..] (toList xs))
where f = (,)
prop_reverse :: Seq A -> Bool
prop_reverse xs =
toList' (reverse xs) ~= Prelude.reverse (toList xs)
-- ** Zips
prop_zip :: Seq A -> Seq B -> Bool
prop_zip xs ys =
toList' (zip xs ys) ~= Prelude.zip (toList xs) (toList ys)
prop_zipWith :: Seq A -> Seq B -> Bool
prop_zipWith xs ys =
toList' (zipWith f xs ys) ~= Prelude.zipWith f (toList xs) (toList ys)
where f = (,)
prop_zip3 :: Seq A -> Seq B -> Seq C -> Bool
prop_zip3 xs ys zs =
toList' (zip3 xs ys zs) ~= Prelude.zip3 (toList xs) (toList ys) (toList zs)
prop_zipWith3 :: Seq A -> Seq B -> Seq C -> Bool
prop_zipWith3 xs ys zs =
toList' (zipWith3 f xs ys zs) ~= Prelude.zipWith3 f (toList xs) (toList ys) (toList zs)
where f = (,,)
prop_zip4 :: Seq A -> Seq B -> Seq C -> Seq Int -> Bool
prop_zip4 xs ys zs ts =
toList' (zip4 xs ys zs ts) ~= Data.List.zip4 (toList xs) (toList ys) (toList zs) (toList ts)
prop_zipWith4 :: Seq A -> Seq B -> Seq C -> Seq Int -> Bool
prop_zipWith4 xs ys zs ts =
toList' (zipWith4 f xs ys zs ts) ~= Data.List.zipWith4 f (toList xs) (toList ys) (toList zs) (toList ts)
where f = (,,,)
-- Simple test monad
data M a = Action Int a
deriving (Eq, Show)
instance Functor M where
fmap f (Action n x) = Action n (f x)
instance Applicative M where
pure x = Action 0 x
Action m f <*> Action n x = Action (m+n) (f x)
instance Monad M where
return x = Action 0 x
Action m x >>= f = let Action n y = f x in Action (m+n) y
instance Foldable M where
foldMap f (Action _ x) = f x
instance Traversable M where
traverse f (Action n x) = Action n <$> f x
|
mightymoose/liquidhaskell
|
benchmarks/containers-0.5.0.0/tests/seq-properties.hs
|
bsd-3-clause
| 18,937
| 9
| 12
| 4,484
| 7,394
| 3,728
| 3,666
| 429
| 2
|
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, TemplateHaskell #-}
module OverloadedLabelsRun04_A where
import GHC.OverloadedLabels
import Language.Haskell.TH
instance IsLabel x (Q [Dec]) where
fromLabel = [d| main = putStrLn "Ok" |]
|
ezyang/ghc
|
testsuite/tests/overloadedrecflds/should_run/OverloadedLabelsRun04_A.hs
|
bsd-3-clause
| 246
| 0
| 8
| 31
| 44
| 28
| 16
| 6
| 0
|
{- |
- Module : CommonUtils
- Description : Common utilities
- Copyright : (c) Maciej Bendkowski
-
- Maintainer : maciej.bendkowski@gmail.com
- Stability : experimental
-}
module CommonUtils (
binom, catalan, leq, eq, geq
) where
-- | Computes the binominal(n, k)
binom :: Int -> Int -> Int
binom _ 0 = 1
binom 0 _ = 0
binom n k = let b = binom (n - 1) (k - 1)
in seq b n * b `div` k
-- | Computes the n-th Catalan number
catalan :: Int -> Int
catalan n = binom (2 * n) n `div` (n + 1)
-- | Returns whether the given list
-- has length less or equal to k.
-- Time: min(length [a], k)
leq :: [a] -> Int -> Bool
leq [] k = True
leq _ 0 = False
leq (x:xs) k = leq xs (k - 1)
-- | Returns whether the given list
-- has length equal to k. Time: min(length [a], k)
eq :: [a] -> Int -> Bool
eq [] 0 = True
eq [] k = False
eq (x:xs) k = eq xs (k - 1)
-- | Returns whether the given list
-- has length greater or equal to k.
-- Time: min(length [a], k)
geq :: [a] -> Int -> Bool
geq _ 0 = True
geq [] k = False
geq (x:xs) k = geq xs (k - 1)
|
maciej-bendkowski/blaz
|
src/CommonUtils.hs
|
mit
| 1,192
| 0
| 11
| 401
| 365
| 199
| 166
| 21
| 1
|
{-# LANGUAGE ForeignFunctionInterface #-}
-- Found at http://book.realworldhaskell.org/read/interfacing-with-c-the-ffi.html
--
-- The purpose of this module is to do some simple imports of
-- C functions into Haskell
module Math where
import Foreign
import Foreign.C.Types
foreign import ccall "math.h sin"
c_sin :: CDouble -> CDouble
fastsin :: Double -> Double
fastsin x = realToFrac (c_sin (realToFrac x))
|
iduhetonas/haskell-projects
|
ForeignFunctionInterface/Math.hs
|
mit
| 415
| 0
| 9
| 62
| 66
| 39
| 27
| 8
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification.html
module Stratosphere.ResourceProperties.EC2LaunchTemplateCapacityReservationSpecification where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.EC2LaunchTemplateCapacityReservationTarget
-- | Full data type definition for
-- EC2LaunchTemplateCapacityReservationSpecification. See
-- 'ec2LaunchTemplateCapacityReservationSpecification' for a more convenient
-- constructor.
data EC2LaunchTemplateCapacityReservationSpecification =
EC2LaunchTemplateCapacityReservationSpecification
{ _eC2LaunchTemplateCapacityReservationSpecificationCapacityReservationTarget :: Maybe EC2LaunchTemplateCapacityReservationTarget
} deriving (Show, Eq)
instance ToJSON EC2LaunchTemplateCapacityReservationSpecification where
toJSON EC2LaunchTemplateCapacityReservationSpecification{..} =
object $
catMaybes
[ fmap (("CapacityReservationTarget",) . toJSON) _eC2LaunchTemplateCapacityReservationSpecificationCapacityReservationTarget
]
-- | Constructor for 'EC2LaunchTemplateCapacityReservationSpecification'
-- containing required fields as arguments.
ec2LaunchTemplateCapacityReservationSpecification
:: EC2LaunchTemplateCapacityReservationSpecification
ec2LaunchTemplateCapacityReservationSpecification =
EC2LaunchTemplateCapacityReservationSpecification
{ _eC2LaunchTemplateCapacityReservationSpecificationCapacityReservationTarget = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification.html#cfn-ec2-launchtemplate-launchtemplatedata-capacityreservationspecification-capacityreservationtarget
ecltcrsCapacityReservationTarget :: Lens' EC2LaunchTemplateCapacityReservationSpecification (Maybe EC2LaunchTemplateCapacityReservationTarget)
ecltcrsCapacityReservationTarget = lens _eC2LaunchTemplateCapacityReservationSpecificationCapacityReservationTarget (\s a -> s { _eC2LaunchTemplateCapacityReservationSpecificationCapacityReservationTarget = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/ResourceProperties/EC2LaunchTemplateCapacityReservationSpecification.hs
|
mit
| 2,290
| 0
| 12
| 158
| 169
| 100
| 69
| 23
| 1
|
module State (
Token(..),
State(..),
TransitionFunction(..),
Transition(..),
TransitionMap
) where
import Data.Map (Map)
data Token = Epsilon | Token Char deriving (Eq, Ord, Show)
data State = State {labelOf :: String} deriving (Eq, Ord, Show)
type TransitionFunction = State -> Token -> State
type Transition = (State, Token, State)
type TransitionMap = Map State (Map Token State)
|
wyager/NDFSMtoFSM
|
State.hs
|
mit
| 393
| 10
| 8
| 67
| 162
| 97
| 65
| 12
| 0
|
{-# LANGUAGE Unsafe #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Protolude.Unsafe (
unsafeHead,
unsafeTail,
unsafeInit,
unsafeLast,
unsafeFromJust,
unsafeIndex,
unsafeThrow,
unsafeRead,
) where
import Protolude.Base (Int)
import Data.Char (Char)
import Text.Read (Read, read)
import qualified Data.List as List
import qualified Data.Maybe as Maybe
import qualified Control.Exception as Exc
unsafeHead :: [a] -> a
unsafeHead = List.head
unsafeTail :: [a] -> [a]
unsafeTail = List.tail
unsafeInit :: [a] -> [a]
unsafeInit = List.init
unsafeLast :: [a] -> a
unsafeLast = List.last
unsafeFromJust :: Maybe.Maybe a -> a
unsafeFromJust = Maybe.fromJust
unsafeIndex :: [a] -> Int -> a
unsafeIndex = (List.!!)
unsafeThrow :: Exc.Exception e => e -> a
unsafeThrow = Exc.throw
unsafeRead :: Read a => [Char] -> a
unsafeRead = Text.Read.read
|
sdiehl/protolude
|
src/Protolude/Unsafe.hs
|
mit
| 858
| 0
| 7
| 145
| 272
| 164
| 108
| 33
| 1
|
module TemplateGen.UrlString (
UrlString
) where
type UrlString = String
|
seahug/seattlehaskell-org-static
|
src/lib/TemplateGen/UrlString.hs
|
mit
| 77
| 0
| 4
| 14
| 17
| 11
| 6
| 3
| 0
|
{- |
Module : $Header$
Description : Tree-based implementation of 'Graph' and 'DynGraph'
using Data.Map
Copyright : (c) Martin Erwig, Christian Maeder and Uni Bremen 1999-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Christian.Maeder@dfki.de
Stability : provisional
Portability : portable
Tree-based implementation of 'Graph' and 'DynGraph' using Data.IntMap
instead of Data.Graph.Inductive.Internal.FiniteMap
-}
module Common.Lib.Graph
( Gr (..)
, GrContext (..)
, unsafeConstructGr
, decomposeGr
, getPaths
, getAllPathsTo
, getPathsTo
, getLEdges
, Common.Lib.Graph.delLEdge
, insLEdge
, delLNode
, labelNode
, getNewNode
, rmIsolated
) where
import Data.Graph.Inductive.Graph as Graph
import qualified Data.IntMap as Map
import Data.List
-- | the graph type constructor
newtype Gr a b = Gr { convertToMap :: Map.IntMap (GrContext a b) }
data GrContext a b = GrContext
{ nodeLabel :: a
, nodeSuccs :: Map.IntMap [b]
, loops :: [b]
, nodePreds :: Map.IntMap [b] }
unsafeConstructGr :: Map.IntMap (GrContext a b) -> Gr a b
unsafeConstructGr = Gr
instance (Show a, Show b) => Show (Gr a b) where
show (Gr g) = showGraph g
instance Graph Gr where
empty = Gr Map.empty
isEmpty (Gr g) = Map.null g
match = matchGr
mkGraph vs es = (insEdges es . insNodes vs) empty
labNodes = map (\ (v, c) -> (v, nodeLabel c)) . Map.toList . convertToMap
-- more efficient versions of derived class members
matchAny g = case Map.keys $ convertToMap g of
[] -> error "Match Exception, Empty Graph"
h : _ -> let (Just c, g') = matchGr h g in (c, g')
noNodes (Gr g) = Map.size g
nodeRange (Gr g) = case Map.keys g of
[] -> (0, -1)
ks@(h : _) -> (h, last ks)
labEdges =
concatMap (\ (v, cw) -> map (\ (l, w) -> (v, w, l))
$ mkLoops v (loops cw) ++ mkAdj (nodeSuccs cw))
. Map.toList . convertToMap
instance DynGraph Gr where
(p, v, l, s) & gr = let
mkMap = foldr (\ (e, w) -> Map.insertWith (++) w [e]) Map.empty
pm = mkMap p
sm = mkMap s
in composeGr v GrContext
{ nodeLabel = l
, nodeSuccs = Map.delete v sm
, loops = Map.findWithDefault [] v pm ++ Map.findWithDefault [] v sm
, nodePreds = Map.delete v pm } gr
showGraph :: (Show a, Show b) => Map.IntMap (GrContext a b) -> String
showGraph = unlines . map
(\ (v, c) ->
shows v ": " ++ show (nodeLabel c)
++ showLinks
((case loops c of
[] -> []
l -> [(v, l)]) ++ Map.toList (nodeSuccs c)))
. Map.toList
showLinks :: Show b => [(Node, [b])] -> String
showLinks = concatMap $ \ (v, l) -> " - " ++
intercalate ", " (map show l) ++ " -> " ++ shows v ";"
mkLoops :: Node -> [b] -> Adj b
mkLoops v = map (\ e -> (e, v))
mkAdj :: Map.IntMap [b] -> Adj b
mkAdj = concatMap (\ (w, l) -> map (\ e -> (e, w)) l) . Map.toList
{- here cyclic edges are omitted as predecessors, thus they only count
as outgoing and not as ingoing! Therefore it is enough that only
successors are filtered during deletions. -}
matchGr :: Node -> Gr a b -> Decomp Gr a b
matchGr v gr = case decomposeGr v gr of
Nothing -> (Nothing, gr)
Just (c, rg) -> (Just ( mkAdj $ nodePreds c , v , nodeLabel c
, mkLoops v (loops c) ++ mkAdj (nodeSuccs c)), rg)
decomposeGr :: Node -> Gr a b -> Maybe (GrContext a b, Gr a b)
decomposeGr v (Gr g) = case Map.lookup v g of
Nothing -> Nothing
Just c -> let
g1 = Map.delete v g
g2 = updAdj g1 (nodeSuccs c) $ clearPred v
g3 = updAdj g2 (nodePreds c) $ clearSucc v
in Just (c, Gr g3)
addSuccs :: Node -> [b] -> GrContext a b -> GrContext a b
addSuccs v ls c = c { nodeSuccs = Map.insert v ls $ nodeSuccs c }
addPreds :: Node -> [b] -> GrContext a b -> GrContext a b
addPreds v ls c = c { nodePreds = Map.insert v ls $ nodePreds c }
clearSucc :: Node -> [b] -> GrContext a b -> GrContext a b
clearSucc v _ c = c { nodeSuccs = Map.delete v $ nodeSuccs c }
clearPred :: Node -> [b] -> GrContext a b -> GrContext a b
clearPred v _ c = c { nodePreds = Map.delete v $ nodePreds c }
updAdj :: Map.IntMap (GrContext a b) -> Map.IntMap [b]
-> ([b] -> GrContext a b -> GrContext a b)
-> Map.IntMap (GrContext a b)
updAdj g m f = Map.foldWithKey (\ v -> updGrContext v . f) g m
updGrContext :: Node -> (GrContext a b -> GrContext a b)
-> Map.IntMap (GrContext a b) -> Map.IntMap (GrContext a b)
updGrContext v f r = case Map.lookup v r of
Nothing -> error $ "Common.Lib.Graph.updGrContext no node: " ++ show v
Just c -> Map.insert v (f c) r
composeGr :: Node -> GrContext a b -> Gr a b -> Gr a b
composeGr v c (Gr g) = let
g1 = updAdj g (nodePreds c) $ addSuccs v
g2 = updAdj g1 (nodeSuccs c) $ addPreds v
g3 = Map.insert v c g2
in if Map.member v g
then error $ "Common.Lib.Graph.composeGr no node: " ++ show v
else Gr g3
-- | compute the possible cycle free paths from a start node
getPaths :: Node -> Gr a b -> [[LEdge b]]
getPaths src gr = case decomposeGr src gr of
Just (c, ng) ->
Map.foldWithKey (\ nxt lbls l ->
l ++ map (\ b -> [(src, nxt, b)]) lbls
++ concatMap (\ p -> map (\ b -> (src, nxt, b) : p) lbls)
(getPaths nxt ng)) [] $ nodeSuccs c
Nothing -> error $ "Common.Lib.Graph.getPaths no node: " ++ show src
-- | compute the possible cycle free reversed paths from a start node
getAllPathsTo :: Node -> Gr a b -> [[LEdge b]]
getAllPathsTo tgt gr = case decomposeGr tgt gr of
Just (c, ng) ->
Map.foldWithKey (\ nxt lbls l ->
l ++ map (\ b -> [(nxt, tgt, b)]) lbls
++ concatMap (\ p -> map (\ b -> (nxt, tgt, b) : p) lbls)
(getAllPathsTo nxt ng)) [] $ nodePreds c
Nothing -> error $ "Common.Lib.Graph.getAllPathsTo no node: " ++ show tgt
-- | compute the possible cycle free paths from a start node to a target node.
getPathsTo :: Node -> Node -> Gr a b -> [[LEdge b]]
getPathsTo src tgt gr = case decomposeGr src gr of
Just (c, ng) -> let
s = nodeSuccs c
in Map.foldWithKey (\ nxt lbls ->
(++ concatMap (\ p -> map (\ b -> (src, nxt, b) : p) lbls)
(getPathsTo nxt tgt ng)))
(map (\ lbl -> [(src, tgt, lbl)]) $ Map.findWithDefault [] tgt s)
(Map.delete tgt s)
Nothing -> error $ "Common.Lib.Graph.getPathsTo no node: " ++ show src
-- | get all the edge labels between two nodes
getLEdges :: Node -> Node -> Gr a b -> [b]
getLEdges v w (Gr m) = let err = "Common.Lib.Graph.getLEdges: no node " in
case Map.lookup v m of
Just c -> if v == w then loops c else
Map.findWithDefault
(if Map.member w m then [] else error $ err ++ show w)
w $ nodeSuccs c
Nothing -> error $ err ++ show v
showEdge :: Node -> Node -> String
showEdge v w = show v ++ " -> " ++ show w
-- | delete a labeled edge from a graph
delLEdge :: (b -> b -> Ordering) -> LEdge b -> Gr a b -> Gr a b
delLEdge cmp (v, w, l) (Gr m) =
let e = showEdge v w
err = "Common.Lib.Graph.delLEdge "
in case Map.lookup v m of
Just c -> let
sm = nodeSuccs c
b = v == w
ls = if b then loops c else Map.findWithDefault [] w sm
in case partition (\ k -> cmp k l == EQ) ls of
([], _) -> error $ err ++ "no edge: " ++ e
([_], rs) -> Gr $ if b then Map.insert v c { loops = rs } m else
updGrContext w
((if null rs then clearPred else addPreds) v rs)
$ Map.insert v c
{ nodeSuccs = if null rs then Map.delete w sm else
Map.insert w rs sm } m
_ -> error $ err ++ "multiple edges: " ++ e
Nothing -> error $ err ++ "no node: " ++ show v ++ " for edge: " ++ e
-- | insert a labeled edge into a graph, returns False if edge exists
insLEdge :: Bool -> (b -> b -> Ordering) -> LEdge b -> Gr a b
-> (Gr a b, Bool)
insLEdge failIfExist cmp (v, w, l) gr@(Gr m) =
let e = showEdge v w
err = "Common.Lib.Graph.insLEdge "
in case Map.lookup v m of
Just c -> let
sm = nodeSuccs c
b = v == w
ls = if b then loops c else Map.findWithDefault [] w sm
ns = insertBy cmp l ls
in if any (\ k -> cmp k l == EQ) ls then
if failIfExist then error $ err ++ "multiple edges: " ++ e
else (gr, False)
else (Gr $ if b then Map.insert v c { loops = ns } m else
updGrContext w (addPreds v ns)
$ Map.insert v c { nodeSuccs = Map.insert w ns sm } m, True)
Nothing -> error $ err ++ "no node: " ++ show v ++ " for edge: " ++ e
isIsolated :: GrContext a b -> Bool
isIsolated c = Map.null (nodeSuccs c) && Map.null (nodePreds c)
-- | delete a labeled node
delLNode :: (a -> a -> Bool) -> LNode a -> Gr a b -> Gr a b
delLNode eq (v, l) (Gr m) =
let err = "Common.Lib.Graph.delLNode: node " ++ show v in
case Map.lookup v m of
Just c -> if isIsolated c && null (loops c) then
if eq l $ nodeLabel c then Gr (Map.delete v m)
else error $ err ++ " has a different label"
else error $ err ++ " has remaining edges"
Nothing -> error $ err ++ " is missing"
-- | sets the node with new label and returns the new graph and the old label
labelNode :: LNode a -> Gr a b -> (Gr a b, a)
labelNode (v, l) (Gr m) = case Map.lookup v m of
Just c -> (Gr $ Map.insert v (c { nodeLabel = l }) m, nodeLabel c)
Nothing -> error $ "Common.Lib.Graph.labelNode no node: " ++ show v
-- | returns one new node id for the given graph
getNewNode :: Gr a b -> Node
getNewNode g = case newNodes 1 g of
[n] -> n
_ -> error "Common.Lib.Graph.getNewNode"
-- | remove isolated nodes without edges
rmIsolated :: Gr a b -> Gr a b
rmIsolated (Gr m) = Gr $ Map.filter (not . isIsolated) m
|
nevrenato/HetsAlloy
|
Common/Lib/Graph.hs
|
gpl-2.0
| 9,849
| 0
| 23
| 2,812
| 3,995
| 2,062
| 1,933
| 203
| 8
|
{-
This file is part of the Haskell Qlogic Library.
The Haskell Qlogic Library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Haskell Qlogic Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the Haskell Qlogic Library. If not, see <http://www.gnu.org/licenses/>.
-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Qlogic.Formula
(-- * Types
Formula(..)
-- * operations
, literal
, isLiteral
, isClause
, isNegClause
, isCnf
, isNegCnf
, size
, simplify
, atoms
-- ** utility functions
, pprintFormula
)
where
import Prelude hiding ((&&),(||),not,foldl,foldr)
import Data.Foldable hiding (all)
import Data.Set (Set)
import Data.Typeable
import Qlogic.Boolean
import Qlogic.Utils
import Text.PrettyPrint.HughesPJ
import qualified Data.Maybe as Maybe
import qualified Data.Set as Set
import qualified Prelude as Prelude
data Formula l a = A a
| SL l
| And [Formula l a]
| Or [Formula l a]
| Iff (Formula l a) (Formula l a)
| Ite (Formula l a) (Formula l a) (Formula l a)
| Imp (Formula l a) (Formula l a)
| Maj (Formula l a) (Formula l a) (Formula l a)
| Odd (Formula l a) (Formula l a) (Formula l a)
| Neg (Formula l a)
| Top
| Bot deriving (Eq, Ord, Typeable, Show)
instance (Eq a, Eq l) => Boolean (Formula l a) where
Top && b = b
Bot && _ = Bot
a && Top = a
_ && Bot = Bot
(And l1) && (And l2) = And $ l1 ++ l2
(And l1) && b = And $ l1 ++ [b]
a && (And l2) = And $ a:l2
a && (Neg b) | a == b = Bot
a && b | a == b = a
a && b | otherwise = And [a,b]
Top || _ = Top
Bot || b = b
_ || Top = Top
a || Bot = a
(Or l1) || (Or l2) = Or $ l1 ++ l2
(Or l1) || b = Or $ l1 ++ [b]
a || (Neg b) | a == b = Top
a || b | a == b = a
a || b | otherwise = Or [a,b]
not Bot = Top
not Top = Bot
not (Neg a) = a
not a = Neg a
top = Top
bot = Bot
Top <-> b = b
Bot <-> b = not b
a <-> Top = a
a <-> Bot = not a
a <-> (Neg b) | a == b = Bot
a <-> b | a == b = Top
a <-> b | otherwise = a `Iff` b
Top --> b = b
Bot --> _ = Top
_ --> Top = Top
a --> Bot = not a
a --> (Neg b) | a == b = Bot
a --> b | a == b = Top
a --> b | otherwise = a `Imp` b
ite Top t _ = t
ite Bot _ e = e
ite g Bot e = not g && e
ite g t Bot = g && t
ite g t e = Ite g t e
maj Top b c = b || c
maj Bot b c = b && c
maj a Top c = a || c
maj a Bot c = a && c
maj a b Top = a || b
maj a b Bot = a && b
maj a b c | a == b = a
maj a b c | a == c = a
maj a b c | b == c = b
maj a b c | otherwise = Maj a b c
odd3 Top b c = b <-> c
odd3 Bot b c = not $ b <-> c
odd3 a Top c = a <-> c
odd3 a Bot c = not $ a <-> c
odd3 a b Top = a <-> b
odd3 a b Bot = not $ a <-> b
odd3 a b c | a == b = a <-> c
odd3 a b c | a == c = a <-> b
odd3 a b c | b == c = a <-> b
odd3 a b c | otherwise = Odd a b c
-- instance (Eq a, Eq l) => NGBoolean (Formula l a) a where
-- atom = A
literal :: l -> Formula l a
literal = SL
isLiteral :: Formula l a -> Bool
isLiteral (A _) = True
isLiteral (SL _) = True
isLiteral (And []) = True
isLiteral (And [a]) = isLiteral a
isLiteral (And _) = False
isLiteral (Or []) = True
isLiteral (Or [a]) = isLiteral a
isLiteral (Or _) = False
isLiteral (_ `Iff` _) = False
isLiteral (Ite _ _ _) = False
isLiteral (_ `Imp` _) = False
isLiteral (Maj _ _ _) = False
isLiteral (Odd _ _ _) = False
isLiteral (Neg a) = isLiteral a
isLiteral Top = True
isLiteral Bot = True
isClause :: Formula l a -> Bool
isClause (A _) = True
isClause (SL _) = True
isClause (And []) = True
isClause (And [a]) = isClause a
isClause (And _) = False
isClause (Or as) = all isClause as
isClause (a `Iff` b) = False
isClause (Ite _ _ _) = False
isClause (a `Imp` b) = isNegClause a && isClause b
isClause (Maj _ _ _) = False
isClause (Odd _ _ _) = False
isClause (Neg a) = isNegClause a
isClause Top = True
isClause Bot = True
isNegClause :: Formula l a -> Bool
isNegClause (A _) = True
isNegClause (SL _) = True
isNegClause (And as) = all isNegClause as
isNegClause (Or []) = True
isNegClause (Or [a]) = isNegClause a
isNegClause (Or as) = False
isNegClause (a `Iff` b) = False
isNegClause (Ite _ _ _) = False
isNegClause (a `Imp` b) = False
isNegClause (Maj _ _ _) = False
isNegClause (Odd _ _ _) = False
isNegClause (Neg a) = isClause a
isNegClause Top = True
isNegClause Bot = True
isCnf :: Formula l a -> Bool
isCnf (A _) = True
isCnf (SL _) = True
isCnf (And as) = all isCnf as
isCnf (Or []) = True
isCnf (Or [a]) = isCnf a
isCnf fm@(Or _) = isClause fm
isCnf (a `Iff` b) = isLiteral a && isLiteral b
isCnf (Ite g t e) = isLiteral g && isClause t && isClause e
isCnf (a `Imp` b) = isNegClause a && isClause b
isCnf (Maj a b c) = isClause a && isClause b && isClause c
isCnf (Odd a b c) = isLiteral a && isLiteral b && isLiteral c
isCnf (Neg a) = isNegCnf a
isCnf Top = True
isCnf Bot = True
isNegCnf :: Formula l a -> Bool
isNegCnf (A _) = True
isNegCnf (SL _) = True
isNegCnf (And []) = True
isNegCnf (And [a]) = isNegCnf a
isNegCnf fm@(And _) = isNegClause fm
isNegCnf (Or as) = all isNegCnf as
isNegCnf (a `Iff` b) = isLiteral a && isLiteral b
isNegCnf (Ite g t e) = isLiteral g && isNegClause t && isNegClause e
isNegCnf (a `Imp` b) = isCnf a && isNegCnf b
isNegCnf (Maj a b c) = isNegClause a && isNegClause b && isNegClause c
isNegCnf (Odd a b c) = isLiteral a && isLiteral b && isLiteral c
isNegCnf (Neg a) = isCnf a
isNegCnf Top = True
isNegCnf Bot = True
atoms :: (Ord a, Ord l) => Formula l a -> Set (Either l a)
atoms (A a) = Set.singleton (Right a)
atoms (SL a) = Set.singleton (Left a)
atoms (And l) = Set.unions [atoms e | e <- l]
atoms (Or l) = Set.unions [atoms e | e <- l]
atoms (a `Iff` b) = atoms a `Set.union` atoms b
atoms (Ite a b c) = Set.unions [atoms a, atoms b, atoms c]
atoms (a `Imp` b) = atoms a `Set.union`atoms b
atoms (Maj a b c) = atoms a `Set.union` atoms b `Set.union` atoms c
atoms (Odd a b c) = atoms a `Set.union` atoms b `Set.union` atoms c
atoms (Neg a) = atoms a
atoms Top = Set.empty
atoms Bot = Set.empty
simplify :: (Eq l, Eq a) => Formula l a -> Formula l a
-- ^ performs basic simplification of formulas
simplify (And l) = bigAnd [simplify e | e <- l]
simplify (Or l) = bigAnd [simplify e | e <- l]
simplify (a `Iff` b) = simplify a <-> simplify b
simplify (Ite g t e) = ite (simplify g) (simplify t) (simplify e)
simplify (a `Imp` b) = simplify a --> simplify b
simplify (Maj a b c) = maj (simplify a) (simplify b) (simplify c)
simplify (Odd a b c) = odd3 (simplify a) (simplify b) (simplify c)
simplify (Neg a) = not $ simplify a
simplify a = a
size :: Formula l a -> Int
size (A a) = 1
size (SL a) = 1
size (And xs) = 1 + Prelude.sum (map size xs)
size (Or xs) = 1 + Prelude.sum (map size xs)
size (Iff a b) = size a + size b + 1
size (Ite a b c) = size a + size b + size c + 1
size (Imp a b) = size a + size b + 1
size (Maj a b c) = size a + size b + size c + 1
size (Odd a b c) = size a + size b + size c + 1
size (Neg a) = size a + 1
size Top = 1
size Bot = 1
pprintBinFm :: (Show a, Show l) => String -> Formula l a -> Formula l a -> Doc
pprintBinFm s a b = parens $ text s <+> (pprintFormula a $$ pprintFormula b)
pprintFormula :: (Show a, Show l) => Formula l a -> Doc
pprintFormula (A a) = text $ show a
pprintFormula (SL a) = text $ show a
pprintFormula (And l) = parens $ text "/\\" <+> sep (punctuate (text " ") $ map pprintFormula l)
pprintFormula (Or l) = parens $ text "\\/" <+> sep (punctuate (text " ") $ map pprintFormula l)
pprintFormula (Iff a b) = pprintBinFm "<->" a b
pprintFormula (Imp a b) = pprintBinFm "-->" a b
pprintFormula (Ite a b c) = parens $ text "ite" <+> (pprintFormula a $$ pprintFormula b $$ pprintFormula c)
pprintFormula (Maj a b c) = parens $ text "maj" <+> (pprintFormula a $$ pprintFormula b $$ pprintFormula c)
pprintFormula (Odd a b c) = parens $ text "odd" <+> (pprintFormula a $$ pprintFormula b $$ pprintFormula c)
pprintFormula (Neg a) = parens $ text "-" <+> (pprintFormula a)
pprintFormula Top = text "T"
pprintFormula Bot = text "F"
|
mzini/qlogic
|
Qlogic/Formula.hs
|
gpl-3.0
| 9,593
| 0
| 11
| 3,181
| 4,420
| 2,188
| 2,232
| 233
| 1
|
{-# LANGUAGE RankNTypes, ScopedTypeVariables, TemplateHaskell #-}
-- | Timeline reporting output. Prouces a svg with columns.
module OrgStat.Outputs.Timeline
( processTimeline
) where
import Data.Colour.CIE (luminance)
import Data.List (lookup, nub)
import qualified Data.List as L
import qualified Data.Text as T
import Data.Time (Day, DiffTime, LocalTime(..), defaultTimeLocale, formatTime, timeOfDayToTime)
import Diagrams.Backend.SVG (B)
import qualified Diagrams.Prelude as D
import qualified Prelude
import Text.Printf (printf)
import Universum
import OrgStat.Ast (Clock(..), Org(..), orgClocks, traverseTree)
import OrgStat.Outputs.Types
(TimelineOutput(..), TimelineParams, tpBackground, tpColorSalt, tpColumnHeight, tpColumnWidth,
tpLegend, tpTopDay)
import OrgStat.Util (addLocalTime, hashColour)
----------------------------------------------------------------------------
-- Processing clocks
----------------------------------------------------------------------------
-- [(a, [b])] -> [(a, b)]
allClocks :: [(Text, [(DiffTime, DiffTime)])] -> [(Text, (DiffTime, DiffTime))]
allClocks tasks = do
(label, clocks) <- tasks
clock <- clocks
pure (label, clock)
-- separate list for each day
selectDays :: [Day] -> [(Text, [Clock])] -> [[(Text, [(DiffTime, DiffTime)])]]
selectDays days tasks =
flip map days $ \day ->
filter (not . null . snd) $
map (second (selectDay day)) tasks
where
selectDay :: Day -> [Clock] -> [(DiffTime, DiffTime)]
selectDay day clocks = do
Clock (LocalTime dFrom tFrom) (LocalTime dTo tTo) <- clocks
guard $ any (== day) [dFrom, dTo]
let tFrom' = if dFrom == day then timeOfDayToTime tFrom else fromInteger 0
let tTo' = if dTo == day then timeOfDayToTime tTo else fromInteger (24*60*60)
pure (tFrom', tTo')
-- total time for each task
totalTimes :: [(Text, [(DiffTime, DiffTime)])] -> [(Text, DiffTime)]
totalTimes tasks = map (second clocksSum) tasks
where
clocksSum :: [(DiffTime, DiffTime)] -> DiffTime
clocksSum clocks = sum $ map (\(start, end) -> end - start) clocks
-- list of leaves
orgToList :: Org -> [(Text, [Clock])]
orgToList = orgToList' ""
where
orgToList' :: Text -> Org -> [(Text, [Clock])]
orgToList' _pr org =
--let path = pr <> "/" <> _orgTitle org
let path = _orgTitle org
in (path, _orgClocks org) : concatMap (orgToList' path) (_orgSubtrees org)
----------------------------------------------------------------------------
-- Drawing
----------------------------------------------------------------------------
diffTimeSeconds :: DiffTime -> Integer
diffTimeSeconds time = floor $ toRational time
diffTimeMinutes :: DiffTime -> Integer
diffTimeMinutes time = diffTimeSeconds time `div` 60
-- diffTimeHours :: DiffTime -> Integer
-- diffTimeHours time = diffTimeMinutes time `div` 60
labelColour :: TimelineParams -> Text -> D.Colour Double
labelColour params _label = hashColour (params ^. tpColorSalt) _label
-- | Returns if the label is to be shown. Second param is font-related
-- heuristic constant, third is length of interval.
fitLabelHeight :: TimelineParams -> Double -> Double -> Bool
fitLabelHeight params n h = h >= (params ^. tpColumnHeight) * n
-- | Decides by <heuristic param n depending on font>, width of column
-- and string, should it be truncated. And returns modified string.
fitLabelWidth :: TimelineParams -> Double -> Text -> Text
fitLabelWidth params n s =
if T.length s <= toTake then s else T.take toTake s <> ".."
where
toTake = floor $ n * ((params ^. tpColumnWidth) ** 1.2)
-- rectangle with origin in the top-left corner
topLeftRect :: Double -> Double -> D.Diagram B
topLeftRect w h =
D.rect w h
& D.moveOriginTo (D.p2 (-w/2, h/2))
-- timeline for a single day
timelineDay :: TimelineParams -> Day -> [(Text, (DiffTime, DiffTime))] -> D.Diagram B
timelineDay params day clocks =
mconcat
[ timeticks
, dateLabel
, mconcat (map showClock clocks)
, clocksBackground
]
where
width = 140 * (params ^. tpColumnWidth)
ticksWidth = 20
height = 700 * (params ^. tpColumnHeight)
timeticks :: D.Diagram B
timeticks =
mconcat $
flip map [(0::Int)..23] $ \hour ->
mconcat
[ D.alignedText 0.5 1 (show hour)
& D.font "DejaVu Sans"
& D.fontSize 8
& D.moveTo (D.p2 (ticksWidth/2, -5))
& D.fc (D.sRGB24 150 150 150)
, D.strokeT (D.p2 (0,0) D.~~ (D.p2 (ticksWidth, 0)))
& D.translateY (-0.5)
& D.lwO 1
& D.lc (D.sRGB24 200 200 200)
]
& D.moveTo (D.p2 (0, negate $ fromInteger . round $ height * (fromIntegral hour / 24)))
& D.moveOriginTo (D.p2 (ticksWidth, 0))
dateLabel :: D.Diagram B
dateLabel =
mconcat
[ D.strutY 20
, D.alignedText 0.5 0 (formatTime defaultTimeLocale "%a, %d.%m.%Y" day)
& D.font "DejaVu Sans"
& D.fontSize 12
& D.moveOriginTo (D.p2 (-width/2, 0))
]
clocksBackground :: D.Diagram B
clocksBackground =
topLeftRect width height
& D.lw D.none
& D.fc (params ^. tpBackground)
contrastFrom c = if luminance c < 0.14 then D.sRGB24 224 224 224 else D.black
showClock :: (Text, (DiffTime, DiffTime)) -> D.Diagram B
showClock (label, (start, end)) =
let
w = width
h = (* height) $ fromInteger (diffTimeMinutes $ end - start) / (24*60)
y = (* height) $ fromInteger (diffTimeMinutes start) / (24*60)
bgboxColour = labelColour params label
bgbox = topLeftRect w h
& D.lw D.none
& D.fc bgboxColour
label' = D.alignedText 0 0.5 (T.unpack $ fitLabelWidth params 21 label)
& D.font "DejaVu Sans"
& D.fontSize 10
& D.fc (contrastFrom bgboxColour)
& D.moveTo (D.p2 (5, -h/2))
box = mconcat $ bool [] [label'] (fitLabelHeight params 12 h) ++ [bgbox]
in box & D.moveTo (D.p2 (0, -y))
-- timelines for several days, with top lists
timelineDays
:: TimelineParams
-> [Day]
-> [[(Text, (DiffTime, DiffTime))]]
-> [[(Text, DiffTime)]]
-> D.Diagram B
timelineDays params days clocks topLists =
(D.strutY 10 D.===) $
D.hcat $
flip map (days `zip` (clocks `zip` topLists)) $ \(day, (dayClocks, topList)) ->
D.vsep 5
[ timelineDay params day dayClocks
, taskList params topList True
]
-- task list, with durations and colours
taskList :: TimelineParams -> [(Text, DiffTime)] -> Bool -> D.Diagram B
taskList params labels fit = D.vsep 5 $ map oneTask $ reverse $ sortOn snd labels
where
oneTask :: (Text, DiffTime) -> D.Diagram B
oneTask (label, time) =
D.hsep 3
[ D.alignedText 1 0.5 (showTime time)
& D.font "DejaVu Sans"
& D.fontSize 10
& D.translateX 20
, D.rect 12 12
& D.fc (labelColour params label)
& D.lw D.none
, D.alignedText 0 0.5 (T.unpack $ bool label (fitLabelWidth params 18 label) fit)
& D.font "DejaVu Sans"
& D.fontSize 10
]
showTime :: DiffTime -> Prelude.String
showTime time = printf "%d:%02d" hours minutes
where
(hours, minutes) = diffTimeMinutes time `divMod` 60
emptyReport :: D.Diagram B
emptyReport =
mconcat
[ D.strutY 20
, D.strutX 40
, D.alignedText 0.5 0 "empty"
& D.font "DejaVu Sans"
& D.fontSize 8
]
timelineReport :: TimelineParams -> Org -> TimelineOutput
timelineReport params org =
if (null $ concat $ org ^.. traverseTree . orgClocks)
then
TimelineOutput $ D.vsep 30 [emptyReport]
else TimelineOutput pic
where
lookupDef :: Eq a => b -> a -> [(a, b)] -> b
lookupDef d a xs = fromMaybe d $ lookup a xs
-- These two should be taken from the Org itself (min/max).
(from,to) =
let c = concat $ org ^.. traverseTree . orgClocks
in (L.minimum (map cFrom c), L.maximum (map cTo c))
-- period to show. Right border is -1min, we assume it's non-inclusive
daysToShow = [localDay from ..
localDay ((negate 120 :: Int) `addLocalTime` to)]
-- unfiltered leaves
tasks :: [(Text, [Clock])]
tasks = orgToList org
-- tasks from the given period, split by days
byDay :: [[(Text, [(DiffTime, DiffTime)])]]
byDay = selectDays daysToShow tasks
-- total durations for each task, split by days
byDayDurations :: [[(Text, DiffTime)]]
byDayDurations = map totalTimes byDay
-- total durations for the whole period
allDaysDurations :: [(Text, DiffTime)]
allDaysDurations =
let allTasks = nub $ map fst $ concat byDayDurations in
flip map allTasks $ \task ->
(task,) $ sum $ flip map byDayDurations $ \durations ->
lookupDef (fromInteger 0) task durations
-- split clocks
clocks :: [[(Text, (DiffTime, DiffTime))]]
clocks = map allClocks byDay
-- top list for each day
topLists :: [[(Text, DiffTime)]]
topLists =
map (take (params ^. tpTopDay) . reverse . sortOn (\(_task, time) -> time))
byDayDurations
optLegend | params ^. tpLegend = [taskList params allDaysDurations False]
| otherwise = []
pic =
D.vsep 30 $ [ timelineDays params daysToShow clocks topLists ] ++ optLegend
processTimeline :: TimelineParams -> Org -> TimelineOutput
processTimeline params org = timelineReport params org
|
volhovM/orgstat
|
src/OrgStat/Outputs/Timeline.hs
|
gpl-3.0
| 9,525
| 0
| 21
| 2,347
| 3,123
| 1,684
| 1,439
| -1
| -1
|
module Geometry
( sphereVolume
, sphereArea
, cubeVolume
, cubeArea
, cuboidArea
, cuboidVolume
) where
sphereVolume :: Float -> Float
sphereVolume radius = (4.0 * pi * radius^3)/3
sphereArea :: Float -> Float
sphereArea radius = 4 * pi * (radius^2)
cubeVolume :: Float -> Float
cubeVolume length = length^3
cubeArea :: Float -> Float
cubeArea length = 6*length^2
cuboidArea :: Float -> Float -> Float -> Float
cuboidArea a b c = rectArea a b * 2 + rectArea a c * 2 + rectArea c b * 2
cuboidVolume :: Float -> Float -> Float -> Float
cuboidVolume a b c = rectArea a b * c
rectArea :: Float -> Float -> Float
rectArea a b = a * b
|
medik/lang-hack
|
Haskell/LearnYouAHaskell/c06/Geometry.hs
|
gpl-3.0
| 650
| 0
| 10
| 145
| 267
| 140
| 127
| 21
| 1
|
{-# LANGUAGE TemplateHaskell, FlexibleInstances#-}
module Wav where
import Test.QuickCheck
import Data.Binary( Binary(..), encode )
import Sound.Wav
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString as B
import Data.DeriveTH
import DeriveArbitrary
import ByteString
import Vector
--instance Arbitrary AudioFormat where
-- arbitrary = oneof $ (map return [MicrosoftPCM])
$(devArbitrary ''WaveFile)
type MWaveFile = WaveFile
mencode :: MWaveFile -> L.ByteString
mencode = encode
|
fcostantini/QuickFuzz
|
src/Wav.hs
|
gpl-3.0
| 516
| 0
| 8
| 73
| 99
| 63
| 36
| 15
| 1
|
{-# LANGUAGE RankNTypes, FlexibleContexts #-}
module Carnap.GHCJS.Action.TruthTable (truthTableAction) where
import Lib
import Carnap.GHCJS.SharedTypes
import Carnap.Core.Data.Types
import Carnap.Core.Data.Classes (Schematizable, Modelable(..))
import Carnap.Calculi.NaturalDeduction.Syntax (NaturalDeductionCalc(..))
import Carnap.Languages.PurePropositional.Syntax (PurePropLexicon)
import Carnap.Languages.PurePropositional.Logic
import Carnap.Languages.PurePropositional.Parser
import Carnap.Languages.PurePropositional.Util (getIndicies)
import Carnap.Languages.PurePropositional.Syntax (PureForm)
import Carnap.Languages.ClassicalSequent.Syntax
import Carnap.Languages.PurePropositional.Logic (PropSequentCalc)
import Carnap.Languages.Util.LanguageClasses
import GHCJS.DOM.Types
import GHCJS.DOM.Element
import GHCJS.DOM.HTMLSelectElement (castToHTMLSelectElement, getValue)
import GHCJS.DOM.Window (alert, prompt)
import GHCJS.DOM.Document (createElement, getDefaultView)
import GHCJS.DOM.Node (appendChild, getParentNode, insertBefore)
import GHCJS.DOM.EventM (newListener, addListener, EventM, target)
import Data.IORef (newIORef, IORef, readIORef,writeIORef, modifyIORef)
import Data.Map as M (Map, lookup, foldr, insert, fromList, toList)
import Data.Text (pack)
import Data.Either (rights)
import Data.List (subsequences, intercalate, nub, zip4, intersperse)
import Control.Monad.IO.Class (liftIO)
import Control.Lens (toListOf, preview)
import Control.Lens.Plated (children)
import Text.Parsec (parse, spaces, sepEndBy1, char, eof, optional, try, (<|>))
truthTableAction :: IO ()
truthTableAction = initElements getTruthTables activateTruthTables
getTruthTables :: Document -> HTMLElement -> IO [Maybe (Element, Element, Map String String)]
getTruthTables d = genInOutElts d "div" "div" "truthtable"
activateTruthTables :: Document -> Maybe (Element, Element, Map String String) -> IO ()
activateTruthTables w (Just (i,o,opts)) = do
case M.lookup "tabletype" opts of
Just "simple" -> checkerWith (formListParser <* eof) createSimpleTruthTable
Just "validity" -> checkerWith seqParser createValidityTruthTable
Just "partial" -> checkerWith (formListPairParser <* eof) createPartialTruthTable
_ -> return ()
where (formParser,seqParser) = case M.lookup "system" opts >>= \sys -> (,) <$> ndParseForm `ofPropSys` sys <*> ndParseSeq `ofPropSys` sys of
Just pair -> pair
Nothing -> (purePropFormulaParser standardLetters, ndParseSeq montagueSCCalc)
formListParser = formParser `sepEndBy1` (spaces *> char ',' <* spaces)
formListPairParser = do gs <- try (formListParser <* char ':') <|> return []
optional (char ':')
spaces
fs <- formListParser
return (gs,fs)
checkerWith parser ttbuilder =
case M.lookup "goal" opts of
Just g ->
case parse parser "" g of
Left e -> setInnerHTML o (Just $ show e)
Right f -> do
ref <- newIORef False
bw <- createButtonWrapper w o
(check,rows) <- ttbuilder w f (i,o) ref bw opts
let submit = submitTruthTable opts ref check rows (show f)
btStatus <- createSubmitButton w bw submit opts
doOnce o change False $ liftIO $ btStatus Edited
if "nocheck" `inOpts` opts then return ()
else do
bt2 <- questionButton w "Check"
appendChild bw (Just bt2)
checkIt <- newListener $ checkTable ref check
addListener bt2 click checkIt False
return ()
_ -> print "truth table was missing an option"
checkTable ref check = do correct <- liftIO $ check
if correct
then do message "Success!"
liftIO $ writeIORef ref True
setAttribute i "class" "input completeTT"
else do message "Something's not quite right"
liftIO $ writeIORef ref False
setAttribute i "class" "input incompleteTT"
submitTruthTable:: IsEvent e => Map String String -> IORef Bool -> IO Bool -> [Element] -> String -> String -> EventM HTMLInputElement e ()
submitTruthTable opts ref check rows s l = do isDone <- liftIO $ readIORef ref
if isDone
then trySubmit TruthTable opts l (ProblemContent (pack s)) True
else if "exam" `inOpts` opts
then do correct <- liftIO check
if correct
then trySubmit TruthTable opts l (ProblemContent (pack s)) True
else do tabulated <- liftIO $ mapM unpackRow rows
trySubmit TruthTable opts l (TruthTableDataOpts (pack s) (reverse tabulated) (M.toList opts)) False
else message "not yet finished (do you still need to check your answer?)"
-------------------------
-- Full Truth Tables --
-------------------------
createValidityTruthTable :: Document -> PropSequentCalc (Sequent (Form Bool))
-> (Element,Element) -> IORef Bool -> Element -> Map String String
-> IO (IO Bool, [Element])
createValidityTruthTable w (antced :|-: succed) (i,o) ref bw opts =
do setInnerHTML i (Just . rewriteWith opts . show $ (antced :|-: succed))
admissibleRows <- case M.lookup "counterexample-to" opts of
Just "equivalence" -> do
addCounterexample w opts bw i ref atomIndicies isEquivCE "Inequivalent"
return $ map (Just . not . isEquivCE) valuations
Just "inconsistency" -> do
addCounterexample w opts bw i ref atomIndicies isInconCE "Consistent"
return $ map (Just . not . isInconCE) valuations
Just "validity" -> do
addCounterexample w opts bw i ref atomIndicies isValCE "Invalid"
return $ map (Just . not . isValCE) valuations
_ -> do
addCounterexample w opts bw i ref atomIndicies isValCE "Counterexample"
return $ map (Just . not . isValCE) valuations
assembleTable w opts o orderedChildren valuations atomIndicies admissibleRows
where forms = antecedList ++ succedList
antecedList = map fromSequent $ toListOf concretes antced
succedList = map fromSequent $ toListOf concretes succed
isValCE v = and (map (unform . satisfies v) antecedList )
&& and (map (not . unform . satisfies v) succedList)
isEquivCE v = and (map (unform . satisfies v) antecedList)
&& not (and succVals || and (map not succVals))
where succVals = map (unform . satisfies v) succedList
isInconCE v = and (map (unform . satisfies v) antecedList)
&& and (map (unform . satisfies v) succedList)
atomIndicies = nub . sort . concatMap getIndicies $ forms
valuations = map toValuation . subsequences $ reverse atomIndicies
orderedChildren = concat $ intersperse [Left ','] (map (toOrderedChildren . fromSequent) (toListOf concretes antced))
++ [[Left '⊢']]
++ intersperse [Left ','] (map (toOrderedChildren. fromSequent) (toListOf concretes succed))
createSimpleTruthTable :: Document -> [PureForm] -> (Element,Element) -> IORef Bool
-> Element -> Map String String
-> IO (IO Bool,[Element])
createSimpleTruthTable w fs (i,o) ref bw opts =
do setInnerHTML i (Just . intercalate ", " . map (rewriteWith opts . show) $ fs)
case M.lookup "counterexample-to" opts of
Just "equivalence" -> addCounterexample w opts bw i ref atomIndicies isEquivCE "Inequivalent"
Just "inconsistency" -> addCounterexample w opts bw i ref atomIndicies isInconCE "Consistent"
Just "tautology" -> addCounterexample w opts bw i ref atomIndicies isTautCE "Non-Tautology"
Just "validity" -> addCounterexample w opts bw i ref atomIndicies isTautCE "Invalid"
_ -> do addCounterexample w opts bw i ref atomIndicies isTautCE "Counterexample"
assembleTable w opts o orderedChildren valuations atomIndicies (repeat Nothing)
where isTautCE v = and (map (not . unform . satisfies v) fs)
isEquivCE v = not (and vals || and (map not vals))
where vals = map (not . unform . satisfies v) fs
isInconCE v = and (map (unform . satisfies v) fs)
atomIndicies = nub . sort . concatMap getIndicies $ fs
valuations = map toValuation . subsequences $ reverse atomIndicies
orderedChildren = concat . intersperse [Left ','] . map toOrderedChildren $ fs
assembleTable :: Document -> Map String String -> Element -> [Either Char PureForm]
-> [Int -> Bool] -> [Int] -> [Maybe Bool]
-> IO (IO Bool, [Element])
assembleTable w opts o orderedChildren valuations atomIndicies admissibleRows =
do (table, thead, tbody) <- initTable w
gridRef <- makeGridRef (length orderedChildren) (length valuations)
head <- toHead w opts atomIndicies orderedChildren
rows <- mapM (toRow' gridRef) (zip4 valuations [1..] admissibleRows givens)
mapM_ (appendChild tbody . Just) (reverse rows)
appendChild thead (Just head)
appendChild o (Just table)
let check = M.foldr (&&) True <$> readIORef gridRef
return (check,rows)
where toRow' = toRow w opts atomIndicies orderedChildren
givens = makeGivens opts (Just $ length valuations) orderedChildren
addCounterexample :: Document -> Map String String -> Element -> Element
-> IORef Bool -> [Int] -> ((Int -> Bool) -> Bool) -> String
-> IO ()
addCounterexample w opts bw i ref atomIndicies isCounterexample title
| "nocounterexample" `inOpts` opts = return ()
| otherwise = do bt <- exclaimButton w title
Just w' <- getDefaultView w
counterexample <- newListener $ liftIO $ tryCounterexample w' opts ref i atomIndicies isCounterexample
addListener bt click counterexample False
appendChild bw (Just bt)
return ()
tryCounterexample :: Window -> Map String String -> IORef Bool -> Element
-> [Int] -> ((Int -> Bool) -> Bool)
-> IO ()
tryCounterexample w opts ref i indicies isCounterexample =
do mrow <- prompt w "enter the truth values for your counterexample row" (Just "")
case mrow of
Nothing -> return ()
Just s ->
case checkLength =<< (clean $ map charToTruthValue s) of
Nothing -> alert w "not a readable row"
Just l -> do let v = listToVal l
let s = isCounterexample v
if "exam" `inOpts` opts
then do alert w "Counterexample received - If you're confident that it is correct, press Submit to submit it."
writeIORef ref s
else if s then
do alert w "Success!"
writeIORef ref True
setAttribute i "class" "input completeTT"
else do alert w "Something's not quite right"
writeIORef ref False
setAttribute i "class" "input incompleteTT"
where clean (Nothing:xs) = Nothing
clean (Just x:xs) = (:) <$> (Just x) <*> (clean xs)
clean [] = Just []
listToVal l = toValuation (mask l indicies)
mask (x:xs) (y:ys) = if x then y:(mask xs ys) else mask xs ys
mask [] _ = []
checkLength l = if length l == length indicies then Just l else Nothing
toRow :: Document -> Map String String -> [Int]
-> [Either Char PureForm] -> IORef (Map (Int,Int) Bool)
-> (Int -> Bool, Int, Maybe Bool, [Maybe Bool])
-> IO Element
toRow w opts atomIndicies orderedChildren gridRef (v,n,mvalid,given) =
do Just row <- createElement w (Just "tr")
Just sep <- createElement w (Just "td")
setAttribute sep "class" "tttdSep"
valTds <- mapM toValTd atomIndicies
childTds <- mapM toChildTd (zip3 orderedChildren [1..] given)
mapM_ (appendChild row . Just) (valTds ++ [sep] ++ childTds)
return row
where toValTd i = do Just td <- createElement w (Just "td")
setInnerHTML td (Just $ if v i then "T" else "F")
setAttribute td "class" "valtd"
return td
toChildTd :: (Either Char PureForm, Int, Maybe Bool) -> IO Element
toChildTd (c,m,mg) = do Just td <- createElement w (Just "td")
case c of
Left '⊢' -> case mvalid of
Just tv -> addDropdown ("turnstilemark" `inOpts` opts) m td tv mg
Nothing -> setInnerHTML td (Just "")
Left c' -> setInnerHTML td (Just "")
Right f -> do let (Form tv) = satisfies v f
case preview _propIndex f of
Just i -> addDropdown False m td tv (if "autoAtoms" `inOpts` opts then (Just $ v i) else mg)
Nothing -> addDropdown False m td tv mg
return td
addDropdown turnstileMark m td bool mg =
do case mg of
Nothing -> modifyIORef gridRef (M.insert (n,m) False)
Just True -> modifyIORef gridRef (M.insert (n,m) bool)
Just False -> modifyIORef gridRef (M.insert (n,m) (not bool))
case mg of
Just val | "strictGivens" `inOpts` opts || "immutable" `inOpts` opts ->
do Just span <- createElement w (Just "span")
if val then setInnerHTML span (Just $ if turnstileMark then "✓" else "T")
else setInnerHTML span (Just $ if turnstileMark then "✗" else "F")
appendChild td (Just span)
_ | "immutable" `inOpts` opts ->
do Just span <- createElement w (Just "span")
setInnerHTML span (Just $ if "nodash" `inOpts` opts then " " else "-")
appendChild td (Just span)
_ -> do sel <- trueFalseOpts w opts turnstileMark mg
onSwitch <- newListener $ switchOnMatch m bool
addListener sel change onSwitch False
appendChild td (Just sel)
return ()
switchOnMatch m tv = do
Just t <- target :: EventM HTMLSelectElement Event (Maybe HTMLSelectElement)
s <- getValue t
if s `elem` [Just "T", Just "✓"]
then liftIO $ modifyIORef gridRef (M.insert (n,m) tv)
else liftIO $ modifyIORef gridRef (M.insert (n,m) (not tv))
----------------------------
-- Partial Truth Tables --
----------------------------
createPartialTruthTable :: Document -> ([PureForm],[PureForm]) -> (Element,Element) -> IORef Bool
-> Element -> Map String String -> IO (IO Bool,[Element])
createPartialTruthTable w (gs,fs) (i,o) _ _ opts =
do (table, thead, tbody) <- initTable w
setInnerHTML i (Just . intercalate ", " . map (rewriteWith opts . show) $ fs)
rRef <- makeRowRef (length orderedChildren)
head <- toPartialHead
row <- toPartialRow' rRef valuations givens
appendChild tbody (Just row)
appendChild thead (Just head)
appendChild o (Just table)
return (check rRef,[row])
where atomIndicies = nub . sort . concatMap getIndicies $ fs ++ gs
valuations = (map toValuation) . subsequences $ reverse atomIndicies
orderedConstraints = concat . intersperse [Left ','] . map toOrderedChildren $ gs
orderedSolvables = concat . intersperse [Left ','] . map toOrderedChildren $ fs
orderedChildren = orderedConstraints ++ orderedSolvables
givens = makeGivens opts Nothing orderedChildren
toPartialRow' = toPartialRow w opts orderedSolvables orderedConstraints
makeRowRef x = newIORef (M.fromList [(z, Nothing) | z <- [1..x]])
toPartialHead =
do Just row <- createElement w (Just "tr")
childThs <- mapM (toChildTh w) orderedSolvables >>= rewriteThs opts
case orderedConstraints of
[] -> mapM_ (appendChild row . Just) childThs
_ -> do Just sep <- createElement w (Just "th")
setAttribute sep "class" "ttthSep"
constraintThs <- mapM (toChildTh w) orderedConstraints >>= rewriteThs opts
mapM_ (appendChild row . Just) constraintThs
appendChild row (Just sep)
mapM_ (appendChild row . Just) childThs
return row
check rRef = do rMap <- readIORef rRef
let fittingVals = filter (\v -> any (fitsGiven v) givens) valuations
return $ any (validates rMap) fittingVals
validates rMap v = all (matches rMap v) (zip orderedChildren [1 ..])
fitsGiven v given = and (zipWith (~=) (map (reform v) orderedChildren) given)
where reform v (Left c) = Left c
reform v (Right f) = Right (unform . satisfies v $ f)
(~=) _ Nothing = True
(~=) (Left _) _ = True
(~=) (Right t) (Just t') = t == t'
matches rMap v (Left _,_) = True
matches rMap v (Right f,m) =
case M.lookup m rMap of
Just (Just tv) -> Form tv == satisfies v f
_ -> False
toPartialRow w opts orderedSolvables orderedConstraints rRef v givens =
do Just row <- createElement w (Just "tr")
solveTds <- mapM toChildTd (Prelude.drop sepIndex zipped)
case orderedConstraints of
[] -> mapM_ (appendChild row . Just) solveTds
_ -> do Just sep <- createElement w (Just "td")
setAttribute sep "class" "tttdSep"
constraintTds <- mapM toConstTd (take sepIndex zipped)
mapM_ (appendChild row . Just) constraintTds
appendChild row (Just sep)
mapM_ (appendChild row . Just) solveTds
return row
where sepIndex = length orderedConstraints
zipped = zip3 (orderedConstraints ++ orderedSolvables) [1 ..] givenRow
givenRow = last givens
--XXX The givens are passed around in reverse order - this is
--actually the first row
toChildTd (c,m,mg) = do Just td <- createElement w (Just "td")
case c of
Left _ -> setInnerHTML td (Just "")
Right _ -> addDropdown m td mg
return td
toConstTd (c,m,mg) = do Just td <- createElement w (Just "td")
case c of
Left _ -> setInnerHTML td (Just "")
Right _ -> case mg of
--TODO: DRY
Just val -> do Just span <- createElement w (Just "span")
setInnerHTML span (Just $ if val then "T" else "F")
modifyIORef rRef (M.insert m mg)
appendChild td (Just span)
return ()
Nothing -> do sel <- trueFalseOpts w opts False mg
modifyIORef rRef (M.insert m mg)
onSwitch <- newListener $ switch rRef m
addListener sel change onSwitch False
appendChild td (Just sel)
return ()
return td
addDropdown m td mg = do case mg of
Just val | "strictGivens" `inOpts` opts || "immutable" `inOpts` opts ->
do Just span <- createElement w (Just "span")
setInnerHTML span (Just $ if val then "T" else "F")
modifyIORef rRef (M.insert m mg)
appendChild td (Just span)
Just val | "hiddenGivens" `inOpts` opts ->
do sel <- trueFalseOpts w opts False Nothing
onSwitch <- newListener $ switch rRef m
addListener sel change onSwitch False
appendChild td (Just sel)
_ | "immutable" `inOpts` opts ->
do Just span <- createElement w (Just "span")
setInnerHTML span (Just $ if "nodash" `inOpts` opts then " " else "-")
appendChild td (Just span)
_ -> do sel <- trueFalseOpts w opts False mg
modifyIORef rRef (M.insert m mg)
onSwitch <- newListener $ switch rRef m
addListener sel change onSwitch False
appendChild td (Just sel)
return ()
switch rRef m = do
Just t <- target :: EventM HTMLSelectElement Event (Maybe HTMLSelectElement)
tv <- stringToTruthValue <$> getValue t
liftIO $ modifyIORef rRef (M.insert m tv)
------------------------
-- HTML Boilerplate --
------------------------
trueFalseOpts :: Document -> Map String String -> Bool -> Maybe Bool -> IO Element
trueFalseOpts w opts turnstileMark mg =
do Just sel <- createElement w (Just "select")
Just bl <- createElement w (Just "option")
Just tr <- createElement w (Just "option")
Just fs <- createElement w (Just "option")
setInnerHTML bl (Just $ if "nodash" `inOpts` opts then " " else "-")
setInnerHTML tr (Just $ if turnstileMark then "✓" else "T")
setInnerHTML fs (Just $ if turnstileMark then "✗" else "F")
case mg of
Nothing -> return ()
Just True -> setAttribute tr "selected" "selected"
Just False -> setAttribute fs "selected" "selected"
appendChild sel (Just bl)
appendChild sel (Just tr)
appendChild sel (Just fs)
return sel
toHead w opts atomIndicies orderedChildren =
do Just row <- createElement w (Just "tr")
Just sep <- createElement w (Just "th")
setAttribute sep "class" "ttthSep"
atomThs <- mapM toAtomTh atomIndicies >>= rewriteThs opts
childThs <- mapM (toChildTh w) orderedChildren >>= rewriteThs opts
mapM_ (appendChild row . Just) atomThs
appendChild row (Just sep)
mapM_ (appendChild row . Just) childThs
return row
where toAtomTh i = do Just th <- createElement w (Just "th")
setInnerHTML th (Just $ show (pn i :: PureForm))
return th
toChildTh :: (Schematizable (f (FixLang f)), CopulaSchema (FixLang f)) => Document -> Either Char (FixLang f a) -> IO Element
toChildTh w c =
do Just th <- createElement w (Just "th")
case c of
Left '⊢' -> do setInnerHTML th (Just ['⊢'])
setAttribute th "class" "ttTurstile"
Left c' -> setInnerHTML th (Just [c'])
Right f -> setInnerHTML th (Just $ mcOf f)
return th
-----------
-- BPT --
-----------
--we use a new data structure to convert formulas to ordered lists of
--subformulas and appropriate parentheses
--Binary propositional parsing tree. This could be written more compactly,
--but this seems conceptually clearer
data BPT = Leaf PureForm | MonNode PureForm BPT | BiNode PureForm BPT BPT
toBPT :: PureForm -> BPT
toBPT f = case children f of
[a] -> MonNode f (toBPT a)
[a,b] -> BiNode f (toBPT a) (toBPT b)
_ -> Leaf f
traverseBPT :: BPT -> [Either Char PureForm]
traverseBPT (Leaf f) = [Right f]
traverseBPT (MonNode f a) = [Right f] ++ traverseBPT a
traverseBPT (BiNode f a b) = [Left '('] ++ traverseBPT a ++ [Right f] ++ traverseBPT b ++ [Left ')']
toOrderedChildren = traverseBPT . toBPT
-------------------------
-- Utility Functions --
-------------------------
--this is a sorting that gets the correct ordering of indicies (reversed on
--negative, negative less than positive, postive as usual)
sort :: [Int] -> [Int]
sort (x:xs) = smaller ++ [x] ++ bigger
where smaller = sort (Prelude.filter small xs )
bigger = sort (Prelude.filter (not . small) xs)
small y | x < 0 && y > 0 = False
| x < 0 && y < 0 = x < y
| otherwise = y < x
sort [] = []
unpackRow :: Element -> IO [Maybe Bool]
unpackRow row = getListOfElementsByTag row "select" >>= mapM toValue
where toValue (Just e) = do stringToTruthValue <$> getValue (castToHTMLSelectElement e)
toValue Nothing = return Nothing
packText :: String -> [Maybe Bool]
packText s = if valid then map charToTruthValue . filter (/= ' ') $ s else []
where valid = all (`elem` ['T','F','-',' ']) s
expandRow :: [Either Char b] -> [Maybe Bool] -> [Maybe Bool]
expandRow (Right y:ys) (x:xs) = x : expandRow ys xs
expandRow (Left '⊢':ys) (x:xs) = x : expandRow ys xs
expandRow (Left y:ys) xs = Nothing : expandRow ys xs
expandRow [] (x:xs) = Nothing : expandRow [] xs
expandRow _ _ = []
initTable :: Document -> IO (Element, Element, Element)
initTable w = do (Just table) <- createElement w (Just "table")
(Just thead) <- createElement w (Just "thead")
(Just tbody) <- createElement w (Just "tbody")
appendChild table (Just thead)
appendChild table (Just tbody)
return (table, thead, tbody)
toValuation :: [Int] -> (Int -> Bool)
toValuation = flip elem
makeGridRef :: Int -> Int -> IO (IORef (Map (Int,Int) Bool))
makeGridRef x y = newIORef (M.fromList [((z,w), True) | z <- [1..x], w <-[1.. y]])
rewriteThs :: Map String String -> [Element] -> IO [Element]
rewriteThs opts ths = do s <- map deMaybe <$> mapM getInnerHTML ths
let s' = rewriteWith opts . concat $ s
mapM (\(c, th) -> setInnerHTML th (Just [c])) $ zip s' ths
return ths
where deMaybe (Just c) = c
deMaybe Nothing = " "
charToTruthValue :: Char -> Maybe Bool
charToTruthValue 'T' = Just True
charToTruthValue 'F' = Just False
charToTruthValue _ = Nothing
stringToTruthValue :: Maybe String -> Maybe Bool
stringToTruthValue (Just [c]) = charToTruthValue c
stringToTruthValue _ = Nothing
mcOf :: (Schematizable (f (FixLang f)), CopulaSchema (FixLang f)) => FixLang f a -> String
mcOf (h :!$: t) = mcOf h
mcOf h = show h
makeGivens :: Map String String -> Maybe Int -> [Either Char (FixLang f a)] -> [[Maybe Bool]]
makeGivens opts mrows orderedChildren = case M.lookup "content" opts of
Nothing -> repeat $ repeat Nothing
Just t -> case (reverse . map packText . filter (not . blank) . lines $ t, mrows) of
(s, Just rows) | length s == rows -> checkRowstrings rows s
| otherwise -> take rows $ repeat $ repeat Nothing
(s, Nothing) | length s > 0 -> checkRowstrings 1 s
| otherwise -> [repeat Nothing]
where checkRowstrings rows rowstrings =
case map (expandRow orderedChildren) rowstrings of
s' | all (\x -> length x == length orderedChildren) s' -> s'
| otherwise -> take rows $ repeat $ repeat Nothing
blank = all (`elem` [' ','\t'])
|
opentower/carnap
|
Carnap-GHCJS/src/Carnap/GHCJS/Action/TruthTable.hs
|
gpl-3.0
| 31,448
| 0
| 22
| 12,577
| 9,156
| 4,484
| 4,672
| 472
| 16
|
{-# 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.Sheets.Spreadsheets.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Returns the spreadsheet at the given ID. The caller must specify the
-- spreadsheet ID. By default, data within grids will not be returned. You
-- can include grid data one of two ways: * Specify a field mask listing
-- your desired fields using the \`fields\` URL parameter in HTTP * Set the
-- includeGridData URL parameter to true. If a field mask is set, the
-- \`includeGridData\` parameter is ignored For large spreadsheets, it is
-- recommended to retrieve only the specific fields of the spreadsheet that
-- you want. To retrieve only subsets of the spreadsheet, use the ranges
-- URL parameter. Multiple ranges can be specified. Limiting the range will
-- return only the portions of the spreadsheet that intersect the requested
-- ranges. Ranges are specified using A1 notation.
--
-- /See:/ <https://developers.google.com/sheets/ Google Sheets API Reference> for @sheets.spreadsheets.get@.
module Network.Google.Resource.Sheets.Spreadsheets.Get
(
-- * REST Resource
SpreadsheetsGetResource
-- * Creating a Request
, spreadsheetsGet
, SpreadsheetsGet
-- * Request Lenses
, sgXgafv
, sgUploadProtocol
, sgPp
, sgAccessToken
, sgSpreadsheetId
, sgUploadType
, sgRanges
, sgIncludeGridData
, sgBearerToken
, sgCallback
) where
import Network.Google.Prelude
import Network.Google.Sheets.Types
-- | A resource alias for @sheets.spreadsheets.get@ method which the
-- 'SpreadsheetsGet' request conforms to.
type SpreadsheetsGetResource =
"v4" :>
"spreadsheets" :>
Capture "spreadsheetId" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "pp" Bool :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParams "ranges" Text :>
QueryParam "includeGridData" Bool :>
QueryParam "bearer_token" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Spreadsheet
-- | Returns the spreadsheet at the given ID. The caller must specify the
-- spreadsheet ID. By default, data within grids will not be returned. You
-- can include grid data one of two ways: * Specify a field mask listing
-- your desired fields using the \`fields\` URL parameter in HTTP * Set the
-- includeGridData URL parameter to true. If a field mask is set, the
-- \`includeGridData\` parameter is ignored For large spreadsheets, it is
-- recommended to retrieve only the specific fields of the spreadsheet that
-- you want. To retrieve only subsets of the spreadsheet, use the ranges
-- URL parameter. Multiple ranges can be specified. Limiting the range will
-- return only the portions of the spreadsheet that intersect the requested
-- ranges. Ranges are specified using A1 notation.
--
-- /See:/ 'spreadsheetsGet' smart constructor.
data SpreadsheetsGet = SpreadsheetsGet'
{ _sgXgafv :: !(Maybe Xgafv)
, _sgUploadProtocol :: !(Maybe Text)
, _sgPp :: !Bool
, _sgAccessToken :: !(Maybe Text)
, _sgSpreadsheetId :: !Text
, _sgUploadType :: !(Maybe Text)
, _sgRanges :: !(Maybe [Text])
, _sgIncludeGridData :: !(Maybe Bool)
, _sgBearerToken :: !(Maybe Text)
, _sgCallback :: !(Maybe Text)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SpreadsheetsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sgXgafv'
--
-- * 'sgUploadProtocol'
--
-- * 'sgPp'
--
-- * 'sgAccessToken'
--
-- * 'sgSpreadsheetId'
--
-- * 'sgUploadType'
--
-- * 'sgRanges'
--
-- * 'sgIncludeGridData'
--
-- * 'sgBearerToken'
--
-- * 'sgCallback'
spreadsheetsGet
:: Text -- ^ 'sgSpreadsheetId'
-> SpreadsheetsGet
spreadsheetsGet pSgSpreadsheetId_ =
SpreadsheetsGet'
{ _sgXgafv = Nothing
, _sgUploadProtocol = Nothing
, _sgPp = True
, _sgAccessToken = Nothing
, _sgSpreadsheetId = pSgSpreadsheetId_
, _sgUploadType = Nothing
, _sgRanges = Nothing
, _sgIncludeGridData = Nothing
, _sgBearerToken = Nothing
, _sgCallback = Nothing
}
-- | V1 error format.
sgXgafv :: Lens' SpreadsheetsGet (Maybe Xgafv)
sgXgafv = lens _sgXgafv (\ s a -> s{_sgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
sgUploadProtocol :: Lens' SpreadsheetsGet (Maybe Text)
sgUploadProtocol
= lens _sgUploadProtocol
(\ s a -> s{_sgUploadProtocol = a})
-- | Pretty-print response.
sgPp :: Lens' SpreadsheetsGet Bool
sgPp = lens _sgPp (\ s a -> s{_sgPp = a})
-- | OAuth access token.
sgAccessToken :: Lens' SpreadsheetsGet (Maybe Text)
sgAccessToken
= lens _sgAccessToken
(\ s a -> s{_sgAccessToken = a})
-- | The spreadsheet to request.
sgSpreadsheetId :: Lens' SpreadsheetsGet Text
sgSpreadsheetId
= lens _sgSpreadsheetId
(\ s a -> s{_sgSpreadsheetId = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
sgUploadType :: Lens' SpreadsheetsGet (Maybe Text)
sgUploadType
= lens _sgUploadType (\ s a -> s{_sgUploadType = a})
-- | The ranges to retrieve from the spreadsheet.
sgRanges :: Lens' SpreadsheetsGet [Text]
sgRanges
= lens _sgRanges (\ s a -> s{_sgRanges = a}) .
_Default
. _Coerce
-- | True if grid data should be returned. This parameter is ignored if a
-- field mask was set in the request.
sgIncludeGridData :: Lens' SpreadsheetsGet (Maybe Bool)
sgIncludeGridData
= lens _sgIncludeGridData
(\ s a -> s{_sgIncludeGridData = a})
-- | OAuth bearer token.
sgBearerToken :: Lens' SpreadsheetsGet (Maybe Text)
sgBearerToken
= lens _sgBearerToken
(\ s a -> s{_sgBearerToken = a})
-- | JSONP
sgCallback :: Lens' SpreadsheetsGet (Maybe Text)
sgCallback
= lens _sgCallback (\ s a -> s{_sgCallback = a})
instance GoogleRequest SpreadsheetsGet where
type Rs SpreadsheetsGet = Spreadsheet
type Scopes SpreadsheetsGet =
'["https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/drive.readonly",
"https://www.googleapis.com/auth/spreadsheets",
"https://www.googleapis.com/auth/spreadsheets.readonly"]
requestClient SpreadsheetsGet'{..}
= go _sgSpreadsheetId _sgXgafv _sgUploadProtocol
(Just _sgPp)
_sgAccessToken
_sgUploadType
(_sgRanges ^. _Default)
_sgIncludeGridData
_sgBearerToken
_sgCallback
(Just AltJSON)
sheetsService
where go
= buildClient
(Proxy :: Proxy SpreadsheetsGetResource)
mempty
|
rueshyna/gogol
|
gogol-sheets/gen/Network/Google/Resource/Sheets/Spreadsheets/Get.hs
|
mpl-2.0
| 7,655
| 0
| 20
| 1,853
| 1,057
| 620
| 437
| 147
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Storage.Objects.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of objects matching the criteria.
--
-- /See:/ <https://developers.google.com/storage/docs/json_api/ Cloud Storage JSON API Reference> for @storage.objects.list@.
module Network.Google.Resource.Storage.Objects.List
(
-- * REST Resource
ObjectsListResource
-- * Creating a Request
, objectsList
, ObjectsList
-- * Request Lenses
, olStartOffSet
, olPrefix
, olBucket
, olVersions
, olUserProject
, olEndOffSet
, olIncludeTrailingDelimiter
, olProjection
, olProvisionalUserProject
, olPageToken
, olDelimiter
, olMaxResults
) where
import Network.Google.Prelude
import Network.Google.Storage.Types
-- | A resource alias for @storage.objects.list@ method which the
-- 'ObjectsList' request conforms to.
type ObjectsListResource =
"storage" :>
"v1" :>
"b" :>
Capture "bucket" Text :>
"o" :>
QueryParam "startOffset" Text :>
QueryParam "prefix" Text :>
QueryParam "versions" Bool :>
QueryParam "userProject" Text :>
QueryParam "endOffset" Text :>
QueryParam "includeTrailingDelimiter" Bool :>
QueryParam "projection" ObjectsListProjection :>
QueryParam "provisionalUserProject" Text :>
QueryParam "pageToken" Text :>
QueryParam "delimiter" Text :>
QueryParam "maxResults" (Textual Word32) :>
QueryParam "alt" AltJSON :>
Get '[JSON] Objects
-- | Retrieves a list of objects matching the criteria.
--
-- /See:/ 'objectsList' smart constructor.
data ObjectsList =
ObjectsList'
{ _olStartOffSet :: !(Maybe Text)
, _olPrefix :: !(Maybe Text)
, _olBucket :: !Text
, _olVersions :: !(Maybe Bool)
, _olUserProject :: !(Maybe Text)
, _olEndOffSet :: !(Maybe Text)
, _olIncludeTrailingDelimiter :: !(Maybe Bool)
, _olProjection :: !(Maybe ObjectsListProjection)
, _olProvisionalUserProject :: !(Maybe Text)
, _olPageToken :: !(Maybe Text)
, _olDelimiter :: !(Maybe Text)
, _olMaxResults :: !(Textual Word32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ObjectsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'olStartOffSet'
--
-- * 'olPrefix'
--
-- * 'olBucket'
--
-- * 'olVersions'
--
-- * 'olUserProject'
--
-- * 'olEndOffSet'
--
-- * 'olIncludeTrailingDelimiter'
--
-- * 'olProjection'
--
-- * 'olProvisionalUserProject'
--
-- * 'olPageToken'
--
-- * 'olDelimiter'
--
-- * 'olMaxResults'
objectsList
:: Text -- ^ 'olBucket'
-> ObjectsList
objectsList pOlBucket_ =
ObjectsList'
{ _olStartOffSet = Nothing
, _olPrefix = Nothing
, _olBucket = pOlBucket_
, _olVersions = Nothing
, _olUserProject = Nothing
, _olEndOffSet = Nothing
, _olIncludeTrailingDelimiter = Nothing
, _olProjection = Nothing
, _olProvisionalUserProject = Nothing
, _olPageToken = Nothing
, _olDelimiter = Nothing
, _olMaxResults = 1000
}
-- | Filter results to objects whose names are lexicographically equal to or
-- after startOffset. If endOffset is also set, the objects listed will
-- have names between startOffset (inclusive) and endOffset (exclusive).
olStartOffSet :: Lens' ObjectsList (Maybe Text)
olStartOffSet
= lens _olStartOffSet
(\ s a -> s{_olStartOffSet = a})
-- | Filter results to objects whose names begin with this prefix.
olPrefix :: Lens' ObjectsList (Maybe Text)
olPrefix = lens _olPrefix (\ s a -> s{_olPrefix = a})
-- | Name of the bucket in which to look for objects.
olBucket :: Lens' ObjectsList Text
olBucket = lens _olBucket (\ s a -> s{_olBucket = a})
-- | If true, lists all versions of an object as distinct results. The
-- default is false. For more information, see Object Versioning.
olVersions :: Lens' ObjectsList (Maybe Bool)
olVersions
= lens _olVersions (\ s a -> s{_olVersions = a})
-- | The project to be billed for this request. Required for Requester Pays
-- buckets.
olUserProject :: Lens' ObjectsList (Maybe Text)
olUserProject
= lens _olUserProject
(\ s a -> s{_olUserProject = a})
-- | Filter results to objects whose names are lexicographically before
-- endOffset. If startOffset is also set, the objects listed will have
-- names between startOffset (inclusive) and endOffset (exclusive).
olEndOffSet :: Lens' ObjectsList (Maybe Text)
olEndOffSet
= lens _olEndOffSet (\ s a -> s{_olEndOffSet = a})
-- | If true, objects that end in exactly one instance of delimiter will have
-- their metadata included in items in addition to prefixes.
olIncludeTrailingDelimiter :: Lens' ObjectsList (Maybe Bool)
olIncludeTrailingDelimiter
= lens _olIncludeTrailingDelimiter
(\ s a -> s{_olIncludeTrailingDelimiter = a})
-- | Set of properties to return. Defaults to noAcl.
olProjection :: Lens' ObjectsList (Maybe ObjectsListProjection)
olProjection
= lens _olProjection (\ s a -> s{_olProjection = a})
-- | The project to be billed for this request if the target bucket is
-- requester-pays bucket.
olProvisionalUserProject :: Lens' ObjectsList (Maybe Text)
olProvisionalUserProject
= lens _olProvisionalUserProject
(\ s a -> s{_olProvisionalUserProject = a})
-- | A previously-returned page token representing part of the larger set of
-- results to view.
olPageToken :: Lens' ObjectsList (Maybe Text)
olPageToken
= lens _olPageToken (\ s a -> s{_olPageToken = a})
-- | Returns results in a directory-like mode. items will contain only
-- objects whose names, aside from the prefix, do not contain delimiter.
-- Objects whose names, aside from the prefix, contain delimiter will have
-- their name, truncated after the delimiter, returned in prefixes.
-- Duplicate prefixes are omitted.
olDelimiter :: Lens' ObjectsList (Maybe Text)
olDelimiter
= lens _olDelimiter (\ s a -> s{_olDelimiter = a})
-- | Maximum number of items plus prefixes to return in a single page of
-- responses. As duplicate prefixes are omitted, fewer total results may be
-- returned than requested. The service will use this parameter or 1,000
-- items, whichever is smaller.
olMaxResults :: Lens' ObjectsList Word32
olMaxResults
= lens _olMaxResults (\ s a -> s{_olMaxResults = a})
. _Coerce
instance GoogleRequest ObjectsList where
type Rs ObjectsList = Objects
type Scopes ObjectsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/devstorage.full_control",
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/devstorage.read_write"]
requestClient ObjectsList'{..}
= go _olBucket _olStartOffSet _olPrefix _olVersions
_olUserProject
_olEndOffSet
_olIncludeTrailingDelimiter
_olProjection
_olProvisionalUserProject
_olPageToken
_olDelimiter
(Just _olMaxResults)
(Just AltJSON)
storageService
where go
= buildClient (Proxy :: Proxy ObjectsListResource)
mempty
|
brendanhay/gogol
|
gogol-storage/gen/Network/Google/Resource/Storage/Objects/List.hs
|
mpl-2.0
| 8,337
| 0
| 24
| 2,028
| 1,224
| 710
| 514
| 168
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.TagManager.Accounts.Containers.Versions.Undelete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Undeletes a Container Version.
--
-- /See:/ <https://developers.google.com/tag-manager/api/v1/ Tag Manager API Reference> for @tagmanager.accounts.containers.versions.undelete@.
module Network.Google.Resource.TagManager.Accounts.Containers.Versions.Undelete
(
-- * REST Resource
AccountsContainersVersionsUndeleteResource
-- * Creating a Request
, accountsContainersVersionsUndelete
, AccountsContainersVersionsUndelete
-- * Request Lenses
, acvucContainerId
, acvucContainerVersionId
, acvucAccountId
) where
import Network.Google.Prelude
import Network.Google.TagManager.Types
-- | A resource alias for @tagmanager.accounts.containers.versions.undelete@ method which the
-- 'AccountsContainersVersionsUndelete' request conforms to.
type AccountsContainersVersionsUndeleteResource =
"tagmanager" :>
"v1" :>
"accounts" :>
Capture "accountId" Text :>
"containers" :>
Capture "containerId" Text :>
"versions" :>
Capture "containerVersionId" Text :>
"undelete" :>
QueryParam "alt" AltJSON :>
Post '[JSON] ContainerVersion
-- | Undeletes a Container Version.
--
-- /See:/ 'accountsContainersVersionsUndelete' smart constructor.
data AccountsContainersVersionsUndelete = AccountsContainersVersionsUndelete'
{ _acvucContainerId :: !Text
, _acvucContainerVersionId :: !Text
, _acvucAccountId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'AccountsContainersVersionsUndelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acvucContainerId'
--
-- * 'acvucContainerVersionId'
--
-- * 'acvucAccountId'
accountsContainersVersionsUndelete
:: Text -- ^ 'acvucContainerId'
-> Text -- ^ 'acvucContainerVersionId'
-> Text -- ^ 'acvucAccountId'
-> AccountsContainersVersionsUndelete
accountsContainersVersionsUndelete pAcvucContainerId_ pAcvucContainerVersionId_ pAcvucAccountId_ =
AccountsContainersVersionsUndelete'
{ _acvucContainerId = pAcvucContainerId_
, _acvucContainerVersionId = pAcvucContainerVersionId_
, _acvucAccountId = pAcvucAccountId_
}
-- | The GTM Container ID.
acvucContainerId :: Lens' AccountsContainersVersionsUndelete Text
acvucContainerId
= lens _acvucContainerId
(\ s a -> s{_acvucContainerId = a})
-- | The GTM Container Version ID.
acvucContainerVersionId :: Lens' AccountsContainersVersionsUndelete Text
acvucContainerVersionId
= lens _acvucContainerVersionId
(\ s a -> s{_acvucContainerVersionId = a})
-- | The GTM Account ID.
acvucAccountId :: Lens' AccountsContainersVersionsUndelete Text
acvucAccountId
= lens _acvucAccountId
(\ s a -> s{_acvucAccountId = a})
instance GoogleRequest
AccountsContainersVersionsUndelete where
type Rs AccountsContainersVersionsUndelete =
ContainerVersion
type Scopes AccountsContainersVersionsUndelete =
'["https://www.googleapis.com/auth/tagmanager.edit.containerversions"]
requestClient AccountsContainersVersionsUndelete'{..}
= go _acvucAccountId _acvucContainerId
_acvucContainerVersionId
(Just AltJSON)
tagManagerService
where go
= buildClient
(Proxy ::
Proxy AccountsContainersVersionsUndeleteResource)
mempty
|
rueshyna/gogol
|
gogol-tagmanager/gen/Network/Google/Resource/TagManager/Accounts/Containers/Versions/Undelete.hs
|
mpl-2.0
| 4,417
| 0
| 17
| 989
| 466
| 278
| 188
| 83
| 1
|
module ViperVM.Library.FloatMatrixMul (
builtin, function, metaKernel, kernels
) where
import Control.Applicative ( (<$>) )
import ViperVM.VirtualPlatform.FunctionalKernel hiding (metaKernel,proto)
import ViperVM.VirtualPlatform.MetaObject
import ViperVM.VirtualPlatform.Descriptor
import ViperVM.VirtualPlatform.MetaKernel hiding (proto,name,kernels)
import ViperVM.VirtualPlatform.Objects.Matrix
import ViperVM.VirtualPlatform.Object
import ViperVM.Platform.Primitive as Prim
import ViperVM.Platform.KernelParameter
import ViperVM.Platform.Kernel
import ViperVM.Platform.Peer.KernelPeer
import qualified ViperVM.Library.OpenCL.FloatMatrixMul as CL
----------------------------------------
-- Builtin & Function
---------------------------------------
builtin :: MakeBuiltin
builtin = makeBuiltinIO function
function :: IO FunctionalKernel
function = FunctionalKernel proto makeParams makeResult <$> metaKernel
where
proto = Prototype {
inputs = [MatrixType,MatrixType],
output = MatrixType
}
makeParams args = do
let [a,b] = args
(w,_) = matrixDescDims (descriptor b)
(_,h) = matrixDescDims (descriptor a)
desc = MatrixDesc Prim.Float w h
c <- allocate desc
return [a,b,c]
makeResult args = last args
----------------------------------------
-- MetaKernel
---------------------------------------
metaKernel :: IO MetaKernel
metaKernel = MetaKernel name proto conf <$> kernels
where
name = "FloatMatrixAdd"
proto = [
Arg ReadOnly "a",
Arg ReadOnly "b",
Arg WriteOnly "c"
]
conf :: [ObjectPeer] -> [KernelParameter]
conf objs = params
where
[MatrixObject ma, MatrixObject mb, MatrixObject mc] = objs
params =
[WordParam (fromIntegral w),
WordParam (fromIntegral h),
WordParam (fromIntegral k),
BufferParam (matrixBuffer ma),
WordParam (fromIntegral lda),
WordParam (fromIntegral $ matrixOffset ma),
BufferParam (matrixBuffer mb),
WordParam (fromIntegral ldb),
WordParam (fromIntegral $ matrixOffset mb),
BufferParam (matrixBuffer mc),
WordParam (fromIntegral ldc),
WordParam (fromIntegral $ matrixOffset mc)]
(k, _) = matrixDimensions ma
w = matrixWidth mb
h = matrixHeight ma
lda = ((matrixWidth ma) * 4 + (matrixPadding ma)) `div` 4
ldb = ((matrixWidth mb) * 4 + (matrixPadding mb)) `div` 4
ldc = ((matrixWidth mc) * 4 + (matrixPadding mc)) `div` 4
----------------------------------------
-- Kernels
---------------------------------------
kernels :: IO [Kernel]
kernels = initKernelsIO [
CLKernel <$> CL.kernel
]
|
hsyl20/HViperVM
|
lib/ViperVM/Library/FloatMatrixMul.hs
|
lgpl-3.0
| 2,938
| 0
| 14
| 795
| 748
| 417
| 331
| 61
| 1
|
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveGeneric #-}
module Dyno.MultipleShooting
( MsOcp(..)
, MsDvs(..)
, MsConstraints(..)
, makeMsNlp
) where
import GHC.Generics ( Generic, Generic1 )
import GHC.TypeLits ( KnownNat, natVal )
import Data.Proxy ( Proxy(..) )
import Data.Vector ( Vector )
import Data.Maybe ( fromMaybe )
import qualified Data.Vector as V
import Linear
import qualified Data.Foldable as F
import Casadi.MX ( MX )
import Dyno.Nlp ( Bounds, Nlp(..), NlpIn(..) )
import Dyno.TypeVecs
import Dyno.View.Fun ( Fun, callSym, toFun )
import Dyno.View.JVec ( JVec(..) )
import Dyno.View.M ( vcat, vsplit )
import Dyno.View.Scheme ( Scheme )
import Dyno.Vectorize ( Vectorize, None(..) )
import Dyno.View.View ( View(..), J, S, JV, JTuple(..), jfill, catJV )
data IntegratorIn x u p a = IntegratorIn (J (JV x) a) (J (JV u) a) (J (JV p) a)
deriving (Generic, Generic1)
data IntegratorOut x a = IntegratorOut (J (JV x) a)
deriving (Generic, Generic1)
instance (Vectorize x, Vectorize u, Vectorize p) => Scheme (IntegratorIn x u p)
instance Vectorize x => Scheme (IntegratorOut x)
type Ode x u p a = x a -> u a -> p a -> a -> x a
-- problem specification
data MsOcp x u p =
MsOcp
{ msOde :: Ode x u p (S MX)
, msMayer :: x (S MX) -> S MX
, msLagrangeSum :: x (S MX) -> u (S MX) -> S MX
, msX0 :: x (Maybe Double)
, msXF :: x (Maybe Double)
, msXBnds :: x Bounds
, msUBnds :: u Bounds
, msPBnds :: p Bounds
, msEndTime :: Double
, msNumRk4Steps :: Maybe Int
}
-- design variables
data MsDvs x u p n a =
MsDvs
{ dvXus :: J (JVec n (JTuple (JV x) (JV u))) a
, dvXf :: J (JV x) a
, dvP :: J (JV p) a
} deriving (Generic, Generic1)
instance (Vectorize x, Vectorize u, Vectorize p, KnownNat n) => View (MsDvs x u p n)
-- constraints
data MsConstraints x n a =
MsConstraints
{ gContinuity :: J (JVec n (JV x)) a
} deriving (Generic, Generic1)
instance (Vectorize x, KnownNat n) => View (MsConstraints x n)
rk4 :: (Floating a, Additive x) => (x a -> u a -> p a -> a -> x a) -> x a -> u a -> p a -> a -> a -> x a
rk4 f x0 u p t h = x0 ^+^ h/6*^(k1 ^+^ 2 *^ k2 ^+^ 2 *^ k3 ^+^ k4)
where
k1 = f x0 u p t
k2 = f (x0 ^+^ h/2 *^ k1) u p (t+h/2)
k3 = f (x0 ^+^ h/2 *^ k2) u p (t+h/2)
k4 = f (x0 ^+^ h *^ k3) u p (t+h)
simulate :: (Floating a, Additive x) => Int -> Ode x u p a -> x a -> u a -> p a -> a -> a -> x a
simulate n ode x0' u p t h = xf
where
dt' = h/ fromIntegral n
xf = foldl sim x0' [ t+fromIntegral i*dt' | i <- [0..(n-1)] ]
sim x0'' t' = rk4 ode x0'' u p t' dt'
makeMsNlp ::
forall x u p n
. (KnownNat n, Vectorize x, Vectorize u, Vectorize p, Additive x)
=> MsOcp x u p -> IO (Nlp (MsDvs x u p n) (JV None) (MsConstraints x n) MX)
makeMsNlp msOcp = do
let n = fromIntegral (natVal (Proxy :: Proxy n))
integrate (IntegratorIn x0 u p) = IntegratorOut (vcat (simulate nsteps ode x0' u' p' 0 dt))
where
endTime = msEndTime msOcp
dt = (realToFrac endTime) / fromIntegral n
ode = msOde msOcp
nsteps = fromMaybe 1 (msNumRk4Steps msOcp)
x0' = vsplit x0
u' = vsplit u
p' = vsplit p
integrator <- toFun "my_integrator" integrate mempty :: IO (Fun (IntegratorIn x u p) (IntegratorOut x))
let nlp =
Nlp
{ nlpFG = fg
, nlpIn =
NlpIn
{ nlpBX = bx
, nlpBG = bg
, nlpX0 = x0
, nlpP = catJV None
, nlpLamX0 = Nothing
, nlpLamG0 = Nothing
}
, nlpScaleF = Nothing
, nlpScaleX = Nothing
, nlpScaleG = Nothing
}
x0 :: J (MsDvs x u p n) (V.Vector Double)
x0 = jfill 0
boundsX0 = catJV (fmap (\x -> (x,x)) (msX0 msOcp)) :: J (JV x) (Vector Bounds)
boundsX = catJV (msXBnds msOcp) :: J (JV x) (Vector Bounds)
boundsU = catJV (msUBnds msOcp) :: J (JV u) (Vector Bounds)
boundsX0u = JTuple boundsX0 boundsU :: JTuple (JV x) (JV u) (Vector Bounds)
boundsXu = JTuple boundsX boundsU :: JTuple (JV x) (JV u) (Vector Bounds)
boundsXF = catJV (fmap (\x -> (x,x)) (msXF msOcp)) :: J (JV x) (Vector Bounds)
boundsXus :: (J (JVec n (JTuple (JV x) (JV u))) (Vector Bounds))
boundsXus = cat $ JVec $ mkVec' ( cat boundsX0u : replicate (n-1) (cat boundsXu))
bx :: J (MsDvs x u p n) (Vector Bounds)
bx = cat MsDvs
{ dvXus = boundsXus
, dvXf = boundsXF
, dvP = catJV (msPBnds msOcp)
}
bg :: J (MsConstraints x n) (Vector Bounds)
bg = cat MsConstraints { gContinuity = jfill (Just 0, Just 0) }
fg :: J (MsDvs x u p n) MX -> J (JV None) MX -> (S MX, J (MsConstraints x n) MX)
fg dvs _ = (f, cat g)
where
MsDvs xus xf p = split dvs
x1s :: Vec n (J (JV x) MX)
x1s = fmap (callIntegrate . split) $ unJVec $ split xus
callIntegrate (JTuple x0' u) = x1
where
IntegratorOut x1 = callSym integrator (IntegratorIn x0' u p)
lagrangeSum = F.sum $ fmap callLagrangeSum (unJVec (split xus))
where
callLagrangeSum xu = msLagrangeSum msOcp (vsplit x) (vsplit u)
where
JTuple x u = split xu
mayer = msMayer msOcp (vsplit xf)
f :: S MX
f = mayer + lagrangeSum
x0s' = fmap (extractx . split) $ unJVec $ split xus :: Vec n (J (JV x) MX)
extractx (JTuple x0'' _) = x0''
x0s = tvtail (x0s' |> xf) :: Vec n (J (JV x) MX)
gaps:: Vec n (J (JV x) MX)
gaps = tvzipWith (-) x1s x0s
g :: MsConstraints x n MX
g = MsConstraints { gContinuity = cat $ JVec gaps }
return nlp
|
ghorn/dynobud
|
dynobud/src/Dyno/MultipleShooting.hs
|
lgpl-3.0
| 5,902
| 0
| 17
| 1,897
| 2,653
| 1,405
| 1,248
| 134
| 1
|
{-|
This package provides functions for parsing and evaluating bitcoin
transaction scripts. Data types are provided for building and
deconstructing all of the standard input and output script types.
-}
module Network.Haskoin.Script
(
-- *Scripts
-- | More informations on scripts is available here:
-- <http://en.bitcoin.it/wiki/Script>
Script(..)
, ScriptOp(..)
, PushDataType(..)
, opPushData
-- *Script Parsing
-- **Script Outputs
, ScriptOutput(..)
, encodeOutput
, encodeOutputBS
, decodeOutput
, decodeOutputBS
, isPayPK
, isPayPKHash
, isPayMulSig
, isPayScriptHash
, scriptAddr
, sortMulSig
-- **Script Inputs
, ScriptInput(..)
, SimpleInput(..)
, RedeemScript
, encodeInput
, encodeInputBS
, decodeInput
, decodeInputBS
, isSpendPK
, isSpendPKHash
, isSpendMulSig
, isScriptHashInput
-- * Helpers
, scriptRecipient
, scriptSender
, intToScriptOp
, scriptOpToInt
-- *SigHash
-- | For additional information on sighashes, see:
-- <http://en.bitcoin.it/wiki/OP_CHECKSIG>
, SigHash(..)
, txSigHash
, encodeSigHash32
, isSigAll
, isSigNone
, isSigSingle
, isSigUnknown
, TxSignature(..)
, encodeSig
, decodeSig
, decodeCanonicalSig
-- *Evaluation
, evalScript
, verifySpend
, SigCheck
) where
import Network.Haskoin.Script.Types
import Network.Haskoin.Script.Parser
import Network.Haskoin.Script.SigHash
import Network.Haskoin.Script.Evaluator
|
nuttycom/haskoin
|
Network/Haskoin/Script.hs
|
unlicense
| 1,377
| 0
| 5
| 198
| 213
| 150
| 63
| 50
| 0
|
{-# LANGUAGE NoImplicitPrelude #-}
import Math.Sieve.Phi
import Prelude hiding ((//))
import Fraction
import qualified Data.Set as S
stop = 1000000
space = [2..stop]
numReducedFractions =
let sv = sieve stop
in sum [phi sv a | a <- space]
main = do
print $ numReducedFractions
|
ulikoehler/ProjectEuler
|
Euler72.hs
|
apache-2.0
| 291
| 0
| 10
| 59
| 95
| 54
| 41
| -1
| -1
|
cnt pat [] = 0
cnt pat str =
let sub = take 3 str
mtc = if pat == sub
then 1
else 0
in
mtc + (cnt pat $ drop 1 str)
ans [] = []
ans (l:ls) =
let j = cnt "JOI" l
i = cnt "IOI" l
in
[j,i] ++ (ans ls)
main = do
c <- getContents
let i = lines c
o = ans i
mapM_ print o
|
a143753/AOJ
|
0522.hs
|
apache-2.0
| 332
| 0
| 10
| 142
| 184
| 90
| 94
| 17
| 2
|
module LibB2 where
myConstant4 :: String
myConstant4 = "blah"
|
kostmo/atom-ghc-mod-testcases
|
stack-multi-package/my-package-b/src/LibB2.hs
|
apache-2.0
| 63
| 0
| 4
| 10
| 14
| 9
| 5
| 3
| 1
|
module Handler.Search where
import Import
import Text.HyperEstraier
import Data.Conduit.Pool
import Data.Maybe (listToMaybe, catMaybes)
import qualified Data.Text as T
import Handler.List (paginateSelect)
import Control.Arrow ((***))
import Data.List (last)
searchNote :: Int -> UserId -> Text -> Handler (Int, [Entity Note])
searchNote pageNumber uid cond = do
i <- indexPool <$> getYesod
runDB $ withResource i (searchNote' pageNumber uid cond)
searchNote' :: Int -> UserId -> Text -> Database -> YesodDB sub App (Int, [Entity Note])
searchNote' pageNumber userId strcond db = do
foundNoteKeys <- liftIO $ do
condition <- newCondition
setPhrase condition strcond
docids <- searchDatabase db condition
catMaybes <$> mapM getKey docids
getNote foundNoteKeys
where
getNote noteIds = paginateSelect 15 pageNumber [NoteOwner ==. userId, NoteId <-. noteIds] []
getKey :: DocumentID -> IO (Maybe NoteId)
getKey docid = fmap (read . T.unpack) <$> getDocAttr db docid "@key"
getSearchR :: Handler RepHtml
getSearchR = do
pageNum <- maybe 1 id <$> (runInputGet $ iopt intField "page")
(Entity userId _) <- requireAuth
strcond <- runInputGet $ ireq textField "search"
(pages, notes) <- ((enumFromTo 1) *** (zip [1 :: Int ..])) <$> searchNote pageNum userId strcond
defaultLayout $ do
let title = "Search results" :: Html
setTitle title
$(widgetFile "list")
where
spoiler (Textarea text) = maybe "" id $ listToMaybe $ T.lines text
|
MasseR/introitu
|
Handler/Search.hs
|
bsd-2-clause
| 1,503
| 0
| 13
| 292
| 535
| 270
| 265
| 35
| 1
|
module Data.LFSR.Tap4 (
Tap4(..), tap4,
) where
import Data.Array (Array, array, (!))
data Tap4 = Tap4 { width :: Int
, bits :: (Int, Int, Int, Int)
} deriving Show
tapPair :: (Int, (Int, Int, Int, Int)) -> (Int, Tap4)
tapPair (i, bs) = (i, Tap4 { width = i, bits = bs })
tap4Table :: Array Int Tap4
tap4Table =
array (5, 768)
. map tapPair
$ [ (8, (8, 6, 5, 4))
-- , (16, (16, 14, 13, 11))
, (16, (16, 15, 13, 4))
-- , (32, (32, 30, 26, 25))
, (32, (32, 22, 2, 1))
, (64, (64, 63, 61, 60))
-- (128, (128, 127, 126, 121))
-- (128, (128, 126, 101, 99))
]
tap4 :: Int -> Tap4
tap4 = (tap4Table !)
|
khibino/haskell-lfsr
|
src/Data/LFSR/Tap4.hs
|
bsd-3-clause
| 686
| 0
| 9
| 219
| 282
| 180
| 102
| 18
| 1
|
module Data.Geo.GPX.Lens.TrksegsL where
import Data.Geo.GPX.Type.Trkseg
import Data.Lens.Common
class TrksegsL a where
trksegsL :: Lens a [Trkseg]
|
tonymorris/geo-gpx
|
src/Data/Geo/GPX/Lens/TrksegsL.hs
|
bsd-3-clause
| 152
| 0
| 8
| 21
| 45
| 28
| 17
| 5
| 0
|
{-# LANGUAGE RankNTypes, NamedFieldPuns, RecordWildCards, RecursiveDo,
BangPatterns, OverloadedStrings, TemplateHaskell, FlexibleContexts #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Distribution.Server.Features.Users (
initUserFeature,
UserFeature(..),
UserResource(..),
GroupResource(..),
) where
import Distribution.Server.Framework
import Distribution.Server.Framework.BackupDump
import qualified Distribution.Server.Framework.Auth as Auth
import Distribution.Server.Users.Types
import Distribution.Server.Users.State
import Distribution.Server.Users.Backup
import qualified Distribution.Server.Users.Users as Users
import qualified Distribution.Server.Users.Group as Group
import Distribution.Server.Users.Group (UserGroup(..), GroupDescription(..), UserList, nullDescription)
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Maybe (fromMaybe)
import Data.Function (fix)
import Control.Applicative (optional)
import Data.Aeson (toJSON)
import Data.Aeson.TH
import qualified Data.Text as T
import Distribution.Text (display, simpleParse)
-- | A feature to allow manipulation of the database of users.
--
-- TODO: clean up mismatched and duplicate functionality (some noted below).
data UserFeature = UserFeature {
-- | The users `HackageFeature`.
userFeatureInterface :: HackageFeature,
-- | User resources.
userResource :: UserResource,
-- | Notification that a user has been added. Currently unused.
userAdded :: Hook () (), --TODO: delete, other status changes?
-- | The admin user group, including its description, members, and
-- modification thereof.
adminGroup :: UserGroup,
-- Authorisation
-- | Require any of a set of privileges.
guardAuthorised_ :: [PrivilegeCondition] -> ServerPartE (),
-- | Require any of a set of privileges, giving the id of the current user.
guardAuthorised :: [PrivilegeCondition] -> ServerPartE UserId,
-- | Require being logged in, giving the id of the current user.
guardAuthenticated :: ServerPartE UserId,
-- | A hook to override the default authentication error in particular
-- circumstances.
authFailHook :: Hook Auth.AuthError (Maybe ErrorResponse),
-- | Retrieves the entire user base.
queryGetUserDb :: forall m. MonadIO m => m Users.Users,
-- | Creates a Hackage 2 user credential.
newUserAuth :: UserName -> PasswdPlain -> UserAuth,
-- | Adds a user with a fresh name.
updateAddUser :: forall m. MonadIO m => UserName -> UserAuth -> m (Either Users.ErrUserNameClash UserId),
-- | Sets the account-enabled status of an existing user to True or False.
updateSetUserEnabledStatus :: MonadIO m => UserId -> Bool
-> m (Maybe (Either Users.ErrNoSuchUserId Users.ErrDeletedUser)),
-- | Sets the credentials of an existing user.
updateSetUserAuth :: MonadIO m => UserId -> UserAuth
-> m (Maybe (Either Users.ErrNoSuchUserId Users.ErrDeletedUser)),
-- | Adds a user to a group based on a "user" path component.
--
-- Use the UserGroup or GroupResource directly instead, as this is a hack.
groupAddUser :: UserGroup -> DynamicPath -> ServerPartE (),
-- | Likewise, deletes a user, will go away soon.
groupDeleteUser :: UserGroup -> DynamicPath -> ServerPartE (),
-- | Get a username from a path.
userNameInPath :: forall m. MonadPlus m => DynamicPath -> m UserName,
-- | Lookup a `UserId` from a name, if the name exists.
lookupUserName :: UserName -> ServerPartE UserId,
-- | Lookup full `UserInfo` from a name, if the name exists.
lookupUserNameFull :: UserName -> ServerPartE (UserId, UserInfo),
-- | Lookup full `UserInfo` from an id, if the id exists.
lookupUserInfo :: UserId -> ServerPartE UserInfo,
-- | An action to change a password directly, using "password" and
-- "repeat-password" form fields. Only admins and the user themselves
-- can do this. This is messy, as it was one of the first things writen
-- for the users feature.
--
-- TODO: update and make more usable.
changePassword :: UserName -> ServerPartE (),
-- | Determine if the first user can change the second user's password,
-- replicating auth functionality. Avoid using.
canChangePassword :: forall m. MonadIO m => UserId -> UserId -> m Bool,
-- | Action to create a new user with the given credentials. This takes the
-- desired name, a password, and a repeated password, validating all.
newUserWithAuth :: String -> PasswdPlain -> PasswdPlain -> ServerPartE UserName,
-- | Action for an admin to create a user with "username", "password", and
-- "repeat-password" username fields.
adminAddUser :: ServerPartE Response,
-- Create a group resource for the given resource path.
groupResourceAt :: String -> UserGroup -> IO (UserGroup, GroupResource),
-- | Create a parameretrized group resource for the given resource path.
-- The parameter `a` can here be called a group key, and there is
-- potentially a set of initial values.
--
-- This takes functions to create a user group on the fly for the given
-- key, go from a key to a DynamicPath (for URI generation), as well as
-- go from a DynamicPath to a key with some possibility of failure. This
-- should check key membership, as well.
--
-- When these parameretrized `UserGroup`s need to be modified, the returned
-- `a -> UserGroup` function should be used, as it wraps the given
-- `a -> UserGroup` function to keep user-to-group mappings up-to-date.
groupResourcesAt :: forall a. String -> (a -> UserGroup)
-> (a -> DynamicPath)
-> (DynamicPath -> ServerPartE a)
-> [a]
-> IO (a -> UserGroup, GroupResource),
-- | Look up whether the current user has (add, remove) capabilities for
-- the given group, erroring out if neither are present.
lookupGroupEditAuth :: UserGroup -> ServerPartE (Bool, Bool),
-- | For a given user, return all of the URIs for groups they are in.
getGroupIndex :: forall m. (Functor m, MonadIO m) => UserId -> m [String],
-- | For a given URI, get a GroupDescription for it, if one can be found.
getIndexDesc :: forall m. MonadIO m => String -> m GroupDescription
}
instance IsHackageFeature UserFeature where
getFeatureInterface = userFeatureInterface
data UserResource = UserResource {
-- | The list of all users.
userList :: Resource,
-- | The main page for a given user.
userPage :: Resource,
-- | A user's password.
passwordResource :: Resource,
-- | A user's enabled status.
enabledResource :: Resource,
-- | The admin group.
adminResource :: GroupResource,
-- | URI for `userList` given a format.
userListUri :: String -> String,
-- | URI for `userPage` given a format and name.
userPageUri :: String -> UserName -> String,
-- | URI for `passwordResource` given a format and name.
userPasswordUri :: String -> UserName -> String,
-- | URI for `enabledResource` given a format and name.
userEnabledUri :: String -> UserName -> String,
-- | URI for `adminResource` given a format.
adminPageUri :: String -> String
}
instance FromReqURI UserName where
fromReqURI = simpleParse
data GroupResource = GroupResource {
-- | A group, potentially parametetrized over some collection.
groupResource :: Resource,
-- | A user's presence in a group.
groupUserResource :: Resource,
-- | A `UserGroup` for a group, with a `DynamicPath` for any parameterization.
getGroup :: DynamicPath -> ServerPartE UserGroup
}
-- This is a mapping of UserId -> group URI and group URI -> description.
-- Like many reverse mappings, it is probably rather volatile. Still, it is
-- a secondary concern, as user groups should be defined by each feature
-- and not globally, to be perfectly modular.
data GroupIndex = GroupIndex {
usersToGroupUri :: !(IntMap (Set String)),
groupUrisToDesc :: !(Map String GroupDescription)
}
emptyGroupIndex :: GroupIndex
emptyGroupIndex = GroupIndex IntMap.empty Map.empty
instance MemSize GroupIndex where
memSize (GroupIndex a b) = memSize2 a b
-- TODO: add renaming
initUserFeature :: ServerEnv -> IO (IO UserFeature)
initUserFeature ServerEnv{serverStateDir} = do
-- Canonical state
usersState <- usersStateComponent serverStateDir
adminsState <- adminsStateComponent serverStateDir
-- Ephemeral state
groupIndex <- newMemStateWHNF emptyGroupIndex
-- Extension hooks
userAdded <- newHook
authFailHook <- newHook
return $ do
-- Slightly tricky: we have an almost recursive knot between the group
-- resource management functions, and creating the admin group
-- resource that is part of the user feature.
--
-- Instead of trying to pull it apart, we just use a 'do rec'
--
rec let (feature@UserFeature{groupResourceAt}, adminGroupDesc)
= userFeature usersState
adminsState
groupIndex
userAdded authFailHook
adminG adminR
(adminG, adminR) <- groupResourceAt "/users/admins/" adminGroupDesc
return feature
usersStateComponent :: FilePath -> IO (StateComponent AcidState Users.Users)
usersStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "Users") initialUsers
return StateComponent {
stateDesc = "List of users"
, stateHandle = st
, getState = query st GetUserDb
, putState = update st . ReplaceUserDb
, backupState = \backuptype users ->
[csvToBackup ["users.csv"] (usersToCSV backuptype users)]
, restoreState = userBackup
, resetState = usersStateComponent
}
adminsStateComponent :: FilePath -> IO (StateComponent AcidState HackageAdmins)
adminsStateComponent stateDir = do
st <- openLocalStateFrom (stateDir </> "db" </> "HackageAdmins") initialHackageAdmins
return StateComponent {
stateDesc = "Admins"
, stateHandle = st
, getState = query st GetHackageAdmins
, putState = update st . ReplaceHackageAdmins . adminList
, backupState = \_ (HackageAdmins admins) -> [csvToBackup ["admins.csv"] (groupToCSV admins)]
, restoreState = HackageAdmins <$> groupBackup ["admins.csv"]
, resetState = adminsStateComponent
}
userFeature :: StateComponent AcidState Users.Users
-> StateComponent AcidState HackageAdmins
-> MemState GroupIndex
-> Hook () ()
-> Hook Auth.AuthError (Maybe ErrorResponse)
-> UserGroup
-> GroupResource
-> (UserFeature, UserGroup)
userFeature usersState adminsState
groupIndex userAdded authFailHook
adminGroup adminResource
= (UserFeature {..}, adminGroupDesc)
where
userFeatureInterface = (emptyHackageFeature "users") {
featureDesc = "Manipulate the user database."
, featureResources =
map ($ userResource)
[ userList
, userPage
, passwordResource
, enabledResource
]
++ [
groupResource adminResource
, groupUserResource adminResource
]
, featureState = [
abstractAcidStateComponent usersState
, abstractAcidStateComponent adminsState
]
, featureCaches = [
CacheComponent {
cacheDesc = "user group index",
getCacheMemSize = memSize <$> readMemState groupIndex
}
]
}
userResource = fix $ \r -> UserResource {
userList = (resourceAt "/users/.:format") {
resourceDesc = [ (GET, "list of users") ]
, resourceGet = [ ("json", serveUsersGet) ]
}
, userPage = (resourceAt "/user/:username.:format") {
resourceDesc = [ (GET, "user id info")
, (PUT, "create user")
, (DELETE, "delete user")
]
, resourceGet = [ ("json", serveUserGet) ]
, resourcePut = [ ("", serveUserPut) ]
, resourceDelete = [ ("", serveUserDelete) ]
}
, passwordResource = resourceAt "/user/:username/password.:format"
--TODO: PUT
, enabledResource = (resourceAt "/user/:username/enabled.:format") {
resourceDesc = [ (GET, "return if the user is enabled")
, (PUT, "set if the user is enabled")
]
, resourceGet = [("json", serveUserEnabledGet)]
, resourcePut = [("json", serveUserEnabledPut)]
}
, adminResource = adminResource
, userListUri = \format ->
renderResource (userList r) [format]
, userPageUri = \format uname ->
renderResource (userPage r) [display uname, format]
, userPasswordUri = \format uname ->
renderResource (passwordResource r) [display uname, format]
, userEnabledUri = \format uname ->
renderResource (enabledResource r) [display uname, format]
, adminPageUri = \format ->
renderResource (groupResource adminResource) [format]
}
-- Queries and updates
--
queryGetUserDb :: MonadIO m => m Users.Users
queryGetUserDb = queryState usersState GetUserDb
updateAddUser :: MonadIO m => UserName -> UserAuth -> m (Either Users.ErrUserNameClash UserId)
updateAddUser uname auth = updateState usersState (AddUserEnabled uname auth)
updateSetUserEnabledStatus :: MonadIO m => UserId -> Bool
-> m (Maybe (Either Users.ErrNoSuchUserId Users.ErrDeletedUser))
updateSetUserEnabledStatus uid isenabled = updateState usersState (SetUserEnabledStatus uid isenabled)
updateSetUserAuth :: MonadIO m => UserId -> UserAuth
-> m (Maybe (Either Users.ErrNoSuchUserId Users.ErrDeletedUser))
updateSetUserAuth uid auth = updateState usersState (SetUserAuth uid auth)
--
-- Authorisation: authentication checks and privilege checks
--
-- High level, all in one check that the client is authenticated as a
-- particular user and has an appropriate privilege, but then ignore the
-- identity of the user.
guardAuthorised_ :: [PrivilegeCondition] -> ServerPartE ()
guardAuthorised_ = void . guardAuthorised
-- As above but also return the identity of the client
guardAuthorised :: [PrivilegeCondition] -> ServerPartE UserId
guardAuthorised privconds = do
users <- queryGetUserDb
uid <- guardAuthenticatedWithErrHook users
Auth.guardPriviledged users uid privconds
return uid
-- Simply check if the user is authenticated as some user, without any
-- check that they have any particular priveledges. Only useful as a
-- building block.
guardAuthenticated :: ServerPartE UserId
guardAuthenticated = do
users <- queryGetUserDb
guardAuthenticatedWithErrHook users
-- As above but using the given userdb snapshot
guardAuthenticatedWithErrHook :: Users.Users -> ServerPartE UserId
guardAuthenticatedWithErrHook users = do
(uid,_) <- Auth.checkAuthenticated realm users
>>= either handleAuthError return
return uid
where
realm = Auth.hackageRealm --TODO: should be configurable
handleAuthError :: Auth.AuthError -> ServerPartE a
handleAuthError err = do
defaultResponse <- Auth.authErrorResponse realm err
overrideResponse <- msum <$> runHook authFailHook err
throwError (fromMaybe defaultResponse overrideResponse)
-- | Resources representing the collection of known users.
--
-- Features:
--
-- * listing the collection of users
-- * adding and deleting users
-- * enabling and disabling accounts
-- * changing user's name and password
--
serveUsersGet :: DynamicPath -> ServerPartE Response
serveUsersGet _ = do
userlist <- Users.enumerateActiveUsers <$> queryGetUserDb
let users = [ UserNameIdResource {
ui_username = userName uinfo,
ui_userid = uid
}
| (uid, uinfo) <- userlist ]
return . toResponse $ toJSON users
serveUserGet :: DynamicPath -> ServerPartE Response
serveUserGet dpath = do
(uid, uinfo) <- lookupUserNameFull =<< userNameInPath dpath
groups <- getGroupIndex uid
return . toResponse $
toJSON UserInfoResource {
ui1_username = userName uinfo,
ui1_userid = uid,
ui1_groups = map T.pack groups
}
serveUserPut :: DynamicPath -> ServerPartE Response
serveUserPut dpath = do
guardAuthorised_ [InGroup adminGroup]
username <- userNameInPath dpath
muid <- updateState usersState $ AddUserDisabled username
case muid of
Left Users.ErrUserNameClash ->
errBadRequest "Username already exists"
[MText "Cannot create a new user account with that username because already exists"]
Right uid -> return . toResponse $
toJSON UserNameIdResource {
ui_username = username,
ui_userid = uid
}
serveUserDelete :: DynamicPath -> ServerPartE Response
serveUserDelete dpath = do
guardAuthorised_ [InGroup adminGroup]
uid <- lookupUserName =<< userNameInPath dpath
merr <- updateState usersState $ DeleteUser uid
case merr of
Nothing -> noContent $ toResponse ()
--TODO: need to be able to delete user by name to fix this race condition
Just Users.ErrNoSuchUserId -> errInternalError [MText "uid does not exist"]
serveUserEnabledGet :: DynamicPath -> ServerPartE Response
serveUserEnabledGet dpath = do
guardAuthorised_ [InGroup adminGroup]
(_uid, uinfo) <- lookupUserNameFull =<< userNameInPath dpath
let enabled = case userStatus uinfo of
AccountEnabled _ -> True
_ -> False
return . toResponse $ toJSON EnabledResource { ui_enabled = enabled }
serveUserEnabledPut :: DynamicPath -> ServerPartE Response
serveUserEnabledPut dpath = do
guardAuthorised_ [InGroup adminGroup]
uid <- lookupUserName =<< userNameInPath dpath
EnabledResource enabled <- expectAesonContent
merr <- updateState usersState (SetUserEnabledStatus uid enabled)
case merr of
Nothing -> noContent $ toResponse ()
Just (Left Users.ErrNoSuchUserId) ->
errInternalError [MText "uid does not exist"]
Just (Right Users.ErrDeletedUser) ->
errBadRequest "User deleted"
[MText "Cannot disable account, it has already been deleted"]
--
-- Exported utils for looking up user names in URLs\/paths
--
userNameInPath :: forall m. MonadPlus m => DynamicPath -> m UserName
userNameInPath dpath = maybe mzero return (simpleParse =<< lookup "username" dpath)
lookupUserName :: UserName -> ServerPartE UserId
lookupUserName = fmap fst . lookupUserNameFull
lookupUserNameFull :: UserName -> ServerPartE (UserId, UserInfo)
lookupUserNameFull uname = do
users <- queryState usersState GetUserDb
case Users.lookupUserName uname users of
Just u -> return u
Nothing -> userLost "Could not find user: not presently registered"
where userLost = errNotFound "User not found" . return . MText
--FIXME: 404 is only the right error for operating on User resources
-- not when users are being looked up for other reasons, like setting
-- ownership of packages. In that case needs errBadRequest
lookupUserInfo :: UserId -> ServerPartE UserInfo
lookupUserInfo uid = do
users <- queryState usersState GetUserDb
case Users.lookupUserId uid users of
Just uinfo -> return uinfo
Nothing -> errInternalError [MText "user id does not exist"]
adminAddUser :: ServerPartE Response
adminAddUser = do
-- with this line commented out, self-registration is allowed
guardAuthorised_ [InGroup adminGroup]
reqData <- getDataFn lookUserNamePasswords
case reqData of
(Left errs) -> errBadRequest "Error registering user"
((MText "Username, password, or repeated password invalid.") : map MText errs)
(Right (ustr, pwd1, pwd2)) -> do
uname <- newUserWithAuth ustr (PasswdPlain pwd1) (PasswdPlain pwd2)
seeOther ("/user/" ++ display uname) (toResponse ())
where lookUserNamePasswords = do
(,,) <$> look "username"
<*> look "password"
<*> look "repeat-password"
newUserWithAuth :: String -> PasswdPlain -> PasswdPlain -> ServerPartE UserName
newUserWithAuth _ pwd1 pwd2 | pwd1 /= pwd2 = errBadRequest "Error registering user" [MText "Entered passwords do not match"]
newUserWithAuth userNameStr password _ =
case simpleParse userNameStr of
Nothing -> errBadRequest "Error registering user" [MText "Not a valid user name!"]
Just uname -> do
let auth = newUserAuth uname password
muid <- updateState usersState $ AddUserEnabled uname auth
case muid of
Left Users.ErrUserNameClash -> errForbidden "Error registering user" [MText "A user account with that user name already exists."]
Right _ -> return uname
-- Arguments: the auth'd user id, the user path id (derived from the :username)
canChangePassword :: MonadIO m => UserId -> UserId -> m Bool
canChangePassword uid userPathId = do
admins <- queryState adminsState GetAdminList
return $ uid == userPathId || (uid `Group.member` admins)
--FIXME: this thing is a total mess!
-- Do admins need to change user's passwords? Why not just reset passwords & (de)activate accounts.
changePassword :: UserName -> ServerPartE ()
changePassword username = do
uid <- lookupUserName username
guardAuthorised [IsUserId uid, InGroup adminGroup]
passwd1 <- look "password" --TODO: fail rather than mzero if missing
passwd2 <- look "repeat-password"
when (passwd1 /= passwd2) $
forbidChange "Copies of new password do not match or is an invalid password (ex: blank)"
let passwd = PasswdPlain passwd1
auth = newUserAuth username passwd
res <- updateState usersState (SetUserAuth uid auth)
case res of
Nothing -> return ()
Just (Left Users.ErrNoSuchUserId) -> errInternalError [MText "user id lookup failure"]
Just (Right Users.ErrDeletedUser) -> forbidChange "Cannot set passwords for deleted users"
where
forbidChange = errForbidden "Error changing password" . return . MText
newUserAuth :: UserName -> PasswdPlain -> UserAuth
newUserAuth name pwd = UserAuth (Auth.newPasswdHash Auth.hackageRealm name pwd)
------ User group management
adminGroupDesc :: UserGroup
adminGroupDesc = UserGroup {
groupDesc = nullDescription { groupTitle = "Hackage admins" },
queryUserList = queryState adminsState GetAdminList,
addUserList = updateState adminsState . AddHackageAdmin,
removeUserList = updateState adminsState . RemoveHackageAdmin,
canAddGroup = [adminGroupDesc],
canRemoveGroup = [adminGroupDesc]
}
groupAddUser :: UserGroup -> DynamicPath -> ServerPartE ()
groupAddUser group _ = do
guardAuthorised_ (map InGroup (canAddGroup group))
users <- queryState usersState GetUserDb
muser <- optional $ look "user"
case muser of
Nothing -> addError "Bad request (could not find 'user' argument)"
Just ustr -> case simpleParse ustr >>= \uname -> Users.lookupUserName uname users of
Nothing -> addError $ "No user with name " ++ show ustr ++ " found"
Just (uid,_) -> liftIO $ addUserList group uid
where addError = errBadRequest "Failed to add user" . return . MText
groupDeleteUser :: UserGroup -> DynamicPath -> ServerPartE ()
groupDeleteUser group dpath = do
guardAuthorised_ (map InGroup (canRemoveGroup group))
uid <- lookupUserName =<< userNameInPath dpath
liftIO $ removeUserList group uid
lookupGroupEditAuth :: UserGroup -> ServerPartE (Bool, Bool)
lookupGroupEditAuth group = do
addList <- liftIO . Group.queryGroups $ canAddGroup group
removeList <- liftIO . Group.queryGroups $ canRemoveGroup group
uid <- guardAuthenticated
let (canAdd, canDelete) = (uid `Group.member` addList, uid `Group.member` removeList)
if not (canAdd || canDelete)
then errForbidden "Forbidden" [MText "Can't edit permissions for user group"]
else return (canAdd, canDelete)
------------ Encapsulation of resources related to editing a user group.
-- | Registers a user group for external display. It takes the index group
-- mapping (groupIndex from UserFeature), the base uri of the group, and a
-- UserGroup object with all the necessary hooks. The base uri shouldn't
-- contain any dynamic or varying components. It returns the GroupResource
-- object, and also an adapted UserGroup that updates the cache. You should
-- use this in order to keep the index updated.
groupResourceAt :: String -> UserGroup -> IO (UserGroup, GroupResource)
groupResourceAt uri group = do
let mainr = resourceAt uri
descr = groupDesc group
groupUri = renderResource mainr []
group' = group
{ addUserList = \uid -> do
addGroupIndex uid groupUri descr
addUserList group uid
, removeUserList = \uid -> do
removeGroupIndex uid groupUri
removeUserList group uid
}
ulist <- queryUserList group
initGroupIndex ulist groupUri descr
let groupr = GroupResource {
groupResource = (extendResourcePath "/.:format" mainr) {
resourceDesc = [ (GET, "Description of the group and a list of its members (defined in 'users' feature)") ]
, resourceGet = [ ("json", serveUserGroupGet groupr) ]
}
, groupUserResource = (extendResourcePath "/user/:username.:format" mainr) {
resourceDesc = [ (PUT, "Add a user to the group (defined in 'users' feature)")
, (DELETE, "Remove a user from the group (defined in 'users' feature)")
]
, resourcePut = [ ("", serveUserGroupUserPut groupr) ]
, resourceDelete = [ ("", serveUserGroupUserDelete groupr) ]
}
, getGroup = \_ -> return group'
}
return (group', groupr)
-- | Registers a collection of user groups for external display. These groups
-- are usually backing a separate collection. Like groupResourceAt, it takes the
-- index group mapping and a base uri The base uri can contain varying path
-- components, so there should be a group-generating function that, given a
-- DynamicPath, yields the proper UserGroup. The final argument is the initial
-- list of DynamicPaths to build the initial group index. Like groupResourceAt,
-- this function returns an adaptor function that keeps the index updated.
groupResourcesAt :: String
-> (a -> UserGroup)
-> (a -> DynamicPath)
-> (DynamicPath -> ServerPartE a)
-> [a]
-> IO (a -> UserGroup, GroupResource)
groupResourcesAt uri mkGroup mkPath getGroupData initialGroupData = do
let mainr = resourceAt uri
sequence_
[ do let group = mkGroup x
dpath = mkPath x
ulist <- queryUserList group
initGroupIndex ulist (renderResource' mainr dpath) (groupDesc group)
| x <- initialGroupData ]
let mkGroup' x =
let group = mkGroup x
dpath = mkPath x
in group {
addUserList = \uid -> do
addGroupIndex uid (renderResource' mainr dpath) (groupDesc group)
addUserList group uid
, removeUserList = \uid -> do
removeGroupIndex uid (renderResource' mainr dpath)
removeUserList group uid
}
groupr = GroupResource {
groupResource = (extendResourcePath "/.:format" mainr) {
resourceDesc = [ (GET, "Description of the group and a list of the members (defined in 'users' feature)") ]
, resourceGet = [ ("json", serveUserGroupGet groupr) ]
}
, groupUserResource = (extendResourcePath "/user/:username.:format" mainr) {
resourceDesc = [ (PUT, "Add a user to the group (defined in 'users' feature)")
, (DELETE, "Delete a user from the group (defined in 'users' feature)")
]
, resourcePut = [ ("", serveUserGroupUserPut groupr) ]
, resourceDelete = [ ("", serveUserGroupUserDelete groupr) ]
}
, getGroup = \dpath -> mkGroup' <$> getGroupData dpath
}
return (mkGroup', groupr)
serveUserGroupGet groupr dpath = do
group <- getGroup groupr dpath
userDb <- queryGetUserDb
userlist <- liftIO $ queryUserList group
return . toResponse $ toJSON
UserGroupResource {
ui_title = T.pack $ groupTitle (groupDesc group),
ui_description = T.pack $ groupPrologue (groupDesc group),
ui_members = [ UserNameIdResource {
ui_username = Users.userIdToName userDb uid,
ui_userid = uid
}
| uid <- Group.enumerate userlist ]
}
--TODO: add serveUserGroupUserPost for the sake of the html frontend
-- and then remove groupAddUser & groupDeleteUser
serveUserGroupUserPut groupr dpath = do
group <- getGroup groupr dpath
guardAuthorised_ (map InGroup (canAddGroup group))
uid <- lookupUserName =<< userNameInPath dpath
liftIO $ addUserList group uid
goToList groupr dpath
serveUserGroupUserDelete groupr dpath = do
group <- getGroup groupr dpath
guardAuthorised_ (map InGroup (canRemoveGroup group))
uid <- lookupUserName =<< userNameInPath dpath
liftIO $ removeUserList group uid
goToList groupr dpath
goToList group dpath = seeOther (renderResource' (groupResource group) dpath)
(toResponse ())
---------------------------------------------------------------
addGroupIndex :: MonadIO m => UserId -> String -> GroupDescription -> m ()
addGroupIndex (UserId uid) uri desc =
modifyMemState groupIndex $
adjustGroupIndex
(IntMap.insertWith Set.union uid (Set.singleton uri))
(Map.insert uri desc)
removeGroupIndex :: MonadIO m => UserId -> String -> m ()
removeGroupIndex (UserId uid) uri =
modifyMemState groupIndex $
adjustGroupIndex
(IntMap.update (keepSet . Set.delete uri) uid)
id
where
keepSet m = if Set.null m then Nothing else Just m
initGroupIndex :: MonadIO m => UserList -> String -> GroupDescription -> m ()
initGroupIndex ulist uri desc =
modifyMemState groupIndex $
adjustGroupIndex
(IntMap.unionWith Set.union (IntMap.fromList . map mkEntry $ Group.enumerate ulist))
(Map.insert uri desc)
where
mkEntry (UserId uid) = (uid, Set.singleton uri)
getGroupIndex :: (Functor m, MonadIO m) => UserId -> m [String]
getGroupIndex (UserId uid) =
liftM (maybe [] Set.toList . IntMap.lookup uid . usersToGroupUri) $ readMemState groupIndex
getIndexDesc :: MonadIO m => String -> m GroupDescription
getIndexDesc uri =
liftM (Map.findWithDefault nullDescription uri . groupUrisToDesc) $ readMemState groupIndex
-- partitioning index modifications, a cheap combinator
adjustGroupIndex :: (IntMap (Set String) -> IntMap (Set String))
-> (Map String GroupDescription -> Map String GroupDescription)
-> GroupIndex -> GroupIndex
adjustGroupIndex f g (GroupIndex a b) = GroupIndex (f a) (g b)
{------------------------------------------------------------------------------
Some types for JSON resources
------------------------------------------------------------------------------}
data UserNameIdResource = UserNameIdResource { ui_username :: UserName,
ui_userid :: UserId }
data UserInfoResource = UserInfoResource { ui1_username :: UserName,
ui1_userid :: UserId,
ui1_groups :: [T.Text] }
data EnabledResource = EnabledResource { ui_enabled :: Bool }
data UserGroupResource = UserGroupResource { ui_title :: T.Text,
ui_description :: T.Text,
ui_members :: [UserNameIdResource] }
deriveJSON (compatAesonOptionsDropPrefix "ui_") ''UserNameIdResource
deriveJSON (compatAesonOptionsDropPrefix "ui1_") ''UserInfoResource
deriveJSON (compatAesonOptionsDropPrefix "ui_") ''EnabledResource
deriveJSON (compatAesonOptionsDropPrefix "ui_") ''UserGroupResource
|
snoyberg/hackage-server
|
Distribution/Server/Features/Users.hs
|
bsd-3-clause
| 34,840
| 0
| 21
| 10,067
| 6,637
| 3,488
| 3,149
| 510
| 18
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Client where
import Control.Monad (forM_)
import Control.Monad.Except (MonadError(..), ExceptT, runExceptT)
import Control.Monad.Reader (MonadReader(..), ReaderT, runReaderT, ask)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.Aeson (FromJSON(..), Value(..), (.:), (.:?), eitherDecode)
import Data.ByteString (ByteString)
import Data.ByteString.Lazy (toStrict)
import Data.CaseInsensitive (mk)
import Data.Either (either)
import Data.Text (Text, pack)
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Test
import System.Directory (listDirectory, removeFile)
import System.FilePath ((</>))
import Web.FormUrlEncoded
import WebApp
data History = History [Weight] [TimeDistance] [SetRep] deriving Show
data Weight = Weight String String Float deriving Show
data TimeDistance = TimeDistance { tdUuid :: String
, tdDate :: String
, tdActivity :: String
, tdDistance :: Maybe Float
, tdDuration :: Maybe Int
, tdComments :: Maybe String
} deriving Show
data SetRep = SetRep deriving Show
data ClientExc = FailingStatus (Status, ByteString)
| DecodeFailure String
deriving Show
newtype ClientM a = ClientM (ReaderT (ByteString, Context) (ExceptT ClientExc IO) a)
deriving (Functor, Applicative, Monad, MonadIO, MonadReader (ByteString, Context), MonadError ClientExc)
runClient :: (ByteString, Context) -> ClientM a -> IO (Either ClientExc a)
runClient ctx (ClientM act) = runExceptT $ runReaderT act ctx
instance FromJSON History where
parseJSON (Object obj) = History <$> obj .: "weight"
<*> obj .: "timeDistance"
<*> obj .: "setRep"
parseJSON v = error $ show v
instance FromJSON Weight where
parseJSON (Object obj) = do
(Object d) <- obj .: "data"
Weight <$> obj .: "id"
<*> d .: "date"
<*> d .: "weight"
parseJSON v = error $ show v
instance FromJSON TimeDistance where
parseJSON (Object obj) = do
(Object d) <- obj .: "data"
TimeDistance <$> obj .: "id"
<*> d .: "date"
<*> d .: "activity"
<*> d .:? "distance"
<*> d .:? "duration"
<*> d .:? "comments"
parseJSON v = error $ show v
instance FromJSON SetRep where
parseJSON _ = pure SetRep
putWeight :: Maybe String -> String -> Float -> ClientM Weight
putWeight uuid date weight = do
(authToken, ctx) <- ask
let body = urlEncodeAsForm [ ("date" :: String, date)
, ("weight" :: String, show weight)
]
let (method, url) = case uuid of
Nothing -> (methodPost, ["api", "weight"])
Just uuid_ -> (methodPut, ["api", "weight", pack uuid_])
let req = SRequest (defaultRequest { requestMethod = method
, pathInfo = url
, requestHeaders = [ (mk "Authorization", authToken)
, (mk "Content-Type", "application/x-www-form-urlencoded")
]
})
body
resp <- liftIO $ runSession (srequest req) (webapp ctx)
case statusCode $ simpleStatus resp of
200 -> either (throwError . DecodeFailure) pure $ eitherDecode (simpleBody resp)
_ -> throwError $ FailingStatus (simpleStatus resp, toStrict $ simpleBody resp)
putTimeDistance :: Maybe String -> String -> String -> Float -> Int -> String -> ClientM TimeDistance
putTimeDistance uuid date activity distance duration comments = do
(authToken, ctx) <- ask
let body = urlEncodeAsForm [ ("date" :: String, date)
, ("activity" :: String, activity)
, ("distance" :: String, show distance)
, ("duration" :: String, show duration)
, ("comments" :: String, comments)
]
let (method, url) = case uuid of
Nothing -> (methodPost, ["api", "time-distance"])
Just uuid_ -> (methodPut, ["api", "time-distance", pack uuid_])
let req = SRequest (defaultRequest { requestMethod = method
, pathInfo = url
, requestHeaders = [ (mk "Authorization", authToken)
, (mk "Content-Type", "application/x-www-form-urlencoded")
]
})
body
resp <- liftIO $ runSession (srequest req) (webapp ctx)
case statusCode $ simpleStatus resp of
200 -> either (throwError . DecodeFailure) pure $ eitherDecode (simpleBody resp)
_ -> throwError $ FailingStatus (simpleStatus resp, toStrict $ simpleBody resp)
getHistory :: Maybe (Text, Text) -> ClientM History
getHistory interval = do
(authToken, ctx) <- ask
resp <- liftIO $ flip runSession (webapp ctx) $ case interval of
Nothing ->
request defaultRequest { pathInfo = ["api", "history", "date"]
, requestHeaders = [ (mk "Authorization", authToken) ]
}
Just (startTime, endTime) ->
request defaultRequest { pathInfo = ["api", "history", "date", startTime, endTime]
, requestHeaders = [ (mk "Authorization", authToken) ]
}
case statusCode $ simpleStatus resp of
200 -> either (throwError . DecodeFailure) pure $ eitherDecode (simpleBody resp)
_ -> throwError $ FailingStatus (simpleStatus resp, toStrict $ simpleBody resp)
removeSeries :: FilePath -> IO ()
removeSeries path = do
files <- listDirectory path
forM_ files $ \f -> removeFile (path </> f)
reloadSeries :: ClientM ()
reloadSeries = do
(authToken, ctx) <- ask
resp <- liftIO $ runSession (request defaultRequest { requestMethod = methodPut
, pathInfo = ["api", "reload"]
, requestHeaders = [ (mk "Authorization", authToken) ]
})
(webapp ctx)
case statusCode $ simpleStatus resp of
200 -> pure ()
_ -> throwError $ FailingStatus (simpleStatus resp, toStrict $ simpleBody resp)
|
savannidgerinel/health
|
tests/Client.hs
|
bsd-3-clause
| 7,258
| 0
| 19
| 2,874
| 1,880
| 1,015
| 865
| 125
| 3
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
module DataStore where
import Event
import Player
import LawSerialization
import NewTTRS.Law
import NewTTRS.Match
import Control.Applicative
import Control.Lens
import Control.Monad (liftM)
import Data.Int (Int64)
import Data.Map (Map)
import Data.Maybe (catMaybes, listToMaybe)
import Data.Text (Text)
import Data.Time
import Data.Traversable (for)
import qualified Database.SQLite.Simple as Sqlite
import Database.SQLite.Simple.FromField
import Database.SQLite.Simple.ToField
import Snap.Snaplet.SqliteSimple
import qualified Data.Map as Map
getPlayers :: HasSqlite m => m (Map PlayerId Player)
getPlayers = do xs <- query_ "SELECT playerId, playerName FROM player"
return $ Map.fromList [(k,v) | Only k :. v <- xs]
getEvents :: HasSqlite m => m (Map EventId Event)
getEvents =
do xs <- query_ "SELECT eventId, eventDay FROM event"
return $ Map.fromList [(i,event) | Only i :. event <- xs]
addEvent :: HasSqlite m => Event -> m EventId
addEvent Event{..} =
do execute "INSERT INTO event (eventDay) VALUES (?)" (Only _eventDay)
liftM EventId lastInsertRowId
getEventIdByMatchId :: HasSqlite m => MatchId -> m (Maybe EventId)
getEventIdByMatchId matchId = do
do xs <- query "SELECT eventId FROM match WHERE matchId = ?" (Only matchId)
return $! case xs of
[] -> Nothing
Only x:_ -> Just x
getMatches :: HasSqlite m => m (Map MatchId (Match PlayerId))
getMatches = do
do xs <- query_ "SELECT matchId, winnerId, loserId, matchTime FROM match"
return $! Map.fromList [(k,v) | Only k :. v <- xs]
getLatestEventId :: HasSqlite m => m EventId
getLatestEventId = do
do xs <- query_ "SELECT eventId FROM event ORDER BY eventDay DESC LIMIT 1"
case xs of
[] -> fail "No events in system"
Only x:_ -> return x
getEventIdByDay :: HasSqlite m => Day -> m (Maybe EventId)
getEventIdByDay day =
do xs <- query "SELECT eventId FROM event WHERE eventDay = ?" (Only day)
return $! case xs of
[] -> Nothing
Only x:_ -> Just x
getEventById :: HasSqlite m => EventId -> m (Maybe Event)
getEventById eventid =
listToMaybe `liftM` query "SELECT eventDay FROM event WHERE eventId = ?"
(Only eventid)
deleteEventById :: HasSqlite m => EventId -> m ()
deleteEventById eventId = do
execute "DELETE FROM match WHERE eventId = ?" (Only eventId)
execute "DELETE FROM law WHERE eventId = ?" (Only eventId)
execute "DELETE FROM event WHERE eventId = ?" (Only eventId)
addMatchToEvent :: HasSqlite m => Match PlayerId -> EventId -> m MatchId
addMatchToEvent Match{..} eventId =
do execute "INSERT INTO match (eventId, winnerId, loserId, matchTime)\
\ VALUES (?,?,?,?)"
(eventId, _matchWinner, _matchLoser, _matchTime)
MatchId `liftM` lastInsertRowId
setMatchEventId :: HasSqlite m => MatchId -> EventId -> m ()
setMatchEventId matchId eventId = execute "UPDATE match SET eventId = ? WHERE matchId = ?" (eventId, matchId)
getMatchById :: HasSqlite m => MatchId -> m (Maybe (Match Player))
getMatchById matchid =
listToMaybe `liftM` query "SELECT w.playerName, l.playerName, matchTime\
\ FROM match\
\ JOIN player AS w ON w.playerId = winnerId\
\ JOIN player AS l ON l.playerId = loserId\
\ WHERE matchId = ?"
(Only matchid)
getMatchById' :: HasSqlite m => MatchId -> m (Maybe (Match PlayerId))
getMatchById' matchid =
listToMaybe `liftM` query "SELECT winnerId, loserId, matchTime\
\ FROM match\
\ WHERE matchId = ?"
(Only matchid)
getMatchTotals :: HasSqlite m => m (Map (PlayerId, PlayerId) Int)
getMatchTotals = do
xs <- query_ "SELECT winnerId, loserId, COUNT(matchId)\
\ FROM match\
\ GROUP BY winnerId, loserId"
return $ Map.fromList [((w,l),n) | (w,l,n) <- xs]
deleteMatchById :: HasSqlite m => MatchId -> m ()
deleteMatchById matchId =
execute "DELETE FROM match WHERE matchId = ?" $ Only matchId
addPlayer :: HasSqlite m => Player -> m PlayerId
addPlayer Player{..} =
do execute "INSERT INTO player (playerName) VALUES (?)" (Only _playerName)
PlayerId `liftM` lastInsertRowId
getPlayerIdByName :: HasSqlite m => Text -> m (Maybe PlayerId)
getPlayerIdByName name =
do xs <- query "SELECT playerId FROM player WHERE playerName = ?"
(Only name)
return $! case xs of
[] -> Nothing
Only x : _ -> x
getPlayerById :: HasSqlite m => PlayerId -> m (Maybe Player)
getPlayerById playerId =
listToMaybe `liftM` query "SELECT playerName FROM player WHERE playerId = ?" (Only playerId)
getMatchesForDay :: HasSqlite m => Day -> m [(MatchId, Match Player)]
getMatchesForDay day =
do xs <- query "SELECT matchId, w.playerName, l.playerName, matchTime\
\ FROM match\
\ JOIN player AS w ON w.playerId = winnerId\
\ JOIN player AS l ON l.playerId = loserId\
\ WHERE date(matchTime) = ?"
(Only day)
return [(x,y) | Only x :. y <- xs]
getMatchesByEventId :: HasSqlite m => EventId -> m (Map MatchId (Match PlayerId))
getMatchesByEventId eventId =
do xs <- query "SELECT matchId, winnerId, loserId, matchTime\
\ FROM match\
\ WHERE eventId = ?"
(Only eventId)
return $ Map.fromList [(k,v) | Only k :. v <- xs]
getActivePlayerIds :: HasSqlite m => m [PlayerId]
getActivePlayerIds =
map fromOnly `liftM` query_ "SELECT playerId FROM player\
\ WHERE playerId IN (SELECT winnerId FROM match)\
\ OR playerId IN (SELECT loserId FROM match)"
getLawsForEvent :: (Applicative m, HasSqlite m) => Bool -> EventId -> m (Map PlayerId (Day, Law))
getLawsForEvent backOne topEventId = do
playerIds <- getActivePlayerIds
fmap (Map.fromList . catMaybes) $
for playerIds $ \playerId -> do
xs <- if backOne
then query "SELECT eventDay, lawData\
\ FROM law\
\ NATURAL JOIN event \
\ WHERE playerId = ? AND eventId < ?\
\ ORDER BY eventDay DESC LIMIT 1"
(playerId, topEventId)
else query "SELECT eventDay, lawData\
\ FROM law\
\ NATURAL JOIN event \
\ WHERE playerId = ? AND eventId <= ?\
\ ORDER BY eventDay DESC LIMIT 1"
(playerId, topEventId)
case xs of
(Only day :. law) : _ -> return (Just (playerId, (day,law)))
_ -> return Nothing
clearLawsForEvent :: HasSqlite m => EventId -> m ()
clearLawsForEvent eventId = execute "DELETE FROM law WHERE eventId = ?" (Only eventId)
addLaw :: HasSqlite m => PlayerId -> EventId -> Law -> m ()
addLaw playerId eventId law =
execute "INSERT INTO law (playerId, eventId, mean, stddev, lawData) VALUES (?,?,?,?,?)"
(playerId, eventId, lawMean law, lawStddev law, serializeLaw law)
getLawsForPlayer :: HasSqlite m => PlayerId -> m (Map EventId (Event, Law))
getLawsForPlayer playerId = do
xs <- query "SELECT eventId, eventDay, lawData\
\ FROM law\
\ NATURAL JOIN event \
\ WHERE playerId = ?" (Only playerId)
return $ Map.fromList [(k,(event,law)) | Only k :. event :. law <- xs]
lastInsertRowId :: HasSqlite m => m Int64
lastInsertRowId = withSqlite Sqlite.lastInsertRowId
--
-- ID Types
--
newtype EventId = EventId Int64 deriving (Read, Show, Eq, Ord)
newtype PlayerId = PlayerId Int64 deriving (Read, Show, Eq, Ord)
newtype MatchId = MatchId Int64 deriving (Read, Show, Eq, Ord)
makeWrapped ''EventId
makeWrapped ''PlayerId
makeWrapped ''MatchId
instance ToField EventId where toField (EventId i) = toField i
instance ToField PlayerId where toField (PlayerId i) = toField i
instance ToField MatchId where toField (MatchId i) = toField i
instance FromField EventId where fromField = fmap EventId . fromField
instance FromField PlayerId where fromField = fmap PlayerId . fromField
instance FromField MatchId where fromField = fmap MatchId . fromField
instance FromRow PlayerId where fromRow = PlayerId <$> field
instance FromRow Law where
fromRow = do dat <- field
case deserializeLaw dat of
Nothing -> fail "bad law data"
Just law -> return law
instance FromRow Player where
fromRow = do _playerName <- field
return Player {..}
instance FromRow p => FromRow (Match p) where
fromRow = do _matchWinner <- fromRow
_matchLoser <- fromRow
_matchTime <- field
return Match {..}
instance FromRow Event where
fromRow = do _eventDay <- field
return Event {..}
|
glguy/tt-ratings
|
DataStore.hs
|
bsd-3-clause
| 9,043
| 0
| 18
| 2,357
| 2,413
| 1,205
| 1,208
| 172
| 3
|
-- | This module provides the 'ProofTree' type.
-- 'ProofTree' stores the open problems and the proofs of applying 'Processor' instances to problems.
module Tct.Core.Data.ProofTree
(
-- * ProofTree
ProofNode (..)
, ProofTree (..)
, open
, size
, flatten
, substitute
, substituteM
-- * Certification
, certificate
, certificateWith
-- * Properites
, isOpen
, isClosed
, isFailing
, isProgressing
-- * Output
, ppProofTree
, ppProofTreeLeafs
) where
import qualified Data.Foldable as F (toList)
import qualified Tct.Core.Common.Pretty as PP
import Tct.Core.Data.Answer (termcomp)
import Tct.Core.Data.Certificate (Certificate, unbounded)
import Tct.Core.Data.Types
-- | Returns the 'Open' nodes of a 'ProofTree'.
open :: ProofTree l -> [l]
open = foldr (:) []
-- | Returns the number of nodes of a 'ProofTree'.
size :: ProofTree l -> Int
size (Open _) = 1
size (Failure _) = 1
size (Success _ _ pts) = 1 + sum (size <$> pts)
-- | Monadic version of 'substitute'.
substituteM :: (Functor m, Monad m) => (l -> m (ProofTree k)) -> ProofTree l -> m (ProofTree k)
substituteM s (Open l) = s l
substituteM _ (Failure r) = return (Failure r)
substituteM s (Success pn cf pts) = Success pn cf <$> mapM (substituteM s) pts
-- | Substitute the open leaves of a proof tree according to the given function
substitute :: (l -> ProofTree k) -> ProofTree l -> ProofTree k
substitute f (Open l) = f l
substitute _ (Failure r) = Failure r
substitute f (Success pn cf pts) = Success pn cf (substitute f `fmap` pts)
-- | Flattens a nested prooftree.
flatten :: ProofTree (ProofTree l) -> ProofTree l
flatten = substitute id
-- | Computes the 'Certificate' of 'ProofTree'.
collectCertificate :: ProofTree Certificate -> Certificate
collectCertificate (Open c) = c
collectCertificate Failure{} = unbounded
collectCertificate (Success _ certfn' subtrees) = certfn' (collectCertificate `fmap` subtrees)
-- | Computes the 'Certificate' of a 'ProofTree'.
-- 'Open' nodes have the 'Certificate' 'unboundend'.
--
-- prop> certificate pt = collectCertificate (const unbounded `fmap` pt)
certificate :: ProofTree l -> Certificate
certificate pt = collectCertificate $ const unbounded `fmap` pt
-- | Computes the 'Certificate' of a 'ProofTree'.
-- 'Open' nodes have the 'Certificate' provided certificate'.
--
-- prop> certificate pt cert = collectCertificate (const cert `fmap` pt)
certificateWith :: ProofTree l -> Certificate -> Certificate
certificateWith pt cert = collectCertificate $ const cert `fmap` pt
-- | Checks if the 'ProofTree' contains a 'Failure' node.
isFailing :: ProofTree l -> Bool
isFailing Failure{} = True
isFailing (Success _ _ pts) = any isFailing pts
isFailing _ = False
-- | Checks that the 'ProofTree' does not contain a 'Failure' node
-- and not consist of a single 'Open' node
isProgressing :: ProofTree l -> Bool
isProgressing (Open _) = False
isProgressing p = not (isFailing p)
-- | Checks if there exists 'Open' nodes in the 'ProofTree'.
isOpen :: ProofTree l -> Bool
isOpen = not . isClosed
-- | Checks if there are no 'Open' nodes in the 'ProofTree'.
--
-- prop> isClosed = not . isOpen
isClosed :: ProofTree l -> Bool
isClosed = null . open
--- * Pretty Printing ------------------------------------------------------------------------------------------------
data Path = Path Int [(Int,Int)]
inc :: Path -> Path
inc (Path i is) = Path (succ i) is
split :: Path -> Int -> Path
split (Path i is) j = Path 1 ((i,j):is)
pathLength :: Path -> Int
pathLength (Path _ is) = 1 + length is
ppPath :: Path -> PP.Doc
ppPath (Path i is) = PP.cat $ PP.punctuate PP.colon . reverse $ PP.int i : f `fmap` is
where
f (j,k) = PP.int j PP.<> PP.dot PP.<> PP.text (g k)
g n = if n >= 1 && n <= 26 then [toEnum (96+n)] else toEnum n : g (n-26)
ppNode :: (Show p, PP.Pretty prob, PP.Pretty po) => p -> prob -> po -> PP.Doc
ppNode p prob po = PP.vcat
[ block "Considered Problem" (PP.pretty prob)
, block "Applied Processor" (PP.text $ show p)
, block "Details" (PP.pretty po) ]
where block n e = PP.nest 4 (PP.text "+" PP.<+> PP.text n PP.<> PP.char ':' PP.<$$> e)
ppProofNode :: Processor p => ProofNode p -> PP.Doc
ppProofNode (ProofNode p prob po) = ppNode p prob po
ppReason :: Reason -> PP.Doc
ppReason (Failed proc prob reason) = ppNode proc prob reason
ppReason r = PP.pretty r
ppProofTree' :: Path -> (prob -> PP.Doc) -> ProofTree prob -> PP.Doc
ppProofTree' is ppProb pt@(Open l) = PP.vcat
[ ppHeader pt is (PP.text "Open")
, PP.indent 4 (ppProb l) ]
ppProofTree' is _ f@(Failure r) =
ppHeader f is (PP.text "Failure")
PP.<$$> PP.indent 2 (ppReason r)
ppProofTree' path ppProb pt@(Success pn _ pts) =
PP.vcat [ ppHeader pt path (PP.text (takeWhile (`notElem` " {") (show (appliedProcessor pn))))
, PP.indent 4 (ppProofNode pn)
, ppSubTrees (F.toList pts) ]
where
ppSubTrees [] = PP.empty
ppSubTrees [t] = ppProofTree' (inc path) ppProb t
ppSubTrees ls = PP.vcat [ ppProofTree' (split path j) ppProb t | (j,t) <- zip [1..] ls]
ppHeader :: ProofTree l -> Path -> PP.Doc -> PP.Doc
ppHeader pt p s =
PP.text (replicate (pathLength p) '*') PP.<+> PP.text "Step" PP.<+> ppPath p PP.<> PP.char ':'
PP.<+> s
PP.<+> PP.group (PP.pretty (termcomp (certificate pt)))
ppProofTree :: (l -> PP.Doc) -> ProofTree l -> PP.Doc
ppProofTree pp pt =
ppProofTree' (Path 1 []) pp pt
PP.<> if null (F.toList pt) then PP.empty else
PP.empty
PP.<$$> PP.text "Following problems could not be solved:"
PP.<$$> PP.indent 2 (ppProofTreeLeafs pp pt)
ppProofTreeLeafs :: (l -> PP.Doc) -> ProofTree l -> PP.Doc
ppProofTreeLeafs pp = PP.vcat . map pp . F.toList
instance PP.Pretty prob => PP.Pretty (ProofTree prob) where
pretty = ppProofTree PP.pretty
|
ComputationWithBoundedResources/tct-core
|
src/Tct/Core/Data/ProofTree.hs
|
bsd-3-clause
| 5,992
| 0
| 15
| 1,323
| 2,035
| 1,056
| 979
| 109
| 3
|
module Sharc.Instruments.CelloMarteleBowing (celloMarteleBowing) where
import Sharc.Types
celloMarteleBowing :: Instr
celloMarteleBowing = Instr
"cello_martele"
"Cello (martele bowing)"
(Legend "McGill" "1" "15")
(Range
(InstrRange
(HarmonicFreq 1 (Pitch 65.4 24 "c2"))
(Pitch 65.4 24 "c2")
(Amplitude 6933.03 (HarmonicFreq 106 (Pitch 65.406 24 "c2")) 1.0e-2))
(InstrRange
(HarmonicFreq 27 (Pitch 10583.86 55 "g4"))
(Pitch 783.99 67 "g5")
(Amplitude 207.65 (HarmonicFreq 1 (Pitch 207.652 44 "g#3")) 6853.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
,note39
,note40
,note41
,note42
,note43]
note0 :: Note
note0 = Note
(Pitch 65.406 24 "c2")
1
(Range
(NoteRange
(NoteRangeAmplitude 6933.03 106 1.0e-2)
(NoteRangeHarmonicFreq 1 65.4))
(NoteRange
(NoteRangeAmplitude 196.21 3 3590.0)
(NoteRangeHarmonicFreq 152 9941.71)))
[Harmonic 1 1.181 26.13
,Harmonic 2 (-1.922) 777.99
,Harmonic 3 (-1.629) 3590.0
,Harmonic 4 (-2.92) 1164.6
,Harmonic 5 0.37 330.84
,Harmonic 6 (-0.498) 1354.24
,Harmonic 7 (-1.519) 640.26
,Harmonic 8 0.383 331.68
,Harmonic 9 2.447 500.14
,Harmonic 10 1.856 86.03
,Harmonic 11 (-0.996) 70.35
,Harmonic 12 (-2.084) 64.27
,Harmonic 13 0.89 82.79
,Harmonic 14 0.186 54.78
,Harmonic 15 (-0.877) 111.82
,Harmonic 16 0.384 74.64
,Harmonic 17 (-2.157) 105.78
,Harmonic 18 (-8.7e-2) 42.17
,Harmonic 19 0.785 13.74
,Harmonic 20 (-2.762) 1.71
,Harmonic 21 2.083 22.57
,Harmonic 22 2.1 28.38
,Harmonic 23 0.48 12.74
,Harmonic 24 (-2.537) 0.77
,Harmonic 25 (-1.057) 26.18
,Harmonic 26 2.347 50.98
,Harmonic 27 1.897 37.13
,Harmonic 28 (-1.533) 40.73
,Harmonic 29 0.286 34.17
,Harmonic 30 0.835 32.11
,Harmonic 31 (-2.945) 17.29
,Harmonic 32 (-1.442) 13.48
,Harmonic 33 2.898 13.66
,Harmonic 34 3.01 16.87
,Harmonic 35 (-2.703) 16.78
,Harmonic 36 (-1.972) 7.44
,Harmonic 37 (-2.213) 11.03
,Harmonic 38 1.562 11.94
,Harmonic 39 0.56 4.26
,Harmonic 40 2.338 8.35
,Harmonic 41 1.626 0.64
,Harmonic 42 (-2.704) 2.13
,Harmonic 43 (-1.241) 1.98
,Harmonic 44 (-9.9e-2) 3.19
,Harmonic 45 0.167 2.17
,Harmonic 46 0.448 5.93
,Harmonic 47 2.365 3.43
,Harmonic 48 (-2.81) 2.45
,Harmonic 49 (-2.177) 2.89
,Harmonic 50 (-1.964) 4.0
,Harmonic 51 (-0.904) 1.6
,Harmonic 52 2.637 0.69
,Harmonic 53 1.919 1.34
,Harmonic 54 (-1.625) 1.71
,Harmonic 55 (-0.157) 1.17
,Harmonic 56 1.065 1.35
,Harmonic 57 2.371 0.68
,Harmonic 58 2.376 0.26
,Harmonic 59 (-1.416) 0.34
,Harmonic 60 (-1.275) 0.53
,Harmonic 61 (-1.653) 0.51
,Harmonic 62 2.067 0.43
,Harmonic 63 0.231 0.69
,Harmonic 64 0.504 0.91
,Harmonic 65 1.446 0.96
,Harmonic 66 1.252 0.85
,Harmonic 67 2.449 0.75
,Harmonic 68 (-0.247) 0.65
,Harmonic 69 (-2.747) 0.29
,Harmonic 70 8.5e-2 0.42
,Harmonic 71 0.815 0.12
,Harmonic 72 1.515 0.52
,Harmonic 73 (-1.978) 0.18
,Harmonic 74 2.561 4.0e-2
,Harmonic 75 0.251 0.17
,Harmonic 76 (-1.6e-2) 0.33
,Harmonic 77 2.305 0.62
,Harmonic 78 1.112 9.0e-2
,Harmonic 79 1.184 0.23
,Harmonic 80 2.114 0.16
,Harmonic 81 (-0.848) 0.12
,Harmonic 82 (-1.155) 0.36
,Harmonic 83 (-0.423) 0.23
,Harmonic 84 (-0.321) 0.19
,Harmonic 85 (-0.643) 0.28
,Harmonic 86 1.126 0.35
,Harmonic 87 2.818 0.24
,Harmonic 88 (-2.973) 0.2
,Harmonic 89 (-1.108) 0.13
,Harmonic 90 0.947 0.47
,Harmonic 91 (-1.337) 0.25
,Harmonic 92 (-0.965) 0.26
,Harmonic 93 (-9.7e-2) 0.22
,Harmonic 94 1.224 0.58
,Harmonic 95 1.113 0.13
,Harmonic 96 (-2.599) 0.16
,Harmonic 97 (-1.035) 0.6
,Harmonic 98 2.895 0.25
,Harmonic 99 0.876 0.25
,Harmonic 100 1.349 0.21
,Harmonic 101 (-1.958) 0.49
,Harmonic 102 (-1.931) 0.3
,Harmonic 103 2.8e-2 0.39
,Harmonic 104 0.513 0.29
,Harmonic 105 (-0.704) 0.1
,Harmonic 106 2.62 1.0e-2
,Harmonic 107 (-1.246) 0.23
,Harmonic 108 (-1.336) 0.23
,Harmonic 109 1.247 0.22
,Harmonic 110 1.364 0.15
,Harmonic 111 (-2.554) 0.21
,Harmonic 112 (-0.501) 0.37
,Harmonic 113 0.479 0.15
,Harmonic 114 1.074 0.32
,Harmonic 115 (-2.243) 0.24
,Harmonic 116 (-1.82) 0.33
,Harmonic 117 0.463 0.58
,Harmonic 118 1.308 0.38
,Harmonic 119 (-2.288) 0.33
,Harmonic 120 (-0.475) 0.3
,Harmonic 121 0.854 0.5
,Harmonic 122 2.363 0.25
,Harmonic 123 3.0 5.0e-2
,Harmonic 124 (-0.771) 0.1
,Harmonic 125 0.518 0.26
,Harmonic 126 (-2.479) 0.13
,Harmonic 127 (-1.303) 0.17
,Harmonic 128 0.397 0.28
,Harmonic 129 (-2.647) 0.16
,Harmonic 130 9.6e-2 4.0e-2
,Harmonic 131 2.168 0.12
,Harmonic 132 1.524 0.16
,Harmonic 133 1.817 0.15
,Harmonic 134 (-0.112) 0.38
,Harmonic 135 (-2.778) 0.32
,Harmonic 136 1.029 0.46
,Harmonic 137 1.21 9.0e-2
,Harmonic 138 (-0.311) 0.2
,Harmonic 139 0.149 0.39
,Harmonic 140 (-0.649) 9.0e-2
,Harmonic 141 1.01 0.28
,Harmonic 142 (-1.317) 0.17
,Harmonic 143 (-2.047) 0.28
,Harmonic 144 (-0.541) 0.12
,Harmonic 145 0.304 0.35
,Harmonic 146 9.0e-2 0.19
,Harmonic 147 (-0.535) 0.25
,Harmonic 148 1.508 0.12
,Harmonic 149 0.692 0.41
,Harmonic 150 (-2.186) 0.11
,Harmonic 151 0.124 0.23
,Harmonic 152 (-1.483) 0.17]
note1 :: Note
note1 = Note
(Pitch 69.296 25 "c#2")
2
(Range
(NoteRange
(NoteRangeAmplitude 9285.66 134 9.0e-2)
(NoteRangeHarmonicFreq 1 69.29))
(NoteRange
(NoteRangeAmplitude 207.88 3 6100.0)
(NoteRangeHarmonicFreq 142 9840.03)))
[Harmonic 1 2.624 60.69
,Harmonic 2 1.959 1108.19
,Harmonic 3 1.046 6100.0
,Harmonic 4 2.101 758.44
,Harmonic 5 1.373 2275.19
,Harmonic 6 (-2.965) 422.76
,Harmonic 7 (-1.047) 489.24
,Harmonic 8 (-2.927) 40.6
,Harmonic 9 1.117 405.77
,Harmonic 10 (-0.145) 158.42
,Harmonic 11 (-2.636) 224.65
,Harmonic 12 (-2.726) 122.0
,Harmonic 13 (-0.976) 237.96
,Harmonic 14 (-0.674) 45.16
,Harmonic 15 1.25 112.85
,Harmonic 16 (-2.532) 103.46
,Harmonic 17 0.45 19.06
,Harmonic 18 0.551 28.41
,Harmonic 19 3.027 83.64
,Harmonic 20 1.284 22.03
,Harmonic 21 (-1.182) 58.96
,Harmonic 22 0.335 45.24
,Harmonic 23 (-2.546) 78.58
,Harmonic 24 (-1.697) 117.89
,Harmonic 25 (-0.682) 42.54
,Harmonic 26 (-1.099) 72.46
,Harmonic 27 (-8.9e-2) 14.3
,Harmonic 28 (-2.861) 151.51
,Harmonic 29 1.547 32.01
,Harmonic 30 2.875 30.2
,Harmonic 31 2.457 68.71
,Harmonic 32 (-0.475) 40.87
,Harmonic 33 (-1.306) 24.9
,Harmonic 34 (-0.754) 46.41
,Harmonic 35 2.962 49.35
,Harmonic 36 2.848 16.3
,Harmonic 37 2.87 27.24
,Harmonic 38 2.3e-2 34.26
,Harmonic 39 1.66 56.78
,Harmonic 40 0.903 22.57
,Harmonic 41 2.807 12.24
,Harmonic 42 2.184 11.53
,Harmonic 43 1.274 19.32
,Harmonic 44 0.549 13.59
,Harmonic 45 1.865 34.01
,Harmonic 46 (-2.4e-2) 34.59
,Harmonic 47 (-1.655) 8.98
,Harmonic 48 1.748 3.74
,Harmonic 49 3.015 1.59
,Harmonic 50 (-0.377) 1.8
,Harmonic 51 0.307 4.82
,Harmonic 52 (-2.907) 6.8
,Harmonic 53 (-1.516) 4.29
,Harmonic 54 2.144 3.18
,Harmonic 55 0.224 3.22
,Harmonic 56 (-3.1) 6.08
,Harmonic 57 0.752 1.81
,Harmonic 58 (-1.833) 0.46
,Harmonic 59 1.058 4.35
,Harmonic 60 2.261 2.2
,Harmonic 61 6.0e-2 7.7
,Harmonic 62 2.64 0.37
,Harmonic 63 0.926 3.85
,Harmonic 64 (-0.679) 2.89
,Harmonic 65 (-1.14) 5.97
,Harmonic 66 (-0.577) 3.47
,Harmonic 67 0.526 3.41
,Harmonic 68 (-0.934) 0.69
,Harmonic 69 (-2.56) 1.4
,Harmonic 70 (-1.548) 1.55
,Harmonic 71 2.681 4.01
,Harmonic 72 (-0.272) 2.72
,Harmonic 73 (-1.077) 3.26
,Harmonic 74 (-2.036) 0.85
,Harmonic 75 0.806 0.75
,Harmonic 76 1.729 1.43
,Harmonic 77 2.35 1.7
,Harmonic 78 (-0.995) 0.48
,Harmonic 79 (-0.221) 0.2
,Harmonic 80 2.576 0.83
,Harmonic 81 2.421 0.44
,Harmonic 82 1.483 1.1
,Harmonic 83 1.541 0.34
,Harmonic 84 1.406 0.26
,Harmonic 85 1.923 0.39
,Harmonic 86 1.951 1.54
,Harmonic 87 1.351 1.09
,Harmonic 88 (-0.998) 0.36
,Harmonic 89 1.218 1.02
,Harmonic 90 1.801 0.13
,Harmonic 91 0.155 0.76
,Harmonic 92 (-1.284) 0.61
,Harmonic 93 (-0.864) 0.75
,Harmonic 94 (-1.118) 2.02
,Harmonic 95 2.426 1.05
,Harmonic 96 (-2.696) 1.15
,Harmonic 97 2.601 0.76
,Harmonic 98 2.379 0.44
,Harmonic 99 0.231 0.35
,Harmonic 100 (-1.377) 0.91
,Harmonic 101 1.509 0.92
,Harmonic 102 (-2.087) 0.21
,Harmonic 103 (-1.3e-2) 0.58
,Harmonic 104 (-1.187) 1.62
,Harmonic 105 1.731 0.79
,Harmonic 106 (-2.789) 0.53
,Harmonic 107 2.39 0.78
,Harmonic 108 (-2.742) 0.25
,Harmonic 109 (-0.35) 0.41
,Harmonic 110 (-2.945) 0.57
,Harmonic 111 (-1.838) 0.48
,Harmonic 112 (-2.448) 0.34
,Harmonic 113 1.618 0.75
,Harmonic 114 1.858 0.61
,Harmonic 115 2.789 0.56
,Harmonic 116 2.672 0.33
,Harmonic 117 1.221 0.46
,Harmonic 118 (-0.66) 0.94
,Harmonic 119 (-0.765) 0.63
,Harmonic 120 1.444 0.94
,Harmonic 121 (-0.864) 0.44
,Harmonic 122 (-2.959) 0.98
,Harmonic 123 (-0.879) 0.46
,Harmonic 124 2.559 0.58
,Harmonic 125 2.536 0.16
,Harmonic 126 2.746 0.81
,Harmonic 127 0.446 0.71
,Harmonic 128 (-2.689) 0.72
,Harmonic 129 (-0.601) 0.3
,Harmonic 130 2.696 0.12
,Harmonic 131 (-2.698) 0.15
,Harmonic 132 (-1.313) 0.57
,Harmonic 133 (-2.388) 0.74
,Harmonic 134 3.042 9.0e-2
,Harmonic 135 (-2.381) 0.46
,Harmonic 136 (-0.107) 0.57
,Harmonic 137 0.975 0.54
,Harmonic 138 (-2.309) 0.52
,Harmonic 139 (-1.591) 0.28
,Harmonic 140 (-1.69) 0.24
,Harmonic 141 1.772 0.15
,Harmonic 142 (-1.006) 1.06]
note2 :: Note
note2 = Note
(Pitch 73.416 26 "d2")
3
(Range
(NoteRange
(NoteRangeAmplitude 9250.41 126 0.21)
(NoteRangeHarmonicFreq 1 73.41))
(NoteRange
(NoteRangeAmplitude 220.24 3 3782.0)
(NoteRangeHarmonicFreq 135 9911.16)))
[Harmonic 1 1.147 55.97
,Harmonic 2 (-0.702) 2235.17
,Harmonic 3 (-1.782) 3782.0
,Harmonic 4 (-1.848) 596.98
,Harmonic 5 2.547 182.05
,Harmonic 6 2.829 959.05
,Harmonic 7 1.738 178.23
,Harmonic 8 0.291 156.63
,Harmonic 9 0.696 330.94
,Harmonic 10 2.468 296.39
,Harmonic 11 (-1.394) 87.13
,Harmonic 12 9.2e-2 130.21
,Harmonic 13 0.768 181.37
,Harmonic 14 0.13 78.54
,Harmonic 15 2.99 78.31
,Harmonic 16 (-2.471) 137.24
,Harmonic 17 (-2.345) 45.62
,Harmonic 18 (-0.236) 121.96
,Harmonic 19 (-1.195) 51.66
,Harmonic 20 (-0.494) 50.52
,Harmonic 21 (-0.362) 36.51
,Harmonic 22 (-0.453) 48.04
,Harmonic 23 0.828 104.83
,Harmonic 24 1.312 32.97
,Harmonic 25 (-2.242) 118.72
,Harmonic 26 (-0.913) 122.58
,Harmonic 27 (-0.342) 38.19
,Harmonic 28 (-0.727) 27.1
,Harmonic 29 1.386 36.71
,Harmonic 30 (-1.898) 100.02
,Harmonic 31 (-2.288) 66.04
,Harmonic 32 0.813 66.01
,Harmonic 33 (-3.091) 125.13
,Harmonic 34 (-1.267) 68.13
,Harmonic 35 2.897 12.61
,Harmonic 36 1.865 17.47
,Harmonic 37 1.04 38.84
,Harmonic 38 2.883 47.87
,Harmonic 39 (-1.775) 16.94
,Harmonic 40 (-2.063) 6.11
,Harmonic 41 (-1.865) 29.15
,Harmonic 42 3.079 27.69
,Harmonic 43 (-2.497) 30.97
,Harmonic 44 (-0.313) 38.6
,Harmonic 45 0.913 18.99
,Harmonic 46 (-2.625) 10.47
,Harmonic 47 (-1.072) 15.58
,Harmonic 48 0.58 14.87
,Harmonic 49 (-3.03) 11.76
,Harmonic 50 (-1.172) 8.66
,Harmonic 51 (-1.531) 1.28
,Harmonic 52 1.337 2.36
,Harmonic 53 0.978 1.87
,Harmonic 54 1.172 0.99
,Harmonic 55 0.557 4.19
,Harmonic 56 0.492 1.66
,Harmonic 57 (-1.537) 2.87
,Harmonic 58 1.761 5.74
,Harmonic 59 2.156 8.56
,Harmonic 60 (-1.335) 10.03
,Harmonic 61 1.102 1.47
,Harmonic 62 2.258 4.18
,Harmonic 63 (-3.035) 1.02
,Harmonic 64 2.058 6.64
,Harmonic 65 (-2.796) 3.52
,Harmonic 66 4.7e-2 2.1
,Harmonic 67 (-0.901) 1.2
,Harmonic 68 (-2.345) 4.9
,Harmonic 69 0.688 1.51
,Harmonic 70 1.135 2.73
,Harmonic 71 2.626 1.53
,Harmonic 72 2.616 2.21
,Harmonic 73 0.459 1.07
,Harmonic 74 0.914 2.13
,Harmonic 75 (-1.831) 1.03
,Harmonic 76 (-0.361) 1.96
,Harmonic 77 2.965 1.45
,Harmonic 78 (-1.197) 2.42
,Harmonic 79 1.339 0.98
,Harmonic 80 (-2.539) 1.48
,Harmonic 81 0.344 1.22
,Harmonic 82 1.334 3.64
,Harmonic 83 (-1.591) 1.44
,Harmonic 84 (-0.611) 1.55
,Harmonic 85 2.061 2.13
,Harmonic 86 (-0.28) 0.81
,Harmonic 87 (-2.609) 0.81
,Harmonic 88 0.516 2.34
,Harmonic 89 1.107 1.65
,Harmonic 90 (-2.203) 4.69
,Harmonic 91 0.671 2.14
,Harmonic 92 2.732 2.47
,Harmonic 93 (-2.053) 0.88
,Harmonic 94 1.005 1.4
,Harmonic 95 0.328 0.65
,Harmonic 96 2.628 1.57
,Harmonic 97 (-1.494) 2.21
,Harmonic 98 1.396 1.68
,Harmonic 99 2.337 1.83
,Harmonic 100 (-1.585) 0.92
,Harmonic 101 (-0.22) 1.52
,Harmonic 102 (-2.543) 0.67
,Harmonic 103 2.23 0.76
,Harmonic 104 (-2.766) 0.51
,Harmonic 105 (-3.139) 0.73
,Harmonic 106 0.552 0.37
,Harmonic 107 2.661 1.06
,Harmonic 108 (-1.469) 0.33
,Harmonic 109 0.549 0.93
,Harmonic 110 1.474 0.95
,Harmonic 111 0.627 0.96
,Harmonic 112 0.484 0.56
,Harmonic 113 2.984 0.48
,Harmonic 114 (-1.198) 0.75
,Harmonic 115 1.172 0.88
,Harmonic 116 (-2.553) 1.02
,Harmonic 117 2.767 0.51
,Harmonic 118 (-7.3e-2) 0.92
,Harmonic 119 1.157 1.08
,Harmonic 120 (-2.03) 0.58
,Harmonic 121 (-7.8e-2) 0.8
,Harmonic 122 1.992 0.77
,Harmonic 123 3.045 0.55
,Harmonic 124 2.124 0.38
,Harmonic 125 1.433 0.42
,Harmonic 126 (-1.275) 0.21
,Harmonic 127 2.85 0.63
,Harmonic 128 1.448 0.22
,Harmonic 129 (-0.852) 0.87
,Harmonic 130 (-0.152) 0.71
,Harmonic 131 (-3.026) 0.79
,Harmonic 132 (-0.682) 0.49
,Harmonic 133 1.631 0.48
,Harmonic 134 (-1.057) 0.82
,Harmonic 135 0.936 0.5]
note3 :: Note
note3 = Note
(Pitch 77.782 27 "d#2")
4
(Range
(NoteRange
(NoteRangeAmplitude 5522.52 71 0.14)
(NoteRangeHarmonicFreq 1 77.78))
(NoteRange
(NoteRangeAmplitude 155.56 2 3572.0)
(NoteRangeHarmonicFreq 128 9956.09)))
[Harmonic 1 0.539 119.64
,Harmonic 2 (-2.091) 3572.0
,Harmonic 3 1.954 1593.21
,Harmonic 4 (-0.617) 1371.26
,Harmonic 5 (-1.224) 1998.61
,Harmonic 6 1.832 229.03
,Harmonic 7 (-2.764) 106.33
,Harmonic 8 1.001 141.18
,Harmonic 9 (-0.276) 217.95
,Harmonic 10 1.243 96.02
,Harmonic 11 (-1.695) 90.84
,Harmonic 12 (-2.963) 110.03
,Harmonic 13 (-0.188) 23.57
,Harmonic 14 (-0.723) 84.79
,Harmonic 15 (-0.678) 73.7
,Harmonic 16 (-0.955) 30.01
,Harmonic 17 0.193 80.31
,Harmonic 18 1.752 26.22
,Harmonic 19 2.808 38.61
,Harmonic 20 1.731 32.09
,Harmonic 21 0.458 31.82
,Harmonic 22 (-2.175) 104.81
,Harmonic 23 1.186 34.64
,Harmonic 24 (-0.113) 35.38
,Harmonic 25 3.018 34.53
,Harmonic 26 (-3.095) 17.14
,Harmonic 27 (-1.614) 26.88
,Harmonic 28 1.764 41.15
,Harmonic 29 (-3.006) 38.93
,Harmonic 30 (-0.783) 6.32
,Harmonic 31 1.63 24.28
,Harmonic 32 2.261 10.98
,Harmonic 33 (-2.428) 9.13
,Harmonic 34 2.332 6.59
,Harmonic 35 0.44 7.99
,Harmonic 36 2.351 16.57
,Harmonic 37 1.474 6.83
,Harmonic 38 (-1.099) 1.96
,Harmonic 39 1.006 0.89
,Harmonic 40 (-2.089) 2.44
,Harmonic 41 1.07 6.07
,Harmonic 42 (-0.139) 1.05
,Harmonic 43 1.761 2.67
,Harmonic 44 7.3e-2 0.15
,Harmonic 45 (-0.621) 2.39
,Harmonic 46 1.145 1.99
,Harmonic 47 1.8 1.57
,Harmonic 48 0.317 1.15
,Harmonic 49 2.684 1.26
,Harmonic 50 1.01 0.63
,Harmonic 51 (-0.519) 0.47
,Harmonic 52 (-2.939) 0.45
,Harmonic 53 (-1.841) 1.13
,Harmonic 54 (-2.767) 1.45
,Harmonic 55 (-1.116) 0.77
,Harmonic 56 2.979 1.21
,Harmonic 57 (-2.296) 0.9
,Harmonic 58 (-0.197) 0.33
,Harmonic 59 (-2.917) 0.23
,Harmonic 60 0.623 0.19
,Harmonic 61 (-1.473) 0.55
,Harmonic 62 0.242 0.93
,Harmonic 63 (-1.131) 0.59
,Harmonic 64 (-0.811) 0.47
,Harmonic 65 0.165 0.51
,Harmonic 66 2.377 0.59
,Harmonic 67 2.433 0.42
,Harmonic 68 (-0.375) 0.73
,Harmonic 69 (-2.129) 0.23
,Harmonic 70 (-3.017) 0.44
,Harmonic 71 2.349 0.14
,Harmonic 72 1.149 0.79
,Harmonic 73 1.889 0.59
,Harmonic 74 (-2.298) 0.58
,Harmonic 75 0.177 0.53
,Harmonic 76 1.482 0.36
,Harmonic 77 (-1.647) 0.42
,Harmonic 78 (-0.588) 0.24
,Harmonic 79 (-3.6e-2) 0.42
,Harmonic 80 2.512 0.25
,Harmonic 81 (-2.743) 0.88
,Harmonic 82 (-0.82) 0.24
,Harmonic 83 (-1.012) 0.95
,Harmonic 84 0.251 1.18
,Harmonic 85 2.412 0.83
,Harmonic 86 (-1.977) 0.99
,Harmonic 87 2.0e-3 1.26
,Harmonic 88 1.005 0.71
,Harmonic 89 (-1.474) 0.32
,Harmonic 90 0.788 0.59
,Harmonic 91 2.863 0.7
,Harmonic 92 (-1.725) 0.24
,Harmonic 93 0.275 0.61
,Harmonic 94 3.018 0.72
,Harmonic 95 (-1.704) 0.19
,Harmonic 96 (-1.985) 0.77
,Harmonic 97 (-0.175) 0.95
,Harmonic 98 (-1.617) 0.3
,Harmonic 99 2.6 0.15
,Harmonic 100 2.702 0.22
,Harmonic 101 (-0.665) 0.26
,Harmonic 102 0.352 0.91
,Harmonic 103 (-0.907) 0.77
,Harmonic 104 0.257 0.4
,Harmonic 105 0.373 0.75
,Harmonic 106 2.629 0.34
,Harmonic 107 0.384 0.78
,Harmonic 108 (-3.031) 0.89
,Harmonic 109 (-2.034) 0.36
,Harmonic 110 0.278 0.22
,Harmonic 111 2.38 0.69
,Harmonic 112 (-2.091) 0.77
,Harmonic 113 (-0.752) 0.77
,Harmonic 114 1.262 0.39
,Harmonic 115 2.995 0.48
,Harmonic 116 (-2.645) 0.26
,Harmonic 117 (-0.326) 0.53
,Harmonic 118 2.016 0.49
,Harmonic 119 2.569 0.36
,Harmonic 120 0.28 0.15
,Harmonic 121 2.436 0.33
,Harmonic 122 (-3.117) 0.5
,Harmonic 123 (-2.404) 0.82
,Harmonic 124 1.1e-2 0.28
,Harmonic 125 1.062 0.37
,Harmonic 126 2.992 0.52
,Harmonic 127 (-2.902) 0.38
,Harmonic 128 (-0.642) 0.76]
note4 :: Note
note4 = Note
(Pitch 82.407 28 "e2")
5
(Range
(NoteRange
(NoteRangeAmplitude 9641.61 117 9.0e-2)
(NoteRangeHarmonicFreq 1 82.4))
(NoteRange
(NoteRangeAmplitude 164.81 2 5497.0)
(NoteRangeHarmonicFreq 121 9971.24)))
[Harmonic 1 2.836 116.52
,Harmonic 2 1.479 5497.0
,Harmonic 3 2.44 788.68
,Harmonic 4 1.378 506.55
,Harmonic 5 (-2.388) 446.42
,Harmonic 6 1.65 335.23
,Harmonic 7 (-1.728) 49.71
,Harmonic 8 0.999 164.58
,Harmonic 9 (-1.936) 142.22
,Harmonic 10 1.455 131.7
,Harmonic 11 2.32 92.16
,Harmonic 12 (-0.182) 54.18
,Harmonic 13 (-1.308) 69.39
,Harmonic 14 0.37 10.25
,Harmonic 15 (-1.581) 33.53
,Harmonic 16 0.823 17.32
,Harmonic 17 1.725 22.09
,Harmonic 18 (-1.024) 15.72
,Harmonic 19 (-2.512) 43.08
,Harmonic 20 (-1.95) 59.07
,Harmonic 21 (-2.605) 127.62
,Harmonic 22 (-1.388) 23.63
,Harmonic 23 (-1.53) 41.04
,Harmonic 24 2.605 61.47
,Harmonic 25 1.109 17.45
,Harmonic 26 (-2.2) 33.04
,Harmonic 27 (-2.589) 56.46
,Harmonic 28 1.348 96.31
,Harmonic 29 1.871 22.3
,Harmonic 30 (-3.091) 24.3
,Harmonic 31 (-1.501) 5.06
,Harmonic 32 3.04 11.84
,Harmonic 33 2.525 4.64
,Harmonic 34 1.944 5.1
,Harmonic 35 (-2.391) 7.06
,Harmonic 36 2.113 5.59
,Harmonic 37 (-1.091) 4.41
,Harmonic 38 (-1.686) 9.49
,Harmonic 39 0.198 14.93
,Harmonic 40 (-1.73) 10.81
,Harmonic 41 1.643 2.13
,Harmonic 42 (-1.61) 5.96
,Harmonic 43 1.871 3.64
,Harmonic 44 (-0.997) 3.54
,Harmonic 45 (-2.167) 2.98
,Harmonic 46 (-3.096) 2.4
,Harmonic 47 0.425 1.47
,Harmonic 48 0.642 1.24
,Harmonic 49 0.174 2.26
,Harmonic 50 (-0.531) 1.11
,Harmonic 51 2.036 3.22
,Harmonic 52 (-7.0e-3) 1.94
,Harmonic 53 1.399 4.02
,Harmonic 54 (-0.904) 0.75
,Harmonic 55 (-0.108) 1.41
,Harmonic 56 3.057 2.05
,Harmonic 57 (-1.39) 0.98
,Harmonic 58 2.368 3.18
,Harmonic 59 0.146 1.65
,Harmonic 60 (-1.888) 0.66
,Harmonic 61 (-1.08) 1.58
,Harmonic 62 8.5e-2 0.68
,Harmonic 63 (-0.588) 0.56
,Harmonic 64 (-2.957) 0.65
,Harmonic 65 (-2.42) 0.83
,Harmonic 66 2.12 1.49
,Harmonic 67 (-2.204) 0.33
,Harmonic 68 (-2.21) 1.51
,Harmonic 69 2.48 1.12
,Harmonic 70 0.566 0.9
,Harmonic 71 (-2.965) 0.22
,Harmonic 72 (-3.5e-2) 0.32
,Harmonic 73 (-2.956) 0.77
,Harmonic 74 2.075 0.58
,Harmonic 75 (-0.834) 0.93
,Harmonic 76 (-2.099) 0.61
,Harmonic 77 (-2.438) 1.14
,Harmonic 78 2.882 0.57
,Harmonic 79 0.885 2.23
,Harmonic 80 (-1.304) 2.28
,Harmonic 81 1.964 1.1
,Harmonic 82 0.935 0.86
,Harmonic 83 (-0.169) 0.7
,Harmonic 84 (-1.485) 0.69
,Harmonic 85 (-2.529) 0.89
,Harmonic 86 1.371 1.0
,Harmonic 87 (-0.844) 1.01
,Harmonic 88 (-2.52) 0.59
,Harmonic 89 1.678 0.4
,Harmonic 90 (-0.517) 0.77
,Harmonic 91 (-1.118) 0.38
,Harmonic 92 (-1.266) 0.71
,Harmonic 93 0.146 0.27
,Harmonic 94 3.086 0.57
,Harmonic 95 2.089 0.46
,Harmonic 96 3.0e-3 0.35
,Harmonic 97 (-2.93) 0.46
,Harmonic 98 1.159 0.7
,Harmonic 99 0.337 0.74
,Harmonic 100 (-1.742) 0.46
,Harmonic 101 2.841 0.35
,Harmonic 102 1.903 0.57
,Harmonic 103 (-1.179) 1.08
,Harmonic 104 (-2.983) 0.98
,Harmonic 105 1.807 0.36
,Harmonic 106 (-1.739) 0.63
,Harmonic 107 (-3.062) 0.18
,Harmonic 108 (-2.398) 0.21
,Harmonic 109 1.459 0.24
,Harmonic 110 (-3.094) 0.23
,Harmonic 111 (-0.969) 0.31
,Harmonic 112 2.402 0.35
,Harmonic 113 0.589 0.47
,Harmonic 114 (-1.931) 0.96
,Harmonic 115 1.663 0.58
,Harmonic 116 (-0.116) 0.38
,Harmonic 117 2.704 9.0e-2
,Harmonic 118 (-2.883) 0.37
,Harmonic 119 1.804 0.63
,Harmonic 120 (-0.493) 0.59
,Harmonic 121 (-2.826) 0.64]
note5 :: Note
note5 = Note
(Pitch 87.307 29 "f2")
6
(Range
(NoteRange
(NoteRangeAmplitude 9865.69 113 0.18)
(NoteRangeHarmonicFreq 1 87.3))
(NoteRange
(NoteRangeAmplitude 174.61 2 2078.0)
(NoteRangeHarmonicFreq 114 9952.99)))
[Harmonic 1 (-1.649) 555.96
,Harmonic 2 (-1.354) 2078.0
,Harmonic 3 (-1.597) 730.84
,Harmonic 4 (-1.576) 923.83
,Harmonic 5 (-2.372) 849.9
,Harmonic 6 0.732 136.79
,Harmonic 7 2.467 195.36
,Harmonic 8 (-5.7e-2) 272.08
,Harmonic 9 1.872 93.81
,Harmonic 10 (-2.461) 24.02
,Harmonic 11 (-8.9e-2) 336.48
,Harmonic 12 (-1.977) 211.94
,Harmonic 13 2.173 529.39
,Harmonic 14 (-2.953) 43.78
,Harmonic 15 1.128 75.32
,Harmonic 16 (-2.923) 23.23
,Harmonic 17 0.771 58.99
,Harmonic 18 (-3.041) 119.18
,Harmonic 19 (-0.692) 195.37
,Harmonic 20 (-3.7e-2) 240.59
,Harmonic 21 (-2.456) 200.14
,Harmonic 22 0.42 154.29
,Harmonic 23 (-1.728) 146.96
,Harmonic 24 (-2.325) 66.24
,Harmonic 25 (-1.406) 131.95
,Harmonic 26 (-1.582) 167.24
,Harmonic 27 (-1.385) 56.64
,Harmonic 28 (-0.987) 114.01
,Harmonic 29 (-1.866) 15.21
,Harmonic 30 2.982 47.26
,Harmonic 31 1.826 19.1
,Harmonic 32 (-1.394) 16.64
,Harmonic 33 (-2.075) 26.8
,Harmonic 34 (-2.466) 37.1
,Harmonic 35 2.56 8.59
,Harmonic 36 (-1.681) 58.09
,Harmonic 37 (-2.547) 30.0
,Harmonic 38 (-2.753) 14.87
,Harmonic 39 (-1.556) 15.46
,Harmonic 40 3.045 6.53
,Harmonic 41 2.576 12.86
,Harmonic 42 1.591 31.97
,Harmonic 43 1.258 11.4
,Harmonic 44 1.758 3.37
,Harmonic 45 2.451 3.58
,Harmonic 46 0.964 3.64
,Harmonic 47 (-1.482) 4.44
,Harmonic 48 2.718 4.29
,Harmonic 49 1.331 7.41
,Harmonic 50 1.456 10.46
,Harmonic 51 2.745 0.32
,Harmonic 52 1.4 5.92
,Harmonic 53 2.117 9.09
,Harmonic 54 2.343 9.68
,Harmonic 55 2.313 10.51
,Harmonic 56 2.739 2.59
,Harmonic 57 (-2.721) 5.95
,Harmonic 58 1.719 2.36
,Harmonic 59 2.352 2.8
,Harmonic 60 (-7.3e-2) 2.05
,Harmonic 61 (-3.066) 2.88
,Harmonic 62 (-5.5e-2) 2.72
,Harmonic 63 3.098 0.27
,Harmonic 64 0.319 1.24
,Harmonic 65 (-3.067) 3.72
,Harmonic 66 3.093 5.94
,Harmonic 67 (-3.042) 5.61
,Harmonic 68 (-2.56) 5.37
,Harmonic 69 (-2.35) 7.88
,Harmonic 70 (-1.774) 6.5
,Harmonic 71 (-1.991) 4.93
,Harmonic 72 (-1.358) 1.94
,Harmonic 73 (-2.604) 2.09
,Harmonic 74 (-2.887) 5.19
,Harmonic 75 (-3.076) 5.63
,Harmonic 76 (-3.064) 6.25
,Harmonic 77 (-2.425) 4.46
,Harmonic 78 2.986 3.16
,Harmonic 79 (-2.772) 1.05
,Harmonic 80 (-1.401) 1.1
,Harmonic 81 0.374 2.94
,Harmonic 82 0.573 3.11
,Harmonic 83 1.374 2.12
,Harmonic 84 1.286 0.96
,Harmonic 85 0.392 2.42
,Harmonic 86 1.236 1.58
,Harmonic 87 (-2.0e-3) 4.36
,Harmonic 88 1.844 1.29
,Harmonic 89 1.858 1.61
,Harmonic 90 2.534 4.44
,Harmonic 91 (-3.046) 2.98
,Harmonic 92 (-2.663) 1.58
,Harmonic 93 (-2.799) 1.41
,Harmonic 94 (-2.298) 1.25
,Harmonic 95 1.3e-2 1.89
,Harmonic 96 0.404 2.77
,Harmonic 97 0.285 4.42
,Harmonic 98 1.107 3.17
,Harmonic 99 1.622 1.71
,Harmonic 100 2.027 0.73
,Harmonic 101 (-3.121) 1.55
,Harmonic 102 (-2.926) 1.07
,Harmonic 103 (-2.8) 0.58
,Harmonic 104 2.84 1.2
,Harmonic 105 (-2.276) 2.21
,Harmonic 106 (-2.217) 0.73
,Harmonic 107 (-1.832) 1.16
,Harmonic 108 (-2.056) 1.15
,Harmonic 109 (-1.803) 1.22
,Harmonic 110 (-2.739) 0.37
,Harmonic 111 1.013 1.02
,Harmonic 112 (-3.047) 1.02
,Harmonic 113 2.72 0.18
,Harmonic 114 (-2.725) 0.87]
note6 :: Note
note6 = Note
(Pitch 92.499 30 "f#2")
7
(Range
(NoteRange
(NoteRangeAmplitude 6659.92 72 0.15)
(NoteRangeHarmonicFreq 1 92.49))
(NoteRange
(NoteRangeAmplitude 277.49 3 3493.0)
(NoteRangeHarmonicFreq 110 10174.89)))
[Harmonic 1 (-2.255) 1561.34
,Harmonic 2 0.949 713.46
,Harmonic 3 (-2.244) 3493.0
,Harmonic 4 0.223 2497.55
,Harmonic 5 2.809 661.28
,Harmonic 6 3.036 368.2
,Harmonic 7 2.611 165.55
,Harmonic 8 1.553 171.24
,Harmonic 9 0.54 142.09
,Harmonic 10 1.417 188.34
,Harmonic 11 0.411 49.11
,Harmonic 12 1.582 3.64
,Harmonic 13 (-1.889) 57.34
,Harmonic 14 0.332 83.44
,Harmonic 15 (-1.253) 33.2
,Harmonic 16 2.546 125.1
,Harmonic 17 2.485 3.75
,Harmonic 18 (-2.374) 59.2
,Harmonic 19 (-2.17) 16.51
,Harmonic 20 1.701 52.54
,Harmonic 21 0.948 194.94
,Harmonic 22 2.071 104.76
,Harmonic 23 0.984 61.55
,Harmonic 24 1.989 66.52
,Harmonic 25 2.667 170.98
,Harmonic 26 (-2.937) 52.5
,Harmonic 27 2.466 124.81
,Harmonic 28 2.447 111.73
,Harmonic 29 3.04 61.8
,Harmonic 30 (-2.4e-2) 71.5
,Harmonic 31 1.5e-2 65.06
,Harmonic 32 (-2.814) 12.26
,Harmonic 33 (-1.973) 25.24
,Harmonic 34 2.458 4.23
,Harmonic 35 (-2.442) 61.84
,Harmonic 36 (-2.873) 28.15
,Harmonic 37 2.797 20.04
,Harmonic 38 (-1.977) 5.41
,Harmonic 39 2.879 7.47
,Harmonic 40 (-2.119) 11.35
,Harmonic 41 0.589 9.5
,Harmonic 42 (-0.102) 3.44
,Harmonic 43 (-2.281) 3.79
,Harmonic 44 (-0.275) 6.96
,Harmonic 45 (-1.224) 2.9
,Harmonic 46 (-0.543) 2.94
,Harmonic 47 (-2.139) 0.38
,Harmonic 48 2.689 4.97
,Harmonic 49 0.65 8.0
,Harmonic 50 (-1.62) 1.93
,Harmonic 51 (-2.808) 4.52
,Harmonic 52 (-1.342) 11.81
,Harmonic 53 (-1.091) 2.61
,Harmonic 54 (-1.582) 14.91
,Harmonic 55 2.318 2.88
,Harmonic 56 0.129 12.35
,Harmonic 57 0.648 8.52
,Harmonic 58 (-2.257) 2.76
,Harmonic 59 (-3.101) 8.3
,Harmonic 60 0.349 0.99
,Harmonic 61 (-2.734) 3.19
,Harmonic 62 (-0.345) 8.12
,Harmonic 63 2.682 1.26
,Harmonic 64 1.412 4.16
,Harmonic 65 2.333 1.86
,Harmonic 66 (-1.82) 1.9
,Harmonic 67 (-2.644) 2.84
,Harmonic 68 3.053 4.46
,Harmonic 69 3.139 5.77
,Harmonic 70 0.841 1.77
,Harmonic 71 1.776 2.04
,Harmonic 72 (-0.181) 0.15
,Harmonic 73 2.598 2.19
,Harmonic 74 1.261 1.65
,Harmonic 75 2.836 2.28
,Harmonic 76 (-2.355) 1.21
,Harmonic 77 (-4.1e-2) 1.89
,Harmonic 78 2.3e-2 1.19
,Harmonic 79 0.801 3.94
,Harmonic 80 2.406 3.81
,Harmonic 81 3.084 4.61
,Harmonic 82 (-2.932) 5.13
,Harmonic 83 (-2.174) 2.19
,Harmonic 84 (-2.741) 1.07
,Harmonic 85 0.381 2.07
,Harmonic 86 (-0.621) 2.04
,Harmonic 87 0.571 1.8
,Harmonic 88 0.594 1.95
,Harmonic 89 0.451 1.45
,Harmonic 90 (-3.03) 0.27
,Harmonic 91 2.495 1.73
,Harmonic 92 (-2.702) 1.21
,Harmonic 93 (-3.052) 1.94
,Harmonic 94 2.859 3.99
,Harmonic 95 (-3.017) 1.48
,Harmonic 96 (-2.417) 1.9
,Harmonic 97 (-2.752) 2.15
,Harmonic 98 (-2.331) 1.12
,Harmonic 99 (-1.607) 1.46
,Harmonic 100 (-1.648) 1.04
,Harmonic 101 (-1.184) 2.72
,Harmonic 102 (-1.073) 0.49
,Harmonic 103 (-0.849) 0.47
,Harmonic 104 1.216 2.12
,Harmonic 105 1.185 1.93
,Harmonic 106 2.53 1.94
,Harmonic 107 2.592 1.94
,Harmonic 108 2.757 1.54
,Harmonic 109 2.367 0.8
,Harmonic 110 (-3.014) 0.81]
note7 :: Note
note7 = Note
(Pitch 97.999 31 "g2")
8
(Range
(NoteRange
(NoteRangeAmplitude 6761.93 69 2.0e-2)
(NoteRangeHarmonicFreq 1 97.99))
(NoteRange
(NoteRangeAmplitude 195.99 2 3061.0)
(NoteRangeHarmonicFreq 101 9897.89)))
[Harmonic 1 3.8e-2 869.26
,Harmonic 2 1.707 3061.0
,Harmonic 3 1.451 995.4
,Harmonic 4 0.203 454.03
,Harmonic 5 (-2.88) 445.23
,Harmonic 6 2.171 304.87
,Harmonic 7 2.913 455.73
,Harmonic 8 0.278 91.1
,Harmonic 9 1.709 111.8
,Harmonic 10 (-1.632) 172.75
,Harmonic 11 1.481 138.83
,Harmonic 12 2.222 53.58
,Harmonic 13 2.191 37.33
,Harmonic 14 1.35 116.87
,Harmonic 15 1.144 91.46
,Harmonic 16 1.7e-2 28.04
,Harmonic 17 0.18 270.36
,Harmonic 18 (-0.899) 20.75
,Harmonic 19 (-0.846) 175.71
,Harmonic 20 2.765 296.9
,Harmonic 21 0.723 59.53
,Harmonic 22 0.295 98.52
,Harmonic 23 (-2.298) 240.1
,Harmonic 24 1.935 61.43
,Harmonic 25 (-1.384) 89.33
,Harmonic 26 (-1.022) 6.89
,Harmonic 27 2.809 33.0
,Harmonic 28 (-0.262) 51.68
,Harmonic 29 1.151 58.47
,Harmonic 30 (-1.876) 25.96
,Harmonic 31 (-0.413) 39.8
,Harmonic 32 (-1.405) 5.65
,Harmonic 33 2.942 19.41
,Harmonic 34 (-0.515) 17.0
,Harmonic 35 (-1.856) 29.45
,Harmonic 36 1.71 15.15
,Harmonic 37 0.285 4.3
,Harmonic 38 1.451 4.53
,Harmonic 39 1.178 3.96
,Harmonic 40 (-2.772) 3.84
,Harmonic 41 2.556 4.52
,Harmonic 42 (-1.615) 3.84
,Harmonic 43 1.435 4.78
,Harmonic 44 (-2.744) 1.9
,Harmonic 45 0.525 4.69
,Harmonic 46 (-1.927) 6.63
,Harmonic 47 2.349 3.72
,Harmonic 48 1.687 5.65
,Harmonic 49 (-1.509) 2.91
,Harmonic 50 2.726 3.76
,Harmonic 51 0.993 5.89
,Harmonic 52 (-1.588) 6.01
,Harmonic 53 (-0.799) 2.16
,Harmonic 54 1.492 3.34
,Harmonic 55 1.617 2.57
,Harmonic 56 0.106 0.64
,Harmonic 57 1.7 1.71
,Harmonic 58 1.55 1.3
,Harmonic 59 (-1.327) 0.96
,Harmonic 60 2.235 1.96
,Harmonic 61 (-0.407) 4.05
,Harmonic 62 2.592 3.37
,Harmonic 63 2.326 1.64
,Harmonic 64 1.535 0.86
,Harmonic 65 2.982 0.69
,Harmonic 66 0.34 3.0
,Harmonic 67 (-2.6) 2.55
,Harmonic 68 2.968 0.96
,Harmonic 69 (-2.352) 2.0e-2
,Harmonic 70 0.306 1.29
,Harmonic 71 (-1.461) 2.19
,Harmonic 72 2.373 4.57
,Harmonic 73 0.21 3.16
,Harmonic 74 (-1.703) 1.65
,Harmonic 75 2.192 1.22
,Harmonic 76 1.303 1.73
,Harmonic 77 (-0.763) 1.44
,Harmonic 78 2.969 0.94
,Harmonic 79 0.604 0.68
,Harmonic 80 (-1.864) 0.23
,Harmonic 81 (-3.036) 0.43
,Harmonic 82 (-0.363) 1.95
,Harmonic 83 (-2.025) 2.49
,Harmonic 84 1.493 1.51
,Harmonic 85 (-0.175) 1.85
,Harmonic 86 (-2.41) 2.77
,Harmonic 87 1.063 1.62
,Harmonic 88 (-1.575) 1.0
,Harmonic 89 0.579 0.27
,Harmonic 90 1.99 0.1
,Harmonic 91 0.216 0.38
,Harmonic 92 (-2.211) 0.85
,Harmonic 93 2.167 0.65
,Harmonic 94 0.196 0.59
,Harmonic 95 0.236 0.3
,Harmonic 96 (-2.682) 0.16
,Harmonic 97 (-2.276) 1.2
,Harmonic 98 1.9 1.57
,Harmonic 99 (-0.303) 0.23
,Harmonic 100 1.274 0.45
,Harmonic 101 (-2.225) 0.33]
note8 :: Note
note8 = Note
(Pitch 103.826 32 "g#2")
9
(Range
(NoteRange
(NoteRangeAmplitude 8513.73 82 0.11)
(NoteRangeHarmonicFreq 1 103.82))
(NoteRange
(NoteRangeAmplitude 207.65 2 4861.0)
(NoteRangeHarmonicFreq 96 9967.29)))
[Harmonic 1 (-2.776) 301.38
,Harmonic 2 1.473 4861.0
,Harmonic 3 (-2.351) 379.89
,Harmonic 4 2.839 181.4
,Harmonic 5 0.37 118.15
,Harmonic 6 1.871 5.21
,Harmonic 7 (-2.645) 63.81
,Harmonic 8 (-0.903) 114.78
,Harmonic 9 0.987 116.03
,Harmonic 10 0.628 55.42
,Harmonic 11 1.081 54.95
,Harmonic 12 (-0.628) 26.58
,Harmonic 13 0.113 44.53
,Harmonic 14 (-1.143) 96.16
,Harmonic 15 2.787 65.15
,Harmonic 16 (-2.317) 67.59
,Harmonic 17 0.518 46.69
,Harmonic 18 (-1.411) 24.31
,Harmonic 19 0.249 144.27
,Harmonic 20 (-0.31) 32.47
,Harmonic 21 (-0.503) 38.23
,Harmonic 22 (-0.713) 47.94
,Harmonic 23 1.894 27.57
,Harmonic 24 1.694 39.97
,Harmonic 25 (-2.353) 6.29
,Harmonic 26 1.537 17.35
,Harmonic 27 2.066 10.51
,Harmonic 28 0.756 3.4
,Harmonic 29 3.123 15.94
,Harmonic 30 (-1.52) 9.68
,Harmonic 31 (-1.157) 13.72
,Harmonic 32 (-0.14) 4.43
,Harmonic 33 1.422 2.58
,Harmonic 34 3.037 2.49
,Harmonic 35 (-2.537) 9.17
,Harmonic 36 (-2.672) 4.36
,Harmonic 37 (-0.795) 2.06
,Harmonic 38 (-1.216) 0.42
,Harmonic 39 1.11 1.36
,Harmonic 40 (-1.54) 1.9
,Harmonic 41 (-1.571) 1.39
,Harmonic 42 (-1.18) 4.13
,Harmonic 43 1.273 2.84
,Harmonic 44 3.106 0.95
,Harmonic 45 (-1.218) 1.86
,Harmonic 46 0.488 2.74
,Harmonic 47 1.16 1.52
,Harmonic 48 (-0.915) 1.03
,Harmonic 49 (-1.906) 1.33
,Harmonic 50 1.149 0.9
,Harmonic 51 (-1.323) 0.33
,Harmonic 52 1.291 0.77
,Harmonic 53 2.287 0.65
,Harmonic 54 (-0.979) 0.61
,Harmonic 55 2.718 0.2
,Harmonic 56 (-2.53) 0.77
,Harmonic 57 (-1.079) 0.53
,Harmonic 58 0.589 0.95
,Harmonic 59 2.418 0.71
,Harmonic 60 2.904 0.54
,Harmonic 61 (-1.424) 0.39
,Harmonic 62 (-0.289) 0.69
,Harmonic 63 0.335 1.43
,Harmonic 64 1.665 1.69
,Harmonic 65 (-2.239) 0.68
,Harmonic 66 (-1.711) 0.68
,Harmonic 67 (-2.575) 0.32
,Harmonic 68 (-1.164) 0.92
,Harmonic 69 0.567 0.61
,Harmonic 70 2.888 0.26
,Harmonic 71 (-0.386) 0.57
,Harmonic 72 0.195 1.27
,Harmonic 73 1.357 0.4
,Harmonic 74 (-1.943) 0.53
,Harmonic 75 (-1.428) 0.38
,Harmonic 76 0.429 1.51
,Harmonic 77 2.225 0.84
,Harmonic 78 (-2.074) 0.58
,Harmonic 79 0.709 0.43
,Harmonic 80 1.034 0.52
,Harmonic 81 (-1.681) 0.47
,Harmonic 82 (-2.118) 0.11
,Harmonic 83 3.026 0.31
,Harmonic 84 (-1.475) 0.9
,Harmonic 85 (-0.352) 0.22
,Harmonic 86 3.037 0.31
,Harmonic 87 (-2.484) 0.28
,Harmonic 88 (-2.307) 0.47
,Harmonic 89 (-1.451) 0.34
,Harmonic 90 0.954 0.3
,Harmonic 91 (-2.253) 0.13
,Harmonic 92 (-0.989) 0.42
,Harmonic 93 0.508 0.16
,Harmonic 94 1.312 0.24
,Harmonic 95 (-2.598) 0.46
,Harmonic 96 (-1.156) 0.66]
note9 :: Note
note9 = Note
(Pitch 110.0 33 "a2")
10
(Range
(NoteRange
(NoteRangeAmplitude 6160.0 56 8.0e-2)
(NoteRangeHarmonicFreq 1 110.0))
(NoteRange
(NoteRangeAmplitude 220.0 2 2805.0)
(NoteRangeHarmonicFreq 90 9900.0)))
[Harmonic 1 (-1.273) 437.78
,Harmonic 2 (-1.391) 2805.0
,Harmonic 3 0.832 443.14
,Harmonic 4 (-3.059) 824.72
,Harmonic 5 (-1.689) 75.86
,Harmonic 6 1.374 244.56
,Harmonic 7 (-2.221) 139.78
,Harmonic 8 2.28 129.59
,Harmonic 9 (-0.709) 37.17
,Harmonic 10 (-2.603) 59.11
,Harmonic 11 (-2.021) 31.44
,Harmonic 12 0.658 84.4
,Harmonic 13 1.216 125.02
,Harmonic 14 0.163 28.76
,Harmonic 15 (-2.2) 181.75
,Harmonic 16 1.706 51.03
,Harmonic 17 1.051 28.7
,Harmonic 18 (-3.0e-3) 7.27
,Harmonic 19 (-2.951) 14.44
,Harmonic 20 (-0.7) 67.62
,Harmonic 21 (-1.556) 24.14
,Harmonic 22 (-1.285) 35.08
,Harmonic 23 (-1.569) 16.63
,Harmonic 24 (-3.041) 18.08
,Harmonic 25 (-1.441) 8.99
,Harmonic 26 (-0.43) 6.29
,Harmonic 27 2.69 7.96
,Harmonic 28 8.5e-2 8.57
,Harmonic 29 2.216 14.01
,Harmonic 30 (-1.161) 0.79
,Harmonic 31 (-2.66) 1.47
,Harmonic 32 (-1.269) 2.21
,Harmonic 33 (-2.957) 3.11
,Harmonic 34 0.143 1.29
,Harmonic 35 2.25 0.66
,Harmonic 36 1.133 1.64
,Harmonic 37 (-1.794) 0.97
,Harmonic 38 (-0.346) 1.47
,Harmonic 39 (-0.172) 1.96
,Harmonic 40 (-1.801) 0.55
,Harmonic 41 1.823 0.69
,Harmonic 42 (-3.9e-2) 0.4
,Harmonic 43 0.879 0.9
,Harmonic 44 2.861 0.42
,Harmonic 45 1.276 1.44
,Harmonic 46 (-2.326) 1.11
,Harmonic 47 (-2.0) 0.48
,Harmonic 48 1.251 0.24
,Harmonic 49 (-0.423) 0.41
,Harmonic 50 1.225 0.34
,Harmonic 51 (-0.957) 0.37
,Harmonic 52 1.095 0.26
,Harmonic 53 1.959 0.19
,Harmonic 54 (-2.275) 0.54
,Harmonic 55 0.691 1.1
,Harmonic 56 1.13 8.0e-2
,Harmonic 57 (-3.126) 0.47
,Harmonic 58 (-0.54) 0.41
,Harmonic 59 0.305 0.75
,Harmonic 60 (-2.5) 0.56
,Harmonic 61 0.498 0.3
,Harmonic 62 (-1.326) 0.28
,Harmonic 63 (-0.964) 0.32
,Harmonic 64 0.292 0.74
,Harmonic 65 1.655 0.52
,Harmonic 66 (-2.108) 0.32
,Harmonic 67 (-1.774) 0.43
,Harmonic 68 1.153 0.11
,Harmonic 69 (-1.947) 0.76
,Harmonic 70 (-2.92) 0.18
,Harmonic 71 1.8e-2 0.52
,Harmonic 72 (-0.128) 0.67
,Harmonic 73 2.489 0.53
,Harmonic 74 1.625 0.23
,Harmonic 75 (-0.934) 1.29
,Harmonic 76 1.924 1.31
,Harmonic 77 (-1.288) 0.38
,Harmonic 78 2.144 0.3
,Harmonic 79 (-0.565) 0.21
,Harmonic 80 0.315 0.36
,Harmonic 81 2.702 0.42
,Harmonic 82 5.6e-2 0.35
,Harmonic 83 (-0.999) 0.6
,Harmonic 84 2.297 0.44
,Harmonic 85 (-1.159) 1.14
,Harmonic 86 2.876 0.89
,Harmonic 87 (-0.138) 0.39
,Harmonic 88 3.022 1.06
,Harmonic 89 0.141 1.03
,Harmonic 90 (-2.659) 1.2]
note10 :: Note
note10 = Note
(Pitch 116.541 34 "a#2")
11
(Range
(NoteRange
(NoteRangeAmplitude 8857.11 76 0.15)
(NoteRangeHarmonicFreq 1 116.54))
(NoteRange
(NoteRangeAmplitude 233.08 2 2508.0)
(NoteRangeHarmonicFreq 85 9905.98)))
[Harmonic 1 0.654 627.45
,Harmonic 2 1.415 2508.0
,Harmonic 3 1.252 968.41
,Harmonic 4 (-2.859) 306.08
,Harmonic 5 (-2.642) 177.27
,Harmonic 6 (-0.936) 315.25
,Harmonic 7 (-1.113) 84.82
,Harmonic 8 (-2.649) 559.02
,Harmonic 9 1.212 172.45
,Harmonic 10 2.865 74.07
,Harmonic 11 2.51 103.89
,Harmonic 12 2.27 57.96
,Harmonic 13 (-2.455) 145.78
,Harmonic 14 1.534 182.15
,Harmonic 15 (-2.885) 306.75
,Harmonic 16 (-0.53) 51.06
,Harmonic 17 1.697 150.7
,Harmonic 18 (-1.075) 106.87
,Harmonic 19 1.726 114.83
,Harmonic 20 (-1.813) 183.63
,Harmonic 21 (-2.038) 78.7
,Harmonic 22 2.364 6.03
,Harmonic 23 (-0.469) 7.54
,Harmonic 24 2.43 31.68
,Harmonic 25 1.609 4.42
,Harmonic 26 (-0.936) 8.83
,Harmonic 27 (-1.107) 7.18
,Harmonic 28 2.745 10.52
,Harmonic 29 (-9.4e-2) 1.08
,Harmonic 30 (-2.168) 8.4
,Harmonic 31 1.1e-2 7.28
,Harmonic 32 1.941 4.75
,Harmonic 33 1.183 4.05
,Harmonic 34 (-2.917) 1.11
,Harmonic 35 (-2.732) 0.65
,Harmonic 36 (-2.576) 6.22
,Harmonic 37 (-1.129) 3.08
,Harmonic 38 1.816 1.2
,Harmonic 39 2.644 2.85
,Harmonic 40 9.0e-3 1.24
,Harmonic 41 1.514 3.3
,Harmonic 42 2.018 2.0
,Harmonic 43 (-0.525) 1.83
,Harmonic 44 (-1.235) 1.24
,Harmonic 45 1.516 1.13
,Harmonic 46 (-7.1e-2) 1.14
,Harmonic 47 0.139 0.87
,Harmonic 48 (-1.305) 0.42
,Harmonic 49 (-2.197) 0.98
,Harmonic 50 (-2.13) 3.69
,Harmonic 51 2.364 0.98
,Harmonic 52 2.75 1.09
,Harmonic 53 0.991 2.71
,Harmonic 54 0.541 1.49
,Harmonic 55 0.484 0.76
,Harmonic 56 (-0.973) 0.24
,Harmonic 57 2.759 2.54
,Harmonic 58 1.688 1.76
,Harmonic 59 0.817 0.62
,Harmonic 60 1.004 1.1
,Harmonic 61 0.728 1.16
,Harmonic 62 (-0.285) 0.51
,Harmonic 63 0.377 0.67
,Harmonic 64 0.192 0.97
,Harmonic 65 (-1.598) 1.71
,Harmonic 66 (-1.809) 1.32
,Harmonic 67 3.03 2.03
,Harmonic 68 1.416 3.3
,Harmonic 69 (-2.1e-2) 1.48
,Harmonic 70 (-0.514) 0.42
,Harmonic 71 (-0.455) 1.14
,Harmonic 72 (-2.167) 0.91
,Harmonic 73 (-2.88) 1.17
,Harmonic 74 1.755 0.71
,Harmonic 75 (-2.422) 0.21
,Harmonic 76 0.714 0.15
,Harmonic 77 (-0.755) 0.67
,Harmonic 78 (-2.863) 1.79
,Harmonic 79 5.1e-2 1.03
,Harmonic 80 (-1.178) 1.47
,Harmonic 81 2.193 1.17
,Harmonic 82 (-0.191) 0.8
,Harmonic 83 (-0.963) 0.95
,Harmonic 84 (-2.028) 1.19
,Harmonic 85 (-3.021) 1.15]
note11 :: Note
note11 = Note
(Pitch 123.471 35 "b2")
12
(Range
(NoteRange
(NoteRangeAmplitude 9507.26 77 0.29)
(NoteRangeHarmonicFreq 1 123.47))
(NoteRange
(NoteRangeAmplitude 246.94 2 3056.0)
(NoteRangeHarmonicFreq 81 10001.15)))
[Harmonic 1 (-2.924) 982.29
,Harmonic 2 0.511 3056.0
,Harmonic 3 (-1.76) 1438.07
,Harmonic 4 (-2.941) 981.65
,Harmonic 5 (-2.178) 379.84
,Harmonic 6 (-2.788) 239.35
,Harmonic 7 (-0.679) 184.59
,Harmonic 8 (-1.219) 502.05
,Harmonic 9 (-1.252) 942.21
,Harmonic 10 (-0.87) 407.76
,Harmonic 11 (-2.259) 499.1
,Harmonic 12 1.552 168.28
,Harmonic 13 2.659 99.23
,Harmonic 14 0.134 394.64
,Harmonic 15 1.486 294.94
,Harmonic 16 3.084 857.52
,Harmonic 17 2.207 169.37
,Harmonic 18 0.877 142.89
,Harmonic 19 2.378 228.5
,Harmonic 20 (-1.617) 159.27
,Harmonic 21 2.8e-2 8.31
,Harmonic 22 (-2.633) 152.58
,Harmonic 23 (-0.791) 33.37
,Harmonic 24 0.365 31.12
,Harmonic 25 (-0.1) 16.04
,Harmonic 26 0.404 68.97
,Harmonic 27 (-0.804) 17.39
,Harmonic 28 2.478 9.49
,Harmonic 29 2.598 10.62
,Harmonic 30 (-2.625) 21.91
,Harmonic 31 (-2.44) 4.88
,Harmonic 32 (-1.727) 13.04
,Harmonic 33 (-0.102) 4.87
,Harmonic 34 0.293 12.23
,Harmonic 35 (-1.837) 0.99
,Harmonic 36 (-2.627) 2.31
,Harmonic 37 3.03 10.99
,Harmonic 38 (-2.516) 8.49
,Harmonic 39 (-1.218) 10.21
,Harmonic 40 1.368 6.2
,Harmonic 41 (-0.767) 10.3
,Harmonic 42 (-1.556) 2.65
,Harmonic 43 1.91 5.22
,Harmonic 44 (-0.319) 2.53
,Harmonic 45 (-1.899) 1.26
,Harmonic 46 1.509 3.22
,Harmonic 47 1.83 2.29
,Harmonic 48 (-3.085) 5.59
,Harmonic 49 (-1.893) 11.82
,Harmonic 50 (-1.4e-2) 9.21
,Harmonic 51 2.181 5.64
,Harmonic 52 (-2.756) 4.79
,Harmonic 53 1.347 2.82
,Harmonic 54 2.532 7.61
,Harmonic 55 (-0.492) 8.56
,Harmonic 56 0.989 2.27
,Harmonic 57 (-1.023) 3.89
,Harmonic 58 1.289 7.33
,Harmonic 59 (-2.939) 1.93
,Harmonic 60 (-1.133) 0.81
,Harmonic 61 (-1.319) 2.23
,Harmonic 62 1.372 3.45
,Harmonic 63 (-0.175) 1.51
,Harmonic 64 (-1.296) 4.96
,Harmonic 65 0.563 2.79
,Harmonic 66 2.967 3.47
,Harmonic 67 (-1.776) 1.46
,Harmonic 68 0.414 4.52
,Harmonic 69 (-0.701) 0.93
,Harmonic 70 (-2.765) 1.18
,Harmonic 71 0.799 1.8
,Harmonic 72 2.86 0.99
,Harmonic 73 (-1.093) 3.7
,Harmonic 74 0.12 2.17
,Harmonic 75 (-2.287) 0.37
,Harmonic 76 (-0.861) 2.15
,Harmonic 77 0.332 0.29
,Harmonic 78 (-2.926) 0.85
,Harmonic 79 (-0.645) 2.61
,Harmonic 80 0.193 2.92
,Harmonic 81 1.497 3.62]
note12 :: Note
note12 = Note
(Pitch 130.813 36 "c3")
13
(Range
(NoteRange
(NoteRangeAmplitude 9680.16 74 0.42)
(NoteRangeHarmonicFreq 1 130.81))
(NoteRange
(NoteRangeAmplitude 392.43 3 1970.0)
(NoteRangeHarmonicFreq 75 9810.97)))
[Harmonic 1 2.035 283.99
,Harmonic 2 2.097 1048.22
,Harmonic 3 1.016 1970.0
,Harmonic 4 1.824 262.41
,Harmonic 5 2.117 624.38
,Harmonic 6 1.86 210.66
,Harmonic 7 (-1.966) 889.72
,Harmonic 8 0.875 544.99
,Harmonic 9 (-1.357) 439.13
,Harmonic 10 0.151 327.55
,Harmonic 11 (-3.07) 267.23
,Harmonic 12 2.614 214.9
,Harmonic 13 1.651 745.92
,Harmonic 14 (-2.391) 140.71
,Harmonic 15 2.94 458.83
,Harmonic 16 3.115 60.97
,Harmonic 17 1.204 259.66
,Harmonic 18 0.971 185.88
,Harmonic 19 (-2.514) 19.64
,Harmonic 20 2.554 7.16
,Harmonic 21 1.131 102.3
,Harmonic 22 (-1.106) 40.55
,Harmonic 23 (-1.729) 47.64
,Harmonic 24 2.352 12.44
,Harmonic 25 0.897 28.02
,Harmonic 26 (-0.487) 8.68
,Harmonic 27 (-0.412) 36.85
,Harmonic 28 (-1.796) 23.77
,Harmonic 29 1.08 4.21
,Harmonic 30 0.249 8.92
,Harmonic 31 1.768 7.65
,Harmonic 32 (-2.842) 13.2
,Harmonic 33 (-1.503) 15.37
,Harmonic 34 (-1.419) 3.52
,Harmonic 35 (-2.928) 9.72
,Harmonic 36 2.39 5.68
,Harmonic 37 (-0.811) 11.7
,Harmonic 38 0.303 16.31
,Harmonic 39 (-0.488) 3.04
,Harmonic 40 (-2.51) 7.47
,Harmonic 41 2.388 3.54
,Harmonic 42 (-0.761) 3.37
,Harmonic 43 (-0.363) 6.5
,Harmonic 44 (-2.625) 2.6
,Harmonic 45 (-2.469) 10.73
,Harmonic 46 2.851 8.76
,Harmonic 47 (-0.468) 4.87
,Harmonic 48 1.289 3.9
,Harmonic 49 (-2.185) 3.37
,Harmonic 50 (-0.61) 2.61
,Harmonic 51 0.977 1.19
,Harmonic 52 1.99 1.3
,Harmonic 53 (-0.974) 1.89
,Harmonic 54 3.041 0.57
,Harmonic 55 (-0.828) 1.87
,Harmonic 56 2.477 3.0
,Harmonic 57 (-0.418) 0.93
,Harmonic 58 (-1.278) 4.66
,Harmonic 59 1.274 2.35
,Harmonic 60 1.957 3.96
,Harmonic 61 (-1.558) 1.91
,Harmonic 62 (-2.337) 3.49
,Harmonic 63 (-1.716) 1.32
,Harmonic 64 2.747 1.07
,Harmonic 65 (-2.754) 1.66
,Harmonic 66 0.55 0.68
,Harmonic 67 (-0.37) 0.57
,Harmonic 68 (-0.79) 1.29
,Harmonic 69 0.511 1.32
,Harmonic 70 1.65 0.65
,Harmonic 71 (-2.778) 2.86
,Harmonic 72 (-2.137) 1.83
,Harmonic 73 (-1.714) 1.49
,Harmonic 74 2.512 0.42
,Harmonic 75 1.516 1.26]
note13 :: Note
note13 = Note
(Pitch 138.591 37 "c#3")
14
(Range
(NoteRange
(NoteRangeAmplitude 9285.59 67 0.23)
(NoteRangeHarmonicFreq 1 138.59))
(NoteRange
(NoteRangeAmplitude 277.18 2 1509.0)
(NoteRangeHarmonicFreq 70 9701.37)))
[Harmonic 1 (-2.58) 1259.54
,Harmonic 2 0.29 1509.0
,Harmonic 3 1.783 1090.02
,Harmonic 4 2.416 176.82
,Harmonic 5 2.026 299.06
,Harmonic 6 1.524 345.94
,Harmonic 7 1.507 150.73
,Harmonic 8 (-7.8e-2) 174.9
,Harmonic 9 (-3.099) 59.07
,Harmonic 10 1.937 25.07
,Harmonic 11 (-1.016) 155.26
,Harmonic 12 (-0.743) 286.71
,Harmonic 13 0.316 94.2
,Harmonic 14 0.84 200.11
,Harmonic 15 (-2.886) 122.21
,Harmonic 16 0.178 69.9
,Harmonic 17 (-2.754) 102.05
,Harmonic 18 2.559 72.2
,Harmonic 19 2.086 51.94
,Harmonic 20 2.116 14.09
,Harmonic 21 (-0.666) 42.18
,Harmonic 22 0.765 16.83
,Harmonic 23 0.918 28.5
,Harmonic 24 0.781 12.15
,Harmonic 25 1.427 2.97
,Harmonic 26 1.729 13.31
,Harmonic 27 2.276 9.79
,Harmonic 28 (-2.494) 3.13
,Harmonic 29 (-2.604) 4.05
,Harmonic 30 2.55 0.29
,Harmonic 31 1.642 2.11
,Harmonic 32 (-0.609) 1.41
,Harmonic 33 0.595 2.86
,Harmonic 34 (-3.113) 8.88
,Harmonic 35 (-1.927) 7.95
,Harmonic 36 (-0.319) 7.34
,Harmonic 37 0.608 2.13
,Harmonic 38 2.6e-2 0.29
,Harmonic 39 (-2.341) 0.52
,Harmonic 40 (-0.804) 0.45
,Harmonic 41 (-3.139) 0.63
,Harmonic 42 (-2.568) 0.89
,Harmonic 43 0.18 0.93
,Harmonic 44 1.53 1.36
,Harmonic 45 (-1.821) 1.23
,Harmonic 46 5.6e-2 1.89
,Harmonic 47 2.329 2.76
,Harmonic 48 3.138 2.02
,Harmonic 49 0.153 0.68
,Harmonic 50 2.817 1.57
,Harmonic 51 (-1.371) 1.58
,Harmonic 52 (-8.3e-2) 2.49
,Harmonic 53 1.559 1.69
,Harmonic 54 (-2.562) 2.22
,Harmonic 55 (-0.977) 1.22
,Harmonic 56 (-0.498) 1.13
,Harmonic 57 (-0.269) 3.08
,Harmonic 58 2.4e-2 1.51
,Harmonic 59 (-0.604) 0.32
,Harmonic 60 0.335 1.15
,Harmonic 61 1.875 0.48
,Harmonic 62 (-2.165) 0.38
,Harmonic 63 0.426 0.38
,Harmonic 64 (-2.899) 0.67
,Harmonic 65 (-0.584) 1.27
,Harmonic 66 2.611 0.28
,Harmonic 67 (-1.547) 0.23
,Harmonic 68 0.94 0.46
,Harmonic 69 (-1.825) 1.24
,Harmonic 70 0.73 0.95]
note14 :: Note
note14 = Note
(Pitch 146.832 38 "d3")
15
(Range
(NoteRange
(NoteRangeAmplitude 7488.43 51 8.0e-2)
(NoteRangeHarmonicFreq 1 146.83))
(NoteRange
(NoteRangeAmplitude 146.83 1 2520.0)
(NoteRangeHarmonicFreq 67 9837.74)))
[Harmonic 1 (-2.106) 2520.0
,Harmonic 2 1.143 2318.63
,Harmonic 3 (-2.702) 1121.61
,Harmonic 4 (-0.28) 973.88
,Harmonic 5 0.137 658.9
,Harmonic 6 (-2.969) 333.33
,Harmonic 7 (-2.422) 187.42
,Harmonic 8 0.24 117.87
,Harmonic 9 1.684 184.48
,Harmonic 10 (-0.536) 136.54
,Harmonic 11 (-1.493) 280.4
,Harmonic 12 (-1.078) 108.93
,Harmonic 13 (-1.8e-2) 214.23
,Harmonic 14 (-1.704) 166.39
,Harmonic 15 2.132 99.13
,Harmonic 16 (-2.38) 28.13
,Harmonic 17 2.754 18.19
,Harmonic 18 6.1e-2 22.07
,Harmonic 19 1.291 31.88
,Harmonic 20 (-2.128) 63.49
,Harmonic 21 0.125 27.2
,Harmonic 22 0.471 18.81
,Harmonic 23 (-2.289) 6.71
,Harmonic 24 2.614 11.07
,Harmonic 25 3.016 16.28
,Harmonic 26 (-1.674) 7.06
,Harmonic 27 (-0.322) 6.61
,Harmonic 28 0.402 2.35
,Harmonic 29 3.117 1.2
,Harmonic 30 2.751 1.27
,Harmonic 31 0.564 4.8
,Harmonic 32 2.304 5.58
,Harmonic 33 (-2.846) 3.79
,Harmonic 34 0.325 1.09
,Harmonic 35 1.779 1.51
,Harmonic 36 (-0.66) 3.53
,Harmonic 37 2.301 1.78
,Harmonic 38 2.35 1.07
,Harmonic 39 (-2.38) 1.74
,Harmonic 40 (-1.412) 0.66
,Harmonic 41 (-2.121) 2.69
,Harmonic 42 0.777 0.78
,Harmonic 43 (-1.615) 2.04
,Harmonic 44 1.215 1.84
,Harmonic 45 (-3.04) 1.68
,Harmonic 46 (-0.416) 0.8
,Harmonic 47 3.029 1.18
,Harmonic 48 (-0.836) 1.24
,Harmonic 49 3.124 1.05
,Harmonic 50 (-0.932) 1.57
,Harmonic 51 1.763 8.0e-2
,Harmonic 52 (-0.898) 0.91
,Harmonic 53 (-0.393) 0.95
,Harmonic 54 1.55 1.85
,Harmonic 55 (-1.16) 0.93
,Harmonic 56 1.6 1.73
,Harmonic 57 (-2.703) 0.9
,Harmonic 58 2.17 0.36
,Harmonic 59 2.86 1.13
,Harmonic 60 (-0.786) 0.58
,Harmonic 61 2.336 0.67
,Harmonic 62 (-1.942) 1.53
,Harmonic 63 0.744 0.42
,Harmonic 64 (-1.729) 0.97
,Harmonic 65 1.468 1.03
,Harmonic 66 (-2.705) 1.02
,Harmonic 67 (-0.174) 1.26]
note15 :: Note
note15 = Note
(Pitch 155.563 39 "d#3")
16
(Range
(NoteRange
(NoteRangeAmplitude 9800.46 63 0.12)
(NoteRangeHarmonicFreq 1 155.56))
(NoteRange
(NoteRangeAmplitude 155.56 1 2945.0)
(NoteRangeHarmonicFreq 64 9956.03)))
[Harmonic 1 (-2.258) 2945.0
,Harmonic 2 0.545 2434.01
,Harmonic 3 1.59 569.56
,Harmonic 4 0.969 380.78
,Harmonic 5 0.176 251.46
,Harmonic 6 (-3.134) 291.76
,Harmonic 7 2.056 97.8
,Harmonic 8 3.072 44.27
,Harmonic 9 2.465 57.31
,Harmonic 10 0.28 177.9
,Harmonic 11 2.307 124.62
,Harmonic 12 2.26 125.09
,Harmonic 13 0.925 14.72
,Harmonic 14 (-2.194) 33.22
,Harmonic 15 (-0.221) 36.2
,Harmonic 16 1.262 48.51
,Harmonic 17 (-1.517) 12.22
,Harmonic 18 2.918 10.47
,Harmonic 19 1.446 16.24
,Harmonic 20 (-1.865) 8.44
,Harmonic 21 (-2.544) 3.77
,Harmonic 22 0.681 2.38
,Harmonic 23 (-0.721) 3.4
,Harmonic 24 0.48 5.14
,Harmonic 25 2.814 1.87
,Harmonic 26 2.812 3.2
,Harmonic 27 2.677 0.45
,Harmonic 28 (-2.66) 1.39
,Harmonic 29 (-2.924) 0.56
,Harmonic 30 (-1.568) 1.19
,Harmonic 31 1.805 2.87
,Harmonic 32 (-1.028) 1.15
,Harmonic 33 (-2.247) 0.35
,Harmonic 34 1.812 0.42
,Harmonic 35 (-0.909) 0.15
,Harmonic 36 2.516 0.55
,Harmonic 37 (-0.167) 0.5
,Harmonic 38 (-2.09) 0.34
,Harmonic 39 (-0.364) 0.52
,Harmonic 40 7.0e-3 0.2
,Harmonic 41 (-2.403) 0.66
,Harmonic 42 1.376 0.46
,Harmonic 43 (-2.414) 0.78
,Harmonic 44 (-0.968) 0.5
,Harmonic 45 1.21 0.21
,Harmonic 46 (-1.911) 0.19
,Harmonic 47 (-2.986) 0.61
,Harmonic 48 (-0.278) 0.9
,Harmonic 49 2.401 0.99
,Harmonic 50 (-2.328) 0.33
,Harmonic 51 (-2.131) 0.3
,Harmonic 52 0.172 0.2
,Harmonic 53 3.021 0.3
,Harmonic 54 (-1.81) 0.48
,Harmonic 55 2.244 0.36
,Harmonic 56 1.26 0.36
,Harmonic 57 1.932 0.13
,Harmonic 58 2.24 0.14
,Harmonic 59 2.721 0.54
,Harmonic 60 2.771 0.16
,Harmonic 61 5.3e-2 0.31
,Harmonic 62 2.527 0.65
,Harmonic 63 (-2.581) 0.12
,Harmonic 64 (-1.249) 0.16]
note16 :: Note
note16 = Note
(Pitch 164.814 40 "e3")
17
(Range
(NoteRange
(NoteRangeAmplitude 8075.88 49 0.27)
(NoteRangeHarmonicFreq 1 164.81))
(NoteRange
(NoteRangeAmplitude 164.81 1 4092.0)
(NoteRangeHarmonicFreq 60 9888.84)))
[Harmonic 1 (-1.552) 4092.0
,Harmonic 2 (-0.378) 712.58
,Harmonic 3 3.025 527.52
,Harmonic 4 (-1.355) 201.77
,Harmonic 5 2.335 100.8
,Harmonic 6 (-2.363) 64.28
,Harmonic 7 1.325 173.56
,Harmonic 8 1.946 161.04
,Harmonic 9 0.216 115.27
,Harmonic 10 (-2.275) 128.92
,Harmonic 11 (-1.821) 204.78
,Harmonic 12 1.336 140.94
,Harmonic 13 2.154 46.37
,Harmonic 14 1.3e-2 78.44
,Harmonic 15 (-2.319) 182.35
,Harmonic 16 (-0.94) 12.56
,Harmonic 17 1.141 67.62
,Harmonic 18 (-0.307) 87.89
,Harmonic 19 (-2.325) 23.23
,Harmonic 20 (-4.2e-2) 27.85
,Harmonic 21 (-2.186) 7.48
,Harmonic 22 (-1.762) 34.83
,Harmonic 23 1.198 16.97
,Harmonic 24 (-1.14) 12.02
,Harmonic 25 2.095 18.8
,Harmonic 26 (-1.53) 16.72
,Harmonic 27 1.197 12.61
,Harmonic 28 (-1.619) 0.87
,Harmonic 29 1.459 10.61
,Harmonic 30 1.123 4.05
,Harmonic 31 2.522 0.97
,Harmonic 32 0.965 5.85
,Harmonic 33 (-1.68) 9.67
,Harmonic 34 (-2.832) 4.7
,Harmonic 35 1.88 4.62
,Harmonic 36 2.396 4.11
,Harmonic 37 2.442 1.7
,Harmonic 38 0.859 3.87
,Harmonic 39 (-0.145) 3.67
,Harmonic 40 (-0.441) 2.38
,Harmonic 41 2.565 1.92
,Harmonic 42 1.455 0.37
,Harmonic 43 (-0.898) 1.17
,Harmonic 44 (-2.0) 1.49
,Harmonic 45 0.799 1.2
,Harmonic 46 1.577 1.44
,Harmonic 47 (-0.511) 2.63
,Harmonic 48 (-1.838) 0.75
,Harmonic 49 (-2.568) 0.27
,Harmonic 50 (-3.013) 1.24
,Harmonic 51 0.958 0.79
,Harmonic 52 2.241 1.76
,Harmonic 53 1.564 1.02
,Harmonic 54 (-2.8e-2) 1.01
,Harmonic 55 (-0.421) 1.19
,Harmonic 56 2.8 1.31
,Harmonic 57 (-1.35) 0.38
,Harmonic 58 1.001 1.07
,Harmonic 59 (-2.86) 0.77
,Harmonic 60 0.154 0.54]
note17 :: Note
note17 = Note
(Pitch 174.614 41 "f3")
18
(Range
(NoteRange
(NoteRangeAmplitude 9079.92 52 0.21)
(NoteRangeHarmonicFreq 1 174.61))
(NoteRange
(NoteRangeAmplitude 174.61 1 2059.0)
(NoteRangeHarmonicFreq 58 10127.61)))
[Harmonic 1 (-1.883) 2059.0
,Harmonic 2 (-0.832) 212.15
,Harmonic 3 2.736 217.84
,Harmonic 4 (-1.609) 504.86
,Harmonic 5 2.271 272.47
,Harmonic 6 2.151 318.97
,Harmonic 7 2.877 126.11
,Harmonic 8 (-0.114) 102.44
,Harmonic 9 (-0.82) 223.58
,Harmonic 10 2.337 618.96
,Harmonic 11 0.905 256.12
,Harmonic 12 (-0.779) 55.33
,Harmonic 13 (-1.677) 45.75
,Harmonic 14 2.866 29.23
,Harmonic 15 1.809 19.46
,Harmonic 16 1.9 24.27
,Harmonic 17 2.759 26.93
,Harmonic 18 (-0.632) 5.66
,Harmonic 19 (-1.216) 13.41
,Harmonic 20 (-2.831) 6.5
,Harmonic 21 (-2.858) 3.17
,Harmonic 22 (-2.715) 4.72
,Harmonic 23 (-2.555) 3.36
,Harmonic 24 (-2.62) 0.89
,Harmonic 25 2.425 3.97
,Harmonic 26 1.569 4.79
,Harmonic 27 0.909 5.04
,Harmonic 28 2.818 4.41
,Harmonic 29 2.574 1.97
,Harmonic 30 1.686 4.41
,Harmonic 31 (-1.007) 7.04
,Harmonic 32 (-1.267) 8.88
,Harmonic 33 (-7.2e-2) 8.81
,Harmonic 34 (-0.55) 14.92
,Harmonic 35 1.594 3.2
,Harmonic 36 0.767 2.6
,Harmonic 37 (-3.081) 6.25
,Harmonic 38 (-2.811) 10.59
,Harmonic 39 (-1.464) 27.53
,Harmonic 40 (-2.222) 12.09
,Harmonic 41 (-0.893) 4.33
,Harmonic 42 1.82 8.41
,Harmonic 43 2.054 5.09
,Harmonic 44 2.355 6.72
,Harmonic 45 2.611 4.7
,Harmonic 46 (-2.901) 7.93
,Harmonic 47 2.815 4.61
,Harmonic 48 2.29 2.78
,Harmonic 49 (-0.117) 1.89
,Harmonic 50 (-2.366) 2.05
,Harmonic 51 1.338 2.31
,Harmonic 52 (-2.508) 0.21
,Harmonic 53 0.323 0.81
,Harmonic 54 1.068 2.62
,Harmonic 55 0.505 1.11
,Harmonic 56 8.2e-2 0.68
,Harmonic 57 (-0.415) 1.1
,Harmonic 58 (-1.07) 1.33]
note18 :: Note
note18 = Note
(Pitch 184.997 42 "f#3")
19
(Range
(NoteRange
(NoteRangeAmplitude 9619.84 52 0.94)
(NoteRangeHarmonicFreq 1 184.99))
(NoteRange
(NoteRangeAmplitude 369.99 2 2313.0)
(NoteRangeHarmonicFreq 53 9804.84)))
[Harmonic 1 1.32 784.99
,Harmonic 2 1.773 2313.0
,Harmonic 3 0.434 448.21
,Harmonic 4 (-1.031) 504.16
,Harmonic 5 (-8.5e-2) 431.04
,Harmonic 6 1.805 506.61
,Harmonic 7 2.049 106.51
,Harmonic 8 2.676 103.43
,Harmonic 9 1.938 297.83
,Harmonic 10 1.941 36.75
,Harmonic 11 (-2.993) 112.32
,Harmonic 12 (-0.72) 238.99
,Harmonic 13 1.295 201.09
,Harmonic 14 2.846 143.66
,Harmonic 15 (-0.537) 115.14
,Harmonic 16 0.416 52.35
,Harmonic 17 2.082 90.14
,Harmonic 18 1.946 34.97
,Harmonic 19 (-1.152) 18.48
,Harmonic 20 (-1.628) 31.75
,Harmonic 21 (-0.23) 21.96
,Harmonic 22 (-2.3e-2) 18.43
,Harmonic 23 (-0.31) 9.02
,Harmonic 24 (-1.227) 4.57
,Harmonic 25 (-1.367) 3.64
,Harmonic 26 0.289 19.85
,Harmonic 27 3.119 13.18
,Harmonic 28 1.492 12.23
,Harmonic 29 2.155 6.95
,Harmonic 30 (-0.804) 2.12
,Harmonic 31 1.603 8.77
,Harmonic 32 (-0.791) 12.24
,Harmonic 33 2.025 8.85
,Harmonic 34 (-1.9) 7.58
,Harmonic 35 (-0.683) 8.45
,Harmonic 36 2.299 6.84
,Harmonic 37 (-2.331) 3.41
,Harmonic 38 (-0.86) 2.29
,Harmonic 39 1.689 1.32
,Harmonic 40 1.471 3.58
,Harmonic 41 (-2.942) 7.76
,Harmonic 42 (-1.143) 7.2
,Harmonic 43 0.15 2.39
,Harmonic 44 (-0.948) 1.44
,Harmonic 45 0.319 1.44
,Harmonic 46 3.09 1.73
,Harmonic 47 (-0.296) 3.27
,Harmonic 48 (-2.909) 2.35
,Harmonic 49 (-0.976) 4.41
,Harmonic 50 0.412 3.33
,Harmonic 51 2.522 2.33
,Harmonic 52 (-0.86) 0.94
,Harmonic 53 0.723 1.24]
note19 :: Note
note19 = Note
(Pitch 195.998 43 "g3")
20
(Range
(NoteRange
(NoteRangeAmplitude 7839.92 40 0.59)
(NoteRangeHarmonicFreq 1 195.99))
(NoteRange
(NoteRangeAmplitude 195.99 1 2747.0)
(NoteRangeHarmonicFreq 51 9995.89)))
[Harmonic 1 (-0.406) 2747.0
,Harmonic 2 2.858 1502.37
,Harmonic 3 2.217 516.56
,Harmonic 4 (-2.23) 229.66
,Harmonic 5 1.894 598.65
,Harmonic 6 0.119 471.0
,Harmonic 7 2.668 711.91
,Harmonic 8 0.806 396.45
,Harmonic 9 (-0.77) 334.04
,Harmonic 10 (-1.138) 411.14
,Harmonic 11 2.803 139.55
,Harmonic 12 (-1.188) 221.52
,Harmonic 13 (-3.128) 39.81
,Harmonic 14 (-0.713) 36.52
,Harmonic 15 1.683 136.49
,Harmonic 16 1.313 105.24
,Harmonic 17 (-3.084) 30.36
,Harmonic 18 (-3.046) 10.14
,Harmonic 19 (-1.947) 7.17
,Harmonic 20 (-2.598) 10.75
,Harmonic 21 2.433 16.2
,Harmonic 22 0.929 16.12
,Harmonic 23 (-0.223) 13.24
,Harmonic 24 2.666 19.29
,Harmonic 25 2.518 7.49
,Harmonic 26 (-0.82) 2.35
,Harmonic 27 (-1.706) 6.49
,Harmonic 28 1.324 5.12
,Harmonic 29 (-2.034) 1.36
,Harmonic 30 (-2.006) 4.38
,Harmonic 31 (-2.94) 6.62
,Harmonic 32 (-1.235) 3.46
,Harmonic 33 (-1.581) 7.96
,Harmonic 34 (-1.148) 2.1
,Harmonic 35 (-0.358) 1.49
,Harmonic 36 (-1.108) 3.42
,Harmonic 37 1.184 0.72
,Harmonic 38 (-2.855) 1.37
,Harmonic 39 (-0.465) 2.2
,Harmonic 40 0.644 0.59
,Harmonic 41 (-1.119) 1.63
,Harmonic 42 (-9.4e-2) 1.93
,Harmonic 43 2.339 2.54
,Harmonic 44 1.896 2.27
,Harmonic 45 2.018 2.18
,Harmonic 46 1.774 2.52
,Harmonic 47 0.353 2.59
,Harmonic 48 0.661 2.07
,Harmonic 49 2.503 1.01
,Harmonic 50 2.181 1.76
,Harmonic 51 3.007 4.29]
note20 :: Note
note20 = Note
(Pitch 207.652 44 "g#3")
21
(Range
(NoteRange
(NoteRangeAmplitude 7060.16 34 3.0e-2)
(NoteRangeHarmonicFreq 1 207.65))
(NoteRange
(NoteRangeAmplitude 207.65 1 6853.0)
(NoteRangeHarmonicFreq 47 9759.64)))
[Harmonic 1 (-1.439) 6853.0
,Harmonic 2 (-2.905) 794.89
,Harmonic 3 1.775 498.16
,Harmonic 4 (-1.839) 300.22
,Harmonic 5 (-2.162) 406.05
,Harmonic 6 (-0.685) 108.79
,Harmonic 7 (-2.533) 54.92
,Harmonic 8 2.934 221.44
,Harmonic 9 1.161 187.43
,Harmonic 10 (-1.853) 153.85
,Harmonic 11 2.663 189.73
,Harmonic 12 1.597 61.54
,Harmonic 13 (-0.323) 43.1
,Harmonic 14 (-0.26) 61.1
,Harmonic 15 (-1.131) 96.24
,Harmonic 16 1.689 4.46
,Harmonic 17 (-0.557) 17.6
,Harmonic 18 (-2.318) 16.16
,Harmonic 19 2.877 18.81
,Harmonic 20 1.987 12.58
,Harmonic 21 1.484 13.05
,Harmonic 22 (-2.759) 6.19
,Harmonic 23 (-2.076) 27.87
,Harmonic 24 1.55 11.17
,Harmonic 25 3.1 9.02
,Harmonic 26 1.113 4.81
,Harmonic 27 2.996 2.68
,Harmonic 28 2.437 7.93
,Harmonic 29 2.08 4.19
,Harmonic 30 (-2.947) 5.63
,Harmonic 31 (-2.048) 13.46
,Harmonic 32 5.2e-2 5.62
,Harmonic 33 (-0.39) 5.64
,Harmonic 34 0.54 3.0e-2
,Harmonic 35 (-1.087) 2.79
,Harmonic 36 (-0.686) 1.26
,Harmonic 37 0.775 3.78
,Harmonic 38 1.602 2.93
,Harmonic 39 2.909 4.76
,Harmonic 40 (-2.928) 1.42
,Harmonic 41 0.124 1.31
,Harmonic 42 1.226 1.15
,Harmonic 43 2.894 1.5
,Harmonic 44 (-2.277) 2.1
,Harmonic 45 (-1.446) 1.09
,Harmonic 46 (-1.778) 0.11
,Harmonic 47 (-3.089) 0.78]
note21 :: Note
note21 = Note
(Pitch 220.0 45 "a3")
22
(Range
(NoteRange
(NoteRangeAmplitude 9900.0 45 0.38)
(NoteRangeHarmonicFreq 1 220.0))
(NoteRange
(NoteRangeAmplitude 220.0 1 3290.0)
(NoteRangeHarmonicFreq 46 10120.0)))
[Harmonic 1 (-2.012) 3290.0
,Harmonic 2 0.623 439.43
,Harmonic 3 0.375 338.71
,Harmonic 4 (-0.419) 175.57
,Harmonic 5 0.647 267.76
,Harmonic 6 (-2.456) 32.21
,Harmonic 7 2.375 394.52
,Harmonic 8 (-0.945) 559.59
,Harmonic 9 8.3e-2 348.56
,Harmonic 10 0.428 88.6
,Harmonic 11 1.0 148.88
,Harmonic 12 (-0.251) 92.57
,Harmonic 13 0.304 45.02
,Harmonic 14 0.133 23.99
,Harmonic 15 (-0.365) 69.57
,Harmonic 16 2.619 15.8
,Harmonic 17 0.188 33.79
,Harmonic 18 (-9.1e-2) 22.19
,Harmonic 19 (-2.968) 24.04
,Harmonic 20 (-0.333) 5.02
,Harmonic 21 (-1.684) 9.88
,Harmonic 22 (-2.55) 14.27
,Harmonic 23 (-2.478) 5.71
,Harmonic 24 0.647 3.63
,Harmonic 25 0.163 3.38
,Harmonic 26 0.301 2.19
,Harmonic 27 (-0.266) 1.0
,Harmonic 28 (-1.389) 6.3
,Harmonic 29 2.302 1.58
,Harmonic 30 0.712 2.09
,Harmonic 31 0.222 1.59
,Harmonic 32 1.869 2.25
,Harmonic 33 (-1.975) 4.29
,Harmonic 34 (-2.469) 0.53
,Harmonic 35 0.641 1.84
,Harmonic 36 (-0.892) 0.77
,Harmonic 37 0.277 2.81
,Harmonic 38 (-1.441) 2.39
,Harmonic 39 (-2.092) 0.96
,Harmonic 40 1.606 1.65
,Harmonic 41 2.557 2.4
,Harmonic 42 1.64 1.67
,Harmonic 43 (-2.557) 1.01
,Harmonic 44 (-0.406) 1.08
,Harmonic 45 1.594 0.38
,Harmonic 46 (-0.342) 0.52]
note22 :: Note
note22 = Note
(Pitch 233.082 46 "a#3")
23
(Range
(NoteRange
(NoteRangeAmplitude 8157.87 35 2.44)
(NoteRangeHarmonicFreq 1 233.08))
(NoteRange
(NoteRangeAmplitude 233.08 1 2983.0)
(NoteRangeHarmonicFreq 42 9789.44)))
[Harmonic 1 (-1.258) 2983.0
,Harmonic 2 (-2.476) 1207.73
,Harmonic 3 (-2.277) 1262.09
,Harmonic 4 (-1.326) 863.51
,Harmonic 5 3.117 718.01
,Harmonic 6 (-0.93) 553.26
,Harmonic 7 0.17 1133.02
,Harmonic 8 (-0.955) 655.37
,Harmonic 9 (-2.166) 731.77
,Harmonic 10 (-0.999) 248.66
,Harmonic 11 0.891 169.08
,Harmonic 12 2.729 237.83
,Harmonic 13 (-2.286) 253.89
,Harmonic 14 (-1.981) 293.05
,Harmonic 15 2.098 56.91
,Harmonic 16 0.643 64.76
,Harmonic 17 1.631 56.75
,Harmonic 18 1.629 87.45
,Harmonic 19 1.6 37.41
,Harmonic 20 0.997 22.66
,Harmonic 21 (-5.2e-2) 5.89
,Harmonic 22 1.481 19.65
,Harmonic 23 2.173 37.51
,Harmonic 24 (-2.154) 11.96
,Harmonic 25 3.0e-2 13.6
,Harmonic 26 (-0.163) 12.22
,Harmonic 27 1.405 9.1
,Harmonic 28 (-2.549) 27.66
,Harmonic 29 0.835 29.88
,Harmonic 30 (-2.85) 22.95
,Harmonic 31 0.933 9.21
,Harmonic 32 (-2.296) 6.81
,Harmonic 33 (-0.412) 11.7
,Harmonic 34 2.772 9.67
,Harmonic 35 (-1.552) 2.44
,Harmonic 36 3.046 3.43
,Harmonic 37 0.935 8.09
,Harmonic 38 (-1.19) 3.54
,Harmonic 39 8.0e-3 14.32
,Harmonic 40 1.231 3.81
,Harmonic 41 (-1.746) 6.24
,Harmonic 42 0.256 3.02]
note23 :: Note
note23 = Note
(Pitch 246.942 47 "b3")
24
(Range
(NoteRange
(NoteRangeAmplitude 7161.31 29 8.66)
(NoteRangeHarmonicFreq 1 246.94))
(NoteRange
(NoteRangeAmplitude 1728.59 7 3186.0)
(NoteRangeHarmonicFreq 40 9877.68)))
[Harmonic 1 0.129 2415.47
,Harmonic 2 (-2.661) 2009.36
,Harmonic 3 (-1.397) 1149.93
,Harmonic 4 2.356 290.47
,Harmonic 5 (-0.817) 665.2
,Harmonic 6 2.25 535.0
,Harmonic 7 1.069 3186.0
,Harmonic 8 3.094 1759.97
,Harmonic 9 2.336 799.56
,Harmonic 10 (-0.533) 511.28
,Harmonic 11 2.067 124.51
,Harmonic 12 2.105 280.98
,Harmonic 13 (-0.779) 538.5
,Harmonic 14 0.762 87.15
,Harmonic 15 (-0.614) 220.99
,Harmonic 16 1.64 149.52
,Harmonic 17 (-2.658) 40.56
,Harmonic 18 0.321 118.78
,Harmonic 19 (-0.233) 51.14
,Harmonic 20 2.464 14.38
,Harmonic 21 (-1.377) 44.31
,Harmonic 22 2.739 61.3
,Harmonic 23 1.658 40.73
,Harmonic 24 (-1.196) 44.01
,Harmonic 25 (-1.197) 46.11
,Harmonic 26 (-2.824) 32.72
,Harmonic 27 2.226 45.73
,Harmonic 28 (-0.21) 31.28
,Harmonic 29 0.434 8.66
,Harmonic 30 (-0.5) 16.46
,Harmonic 31 (-0.915) 28.34
,Harmonic 32 (-2.869) 14.12
,Harmonic 33 (-2.673) 15.21
,Harmonic 34 0.566 27.76
,Harmonic 35 2.236 13.13
,Harmonic 36 (-0.398) 17.0
,Harmonic 37 (-2.581) 43.0
,Harmonic 38 1.744 18.41
,Harmonic 39 0.811 11.05
,Harmonic 40 (-2.078) 13.76]
note24 :: Note
note24 = Note
(Pitch 261.626 48 "c4")
25
(Range
(NoteRange
(NoteRangeAmplitude 7325.52 28 3.32)
(NoteRangeHarmonicFreq 1 261.62))
(NoteRange
(NoteRangeAmplitude 261.62 1 3260.0)
(NoteRangeHarmonicFreq 38 9941.78)))
[Harmonic 1 (-2.396) 3260.0
,Harmonic 2 (-0.84) 792.83
,Harmonic 3 (-3.046) 444.52
,Harmonic 4 0.554 878.4
,Harmonic 5 (-1.163) 635.02
,Harmonic 6 (-1.088) 1111.22
,Harmonic 7 (-1.486) 1722.98
,Harmonic 8 (-3.5e-2) 519.39
,Harmonic 9 1.879 355.94
,Harmonic 10 (-2.602) 253.05
,Harmonic 11 (-0.824) 356.44
,Harmonic 12 1.701 736.84
,Harmonic 13 (-0.951) 312.39
,Harmonic 14 (-2.601) 447.24
,Harmonic 15 (-2.332) 208.57
,Harmonic 16 2.423 215.63
,Harmonic 17 (-0.678) 82.83
,Harmonic 18 (-0.673) 31.36
,Harmonic 19 4.7e-2 37.71
,Harmonic 20 1.139 91.06
,Harmonic 21 2.884 81.12
,Harmonic 22 (-0.414) 67.66
,Harmonic 23 1.781 9.34
,Harmonic 24 (-1.217) 72.42
,Harmonic 25 0.551 71.82
,Harmonic 26 (-2.056) 44.29
,Harmonic 27 0.46 35.85
,Harmonic 28 1.673 3.32
,Harmonic 29 1.908 18.32
,Harmonic 30 (-1.279) 40.05
,Harmonic 31 0.448 20.64
,Harmonic 32 (-1.53) 10.67
,Harmonic 33 (-0.723) 8.67
,Harmonic 34 2.901 17.45
,Harmonic 35 0.749 16.95
,Harmonic 36 2.538 12.12
,Harmonic 37 (-1.578) 9.56
,Harmonic 38 0.843 22.19]
note25 :: Note
note25 = Note
(Pitch 277.183 49 "c#4")
26
(Range
(NoteRange
(NoteRangeAmplitude 8315.49 30 1.39)
(NoteRangeHarmonicFreq 1 277.18))
(NoteRange
(NoteRangeAmplitude 277.18 1 4794.0)
(NoteRangeHarmonicFreq 35 9701.4)))
[Harmonic 1 (-1.756) 4794.0
,Harmonic 2 (-1.976) 700.23
,Harmonic 3 1.763 461.26
,Harmonic 4 (-0.999) 1555.08
,Harmonic 5 2.334 1063.25
,Harmonic 6 (-2.339) 657.98
,Harmonic 7 (-0.333) 858.6
,Harmonic 8 (-2.352) 356.46
,Harmonic 9 (-1.671) 211.69
,Harmonic 10 1.473 65.89
,Harmonic 11 1.332 357.6
,Harmonic 12 1.278 191.03
,Harmonic 13 1.521 50.82
,Harmonic 14 (-2.202) 36.63
,Harmonic 15 3.049 42.96
,Harmonic 16 2.669 45.11
,Harmonic 17 1.916 16.69
,Harmonic 18 (-0.812) 18.54
,Harmonic 19 (-1.172) 33.11
,Harmonic 20 2.558 7.28
,Harmonic 21 (-2.52) 16.36
,Harmonic 22 2.072 8.5
,Harmonic 23 (-0.288) 6.6
,Harmonic 24 1.042 13.38
,Harmonic 25 2.756 10.23
,Harmonic 26 1.051 4.9
,Harmonic 27 2.082 2.79
,Harmonic 28 (-2.351) 7.6
,Harmonic 29 (-2.774) 6.84
,Harmonic 30 (-0.401) 1.39
,Harmonic 31 1.509 1.44
,Harmonic 32 1.277 4.89
,Harmonic 33 0.139 2.83
,Harmonic 34 1.229 1.74
,Harmonic 35 0.231 2.85]
note26 :: Note
note26 = Note
(Pitch 293.665 50 "d4")
27
(Range
(NoteRange
(NoteRangeAmplitude 8809.95 30 1.36)
(NoteRangeHarmonicFreq 1 293.66))
(NoteRange
(NoteRangeAmplitude 293.66 1 2829.0)
(NoteRangeHarmonicFreq 32 9397.28)))
[Harmonic 1 1.833 2829.0
,Harmonic 2 1.216 1993.37
,Harmonic 3 (-2.623) 132.77
,Harmonic 4 (-2.21) 667.4
,Harmonic 5 (-2.295) 868.84
,Harmonic 6 1.378 415.4
,Harmonic 7 2.712 475.48
,Harmonic 8 (-2.458) 43.57
,Harmonic 9 0.115 34.36
,Harmonic 10 (-3.004) 124.88
,Harmonic 11 (-0.36) 27.3
,Harmonic 12 0.225 22.4
,Harmonic 13 1.885 3.96
,Harmonic 14 (-0.731) 9.52
,Harmonic 15 1.791 16.0
,Harmonic 16 0.573 8.05
,Harmonic 17 (-2.974) 32.5
,Harmonic 18 0.172 7.38
,Harmonic 19 2.085 28.66
,Harmonic 20 (-0.646) 75.07
,Harmonic 21 (-0.75) 78.76
,Harmonic 22 (-0.201) 36.53
,Harmonic 23 0.318 61.96
,Harmonic 24 1.146 23.51
,Harmonic 25 (-3.122) 8.53
,Harmonic 26 (-2.708) 36.76
,Harmonic 27 2.464 32.91
,Harmonic 28 0.42 3.56
,Harmonic 29 1.156 29.92
,Harmonic 30 (-0.59) 1.36
,Harmonic 31 (-2.317) 5.24
,Harmonic 32 2.844 11.28]
note27 :: Note
note27 = Note
(Pitch 311.127 51 "d#4")
28
(Range
(NoteRange
(NoteRangeAmplitude 9022.68 29 7.53)
(NoteRangeHarmonicFreq 1 311.12))
(NoteRange
(NoteRangeAmplitude 1866.76 6 2782.0)
(NoteRangeHarmonicFreq 32 9956.06)))
[Harmonic 1 (-0.807) 2479.43
,Harmonic 2 2.97 1680.77
,Harmonic 3 2.225 1537.49
,Harmonic 4 (-1.477) 587.32
,Harmonic 5 (-1.426) 873.3
,Harmonic 6 (-1.779) 2782.0
,Harmonic 7 0.594 373.64
,Harmonic 8 (-1.016) 334.73
,Harmonic 9 (-2.8) 353.42
,Harmonic 10 1.038 259.25
,Harmonic 11 0.669 275.59
,Harmonic 12 (-2.26) 182.25
,Harmonic 13 (-3.2e-2) 135.24
,Harmonic 14 0.303 137.97
,Harmonic 15 (-2.28) 17.38
,Harmonic 16 2.788 44.78
,Harmonic 17 1.857 45.37
,Harmonic 18 (-0.323) 52.01
,Harmonic 19 (-2.757) 73.85
,Harmonic 20 (-2.964) 39.1
,Harmonic 21 0.873 57.51
,Harmonic 22 (-0.709) 75.01
,Harmonic 23 2.335 25.39
,Harmonic 24 3.018 14.99
,Harmonic 25 0.639 41.06
,Harmonic 26 (-1.007) 13.56
,Harmonic 27 (-2.308) 12.38
,Harmonic 28 (-1.632) 17.35
,Harmonic 29 1.232 7.53
,Harmonic 30 0.463 13.02
,Harmonic 31 (-3.091) 19.07
,Harmonic 32 1.794 8.9]
note28 :: Note
note28 = Note
(Pitch 329.628 52 "e4")
29
(Range
(NoteRange
(NoteRangeAmplitude 6922.18 21 6.5)
(NoteRangeHarmonicFreq 1 329.62))
(NoteRange
(NoteRangeAmplitude 659.25 2 4847.0)
(NoteRangeHarmonicFreq 30 9888.84)))
[Harmonic 1 0.825 1196.59
,Harmonic 2 1.786 4847.0
,Harmonic 3 2.488 2252.57
,Harmonic 4 1.189 2327.88
,Harmonic 5 7.3e-2 3884.78
,Harmonic 6 3.06 1232.2
,Harmonic 7 (-1.192) 763.61
,Harmonic 8 0.151 456.45
,Harmonic 9 1.874 338.4
,Harmonic 10 1.001 568.88
,Harmonic 11 (-3.106) 633.17
,Harmonic 12 1.219 317.96
,Harmonic 13 0.978 344.2
,Harmonic 14 1.312 107.78
,Harmonic 15 0.326 100.83
,Harmonic 16 1.537 212.85
,Harmonic 17 1.32 46.0
,Harmonic 18 (-0.988) 13.89
,Harmonic 19 (-2.351) 22.34
,Harmonic 20 (-2.166) 15.26
,Harmonic 21 (-2.155) 6.5
,Harmonic 22 0.594 44.7
,Harmonic 23 0.247 48.2
,Harmonic 24 2.47 58.86
,Harmonic 25 (-1.3e-2) 56.65
,Harmonic 26 0.148 9.43
,Harmonic 27 (-1.205) 36.59
,Harmonic 28 0.33 34.04
,Harmonic 29 (-2.579) 9.01
,Harmonic 30 2.115 34.55]
note29 :: Note
note29 = Note
(Pitch 349.228 53 "f4")
30
(Range
(NoteRange
(NoteRangeAmplitude 9778.38 28 9.46)
(NoteRangeHarmonicFreq 1 349.22))
(NoteRange
(NoteRangeAmplitude 1746.14 5 6280.0)
(NoteRangeHarmonicFreq 28 9778.38)))
[Harmonic 1 (-0.535) 5156.19
,Harmonic 2 (-2.902) 3839.36
,Harmonic 3 2.48 2317.4
,Harmonic 4 2.7 1408.05
,Harmonic 5 1.204 6280.0
,Harmonic 6 2.2e-2 1290.98
,Harmonic 7 (-3.089) 538.86
,Harmonic 8 1.915 449.89
,Harmonic 9 2.369 557.64
,Harmonic 10 1.096 166.03
,Harmonic 11 2.649 250.67
,Harmonic 12 1.939 123.03
,Harmonic 13 (-2.982) 83.68
,Harmonic 14 (-0.423) 45.08
,Harmonic 15 (-1.362) 85.08
,Harmonic 16 (-0.942) 27.88
,Harmonic 17 2.477 34.86
,Harmonic 18 1.53 33.22
,Harmonic 19 (-1.818) 78.24
,Harmonic 20 0.412 54.75
,Harmonic 21 (-2.068) 31.97
,Harmonic 22 (-2.705) 36.88
,Harmonic 23 (-2.169) 32.62
,Harmonic 24 (-3.082) 20.45
,Harmonic 25 1.089 17.95
,Harmonic 26 (-2.366) 13.4
,Harmonic 27 (-0.242) 17.01
,Harmonic 28 2.067 9.46]
note30 :: Note
note30 = Note
(Pitch 369.994 54 "f#4")
31
(Range
(NoteRange
(NoteRangeAmplitude 5919.9 16 4.73)
(NoteRangeHarmonicFreq 1 369.99))
(NoteRange
(NoteRangeAmplitude 369.99 1 3627.0)
(NoteRangeHarmonicFreq 26 9619.84)))
[Harmonic 1 (-1.631) 3627.0
,Harmonic 2 (-0.698) 706.59
,Harmonic 3 (-1.342) 1381.36
,Harmonic 4 1.639 363.19
,Harmonic 5 (-2.321) 1579.67
,Harmonic 6 (-1.42) 697.18
,Harmonic 7 (-1.183) 369.69
,Harmonic 8 4.4e-2 276.16
,Harmonic 9 3.024 165.94
,Harmonic 10 (-2.929) 134.46
,Harmonic 11 1.52 39.23
,Harmonic 12 (-1.466) 67.67
,Harmonic 13 0.1 42.8
,Harmonic 14 (-1.472) 41.85
,Harmonic 15 1.398 22.66
,Harmonic 16 (-2.235) 4.73
,Harmonic 17 (-3.136) 18.6
,Harmonic 18 (-3.041) 23.18
,Harmonic 19 (-2.056) 20.05
,Harmonic 20 (-4.0e-2) 5.49
,Harmonic 21 2.149 9.46
,Harmonic 22 (-2.333) 20.15
,Harmonic 23 3.0e-3 15.73
,Harmonic 24 (-3.116) 13.51
,Harmonic 25 (-2.666) 14.65
,Harmonic 26 (-0.677) 7.64]
note31 :: Note
note31 = Note
(Pitch 391.995 55 "g4")
32
(Range
(NoteRange
(NoteRangeAmplitude 9799.87 25 2.06)
(NoteRangeHarmonicFreq 1 391.99))
(NoteRange
(NoteRangeAmplitude 391.99 1 3264.0)
(NoteRangeHarmonicFreq 27 10583.86)))
[Harmonic 1 1.274 3264.0
,Harmonic 2 (-1.951) 125.0
,Harmonic 3 0.108 565.06
,Harmonic 4 (-1.264) 736.87
,Harmonic 5 1.426 466.77
,Harmonic 6 (-1.049) 203.08
,Harmonic 7 (-2.281) 13.61
,Harmonic 8 1.029 73.74
,Harmonic 9 1.783 3.82
,Harmonic 10 (-1.44) 44.61
,Harmonic 11 0.509 16.31
,Harmonic 12 2.364 49.15
,Harmonic 13 0.276 8.02
,Harmonic 14 2.801 40.37
,Harmonic 15 1.693 16.65
,Harmonic 16 (-0.706) 62.14
,Harmonic 17 2.228 20.02
,Harmonic 18 (-0.519) 22.43
,Harmonic 19 (-1.147) 50.2
,Harmonic 20 (-2.188) 6.63
,Harmonic 21 0.221 41.48
,Harmonic 22 0.818 52.51
,Harmonic 23 1.674 13.45
,Harmonic 24 0.377 6.16
,Harmonic 25 (-0.865) 2.06
,Harmonic 26 (-2.865) 2.91
,Harmonic 27 3.11 4.28]
note32 :: Note
note32 = Note
(Pitch 415.305 56 "g#4")
33
(Range
(NoteRange
(NoteRangeAmplitude 7890.79 19 2.73)
(NoteRangeHarmonicFreq 1 415.3))
(NoteRange
(NoteRangeAmplitude 415.3 1 3256.0)
(NoteRangeHarmonicFreq 23 9552.01)))
[Harmonic 1 0.54 3256.0
,Harmonic 2 (-3.074) 709.57
,Harmonic 3 3.133 701.34
,Harmonic 4 1.81 1960.79
,Harmonic 5 (-1.54) 248.05
,Harmonic 6 1.721 419.67
,Harmonic 7 1.794 558.75
,Harmonic 8 1.636 144.89
,Harmonic 9 (-1.163) 260.25
,Harmonic 10 (-0.52) 139.86
,Harmonic 11 (-2.857) 22.39
,Harmonic 12 0.418 71.43
,Harmonic 13 3.14 26.4
,Harmonic 14 0.701 37.99
,Harmonic 15 2.389 28.26
,Harmonic 16 0.852 16.01
,Harmonic 17 (-1.601) 19.02
,Harmonic 18 2.72 24.87
,Harmonic 19 0.175 2.73
,Harmonic 20 (-0.12) 35.05
,Harmonic 21 0.615 17.84
,Harmonic 22 (-1.275) 14.89
,Harmonic 23 2.65 15.07]
note33 :: Note
note33 = Note
(Pitch 440.0 57 "a4")
34
(Range
(NoteRange
(NoteRangeAmplitude 5720.0 13 11.56)
(NoteRangeHarmonicFreq 1 440.0))
(NoteRange
(NoteRangeAmplitude 1320.0 3 2690.0)
(NoteRangeHarmonicFreq 22 9680.0)))
[Harmonic 1 (-1.996) 2029.38
,Harmonic 2 (-0.554) 980.77
,Harmonic 3 (-2.1e-2) 2690.0
,Harmonic 4 (-2.276) 2161.78
,Harmonic 5 1.753 1196.45
,Harmonic 6 (-1.351) 561.74
,Harmonic 7 2.951 262.79
,Harmonic 8 (-1.57) 180.29
,Harmonic 9 (-1.503) 300.25
,Harmonic 10 (-0.386) 163.4
,Harmonic 11 2.296 170.98
,Harmonic 12 3.087 209.94
,Harmonic 13 (-3.133) 11.56
,Harmonic 14 (-2.729) 59.97
,Harmonic 15 (-0.695) 56.95
,Harmonic 16 (-2.143) 85.4
,Harmonic 17 (-0.382) 49.5
,Harmonic 18 (-1.991) 33.76
,Harmonic 19 2.221 67.69
,Harmonic 20 2.612 24.11
,Harmonic 21 (-0.466) 54.93
,Harmonic 22 (-1.644) 39.16]
note34 :: Note
note34 = Note
(Pitch 466.164 58 "a#4")
35
(Range
(NoteRange
(NoteRangeAmplitude 9789.44 21 17.39)
(NoteRangeHarmonicFreq 1 466.16))
(NoteRange
(NoteRangeAmplitude 466.16 1 3241.0)
(NoteRangeHarmonicFreq 21 9789.44)))
[Harmonic 1 0.427 3241.0
,Harmonic 2 3.058 2742.37
,Harmonic 3 0.667 538.33
,Harmonic 4 1.087 2582.39
,Harmonic 5 (-2.638) 78.53
,Harmonic 6 2.768 490.48
,Harmonic 7 0.294 397.05
,Harmonic 8 (-0.542) 314.09
,Harmonic 9 2.089 366.85
,Harmonic 10 (-0.134) 119.23
,Harmonic 11 (-0.756) 79.55
,Harmonic 12 (-2.013) 40.29
,Harmonic 13 1.65 39.04
,Harmonic 14 0.822 49.02
,Harmonic 15 2.431 53.05
,Harmonic 16 0.155 31.25
,Harmonic 17 0.391 36.43
,Harmonic 18 2.419 29.3
,Harmonic 19 (-1.039) 63.22
,Harmonic 20 (-0.17) 27.02
,Harmonic 21 (-2.002) 17.39]
note35 :: Note
note35 = Note
(Pitch 493.883 59 "b4")
36
(Range
(NoteRange
(NoteRangeAmplitude 7408.24 15 14.02)
(NoteRangeHarmonicFreq 1 493.88))
(NoteRange
(NoteRangeAmplitude 1975.53 4 4076.0)
(NoteRangeHarmonicFreq 20 9877.66)))
[Harmonic 1 1.874 3379.73
,Harmonic 2 0.37 2602.37
,Harmonic 3 (-1.686) 1053.98
,Harmonic 4 (-2.591) 4076.0
,Harmonic 5 (-2.268) 2027.74
,Harmonic 6 (-0.201) 2068.92
,Harmonic 7 0.495 187.21
,Harmonic 8 1.822 330.89
,Harmonic 9 (-0.364) 145.14
,Harmonic 10 3.9e-2 97.7
,Harmonic 11 (-2.163) 216.87
,Harmonic 12 (-0.616) 130.44
,Harmonic 13 1.837 155.86
,Harmonic 14 (-2.562) 80.86
,Harmonic 15 0.201 14.02
,Harmonic 16 3.012 45.45
,Harmonic 17 (-0.558) 123.72
,Harmonic 18 2.195 95.88
,Harmonic 19 (-2.973) 36.64
,Harmonic 20 (-1.379) 29.34]
note36 :: Note
note36 = Note
(Pitch 523.251 60 "c5")
37
(Range
(NoteRange
(NoteRangeAmplitude 9941.76 19 10.37)
(NoteRangeHarmonicFreq 1 523.25))
(NoteRange
(NoteRangeAmplitude 1046.5 2 3121.0)
(NoteRangeHarmonicFreq 19 9941.76)))
[Harmonic 1 (-2.777) 2746.71
,Harmonic 2 0.998 3121.0
,Harmonic 3 (-1.762) 2395.63
,Harmonic 4 (-1.839) 1196.96
,Harmonic 5 1.202 283.49
,Harmonic 6 (-1.494) 773.55
,Harmonic 7 (-1.79) 97.23
,Harmonic 8 1.856 78.08
,Harmonic 9 (-2.363) 39.1
,Harmonic 10 0.938 61.12
,Harmonic 11 (-2.637) 67.96
,Harmonic 12 (-2.775) 27.03
,Harmonic 13 (-2.732) 42.32
,Harmonic 14 0.213 52.03
,Harmonic 15 0.79 19.3
,Harmonic 16 1.131 14.3
,Harmonic 17 0.482 14.11
,Harmonic 18 (-2.108) 61.24
,Harmonic 19 2.262 10.37]
note37 :: Note
note37 = Note
(Pitch 554.365 61 "c#5")
38
(Range
(NoteRange
(NoteRangeAmplitude 9424.2 17 8.94)
(NoteRangeHarmonicFreq 1 554.36))
(NoteRange
(NoteRangeAmplitude 1108.73 2 5121.0)
(NoteRangeHarmonicFreq 18 9978.57)))
[Harmonic 1 (-0.197) 4365.63
,Harmonic 2 1.148 5121.0
,Harmonic 3 1.153 4553.38
,Harmonic 4 2.768 3440.96
,Harmonic 5 1.522 1293.91
,Harmonic 6 2.235 2353.45
,Harmonic 7 0.225 49.75
,Harmonic 8 0.161 371.65
,Harmonic 9 (-2.332) 151.25
,Harmonic 10 1.037 145.31
,Harmonic 11 (-3.034) 42.79
,Harmonic 12 0.895 96.52
,Harmonic 13 1.628 63.33
,Harmonic 14 2.956 115.17
,Harmonic 15 (-2.589) 105.97
,Harmonic 16 2.603 62.01
,Harmonic 17 0.325 8.94
,Harmonic 18 1.464 28.67]
note38 :: Note
note38 = Note
(Pitch 587.33 62 "d5")
39
(Range
(NoteRange
(NoteRangeAmplitude 9397.28 16 13.09)
(NoteRangeHarmonicFreq 1 587.33))
(NoteRange
(NoteRangeAmplitude 2349.32 4 3303.0)
(NoteRangeHarmonicFreq 17 9984.61)))
[Harmonic 1 0.353 1732.13
,Harmonic 2 (-1.129) 1401.48
,Harmonic 3 2.899 2965.8
,Harmonic 4 (-1.982) 3303.0
,Harmonic 5 (-1.205) 1921.92
,Harmonic 6 1.65 530.87
,Harmonic 7 (-1.902) 264.59
,Harmonic 8 (-2.037) 196.48
,Harmonic 9 (-0.335) 220.24
,Harmonic 10 2.308 53.75
,Harmonic 11 (-1.248) 190.18
,Harmonic 12 (-0.292) 61.3
,Harmonic 13 (-2.839) 90.14
,Harmonic 14 5.9e-2 97.48
,Harmonic 15 1.304 35.99
,Harmonic 16 (-1.118) 13.09
,Harmonic 17 (-2.357) 25.74]
note39 :: Note
note39 = Note
(Pitch 622.254 63 "d#5")
40
(Range
(NoteRange
(NoteRangeAmplitude 8711.55 14 20.53)
(NoteRangeHarmonicFreq 1 622.25))
(NoteRange
(NoteRangeAmplitude 622.25 1 2744.0)
(NoteRangeHarmonicFreq 15 9333.81)))
[Harmonic 1 (-2.418) 2744.0
,Harmonic 2 1.828 355.18
,Harmonic 3 (-1.018) 1980.93
,Harmonic 4 1.585 1216.29
,Harmonic 5 (-1.763) 1896.64
,Harmonic 6 (-0.501) 296.38
,Harmonic 7 (-2.635) 88.49
,Harmonic 8 0.544 100.24
,Harmonic 9 1.44 53.75
,Harmonic 10 1.614 133.75
,Harmonic 11 (-0.408) 95.65
,Harmonic 12 0.58 94.95
,Harmonic 13 (-1.517) 23.67
,Harmonic 14 (-1.06) 20.53
,Harmonic 15 2.938 21.53]
note40 :: Note
note40 = Note
(Pitch 659.255 64 "e5")
41
(Range
(NoteRange
(NoteRangeAmplitude 8570.31 13 39.35)
(NoteRangeHarmonicFreq 1 659.25))
(NoteRange
(NoteRangeAmplitude 1977.76 3 4620.0)
(NoteRangeHarmonicFreq 15 9888.82)))
[Harmonic 1 3.0e-3 2677.7
,Harmonic 2 (-2.17) 2002.42
,Harmonic 3 (-1.799) 4620.0
,Harmonic 4 (-3.065) 330.79
,Harmonic 5 (-2.526) 891.27
,Harmonic 6 1.392 407.51
,Harmonic 7 2.084 49.26
,Harmonic 8 (-0.347) 107.1
,Harmonic 9 1.337 62.0
,Harmonic 10 (-2.661) 160.82
,Harmonic 11 2.925 59.81
,Harmonic 12 (-2.228) 63.07
,Harmonic 13 1.815 39.35
,Harmonic 14 (-1.886) 101.09
,Harmonic 15 (-0.209) 47.83]
note41 :: Note
note41 = Note
(Pitch 698.456 65 "f5")
42
(Range
(NoteRange
(NoteRangeAmplitude 6286.1 9 7.96)
(NoteRangeHarmonicFreq 1 698.45))
(NoteRange
(NoteRangeAmplitude 698.45 1 3873.0)
(NoteRangeHarmonicFreq 15 10476.84)))
[Harmonic 1 (-2.067) 3873.0
,Harmonic 2 1.434 1982.54
,Harmonic 3 0.102 204.36
,Harmonic 4 1.718 388.34
,Harmonic 5 (-2.232) 26.44
,Harmonic 6 2.898 9.22
,Harmonic 7 9.1e-2 12.62
,Harmonic 8 0.138 11.15
,Harmonic 9 1.91 7.96
,Harmonic 10 (-2.983) 12.43
,Harmonic 11 2.086 42.23
,Harmonic 12 (-1.459) 77.4
,Harmonic 13 (-2.495) 20.61
,Harmonic 14 (-1.071) 80.71
,Harmonic 15 (-1.08) 76.94]
note42 :: Note
note42 = Note
(Pitch 739.989 66 "f#5")
43
(Range
(NoteRange
(NoteRangeAmplitude 8879.86 12 23.1)
(NoteRangeHarmonicFreq 1 739.98))
(NoteRange
(NoteRangeAmplitude 2219.96 3 3595.0)
(NoteRangeHarmonicFreq 13 9619.85)))
[Harmonic 1 3.09 2046.12
,Harmonic 2 0.669 2604.75
,Harmonic 3 1.381 3595.0
,Harmonic 4 1.353 2379.23
,Harmonic 5 (-2.685) 1077.55
,Harmonic 6 (-1.141) 154.24
,Harmonic 7 2.815 121.83
,Harmonic 8 (-2.499) 67.43
,Harmonic 9 (-3.107) 80.96
,Harmonic 10 1.67 50.68
,Harmonic 11 (-2.509) 45.53
,Harmonic 12 0.953 23.1
,Harmonic 13 1.6 36.2]
note43 :: Note
note43 = Note
(Pitch 783.991 67 "g5")
44
(Range
(NoteRange
(NoteRangeAmplitude 7055.91 9 46.45)
(NoteRangeHarmonicFreq 1 783.99))
(NoteRange
(NoteRangeAmplitude 2351.97 3 3267.0)
(NoteRangeHarmonicFreq 12 9407.89)))
[Harmonic 1 (-1.797) 1684.79
,Harmonic 2 (-0.371) 2954.92
,Harmonic 3 (-2.01) 3267.0
,Harmonic 4 (-2.587) 1998.09
,Harmonic 5 (-0.875) 510.46
,Harmonic 6 2.3e-2 103.78
,Harmonic 7 (-0.698) 109.11
,Harmonic 8 (-0.295) 48.5
,Harmonic 9 (-2.914) 46.45
,Harmonic 10 (-2.095) 106.07
,Harmonic 11 1.936 132.07
,Harmonic 12 (-1.464) 122.47]
|
anton-k/sharc-timbre
|
src/Sharc/Instruments/CelloMarteleBowing.hs
|
bsd-3-clause
| 89,100
| 0
| 15
| 24,894
| 35,221
| 18,270
| 16,951
| 3,030
| 1
|
{-# LANGUAGE ViewPatterns #-}
{- |
Used for building symmetrical sequences from one half of the symmetrical shape.
Eg: An oval can be described by giving the radius of the first 180 degrees, then reversing these first 180 degrees, and adding them on to the tail.
Note though, that the 180th degree would be there twice, which has to be handled.
-}
module Helpers.Symmetrical.Sequence (mirror, mirrorPlusMidPoint, mirrorMinusMidPoint) where
import qualified Data.Sequence as S
import qualified Data.Foldable as F
{- |
Reverse the first half and add to tail. This will create a second copy of the last item.
-}
mirror :: (S.Seq a) -> (S.Seq a)
mirror seq = seq S.>< (S.reverse seq)
{- |
Reverse the first half and add to tail. Add a midpoint between the 2 halves.
-}
mirrorPlusMidPoint :: (S.Seq a) -> a -> (S.Seq a)
mirrorPlusMidPoint seq midPoint =
(seq S.|> midPoint) S.>< (S.reverse seq)
{- |
Reverse the first half and add to tail. Remove the midpoint from the second half so it is not repeated.
-}
mirrorMinusMidPoint :: (S.Seq a) -> (S.Seq a)
mirrorMinusMidPoint seq =
seq S.>< (S.reverse(xs seq))
xs :: (S.Seq a) -> (S.Seq a)
xs (S.viewr -> xs' S.:> x) = xs'
|
heathweiss/Tricad
|
src/Helpers/Symmetrical/Sequence.hs
|
gpl-2.0
| 1,196
| 0
| 9
| 233
| 249
| 137
| 112
| 14
| 1
|
module Lib.Posix.FileType
( FileType(..), fileTypeOfStat
) where
import Data.Binary (Binary)
import GHC.Generics (Generic)
import qualified System.Posix.ByteString as Posix
import Prelude.Compat
data FileType
= BlockDevice
| CharacterDevice
| Directory
| NamedPipe
| RegularFile
| Socket
| SymbolicLink
deriving (Generic, Eq, Show)
instance Binary FileType
fileTypeOfStat :: Posix.FileStatus -> FileType
fileTypeOfStat stat
| Posix.isBlockDevice stat = BlockDevice
| Posix.isCharacterDevice stat = CharacterDevice
| Posix.isDirectory stat = Directory
| Posix.isNamedPipe stat = NamedPipe
| Posix.isRegularFile stat = RegularFile
| Posix.isSocket stat = Socket
| Posix.isSymbolicLink stat = SymbolicLink
| otherwise = error "Unrecognized file type"
|
buildsome/buildsome
|
src/Lib/Posix/FileType.hs
|
gpl-2.0
| 818
| 0
| 9
| 162
| 226
| 117
| 109
| 26
| 1
|
module Haskus.Arch.X86_64.Linux.SyscallTable
( syscalls
)
where
import Haskus.Utils.Flow
import Haskus.Utils.Maybe
import Language.Haskell.TH.Quote
import Language.Haskell.TH.Syntax
import Text.Megaparsec
import Text.Megaparsec.Char.Lexer hiding (space)
import Text.Megaparsec.Char
import Data.Void
type Parser = Parsec Void String
syscalls :: QuasiQuoter
syscalls = QuasiQuoter
{ quoteDec = makeSyscalls
, quoteExp = undefined
, quotePat = undefined
, quoteType = undefined
}
makeSyscalls :: String -> Q [Dec]
makeSyscalls str =
case runParser parseLines "syscalls table" str of
Right entries -> return (concatMap makeSyscall entries)
Left err -> fail (show err)
type Entry = (Integer,String,String,[[String]])
makeSyscall :: Entry -> [Dec]
makeSyscall (num,mode,name,typ) = [sysSig,sysFun]
where
arity = length typ - 1
syscallN = mkName <| mconcat
[ "syscall"
, show arity
, case mode of
"PrimOp" -> "primop"
"Safe" -> "safe"
r -> fail ("Invalid syscall mode: " ++ r)
]
makeType :: [[String]] -> Type
makeType xs =
xs ||> fmap (ConT . mkName)
||> foldl1 AppT
|> foldr1 (\x y -> AppT (AppT ArrowT x) y)
sysName = mkName ("syscall_"++name)
sysFun = FunD sysName
[ Clause []
(NormalB (AppE (VarE syscallN) (LitE (IntegerL num))))
[]
]
sysSig = SigD sysName (makeType typ)
-- | Parse a line with the form:
-- num mode name :: type
-- e.g.
-- 4 PrimOp stat :: CString -> Ptr () -> IO Int64
parseLines :: Parser [(Integer,String,String,[[String]])]
parseLines = catMaybes <$> lines'
where
lines' = (line `sepEndBy` eol) <* eof
line = manySpace *>
( (Just <$> try entryLine)
<|> (try comment >> return Nothing)
<|> (lookAhead end >> return Nothing)
)
entryLine = do
num <- decimal
someSpace
mode <- some alphaNumChar
someSpace
name <- identifier
manySpace
void (string "::")
manySpace
typ <- (typElem `sepEndBy` manySpace) `sepBy` arrow
manySpace
lookAhead end
return (num,mode,name,typ)
end = void eol <|> eof
arrow = void (string "->") >> manySpace
identifier = some (alphaNumChar <|> char '_')
typElem = identifier <|> string "()"
-- 'space' from MegaParsec also considers line-breaks as spaces...
manySpace = skipMany (char ' ')
someSpace = skipSome (char ' ')
comment = do
void (string "--")
anySingle `manyTill` lookAhead end
|
hsyl20/ViperVM
|
haskus-system/src/lib/Haskus/Arch/X86_64/Linux/SyscallTable.hs
|
bsd-3-clause
| 2,815
| 0
| 17
| 929
| 819
| 441
| 378
| 73
| 3
|
{-# LANGUAGE GeneralizedNewtypeDeriving, RankNTypes, TypeFamilies #-}
-- | General content types and operations.
module Game.LambdaHack.Common.Kind
( Id, Speedup, Ops(..), COps(..), createOps, stdRuleset
) where
import Control.Exception.Assert.Sugar
import Data.Binary
import qualified Data.EnumMap.Strict as EM
import qualified Data.Ix as Ix
import Data.List
import qualified Data.Map.Strict as M
import qualified Data.Text as T
import Game.LambdaHack.Common.ContentDef
import Game.LambdaHack.Common.Frequency
import Game.LambdaHack.Common.Misc
import Game.LambdaHack.Common.Msg
import Game.LambdaHack.Common.Random
import Game.LambdaHack.Content.CaveKind
import Game.LambdaHack.Content.ItemKind
import Game.LambdaHack.Content.ModeKind
import Game.LambdaHack.Content.PlaceKind
import Game.LambdaHack.Content.RuleKind
import Game.LambdaHack.Content.TileKind
-- | Content identifiers for the content type @c@.
newtype Id c = Id Word8
deriving (Show, Eq, Ord, Ix.Ix, Enum, Bounded, Binary)
-- | Type family for auxiliary data structures for speeding up
-- content operations.
type family Speedup a
-- | Content operations for the content of type @a@.
data Ops a = Ops
{ okind :: Id a -> a -- ^ the content element at given id
, ouniqGroup :: GroupName a -> Id a -- ^ the id of the unique member of
-- a singleton content group
, opick :: GroupName a -> (a -> Bool) -> Rnd (Maybe (Id a))
-- ^ pick a random id belonging to a group
-- and satisfying a predicate
, ofoldrWithKey :: forall b. (Id a -> a -> b -> b) -> b -> b
-- ^ fold over all content elements of @a@
, ofoldrGroup :: forall b.
GroupName a -> (Int -> Id a -> a -> b -> b) -> b -> b
-- ^ fold over the given group only
, obounds :: !(Id a, Id a) -- ^ bounds of identifiers of content @a@
, ospeedup :: !(Maybe (Speedup a)) -- ^ auxiliary speedup components
}
-- | Create content operations for type @a@ from definition of content
-- of type @a@.
createOps :: forall a. Show a => ContentDef a -> Ops a
createOps ContentDef{getName, getFreq, content, validateSingle, validateAll} =
assert (length content <= fromEnum (maxBound :: Id a)) $
let kindMap :: EM.EnumMap (Id a) a
!kindMap = EM.fromDistinctAscList $ zip [Id 0..] content
kindFreq :: M.Map (GroupName a) [(Int, (Id a, a))]
kindFreq =
let tuples = [ (cgroup, (n, (i, k)))
| (i, k) <- EM.assocs kindMap
, (cgroup, n) <- getFreq k
, n > 0 ]
f m (cgroup, nik) = M.insertWith (++) cgroup [nik] m
in foldl' f M.empty tuples
okind i = let assFail = assert `failure` "no kind" `twith` (i, kindMap)
in EM.findWithDefault assFail i kindMap
correct a = not (T.null (getName a)) && all ((> 0) . snd) (getFreq a)
singleOffenders = [ (offences, a)
| a <- content
, let offences = validateSingle a
, not (null offences) ]
allOffences = validateAll content
in assert (allB correct content) $
assert (null singleOffenders `blame` "some content items not valid"
`twith` singleOffenders) $
assert (null allOffences `blame` "the content set not valid"
`twith` (allOffences, content))
-- By this point 'content' can be GCd.
Ops
{ okind
, ouniqGroup = \cgroup ->
let freq = let assFail = assert `failure` "no unique group"
`twith` (cgroup, kindFreq)
in M.findWithDefault assFail cgroup kindFreq
in case freq of
[(n, (i, _))] | n > 0 -> i
l -> assert `failure` "not unique" `twith` (l, cgroup, kindFreq)
, opick = \cgroup p ->
case M.lookup cgroup kindFreq of
Just freqRaw ->
let freq = toFreq ("opick ('" <> tshow cgroup <> "')") freqRaw
in if nullFreq freq
then return Nothing
else fmap Just $ frequency $ do
(i, k) <- freq
breturn (p k) i
{- with MonadComprehensions:
frequency [ i | (i, k) <- kindFreq M.! cgroup, p k ]
-}
_ -> return Nothing
, ofoldrWithKey = \f z -> foldr (uncurry f) z $ EM.assocs kindMap
, ofoldrGroup = \cgroup f z ->
case M.lookup cgroup kindFreq of
Just freq -> foldr (\(p, (i, a)) -> f p i a) z freq
_ -> assert `failure` "no group '" <> tshow cgroup
<> "' among content that has groups"
<+> tshow (M.keys kindFreq)
, obounds = ( fst $ EM.findMin kindMap
, fst $ EM.findMax kindMap )
, ospeedup = Nothing -- define elsewhere
}
-- | Operations for all content types, gathered together.
data COps = COps
{ cocave :: !(Ops CaveKind) -- server only
, coitem :: !(Ops ItemKind)
, comode :: !(Ops ModeKind) -- server only
, coplace :: !(Ops PlaceKind) -- server only, so far
, corule :: !(Ops RuleKind)
, cotile :: !(Ops TileKind)
}
-- | The standard ruleset used for level operations.
stdRuleset :: Ops RuleKind -> RuleKind
stdRuleset Ops{ouniqGroup, okind} = okind $ ouniqGroup "standard"
instance Show COps where
show _ = "game content"
instance Eq COps where
(==) _ _ = True
|
Concomitant/LambdaHack
|
Game/LambdaHack/Common/Kind.hs
|
bsd-3-clause
| 5,727
| 0
| 24
| 1,911
| 1,534
| 853
| 681
| -1
| -1
|
{-# LANGUAGE TypeOperators #-}
module BarnesHutGen where
import Monad (liftM)
import List (nubBy)
import IO
import System (ExitCode(..), getArgs, exitWith)
import Random (Random, RandomGen, getStdGen, randoms, randomRs)
import Data.Array.Parallel.Unlifted.Sequential
import Data.Array.Parallel.Base ( (:*:)(..) )
type Vector = (Double :*: Double)
type Point = Vector
type Accel = Vector
type Velocity = Vector
type MassPoint = Point :*: Double
type Particle = MassPoint :*: Velocity
type BoundingBox = Point :*: Point
type BHTree = [BHTreeLevel]
type BHTreeLevel = (UArr MassPoint, USegd) -- centroids
epsilon = 0.05
eClose = 0.5
-- particle generation
-- -------------------
randomTo, randomFrom :: Integer
randomTo = 2^30
randomFrom = - randomTo
randomRIOs :: Random a => (a, a) -> IO [a]
randomRIOs range = liftM (randomRs range) getStdGen
randomIOs :: Random a => IO [a]
randomIOs = liftM randoms getStdGen
-- generate a stream of random numbers in [0, 1)
--
randomDoubleIO :: IO [Double]
randomDoubleIO = randomIOs
-- generate an infinite list of random mass points located with a homogeneous
-- distribution around the origin within the given bounds
--
randomMassPointsIO :: Double -> Double -> IO [MassPoint]
randomMassPointsIO dx dy = do
rs <- randomRIOs (randomFrom, randomTo)
return (massPnts rs)
where
to = fromIntegral randomTo
from = fromIntegral randomFrom
xmin = - (dx / 2.0)
ymin = - (dy / 2.0)
xfrac = (to - from) / dx
yfrac = (to - from) / dy
massPnts :: [Integer] -> [MassPoint]
massPnts (xb:yb:mb:rs) =
((x :*: y) :*: m) : massPnts rs
where
m = (fromInteger . abs) mb + epsilon
x = xmin + (fromInteger xb) / xfrac
y = ymin + (fromInteger yb) / yfrac
-- The mass of the generated particle cloud is standardized to about
-- 5.0e7 g/m^2. The mass of individual particles may deviate by a factor of
-- ten from the average.
--
smoothMass :: Double -> Double -> [MassPoint] -> [MassPoint]
smoothMass dx dy mps = let
avmass = 5.0e7
area = dx * dy
middle = avmass * area / fromIntegral (length mps)
range = fromIntegral (randomTo - randomFrom)
factor = (middle * 10 - middle / 10) / range
adjust (xy :*: m) =
xy :*: (middle + factor * m)
in
map adjust mps
-- Given the number of particles to generate and the horizontal and vertical
-- extensions of the area where the generated particles should occur, generate
-- a particle set according to a function specific strategy.
--
asymTwinParticles,
sphereParticles,
plummerParticles,
homParticles :: Int -> Double -> Double -> IO ([Particle])
asymTwinParticles n dx dy = error "asymTwinPrticles not implemented yet\n"
sphereParticles n dx dy =
do
let rad = dx `min` dy
mps <- randomMassPointsIO dx dy
return (( map (\mp -> mp :*: (0.0 :*: 0.0))
. smoothMass dx dy
. head
. filter ((== n) . length)
. map fst
. iterate refine
) ([], filter (inside rad) mps)
)
where
--
-- move suitable mass points from the second list to the first (i.e., those
-- not conflicting with points that are already in the first list)
--
refine :: ([MassPoint], [MassPoint]) -> ([MassPoint], [MassPoint])
refine (ds, rs) = let
(ns, rs') = splitAt (n - length ds) rs
in
(nubMassPoints (ds ++ ns), rs')
-- check whether inside the given radius
--
inside :: Double -> MassPoint -> Bool
inside rad ((dx :*: dy) :*: _) = dx * dx + dy * dy <= rad * rad
plummerParticles n _ _ =
do
rs <- randomDoubleIO
return (( normalize
. head
. filter ((== n) . length)
. map fst
. iterate refine
) ([], particles rs)
)
where
particles (w:preY:rs') = let
s_i = rsc * r_i
rsc = (3 * pi) / 16
r_i = sqrt' ((0.999 * w)`power`(-2/3) - 1)
--
u_i = vsc * v_i
vsc = 1 / sqrt rsc
v_i = (x * sqrt 2) / (1 + r_i^2)**(1/4)
--
(pos :*: rs''' ) = rndVec s_i rs''
(vel :*: rs'''') = rndVec u_i rs'''
in
((pos :*: m) :*: vel) : particles rs''''
where
y = preY / 101
-- !!!should be 10, but then
-- !!!findX gets problems
(x, rs'') = findX y rs'
--
m = 1 / fromIntegral n
--
x`power`y | x == 0.0 = 0.0
| otherwise = x**y
sqrt' x | x < 0 = 0
| otherwise = sqrt x
findX :: Double -> [Double] -> (Double, [Double])
findX y (x:rs) | y <= x^2 * (1 - x^2)**(7/2) = (x, rs)
| otherwise = findX y rs
rndVec len (x:y:rs) = let r = len / sqrt (x^2 + y^2)
in
((r * x :*: r * y) :*: rs)
-- move suitable mass points from the second list to the first (i.e., those
-- not conflicting with points that are already in the first list)
--
refine :: ([Particle], [Particle]) -> ([Particle], [Particle])
refine (ds, rs) = let
(ns, rs') = splitAt (n - length ds) rs
in
(nubParticles (ds ++ ns), rs')
-- translate positions and velocities such that they are at the origin
--
normalize :: [Particle] -> [Particle]
normalize ps =
let (dx :*: dy) :*: _ = centroid [mp | mp :*: _ <- ps]
((dvx:*: dvy) :*: _) = totalMomentum ps
in
(map (translateVel (-dvx :*: -dvy)) . map (translate (-dx :*: -dy))) ps
homParticles n dx dy =
do
mps <- randomMassPointsIO dx dy
return (( map (\mp -> mp :*: (0.0 :*: 0.0))
. smoothMass dx dy
. head
. filter ((== n) . length)
. map fst
. iterate refine
) ([], mps)
)
where
--
-- move suitable mass points from the second list to the first (i.e., those
-- not conflicting with points that are already in the first list)
--
refine :: ([MassPoint], [MassPoint]) -> ([MassPoint], [MassPoint])
refine (ds, rs) = let
(ns, rs') = splitAt (n - length ds) rs
in
(nubMassPoints (ds ++ ns), rs')
-- Drop all mass points that are too close to another.
--
nubMassPoints :: [MassPoint] -> [MassPoint]
nubMassPoints = nubBy (\(p1 :*: _) (p2 :*: _) -> epsilonEqual p1 p2)
-- Same for particles.
--
nubParticles :: [Particle] -> [Particle]
nubParticles = nubBy (\((p1 :*: _) :*: _) ->
\((p2 :*: _) :*: _) -> epsilonEqual p1 p2)
-- Test whether the Manhattan distance between two points is smaller than
-- `epsilon'.
--
epsilonEqual :: Point -> Point -> Bool
epsilonEqual (x1 :*: y1) (x2 :*: y2) = abs (x1 - x2) + abs (y1 - y2) < epsilon
-- Calculates the centroid of a list of mass points.
--
centroid :: [MassPoint] -> MassPoint
centroid mps = let
m = sum [m | _ :*: m <- mps]
(wxs, wys) = unzip [(m * x, m * y) | (x :*: y) :*: m <- mps]
in
((sum wxs / m) :*: (sum wys / m)) :*: m
-- Calculates the total momentum.
--
totalMomentum :: [Particle] -> (Point :*: Double)
totalMomentum ps =
let
m = sum [m | ((_ :*: m) :*: _) <- ps]
(wxs, wys) = unzip [(m * x, m * y) | (_ :*: m) :*: (x:*: y) <- ps]
in
((sum wxs / m :*: sum wys / m) :*: m)
-- translate a particle
--
translate :: Point -> Particle -> Particle
translate (dx :*: dy) (((x :*: y) :*: m) :*: vxy) =
((x + dx :*: y + dy) :*: m) :*: vxy
-- translate the velocity of particle
--
translateVel :: Point -> Particle -> Particle
translateVel (dvx :*: dvy) (mp :*: (vx :*: vy)) =
mp :*: (vx + dvx :*: vy + dvy)
showBHTree:: BHTree -> String
showBHTree treeLevels = "Tree:" ++ concat (map showBHTreeLevel treeLevels)
showBHTreeLevel (massPnts, cents) = "\t" ++ show massPnts ++ "\n\t" ++
show cents ++ "\n" ++ "\t\t|\n\t\t|\n"
|
mainland/dph
|
icebox/examples/barnesHut/BarnesHutGen.hs
|
bsd-3-clause
| 8,011
| 54
| 22
| 2,448
| 2,695
| 1,500
| 1,195
| 159
| 1
|
{-# LANGUAGE TemplateHaskell, ForeignFunctionInterface #-}
module Graphics.Wayland.Internal.SpliceClientInternal where
import Data.Functor
import Language.Haskell.TH
import Foreign.C.Types
import Graphics.Wayland.Scanner.Protocol
import Graphics.Wayland.Scanner
import Graphics.Wayland.Internal.SpliceClientTypes
$(runIO readProtocol >>= generateClientInternal)
|
abooij/haskell-wayland
|
Graphics/Wayland/Internal/SpliceClientInternal.hs
|
mit
| 367
| 0
| 8
| 29
| 60
| 38
| 22
| 9
| 0
|
{-# LANGUAGE FlexibleContexts #-}
module CrawlProject where
import qualified Data.Map as Map
import qualified Elm.Compiler.Module as Module
import TheMasterPlan
( ModuleID(ModuleID), PackageID, Location(Location)
, PackageSummary(..), PackageData(..)
, ProjectSummary(..), ProjectData(..)
)
canonicalizePackageSummary
:: PackageID
-> PackageSummary
-> ProjectSummary Location
canonicalizePackageSummary package (PackageSummary pkgData natives foreignDependencies) =
ProjectSummary
{ projectData =
Map.map
(canonicalizePackageData package foreignDependencies)
(canonicalizeKeys pkgData)
, projectNatives =
Map.map (\path -> Location path package) (canonicalizeKeys natives)
}
where
canonicalizeKeys =
Map.mapKeysMonotonic (\name -> ModuleID name package)
canonicalizePackageData
:: PackageID
-> Map.Map Module.Name PackageID
-> PackageData
-> ProjectData Location
canonicalizePackageData package foreignDependencies (PackageData filePath deps) =
ProjectData {
projectLocation = Location filePath package,
projectDependencies = map canonicalizeModule deps
}
where
canonicalizeModule :: Module.Name -> ModuleID
canonicalizeModule moduleName =
case Map.lookup moduleName foreignDependencies of
Nothing -> ModuleID moduleName package
Just foreignPackage ->
ModuleID moduleName foreignPackage
union :: ProjectSummary a -> ProjectSummary a -> ProjectSummary a
union (ProjectSummary d natives) (ProjectSummary d' natives') =
ProjectSummary (Map.union d d') (Map.union natives natives')
|
mgold/elm-make
|
src/CrawlProject.hs
|
bsd-3-clause
| 1,680
| 0
| 10
| 360
| 397
| 214
| 183
| 40
| 2
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE PolyKinds #-}
module T14579b where
import Data.Kind
import Data.Proxy
-- type P :: forall {k} {t :: k}. Proxy t
type P = 'Proxy
-- type Wat :: forall a. Proxy a -> *
newtype Wat (x :: Proxy (a :: Type)) = MkWat (Maybe a)
deriving Eq
-- type Wat2 :: forall {a}. Proxy a -> *
type Wat2 = Wat
-- type Glurp :: * -> *
newtype Glurp a = MkGlurp (Wat2 (P :: Proxy a))
deriving Eq
|
sdiehl/ghc
|
testsuite/tests/deriving/should_compile/T14579b.hs
|
bsd-3-clause
| 467
| 1
| 9
| 100
| 96
| 61
| 35
| -1
| -1
|
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
-- we have lots of parsers which don't want signatures; and we have
-- uniplate patterns
{-# OPTIONS_GHC -fno-warn-missing-signatures
-fno-warn-incomplete-patterns
-fno-warn-name-shadowing #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Syntax.Haskell
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
--
-- NOTES:
-- Note if the layout of the first line (not comments)
-- is wrong the parser will only parse what is in the blocks given by Layout.hs
module Yi.Syntax.Haskell ( PModule
, PModuleDecl
, PImport
, Exp (..)
, Tree
, parse
, indentScanner
) where
import Control.Applicative (Alternative ((<|>), empty, many, some), optional)
import Control.Arrow ((&&&))
import Data.List ((\\))
import Data.Maybe (fromJust, isNothing)
import Yi.IncrementalParse
import Yi.Lexer.Alex (Posn (Posn, posnOfs), Tok (Tok, tokT),
startPosn, tokBegin)
import Yi.Lexer.Haskell
import Yi.Syntax (Scanner)
import Yi.Syntax.Layout (State, layoutHandler)
import Yi.Syntax.Tree (IsTree (emptyNode, uniplate), sepBy1)
indentScanner :: Scanner (AlexState lexState) TT
-> Scanner (Yi.Syntax.Layout.State Token lexState) TT
indentScanner = layoutHandler startsLayout [(Special '(', Special ')'),
(Reserved Let, Reserved In),
(Special '[', Special ']'),
(Special '{', Special '}')]
ignoredToken
(Special '<', Special '>', Special '.')
isBrace
-- HACK: We insert the Special '<', '>', '.', which do not occur in
-- normal haskell parsing.
-- | Check if a token is a brace, this function is used to
-- fix the layout so that do { works correctly
isBrace :: TT -> Bool
isBrace (Tok br _ _) = Special '{' == br
-- | Theese are the tokens ignored by the layout handler.
ignoredToken :: TT -> Bool
ignoredToken (Tok t _ (Posn{})) = isComment t || t == CppDirective
type Tree = PModule
type PAtom = Exp
type Block = Exp
type PGuard = Exp
type PModule = Exp
type PModuleDecl = Exp
type PImport = Exp
-- | Exp can be expression or declaration
data Exp t
= PModule { comments :: [t]
, progMod :: Maybe (PModule t)
}
| ProgMod { modDecl :: PModuleDecl t
, body :: PModule t -- ^ The module declaration part
}
| Body { imports :: Exp t -- [PImport t]
, content :: Block t
, extraContent :: Block t -- ^ The body of the module
}
| PModuleDecl { moduleKeyword :: PAtom t
, name :: PAtom t
, exports :: Exp t
, whereKeyword :: Exp t
}
| PImport { importKeyword :: PAtom t
, qual :: Exp t
, name' :: PAtom t
, as :: Exp t
, specification :: Exp t
}
| TS t [Exp t] -- ^ Type signature
| PType { typeKeyword :: PAtom t
, typeCons :: Exp t
, equal :: PAtom t
, btype :: Exp t
} -- ^ Type declaration
| PData { dataKeyword :: PAtom t
, dtypeCons :: Exp t
, dEqual :: Exp t
, dataRhs :: Exp t
} -- ^ Data declaration
| PData' { dEqual :: PAtom t
, dataCons :: Exp t -- ^ Data declaration RHS
}
| PClass { cKeyword :: PAtom t -- Can be class or instance
, cHead :: Exp t
, cwhere :: Exp t -- ^ Class declaration
}
-- declaration
-- declarations and parts of them follow
| Paren (PAtom t) [Exp t] (PAtom t) -- ^ A parenthesized, bracked or braced
| Block [Exp t] -- ^ A block of things separated by layout
| PAtom t [t] -- ^ An atom is a token followed by many comments
| Expr [Exp t] -- ^
| PWhere (PAtom t) (Exp t) (Exp t) -- ^ Where clause
| Bin (Exp t) (Exp t)
-- an error with comments following so we never color comments in wrong
-- color. The error has an extra token, the Special '!' token to
-- indicate that it contains an error
| PError { errorTok :: t
, marker :: t
, commentList :: [t] -- ^ An wrapper for errors
}
-- rhs that begins with Equal
| RHS (PAtom t) (Exp t) -- ^ Righthandside of functions with =
| Opt (Maybe (Exp t)) -- ^ An optional
| Modid t [t] -- ^ Module identifier
| Context (Exp t) (Exp t) (PAtom t) -- ^
| PGuard [PGuard t] -- ^ Righthandside of functions with |
-- the PAtom in PGuard' does not contain any comments
| PGuard' (PAtom t) (Exp t) (PAtom t)
-- type constructor is just a wrapper to indicate which highlightning to
-- use.
| TC (Exp t) -- ^ Type constructor
-- data constructor same as with the TC constructor
| DC (Exp t) -- ^ Data constructor
| PLet (PAtom t) (Exp t) (Exp t) -- ^ let expression
| PIn t [Exp t]
deriving (Show, Foldable)
instance IsTree Exp where
emptyNode = Expr []
uniplate tree = case tree of
(ProgMod a b) -> ([a,b], \[a,b] -> ProgMod a b)
(Body x exp exp') -> ([x, exp, exp'], \[x, exp, exp'] -> Body x exp exp')
(PModule x (Just e)) -> ([e],\[e] -> PModule x (Just e))
(Paren l g r) -> -- TODO: improve
(l:g ++ [r], \(l:gr) -> Paren l (init gr) (last gr))
(RHS l g) -> ([l,g],\[l,g] -> (RHS l g))
(Block s) -> (s,Block)
(PLet l s i) -> ([l,s,i],\[l,s,i] -> PLet l s i)
(PIn x ts) -> (ts,PIn x)
(Expr a) -> (a,Expr)
(PClass a b c) -> ([a,b,c],\[a,b,c] -> PClass a b c)
(PWhere a b c) -> ([a,b,c],\[a,b,c] -> PWhere a b c)
(Opt (Just x)) -> ([x],\[x] -> (Opt (Just x)))
(Bin a b) -> ([a,b],\[a,b] -> (Bin a b))
(PType a b c d) -> ([a,b,c,d],\[a,b,c,d] -> PType a b c d)
(PData a b c d) -> ([a,b,c,d],\[a,b,c,d] -> PData a b c d)
(PData' a b) -> ([a,b] ,\[a,b] -> PData' a b)
(Context a b c) -> ([a,b,c],\[a,b,c] -> Context a b c)
(PGuard xs) -> (xs,PGuard)
(PGuard' a b c) -> ([a,b,c],\[a,b,c] -> PGuard' a b c)
(TC e) -> ([e],\[e] -> TC e)
(DC e) -> ([e],\[e] -> DC e)
PModuleDecl a b c d -> ([a,b,c,d],\[a,b,c,d] -> PModuleDecl a b c d)
PImport a b c d e -> ([a,b,c,d,e],\[a,b,c,d,e] -> PImport a b c d e)
t -> ([],const t)
-- | The parser
parse :: P TT (Tree TT)
parse = pModule <* eof
-- | @pModule@ parse a module
pModule :: Parser TT (PModule TT)
pModule = PModule <$> pComments <*> optional
(pBlockOf' (ProgMod <$> pModuleDecl
<*> pModBody <|> pBody))
-- | Parse a body that follows a module
pModBody :: Parser TT (PModule TT)
pModBody = (exact [startBlock] *>
(Body <$> pImports
<*> ((pTestTok elems *> pBod)
<|> pEmptyBL) <* exact [endBlock]
<*> pBod
<|> Body <$> noImports
<*> ((pBod <|> pEmptyBL) <* exact [endBlock])
<*> pBod))
<|> (exact [nextLine] *> pBody)
<|> Body <$> pure emptyNode <*> pEmptyBL <*> pEmptyBL
where pBod = Block <$> pBlocks pTopDecl
elems = [Special ';', nextLine, startBlock]
-- | @pEmptyBL@ A parser returning an empty block
pEmptyBL :: Parser TT (Exp TT)
pEmptyBL = Block <$> pEmpty
-- | Parse a body of a program
pBody :: Parser TT (PModule TT)
pBody = Body <$> noImports <*> (Block <$> pBlocks pTopDecl) <*> pEmptyBL
<|> Body <$> pImports <*> ((pTestTok elems *> (Block <$> pBlocks pTopDecl))
<|> pEmptyBL) <*> pEmptyBL
where elems = [nextLine, startBlock]
noImports :: Parser TT (Exp TT)
noImports = notNext [Reserved Import] *> pure emptyNode
where notNext f = testNext $ uncurry (||) . (&&&) isNothing
(flip notElem f . tokT . fromJust)
-- Helper functions for parsing follows
-- | Parse Variables
pVarId :: Parser TT (Exp TT)
pVarId = pAtom [VarIdent, Reserved Other, Reserved As]
-- | Parse VarIdent and ConsIdent
pQvarid :: Parser TT (Exp TT)
pQvarid = pAtom [VarIdent, ConsIdent, Reserved Other, Reserved As]
-- | Parse an operator using please
pQvarsym :: Parser TT (Exp TT)
pQvarsym = pParen ((:) <$> please (PAtom <$> sym isOperator <*> pComments)
<*> pEmpty)
-- | Parse any operator
isOperator :: Token -> Bool
isOperator (Operator _) = True
isOperator (ReservedOp _) = True
isOperator (ConsOperator _) = True
isOperator _ = False
-- | Parse a consident
pQtycon :: Parser TT (Exp TT)
pQtycon = pAtom [ConsIdent]
-- | Parse many variables
pVars :: Parser TT (Exp TT)
pVars = pMany pVarId
-- | Parse a nextline token (the nexLine token is inserted by Layout.hs)
nextLine :: Token
nextLine = Special '.'
-- | Parse a startBlock token
startBlock :: Token
startBlock = Special '<'
-- | Parse a endBlock token
endBlock :: Token
endBlock = Special '>'
pEmpty :: Applicative f => f [a]
pEmpty = pure []
pToList :: Applicative f => f a -> f [a]
pToList = (box <$>)
where box x = [x]
-- | @sym f@ returns a parser parsing @f@ as a special symbol
sym :: (Token -> Bool) -> Parser TT TT
sym f = symbol (f . tokT)
-- | @exact tokList@ parse anything that is in @tokList@
exact :: [Token] -> Parser TT TT
exact = sym . flip elem
-- | @please p@ returns a parser parsing either @p@ or recovers with the
-- (Special '!') token.
please :: Parser TT (Exp TT) -> Parser TT (Exp TT)
please = (<|>) (PError <$> recoverWith errTok
<*> errTok
<*> pEmpty)
-- | Parse anything, as errors
pErr :: Parser TT (Exp TT)
pErr = PError <$> recoverWith (sym $ not . uncurry (||) . (&&&) isComment
(== CppDirective))
<*> errTok
<*> pComments
-- | Parse an ConsIdent
ppCons :: Parser TT (Exp TT)
ppCons = ppAtom [ConsIdent]
-- | Parse a keyword
pKW :: [Token] -> Parser TT (Exp TT) -> Parser TT (Exp TT)
pKW k r = Bin <$> pAtom k <*> r
-- | Parse an unary operator with and without using please
pOP :: [Token] -> Parser TT (Exp TT) -> Parser TT (Exp TT)
pOP op r = Bin <$> pAtom op <*> r
--ppOP op r = Bin <$> ppAtom op <*> r
-- | Parse comments
pComments :: Parser TT [TT]
pComments = many $ sym $ uncurry (||) . (&&&) isComment (== CppDirective)
-- | Parse something thats optional
pOpt :: Parser TT (Exp TT) -> Parser TT (Exp TT)
pOpt x = Opt <$> optional x
-- | Parse an atom with, and without using please
pAtom, ppAtom :: [Token] -> Parser TT (Exp TT)
pAtom = flip pCAtom pComments
ppAtom at = pAtom at <|> recoverAtom
recoverAtom :: Parser TT (Exp TT)
recoverAtom = PAtom <$> recoverWith errTok <*> pEmpty
-- | Parse an atom with optional comments
pCAtom :: [Token] -> Parser TT [TT] -> Parser TT (Exp TT)
pCAtom r c = PAtom <$> exact r <*> c
pBareAtom a = pCAtom a pEmpty
-- | @pSepBy p sep@ parse /zero/ or more occurences of @p@, separated
-- by @sep@, with optional ending @sep@,
-- this is quite similar to the sepBy function provided in
-- Parsec, but this one allows an optional extra separator at the end.
--
-- > commaSep p = p `pSepBy` (symbol (==(Special ',')))
pSepBy :: Parser TT (Exp TT) -> Parser TT (Exp TT) -> Parser TT [Exp TT]
pSepBy p sep = pEmpty
<|> (:) <$> p <*> (pSepBy1 p sep <|> pEmpty)
<|> pToList sep -- optional ending separator
where pSepBy1 r p' = (:) <$> p' <*> (pEmpty <|> pSepBy1 p' r)
-- | Separate a list of things separated with comma inside of parenthesis
pParenSep :: Parser TT (Exp TT) -> Parser TT (Exp TT)
pParenSep = pParen . flip pSepBy pComma
-- | Parse a comma separator
pComma :: Parser TT (Exp TT)
pComma = pAtom [Special ',']
-- End of helper functions Parsing different parts follows
-- | Parse a Module declaration
pModuleDecl :: Parser TT (PModuleDecl TT)
pModuleDecl = PModuleDecl <$> pAtom [Reserved Module]
<*> ppAtom [ConsIdent]
<*> pOpt (pParenSep pExport)
<*> (optional (exact [nextLine]) *>
(Bin <$> ppAtom [Reserved Where])
<*> pMany pErr) <* pTestTok elems
where elems = [nextLine, startBlock, endBlock]
pExport :: Parser TT (Exp TT)
pExport = optional (exact [nextLine]) *> please
( pVarId
<|> pEModule
<|> Bin <$> pQvarsym <*> (DC <$> pOpt expSpec) -- typeOperator
<|> Bin <$> (TC <$> pQtycon) <*> (DC <$> pOpt expSpec)
)
where expSpec = pParen (pToList (please (pAtom [ReservedOp DoubleDot]))
<|> pSepBy pQvarid pComma)
-- | Check if next token is in given list
pTestTok :: [Token] -> Parser TT ()
pTestTok f = testNext (uncurry (||) . (&&&) isNothing
(flip elem f . tokT . fromJust))
-- | Parse several imports
pImports :: Parser TT (Exp TT) -- [PImport TT]
pImports = Expr <$> many (pImport
<* pTestTok pEol
<* optional (some $ exact [nextLine, Special ';']))
where pEol = [Special ';', nextLine, endBlock]
-- | Parse one import
pImport :: Parser TT (PImport TT)
pImport = PImport <$> pAtom [Reserved Import]
<*> pOpt (pAtom [Reserved Qualified])
<*> ppAtom [ConsIdent]
<*> pOpt (pKW [Reserved As] ppCons)
<*> (TC <$> pImpSpec)
where pImpSpec = Bin <$> pKW [Reserved Hiding]
(please pImpS) <*> pMany pErr
<|> Bin <$> pImpS <*> pMany pErr
<|> pMany pErr
pImpS = DC <$> pParenSep pExp'
pExp' = Bin
<$> (PAtom <$> sym
(uncurry (||) . (&&&)
(`elem` [VarIdent, ConsIdent])
isOperator) <*> pComments
<|> pQvarsym)
<*> pOpt pImpS
-- | Parse simple type synonyms
pType :: Parser TT (Exp TT)
pType = PType <$> (Bin <$> pAtom [Reserved Type]
<*> pOpt (pAtom [Reserved Instance]))
<*> (TC . Expr <$> pTypeExpr')
<*> ppAtom [ReservedOp Equal]
<*> (TC . Expr <$> pTypeExpr')
-- | Parse data declarations
pData :: Parser TT (Exp TT)
pData = PData <$> pAtom [Reserved Data, Reserved NewType]
<*> (TC . Expr <$> pTypeExpr')
<*> pOpt (pDataRHS <|> pGadt)
<*> pOpt pDeriving
pGadt :: Parser TT (Exp TT)
pGadt = pWhere pTypeDecl
-- | Parse second half of the data declaration, if there is one
pDataRHS :: Parser TT (Exp TT)
pDataRHS = PData' <$> pAtom [ReservedOp Equal] <*> pConstrs
-- | Parse a deriving
pDeriving :: Parser TT (Exp TT)
pDeriving = pKW [Reserved Deriving] (TC . Expr <$> pTypeExpr')
pAtype :: Parser TT (Exp TT)
pAtype = pAtype'
<|> pErr
pAtype' :: Parser TT (Exp TT)
pAtype' = pTypeCons
<|> pParen (many $ pExprElem [])
<|> pBrack (many $ pExprElem [])
pTypeCons :: Parser TT (Exp TT)
pTypeCons = Bin <$> pAtom [ConsIdent]
<*> please (pMany $ pAtom [VarIdent, ConsIdent])
pContext :: Parser TT (Exp TT)
pContext = Context <$> pOpt pForAll
<*> (TC <$> (pClass' <|> pParenSep pClass'))
<*> ppAtom [ReservedOp DoubleRightArrow]
where pClass' :: Parser TT (Exp TT)
pClass' = Bin <$> pQtycon
<*> (please pVarId
<|> pParen ((:) <$> please pVarId
<*> many pAtype'))
-- | Parse for all
pForAll :: Parser TT (Exp TT)
pForAll = pKW [Reserved Forall]
(Bin <$> pVars <*> ppAtom [Operator "."])
pConstrs :: Parser TT (Exp TT)
pConstrs = Bin <$> (Bin <$> pOpt pContext <*> pConstr)
<*> pMany (pOP [ReservedOp Pipe]
(Bin <$> pOpt pContext <*> please pConstr))
pConstr :: Parser TT (Exp TT)
pConstr = Bin <$> pOpt pForAll
<*> (Bin <$>
(Bin <$> (DC <$> pAtype) <*>
(TC <$> pMany (strictF pAtype))) <*> pOpt st)
<|> Bin <$> lrHs <*> pMany (strictF pAtype)
<|> pErr
where lrHs = pOP [Operator "!"] pAtype
st = pEBrace (pTypeDecl `sepBy1` pBareAtom [Special ','])
-- named fields declarations
-- | Parse optional strict variables
strictF :: Parser TT (Exp TT) -> Parser TT (Exp TT)
strictF a = Bin <$> pOpt (pAtom [Operator "!"]) <*> a
-- | Exporting module
pEModule ::Parser TT (Exp TT)
pEModule = pKW [Reserved Module]
$ please (Modid <$> exact [ConsIdent] <*> pComments)
-- | Parse a Let expression
pLet :: Parser TT (Exp TT)
pLet = PLet <$> pAtom [Reserved Let]
<*> pBlock pFunDecl
<*> pOpt (pBareAtom [Reserved In])
-- | Parse a Do block
pDo :: Parser TT (Exp TT)
pDo = Bin <$> pAtom [Reserved Do]
<*> pBlock (pExpr ((Special ';' : recognizedSometimes)
\\ [ReservedOp LeftArrow]))
-- | Parse part of a lambda binding.
pLambda :: Parser TT (Exp TT)
pLambda = Bin <$> pAtom [ReservedOp BackSlash]
<*> (Bin <$> (Expr <$> pPattern)
<*> please (pBareAtom [ReservedOp RightArrow]))
-- | Parse an Of block
pOf :: Parser TT (Exp TT)
pOf = Bin <$> pAtom [Reserved Of]
<*> pBlock pAlternative
pAlternative = Bin <$> (Expr <$> pPattern)
<*> please (pFunRHS (ReservedOp RightArrow))
-- | Parse classes and instances
-- This is very imprecise, but shall suffice for now.
-- At least is does not complain too often.
pClass :: Parser TT (Exp TT)
pClass = PClass <$> pAtom [Reserved Class, Reserved Instance]
<*> (TC . Expr <$> pTypeExpr')
<*> pOpt (please (pWhere pTopDecl))
-- use topDecl since we have associated types and such.
-- | Parse some guards and a where clause
pGuard :: Token -> Parser TT (Exp TT)
pGuard equalSign = PGuard
<$> some (PGuard' <$> pCAtom [ReservedOp Pipe] pEmpty <*>
-- comments are by default parsed after this
pExpr (recognizedSometimes
-- these two symbols can appear in guards.
\\ [ReservedOp LeftArrow, Special ','])
<*> please (pEq equalSign))
-- this must be -> if used in case
-- | Right-hand-side of a function or case equation (after the pattern)
pFunRHS :: Token -> Parser TT (Exp TT)
pFunRHS equalSign =
Bin <$> (pGuard equalSign <|> pEq equalSign) <*> pOpt (pWhere pFunDecl)
pWhere :: Parser TT (Exp TT) -> Parser TT (Exp TT)
pWhere p =
PWhere <$> pAtom [Reserved Where] <*> please (pBlock p) <*> pMany pErr
-- After a where there might "misaligned" code that do not "belong" to anything.
-- Here we swallow it as errors.
-- Note that this can both parse an equation and a type declaration.
-- Since they can start with the same token, the left part is factored here.
pDecl :: Bool -> Bool -> Parser TT (Exp TT)
pDecl acceptType acceptEqu =
Expr <$> ((Yuck $
Enter "missing end of type or equation declaration" $ pure [])
<|> ((:) <$> pElem False recognizedSometimes
<*> pToList (pDecl acceptType acceptEqu))
<|> ((:) <$> pBareAtom [Special ',']
<*> pToList (pDecl acceptType False))
-- if a comma is found, then the rest must be a type
-- declaration.
<|> (if acceptType then pTypeEnding else empty)
<|> (if acceptEqu then pEquEnding else empty))
where pTypeEnding = (:) <$> (TS <$> exact [ReservedOp DoubleColon]
<*> pTypeExpr') <*> pure []
pEquEnding = (:) <$> pFunRHS (ReservedOp Equal) <*> pure []
pFunDecl = pDecl True True
pTypeDecl = pDecl True False
--pEquation = pDecl False True
-- | The RHS of an equation.
pEq :: Token -> Parser TT (Exp TT)
pEq equalSign = RHS <$> pBareAtom [equalSign] <*> pExpr'
-- | Parse many of something
pMany :: Parser TT (Exp TT) -> Parser TT (Exp TT)
pMany p = Expr <$> many p
-- | Parse a some of something separated by the token (Special '.')
pBlocks :: Parser TT r -> Parser TT [r]
pBlocks p = p `sepBy1` exact [nextLine]
-- | Parse a some of something separated by the token (Special '.'), or nothing
--pBlocks' :: Parser TT r -> Parser TT (BL.BList r)
pBlocks' p = pBlocks p <|> pure []
-- | Parse a block of some something separated by the tok (Special '.')
pBlockOf :: Parser TT (Exp TT) -> Parser TT (Exp TT)
pBlockOf p = Block <$> pBlockOf' (pBlocks p) -- see HACK above
pBlock :: Parser TT (Exp TT) -> Parser TT (Exp TT)
pBlock p = pBlockOf' (Block <$> pBlocks' p)
<|> pEBrace (p `sepBy1` exact [Special ';'] <|> pure [])
<|> (Yuck $ Enter "block expected" pEmptyBL)
-- | Parse something surrounded by (Special '<') and (Special '>')
pBlockOf' :: Parser TT a -> Parser TT a
pBlockOf' p = exact [startBlock] *> p <* exact [endBlock] -- see HACK above
-- note that, by construction, '<' and '>' will always be matched, so
-- we don't try to recover errors with them.
-- | Parse something that can contain a data, type declaration or a class
pTopDecl :: Parser TT (Exp TT)
pTopDecl = pFunDecl
<|> pType
<|> pData
<|> pClass
<|> pure emptyNode
-- | A "normal" expression, where none of the following symbols are acceptable.
pExpr' = pExpr recognizedSometimes
recognizedSometimes = [ReservedOp DoubleDot,
Special ',',
ReservedOp Pipe,
ReservedOp Equal,
ReservedOp LeftArrow,
ReservedOp RightArrow,
ReservedOp DoubleRightArrow,
ReservedOp BackSlash,
ReservedOp DoubleColon
]
-- | Parse an expression, as a concatenation of elements.
pExpr :: [Token] -> Parser TT (Exp TT)
pExpr at = Expr <$> pExprOrPattern True at
-- | Parse an expression, as a concatenation of elements.
pExprOrPattern :: Bool -> [Token] -> Parser TT [Exp TT]
pExprOrPattern isExpresssion at =
pure []
<|> ((:) <$> pElem isExpresssion at <*> pExprOrPattern True at)
<|> ((:) <$> (TS <$> exact [ReservedOp DoubleColon] <*> pTypeExpr')
<*> pure [])
-- TODO: not really correct: in (x :: X , y :: Z), all after the
-- first :: will be a "type".
pPattern = pExprOrPattern False recognizedSometimes
pExprElem = pElem True
-- | Parse an "element" of an expression or a pattern.
-- "at" is a list of symbols that, if found, should be considered errors.
pElem :: Bool -> [Token] -> Parser TT (Exp TT)
pElem isExpresssion at =
pCParen (pExprOrPattern isExpresssion
-- might be a tuple, so accept commas as noise
(recognizedSometimes \\ [Special ','])) pEmpty
<|> pCBrack (pExprOrPattern isExpresssion
(recognizedSometimes \\ [ ReservedOp DoubleDot, ReservedOp Pipe
, ReservedOp LeftArrow
, Special ','])) pEmpty -- list thing
<|> pCBrace (many $ pElem isExpresssion
-- record: TODO: improve
(recognizedSometimes \\ [ ReservedOp Equal, Special ','
, ReservedOp Pipe])) pEmpty
<|> (Yuck $ Enter "incorrectly placed block" $
-- no error token, but the previous keyword will be one. (of, where, ...)
pBlockOf (pExpr recognizedSometimes))
<|> (PError <$> recoverWith
(sym $ flip elem $ isNoiseErr at) <*> errTok <*> pEmpty)
<|> (PAtom <$> sym (`notElem` isNotNoise at) <*> pEmpty)
<|> if isExpresssion then pLet <|> pDo <|> pOf <|> pLambda else empty
-- TODO: support type expressions
pTypeExpr at = many (pTypeElem at)
pTypeExpr' = pTypeExpr (recognizedSometimes \\ [ReservedOp RightArrow,
ReservedOp DoubleRightArrow])
pTypeElem :: [Token] -> Parser TT (Exp TT)
pTypeElem at
= pCParen (pTypeExpr (recognizedSometimes
\\ [ ReservedOp RightArrow,
ReservedOp DoubleRightArrow,
-- might be a tuple, so accept commas as noise
Special ','])) pEmpty
<|> pCBrack pTypeExpr' pEmpty
<|> pCBrace pTypeExpr' pEmpty -- TODO: this is an error: mark as such.
<|> (Yuck $ Enter "incorrectly placed block" $
pBlockOf (pExpr recognizedSometimes))
<|> (PError <$> recoverWith
(sym $ flip elem $ isNoiseErr at) <*> errTok <*> pEmpty)
<|> (PAtom <$> sym (`notElem` isNotNoise at) <*> pEmpty)
-- | List of things that always should be parsed as errors
isNoiseErr :: [Token] -> [Token]
isNoiseErr r = recoverableSymbols ++ r
recoverableSymbols = recognizedSymbols \\ fmap Special "([{<>."
-- We just don't recover opening symbols (only closing are "fixed").
-- Layout symbols "<>." are never recovered, because layout is
-- constructed correctly.
-- | List of things that should not be parsed as noise
isNotNoise :: [Token] -> [Token]
isNotNoise r = recognizedSymbols ++ r
-- | These symbols are always properly recognized, and therefore they
-- should never be accepted as "noise" inside expressions.
recognizedSymbols =
[ Reserved Let
, Reserved In
, Reserved Do
, Reserved Of
, Reserved Class
, Reserved Instance
, Reserved Deriving
, Reserved Module
, Reserved Import
, Reserved Type
, Reserved Data
, Reserved NewType
, Reserved Where] ++ fmap Special "()[]{}<>."
-- | Parse parenthesis, brackets and braces containing
-- an expression followed by possible comments
pCParen, pCBrace, pCBrack
:: Parser TT [Exp TT] -> Parser TT [TT] -> Parser TT (Exp TT)
pCParen p c = Paren <$> pCAtom [Special '('] c
<*> p <*> (recoverAtom <|> pCAtom [Special ')'] c)
pCBrace p c = Paren <$> pCAtom [Special '{'] c
<*> p <*> (recoverAtom <|> pCAtom [Special '}'] c)
pCBrack p c = Paren <$> pCAtom [Special '['] c
<*> p <*> (recoverAtom <|> pCAtom [Special ']'] c)
pParen, pBrack :: Parser TT [Exp TT] -> Parser TT (Exp TT)
pParen = flip pCParen pComments
--pBrace = flip pCBrace pComments
pBrack = flip pCBrack pComments
-- pEBrace parse an opening brace, followed by zero comments
-- then followed by an closing brace and some comments
pEBrace p = Paren <$> pCAtom [Special '{'] pEmpty
<*> p <*> (recoverAtom <|> pCAtom [Special '}'] pComments)
-- | Create a special error token. (e.g. fill in where there is no
-- correct token to parse) Note that the position of the token has to
-- be correct for correct computation of node spans.
errTok = mkTok <$> curPos
where curPos = tB <$> lookNext
tB Nothing = maxBound
tB (Just x) = tokBegin x
mkTok p = Tok (Special '!') 0 (startPosn {posnOfs = p})
|
siddhanathan/yi
|
yi-mode-haskell/src/Yi/Syntax/Haskell.hs
|
gpl-2.0
| 27,431
| 0
| 24
| 8,424
| 8,009
| 4,276
| 3,733
| 477
| 3
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{- Printf.hs -}
module TH.Printf where
-- Skeletal printf from the paper.
-- It needs to be in a separate module to the one where
-- you intend to use it.
-- Import some Template Haskell syntax
-- import Language.Haskell.THSyntax
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import qualified Language.Haskell.TH as TH
-- Describe a format string
data Format = D | S | L String
-- Parse a format string. This is left largely to you
-- as we are here interested in building our first ever
-- Template Haskell program and not in building printf.
parse :: String -> [Format]
parse s = [ L s ]
-- Generate Haskell source code from a parsed representation
-- of the format string. This code will be spliced into
-- the module which calls "pr", at compile time.
gen :: [Format] -> ExpQ
gen [D] = [| \n -> show n |]
gen [S] = [| \s -> s |]
gen [L s] = stringE s
-- Here we generate the Haskell code for the splice
-- from an input format string.
pr :: String -> ExpQ
pr s = gen (parse s)
-- str :: QuasiQuoter
-- str = QuasiQuoter { quoteExp = stringE }
silly :: QuasiQuoter
silly = QuasiQuoter { quoteExp = \_ -> [| "yeah!!!" |] }
silly2 :: QuasiQuoter
silly2 = QuasiQuoter { quoteExp = \_ -> stringE "yeah!!!"
, quotePat = undefined
, quoteType = undefined
, quoteDec = undefined
}
|
RefactoringTools/HaRe
|
test/testdata/TH/Printf.hs
|
bsd-3-clause
| 1,460
| 0
| 8
| 359
| 241
| 152
| 89
| 22
| 1
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
module T9036 where
import Data.Kind
class UncurryM t where
type GetMonad t :: Type -> Type
class Curry a b where
type Curried a b :: Type
gSimple :: String -> String -> [String]
gSimple = simpleLogger (return ())
simpleLogger :: Maybe (GetMonad t after) -> t `Curried` [t]
simpleLogger _ _ = undefined
|
sdiehl/ghc
|
testsuite/tests/indexed-types/should_fail/T9036.hs
|
bsd-3-clause
| 413
| 0
| 8
| 77
| 123
| 69
| 54
| -1
| -1
|
{-# LANGUAGE TypeOperators, TypeFamilies #-}
module T2544 where
data (:|:) a b = Inl a | Inr b
class Ix i where
type IxMap i :: * -> *
empty :: IxMap i [Int]
data BiApp a b c = BiApp (a c) (b c)
instance (Ix l, Ix r) => Ix (l :|: r) where
type IxMap (l :|: r) = BiApp (IxMap l) (IxMap r)
empty = BiApp empty empty
|
frantisekfarka/ghc-dsi
|
testsuite/tests/indexed-types/should_fail/T2544.hs
|
bsd-3-clause
| 345
| 0
| 8
| 103
| 155
| 87
| 68
| 10
| 0
|
-- !!! Malformed infix expression
module M where
f a b c = a==b==c
|
ezyang/ghc
|
testsuite/tests/module/mod61.hs
|
bsd-3-clause
| 67
| 0
| 6
| 14
| 25
| 14
| 11
| -1
| -1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.