code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
module Paths_sandlib ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,0,3], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/home/vertexclique/.cabal/bin" libdir = "/home/vertexclique/.cabal/lib/sandlib-0.0.3/ghc-7.4.1" datadir = "/home/vertexclique/.cabal/share/sandlib-0.0.3" libexecdir = "/home/vertexclique/.cabal/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "sandlib_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "sandlib_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "sandlib_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "sandlib_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
vertexclique/sandlib
dist/build/autogen/Paths_sandlib.hs
Haskell
bsd-3-clause
1,149
-- | Errors that may occur during decoding/encoding of HTTP message bodies module Network.HTTP.Encoding.Error (EncodingError (..) ,ConversionError (..)) where import Codec.Text.IConv (ConversionError ,reportConversionError) -- | Encoding/Decoding error message data EncodingError = CannotDetermineCharacterEncoding -- ^ Character decoding is not specified and -- cannot be guessed | UnsupportedCompressionAlgorithm -- ^ A compression algorithm is not supported (LZW) | IConvError ConversionError -- ^ IConv conversion error | GenericError String -- ^ Other error instance Show EncodingError where show err = case err of CannotDetermineCharacterEncoding -> "No character encoding was specified in message headers \ \and the body character encoding cannot be determined" UnsupportedCompressionAlgorithm -> "Sorry, the 'compress' algorithm is not supported at this time" IConvError conv_err -> "Charset conversion error in iconv: " ++ show (reportConversionError conv_err) GenericError err -> "Generic error: " ++ err
achudnov/http-encodings
Network/HTTP/Encoding/Error.hs
Haskell
bsd-3-clause
1,337
{-# LANGUAGE UnicodeSyntax #-} module Shake.It.FileSystem ( module FileSystem ) where import Shake.It.FileSystem.Dir as FileSystem import Shake.It.FileSystem.File as FileSystem
Heather/Shake.it.off
src/Shake/It/FileSystem.hs
Haskell
bsd-3-clause
204
{-# LANGUAGE TypeOperators #-} module Web.ApiAi.API ( module Import , ApiAiAPI ) where import Servant.API import Web.ApiAi.API.Core as Import import Web.ApiAi.API.Entities as Import import Web.ApiAi.API.Query as Import type ApiAiAPI = ApiAiEntitiesAPI :<|> ApiAiQueryAPI
CthulhuDen/api-ai
src/Web/ApiAi/API.hs
Haskell
bsd-3-clause
286
----------------------------------------------------------------------------- -- | -- Module : Distribution.Make -- Copyright : Martin Sj&#xF6;gren 2004 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- This is an alternative build system that delegates everything to the @make@ -- program. All the commands just end up calling @make@ with appropriate -- arguments. The intention was to allow preexisting packages that used -- makefiles to be wrapped into Cabal packages. In practice essentially all -- such packages were converted over to the \"Simple\" build system instead. -- Consequently this module is not used much and it certainly only sees cursory -- maintenance and no testing. Perhaps at some point we should stop pretending -- that it works. -- -- Uses the parsed command-line from Distribution.Setup in order to build -- Haskell tools using a backend build system based on make. Obviously we -- assume that there is a configure script, and that after the ConfigCmd has -- been run, there is a Makefile. Further assumptions: -- -- [ConfigCmd] We assume the configure script accepts -- @--with-hc@, -- @--with-hc-pkg@, -- @--prefix@, -- @--bindir@, -- @--libdir@, -- @--libexecdir@, -- @--datadir@. -- -- [BuildCmd] We assume that the default Makefile target will build everything. -- -- [InstallCmd] We assume there is an @install@ target. Note that we assume that -- this does *not* register the package! -- -- [CopyCmd] We assume there is a @copy@ target, and a variable @$(destdir)@. -- The @copy@ target should probably just invoke @make install@ -- recursively (e.g. @$(MAKE) install prefix=$(destdir)\/$(prefix) -- bindir=$(destdir)\/$(bindir)@. The reason we can\'t invoke @make -- install@ directly here is that we don\'t know the value of @$(prefix)@. -- -- [SDistCmd] We assume there is a @dist@ target. -- -- [RegisterCmd] We assume there is a @register@ target and a variable @$(user)@. -- -- [UnregisterCmd] We assume there is an @unregister@ target. -- -- [HaddockCmd] We assume there is a @docs@ or @doc@ target. -- copy : -- $(MAKE) install prefix=$(destdir)/$(prefix) \ -- bindir=$(destdir)/$(bindir) \ {- All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Isaac Jones nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Distribution.Make ( module Distribution.Package, License(..), Version(..), defaultMain, defaultMainArgs, defaultMainNoRead ) where -- local import Distribution.Package --must not specify imports, since we're exporting moule. import Distribution.Simple.Program(defaultProgramConfiguration) import Distribution.PackageDescription import Distribution.Simple.Setup import Distribution.Simple.Command import Distribution.Simple.Utils (rawSystemExit, cabalVersion) import Distribution.License (License(..)) import Distribution.Version ( Version(..) ) import Distribution.Text ( display ) import System.Environment (getArgs, getProgName) import Data.List (intersperse) import System.Exit defaultMain :: IO () defaultMain = getArgs >>= defaultMainArgs defaultMainArgs :: [String] -> IO () defaultMainArgs = defaultMainHelper {-# DEPRECATED defaultMainNoRead "it ignores its PackageDescription arg" #-} defaultMainNoRead :: PackageDescription -> IO () defaultMainNoRead = const defaultMain defaultMainHelper :: [String] -> IO () defaultMainHelper args = case commandsRun globalCommand commands args of CommandHelp help -> printHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo (flags, commandParse) -> case commandParse of _ | fromFlag (globalVersion flags) -> printVersion | fromFlag (globalNumericVersion flags) -> printNumericVersion CommandHelp help -> printHelp help CommandList opts -> printOptionsList opts CommandErrors errs -> printErrors errs CommandReadyToGo action -> action where printHelp help = getProgName >>= putStr . help printOptionsList = putStr . unlines printErrors errs = do putStr (concat (intersperse "\n" errs)) exitWith (ExitFailure 1) printNumericVersion = putStrLn $ display cabalVersion printVersion = putStrLn $ "Cabal library version " ++ display cabalVersion progs = defaultProgramConfiguration commands = [configureCommand progs `commandAddAction` configureAction ,buildCommand progs `commandAddAction` buildAction ,installCommand `commandAddAction` installAction ,copyCommand `commandAddAction` copyAction ,haddockCommand `commandAddAction` haddockAction ,cleanCommand `commandAddAction` cleanAction ,sdistCommand `commandAddAction` sdistAction ,registerCommand `commandAddAction` registerAction ,unregisterCommand `commandAddAction` unregisterAction ] configureAction :: ConfigFlags -> [String] -> IO () configureAction flags args = do noExtraFlags args let verbosity = fromFlag (configVerbosity flags) rawSystemExit verbosity "sh" $ "configure" : configureArgs backwardsCompatHack flags where backwardsCompatHack = True copyAction :: CopyFlags -> [String] -> IO () copyAction flags args = do noExtraFlags args let destArgs = case fromFlag $ copyDest flags of NoCopyDest -> ["install"] CopyTo path -> ["copy", "destdir=" ++ path] CopyPrefix path -> ["install", "prefix=" ++ path] -- CopyPrefix is backwards compat, DEPRECATED rawSystemExit (fromFlag $ copyVerbosity flags) "make" destArgs installAction :: InstallFlags -> [String] -> IO () installAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ installVerbosity flags) "make" ["install"] rawSystemExit (fromFlag $ installVerbosity flags) "make" ["register"] haddockAction :: HaddockFlags -> [String] -> IO () haddockAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ haddockVerbosity flags) "make" ["docs"] `catch` \_ -> rawSystemExit (fromFlag $ haddockVerbosity flags) "make" ["doc"] buildAction :: BuildFlags -> [String] -> IO () buildAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ buildVerbosity flags) "make" [] cleanAction :: CleanFlags -> [String] -> IO () cleanAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ cleanVerbosity flags) "make" ["clean"] sdistAction :: SDistFlags -> [String] -> IO () sdistAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ sDistVerbosity flags) "make" ["dist"] registerAction :: RegisterFlags -> [String] -> IO () registerAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ regVerbosity flags) "make" ["register"] unregisterAction :: RegisterFlags -> [String] -> IO () unregisterAction flags args = do noExtraFlags args rawSystemExit (fromFlag $ regVerbosity flags) "make" ["unregister"]
dcreager/cabal
Distribution/Make.hs
Haskell
bsd-3-clause
8,739
-- | Here we use @dynamic-object@ to descibe the concept of point-like particles from -- classical mechanics. Also read the HSpec tests : -- <https://github.com/nushio3/dynamic-object/blob/master/test/ObjectSpec.hs> -- for more details. {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module Data.Object.Dynamic.Examples.PointParticle (Vec(..), Mass(..), Velocity(..), Momentum(..), KineticEnergy(..), mass, velocity, momentum, kineticEnergy, fromMassVelocity, fromMassMomentum, laserBeam, duck, lens, banana, envelope, ghost ) where import Control.Applicative hiding (empty) import Control.Lens hiding (lens) import Data.Dynamic import Data.String import Test.QuickCheck import Data.Object.Dynamic import Data.Object.Dynamic.Type -- $setup -- >>> :set -XOverloadedStrings -- >>> :set -XScopedTypeVariables -- >>> import Data.Object.Dynamic.Presets -- >>> import Data.Maybe -- | First, let us create a tiny two-dimensional vector class. -- We make it an instance of 'Arbitrary' to use them later for tests. data Vec a = Vec a a deriving (Eq, Show, Ord, Typeable) instance (Arbitrary a) => Arbitrary (Vec a) where arbitrary = Vec <$> arbitrary <*> arbitrary shrink (Vec x y) = Vec <$> shrink x <*> shrink y -- | Now, let us introduce the concepts of 'Mass', 'Velocity', -- 'Momentum' and 'KineticEnergy'. Any such concepts are described -- in terms of 'Member' labels. data Mass = Mass deriving (Typeable) instance (Objective o, UseReal o) => Member o Mass where type ValType o Mass = UnderlyingReal o -- | To define a member with compound types like vector of real numbers, -- we use 'UnderlyingReal' to -- ask the object which real value it prefers, then put the response -- into the type constructors. -- -- We also give a fallback accessor here. If the 'velocity' field is missing, we attempt to re-calculate it -- from the 'mass' and 'momentum'. Here is how we can do that. data Velocity = Velocity deriving (Typeable) instance (Objective o, UseReal o, Fractional (UnderlyingReal o)) => Member o Velocity where type ValType o Velocity = Vec (UnderlyingReal o) memberLookup = acyclically $ do m <- its Mass Vec mx my <- its Momentum return $ Vec (mx/m) (my/m) -- | If the 'momentum' field is missing, we re-calculate it -- from the 'mass' and 'velocity'. data Momentum = Momentum deriving (Typeable) instance (Objective o, UseReal o, Fractional (UnderlyingReal o)) => Member o Momentum where type ValType o Momentum = Vec (UnderlyingReal o) memberLookup = acyclically $ do m <- its Mass Vec vx vy <- its Velocity return $ Vec (m * vx) (m * vy) -- | 'kineticEnergy', unless given explicitly, is defined in terms of 'mass' and 'velocity' . data KineticEnergy = KineticEnergy deriving (Typeable) instance (Objective o, UseReal o, Fractional (UnderlyingReal o)) => Member o KineticEnergy where type ValType o KineticEnergy = UnderlyingReal o memberLookup = acyclically $ do m <- its Mass Vec vx vy <- its Velocity return $ ((m * vx * vx) + (m * vy * vy)) / 2 -- | Now we define the lenses. mass :: MemberLens o Mass mass = memberLens Mass velocity :: MemberLens o Velocity velocity = memberLens Velocity momentum :: (UseReal o, Fractional (UnderlyingReal o)) => MemberLens o Momentum momentum = memberLens Momentum kineticEnergy :: (UseReal o, Fractional (UnderlyingReal o)) => MemberLens o KineticEnergy kineticEnergy = memberLens KineticEnergy -- | We can write functions that would construct a point particle from -- its mass and velocity. And we can make the function polymorphic over the -- representation of the real numbers the objects prefer. fromMassVelocity :: (Objective o, UseReal o, Fractional real, real ~ (UnderlyingReal o)) => real -> Vec real -> o fromMassVelocity m v = empty & insert Mass m & insert Velocity v -- | We can also construct a point particle from -- its mass and momentum. fromMassMomentum :: (Objective o, UseReal o, Fractional real, real ~ (UnderlyingReal o)) => real -> Vec real -> o fromMassMomentum m v = empty & insert Mass m & insert Momentum v -- | We define an instance of point-like particle. And again, we can -- keep it polymorphic, so that anyone can choose its concrete type -- later, according to their purpose. Thus we will achieve the -- polymorphic encoding of the knowledge of this world, in Haskell. -- -- >>> (laserBeam :: Object DIT) ^? kineticEnergy -- Just 1631.25 -- >>> (laserBeam :: Object Precise) ^? kineticEnergy -- Just (6525 % 4) -- -- Moreover, we can ask Ichiro to sign the ball. Usually, we needed to -- create a new data-type to add a new field. But with -- 'dynamic-object' we can do so without changing the type of the -- ball. So, we can put our precious, one-of-a-kind ball -- into toybox together with less uncommon balls, and with various -- other toys. And still, we can safely access the contents of the -- toybox without runtime errors, and e.g. see which toy is the heaviest. -- -- >>> let (mySpecialBall :: Object DIT) = laserBeam & insert Autograph "Ichiro Suzuki" -- >>> let toybox = [laserBeam, mySpecialBall] -- >>> let toybox2 = toybox ++ [duck, lens, banana, envelope, ghost] -- >>> maximum $ mapMaybe (^?mass) toybox2 -- 5.2 laserBeam :: (Objective o, UseReal o, Fractional real, real ~ (UnderlyingReal o)) => o laserBeam = fromMassVelocity 0.145 (Vec 150 0) -- a baseball thrown by -- Ichiro duck, lens, banana :: (Objective o, UseReal o, Fractional real, real ~ (UnderlyingReal o)) => o duck = empty & insert Mass 5.2 lens = empty & insert Mass 0.56 banana = empty & insert Mass 0.187 envelope :: (Objective o, UseReal o, UseString o, Fractional (UnderlyingReal o), IsString (UnderlyingString o)) => o envelope = empty & insert Mass 0.025 & insert Autograph (fromString "Edward Kmett") ghost :: (Objective o) => o ghost = empty data Autograph = Autograph deriving Typeable instance (Objective o, UseString o) => Member o Autograph where type ValType o Autograph = UnderlyingString o
nushio3/dynamic-object
Data/Object/Dynamic/Examples/PointParticle.hs
Haskell
bsd-3-clause
6,339
module Main (main) where import D12Lib import System.Environment (getArgs) import Text.Parsec.String (parseFromFile) main :: IO () main = do file <- head <$> getArgs parseResult <- parseFromFile instructionsP file let instructions = either (error . show) id parseResult let vm = newVM instructions let vmRan = run vm putStrLn $ "final VM part 1: " ++ show vmRan let vm2 = newVM2 instructions let vm2Ran = run vm2 putStrLn $ "final VM part 2: " ++ show vm2Ran
wfleming/advent-of-code-2016
2016/app/D12.hs
Haskell
bsd-3-clause
481
{-# LANGUAGE OverloadedStrings #-} module InvalidateCacheTestCommon (test1Common) where import qualified Data.ByteString.Char8 as BS test1Common lookup3 keysCached3 invalidateCache3 = do b <- lookup3 ("file1" :: BS.ByteString) b <- lookup3 "file2" b <- lookup3 "file3" b <- lookup3 "file2" b <- lookup3 "file3" shouldBe 3 "file3" b <- lookup3 "file1" b <- lookup3 "file2" b <- lookup3 "file3" b <- lookup3 "file1" shouldBe 3 "file1" b <- lookup3 "file1" b <- lookup3 "file2" b <- lookup3 "file3" b <- lookup3 "file4" b <- lookup3 "file5" b <- lookup3 "file2" shouldBe 5 "file2" b <- lookup3 "file1" b <- lookup3 "file2" b <- lookup3 "file3" b <- lookup3 "file4" b <- lookup3 "file5" b <- lookup3 "file6" b <- lookup3 "file7" b <- lookup3 "file8" b <- lookup3 "file9" b <- lookup3 "file3" shouldBe 9 "file3" return () where shouldBe count lastkey = do l <- keysCached3 putStrLn $ show l if count == (length l) then do kv <- invalidateCache3 putStrLn $ show kv case kv of Just (k, v) | k == lastkey -> do l2 <- keysCached3 if 0 == (length l2) then return () else error "Did not fully invalidate" else error "Wrong length"
elblake/expiring-cache-map
tests/InvalidateCacheTestCommon.hs
Haskell
bsd-3-clause
1,344
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Init -- Copyright : (c) Brent Yorgey 2009 -- License : BSD-like -- -- Maintainer : cabal-devel@haskell.org -- Stability : provisional -- Portability : portable -- -- Implementation of the 'cabal init' command, which creates an initial .cabal -- file for a project. -- ----------------------------------------------------------------------------- module Distribution.Client.Init ( -- * Commands initCabal ) where import System.IO ( hSetBuffering, stdout, BufferMode(..) ) import System.Directory ( getCurrentDirectory ) import Data.Time ( getCurrentTime, utcToLocalTime, toGregorian, localDay, getCurrentTimeZone ) import Data.List ( intersperse, (\\) ) import Data.Maybe ( fromMaybe, isJust ) import Data.Traversable ( traverse ) import Control.Monad ( when ) #if MIN_VERSION_base(3,0,0) import Control.Monad ( (>=>), join ) #endif import Text.PrettyPrint hiding (mode, cat) import Data.Version ( Version(..) ) import Distribution.Version ( orLaterVersion ) import Distribution.Client.Init.Types ( InitFlags(..), PackageType(..), Category(..) ) import Distribution.Client.Init.Licenses ( bsd3, gplv2, gplv3, lgpl2, lgpl3 ) import Distribution.Client.Init.Heuristics ( guessPackageName, guessAuthorNameMail, SourceFileEntry(..), scanForModules, neededBuildPrograms ) import Distribution.License ( License(..), knownLicenses ) import Distribution.ModuleName ( ) -- for the Text instance import Distribution.ReadE ( runReadE, readP_to_E ) import Distribution.Simple.Setup ( Flag(..), flagToMaybe ) import Distribution.Text ( display, Text(..) ) initCabal :: InitFlags -> IO () initCabal initFlags = do hSetBuffering stdout NoBuffering initFlags' <- extendFlags initFlags writeLicense initFlags' writeSetupFile initFlags' success <- writeCabalFile initFlags' when success $ generateWarnings initFlags' --------------------------------------------------------------------------- -- Flag acquisition ----------------------------------------------------- --------------------------------------------------------------------------- -- | Fill in more details by guessing, discovering, or prompting the -- user. extendFlags :: InitFlags -> IO InitFlags extendFlags = getPackageName >=> getVersion >=> getLicense >=> getAuthorInfo >=> getHomepage >=> getSynopsis >=> getCategory >=> getLibOrExec >=> getGenComments >=> getSrcDir >=> getModulesAndBuildTools -- | Combine two actions which may return a value, preferring the first. That -- is, run the second action only if the first doesn't return a value. infixr 1 ?>> (?>>) :: IO (Maybe a) -> IO (Maybe a) -> IO (Maybe a) f ?>> g = do ma <- f if isJust ma then return ma else g -- | Witness the isomorphism between Maybe and Flag. maybeToFlag :: Maybe a -> Flag a maybeToFlag = maybe NoFlag Flag -- | Get the package name: use the package directory (supplied, or the current -- directory by default) as a guess. getPackageName :: InitFlags -> IO InitFlags getPackageName flags = do guess <- traverse guessPackageName (flagToMaybe $ packageDir flags) ?>> Just `fmap` (getCurrentDirectory >>= guessPackageName) pkgName' <- return (flagToMaybe $ packageName flags) ?>> maybePrompt flags (promptStr "Package name" guess) ?>> return guess return $ flags { packageName = maybeToFlag pkgName' } -- | Package version: use 0.1.0.0 as a last resort, but try prompting the user -- if possible. getVersion :: InitFlags -> IO InitFlags getVersion flags = do let v = Just $ Version { versionBranch = [0,1,0,0], versionTags = [] } v' <- return (flagToMaybe $ version flags) ?>> maybePrompt flags (prompt "Package version" v) ?>> return v return $ flags { version = maybeToFlag v' } -- | Choose a license. getLicense :: InitFlags -> IO InitFlags getLicense flags = do lic <- return (flagToMaybe $ license flags) ?>> fmap (fmap (either UnknownLicense id) . join) (maybePrompt flags (promptListOptional "Please choose a license" listedLicenses)) return $ flags { license = maybeToFlag lic } where listedLicenses = knownLicenses \\ [GPL Nothing, LGPL Nothing, OtherLicense] -- | The author's name and email. Prompt, or try to guess from an existing -- darcs repo. getAuthorInfo :: InitFlags -> IO InitFlags getAuthorInfo flags = do (authorName, authorEmail) <- (\(a,e) -> (flagToMaybe a, flagToMaybe e)) `fmap` guessAuthorNameMail authorName' <- return (flagToMaybe $ author flags) ?>> maybePrompt flags (promptStr "Author name" authorName) ?>> return authorName authorEmail' <- return (flagToMaybe $ email flags) ?>> maybePrompt flags (promptStr "Maintainer email" authorEmail) ?>> return authorEmail return $ flags { author = maybeToFlag authorName' , email = maybeToFlag authorEmail' } -- | Prompt for a homepage URL. getHomepage :: InitFlags -> IO InitFlags getHomepage flags = do hp <- queryHomepage hp' <- return (flagToMaybe $ homepage flags) ?>> maybePrompt flags (promptStr "Project homepage/repo URL" hp) ?>> return hp return $ flags { homepage = maybeToFlag hp' } -- | Right now this does nothing, but it could be changed to do some -- intelligent guessing. queryHomepage :: IO (Maybe String) queryHomepage = return Nothing -- get default remote darcs repo? -- | Prompt for a project synopsis. getSynopsis :: InitFlags -> IO InitFlags getSynopsis flags = do syn <- return (flagToMaybe $ synopsis flags) ?>> maybePrompt flags (promptStr "Project synopsis" Nothing) return $ flags { synopsis = maybeToFlag syn } -- | Prompt for a package category. -- Note that it should be possible to do some smarter guessing here too, i.e. -- look at the name of the top level source directory. getCategory :: InitFlags -> IO InitFlags getCategory flags = do cat <- return (flagToMaybe $ category flags) ?>> fmap join (maybePrompt flags (promptListOptional "Project category" [Codec ..])) return $ flags { category = maybeToFlag cat } -- | Ask whether the project builds a library or executable. getLibOrExec :: InitFlags -> IO InitFlags getLibOrExec flags = do isLib <- return (flagToMaybe $ packageType flags) ?>> maybePrompt flags (either (const Library) id `fmap` (promptList "What does the package build" [Library, Executable] Nothing display False)) ?>> return (Just Library) return $ flags { packageType = maybeToFlag isLib } -- | Ask whether to generate explanitory comments. getGenComments :: InitFlags -> IO InitFlags getGenComments flags = do genComments <- return (flagToMaybe $ noComments flags) ?>> maybePrompt flags (promptYesNo promptMsg (Just False)) ?>> return (Just False) return $ flags { noComments = maybeToFlag (fmap not genComments) } where promptMsg = "Include documentation on what each field means y/n" -- | Try to guess the source root directory (don't prompt the user). getSrcDir :: InitFlags -> IO InitFlags getSrcDir flags = do srcDirs <- return (sourceDirs flags) ?>> guessSourceDirs return $ flags { sourceDirs = srcDirs } -- XXX -- | Try to guess source directories. guessSourceDirs :: IO (Maybe [String]) guessSourceDirs = return Nothing -- | Get the list of exposed modules and extra tools needed to build them. getModulesAndBuildTools :: InitFlags -> IO InitFlags getModulesAndBuildTools flags = do dir <- fromMaybe getCurrentDirectory (fmap return . flagToMaybe $ packageDir flags) -- XXX really should use guessed source roots. sourceFiles <- scanForModules dir mods <- return (exposedModules flags) ?>> (return . Just . map moduleName $ sourceFiles) tools <- return (buildTools flags) ?>> (return . Just . neededBuildPrograms $ sourceFiles) return $ flags { exposedModules = mods , buildTools = tools } --------------------------------------------------------------------------- -- Prompting/user interaction ------------------------------------------- --------------------------------------------------------------------------- -- | Run a prompt or not based on the nonInteractive flag of the -- InitFlags structure. maybePrompt :: InitFlags -> IO t -> IO (Maybe t) maybePrompt flags p = case nonInteractive flags of Flag True -> return Nothing _ -> Just `fmap` p -- | Create a prompt with optional default value that returns a -- String. promptStr :: String -> Maybe String -> IO String promptStr = promptDefault' Just id -- | Create a yes/no prompt with optional default value. -- promptYesNo :: String -> Maybe Bool -> IO Bool promptYesNo = promptDefault' recogniseYesNo showYesNo where recogniseYesNo s | s == "y" || s == "Y" = Just True | s == "n" || s == "N" = Just False | otherwise = Nothing showYesNo True = "y" showYesNo False = "n" -- | Create a prompt with optional default value that returns a value -- of some Text instance. prompt :: Text t => String -> Maybe t -> IO t prompt = promptDefault' (either (const Nothing) Just . runReadE (readP_to_E id parse)) display -- | Create a prompt with an optional default value. promptDefault' :: (String -> Maybe t) -- ^ parser -> (t -> String) -- ^ pretty-printer -> String -- ^ prompt message -> Maybe t -- ^ optional default value -> IO t promptDefault' parser pretty pr def = do putStr $ mkDefPrompt pr (pretty `fmap` def) inp <- getLine case (inp, def) of ("", Just d) -> return d _ -> case parser inp of Just t -> return t Nothing -> do putStrLn $ "Couldn't parse " ++ inp ++ ", please try again!" promptDefault' parser pretty pr def -- | Create a prompt from a prompt string and a String representation -- of an optional default value. mkDefPrompt :: String -> Maybe String -> String mkDefPrompt pr def = pr ++ "?" ++ defStr def where defStr Nothing = " " defStr (Just s) = " [default: " ++ s ++ "] " promptListOptional :: (Text t, Eq t) => String -- ^ prompt -> [t] -- ^ choices -> IO (Maybe (Either String t)) promptListOptional pr choices = fmap rearrange $ promptList pr (Nothing : map Just choices) (Just Nothing) (maybe "(none)" display) True where rearrange = either (Just . Left) (maybe Nothing (Just . Right)) -- | Create a prompt from a list of items. promptList :: Eq t => String -- ^ prompt -> [t] -- ^ choices -> Maybe t -- ^ optional default value -> (t -> String) -- ^ show an item -> Bool -- ^ whether to allow an 'other' option -> IO (Either String t) promptList pr choices def displayItem other = do putStrLn $ pr ++ ":" let options1 = map (\c -> (Just c == def, displayItem c)) choices options2 = zip ([1..]::[Int]) (options1 ++ if other then [(False, "Other (specify)")] else []) mapM_ (putStrLn . \(n,(i,s)) -> showOption n i ++ s) options2 promptList' displayItem (length options2) choices def other where showOption n i | n < 10 = " " ++ star i ++ " " ++ rest | otherwise = " " ++ star i ++ rest where rest = show n ++ ") " star True = "*" star False = " " promptList' :: (t -> String) -> Int -> [t] -> Maybe t -> Bool -> IO (Either String t) promptList' displayItem numChoices choices def other = do putStr $ mkDefPrompt "Your choice" (displayItem `fmap` def) inp <- getLine case (inp, def) of ("", Just d) -> return $ Right d _ -> case readMaybe inp of Nothing -> invalidChoice inp Just n -> getChoice n where invalidChoice inp = do putStrLn $ inp ++ " is not a valid choice." promptList' displayItem numChoices choices def other getChoice n | n < 1 || n > numChoices = invalidChoice (show n) | n < numChoices || (n == numChoices && not other) = return . Right $ choices !! (n-1) | otherwise = Left `fmap` promptStr "Please specify" Nothing readMaybe :: (Read a) => String -> Maybe a readMaybe s = case reads s of [(a,"")] -> Just a _ -> Nothing --------------------------------------------------------------------------- -- File generation ------------------------------------------------------ --------------------------------------------------------------------------- writeLicense :: InitFlags -> IO () writeLicense flags = do message flags "Generating LICENSE..." year <- getYear let licenseFile = case license flags of Flag BSD3 -> Just $ bsd3 (fromMaybe "???" . flagToMaybe . author $ flags) (show year) Flag (GPL (Just (Version {versionBranch = [2]}))) -> Just gplv2 Flag (GPL (Just (Version {versionBranch = [3]}))) -> Just gplv3 Flag (LGPL (Just (Version {versionBranch = [2]}))) -> Just lgpl2 Flag (LGPL (Just (Version {versionBranch = [3]}))) -> Just lgpl3 _ -> Nothing case licenseFile of Just licenseText -> writeFile "LICENSE" licenseText Nothing -> message flags "Warning: unknown license type, you must put a copy in LICENSE yourself." getYear :: IO Integer getYear = do u <- getCurrentTime z <- getCurrentTimeZone let l = utcToLocalTime z u (y, _, _) = toGregorian $ localDay l return y writeSetupFile :: InitFlags -> IO () writeSetupFile flags = do message flags "Generating Setup.hs..." writeFile "Setup.hs" setupFile where setupFile = unlines [ "import Distribution.Simple" , "main = defaultMain" ] writeCabalFile :: InitFlags -> IO Bool writeCabalFile flags@(InitFlags{packageName = NoFlag}) = do message flags "Error: no package name provided." return False writeCabalFile flags@(InitFlags{packageName = Flag p}) = do let cabalFileName = p ++ ".cabal" message flags $ "Generating " ++ cabalFileName ++ "..." writeFile cabalFileName (generateCabalFile cabalFileName flags) return True -- | Generate a .cabal file from an InitFlags structure. NOTE: this -- is rather ad-hoc! What we would REALLY like is to have a -- standard low-level AST type representing .cabal files, which -- preserves things like comments, and to write an *inverse* -- parser/pretty-printer pair between .cabal files and this AST. -- Then instead of this ad-hoc code we could just map an InitFlags -- structure onto a low-level AST structure and use the existing -- pretty-printing code to generate the file. generateCabalFile :: String -> InitFlags -> String generateCabalFile fileName c = renderStyle style { lineLength = 79, ribbonsPerLine = 1.1 } $ (if (minimal c /= Flag True) then showComment (Just $ "Initial " ++ fileName ++ " generated by cabal " ++ "init. For further documentation, see " ++ "http://haskell.org/cabal/users-guide/") $$ text "" else empty) $$ vcat [ fieldS "name" (packageName c) (Just "The name of the package.") True , field "version" (version c) (Just "The package version. See the Haskell package versioning policy (http://www.haskell.org/haskellwiki/Package_versioning_policy) for standards guiding when and how versions should be incremented.") True , fieldS "synopsis" (synopsis c) (Just "A short (one-line) description of the package.") True , fieldS "description" NoFlag (Just "A longer description of the package.") True , fieldS "homepage" (homepage c) (Just "URL for the project homepage or repository.") False , fieldS "bug-reports" NoFlag (Just "A URL where users can report bugs.") False , field "license" (license c) (Just "The license under which the package is released.") True , fieldS "license-file" (Flag "LICENSE") (Just "The file containing the license text.") True , fieldS "author" (author c) (Just "The package author(s).") True , fieldS "maintainer" (email c) (Just "An email address to which users can send suggestions, bug reports, and patches.") True , fieldS "copyright" NoFlag (Just "A copyright notice.") True , fieldS "category" (either id display `fmap` category c) Nothing True , fieldS "build-type" (Flag "Simple") Nothing True , fieldS "extra-source-files" NoFlag (Just "Extra files to be distributed with the package, such as examples or a README.") False , field "cabal-version" (Flag $ orLaterVersion (Version [1,8] [])) (Just "Constraint on the version of Cabal needed to build this package.") False , case packageType c of Flag Executable -> text "\nexecutable" <+> text (fromMaybe "" . flagToMaybe $ packageName c) $$ (nest 2 $ vcat [ fieldS "main-is" NoFlag (Just ".hs or .lhs file containing the Main module.") True , generateBuildInfo Executable c ]) Flag Library -> text "\nlibrary" $$ (nest 2 $ vcat [ fieldS "exposed-modules" (listField (exposedModules c)) (Just "Modules exported by the library.") True , generateBuildInfo Library c ]) _ -> empty ] where generateBuildInfo :: PackageType -> InitFlags -> Doc generateBuildInfo pkgtype c' = vcat [ fieldS "other-modules" (listField (otherModules c')) (Just $ case pkgtype of Library -> "Modules included in this library but not exported." Executable -> "Modules included in this executable, other than Main.") True , fieldS "build-depends" (listField (dependencies c')) (Just "Other library packages from which modules are imported.") True , fieldS "hs-source-dirs" (listFieldS (sourceDirs c')) (Just "Directories containing source files.") False , fieldS "build-tools" (listFieldS (buildTools c')) (Just "Extra tools (e.g. alex, hsc2hs, ...) needed to build the source.") False ] listField :: Text s => Maybe [s] -> Flag String listField = listFieldS . fmap (map display) listFieldS :: Maybe [String] -> Flag String listFieldS = Flag . maybe "" (concat . intersperse ", ") field :: Text t => String -> Flag t -> Maybe String -> Bool -> Doc field s f = fieldS s (fmap display f) fieldS :: String -- ^ Name of the field -> Flag String -- ^ Field contents -> Maybe String -- ^ Comment to explain the field -> Bool -- ^ Should the field be included (commented out) even if blank? -> Doc fieldS _ NoFlag _ inc | not inc || (minimal c == Flag True) = empty fieldS _ (Flag "") _ inc | not inc || (minimal c == Flag True) = empty fieldS s f com _ = case (isJust com, noComments c, minimal c) of (_, _, Flag True) -> id (_, Flag True, _) -> id (True, _, _) -> (showComment com $$) . ($$ text "") (False, _, _) -> ($$ text "") $ comment f <> text s <> colon <> text (take (20 - length s) (repeat ' ')) <> text (fromMaybe "" . flagToMaybe $ f) comment NoFlag = text "-- " comment (Flag "") = text "-- " comment _ = text "" showComment :: Maybe String -> Doc showComment (Just t) = vcat . map text . map ("-- "++) . lines . renderStyle style { lineLength = 76, ribbonsPerLine = 1.05 } . fsep . map text . words $ t showComment Nothing = text "" -- | Generate warnings for missing fields etc. generateWarnings :: InitFlags -> IO () generateWarnings flags = do message flags "" when (synopsis flags `elem` [NoFlag, Flag ""]) (message flags "Warning: no synopsis given. You should edit the .cabal file and add one.") message flags "You may want to edit the .cabal file and add a Description field." -- | Possibly generate a message to stdout, taking into account the -- --quiet flag. message :: InitFlags -> String -> IO () message (InitFlags{quiet = Flag True}) _ = return () message _ s = putStrLn s #if MIN_VERSION_base(3,0,0) #else (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c) f >=> g = \x -> f x >>= g #endif
IreneKnapp/Faction
faction/Distribution/Client/Init.hs
Haskell
bsd-3-clause
22,401
module Text.Email.Parser.Polymorphic ( addrSpec, -- addrSpec is from this module, the rest are re-exports. localPart, domainPart, EmailAddress, unsafeEmailAddress, toByteString ) where import Text.Email.Parser (localPart, domainPart, EmailAddress(..), unsafeEmailAddress, toByteString) import Text.Domain.Parser.Polymorphic (domainParser,isAsciiAlphaNum) import qualified Data.ByteString.Char8 as BS import Data.ByteString (ByteString) import Text.Parser.Combinators hiding (between) import Text.Parser.Char import Control.Applicative import Control.Monad (void) import Data.List (intercalate) --import Data.Char (isAscii, isAlpha, isDigit) --import Data.List (intercalate) addrSpec :: (Monad m, CharParsing m) => m EmailAddress addrSpec = do l <- local char '@' d <- domain return (unsafeEmailAddress (BS.pack l) (BS.pack d)) local :: (Monad m, CharParsing m) => m String local = dottedAtoms domain :: (Monad m, CharParsing m) => m String domain = domainName <|> domainLiteral domainName :: (Monad m, CharParsing m) => m String domainName = undefined -- TODO: Not sure how to do this part polymorphically. dottedAtoms :: (Monad m, CharParsing m) => m String dottedAtoms = intercalate "." <$> between1 (optional cfws) (atom <|> quotedString) `sepBy1` char '.' atom :: (Monad m, CharParsing m) => m String atom = some (satisfy isAtomText) isAtomText :: Char -> Bool isAtomText x = isAsciiAlphaNum x || x `elem` "!#$%&'*+/=?^_`{|}~-" domainLiteral :: (Monad m, CharParsing m) => m String domainLiteral = do innards <- between (optional cfws *> char '[') (char ']' <* optional cfws) (many (optional fws >> some (satisfy isDomainText)) <* optional fws) return $ concat ["[",concat innards,"]"] isDomainText :: Char -> Bool isDomainText x = x `elem` "\33-\90\94-\126" || isObsNoWsCtl x quotedString :: (Monad m, CharParsing m) => m String quotedString = do innards <- between (char '"') (char '"') (many (optional fws >> quotedContent) <* optional fws) return $ "\"" ++ (concat innards) ++ "\"" quotedContent :: (Monad m, CharParsing m) => m String quotedContent = some (satisfy isQuotedText) <|> quotedPair isQuotedText :: Char -> Bool isQuotedText x = x `elem` "\33\35-\91\93-\126" || isObsNoWsCtl x quotedPair :: (Monad m, CharParsing m) => m String quotedPair = (\ c -> ['\\',c]) <$> (char '\\' *> (vchar <|> wsp <|> lf <|> cr <|> obsNoWsCtl <|> nullChar)) cfws :: (Monad m, CharParsing m) => m () cfws = skipMany (comment <|> fws) fws :: (Monad m, CharParsing m) => m () fws = void (wsp1 >> optional (crlf >> wsp1)) <|> (skipSome (crlf >> wsp1)) between :: Applicative f => f l -> f r -> f a -> f a between l r x = l *> x <* r between1 :: Applicative f => f lr -> f a -> f a between1 lr x = lr *> x <* lr comment :: (Monad m, CharParsing m) => m () comment = between (char '(') (char ')') $ skipMany (void commentContent <|> fws) commentContent :: (Monad m, CharParsing m) => m () commentContent = skipSome (satisfy isCommentText) <|> void quotedPair <|> comment isCommentText :: Char -> Bool isCommentText x = x `elem` "\33-\39\42-\91\93-\126" || isObsNoWsCtl x nullChar :: (CharParsing m) => m Char nullChar = char '\0' wsp1 :: (CharParsing m) => m () wsp1 = skipSome (satisfy isWsp) wsp :: (CharParsing m) => m Char wsp = satisfy isWsp isWsp :: Char -> Bool isWsp x = x == ' ' || x == '\t' cr :: (CharParsing m) => m Char cr = char '\r' lf :: (CharParsing m) => m Char lf = char '\n' crlf :: (Monad m, CharParsing m) => m () crlf = void $ cr >> lf isVchar :: Char -> Bool isVchar c = c `elem` "\x21-\x7e" vchar :: (CharParsing m) => m Char vchar = satisfy isVchar isObsNoWsCtl :: Char -> Bool isObsNoWsCtl c = c `elem` "\1-\8\11-\12\14-\31\127" obsNoWsCtl :: (CharParsing m) => m Char obsNoWsCtl = satisfy isObsNoWsCtl
bitemyapp/email-validate-hs
src/Text/Email/Parser/Polymorphic.hs
Haskell
bsd-3-clause
3,833
{-# LANGUAGE OverloadedStrings #-} module NLP.Romkan.Internal ( romKanAList , romKanAList_H , kanRomAList , kanRomAList_H , kunreiToHepburnAList , hepburnToKunreiAList ) where import Data.Text (Text) romKanAList :: [(Text, Text)] romKanAList = [ ("bbya", "ッビャ") ,("bbyo", "ッビョ") ,("bbyu", "ッビュ") ,("ccha", "ッチャ") ,("cche", "ッチェ") ,("cchi", "ッチ") ,("ccho", "ッチョ") ,("cchu", "ッチュ") ,("ddya", "ッヂャ") ,("ddyo", "ッヂョ") ,("ddyu", "ッヂュ") ,("ggya", "ッギャ") ,("ggyo", "ッギョ") ,("ggyu", "ッギュ") ,("hhya", "ッヒャ") ,("hhyo", "ッヒョ") ,("hhyu", "ッヒュ") ,("kkya", "ッキャ") ,("kkyo", "ッキョ") ,("kkyu", "ッキュ") ,("ppya", "ッピャ") ,("ppyo", "ッピョ") ,("ppyu", "ッピュ") ,("rrya", "ッリャ") ,("rryo", "ッリョ") ,("rryu", "ッリュ") ,("ssha", "ッシャ") ,("sshe", "ッシェ") ,("sshi", "ッシ") ,("ssho", "ッショ") ,("sshu", "ッシュ") ,("ssya", "ッシャ") ,("ssye", "ッシェ") ,("ssyo", "ッショ") ,("ssyu", "ッシュ") ,("ttsu", "ッツ") ,("ttya", "ッチャ") ,("ttye", "ッチェ") ,("ttyo", "ッチョ") ,("ttyu", "ッチュ") ,("xtsu", "ッ") ,("zzya", "ッジャ") ,("zzyo", "ッジョ") ,("zzyu", "ッジュ") ,("bba", "ッバ") ,("bbe", "ッベ") ,("bbi", "ッビ") ,("bbo", "ッボ") ,("bbu", "ッブ") ,("bya", "ビャ") ,("byo", "ビョ") ,("byu", "ビュ") ,("cha", "チャ") ,("che", "チェ") ,("chi", "チ") ,("cho", "チョ") ,("chu", "チュ") ,("dda", "ッダ") ,("dde", "ッデ") ,("ddi", "ッヂ") ,("ddo", "ッド") ,("ddu", "ッドゥ") ,("dya", "ヂャ") ,("dyi", "ディ") ,("dyo", "ヂョ") ,("dyu", "ヂュ") ,("ffa", "ッファ") ,("ffe", "ッフェ") ,("ffi", "ッフィ") ,("ffo", "ッフォ") ,("ffu", "ッフュ") ,("gga", "ッガ") ,("gge", "ッゲ") ,("ggi", "ッギ") ,("ggo", "ッゴ") ,("ggu", "ッグ") ,("gya", "ギャ") ,("gyo", "ギョ") ,("gyu", "ギュ") ,("hha", "ッハ") ,("hhe", "ッヘ") ,("hhi", "ッヒ") ,("hho", "ッホ") ,("hhu", "ッフ") ,("hya", "ヒャ") ,("hyo", "ヒョ") ,("hyu", "ヒュ") ,("jja", "ッジャ") ,("jji", "ッジ") ,("jjo", "ッジョ") ,("jju", "ッジュ") ,("kka", "ッカ") ,("kke", "ッケ") ,("kki", "ッキ") ,("kko", "ッコ") ,("kku", "ック") ,("kya", "キャ") ,("kyo", "キョ") ,("kyu", "キュ") ,("mya", "ミャ") ,("myo", "ミョ") ,("myu", "ミュ") ,("nya", "ニャ") ,("nyo", "ニョ") ,("nyu", "ニュ") ,("ppa", "ッパ") ,("ppe", "ッペ") ,("ppi", "ッピ") ,("ppo", "ッポ") ,("ppu", "ップ") ,("pya", "ピャ") ,("pyo", "ピョ") ,("pyu", "ピュ") ,("rra", "ッラ") ,("rre", "ッレ") ,("rri", "ッリ") ,("rro", "ッロ") ,("rru", "ッル") ,("rya", "リャ") ,("ryo", "リョ") ,("ryu", "リュ") ,("sha", "シャ") ,("she", "シェ") ,("shi", "シ") ,("sho", "ショ") ,("shu", "シュ") ,("ssa", "ッサ") ,("sse", "ッセ") ,("ssi", "ッシ") ,("sso", "ッソ") ,("ssu", "ッス") ,("sya", "シャ") ,("sye", "シェ") ,("syo", "ショ") ,("syu", "シュ") ,("tsu", "ツ") ,("tta", "ッタ") ,("tte", "ッテ") ,("tti", "ッティ") ,("tto", "ット") ,("ttu", "ッツ") ,("tya", "チャ") ,("tye", "チェ") ,("tyo", "チョ") ,("tyu", "チュ") ,("vva", "ッヴァ") ,("vve", "ッヴェ") ,("vvi", "ッヴィ") ,("vvo", "ッヴォ") ,("vvu", "ッヴ") ,("xtu", "ッ") ,("xwa", "ヮ") ,("xya", "ャ") ,("xyo", "ョ") ,("xyu", "ュ") ,("yya", "ッヤ") ,("yyo", "ッヨ") ,("yyu", "ッユ") ,("zya", "ジャ") ,("zye", "ジェ") ,("zyo", "ジョ") ,("zyu", "ジュ") ,("zza", "ッザ") ,("zze", "ッゼ") ,("zzi", "ッジ") ,("zzo", "ッゾ") ,("zzu", "ッズ") ,("ba", "バ") ,("be", "ベ") ,("bi", "ビ") ,("bo", "ボ") ,("bu", "ブ") ,("da", "ダ") ,("de", "デ") ,("di", "ヂ") ,("do", "ド") ,("du", "ヅ") ,("fa", "ファ") ,("fe", "フェ") ,("fi", "フィ") ,("fo", "フォ") ,("fu", "フ") ,("ga", "ガ") ,("ge", "ゲ") ,("gi", "ギ") ,("go", "ゴ") ,("gu", "グ") ,("ha", "ハ") ,("he", "ヘ") ,("hi", "ヒ") ,("ho", "ホ") ,("hu", "フ") ,("ja", "ジャ") ,("je", "ジェ") ,("ji", "ジ") ,("jo", "ジョ") ,("ju", "ジュ") ,("ka", "カ") ,("ke", "ケ") ,("ki", "キ") ,("ko", "コ") ,("ku", "ク") ,("ma", "マ") ,("me", "メ") ,("mi", "ミ") ,("mo", "モ") ,("mu", "ム") ,("n'", "ン") ,("na", "ナ") ,("ne", "ネ") ,("ni", "ニ") ,("no", "ノ") ,("nu", "ヌ") ,("pa", "パ") ,("pe", "ペ") ,("pi", "ピ") ,("po", "ポ") ,("pu", "プ") ,("ra", "ラ") ,("re", "レ") ,("ri", "リ") ,("ro", "ロ") ,("ru", "ル") ,("sa", "サ") ,("se", "セ") ,("si", "シ") ,("so", "ソ") ,("su", "ス") ,("ta", "タ") ,("te", "テ") ,("ti", "チ") ,("to", "ト") ,("tu", "ツ") ,("va", "ヴァ") ,("ve", "ヴェ") ,("vi", "ヴィ") ,("vo", "ヴォ") ,("vu", "ヴ") ,("wa", "ワ") ,("we", "ウェ") ,("wi", "ウィ") ,("wo", "ヲ") ,("xa", "ァ") ,("xe", "ェ") ,("xi", "ィ") ,("xo", "ォ") ,("xu", "ゥ") ,("ya", "ヤ") ,("yo", "ヨ") ,("yu", "ユ") ,("za", "ザ") ,("ze", "ゼ") ,("zi", "ジ") ,("zo", "ゾ") ,("zu", "ズ") ,("-", "ー") ,("a", "ア") ,("e", "エ") ,("i", "イ") ,("n", "ン") ,("o", "オ") ,("u", "ウ") ] romKanAList_H :: [(Text, Text)] romKanAList_H = [ ("bbya", "っびゃ") ,("bbyo", "っびょ") ,("bbyu", "っびゅ") ,("ccha", "っちゃ") ,("cche", "っちぇ") ,("cchi", "っち") ,("ccho", "っちょ") ,("cchu", "っちゅ") ,("ddya", "っぢゃ") ,("ddyo", "っぢょ") ,("ddyu", "っぢゅ") ,("ggya", "っぎゃ") ,("ggyo", "っぎょ") ,("ggyu", "っぎゅ") ,("hhya", "っひゃ") ,("hhyo", "っひょ") ,("hhyu", "っひゅ") ,("kkya", "っきゃ") ,("kkyo", "っきょ") ,("kkyu", "っきゅ") ,("ppya", "っぴゃ") ,("ppyo", "っぴょ") ,("ppyu", "っぴゅ") ,("rrya", "っりゃ") ,("rryo", "っりょ") ,("rryu", "っりゅ") ,("ssha", "っしゃ") ,("sshi", "っし") ,("ssho", "っしょ") ,("sshu", "っしゅ") ,("ssya", "っしゃ") ,("ssyo", "っしょ") ,("ssyu", "っしゅ") ,("ttsu", "っつ") ,("ttya", "っちゃ") ,("ttye", "っちぇ") ,("ttyo", "っちょ") ,("ttyu", "っちゅ") ,("xtsu", "っ") ,("zzya", "っじゃ") ,("zzyo", "っじょ") ,("zzyu", "っじゅ") ,("bba", "っば") ,("bbe", "っべ") ,("bbi", "っび") ,("bbo", "っぼ") ,("bbu", "っぶ") ,("bya", "びゃ") ,("byo", "びょ") ,("byu", "びゅ") ,("cha", "ちゃ") ,("che", "ちぇ") ,("chi", "ち") ,("cho", "ちょ") ,("chu", "ちゅ") ,("dda", "っだ") ,("dde", "っで") ,("ddi", "っぢ") ,("ddo", "っど") ,("ddu", "っづ") ,("dya", "ぢゃ") ,("dyi", "でぃ") ,("dyo", "ぢょ") ,("dyu", "ぢゅ") ,("ffa", "っふぁ") ,("ffe", "っふぇ") ,("ffi", "っふぃ") ,("ffo", "っふぉ") ,("ffu", "っふ") ,("gga", "っが") ,("gge", "っげ") ,("ggi", "っぎ") ,("ggo", "っご") ,("ggu", "っぐ") ,("gya", "ぎゃ") ,("gyo", "ぎょ") ,("gyu", "ぎゅ") ,("hha", "っは") ,("hhe", "っへ") ,("hhi", "っひ") ,("hho", "っほ") ,("hhu", "っふ") ,("hya", "ひゃ") ,("hyo", "ひょ") ,("hyu", "ひゅ") ,("jja", "っじゃ") ,("jji", "っじ") ,("jjo", "っじょ") ,("jju", "っじゅ") ,("kka", "っか") ,("kke", "っけ") ,("kki", "っき") ,("kko", "っこ") ,("kku", "っく") ,("kya", "きゃ") ,("kyo", "きょ") ,("kyu", "きゅ") ,("mya", "みゃ") ,("myo", "みょ") ,("myu", "みゅ") ,("nya", "にゃ") ,("nyo", "にょ") ,("nyu", "にゅ") ,("ppa", "っぱ") ,("ppe", "っぺ") ,("ppi", "っぴ") ,("ppo", "っぽ") ,("ppu", "っぷ") ,("pya", "ぴゃ") ,("pyo", "ぴょ") ,("pyu", "ぴゅ") ,("rra", "っら") ,("rre", "っれ") ,("rri", "っり") ,("rro", "っろ") ,("rru", "っる") ,("rya", "りゃ") ,("ryo", "りょ") ,("ryu", "りゅ") ,("sha", "しゃ") ,("shi", "し") ,("sho", "しょ") ,("shu", "しゅ") ,("ssa", "っさ") ,("sse", "っせ") ,("ssi", "っし") ,("sso", "っそ") ,("ssu", "っす") ,("sya", "しゃ") ,("syo", "しょ") ,("syu", "しゅ") ,("tsu", "つ") ,("tta", "った") ,("tte", "って") ,("tti", "っち") ,("tto", "っと") ,("ttu", "っつ") ,("tya", "ちゃ") ,("tye", "ちぇ") ,("tyo", "ちょ") ,("tyu", "ちゅ") ,("vva", "っう゛ぁ") ,("vve", "っう゛ぇ") ,("vvi", "っう゛ぃ") ,("vvo", "っう゛ぉ") ,("vvu", "っう゛") ,("xtu", "っ") ,("xwa", "ゎ") ,("xya", "ゃ") ,("xyo", "ょ") ,("xyu", "ゅ") ,("yya", "っや") ,("yyo", "っよ") ,("yyu", "っゆ") ,("zya", "じゃ") ,("zye", "じぇ") ,("zyo", "じょ") ,("zyu", "じゅ") ,("zza", "っざ") ,("zze", "っぜ") ,("zzi", "っじ") ,("zzo", "っぞ") ,("zzu", "っず") ,("ba", "ば") ,("be", "べ") ,("bi", "び") ,("bo", "ぼ") ,("bu", "ぶ") ,("da", "だ") ,("de", "で") ,("di", "ぢ") ,("do", "ど") ,("du", "づ") ,("fa", "ふぁ") ,("fe", "ふぇ") ,("fi", "ふぃ") ,("fo", "ふぉ") ,("fu", "ふ") ,("ga", "が") ,("ge", "げ") ,("gi", "ぎ") ,("go", "ご") ,("gu", "ぐ") ,("ha", "は") ,("he", "へ") ,("hi", "ひ") ,("ho", "ほ") ,("hu", "ふ") ,("ja", "じゃ") ,("je", "じぇ") ,("ji", "じ") ,("jo", "じょ") ,("ju", "じゅ") ,("ka", "か") ,("ke", "け") ,("ki", "き") ,("ko", "こ") ,("ku", "く") ,("ma", "ま") ,("me", "め") ,("mi", "み") ,("mo", "も") ,("mu", "む") ,("n'", "ん") ,("na", "な") ,("ne", "ね") ,("ni", "に") ,("no", "の") ,("nu", "ぬ") ,("pa", "ぱ") ,("pe", "ぺ") ,("pi", "ぴ") ,("po", "ぽ") ,("pu", "ぷ") ,("ra", "ら") ,("re", "れ") ,("ri", "り") ,("ro", "ろ") ,("ru", "る") ,("sa", "さ") ,("se", "せ") ,("si", "し") ,("so", "そ") ,("su", "す") ,("ta", "た") ,("te", "て") ,("ti", "ち") ,("to", "と") ,("tu", "つ") ,("va", "う゛ぁ") ,("ve", "う゛ぇ") ,("vi", "う゛ぃ") ,("vo", "う゛ぉ") ,("vu", "う゛") ,("wa", "わ") ,("we", "うぇ") ,("wi", "うぃ") ,("wo", "を") ,("xa", "ぁ") ,("xe", "ぇ") ,("xi", "ぃ") ,("xo", "ぉ") ,("xu", "ぅ") ,("ya", "や") ,("yo", "よ") ,("yu", "ゆ") ,("za", "ざ") ,("ze", "ぜ") ,("zi", "じ") ,("zo", "ぞ") ,("zu", "ず") ,("-", "ー") ,("a", "あ") ,("e", "え") ,("i", "い") ,("n", "ん") ,("o", "お") ,("u", "う") ] kanRomAList :: [(Text, Text)] kanRomAList = [ ("ッジャ", "jja") ,("ッジュ", "jju") ,("ッジョ", "jjo") ,("ッティ", "tti") ,("ッドゥ", "ddu") ,("ッファ", "ffa") ,("ッフィ", "ffi") ,("ッフェ", "ffe") ,("ッフォ", "ffo") ,("ッフュ", "ffu") ,("ッヴァ", "vva") ,("ッヴィ", "vvi") ,("ッヴェ", "vve") ,("ッヴォ", "vvo") ,("ッキャ", "kkya") ,("ッキュ", "kkyu") ,("ッキョ", "kkyo") ,("ッギャ", "ggya") ,("ッギュ", "ggyu") ,("ッギョ", "ggyo") ,("ッシェ", "sshe") ,("ッシャ", "ssha") ,("ッシュ", "sshu") ,("ッショ", "ssho") ,("ッチェ", "cche") ,("ッチャ", "ccha") ,("ッチュ", "cchu") ,("ッチョ", "ccho") ,("ッヂャ", "ddya") ,("ッヂュ", "ddyu") ,("ッヂョ", "ddyo") ,("ッヒャ", "hhya") ,("ッヒュ", "hhyu") ,("ッヒョ", "hhyo") ,("ッビャ", "bbya") ,("ッビュ", "bbyu") ,("ッビョ", "bbyo") ,("ッピャ", "ppya") ,("ッピュ", "ppyu") ,("ッピョ", "ppyo") ,("ッリャ", "rrya") ,("ッリュ", "rryu") ,("ッリョ", "rryo") ,("ウィ", "wi") ,("ウェ", "we") ,("ウォ", "wo") ,("ジェ", "je") ,("ジャ", "ja") ,("ジュ", "ju") ,("ジョ", "jo") ,("ティ", "ti") ,("ディ", "di") ,("ドゥ", "du") ,("ファ", "fa") ,("フィ", "fi") ,("フェ", "fe") ,("フォ", "fo") ,("フュ", "fu") ,("ヴァ", "va") ,("ヴィ", "vi") ,("ヴェ", "ve") ,("ヴォ", "vo") ,("キャ", "kya") ,("キュ", "kyu") ,("キョ", "kyo") ,("ギャ", "gya") ,("ギュ", "gyu") ,("ギョ", "gyo") ,("シェ", "she") ,("シャ", "sha") ,("シュ", "shu") ,("ショ", "sho") ,("チェ", "che") ,("チャ", "cha") ,("チュ", "chu") ,("チョ", "cho") ,("ヂャ", "dya") ,("ヂュ", "dyu") ,("ヂョ", "dyo") ,("ッカ", "kka") ,("ッガ", "gga") ,("ッキ", "kki") ,("ッギ", "ggi") ,("ック", "kku") ,("ッグ", "ggu") ,("ッケ", "kke") ,("ッゲ", "gge") ,("ッコ", "kko") ,("ッゴ", "ggo") ,("ッサ", "ssa") ,("ッザ", "zza") ,("ッジ", "jji") ,("ッス", "ssu") ,("ッズ", "zzu") ,("ッセ", "sse") ,("ッゼ", "zze") ,("ッソ", "sso") ,("ッゾ", "zzo") ,("ッタ", "tta") ,("ッダ", "dda") ,("ッヂ", "ddi") ,("ッヅ", "ddu") ,("ッテ", "tte") ,("ッデ", "dde") ,("ット", "tto") ,("ッド", "ddo") ,("ッハ", "hha") ,("ッバ", "bba") ,("ッパ", "ppa") ,("ッヒ", "hhi") ,("ッビ", "bbi") ,("ッピ", "ppi") ,("ッフ", "ffu") ,("ッブ", "bbu") ,("ップ", "ppu") ,("ッヘ", "hhe") ,("ッベ", "bbe") ,("ッペ", "ppe") ,("ッホ", "hho") ,("ッボ", "bbo") ,("ッポ", "ppo") ,("ッヤ", "yya") ,("ッユ", "yyu") ,("ッヨ", "yyo") ,("ッラ", "rra") ,("ッリ", "rri") ,("ッル", "rru") ,("ッレ", "rre") ,("ッロ", "rro") ,("ッヴ", "vvu") ,("ニャ", "nya") ,("ニュ", "nyu") ,("ニョ", "nyo") ,("ヒャ", "hya") ,("ヒュ", "hyu") ,("ヒョ", "hyo") ,("ビャ", "bya") ,("ビュ", "byu") ,("ビョ", "byo") ,("ピャ", "pya") ,("ピュ", "pyu") ,("ピョ", "pyo") ,("ミャ", "mya") ,("ミュ", "myu") ,("ミョ", "myo") ,("リャ", "rya") ,("リュ", "ryu") ,("リョ", "ryo") ,("ッシ", "sshi") ,("ッチ", "cchi") ,("ッツ", "ttsu") ,("ア", "a") ,("イ", "i") ,("ウ", "u") ,("エ", "e") ,("オ", "o") ,("ー", "-") ,("ァ", "xa") ,("ィ", "xi") ,("ゥ", "xu") ,("ェ", "xe") ,("ォ", "xo") ,("カ", "ka") ,("ガ", "ga") ,("キ", "ki") ,("ギ", "gi") ,("ク", "ku") ,("グ", "gu") ,("ケ", "ke") ,("ゲ", "ge") ,("コ", "ko") ,("ゴ", "go") ,("サ", "sa") ,("ザ", "za") ,("ジ", "ji") ,("ス", "su") ,("ズ", "zu") ,("セ", "se") ,("ゼ", "ze") ,("ソ", "so") ,("ゾ", "zo") ,("タ", "ta") ,("ダ", "da") ,("ヂ", "di") ,("ヅ", "du") ,("テ", "te") ,("デ", "de") ,("ト", "to") ,("ド", "do") ,("ナ", "na") ,("ニ", "ni") ,("ヌ", "nu") ,("ネ", "ne") ,("ノ", "no") ,("ハ", "ha") ,("バ", "ba") ,("パ", "pa") ,("ヒ", "hi") ,("ビ", "bi") ,("ピ", "pi") ,("フ", "fu") ,("ブ", "bu") ,("プ", "pu") ,("ヘ", "he") ,("ベ", "be") ,("ペ", "pe") ,("ホ", "ho") ,("ボ", "bo") ,("ポ", "po") ,("マ", "ma") ,("ミ", "mi") ,("ム", "mu") ,("メ", "me") ,("モ", "mo") ,("ヤ", "ya") ,("ユ", "yu") ,("ヨ", "yo") ,("ラ", "ra") ,("リ", "ri") ,("ル", "ru") ,("レ", "re") ,("ロ", "ro") ,("ワ", "wa") ,("ヰ", "wi") ,("ヱ", "we") ,("ヲ", "wo") ,("ン", "n'") ,("ヴ", "vu") ,("シ", "shi") ,("チ", "chi") ,("ツ", "tsu") ,("ャ", "xya") ,("ュ", "xyu") ,("ョ", "xyo") ,("ヮ", "xwa") ,("ッ", "xtsu") ] kanRomAList_H :: [(Text, Text)] kanRomAList_H = [ ("っう゛ぁ", "vva") ,("っう゛ぃ", "vvi") ,("っう゛ぇ", "vve") ,("っう゛ぉ", "vvo") ,("う゛ぁ", "va") ,("う゛ぃ", "vi") ,("う゛ぇ", "ve") ,("う゛ぉ", "vo") ,("っう゛", "vvu") ,("っじゃ", "jja") ,("っじゅ", "jju") ,("っじょ", "jjo") ,("っふぁ", "ffa") ,("っふぃ", "ffi") ,("っふぇ", "ffe") ,("っふぉ", "ffo") ,("っきゃ", "kkya") ,("っきゅ", "kkyu") ,("っきょ", "kkyo") ,("っぎゃ", "ggya") ,("っぎゅ", "ggyu") ,("っぎょ", "ggyo") ,("っしゃ", "ssha") ,("っしゅ", "sshu") ,("っしょ", "ssho") ,("っちぇ", "cche") ,("っちゃ", "ccha") ,("っちゅ", "cchu") ,("っちょ", "ccho") ,("っぢゃ", "ddya") ,("っぢゅ", "ddyu") ,("っぢょ", "ddyo") ,("っひゃ", "hhya") ,("っひゅ", "hhyu") ,("っひょ", "hhyo") ,("っびゃ", "bbya") ,("っびゅ", "bbyu") ,("っびょ", "bbyo") ,("っぴゃ", "ppya") ,("っぴゅ", "ppyu") ,("っぴょ", "ppyo") ,("っりゃ", "rrya") ,("っりゅ", "rryu") ,("っりょ", "rryo") ,("う゛", "vu") ,("じぇ", "je") ,("じゃ", "ja") ,("じゅ", "ju") ,("じょ", "jo") ,("ふぁ", "fa") ,("ふぃ", "fi") ,("ふぇ", "fe") ,("ふぉ", "fo") ,("きゃ", "kya") ,("きゅ", "kyu") ,("きょ", "kyo") ,("ぎゃ", "gya") ,("ぎゅ", "gyu") ,("ぎょ", "gyo") ,("しゃ", "sha") ,("しゅ", "shu") ,("しょ", "sho") ,("ちぇ", "che") ,("ちゃ", "cha") ,("ちゅ", "chu") ,("ちょ", "cho") ,("ぢゃ", "dya") ,("ぢゅ", "dyu") ,("ぢょ", "dyo") ,("っか", "kka") ,("っが", "gga") ,("っき", "kki") ,("っぎ", "ggi") ,("っく", "kku") ,("っぐ", "ggu") ,("っけ", "kke") ,("っげ", "gge") ,("っこ", "kko") ,("っご", "ggo") ,("っさ", "ssa") ,("っざ", "zza") ,("っじ", "jji") ,("っす", "ssu") ,("っず", "zzu") ,("っせ", "sse") ,("っぜ", "zze") ,("っそ", "sso") ,("っぞ", "zzo") ,("った", "tta") ,("っだ", "dda") ,("っぢ", "ddi") ,("っづ", "ddu") ,("って", "tte") ,("っで", "dde") ,("っと", "tto") ,("っど", "ddo") ,("っは", "hha") ,("っば", "bba") ,("っぱ", "ppa") ,("っひ", "hhi") ,("っび", "bbi") ,("っぴ", "ppi") ,("っふ", "ffu") ,("っぶ", "bbu") ,("っぷ", "ppu") ,("っへ", "hhe") ,("っべ", "bbe") ,("っぺ", "ppe") ,("っほ", "hho") ,("っぼ", "bbo") ,("っぽ", "ppo") ,("っや", "yya") ,("っゆ", "yyu") ,("っよ", "yyo") ,("っら", "rra") ,("っり", "rri") ,("っる", "rru") ,("っれ", "rre") ,("っろ", "rro") ,("でぃ", "dyi") ,("にゃ", "nya") ,("にゅ", "nyu") ,("にょ", "nyo") ,("ひゃ", "hya") ,("ひゅ", "hyu") ,("ひょ", "hyo") ,("びゃ", "bya") ,("びゅ", "byu") ,("びょ", "byo") ,("ぴゃ", "pya") ,("ぴゅ", "pyu") ,("ぴょ", "pyo") ,("みゃ", "mya") ,("みゅ", "myu") ,("みょ", "myo") ,("りゃ", "rya") ,("りゅ", "ryu") ,("りょ", "ryo") ,("っし", "sshi") ,("っち", "cchi") ,("っつ", "ttsu") ,("あ", "a") ,("い", "i") ,("う", "u") ,("え", "e") ,("お", "o") ,("ー", "-") ,("ぁ", "xa") ,("ぃ", "xi") ,("ぅ", "xu") ,("ぇ", "xe") ,("ぉ", "xo") ,("か", "ka") ,("が", "ga") ,("き", "ki") ,("ぎ", "gi") ,("く", "ku") ,("ぐ", "gu") ,("け", "ke") ,("げ", "ge") ,("こ", "ko") ,("ご", "go") ,("さ", "sa") ,("ざ", "za") ,("じ", "ji") ,("す", "su") ,("ず", "zu") ,("せ", "se") ,("ぜ", "ze") ,("そ", "so") ,("ぞ", "zo") ,("た", "ta") ,("だ", "da") ,("ぢ", "di") ,("づ", "du") ,("て", "te") ,("で", "de") ,("と", "to") ,("ど", "do") ,("な", "na") ,("に", "ni") ,("ぬ", "nu") ,("ね", "ne") ,("の", "no") ,("は", "ha") ,("ば", "ba") ,("ぱ", "pa") ,("ひ", "hi") ,("び", "bi") ,("ぴ", "pi") ,("ふ", "fu") ,("ぶ", "bu") ,("ぷ", "pu") ,("へ", "he") ,("べ", "be") ,("ぺ", "pe") ,("ほ", "ho") ,("ぼ", "bo") ,("ぽ", "po") ,("ま", "ma") ,("み", "mi") ,("む", "mu") ,("め", "me") ,("も", "mo") ,("や", "ya") ,("ゆ", "yu") ,("よ", "yo") ,("ら", "ra") ,("り", "ri") ,("る", "ru") ,("れ", "re") ,("ろ", "ro") ,("わ", "wa") ,("ゐ", "wi") ,("ゑ", "we") ,("を", "wo") ,("ん", "n'") ,("し", "shi") ,("ち", "chi") ,("つ", "tsu") ,("ゃ", "xya") ,("ゅ", "xyu") ,("ょ", "xyo") ,("ゎ", "xwa") ,("っ", "xtsu") ] kunreiToHepburnAList :: [(Text, Text)] kunreiToHepburnAList = [ ("bbya", "bbya") ,("bbyo", "bbyo") ,("bbyu", "bbyu") ,("ddya", "ddya") ,("ddyo", "ddyo") ,("ddyu", "ddyu") ,("ggya", "ggya") ,("ggyo", "ggyo") ,("ggyu", "ggyu") ,("hhya", "hhya") ,("hhyo", "hhyo") ,("hhyu", "hhyu") ,("kkya", "kkya") ,("kkyo", "kkyo") ,("kkyu", "kkyu") ,("ppya", "ppya") ,("ppyo", "ppyo") ,("ppyu", "ppyu") ,("rrya", "rrya") ,("rryo", "rryo") ,("rryu", "rryu") ,("ssya", "ssha") ,("ssye", "sshe") ,("ssyo", "ssho") ,("ssyu", "sshu") ,("ttya", "ccha") ,("ttye", "cche") ,("ttyo", "ccho") ,("ttyu", "cchu") ,("zzya", "jja") ,("zzyo", "jjo") ,("zzyu", "jju") ,("bba", "bba") ,("bbe", "bbe") ,("bbi", "bbi") ,("bbo", "bbo") ,("bbu", "bbu") ,("bya", "bya") ,("byo", "byo") ,("byu", "byu") ,("dda", "dda") ,("dde", "dde") ,("ddi", "ddi") ,("ddo", "ddo") ,("ddu", "ddu") ,("dya", "dya") ,("dyi", "di") ,("dyo", "dyo") ,("dyu", "dyu") ,("ffa", "ffa") ,("ffe", "ffe") ,("ffi", "ffi") ,("ffo", "ffo") ,("ffu", "ffu") ,("gga", "gga") ,("gge", "gge") ,("ggi", "ggi") ,("ggo", "ggo") ,("ggu", "ggu") ,("gya", "gya") ,("gyo", "gyo") ,("gyu", "gyu") ,("hha", "hha") ,("hhe", "hhe") ,("hhi", "hhi") ,("hho", "hho") ,("hhu", "ffu") ,("hya", "hya") ,("hyo", "hyo") ,("hyu", "hyu") ,("kka", "kka") ,("kke", "kke") ,("kki", "kki") ,("kko", "kko") ,("kku", "kku") ,("kya", "kya") ,("kyo", "kyo") ,("kyu", "kyu") ,("mya", "mya") ,("myo", "myo") ,("myu", "myu") ,("nya", "nya") ,("nyo", "nyo") ,("nyu", "nyu") ,("ppa", "ppa") ,("ppe", "ppe") ,("ppi", "ppi") ,("ppo", "ppo") ,("ppu", "ppu") ,("pya", "pya") ,("pyo", "pyo") ,("pyu", "pyu") ,("rra", "rra") ,("rre", "rre") ,("rri", "rri") ,("rro", "rro") ,("rru", "rru") ,("rya", "rya") ,("ryo", "ryo") ,("ryu", "ryu") ,("ssa", "ssa") ,("sse", "sse") ,("ssi", "sshi") ,("sso", "sso") ,("ssu", "ssu") ,("sya", "sha") ,("sye", "she") ,("syo", "sho") ,("syu", "shu") ,("tta", "tta") ,("tte", "tte") ,("tti", "tti") ,("tto", "tto") ,("ttu", "ttsu") ,("tya", "cha") ,("tye", "che") ,("tyo", "cho") ,("tyu", "chu") ,("vva", "vva") ,("vve", "vve") ,("vvi", "vvi") ,("vvo", "vvo") ,("vvu", "vvu") ,("xtu", "xtsu") ,("xwa", "xwa") ,("xya", "xya") ,("xyo", "xyo") ,("xyu", "xyu") ,("yya", "yya") ,("yyo", "yyo") ,("yyu", "yyu") ,("zya", "ja") ,("zye", "je") ,("zyo", "jo") ,("zyu", "ju") ,("zza", "zza") ,("zze", "zze") ,("zzi", "jji") ,("zzo", "zzo") ,("zzu", "zzu") ,("ba", "ba") ,("be", "be") ,("bi", "bi") ,("bo", "bo") ,("bu", "bu") ,("da", "da") ,("de", "de") ,("di", "di") ,("do", "do") ,("du", "du") ,("fa", "fa") ,("fe", "fe") ,("fi", "fi") ,("fo", "fo") ,("fu", "fu") ,("ga", "ga") ,("ge", "ge") ,("gi", "gi") ,("go", "go") ,("gu", "gu") ,("ha", "ha") ,("he", "he") ,("hi", "hi") ,("ho", "ho") ,("hu", "fu") ,("ka", "ka") ,("ke", "ke") ,("ki", "ki") ,("ko", "ko") ,("ku", "ku") ,("ma", "ma") ,("me", "me") ,("mi", "mi") ,("mo", "mo") ,("mu", "mu") ,("n'", "n'") ,("na", "na") ,("ne", "ne") ,("ni", "ni") ,("no", "no") ,("nu", "nu") ,("pa", "pa") ,("pe", "pe") ,("pi", "pi") ,("po", "po") ,("pu", "pu") ,("ra", "ra") ,("re", "re") ,("ri", "ri") ,("ro", "ro") ,("ru", "ru") ,("sa", "sa") ,("se", "se") ,("si", "shi") ,("so", "so") ,("su", "su") ,("ta", "ta") ,("te", "te") ,("ti", "chi") ,("to", "to") ,("tu", "tsu") ,("va", "va") ,("ve", "ve") ,("vi", "vi") ,("vo", "vo") ,("vu", "vu") ,("wa", "wa") ,("we", "we") ,("wi", "wi") ,("wo", "wo") ,("xa", "xa") ,("xe", "xe") ,("xi", "xi") ,("xo", "xo") ,("xu", "xu") ,("ya", "ya") ,("yo", "yo") ,("yu", "yu") ,("za", "za") ,("ze", "ze") ,("zi", "ji") ,("zo", "zo") ,("zu", "zu") ,("-", "-") ,("a", "a") ,("e", "e") ,("i", "i") ,("n", "n") ,("o", "o") ,("u", "u") ] hepburnToKunreiAList :: [(Text, Text)] hepburnToKunreiAList = [ ("bbya", "bbya") ,("bbyo", "bbyo") ,("bbyu", "bbyu") ,("ccha", "ttya") ,("cche", "ttye") ,("cchi", "tti") ,("ccho", "ttyo") ,("cchu", "ttyu") ,("ddya", "ddya") ,("ddyo", "ddyo") ,("ddyu", "ddyu") ,("ggya", "ggya") ,("ggyo", "ggyo") ,("ggyu", "ggyu") ,("hhya", "hhya") ,("hhyo", "hhyo") ,("hhyu", "hhyu") ,("kkya", "kkya") ,("kkyo", "kkyo") ,("kkyu", "kkyu") ,("ppya", "ppya") ,("ppyo", "ppyo") ,("ppyu", "ppyu") ,("rrya", "rrya") ,("rryo", "rryo") ,("rryu", "rryu") ,("ssha", "ssya") ,("sshe", "ssye") ,("sshi", "ssi") ,("ssho", "ssyo") ,("sshu", "ssyu") ,("ttsu", "ttu") ,("xtsu", "xtu") ,("bba", "bba") ,("bbe", "bbe") ,("bbi", "bbi") ,("bbo", "bbo") ,("bbu", "bbu") ,("bya", "bya") ,("byo", "byo") ,("byu", "byu") ,("cha", "tya") ,("che", "tye") ,("chi", "ti") ,("cho", "tyo") ,("chu", "tyu") ,("dda", "dda") ,("dde", "dde") ,("ddi", "ddi") ,("ddo", "ddo") ,("ddu", "ddu") ,("dya", "dya") ,("dyo", "dyo") ,("dyu", "dyu") ,("ffa", "ffa") ,("ffe", "ffe") ,("ffi", "ffi") ,("ffo", "ffo") ,("ffu", "ffu") ,("gga", "gga") ,("gge", "gge") ,("ggi", "ggi") ,("ggo", "ggo") ,("ggu", "ggu") ,("gya", "gya") ,("gyo", "gyo") ,("gyu", "gyu") ,("hha", "hha") ,("hhe", "hhe") ,("hhi", "hhi") ,("hho", "hho") ,("hya", "hya") ,("hyo", "hyo") ,("hyu", "hyu") ,("jja", "zzya") ,("jji", "zzi") ,("jjo", "zzyo") ,("jju", "zzyu") ,("kka", "kka") ,("kke", "kke") ,("kki", "kki") ,("kko", "kko") ,("kku", "kku") ,("kya", "kya") ,("kyo", "kyo") ,("kyu", "kyu") ,("mya", "mya") ,("myo", "myo") ,("myu", "myu") ,("nya", "nya") ,("nyo", "nyo") ,("nyu", "nyu") ,("ppa", "ppa") ,("ppe", "ppe") ,("ppi", "ppi") ,("ppo", "ppo") ,("ppu", "ppu") ,("pya", "pya") ,("pyo", "pyo") ,("pyu", "pyu") ,("rra", "rra") ,("rre", "rre") ,("rri", "rri") ,("rro", "rro") ,("rru", "rru") ,("rya", "rya") ,("ryo", "ryo") ,("ryu", "ryu") ,("sha", "sya") ,("she", "sye") ,("shi", "si") ,("sho", "syo") ,("shu", "syu") ,("ssa", "ssa") ,("sse", "sse") ,("sso", "sso") ,("ssu", "ssu") ,("tsu", "tu") ,("tta", "tta") ,("tte", "tte") ,("tti", "tti") ,("tto", "tto") ,("vva", "vva") ,("vve", "vve") ,("vvi", "vvi") ,("vvo", "vvo") ,("vvu", "vvu") ,("xwa", "xwa") ,("xya", "xya") ,("xyo", "xyo") ,("xyu", "xyu") ,("yya", "yya") ,("yyo", "yyo") ,("yyu", "yyu") ,("zza", "zza") ,("zze", "zze") ,("zzo", "zzo") ,("zzu", "zzu") ,("ba", "ba") ,("be", "be") ,("bi", "bi") ,("bo", "bo") ,("bu", "bu") ,("da", "da") ,("de", "de") ,("di", "dyi") ,("do", "do") ,("du", "du") ,("fa", "fa") ,("fe", "fe") ,("fi", "fi") ,("fo", "fo") ,("fu", "fu") ,("ga", "ga") ,("ge", "ge") ,("gi", "gi") ,("go", "go") ,("gu", "gu") ,("ha", "ha") ,("he", "he") ,("hi", "hi") ,("ho", "ho") ,("ja", "zya") ,("je", "zye") ,("ji", "zi") ,("jo", "zyo") ,("ju", "zyu") ,("ka", "ka") ,("ke", "ke") ,("ki", "ki") ,("ko", "ko") ,("ku", "ku") ,("ma", "ma") ,("me", "me") ,("mi", "mi") ,("mo", "mo") ,("mu", "mu") ,("n'", "n'") ,("na", "na") ,("ne", "ne") ,("ni", "ni") ,("no", "no") ,("nu", "nu") ,("pa", "pa") ,("pe", "pe") ,("pi", "pi") ,("po", "po") ,("pu", "pu") ,("ra", "ra") ,("re", "re") ,("ri", "ri") ,("ro", "ro") ,("ru", "ru") ,("sa", "sa") ,("se", "se") ,("so", "so") ,("su", "su") ,("ta", "ta") ,("te", "te") ,("ti", "ti") ,("to", "to") ,("va", "va") ,("ve", "ve") ,("vi", "vi") ,("vo", "vo") ,("vu", "vu") ,("wa", "wa") ,("we", "we") ,("wi", "wi") ,("wo", "wo") ,("xa", "xa") ,("xe", "xe") ,("xi", "xi") ,("xo", "xo") ,("xu", "xu") ,("ya", "ya") ,("yo", "yo") ,("yu", "yu") ,("za", "za") ,("ze", "ze") ,("zo", "zo") ,("zu", "zu") ,("-", "-") ,("a", "a") ,("e", "e") ,("i", "i") ,("n", "n") ,("o", "o") ,("u", "u") ]
karlvoigtland/romkan-hs
NLP/Romkan/Internal.hs
Haskell
bsd-3-clause
29,985
module Main ( main ) where import Test.HUnit (runTestTT) import Yawn.Test.Common (withServer) import qualified Yawn.Test.BlackBox.ParserTest as ParserTest (tests) main :: IO () main = withServer "www" $ do runTestTT ParserTest.tests return ()
ameingast/yawn
test/src/TestMain.hs
Haskell
bsd-3-clause
252
module Benchmarks.ListSet where type Set a = [a] empty :: Set a empty = [] insert :: Ord a => a -> Set a -> Set a insert a [] = [a] insert a (x:xs) | a < x = a:x:xs | a > x = x:insert a xs | a == x = x:xs set :: Ord a => [a] -> Set a set = foldr insert empty ordered [] = True ordered [x] = True ordered (x:y:zs) = x <= y && ordered (y:zs) allDiff [] = True allDiff (x:xs) = x `notElem` xs && allDiff xs isSet s = ordered s && allDiff s -- Properties infixr 0 --> False --> _ = True True --> x = x prop_insertSet :: (Char, Set Char) -> Bool prop_insertSet (c, s) = ordered s --> ordered (insert c s)
UoYCS-plasma/LazySmallCheck2012
suite/performance/Benchmarks/ListSet.hs
Haskell
bsd-3-clause
616
module HsImport.Utils ( firstSrcLine , lastSrcLine , srcSpan , declSrcLoc , importDecls ) where import qualified Language.Haskell.Exts as HS import HsImport.Types declSrcLoc :: Decl -> SrcLoc declSrcLoc decl = HS.SrcLoc srcFile srcLine srcCol where declSrcSpan = srcSpan . HS.ann $ decl srcFile = HS.srcSpanFilename declSrcSpan srcLine = HS.srcSpanStartLine declSrcSpan srcCol = HS.srcSpanStartColumn declSrcSpan importDecls :: Module -> [ImportDecl] importDecls (HS.Module _ _ _ imports _) = imports importDecls (HS.XmlPage _ _ _ _ _ _ _) = [] importDecls (HS.XmlHybrid _ _ _ imports _ _ _ _ _) = imports
dan-t/hsimport
lib/HsImport/Utils.hs
Haskell
bsd-3-clause
692
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Common where -- orig in mu/Syntax.hs -- N for name, but Name already used in Bound, -- and Nm is a data type in Syntax, thus N - oh well type N = String data Binop = Add | Sub | Mul | Eql deriving (Eq, Ord, Show, Read)
reuleaux/pire
exe/Common.hs
Haskell
bsd-3-clause
283
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE RankNTypes #-} module Language.Haskell.Refact.Utils.ExactPrint ( replace , replaceAnnKey , copyAnn , setAnnKeywordDP , clearPriorComments , balanceAllComments ) where import qualified GHC as GHC import qualified Data.Generics as SYB import Control.Monad import Language.Haskell.GHC.ExactPrint.Transform import Language.Haskell.GHC.ExactPrint.Types -- import Language.Haskell.GHC.ExactPrint.Utils import Language.Haskell.Refact.Utils.GhcUtils import qualified Data.Map as Map -- --------------------------------------------------------------------- -- ++AZ++:TODO: Move this to ghc-exactprint -- |The annotations are keyed to the constructor, so if we replace a qualified -- with an unqualified RdrName or vice versa we have to rebuild the key for the -- appropriate annotation. replaceAnnKey :: (SYB.Data old,SYB.Data new) => GHC.Located old -> GHC.Located new -> Anns -> Anns replaceAnnKey old new ans = case Map.lookup (mkAnnKey old) ans of Nothing -> ans Just v -> anns' where anns1 = Map.delete (mkAnnKey old) ans anns' = Map.insert (mkAnnKey new) v anns1 -- --------------------------------------------------------------------- -- ++AZ++ TODO: migrate this to ghc-exactprint copyAnn :: (SYB.Data old,SYB.Data new) => GHC.Located old -> GHC.Located new -> Anns -> Anns copyAnn old new ans = case Map.lookup (mkAnnKey old) ans of Nothing -> ans Just v -> Map.insert (mkAnnKey new) v ans -- --------------------------------------------------------------------- -- | Replaces an old expression with a new expression replace :: AnnKey -> AnnKey -> Anns -> Maybe Anns replace old new ans = do let as = ans oldan <- Map.lookup old as newan <- Map.lookup new as let newan' = Ann { annEntryDelta = annEntryDelta oldan -- , annDelta = annDelta oldan -- , annTrueEntryDelta = annTrueEntryDelta oldan , annPriorComments = annPriorComments oldan , annFollowingComments = annFollowingComments oldan , annsDP = moveAnns (annsDP oldan) (annsDP newan) , annSortKey = annSortKey oldan , annCapturedSpan = annCapturedSpan oldan } return ((\anns -> Map.delete old . Map.insert new newan' $ anns) ans) -- --------------------------------------------------------------------- -- | Shift the first output annotation into the correct place moveAnns :: [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] -> [(KeywordId, DeltaPos)] moveAnns [] xs = xs moveAnns ((_, dp): _) ((kw, _):xs) = (kw,dp) : xs moveAnns _ [] = [] -- --------------------------------------------------------------------- -- |Change the @DeltaPos@ for a given @KeywordId@ if it appears in the -- annotation for the given item. setAnnKeywordDP :: (SYB.Data a) => GHC.Located a -> KeywordId -> DeltaPos -> Transform () setAnnKeywordDP la kw dp = modifyAnnsT changer where changer ans = case Map.lookup (mkAnnKey la) ans of Nothing -> ans Just an -> Map.insert (mkAnnKey la) (an {annsDP = map update (annsDP an)}) ans update (kw',dp') | kw == kw' = (kw',dp) | otherwise = (kw',dp') -- --------------------------------------------------------------------- -- |Remove any preceding comments from the given item clearPriorComments :: (SYB.Data a) => GHC.Located a -> Transform () clearPriorComments la = do edp <- getEntryDPT la modifyAnnsT $ \ans -> case Map.lookup (mkAnnKey la) ans of Nothing -> ans Just an -> Map.insert (mkAnnKey la) (an {annPriorComments = [] }) ans setEntryDPT la edp -- --------------------------------------------------------------------- balanceAllComments :: SYB.Data a => GHC.Located a -> Transform (GHC.Located a) balanceAllComments la -- Must be top-down = everywhereM' (SYB.mkM inMod `SYB.extM` inExpr `SYB.extM` inMatch `SYB.extM` inStmt ) la where inMod :: GHC.ParsedSource -> Transform (GHC.ParsedSource) inMod m = doBalance m inExpr :: GHC.LHsExpr GHC.RdrName -> Transform (GHC.LHsExpr GHC.RdrName) inExpr e = doBalance e inMatch :: (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) -> Transform (GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)) inMatch m = doBalance m inStmt :: GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName) -> Transform (GHC.LStmt GHC.RdrName (GHC.LHsExpr GHC.RdrName)) inStmt s = doBalance s -- |Balance all comments between adjacent decls, as well as pushing all -- trailing comments to the right place. {- e.g., for foo = do return x where x = ['a'] -- do bar = undefined the "-- do" comment must end up in the trailing comments for "x = ['a']" -} doBalance t = do decls <- hsDecls t let go [] = return [] go [x] = return [x] go (x1:x2:xs) = do balanceComments x1 x2 go (x2:xs) _ <- go decls -- replaceDecls t decls' unless (null decls) $ moveTrailingComments t (last decls) return t -- ---------------------------------------------------------------------
SAdams601/ParRegexSearch
test/HaRe/src/Language/Haskell/Refact/Utils/ExactPrint.hs
Haskell
mit
5,482
{-# OPTIONS_GHC -F -pgmF htfpp #-} module GameTest where import Test.Framework prop_reverse :: [Int] -> Bool prop_reverse xs = xs == (reverse (reverse xs))
abailly/hsgames
acquire/test/GameTest.hs
Haskell
apache-2.0
168
{-# LANGUAGE TemplateHaskell #-} {-| Implementation of the Ganeti LUXI interface. -} {- Copyright (C) 2009, 2010, 2011, 2012, 2013 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.Luxi ( LuxiOp(..) , LuxiReq(..) , Client , Server , JobId , fromJobId , makeJobId , RecvResult(..) , strOfOp , opToArgs , getLuxiClient , getLuxiServer , acceptClient , closeClient , closeServer , callMethod , submitManyJobs , queryJobsStatus , buildCall , buildResponse , decodeLuxiCall , recvMsg , recvMsgExt , sendMsg , allLuxiCalls ) where import Control.Applicative (optional, liftA, (<|>)) import Control.Monad import qualified Text.JSON as J import Text.JSON.Pretty (pp_value) import Text.JSON.Types import Ganeti.BasicTypes import Ganeti.Constants import Ganeti.Errors import Ganeti.JSON (fromJResult, fromJVal, Tuple5(..), MaybeForJSON(..), TimeAsDoubleJSON(..)) import Ganeti.UDSServer import Ganeti.Objects import Ganeti.OpParams (pTagsObject) import Ganeti.OpCodes import qualified Ganeti.Query.Language as Qlang import Ganeti.Runtime (GanetiDaemon(..), GanetiGroup(..), MiscGroup(..)) import Ganeti.THH import Ganeti.THH.Field import Ganeti.THH.Types (getOneTuple) import Ganeti.Types import Ganeti.Utils -- | Currently supported Luxi operations and JSON serialization. $(genLuxiOp "LuxiOp" [ (luxiReqQuery, [ simpleField "what" [t| Qlang.ItemType |] , simpleField "fields" [t| [String] |] , simpleField "qfilter" [t| Qlang.Filter Qlang.FilterField |] ]) , (luxiReqQueryFields, [ simpleField "what" [t| Qlang.ItemType |] , simpleField "fields" [t| [String] |] ]) , (luxiReqQueryNodes, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryGroups, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryNetworks, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryInstances, [ simpleField "names" [t| [String] |] , simpleField "fields" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryFilters, [ simpleField "uuids" [t| [String] |] , simpleField "fields" [t| [String] |] ]) , (luxiReqReplaceFilter, -- UUID is missing for insert, present for upsert [ optionalNullSerField $ simpleField "uuid" [t| String |] , simpleField "priority" [t| NonNegative Int |] , simpleField "predicates" [t| [FilterPredicate] |] , simpleField "action" [t| FilterAction |] , simpleField "reason" [t| ReasonTrail |] ]) , (luxiReqDeleteFilter, [ simpleField "uuid" [t| String |] ]) , (luxiReqQueryJobs, [ simpleField "ids" [t| [JobId] |] , simpleField "fields" [t| [String] |] ]) , (luxiReqQueryExports, [ simpleField "nodes" [t| [String] |] , simpleField "lock" [t| Bool |] ]) , (luxiReqQueryConfigValues, [ simpleField "fields" [t| [String] |] ] ) , (luxiReqQueryClusterInfo, []) , (luxiReqQueryTags, [ pTagsObject , simpleField "name" [t| String |] ]) , (luxiReqSubmitJob, [ simpleField "job" [t| [MetaOpCode] |] ] ) , (luxiReqSubmitJobToDrainedQueue, [ simpleField "job" [t| [MetaOpCode] |] ] ) , (luxiReqSubmitManyJobs, [ simpleField "ops" [t| [[MetaOpCode]] |] ] ) , (luxiReqWaitForJobChange, [ simpleField "job" [t| JobId |] , simpleField "fields" [t| [String]|] , simpleField "prev_job" [t| JSValue |] , simpleField "prev_log" [t| JSValue |] , simpleField "tmout" [t| Int |] ]) , (luxiReqPickupJob, [ simpleField "job" [t| JobId |] ] ) , (luxiReqArchiveJob, [ simpleField "job" [t| JobId |] ] ) , (luxiReqAutoArchiveJobs, [ simpleField "age" [t| Int |] , simpleField "tmout" [t| Int |] ]) , (luxiReqCancelJob, [ simpleField "job" [t| JobId |] , simpleField "kill" [t| Bool |] ]) , (luxiReqChangeJobPriority, [ simpleField "job" [t| JobId |] , simpleField "priority" [t| Int |] ] ) , (luxiReqSetDrainFlag, [ simpleField "flag" [t| Bool |] ] ) , (luxiReqSetWatcherPause, [ optionalNullSerField $ timeAsDoubleField "duration" ] ) ]) $(makeJSONInstance ''LuxiReq) -- | List of all defined Luxi calls. $(genAllConstr (drop 3) ''LuxiReq "allLuxiCalls") -- | The serialisation of LuxiOps into strings in messages. $(genStrOfOp ''LuxiOp "strOfOp") luxiConnectConfig :: ServerConfig luxiConnectConfig = ServerConfig -- The rapi daemon talks to the luxi one, and for this -- purpose we need group rw permissions. FilePermissions { fpOwner = Just GanetiLuxid , fpGroup = Just $ ExtraGroup DaemonsGroup , fpPermissions = 0o0660 } ConnectConfig { recvTmo = luxiDefRwto , sendTmo = luxiDefRwto } -- | Connects to the master daemon and returns a luxi Client. getLuxiClient :: String -> IO Client getLuxiClient = connectClient (connConfig luxiConnectConfig) luxiDefCtmo -- | Creates and returns a server endpoint. getLuxiServer :: Bool -> FilePath -> IO Server getLuxiServer = connectServer luxiConnectConfig -- | Converts Luxi call arguments into a 'LuxiOp' data structure. -- This is used for building a Luxi 'Handler'. -- -- This is currently hand-coded until we make it more uniform so that -- it can be generated using TH. decodeLuxiCall :: JSValue -> JSValue -> Result LuxiOp decodeLuxiCall method args = do call <- fromJResult "Unable to parse LUXI request method" $ J.readJSON method case call of ReqQueryFilters -> do (uuids, fields) <- fromJVal args uuids' <- case uuids of JSNull -> return [] _ -> fromJVal uuids return $ QueryFilters uuids' fields ReqReplaceFilter -> do Tuple5 ( uuid , priority , predicates , action , reason) <- fromJVal args return $ ReplaceFilter (unMaybeForJSON uuid) priority predicates action reason ReqDeleteFilter -> do [uuid] <- fromJVal args return $ DeleteFilter uuid ReqQueryJobs -> do (jids, jargs) <- fromJVal args jids' <- case jids of JSNull -> return [] _ -> fromJVal jids return $ QueryJobs jids' jargs ReqQueryInstances -> do (names, fields, locking) <- fromJVal args return $ QueryInstances names fields locking ReqQueryNodes -> do (names, fields, locking) <- fromJVal args return $ QueryNodes names fields locking ReqQueryGroups -> do (names, fields, locking) <- fromJVal args return $ QueryGroups names fields locking ReqQueryClusterInfo -> return QueryClusterInfo ReqQueryNetworks -> do (names, fields, locking) <- fromJVal args return $ QueryNetworks names fields locking ReqQuery -> do (what, fields, qfilter) <- fromJVal args return $ Query what fields qfilter ReqQueryFields -> do (what, fields) <- fromJVal args fields' <- case fields of JSNull -> return [] _ -> fromJVal fields return $ QueryFields what fields' ReqSubmitJob -> do [ops1] <- fromJVal args ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1 return $ SubmitJob ops2 ReqSubmitJobToDrainedQueue -> do [ops1] <- fromJVal args ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1 return $ SubmitJobToDrainedQueue ops2 ReqSubmitManyJobs -> do [ops1] <- fromJVal args ops2 <- mapM (fromJResult (luxiReqToRaw call) . J.readJSON) ops1 return $ SubmitManyJobs ops2 ReqWaitForJobChange -> do (jid, fields, pinfo, pidx, wtmout) <- -- No instance for 5-tuple, code copied from the -- json sources and adapted fromJResult "Parsing WaitForJobChange message" $ case args of JSArray [a, b, c, d, e] -> (,,,,) `fmap` J.readJSON a `ap` J.readJSON b `ap` J.readJSON c `ap` J.readJSON d `ap` J.readJSON e _ -> J.Error "Not enough values" return $ WaitForJobChange jid fields pinfo pidx wtmout ReqPickupJob -> do [jid] <- fromJVal args return $ PickupJob jid ReqArchiveJob -> do [jid] <- fromJVal args return $ ArchiveJob jid ReqAutoArchiveJobs -> do (age, tmout) <- fromJVal args return $ AutoArchiveJobs age tmout ReqQueryExports -> do (nodes, lock) <- fromJVal args return $ QueryExports nodes lock ReqQueryConfigValues -> do [fields] <- fromJVal args return $ QueryConfigValues fields ReqQueryTags -> do (kind, name) <- fromJVal args return $ QueryTags kind name ReqCancelJob -> do (jid, kill) <- fromJVal args <|> liftA (flip (,) False . getOneTuple) (fromJVal args) return $ CancelJob jid kill ReqChangeJobPriority -> do (jid, priority) <- fromJVal args return $ ChangeJobPriority jid priority ReqSetDrainFlag -> do [flag] <- fromJVal args return $ SetDrainFlag flag ReqSetWatcherPause -> do duration <- optional $ do [x] <- fromJVal args liftM unTimeAsDoubleJSON $ fromJVal x return $ SetWatcherPause duration -- | Generic luxi method call callMethod :: LuxiOp -> Client -> IO (ErrorResult JSValue) callMethod method s = do sendMsg s $ buildCall (strOfOp method) (opToArgs method) result <- recvMsg s return $ parseResponse result -- | Parse job submission result. parseSubmitJobResult :: JSValue -> ErrorResult JobId parseSubmitJobResult (JSArray [JSBool True, v]) = case J.readJSON v of J.Error msg -> Bad $ LuxiError msg J.Ok v' -> Ok v' parseSubmitJobResult (JSArray [JSBool False, JSString x]) = Bad . LuxiError $ fromJSString x parseSubmitJobResult v = Bad . LuxiError $ "Unknown result from the master daemon: " ++ show (pp_value v) -- | Specialized submitManyJobs call. submitManyJobs :: Client -> [[MetaOpCode]] -> IO (ErrorResult [JobId]) submitManyJobs s jobs = do rval <- callMethod (SubmitManyJobs jobs) s -- map each result (status, payload) pair into a nice Result ADT return $ case rval of Bad x -> Bad x Ok (JSArray r) -> mapM parseSubmitJobResult r x -> Bad . LuxiError $ "Cannot parse response from Ganeti: " ++ show x -- | Custom queryJobs call. queryJobsStatus :: Client -> [JobId] -> IO (ErrorResult [JobStatus]) queryJobsStatus s jids = do rval <- callMethod (QueryJobs jids ["status"]) s return $ case rval of Bad x -> Bad x Ok y -> case J.readJSON y::(J.Result [[JobStatus]]) of J.Ok vals -> if any null vals then Bad $ LuxiError "Missing job status field" else Ok (map head vals) J.Error x -> Bad $ LuxiError x
mbakke/ganeti
src/Ganeti/Luxi.hs
Haskell
bsd-2-clause
13,584
module Tandoori.GHC.Internals (module SrcLoc, module Outputable, module Name, module BasicTypes, module Unique, module FastString, module HsExpr, module HsTypes, module HsPat, module HsLit, module HsBinds, module DataCon, module TysWiredIn, module PrelNames, module HsDecls, module Module) where import SrcLoc import Outputable import Name import BasicTypes import Unique import FastString import HsExpr import HsTypes import HsPat import HsLit import HsBinds import DataCon (dataConName) import TysWiredIn (intTyConName, charTyConName, boolTyConName, listTyConName, tupleTyCon, nilDataCon, consDataCon, trueDataCon, falseDataCon) import PrelNames (stringTyConName, eqClassName, ordClassName, numClassName, fractionalClassName) import HsDecls import Module
bitemyapp/tandoori
src/Tandoori/GHC/Internals.hs
Haskell
bsd-3-clause
845
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1997-1998 Author: Juan J. Quintela <quintela@krilin.dc.fi.udc.es> -} {-# LANGUAGE CPP #-} module ETA.DeSugar.Check ( check , ExhaustivePat ) where import ETA.HsSyn.HsSyn import ETA.TypeCheck.TcHsSyn import ETA.DeSugar.DsUtils import ETA.DeSugar.MatchLit import ETA.BasicTypes.Id import ETA.BasicTypes.ConLike import ETA.BasicTypes.DataCon import ETA.BasicTypes.PatSyn import ETA.BasicTypes.Name import ETA.Prelude.TysWiredIn import ETA.Prelude.PrelNames import ETA.Types.TyCon import ETA.BasicTypes.SrcLoc import ETA.Utils.UniqSet import ETA.Utils.Util import ETA.BasicTypes.BasicTypes import ETA.Utils.Outputable import ETA.Utils.FastString #include "HsVersions.h" {- This module performs checks about if one list of equations are: \begin{itemize} \item Overlapped \item Non exhaustive \end{itemize} To discover that we go through the list of equations in a tree-like fashion. If you like theory, a similar algorithm is described in: \begin{quotation} {\em Two Techniques for Compiling Lazy Pattern Matching}, Luc Maranguet, INRIA Rocquencourt (RR-2385, 1994) \end{quotation} The algorithm is based on the first technique, but there are some differences: \begin{itemize} \item We don't generate code \item We have constructors and literals (not only literals as in the article) \item We don't use directions, we must select the columns from left-to-right \end{itemize} (By the way the second technique is really similar to the one used in @Match.lhs@ to generate code) This function takes the equations of a pattern and returns: \begin{itemize} \item The patterns that are not recognized \item The equations that are not overlapped \end{itemize} It simplify the patterns and then call @check'@ (the same semantics), and it needs to reconstruct the patterns again .... The problem appear with things like: \begin{verbatim} f [x,y] = .... f (x:xs) = ..... \end{verbatim} We want to put the two patterns with the same syntax, (prefix form) and then all the constructors are equal: \begin{verbatim} f (: x (: y [])) = .... f (: x xs) = ..... \end{verbatim} (more about that in @tidy_eqns@) We would prefer to have a @WarningPat@ of type @String@, but Strings and the Pretty Printer are not friends. We use @InPat@ in @WarningPat@ instead of @OutPat@ because we need to print the warning messages in the same way they are introduced, i.e. if the user wrote: \begin{verbatim} f [x,y] = .. \end{verbatim} He don't want a warning message written: \begin{verbatim} f (: x (: y [])) ........ \end{verbatim} Then we need to use InPats. \begin{quotation} Juan Quintela 5 JUL 1998\\ User-friendliness and compiler writers are no friends. \end{quotation} -} type WarningPat = InPat Name type ExhaustivePat = ([WarningPat], [(Name, [HsLit])]) type EqnNo = Int type EqnSet = UniqSet EqnNo check :: [EquationInfo] -> ([ExhaustivePat], [EquationInfo]) -- Second result is the shadowed equations -- if there are view patterns, just give up - don't know what the function is check qs = (untidy_warns, shadowed_eqns) where tidy_qs = map tidy_eqn qs (warns, used_nos) = check' ([1..] `zip` tidy_qs) untidy_warns = map untidy_exhaustive warns shadowed_eqns = [eqn | (eqn,i) <- qs `zip` [1..], not (i `elementOfUniqSet` used_nos)] untidy_exhaustive :: ExhaustivePat -> ExhaustivePat untidy_exhaustive ([pat], messages) = ([untidy_no_pars pat], map untidy_message messages) untidy_exhaustive (pats, messages) = (map untidy_pars pats, map untidy_message messages) untidy_message :: (Name, [HsLit]) -> (Name, [HsLit]) untidy_message (string, lits) = (string, map untidy_lit lits) -- The function @untidy@ does the reverse work of the @tidy_pat@ function. type NeedPars = Bool untidy_no_pars :: WarningPat -> WarningPat untidy_no_pars p = untidy False p untidy_pars :: WarningPat -> WarningPat untidy_pars p = untidy True p untidy :: NeedPars -> WarningPat -> WarningPat untidy b (L loc p) = L loc (untidy' b p) where untidy' _ p@(WildPat _) = p untidy' _ p@(VarPat _) = p untidy' _ (LitPat lit) = LitPat (untidy_lit lit) untidy' _ p@(ConPatIn _ (PrefixCon [])) = p untidy' b (ConPatIn name ps) = pars b (L loc (ConPatIn name (untidy_con ps))) untidy' _ (ListPat pats ty Nothing) = ListPat (map untidy_no_pars pats) ty Nothing untidy' _ (TuplePat pats box tys) = TuplePat (map untidy_no_pars pats) box tys untidy' _ (ListPat _ _ (Just _)) = panic "Check.untidy: Overloaded ListPat" untidy' _ (PArrPat _ _) = panic "Check.untidy: Shouldn't get a parallel array here!" untidy' _ (SigPatIn _ _) = panic "Check.untidy: SigPat" untidy' _ (LazyPat {}) = panic "Check.untidy: LazyPat" untidy' _ (AsPat {}) = panic "Check.untidy: AsPat" untidy' _ (ParPat {}) = panic "Check.untidy: ParPat" untidy' _ (BangPat {}) = panic "Check.untidy: BangPat" untidy' _ (ConPatOut {}) = panic "Check.untidy: ConPatOut" untidy' _ (ViewPat {}) = panic "Check.untidy: ViewPat" untidy' _ (SplicePat {}) = panic "Check.untidy: SplicePat" untidy' _ (QuasiQuotePat {}) = panic "Check.untidy: QuasiQuotePat" untidy' _ (NPat {}) = panic "Check.untidy: NPat" untidy' _ (NPlusKPat {}) = panic "Check.untidy: NPlusKPat" untidy' _ (SigPatOut {}) = panic "Check.untidy: SigPatOut" untidy' _ (CoPat {}) = panic "Check.untidy: CoPat" untidy_con :: HsConPatDetails Name -> HsConPatDetails Name untidy_con (PrefixCon pats) = PrefixCon (map untidy_pars pats) untidy_con (InfixCon p1 p2) = InfixCon (untidy_pars p1) (untidy_pars p2) untidy_con (RecCon (HsRecFields flds dd)) = RecCon (HsRecFields [ L l (fld { hsRecFieldArg = untidy_pars (hsRecFieldArg fld) }) | L l fld <- flds ] dd) pars :: NeedPars -> WarningPat -> Pat Name pars True p = ParPat p pars _ p = unLoc p untidy_lit :: HsLit -> HsLit untidy_lit (HsCharPrim src c) = HsChar src c untidy_lit lit = lit {- This equation is the same that check, the only difference is that the boring work is done, that work needs to be done only once, this is the reason top have two functions, check is the external interface, @check'@ is called recursively. There are several cases: \begin{itemize} \item There are no equations: Everything is OK. \item There are only one equation, that can fail, and all the patterns are variables. Then that equation is used and the same equation is non-exhaustive. \item All the patterns are variables, and the match can fail, there are more equations then the results is the result of the rest of equations and this equation is used also. \item The general case, if all the patterns are variables (here the match can't fail) then the result is that this equation is used and this equation doesn't generate non-exhaustive cases. \item In the general case, there can exist literals ,constructors or only vars in the first column, we actuate in consequence. \end{itemize} -} check' :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], -- Pattern scheme that might not be matched at all EqnSet) -- Eqns that are used (others are overlapped) check' [] = ([],emptyUniqSet) -- Was ([([],[])], emptyUniqSet) -- But that (a) seems weird, and (b) triggered Trac #7669 -- So now I'm just doing the simple obvious thing check' ((n, EqnInfo { eqn_pats = ps, eqn_rhs = MatchResult can_fail _ }) : rs) | first_eqn_all_vars && case can_fail of { CantFail -> True; CanFail -> False } = ([], unitUniqSet n) -- One eqn, which can't fail | first_eqn_all_vars && null rs -- One eqn, but it can fail = ([(takeList ps (repeat nlWildPatName),[])], unitUniqSet n) | first_eqn_all_vars -- Several eqns, first can fail = (pats, addOneToUniqSet indexs n) where first_eqn_all_vars = all_vars ps (pats,indexs) = check' rs check' qs | some_literals = split_by_literals qs | some_constructors = split_by_constructor qs | only_vars = first_column_only_vars qs | otherwise = pprPanic "Check.check': Not implemented :-(" (ppr first_pats) -- Shouldn't happen where -- Note: RecPats will have been simplified to ConPats -- at this stage. first_pats = ASSERT2( okGroup qs, pprGroup qs ) map firstPatN qs some_constructors = any is_con first_pats some_literals = any is_lit first_pats only_vars = all is_var first_pats {- Here begins the code to deal with literals, we need to split the matrix in different matrix beginning by each literal and a last matrix with the rest of values. -} split_by_literals :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], EqnSet) split_by_literals qs = process_literals used_lits qs where used_lits = get_used_lits qs {- @process_explicit_literals@ is a function that process each literal that appears in the column of the matrix. -} process_explicit_literals :: [HsLit] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) process_explicit_literals lits qs = (concat pats, unionManyUniqSets indexs) where pats_indexs = map (\x -> construct_literal_matrix x qs) lits (pats,indexs) = unzip pats_indexs {- @process_literals@ calls @process_explicit_literals@ to deal with the literals that appears in the matrix and deal also with the rest of the cases. It must be one Variable to be complete. -} process_literals :: [HsLit] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) process_literals used_lits qs | null default_eqns = ASSERT( not (null qs) ) ([make_row_vars used_lits (head qs)] ++ pats,indexs) | otherwise = (pats_default,indexs_default) where (pats,indexs) = process_explicit_literals used_lits qs default_eqns = ASSERT2( okGroup qs, pprGroup qs ) [remove_var q | q <- qs, is_var (firstPatN q)] (pats',indexs') = check' default_eqns pats_default = [(nlWildPatName:ps,constraints) | (ps,constraints) <- (pats')] ++ pats indexs_default = unionUniqSets indexs' indexs {- Here we have selected the literal and we will select all the equations that begins for that literal and create a new matrix. -} construct_literal_matrix :: HsLit -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) construct_literal_matrix lit qs = (map (\ (xs,ys) -> (new_lit:xs,ys)) pats,indexs) where (pats,indexs) = (check' (remove_first_column_lit lit qs)) new_lit = nlLitPat lit remove_first_column_lit :: HsLit -> [(EqnNo, EquationInfo)] -> [(EqnNo, EquationInfo)] remove_first_column_lit lit qs = ASSERT2( okGroup qs, pprGroup qs ) [(n, shift_pat eqn) | q@(n,eqn) <- qs, is_var_lit lit (firstPatN q)] where shift_pat eqn@(EqnInfo { eqn_pats = _:ps}) = eqn { eqn_pats = ps } shift_pat _ = panic "Check.shift_var: no patterns" {- This function splits the equations @qs@ in groups that deal with the same constructor. -} split_by_constructor :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat], EqnSet) split_by_constructor qs | null used_cons = ([], mkUniqSet $ map fst qs) | notNull unused_cons = need_default_case used_cons unused_cons qs | otherwise = no_need_default_case used_cons qs where used_cons = get_used_cons qs unused_cons = get_unused_cons used_cons {- The first column of the patterns matrix only have vars, then there is nothing to do. -} first_column_only_vars :: [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) first_column_only_vars qs = (map (\ (xs,ys) -> (nlWildPatName:xs,ys)) pats,indexs) where (pats, indexs) = check' (map remove_var qs) {- This equation takes a matrix of patterns and split the equations by constructor, using all the constructors that appears in the first column of the pattern matching. We can need a default clause or not ...., it depends if we used all the constructors or not explicitly. The reasoning is similar to @process_literals@, the difference is that here the default case is not always needed. -} no_need_default_case :: [Pat Id] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) no_need_default_case cons qs = (concat pats, unionManyUniqSets indexs) where pats_indexs = map (\x -> construct_matrix x qs) cons (pats,indexs) = unzip pats_indexs need_default_case :: [Pat Id] -> [DataCon] -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) need_default_case used_cons unused_cons qs | null default_eqns = (pats_default_no_eqns,indexs) | otherwise = (pats_default,indexs_default) where (pats,indexs) = no_need_default_case used_cons qs default_eqns = ASSERT2( okGroup qs, pprGroup qs ) [remove_var q | q <- qs, is_var (firstPatN q)] (pats',indexs') = check' default_eqns pats_default = [(make_whole_con c:ps,constraints) | c <- unused_cons, (ps,constraints) <- pats'] ++ pats new_wilds = ASSERT( not (null qs) ) make_row_vars_for_constructor (head qs) pats_default_no_eqns = [(make_whole_con c:new_wilds,[]) | c <- unused_cons] ++ pats indexs_default = unionUniqSets indexs' indexs construct_matrix :: Pat Id -> [(EqnNo, EquationInfo)] -> ([ExhaustivePat],EqnSet) construct_matrix con qs = (map (make_con con) pats,indexs) where (pats,indexs) = (check' (remove_first_column con qs)) {- Here remove first column is more difficult that with literals due to the fact that constructors can have arguments. For instance, the matrix \begin{verbatim} (: x xs) y z y \end{verbatim} is transformed in: \begin{verbatim} x xs y _ _ y \end{verbatim} -} remove_first_column :: Pat Id -- Constructor -> [(EqnNo, EquationInfo)] -> [(EqnNo, EquationInfo)] remove_first_column (ConPatOut{ pat_con = L _ con, pat_args = PrefixCon con_pats }) qs = ASSERT2( okGroup qs, pprGroup qs ) [(n, shift_var eqn) | q@(n, eqn) <- qs, is_var_con con (firstPatN q)] where new_wilds = [WildPat (hsLPatType arg_pat) | arg_pat <- con_pats] shift_var eqn@(EqnInfo { eqn_pats = ConPatOut{ pat_args = PrefixCon ps' } : ps}) = eqn { eqn_pats = map unLoc ps' ++ ps } shift_var eqn@(EqnInfo { eqn_pats = WildPat _ : ps }) = eqn { eqn_pats = new_wilds ++ ps } shift_var _ = panic "Check.Shift_var:No done" remove_first_column _ _ = panic "Check.remove_first_column: Not ConPatOut" make_row_vars :: [HsLit] -> (EqnNo, EquationInfo) -> ExhaustivePat make_row_vars used_lits (_, EqnInfo { eqn_pats = pats}) = (nlVarPat new_var:takeList (tail pats) (repeat nlWildPatName) ,[(new_var,used_lits)]) where new_var = hash_x hash_x :: Name hash_x = mkInternalName unboundKey {- doesn't matter much -} (mkVarOccFS (fsLit "#x")) noSrcSpan make_row_vars_for_constructor :: (EqnNo, EquationInfo) -> [WarningPat] make_row_vars_for_constructor (_, EqnInfo { eqn_pats = pats}) = takeList (tail pats) (repeat nlWildPatName) compare_cons :: Pat Id -> Pat Id -> Bool compare_cons (ConPatOut{ pat_con = L _ con1 }) (ConPatOut{ pat_con = L _ con2 }) = case (con1, con2) of (RealDataCon id1, RealDataCon id2) -> id1 == id2 _ -> False compare_cons _ _ = panic "Check.compare_cons: Not ConPatOut with RealDataCon" remove_dups :: [Pat Id] -> [Pat Id] remove_dups [] = [] remove_dups (x:xs) | any (\y -> compare_cons x y) xs = remove_dups xs | otherwise = x : remove_dups xs get_used_cons :: [(EqnNo, EquationInfo)] -> [Pat Id] get_used_cons qs = remove_dups [pat | q <- qs, let pat = firstPatN q, isConPatOut pat] isConPatOut :: Pat Id -> Bool isConPatOut ConPatOut{ pat_con = L _ RealDataCon{} } = True isConPatOut _ = False remove_dups' :: [HsLit] -> [HsLit] remove_dups' [] = [] remove_dups' (x:xs) | x `elem` xs = remove_dups' xs | otherwise = x : remove_dups' xs get_used_lits :: [(EqnNo, EquationInfo)] -> [HsLit] get_used_lits qs = remove_dups' all_literals where all_literals = get_used_lits' qs get_used_lits' :: [(EqnNo, EquationInfo)] -> [HsLit] get_used_lits' [] = [] get_used_lits' (q:qs) | Just lit <- get_lit (firstPatN q) = lit : get_used_lits' qs | otherwise = get_used_lits qs get_lit :: Pat id -> Maybe HsLit -- Get a representative HsLit to stand for the OverLit -- It doesn't matter which one, because they will only be compared -- with other HsLits gotten in the same way get_lit (LitPat lit) = Just lit get_lit (NPat (L _ (OverLit { ol_val = HsIntegral src i})) mb _) = Just (HsIntPrim src (mb_neg negate mb i)) get_lit (NPat (L _ (OverLit { ol_val = HsFractional f })) mb _) = Just (HsFloatPrim (mb_neg negateFractionalLit mb f)) get_lit (NPat (L _ (OverLit { ol_val = HsIsString src s })) _ _) = Just (HsStringPrim src (fastStringToByteString s)) get_lit _ = Nothing mb_neg :: (a -> a) -> Maybe b -> a -> a mb_neg _ Nothing v = v mb_neg negate (Just _) v = negate v get_unused_cons :: [Pat Id] -> [DataCon] get_unused_cons used_cons = ASSERT( not (null used_cons) ) unused_cons where used_set :: UniqSet DataCon used_set = mkUniqSet [d | ConPatOut{ pat_con = L _ (RealDataCon d) } <- used_cons] (ConPatOut { pat_con = L _ (RealDataCon con1), pat_arg_tys = inst_tys }) = head used_cons ty_con = dataConTyCon con1 unused_cons = filterOut is_used (tyConDataCons ty_con) is_used con = con `elementOfUniqSet` used_set || dataConCannotMatch inst_tys con all_vars :: [Pat Id] -> Bool all_vars [] = True all_vars (WildPat _:ps) = all_vars ps all_vars _ = False remove_var :: (EqnNo, EquationInfo) -> (EqnNo, EquationInfo) remove_var (n, eqn@(EqnInfo { eqn_pats = WildPat _ : ps})) = (n, eqn { eqn_pats = ps }) remove_var _ = panic "Check.remove_var: equation does not begin with a variable" ----------------------- eqnPats :: (EqnNo, EquationInfo) -> [Pat Id] eqnPats (_, eqn) = eqn_pats eqn okGroup :: [(EqnNo, EquationInfo)] -> Bool -- True if all equations have at least one pattern, and -- all have the same number of patterns okGroup [] = True okGroup (e:es) = n_pats > 0 && and [length (eqnPats e) == n_pats | e <- es] where n_pats = length (eqnPats e) -- Half-baked print pprGroup :: [(EqnNo, EquationInfo)] -> SDoc pprEqnInfo :: (EqnNo, EquationInfo) -> SDoc pprGroup es = vcat (map pprEqnInfo es) pprEqnInfo e = ppr (eqnPats e) firstPatN :: (EqnNo, EquationInfo) -> Pat Id firstPatN (_, eqn) = firstPat eqn is_con :: Pat Id -> Bool is_con (ConPatOut {}) = True is_con _ = False is_lit :: Pat Id -> Bool is_lit (LitPat _) = True is_lit (NPat _ _ _) = True is_lit _ = False is_var :: Pat Id -> Bool is_var (WildPat _) = True is_var _ = False is_var_con :: ConLike -> Pat Id -> Bool is_var_con _ (WildPat _) = True is_var_con con (ConPatOut{ pat_con = L _ id }) = id == con is_var_con _ _ = False is_var_lit :: HsLit -> Pat Id -> Bool is_var_lit _ (WildPat _) = True is_var_lit lit pat | Just lit' <- get_lit pat = lit == lit' | otherwise = False {- The difference beteewn @make_con@ and @make_whole_con@ is that @make_wole_con@ creates a new constructor with all their arguments, and @make_con@ takes a list of argumntes, creates the contructor getting their arguments from the list. See where \fbox{\ ???\ } are used for details. We need to reconstruct the patterns (make the constructors infix and similar) at the same time that we create the constructors. You can tell tuple constructors using \begin{verbatim} Id.isTupleDataCon \end{verbatim} You can see if one constructor is infix with this clearer code :-)))))))))) \begin{verbatim} Lex.isLexConSym (Name.occNameString (Name.getOccName con)) \end{verbatim} Rather clumsy but it works. (Simon Peyton Jones) We don't mind the @nilDataCon@ because it doesn't change the way to print the message, we are searching only for things like: @[1,2,3]@, not @x:xs@ .... In @reconstruct_pat@ we want to ``undo'' the work that we have done in @tidy_pat@. In particular: \begin{tabular}{lll} @((,) x y)@ & returns to be & @(x, y)@ \\ @((:) x xs)@ & returns to be & @(x:xs)@ \\ @(x:(...:[])@ & returns to be & @[x,...]@ \end{tabular} The difficult case is the third one becouse we need to follow all the contructors until the @[]@ to know that we need to use the second case, not the second. \fbox{\ ???\ } -} isInfixCon :: DataCon -> Bool isInfixCon con = isDataSymOcc (getOccName con) is_nil :: Pat Name -> Bool is_nil (ConPatIn con (PrefixCon [])) = unLoc con == getName nilDataCon is_nil _ = False is_list :: Pat Name -> Bool is_list (ListPat _ _ Nothing) = True is_list _ = False return_list :: DataCon -> Pat Name -> Bool return_list id q = id == consDataCon && (is_nil q || is_list q) make_list :: LPat Name -> Pat Name -> Pat Name make_list p q | is_nil q = ListPat [p] placeHolderType Nothing make_list p (ListPat ps ty Nothing) = ListPat (p:ps) ty Nothing make_list _ _ = panic "Check.make_list: Invalid argument" make_con :: Pat Id -> ExhaustivePat -> ExhaustivePat make_con (ConPatOut{ pat_con = L _ (RealDataCon id) }) (lp:lq:ps, constraints) | return_list id q = (noLoc (make_list lp q) : ps, constraints) | isInfixCon id = (nlInfixConPat (getName id) lp lq : ps, constraints) where q = unLoc lq make_con (ConPatOut{ pat_con = L _ (RealDataCon id), pat_args = PrefixCon pats}) (ps, constraints) | isTupleTyCon tc = (noLoc (TuplePat pats_con (tupleTyConBoxity tc) []) : rest_pats, constraints) | isPArrFakeCon id = (noLoc (PArrPat pats_con placeHolderType) : rest_pats, constraints) | otherwise = (nlConPatName name pats_con : rest_pats, constraints) where name = getName id (pats_con, rest_pats) = splitAtList pats ps tc = dataConTyCon id make_con _ _ = panic "Check.make_con: Not ConPatOut" -- reconstruct parallel array pattern -- -- * don't check for the type only; we need to make sure that we are really -- dealing with one of the fake constructors and not with the real -- representation make_whole_con :: DataCon -> WarningPat make_whole_con con | isInfixCon con = nlInfixConPat name nlWildPatName nlWildPatName | otherwise = nlConPatName name pats where name = getName con pats = [nlWildPatName | _ <- dataConOrigArgTys con] {- ------------------------------------------------------------------------ Tidying equations ------------------------------------------------------------------------ tidy_eqn does more or less the same thing as @tidy@ in @Match.lhs@; that is, it removes syntactic sugar, reducing the number of cases that must be handled by the main checking algorithm. One difference is that here we can do *all* the tidying at once (recursively), rather than doing it incrementally. -} tidy_eqn :: EquationInfo -> EquationInfo tidy_eqn eqn = eqn { eqn_pats = map tidy_pat (eqn_pats eqn), eqn_rhs = tidy_rhs (eqn_rhs eqn) } where -- Horrible hack. The tidy_pat stuff converts "might-fail" patterns to -- WildPats which of course loses the info that they can fail to match. -- So we stick in a CanFail as if it were a guard. tidy_rhs (MatchResult can_fail body) | any might_fail_pat (eqn_pats eqn) = MatchResult CanFail body | otherwise = MatchResult can_fail body -------------- might_fail_pat :: Pat Id -> Bool -- Returns True of patterns that might fail (i.e. fall through) in a way -- that is not covered by the checking algorithm. Specifically: -- NPlusKPat -- ViewPat (if refutable) -- ConPatOut of a PatSynCon -- First the two special cases might_fail_pat (NPlusKPat {}) = True might_fail_pat (ViewPat _ p _) = not (isIrrefutableHsPat p) -- Now the recursive stuff might_fail_pat (ParPat p) = might_fail_lpat p might_fail_pat (AsPat _ p) = might_fail_lpat p might_fail_pat (SigPatOut p _ ) = might_fail_lpat p might_fail_pat (ListPat ps _ Nothing) = any might_fail_lpat ps might_fail_pat (ListPat _ _ (Just _)) = True might_fail_pat (TuplePat ps _ _) = any might_fail_lpat ps might_fail_pat (PArrPat ps _) = any might_fail_lpat ps might_fail_pat (BangPat p) = might_fail_lpat p might_fail_pat (ConPatOut { pat_con = con, pat_args = ps }) = case unLoc con of RealDataCon _dcon -> any might_fail_lpat (hsConPatArgs ps) PatSynCon _psyn -> True -- Finally the ones that are sure to succeed, or which are covered by the checking algorithm might_fail_pat (LazyPat _) = False -- Always succeeds might_fail_pat _ = False -- VarPat, WildPat, LitPat, NPat -------------- might_fail_lpat :: LPat Id -> Bool might_fail_lpat (L _ p) = might_fail_pat p -------------- tidy_lpat :: LPat Id -> LPat Id tidy_lpat p = fmap tidy_pat p -------------- tidy_pat :: Pat Id -> Pat Id tidy_pat pat@(WildPat _) = pat tidy_pat (VarPat id) = WildPat (idType id) tidy_pat (ParPat p) = tidy_pat (unLoc p) tidy_pat (LazyPat p) = WildPat (hsLPatType p) -- For overlap and exhaustiveness checking -- purposes, a ~pat is like a wildcard tidy_pat (BangPat p) = tidy_pat (unLoc p) tidy_pat (AsPat _ p) = tidy_pat (unLoc p) tidy_pat (SigPatOut p _) = tidy_pat (unLoc p) tidy_pat (CoPat _ pat _) = tidy_pat pat -- These two are might_fail patterns, so we map them to -- WildPats. The might_fail_pat stuff arranges that the -- guard says "this equation might fall through". tidy_pat (NPlusKPat id _ _ _) = WildPat (idType (unLoc id)) tidy_pat (ViewPat _ _ ty) = WildPat ty tidy_pat (ListPat _ _ (Just (ty,_))) = WildPat ty tidy_pat (ConPatOut { pat_con = L _ (PatSynCon syn), pat_arg_tys = tys }) = WildPat (patSynInstResTy syn tys) tidy_pat pat@(ConPatOut { pat_con = L _ con, pat_args = ps }) = pat { pat_args = tidy_con con ps } tidy_pat (ListPat ps ty Nothing) = unLoc $ foldr (\ x y -> mkPrefixConPat consDataCon [x,y] [ty]) (mkNilPat ty) (map tidy_lpat ps) -- introduce fake parallel array constructors to be able to handle parallel -- arrays with the existing machinery for constructor pattern -- tidy_pat (PArrPat ps ty) = unLoc $ mkPrefixConPat (parrFakeCon (length ps)) (map tidy_lpat ps) [ty] tidy_pat (TuplePat ps boxity tys) = unLoc $ mkPrefixConPat (tupleCon (boxityNormalTupleSort boxity) arity) (map tidy_lpat ps) tys where arity = length ps tidy_pat (NPat (L _ lit) mb_neg eq) = tidyNPat tidy_lit_pat lit mb_neg eq tidy_pat (LitPat lit) = tidy_lit_pat lit tidy_pat (ConPatIn {}) = panic "Check.tidy_pat: ConPatIn" tidy_pat (SplicePat {}) = panic "Check.tidy_pat: SplicePat" tidy_pat (QuasiQuotePat {}) = panic "Check.tidy_pat: QuasiQuotePat" tidy_pat (SigPatIn {}) = panic "Check.tidy_pat: SigPatIn" tidy_lit_pat :: HsLit -> Pat Id -- Unpack string patterns fully, so we can see when they -- overlap with each other, or even explicit lists of Chars. tidy_lit_pat lit | HsString src s <- lit = unLoc $ foldr (\c pat -> mkPrefixConPat consDataCon [mkCharLitPat src c, pat] [charTy]) (mkPrefixConPat nilDataCon [] [charTy]) (unpackFS s) | otherwise = tidyLitPat lit ----------------- tidy_con :: ConLike -> HsConPatDetails Id -> HsConPatDetails Id tidy_con _ (PrefixCon ps) = PrefixCon (map tidy_lpat ps) tidy_con _ (InfixCon p1 p2) = PrefixCon [tidy_lpat p1, tidy_lpat p2] tidy_con con (RecCon (HsRecFields fs _)) | null fs = PrefixCon (replicate arity nlWildPatId) -- Special case for null patterns; maybe not a record at all | otherwise = PrefixCon (map (tidy_lpat.snd) all_pats) where arity = case con of RealDataCon dcon -> dataConSourceArity dcon PatSynCon psyn -> patSynArity psyn -- pad out all the missing fields with WildPats. field_pats = case con of RealDataCon dc -> map (\ f -> (f, nlWildPatId)) (dataConFieldLabels dc) PatSynCon{} -> panic "Check.tidy_con: pattern synonym with record syntax" all_pats = foldr (\(L _ (HsRecField id p _)) acc -> insertNm (getName (unLoc id)) p acc) field_pats fs insertNm nm p [] = [(nm,p)] insertNm nm p (x@(n,_):xs) | nm == n = (nm,p):xs | otherwise = x : insertNm nm p xs
pparkkin/eta
compiler/ETA/DeSugar/Check.hs
Haskell
bsd-3-clause
30,170
{-# LANGUAGE CPP #-} -- | -- Package configuration information: essentially the interface to Cabal, with -- some utilities -- -- (c) The University of Glasgow, 2004 -- module PackageConfig ( -- $package_naming -- * PackageId mkPackageId, packageConfigId, -- * The PackageConfig type: information about a package PackageConfig, InstalledPackageInfo_(..), display, Version(..), PackageIdentifier(..), defaultPackageConfig, packageConfigToInstalledPackageInfo, installedPackageInfoToPackageConfig ) where #include "HsVersions.h" import Distribution.InstalledPackageInfo import Distribution.ModuleName import Distribution.Package hiding (PackageId) import Distribution.Text import Distribution.Version import Maybes import Module -- ----------------------------------------------------------------------------- -- Our PackageConfig type is just InstalledPackageInfo from Cabal. Later we -- might need to extend it with some GHC-specific stuff, but for now it's fine. type PackageConfig = InstalledPackageInfo_ Module.ModuleName defaultPackageConfig :: PackageConfig defaultPackageConfig = emptyInstalledPackageInfo -- ----------------------------------------------------------------------------- -- PackageId (package names with versions) -- $package_naming -- #package_naming# -- Mostly the compiler deals in terms of 'PackageId's, which have the -- form @<pkg>-<version>@. You're expected to pass in the version for -- the @-package-name@ flag. However, for wired-in packages like @base@ -- & @rts@, we don't necessarily know what the version is, so these are -- handled specially; see #wired_in_packages#. -- | Turn a Cabal 'PackageIdentifier' into a GHC 'PackageId' mkPackageId :: PackageIdentifier -> PackageId mkPackageId = stringToPackageId . display -- | Get the GHC 'PackageId' right out of a Cabalish 'PackageConfig' packageConfigId :: PackageConfig -> PackageId packageConfigId = mkPackageId . sourcePackageId -- | Turn a 'PackageConfig', which contains GHC 'Module.ModuleName's into a Cabal specific -- 'InstalledPackageInfo' which contains Cabal 'Distribution.ModuleName.ModuleName's packageConfigToInstalledPackageInfo :: PackageConfig -> InstalledPackageInfo packageConfigToInstalledPackageInfo (pkgconf@(InstalledPackageInfo { exposedModules = e, hiddenModules = h })) = pkgconf{ exposedModules = map convert e, hiddenModules = map convert h } where convert :: Module.ModuleName -> Distribution.ModuleName.ModuleName convert = (expectJust "packageConfigToInstalledPackageInfo") . simpleParse . moduleNameString -- | Turn an 'InstalledPackageInfo', which contains Cabal 'Distribution.ModuleName.ModuleName's -- into a GHC specific 'PackageConfig' which contains GHC 'Module.ModuleName's installedPackageInfoToPackageConfig :: InstalledPackageInfo_ String -> PackageConfig installedPackageInfoToPackageConfig (pkgconf@(InstalledPackageInfo { exposedModules = e, hiddenModules = h })) = pkgconf{ exposedModules = map mkModuleName e, hiddenModules = map mkModuleName h }
frantisekfarka/ghc-dsi
compiler/main/PackageConfig.hs
Haskell
bsd-3-clause
3,235
module A1 where import D1 sumSq xs ys= sum (map sq xs) + sumSquares xs ys main = sumSq [1..4]
kmate/HaRe
old/testing/rmOneParameter/A1.hs
Haskell
bsd-3-clause
99
{-# LANGUAGE TypeFamilyDependencies #-} module T6018Bfail where import Data.Kind (Type) type family H a b c = (result :: Type) | result -> a b c
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T6018Bfail.hs
Haskell
bsd-3-clause
148
import GHC.Conc main :: IO () main = setNumCapabilities 0
ezyang/ghc
testsuite/tests/rts/T13832.hs
Haskell
bsd-3-clause
59
{-# LANGUAGE FlexibleContexts #-} -- | Implementation of Kahan summation algorithm that tests -- performance of tight loops involving unboxed arrays and floating -- point arithmetic. module Main (main) where import Control.Monad.ST import Data.Array.Base import Data.Array.ST import Data.Bits import Data.Word import System.Environment vdim :: Int vdim = 100 prng :: Word -> Word prng w = w' where w1 = w `xor` (w `shiftL` 13) w2 = w1 `xor` (w1 `shiftR` 7) w' = w2 `xor` (w2 `shiftL` 17) type Vec s = STUArray s Int Double kahan :: Int -> Vec s -> Vec s -> ST s () kahan vnum s c = do let inner w j | j < vdim = do cj <- unsafeRead c j sj <- unsafeRead s j let y = fromIntegral w - cj t = sj + y w' = prng w unsafeWrite c j ((t-sj)-y) unsafeWrite s j t inner w' (j+1) | otherwise = return () outer i | i <= vnum = inner (fromIntegral i) 0 >> outer (i+1) | otherwise = return () outer 1 calc :: Int -> ST s (Vec s) calc vnum = do s <- newArray (0,vdim-1) 0 c <- newArray (0,vdim-1) 0 kahan vnum s c return s main :: IO () main = do [arg] <- getArgs print . elems $ runSTUArray $ calc $ read arg
k-bx/ghcjs
test/nofib/imaginary/kahan/Main.hs
Haskell
mit
1,334
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeFamilyDependencies #-} module T13271 where import GHC.TypeLits data T1 = T1 type T2 = TypeError (Text "You can't do that!") type family X i = r | r -> i where X 1 = T1 X 2 = T2
shlevy/ghc
testsuite/tests/indexed-types/should_fail/T13271.hs
Haskell
bsd-3-clause
229
{-# LANGUAGE TemplateHaskell #-} module Main where import Data.Maybe (Maybe(..)) import Data.Ord (Ord) import Language.Haskell.TH (mkName, nameSpace) main :: IO () main = mapM_ (print . nameSpace) [ 'Prelude.id , mkName "id" , 'Data.Maybe.Just , ''Data.Maybe.Maybe , ''Data.Ord.Ord ]
ezyang/ghc
testsuite/tests/th/TH_nameSpace.hs
Haskell
bsd-3-clause
364
main = interact wordCount where wordCount input = show (length input) ++ "\n"
akampjes/learning-realworldhaskell
ch01/WC.hs
Haskell
mit
80
{-# Language GADTs #-} module Unison.Runtime.Vector where import Unison.Prelude import qualified Data.MemoCombinators as Memo import qualified Data.Vector.Unboxed as UV -- A `Vec a` denotes a `Nat -> Maybe a` data Vec a where Scalar :: a -> Vec a Vec :: UV.Unbox a => UV.Vector a -> Vec a Pair :: Vec a -> Vec b -> Vec (a, b) Choose :: Vec Bool -> Vec a -> Vec a -> Vec a Mux :: Vec Nat -> Vec (Vec a) -> Vec a -- todo: maybe make representation `(UV.Vector Nat -> UnboxedMap Nat a, Bound)` -- `UnboxedMap Nat a = (UV.Vector Nat, UV.Vector a)` -- UnboxedMap Nat could be implemented as an `UArray` -- `Bound` is Nat, max possible index -- then easy to implement `+`, `-`, etc type Nat = Word64 mu :: Vec a -> Nat -> Maybe a mu v = case v of Scalar a -> const (Just a) Vec vs -> \i -> vs UV.!? fromIntegral i Choose cond t f -> let (condr, tr, tf) = (mu cond, mu t, mu f) in \i -> condr i >>= \b -> if b then tr i else tf i Mux mux branches -> let muxr = mu mux branchesr = Memo.integral $ let f = mu branches in \i -> mu <$> f i in \i -> do j <- muxr i; b <- branchesr j; b i Pair v1 v2 -> let (v1r, v2r) = (mu v1, mu v2) in \i -> liftA2 (,) (v1r i) (v2r i) -- Returns the maximum `Nat` for which `mu v` may return `Just`. bound :: Nat -> Vec a -> Nat bound width v = case v of Scalar _ -> width Vec vs -> fromIntegral $ UV.length vs Pair v1 v2 -> bound width v1 `min` bound width v2 Choose cond _ _ -> bound width cond Mux mux _ -> bound width mux toList :: Vec a -> [a] toList v = let n = bound maxBound v muv = mu v in catMaybes $ muv <$> [0..n]
unisonweb/platform
parser-typechecker/src/Unison/Runtime/Vector.hs
Haskell
mit
1,622
import Control.Monad import Test.QuickCheck import Test.QuickCheck.Checkers import Test.QuickCheck.Classes bind :: Monad m => (a -> m b) -> m a -> m b bind f n = join $ fmap f n data Nope a = NopeDotJpg deriving (Show, Eq) instance Functor Nope where fmap f a = NopeDotJpg instance Applicative Nope where pure a = NopeDotJpg f <*> g = NopeDotJpg instance Monad Nope where return a = NopeDotJpg f >>= g = NopeDotJpg instance Arbitrary (Nope a) where arbitrary = elements [ NopeDotJpg ] instance Eq a => EqProp (Nope a) where (=-=) = eq main :: IO() main = let trigger = undefined :: Nope (Int, Int, Int) in quickBatch $ monad trigger data PhhhbbtttEither b a = Lefty a | Righty b deriving (Eq, Show) instance Functor (PhhhbbtttEither b) where fmap f (Lefty a) = Lefty (f a) fmap f (Righty b) = Righty b instance Applicative (PhhhbbtttEither b) where pure a = Lefty a _ <*> Righty b = Righty b Righty b <*> _ = Righty b Lefty f <*> Lefty a = Lefty (f a) instance Monad (PhhhbbtttEither b) where return a = Lefty a Lefty a >>= f = f a Righty b >>= _ = Righty b instance (Arbitrary a, Arbitrary b) => Arbitrary (PhhhbbtttEither b a) where arbitrary = do a <- arbitrary b <- arbitrary elements [Lefty a, Righty b] instance (Eq a, Eq b) => EqProp (PhhhbbtttEither a b) where (=-=) = eq main2 :: IO() main2 = let trigger = undefined :: PhhhbbtttEither Int (Int, Int, Int) in quickBatch $ monad trigger newtype Identity a = Identity a deriving (Eq, Ord, Show) instance Functor Identity where fmap f (Identity a) = Identity (f a) instance Applicative Identity where pure = Identity Identity f <*> Identity a = Identity (f a) instance Monad Identity where return = pure Identity a >>= f = f a instance (Arbitrary a) => Arbitrary (Identity a) where arbitrary = do a <- arbitrary return (Identity a) instance (Eq a) => EqProp (Identity a) where (=-=) = eq main3 :: IO() main3 = let trigger = undefined :: Identity (Int, Int, Int) in quickBatch $ monad trigger data List a = Nil | Cons a (List a) deriving (Eq, Show) instance Functor List where fmap f Nil = Nil fmap f (Cons a b) = Cons (f a) (fmap f b) instance Applicative List where pure a = Cons a Nil Nil <*> _ = Nil _ <*> Nil = Nil Cons f g <*> a = append (fmap f a) (g <*> a) instance Monad List where return = pure a >>= f = flatMap f a -- from ch17 append :: List a -> List a -> List a append Nil ys = ys append (Cons x xs) ys = Cons x $ xs `append` ys fold :: ( a -> b -> b) -> b -> List a -> b fold _ b Nil = b fold f b (Cons h t) = f h (fold f b t) concat' :: List (List a) -> List a concat' = fold append Nil -- write this one in terms of concat' and fmap flatMap :: (a -> List b) -> List a -> List b flatMap f as = concat' (fmap f as) instance (Arbitrary a) => Arbitrary (List a) where arbitrary = do a <- arbitrary b <- arbitrary frequency [ (1, return Nil) , (2, return (Cons a b)) ] instance Eq a => EqProp (List a) where (=-=) = eq main4 :: IO() main4 = let trigger = undefined :: List (Int, Int, Int) in quickBatch $ monad trigger j :: Monad m => m (m a) -> m a j = join l1 :: Monad m => (a -> b) -> m a -> m b l1 = (<$>) l2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c l2 = liftM2 a :: Monad m => m a -> m (a -> b) -> m b a = flip (<*>) meh :: Monad m => [a] -> (a -> m b) -> m [b] meh l f = let g = map f l in sequence g meh2 :: Monad m => [a] -> (a -> m b) -> m [b] meh2 [] _ = pure [] meh2 (x:xs) f = do y <- f x z <- meh2 xs f pure (y : z) meh3 :: Monad m => [a] -> (a -> m b) -> m [b] meh3 [] _ = pure [] meh3 (x:xs) f = f x >>= \y -> (meh3 xs f) >>= \z -> return (y:z) flipType :: (Monad m) => [m a] -> m [a] flipType = sequence flipType2 :: (Monad m) => [m a] -> m [a] flipType2 k = meh k id
mitochon/hexercise
src/haskellbook/ch18/ch18.hs
Haskell
mit
3,911
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE ScopedTypeVariables #-} module Database.Esqueleto.TextSearchSpec (main, spec) where import Control.Monad (forM_) import Data.Text (Text, pack) import Control.Monad.IO.Class (MonadIO(liftIO)) import Control.Monad.Logger (MonadLogger(..), runStderrLoggingT) import Control.Monad.Trans.Resource ( MonadBaseControl, MonadThrow, ResourceT, runResourceT) import Database.Esqueleto ( SqlExpr, Value(..), unValue, update, select, set, val, from, where_ , (=.), (^.)) import Database.Persist (entityKey, insert, get, PersistField(..)) import Database.Persist.Postgresql ( SqlPersistT, ConnectionString, runSqlConn, transactionUndo , withPostgresqlConn, runMigration) import Database.Persist.TH ( mkPersist, mkMigrate, persistUpperCase, share, sqlSettings) import Test.Hspec (Spec, hspec, describe, it, shouldBe) import Test.QuickCheck ( Arbitrary(..), property, elements, oneof, listOf, listOf1, choose) import Database.Esqueleto.TextSearch connString :: ConnectionString connString = "host=localhost port=5432 user=test dbname=test password=test" -- Test schema share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistUpperCase| Article title Text content Text textsearch TsVector deriving Eq Show WeightsModel weights Weights deriving Eq Show WeightModel weight Weight deriving Eq Show RegConfigModel config RegConfig deriving Eq Show QueryModel query (TsQuery Lexemes) deriving Eq Show |] main :: IO () main = hspec spec to_etsvector :: SqlExpr (Value Text) -> SqlExpr (Value TsVector) to_etsvector = to_tsvector (val "english") spec :: Spec spec = do describe "TsVector" $ do it "can be persisted and retrieved" $ run $ do let article = Article "some title" "some content" def arId <- insert article update $ \a -> do set a [ArticleTextsearch =. to_etsvector (a^.ArticleContent)] Just ret <- get arId liftIO $ articleTextsearch ret /= def `shouldBe` True it "can be persisted and retrieved with weight" $ run $ do let article = Article "some title" "some content" def arId <- insert article update $ \a -> do set a [ ArticleTextsearch =. setweight (to_etsvector (a^.ArticleContent)) (val Highest) ] Just ret <- get arId liftIO $ articleTextsearch ret /= def `shouldBe` True describe "Weight" $ do it "can be persisted and retrieved" $ run $ do forM_ [Low, Medium, High, Highest] $ \w -> do let m = WeightModel w wId <- insert m ret <- get wId liftIO $ ret `shouldBe` Just m describe "Weights" $ do it "can be persisted and retrieved" $ run $ do let m = WeightsModel $ Weights 0.5 0.6 0.7 0.8 wsId <- insert m ret <- get wsId liftIO $ ret `shouldBe` Just m describe "RegConfig" $ do it "can be persisted and retrieved" $ run $ do forM_ ["english", "spanish"] $ \c -> do let m = RegConfigModel c wId <- insert m ret <- get wId liftIO $ ret `shouldBe` Just m describe "TsQuery" $ do it "can be persisted and retrieved" $ run $ do let qm = QueryModel (lexm "foo" :& lexm "bar") qId <- insert qm Just ret <- get qId liftIO $ qm `shouldBe` ret describe "to_tsquery" $ do it "converts words to lexemes" $ run $ do [Value lq ] <- select $ return $ to_tsquery (val "english") (val ("supernovae" :& "rats")) liftIO $ lq `shouldBe` (lexm "supernova" :& lexm "rat") describe "plainto_tsquery" $ do it "converts text to lexemes" $ run $ do [Value lq ] <- select $ return $ plainto_tsquery (val "english") (val "rats in supernovae") liftIO $ lq `shouldBe` (lexm "rat" :& lexm "supernova") describe "queryToText" $ do it "can serialize infix lexeme" $ queryToText (lexm "foo") `shouldBe` "'foo'" it "can serialize infix lexeme with weights" $ queryToText (Lexeme Infix [Highest,Low] "foo") `shouldBe` "'foo':AD" it "can serialize prefix lexeme" $ queryToText (Lexeme Prefix [] "foo") `shouldBe` "'foo':*" it "can serialize prefix lexeme with weights" $ queryToText (Lexeme Prefix [Highest,Low] "foo") `shouldBe` "'foo':*AD" it "can serialize AND" $ queryToText ("foo" :& "bar" :& "car") `shouldBe` "'foo'&('bar'&'car')" it "can serialize OR" $ queryToText ("foo" :| "bar") `shouldBe` "'foo'|'bar'" it "can serialize Not" $ queryToText (Not "bar") `shouldBe` "!'bar'" describe "textToQuery" $ do describe "infix lexeme" $ do it "can parse it" $ textToQuery "'foo'" `shouldBe` Right (lexm "foo") it "can parse it surrounded by spaces" $ textToQuery " 'foo' " `shouldBe` Right (lexm "foo") describe "infix lexeme with weights" $ do it "can parse it" $ textToQuery "'foo':AB" `shouldBe` Right (Lexeme Infix [Highest,High] "foo") it "can parse it surrounded by spaces" $ textToQuery " 'foo':AB " `shouldBe` Right (Lexeme Infix [Highest,High] "foo") describe "prefix lexeme" $ do it "can parse it" $ textToQuery "'foo':*" `shouldBe` Right (Lexeme Prefix [] "foo") it "can parse it surrounded byb spaces" $ textToQuery " 'foo':* " `shouldBe` Right (Lexeme Prefix [] "foo") describe "prefix lexeme with weights" $ do it "can parse it" $ textToQuery "'foo':*AB" `shouldBe` Right (Lexeme Prefix [Highest,High] "foo") it "can parse it surrounded by spaces" $ textToQuery " 'foo':*AB " `shouldBe` Right (Lexeme Prefix [Highest,High] "foo") describe "&" $ do it "can parse it" $ textToQuery "'foo'&'bar'" `shouldBe` Right (lexm "foo" :& lexm "bar") it "can parse it surrounded by spaces" $ do textToQuery "'foo' & 'bar'" `shouldBe` Right (lexm "foo" :& lexm "bar") textToQuery "'foo'& 'bar'" `shouldBe` Right (lexm "foo" :& lexm "bar") textToQuery "'foo' &'bar'" `shouldBe` Right (lexm "foo" :& lexm "bar") textToQuery " 'foo'&'bar' " `shouldBe` Right (lexm "foo" :& lexm "bar") it "can parse several" $ textToQuery "'foo'&'bar'&'car'" `shouldBe` Right (lexm "foo" :& lexm "bar" :& lexm "car") describe "|" $ do it "can parse it" $ textToQuery "'foo'|'bar'" `shouldBe` Right (lexm "foo" :| lexm "bar") it "can parse several" $ textToQuery "'foo'|'bar'|'car'" `shouldBe` Right (lexm "foo" :| lexm "bar" :| lexm "car") describe "mixed |s and &s" $ do it "respects precedence" $ do textToQuery "'foo'|'bar'&'car'" `shouldBe` Right (lexm "foo" :| lexm "bar" :& lexm "car") textToQuery "'foo'&'bar'|'car'" `shouldBe` Right (lexm "foo" :& lexm "bar" :| lexm "car") describe "!" $ do it "can parse it" $ textToQuery "!'foo'" `shouldBe` Right (Not (lexm "foo")) describe "! and &" $ do it "can parse it" $ do textToQuery "!'foo'&'car'" `shouldBe` Right (Not (lexm "foo") :& lexm "car") textToQuery "!('foo'&'car')" `shouldBe` Right (Not (lexm "foo" :& lexm "car")) it "can parse it surrounded by spaces" $ do textToQuery "!'foo' & 'car'" `shouldBe` Right (Not (lexm "foo") :& lexm "car") textToQuery "!( 'foo' & 'car' )" `shouldBe` Right (Not (lexm "foo" :& lexm "car")) describe "textToQuery . queryToText" $ do it "is isomorphism" $ property $ \q -> (textToQuery . queryToText) q `shouldBe` Right q describe "@@" $ do it "works as expected" $ run $ do let article = Article "some title" "some content" def arId <- insert article update $ \a -> do set a [ArticleTextsearch =. to_etsvector (a^.ArticleContent)] let query = to_tsquery (val "english") (val "content") result <- select $ from $ \a -> do where_ $ (a^. ArticleTextsearch) @@. query return a liftIO $ do length result `shouldBe` 1 map entityKey result `shouldBe` [arId] let query2 = to_tsquery (val "english") (val "foo") result2 <- select $ from $ \a -> do where_ $ (a^. ArticleTextsearch) @@. query2 return a liftIO $ length result2 `shouldBe` 0 describe "ts_rank_cd" $ do it "works as expected" $ run $ do let vector = to_tsvector (val "english") (val content) content = "content" :: Text query = to_tsquery (val "english") (val "content") norm = val [] ret <- select $ return $ ts_rank_cd (val def) vector query norm liftIO $ map unValue ret `shouldBe` [0.1] describe "ts_rank" $ do it "works as expected" $ run $ do let vector = to_tsvector (val "english") (val content) content = "content" :: Text query = to_tsquery (val "english") (val "content") norm = val [] ret <- select $ return $ ts_rank (val def) vector query norm liftIO $ map unValue ret `shouldBe` [6.07927e-2] describe "NormalizationOption" $ do describe "fromPersistValue . toPersistValue" $ do let isEqual [] [] = True isEqual [NormNone] [] = True isEqual [] [NormNone] = True isEqual a b = a == b toRight (Right a) = a toRight _ = error "unexpected Left" it "is isomorphism" $ property $ \(q :: [NormalizationOption]) -> isEqual ((toRight . fromPersistValue . toPersistValue) q) q `shouldBe` True instance Arbitrary ([NormalizationOption]) where arbitrary = (:[]) <$> elements [minBound..maxBound] instance a ~ Lexemes => Arbitrary (TsQuery a) where arbitrary = query 0 where maxDepth :: Int maxDepth = 10 query d | d<maxDepth = oneof [lexeme, and_ d, or_ d, not_ d] | otherwise = lexeme lexeme = Lexeme <$> arbitrary <*> weights <*> lexString weights = listOf arbitrary and_ d = (:&) <$> query (d+1) <*> query (d+1) or_ d = (:|) <$> query (d+1) <*> query (d+1) not_ d = Not <$> query (d+1) lexString = pack <$> listOf1 (oneof $ [ choose ('a','z') , choose ('A','Z') , choose ('0','9') ] ++ map pure "-_&|ñçáéíóú") instance Arbitrary Position where arbitrary = oneof [pure Infix, pure Prefix] instance Arbitrary Weight where arbitrary = oneof [pure Highest, pure High, pure Medium, pure Low] lexm :: Text -> TsQuery Lexemes lexm = Lexeme Infix [] type RunDbMonad m = (MonadBaseControl IO m, MonadIO m, MonadLogger m, MonadThrow m) run :: (forall m. RunDbMonad m => SqlPersistT (ResourceT m) a) -> IO a run act = runStderrLoggingT . runResourceT . withPostgresqlConn connString . runSqlConn $ (initializeDB >> act >>= \ret -> transactionUndo >> return ret) initializeDB :: (forall m. RunDbMonad m => SqlPersistT (ResourceT m) ()) initializeDB = do runMigration migrateAll
albertov/esqueleto-textsearch
test/Database/Esqueleto/TextSearchSpec.hs
Haskell
mit
11,840
{- ghci c:\Users\Thomas\Documents\GitHub\practice\pe\nonvisualstudio\haskell\Spec\Problem0002.Spec.hs c:\Users\Thomas\Documents\GitHub\practice\pe\nonvisualstudio\haskell\Implementation\Problem0002.hs -} -- :r :q :set +s for times module Problem0002Tests where import Test.HUnit import System.IO import Problem0002 testCases = TestList [ TestCase $ assertEqual "sumOfEvenFibonacciesLessThan 100 should return 44" 44 (sumOfEvenFibonacciesLessThan 100), TestCase $ assertEqual "sumOfEvenFibonacciesLessThan 4000000 should return 44" 4613732 (sumOfEvenFibonacciesLessThan 4000000) ] tests = runTestTT testCases
Sobieck00/practice
pe/nonvisualstudio/haskell/OldWork/Spec/Problem0002.Spec.hs
Haskell
mit
644
{-# OPTIONS #-} -- ------------------------------------------------------------ module Holumbus.Crawler.XmlArrows where import Text.XML.HXT.Core -- ------------------------------------------------------------ -- | Remove contents, when document status isn't ok, but remain meta info checkDocumentStatus :: IOSArrow XmlTree XmlTree checkDocumentStatus = replaceChildren none `whenNot` documentStatusOk -- ------------------------------------------------------------
ichistmeinname/holumbus
src/Holumbus/Crawler/XmlArrows.hs
Haskell
mit
578
{-| Module : Control.Monad.Bayes.LogDomain Description : Numeric types representing numbers using their logarithms Copyright : (c) Adam Scibior, 2016 License : MIT Maintainer : ams240@cam.ac.uk Stability : experimental Portability : GHC -} -- Log-domain non-negative real numbers -- Essentially a polymorphic version of LogFloat to allow for AD module Control.Monad.Bayes.LogDomain where import qualified Numeric.SpecFunctions as Spec import Data.Reflection import Numeric.AD.Mode.Reverse import Numeric.AD.Internal.Reverse import Numeric.AD.Internal.Identity import Numeric.AD.Jacobian -- | Log-domain non-negative real numbers. -- Used to prevent underflow when computing small probabilities. newtype LogDomain a = LogDomain a deriving (Eq, Ord) -- | Convert to log-domain. toLogDomain :: Floating a => a -> LogDomain a toLogDomain = fromLog . log -- | Inverse of `toLogDomain`. -- -- > toLogDomain . fromLogDomain = id -- > fromLogDomain . toLogDomain = id fromLogDomain :: Floating a => LogDomain a -> a fromLogDomain = exp . toLog -- | Apply a function to a log-domain value by first exponentiating, -- then applying the function, then taking the logarithm. -- -- > mapLog f = toLogDomain . f . fromLogDomain mapLog :: (Floating a, Floating b) => (a -> b) -> LogDomain a -> LogDomain b mapLog f = toLogDomain . f . fromLogDomain -- | A raw representation of a logarithm. -- -- > toLog = log . fromLogDomain toLog :: LogDomain a -> a toLog (LogDomain x) = x -- | Inverse of `toLog`. -- -- > fromLog = toLogDomain . exp fromLog :: a -> LogDomain a fromLog = LogDomain -- | Apply a function to a logarithm. -- -- > liftLog f = fromLog . f . toLog liftLog :: (a -> b) -> LogDomain a -> LogDomain b liftLog f = fromLog . f . toLog -- | Apply a function of two arguments to two logarithms. -- -- > liftLog2 f x y = fromLog $ f (toLog x) (toLog y) liftLog2 :: (a -> b -> c) -> LogDomain a -> LogDomain b -> LogDomain c liftLog2 f x y = fromLog $ f (toLog x) (toLog y) instance Show a => Show (LogDomain a) where show = show . toLog instance (Ord a, Floating a) => Num (LogDomain a) where x + y = if y > x then y + x else fromLog (toLog x + log (1 + exp (toLog y - toLog x))) x - y = if x >= y then fromLog (toLog x + log (1 - exp (toLog y - toLog x))) else error "LogDomain: subtraction resulted in a negative value" (*) = liftLog2 (+) negate _ = error "LogDomain does not support negation" abs = id signum x = if toLog x == -1/0 then 0 else 1 fromInteger = toLogDomain . fromInteger instance (Real a, Floating a) => Real (LogDomain a) where toRational = toRational . fromLogDomain instance (Ord a, Floating a) => Fractional (LogDomain a) where (/) = liftLog2 (-) recip = liftLog negate fromRational = toLogDomain . fromRational instance (Ord a, Floating a) => Floating (LogDomain a) where pi = toLogDomain pi exp = liftLog exp log = liftLog log sqrt = liftLog (/ 2) x ** y = liftLog (* fromLogDomain y) x logBase x y = log y / log x sin = mapLog sin cos = mapLog cos tan = mapLog tan asin = mapLog asin acos = mapLog acos atan = mapLog atan sinh = mapLog sinh cosh = mapLog cosh tanh = mapLog tanh asinh = mapLog asinh acosh = mapLog acosh atanh = mapLog atanh -- | A class for numeric types that provide certain special functions. class Floating a => NumSpec a where {-# MINIMAL (gamma | logGamma) , (beta | logBeta) #-} -- | Gamma function. gamma :: a -> a gamma = exp . logGamma -- | Beta function. beta :: a -> a -> a beta a b = exp $ logBeta a b -- | Logarithm of `gamma`. -- -- > logGamma = log . gamma logGamma :: a -> a logGamma = log . gamma -- | Logarithm of `beta` -- -- > logBeta a b = log (beta a b) logBeta :: a -> a -> a logBeta a b = log $ beta a b instance NumSpec Double where logGamma = Spec.logGamma logBeta = Spec.logBeta instance (Ord a, NumSpec a) => NumSpec (LogDomain a) where gamma = liftLog (logGamma . exp) beta a b = liftLog2 (\x y -> logBeta (exp x) (exp y)) a b ------------------------------------------------- -- Automatic Differentiation instances instance (Reifies s Tape) => NumSpec (Reverse s Double) where logGamma = lift1 logGamma (Id . Spec.digamma . runId) logBeta = lift2 logBeta (\(Id x) (Id y) -> (Id (psi x - psi (x+y)), Id (psi y - psi (x+y)))) where psi = Spec.digamma
ocramz/monad-bayes
src/Control/Monad/Bayes/LogDomain.hs
Haskell
mit
4,423
module Frontend.Values where import Frontend.Types import Internal data Value = IntValue Int | FloatValue Float | BoolValue Bool | UnitValue deriving Eq instance Show Value where show (IntValue i) = show i show (FloatValue f) = show f show (BoolValue True) = "true" show (BoolValue False) = "false" show UnitValue = "()" typeOfValue :: Value -> Type typeOfValue (IntValue _) = IntType typeOfValue (FloatValue _) = FloatType typeOfValue (BoolValue _) = BoolType typeOfValue UnitValue = UnitType
alpicola/mel
src/Frontend/Values.hs
Haskell
mit
553
data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show) data Direction = L | R deriving (Show) type Directions = [ Direction ] freeTree :: Tree Char freeTree = Node 'P' (Node 'O' (Node 'L' (Node 'N' Empty Empty) (Node 'T' Empty Empty) ) (Node 'Y' (Node 'S' Empty Empty) (Node 'A' Empty Empty) ) ) (Node 'L' (Node 'W' (Node 'C' Empty Empty) (Node 'R' Empty Empty) ) (Node 'A' (Node 'A' Empty Empty) (Node 'C' Empty Empty) ) ) data Crumb a = LeftCrumb a (Tree a) | RightCrumb a (Tree a) deriving (Show) type Breadcrumbs a = [ Crumb a ] type Zipper a = (Tree a, Breadcrumbs a) goLeft :: Zipper a -> Maybe (Zipper a) goLeft (Node x l r, bs) = Just (l, LeftCrumb x r:bs) goLeft (Empty, _) = Nothing goRight :: Zipper a -> Maybe (Zipper a) goRight (Node x l r, bs) = Just (r, RightCrumb x l:bs) goRight (Empty, _) = Nothing goUp :: Zipper a -> Maybe (Zipper a) goUp (t, LeftCrumb x r:bs) = Just (Node x t r, bs) goUp (t, RightCrumb x l:bs) = Just (Node x l t, bs) goUp (_, []) = Nothing moveAround = return (freeTree, []) >>= goLeft >= goRight
afronski/playground-fp
books/learn-you-a-haskell-for-great-good/zippers/trees.hs
Haskell
mit
1,321
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE StandaloneDeriving #-} module Nanocoin.Network.Peer ( Peer(..), Peers, ) where import Protolude hiding (put, get) import Data.Aeson (ToJSON(..)) import Data.Binary (Binary, encode, decode) import Data.Serialize (Serialize(..)) import Control.Distributed.Process (ProcessId, NodeId) import Control.Distributed.Process.Serializable import Nanocoin.Network.Utils type Peers = Set Peer instance Serialize NodeId where put = put . encode get = decode <$> get newtype Peer = Peer { nid :: NodeId } deriving (Show, Eq, Ord, Generic, Binary, Typeable, Serializable, Serialize)
tdietert/nanocoin
src/Nanocoin/Network/Peer.hs
Haskell
apache-2.0
663
module Lycopene.Core.Record.Service where import Control.Monad.Trans (liftIO) import Data.Time.Clock (getCurrentTime) import Data.Time.LocalTime (utcToLocalTime, getCurrentTimeZone, LocalTime) import Lycopene.Core.Monad import Lycopene.Core.Database import qualified Lycopene.Core.Record as E newRecord :: Integer -> LocalTime -> Lycopene Integer newRecord i st = do et <- liftIO $ utcToLocalTime <$> getCurrentTimeZone <*> getCurrentTime let v = E.RecordV { E.vIssueId = i , E.vStartOn = st , E.vEndOn = Just et } runPersist $ insertP E.insertRecordV v history :: Integer -> Lycopene [E.Record] history i = runPersist $ relationP E.selectRecordByIssue i
utky/lycopene
src/Lycopene/Core/Record/Service.hs
Haskell
apache-2.0
714
module Handler.ToPostList where import Import import Data.List (sort) getToPostListR :: Handler RepHtml getToPostListR = do toposts <- liftIO getToPosts defaultLayout $ do setTitle "To post list" $(widgetFile "topost-list")
snoyberg/photosorter
Handler/ToPostList.hs
Haskell
bsd-2-clause
250
module Database.Narc.Common where type Tabname = String type Field = String
ezrakilty/narc
Database/Narc/Common.hs
Haskell
bsd-2-clause
79
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QLineEdit.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:25 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QLineEdit ( QqLineEdit(..) ,backspace ,QcursorBackward(..) ,QcursorForward(..) ,cursorPosition ,cursorPositionAt, qcursorPositionAt ,cursorWordBackward ,cursorWordForward ,del ,deselect ,displayText ,echoMode ,hasSelectedText ,inputMask ,insert ,maxLength ,setCursorPosition ,setEchoMode ,setInputMask ,setMaxLength ,qLineEdit_delete ,qLineEdit_deleteLater ) where import Foreign.C.Types import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QLineEdit import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui instance QuserMethod (QLineEdit ()) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QLineEdit_userMethod cobj_qobj (toCInt evid) foreign import ccall "qtc_QLineEdit_userMethod" qtc_QLineEdit_userMethod :: Ptr (TQLineEdit a) -> CInt -> IO () instance QuserMethod (QLineEditSc a) (()) (IO ()) where userMethod qobj evid () = withObjectPtr qobj $ \cobj_qobj -> qtc_QLineEdit_userMethod cobj_qobj (toCInt evid) instance QuserMethod (QLineEdit ()) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QLineEdit_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj foreign import ccall "qtc_QLineEdit_userMethodVariant" qtc_QLineEdit_userMethodVariant :: Ptr (TQLineEdit a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) instance QuserMethod (QLineEditSc a) (QVariant ()) (IO (QVariant ())) where userMethod qobj evid qvoj = withObjectRefResult $ withObjectPtr qobj $ \cobj_qobj -> withObjectPtr qvoj $ \cobj_qvoj -> qtc_QLineEdit_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj class QqLineEdit x1 where qLineEdit :: x1 -> IO (QLineEdit ()) instance QqLineEdit (()) where qLineEdit () = withQLineEditResult $ qtc_QLineEdit foreign import ccall "qtc_QLineEdit" qtc_QLineEdit :: IO (Ptr (TQLineEdit ())) instance QqLineEdit ((String)) where qLineEdit (x1) = withQLineEditResult $ withCWString x1 $ \cstr_x1 -> qtc_QLineEdit1 cstr_x1 foreign import ccall "qtc_QLineEdit1" qtc_QLineEdit1 :: CWString -> IO (Ptr (TQLineEdit ())) instance QqLineEdit ((QWidget t1)) where qLineEdit (x1) = withQLineEditResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit2 cobj_x1 foreign import ccall "qtc_QLineEdit2" qtc_QLineEdit2 :: Ptr (TQWidget t1) -> IO (Ptr (TQLineEdit ())) instance QqLineEdit ((String, QWidget t2)) where qLineEdit (x1, x2) = withQLineEditResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QLineEdit3 cstr_x1 cobj_x2 foreign import ccall "qtc_QLineEdit3" qtc_QLineEdit3 :: CWString -> Ptr (TQWidget t2) -> IO (Ptr (TQLineEdit ())) instance Qalignment (QLineEdit a) (()) where alignment x0 () = withQFlagsResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_alignment cobj_x0 foreign import ccall "qtc_QLineEdit_alignment" qtc_QLineEdit_alignment :: Ptr (TQLineEdit a) -> IO CLong backspace :: QLineEdit a -> (()) -> IO () backspace x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_backspace cobj_x0 foreign import ccall "qtc_QLineEdit_backspace" qtc_QLineEdit_backspace :: Ptr (TQLineEdit a) -> IO () instance QchangeEvent (QLineEdit ()) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_changeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_changeEvent_h" qtc_QLineEdit_changeEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent (QLineEditSc a) ((QEvent t1)) where changeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_changeEvent_h cobj_x0 cobj_x1 instance Qclear (QLineEdit a) (()) where clear x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_clear cobj_x0 foreign import ccall "qtc_QLineEdit_clear" qtc_QLineEdit_clear :: Ptr (TQLineEdit a) -> IO () instance Qcompleter (QLineEdit a) (()) where completer x0 () = withQCompleterResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_completer cobj_x0 foreign import ccall "qtc_QLineEdit_completer" qtc_QLineEdit_completer :: Ptr (TQLineEdit a) -> IO (Ptr (TQCompleter ())) instance QcontextMenuEvent (QLineEdit ()) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_contextMenuEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_contextMenuEvent_h" qtc_QLineEdit_contextMenuEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent (QLineEditSc a) ((QContextMenuEvent t1)) where contextMenuEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_contextMenuEvent_h cobj_x0 cobj_x1 instance Qcopy (QLineEdit a) (()) (IO ()) where copy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_copy cobj_x0 foreign import ccall "qtc_QLineEdit_copy" qtc_QLineEdit_copy :: Ptr (TQLineEdit a) -> IO () instance Qcopy_nf (QLineEdit a) (()) (IO ()) where copy_nf x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_copy cobj_x0 instance QcreateStandardContextMenu (QLineEdit a) (()) where createStandardContextMenu x0 () = withQMenuResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_createStandardContextMenu cobj_x0 foreign import ccall "qtc_QLineEdit_createStandardContextMenu" qtc_QLineEdit_createStandardContextMenu :: Ptr (TQLineEdit a) -> IO (Ptr (TQMenu ())) class QcursorBackward x1 where cursorBackward :: QLineEdit a -> x1 -> IO () instance QcursorBackward ((Bool)) where cursorBackward x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorBackward cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_cursorBackward" qtc_QLineEdit_cursorBackward :: Ptr (TQLineEdit a) -> CBool -> IO () instance QcursorBackward ((Bool, Int)) where cursorBackward x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorBackward1 cobj_x0 (toCBool x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_cursorBackward1" qtc_QLineEdit_cursorBackward1 :: Ptr (TQLineEdit a) -> CBool -> CInt -> IO () class QcursorForward x1 where cursorForward :: QLineEdit a -> x1 -> IO () instance QcursorForward ((Bool)) where cursorForward x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorForward cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_cursorForward" qtc_QLineEdit_cursorForward :: Ptr (TQLineEdit a) -> CBool -> IO () instance QcursorForward ((Bool, Int)) where cursorForward x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorForward1 cobj_x0 (toCBool x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_cursorForward1" qtc_QLineEdit_cursorForward1 :: Ptr (TQLineEdit a) -> CBool -> CInt -> IO () cursorPosition :: QLineEdit a -> (()) -> IO (Int) cursorPosition x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorPosition cobj_x0 foreign import ccall "qtc_QLineEdit_cursorPosition" qtc_QLineEdit_cursorPosition :: Ptr (TQLineEdit a) -> IO CInt cursorPositionAt :: QLineEdit a -> ((Point)) -> IO (Int) cursorPositionAt x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QLineEdit_cursorPositionAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QLineEdit_cursorPositionAt_qth" qtc_QLineEdit_cursorPositionAt_qth :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO CInt qcursorPositionAt :: QLineEdit a -> ((QPoint t1)) -> IO (Int) qcursorPositionAt x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_cursorPositionAt cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_cursorPositionAt" qtc_QLineEdit_cursorPositionAt :: Ptr (TQLineEdit a) -> Ptr (TQPoint t1) -> IO CInt cursorWordBackward :: QLineEdit a -> ((Bool)) -> IO () cursorWordBackward x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorWordBackward cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_cursorWordBackward" qtc_QLineEdit_cursorWordBackward :: Ptr (TQLineEdit a) -> CBool -> IO () cursorWordForward :: QLineEdit a -> ((Bool)) -> IO () cursorWordForward x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cursorWordForward cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_cursorWordForward" qtc_QLineEdit_cursorWordForward :: Ptr (TQLineEdit a) -> CBool -> IO () instance Qcut (QLineEdit a) (()) where cut x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_cut cobj_x0 foreign import ccall "qtc_QLineEdit_cut" qtc_QLineEdit_cut :: Ptr (TQLineEdit a) -> IO () del :: QLineEdit a -> (()) -> IO () del x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_del cobj_x0 foreign import ccall "qtc_QLineEdit_del" qtc_QLineEdit_del :: Ptr (TQLineEdit a) -> IO () deselect :: QLineEdit a -> (()) -> IO () deselect x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_deselect cobj_x0 foreign import ccall "qtc_QLineEdit_deselect" qtc_QLineEdit_deselect :: Ptr (TQLineEdit a) -> IO () displayText :: QLineEdit a -> (()) -> IO (String) displayText x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_displayText cobj_x0 foreign import ccall "qtc_QLineEdit_displayText" qtc_QLineEdit_displayText :: Ptr (TQLineEdit a) -> IO (Ptr (TQString ())) instance QdragEnabled (QLineEdit a) (()) where dragEnabled x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_dragEnabled cobj_x0 foreign import ccall "qtc_QLineEdit_dragEnabled" qtc_QLineEdit_dragEnabled :: Ptr (TQLineEdit a) -> IO CBool instance QdragEnterEvent (QLineEdit ()) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragEnterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_dragEnterEvent_h" qtc_QLineEdit_dragEnterEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent (QLineEditSc a) ((QDragEnterEvent t1)) where dragEnterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragEnterEvent_h cobj_x0 cobj_x1 instance QdragLeaveEvent (QLineEdit ()) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragLeaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_dragLeaveEvent_h" qtc_QLineEdit_dragLeaveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent (QLineEditSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragLeaveEvent_h cobj_x0 cobj_x1 instance QdragMoveEvent (QLineEdit ()) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_dragMoveEvent_h" qtc_QLineEdit_dragMoveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent (QLineEditSc a) ((QDragMoveEvent t1)) where dragMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dragMoveEvent_h cobj_x0 cobj_x1 instance QdropEvent (QLineEdit ()) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dropEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_dropEvent_h" qtc_QLineEdit_dropEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent (QLineEditSc a) ((QDropEvent t1)) where dropEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_dropEvent_h cobj_x0 cobj_x1 echoMode :: QLineEdit a -> (()) -> IO (EchoMode) echoMode x0 () = withQEnumResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_echoMode cobj_x0 foreign import ccall "qtc_QLineEdit_echoMode" qtc_QLineEdit_echoMode :: Ptr (TQLineEdit a) -> IO CLong instance Qend (QLineEdit a) ((Bool)) (IO ()) where end x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_end cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_end" qtc_QLineEdit_end :: Ptr (TQLineEdit a) -> CBool -> IO () instance Qevent (QLineEdit ()) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_event_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_event_h" qtc_QLineEdit_event_h :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent (QLineEditSc a) ((QEvent t1)) where event x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_event_h cobj_x0 cobj_x1 instance QfocusInEvent (QLineEdit ()) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_focusInEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_focusInEvent_h" qtc_QLineEdit_focusInEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent (QLineEditSc a) ((QFocusEvent t1)) where focusInEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_focusInEvent_h cobj_x0 cobj_x1 instance QfocusOutEvent (QLineEdit ()) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_focusOutEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_focusOutEvent_h" qtc_QLineEdit_focusOutEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent (QLineEditSc a) ((QFocusEvent t1)) where focusOutEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_focusOutEvent_h cobj_x0 cobj_x1 instance QhasAcceptableInput (QLineEdit a) (()) where hasAcceptableInput x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_hasAcceptableInput cobj_x0 foreign import ccall "qtc_QLineEdit_hasAcceptableInput" qtc_QLineEdit_hasAcceptableInput :: Ptr (TQLineEdit a) -> IO CBool instance QhasFrame (QLineEdit a) (()) where hasFrame x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_hasFrame cobj_x0 foreign import ccall "qtc_QLineEdit_hasFrame" qtc_QLineEdit_hasFrame :: Ptr (TQLineEdit a) -> IO CBool hasSelectedText :: QLineEdit a -> (()) -> IO (Bool) hasSelectedText x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_hasSelectedText cobj_x0 foreign import ccall "qtc_QLineEdit_hasSelectedText" qtc_QLineEdit_hasSelectedText :: Ptr (TQLineEdit a) -> IO CBool instance Qhome (QLineEdit a) ((Bool)) where home x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_home cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_home" qtc_QLineEdit_home :: Ptr (TQLineEdit a) -> CBool -> IO () instance QinitStyleOption (QLineEdit ()) ((QStyleOptionFrame t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_initStyleOption cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_initStyleOption" qtc_QLineEdit_initStyleOption :: Ptr (TQLineEdit a) -> Ptr (TQStyleOptionFrame t1) -> IO () instance QinitStyleOption (QLineEditSc a) ((QStyleOptionFrame t1)) where initStyleOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_initStyleOption cobj_x0 cobj_x1 inputMask :: QLineEdit a -> (()) -> IO (String) inputMask x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_inputMask cobj_x0 foreign import ccall "qtc_QLineEdit_inputMask" qtc_QLineEdit_inputMask :: Ptr (TQLineEdit a) -> IO (Ptr (TQString ())) instance QinputMethodEvent (QLineEdit ()) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_inputMethodEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_inputMethodEvent" qtc_QLineEdit_inputMethodEvent :: Ptr (TQLineEdit a) -> Ptr (TQInputMethodEvent t1) -> IO () instance QinputMethodEvent (QLineEditSc a) ((QInputMethodEvent t1)) where inputMethodEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_inputMethodEvent cobj_x0 cobj_x1 instance QinputMethodQuery (QLineEdit ()) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QLineEdit_inputMethodQuery_h" qtc_QLineEdit_inputMethodQuery_h :: Ptr (TQLineEdit a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery (QLineEditSc a) ((InputMethodQuery)) where inputMethodQuery x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1) insert :: QLineEdit a -> ((String)) -> IO () insert x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_insert cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_insert" qtc_QLineEdit_insert :: Ptr (TQLineEdit a) -> CWString -> IO () instance QisModified (QLineEdit a) (()) where isModified x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_isModified cobj_x0 foreign import ccall "qtc_QLineEdit_isModified" qtc_QLineEdit_isModified :: Ptr (TQLineEdit a) -> IO CBool instance QisReadOnly (QLineEdit a) (()) where isReadOnly x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_isReadOnly cobj_x0 foreign import ccall "qtc_QLineEdit_isReadOnly" qtc_QLineEdit_isReadOnly :: Ptr (TQLineEdit a) -> IO CBool instance QisRedoAvailable (QLineEdit a) (()) where isRedoAvailable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_isRedoAvailable cobj_x0 foreign import ccall "qtc_QLineEdit_isRedoAvailable" qtc_QLineEdit_isRedoAvailable :: Ptr (TQLineEdit a) -> IO CBool instance QisUndoAvailable (QLineEdit a) (()) where isUndoAvailable x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_isUndoAvailable cobj_x0 foreign import ccall "qtc_QLineEdit_isUndoAvailable" qtc_QLineEdit_isUndoAvailable :: Ptr (TQLineEdit a) -> IO CBool instance QkeyPressEvent (QLineEdit ()) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_keyPressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_keyPressEvent_h" qtc_QLineEdit_keyPressEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent (QLineEditSc a) ((QKeyEvent t1)) where keyPressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_keyPressEvent_h cobj_x0 cobj_x1 maxLength :: QLineEdit a -> (()) -> IO (Int) maxLength x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_maxLength cobj_x0 foreign import ccall "qtc_QLineEdit_maxLength" qtc_QLineEdit_maxLength :: Ptr (TQLineEdit a) -> IO CInt instance QqminimumSizeHint (QLineEdit ()) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_minimumSizeHint_h cobj_x0 foreign import ccall "qtc_QLineEdit_minimumSizeHint_h" qtc_QLineEdit_minimumSizeHint_h :: Ptr (TQLineEdit a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint (QLineEditSc a) (()) where qminimumSizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_minimumSizeHint_h cobj_x0 instance QminimumSizeHint (QLineEdit ()) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QLineEdit_minimumSizeHint_qth_h" qtc_QLineEdit_minimumSizeHint_qth_h :: Ptr (TQLineEdit a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint (QLineEditSc a) (()) where minimumSizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance QmouseDoubleClickEvent (QLineEdit ()) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseDoubleClickEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_mouseDoubleClickEvent_h" qtc_QLineEdit_mouseDoubleClickEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent (QLineEditSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseDoubleClickEvent_h cobj_x0 cobj_x1 instance QmouseMoveEvent (QLineEdit ()) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseMoveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_mouseMoveEvent_h" qtc_QLineEdit_mouseMoveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent (QLineEditSc a) ((QMouseEvent t1)) where mouseMoveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseMoveEvent_h cobj_x0 cobj_x1 instance QmousePressEvent (QLineEdit ()) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mousePressEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_mousePressEvent_h" qtc_QLineEdit_mousePressEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent (QLineEditSc a) ((QMouseEvent t1)) where mousePressEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mousePressEvent_h cobj_x0 cobj_x1 instance QmouseReleaseEvent (QLineEdit ()) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_mouseReleaseEvent_h" qtc_QLineEdit_mouseReleaseEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent (QLineEditSc a) ((QMouseEvent t1)) where mouseReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_mouseReleaseEvent_h cobj_x0 cobj_x1 instance QpaintEvent (QLineEdit ()) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_paintEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_paintEvent_h" qtc_QLineEdit_paintEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent (QLineEditSc a) ((QPaintEvent t1)) where paintEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_paintEvent_h cobj_x0 cobj_x1 instance Qpaste (QLineEdit a) (()) where paste x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_paste cobj_x0 foreign import ccall "qtc_QLineEdit_paste" qtc_QLineEdit_paste :: Ptr (TQLineEdit a) -> IO () instance Qredo (QLineEdit a) (()) where redo x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_redo cobj_x0 foreign import ccall "qtc_QLineEdit_redo" qtc_QLineEdit_redo :: Ptr (TQLineEdit a) -> IO () instance QselectAll (QLineEdit a) (()) where selectAll x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_selectAll cobj_x0 foreign import ccall "qtc_QLineEdit_selectAll" qtc_QLineEdit_selectAll :: Ptr (TQLineEdit a) -> IO () instance QselectedText (QLineEdit a) (()) where selectedText x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_selectedText cobj_x0 foreign import ccall "qtc_QLineEdit_selectedText" qtc_QLineEdit_selectedText :: Ptr (TQLineEdit a) -> IO (Ptr (TQString ())) instance QselectionStart (QLineEdit a) (()) where selectionStart x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_selectionStart cobj_x0 foreign import ccall "qtc_QLineEdit_selectionStart" qtc_QLineEdit_selectionStart :: Ptr (TQLineEdit a) -> IO CInt instance QsetAlignment (QLineEdit a) ((Alignment)) (IO ()) where setAlignment x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setAlignment cobj_x0 (toCLong $ qFlags_toInt x1) foreign import ccall "qtc_QLineEdit_setAlignment" qtc_QLineEdit_setAlignment :: Ptr (TQLineEdit a) -> CLong -> IO () instance QsetCompleter (QLineEdit a) ((QCompleter t1)) where setCompleter x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_setCompleter cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_setCompleter" qtc_QLineEdit_setCompleter :: Ptr (TQLineEdit a) -> Ptr (TQCompleter t1) -> IO () setCursorPosition :: QLineEdit a -> ((Int)) -> IO () setCursorPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setCursorPosition cobj_x0 (toCInt x1) foreign import ccall "qtc_QLineEdit_setCursorPosition" qtc_QLineEdit_setCursorPosition :: Ptr (TQLineEdit a) -> CInt -> IO () instance QsetDragEnabled (QLineEdit a) ((Bool)) where setDragEnabled x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setDragEnabled cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setDragEnabled" qtc_QLineEdit_setDragEnabled :: Ptr (TQLineEdit a) -> CBool -> IO () setEchoMode :: QLineEdit a -> ((EchoMode)) -> IO () setEchoMode x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setEchoMode cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QLineEdit_setEchoMode" qtc_QLineEdit_setEchoMode :: Ptr (TQLineEdit a) -> CLong -> IO () instance QsetFrame (QLineEdit a) ((Bool)) where setFrame x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setFrame cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setFrame" qtc_QLineEdit_setFrame :: Ptr (TQLineEdit a) -> CBool -> IO () setInputMask :: QLineEdit a -> ((String)) -> IO () setInputMask x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_setInputMask cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_setInputMask" qtc_QLineEdit_setInputMask :: Ptr (TQLineEdit a) -> CWString -> IO () setMaxLength :: QLineEdit a -> ((Int)) -> IO () setMaxLength x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setMaxLength cobj_x0 (toCInt x1) foreign import ccall "qtc_QLineEdit_setMaxLength" qtc_QLineEdit_setMaxLength :: Ptr (TQLineEdit a) -> CInt -> IO () instance QsetModified (QLineEdit a) ((Bool)) where setModified x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setModified cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setModified" qtc_QLineEdit_setModified :: Ptr (TQLineEdit a) -> CBool -> IO () instance QsetReadOnly (QLineEdit a) ((Bool)) where setReadOnly x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setReadOnly cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setReadOnly" qtc_QLineEdit_setReadOnly :: Ptr (TQLineEdit a) -> CBool -> IO () instance QsetSelection (QLineEdit a) ((Int, Int)) where setSelection x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setSelection cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_setSelection" qtc_QLineEdit_setSelection :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance QsetText (QLineEdit a) ((String)) where setText x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_setText cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_setText" qtc_QLineEdit_setText :: Ptr (TQLineEdit a) -> CWString -> IO () instance QsetValidator (QLineEdit a) ((QValidator t1)) where setValidator x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_setValidator cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_setValidator" qtc_QLineEdit_setValidator :: Ptr (TQLineEdit a) -> Ptr (TQValidator t1) -> IO () instance QqsizeHint (QLineEdit ()) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sizeHint_h cobj_x0 foreign import ccall "qtc_QLineEdit_sizeHint_h" qtc_QLineEdit_sizeHint_h :: Ptr (TQLineEdit a) -> IO (Ptr (TQSize ())) instance QqsizeHint (QLineEditSc a) (()) where qsizeHint x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sizeHint_h cobj_x0 instance QsizeHint (QLineEdit ()) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QLineEdit_sizeHint_qth_h" qtc_QLineEdit_sizeHint_qth_h :: Ptr (TQLineEdit a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint (QLineEditSc a) (()) where sizeHint x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h instance Qtext (QLineEdit a) (()) (IO (String)) where text x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_text cobj_x0 foreign import ccall "qtc_QLineEdit_text" qtc_QLineEdit_text :: Ptr (TQLineEdit a) -> IO (Ptr (TQString ())) instance Qundo (QLineEdit a) (()) where undo x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_undo cobj_x0 foreign import ccall "qtc_QLineEdit_undo" qtc_QLineEdit_undo :: Ptr (TQLineEdit a) -> IO () instance Qvalidator (QLineEdit a) (()) where validator x0 () = withQValidatorResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_validator cobj_x0 foreign import ccall "qtc_QLineEdit_validator" qtc_QLineEdit_validator :: Ptr (TQLineEdit a) -> IO (Ptr (TQValidator ())) qLineEdit_delete :: QLineEdit a -> IO () qLineEdit_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_delete cobj_x0 foreign import ccall "qtc_QLineEdit_delete" qtc_QLineEdit_delete :: Ptr (TQLineEdit a) -> IO () qLineEdit_deleteLater :: QLineEdit a -> IO () qLineEdit_deleteLater x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_deleteLater cobj_x0 foreign import ccall "qtc_QLineEdit_deleteLater" qtc_QLineEdit_deleteLater :: Ptr (TQLineEdit a) -> IO () instance QactionEvent (QLineEdit ()) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_actionEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_actionEvent_h" qtc_QLineEdit_actionEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent (QLineEditSc a) ((QActionEvent t1)) where actionEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_actionEvent_h cobj_x0 cobj_x1 instance QaddAction (QLineEdit ()) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_addAction cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_addAction" qtc_QLineEdit_addAction :: Ptr (TQLineEdit a) -> Ptr (TQAction t1) -> IO () instance QaddAction (QLineEditSc a) ((QAction t1)) (IO ()) where addAction x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_addAction cobj_x0 cobj_x1 instance QcloseEvent (QLineEdit ()) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_closeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_closeEvent_h" qtc_QLineEdit_closeEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent (QLineEditSc a) ((QCloseEvent t1)) where closeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_closeEvent_h cobj_x0 cobj_x1 instance Qcreate (QLineEdit ()) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_create cobj_x0 foreign import ccall "qtc_QLineEdit_create" qtc_QLineEdit_create :: Ptr (TQLineEdit a) -> IO () instance Qcreate (QLineEditSc a) (()) (IO ()) where create x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_create cobj_x0 instance Qcreate (QLineEdit ()) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create1 cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_create1" qtc_QLineEdit_create1 :: Ptr (TQLineEdit a) -> Ptr (TQVoid t1) -> IO () instance Qcreate (QLineEditSc a) ((QVoid t1)) (IO ()) where create x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create1 cobj_x0 cobj_x1 instance Qcreate (QLineEdit ()) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create2 cobj_x0 cobj_x1 (toCBool x2) foreign import ccall "qtc_QLineEdit_create2" qtc_QLineEdit_create2 :: Ptr (TQLineEdit a) -> Ptr (TQVoid t1) -> CBool -> IO () instance Qcreate (QLineEditSc a) ((QVoid t1, Bool)) (IO ()) where create x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create2 cobj_x0 cobj_x1 (toCBool x2) instance Qcreate (QLineEdit ()) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) foreign import ccall "qtc_QLineEdit_create3" qtc_QLineEdit_create3 :: Ptr (TQLineEdit a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO () instance Qcreate (QLineEditSc a) ((QVoid t1, Bool, Bool)) (IO ()) where create x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3) instance Qdestroy (QLineEdit ()) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy cobj_x0 foreign import ccall "qtc_QLineEdit_destroy" qtc_QLineEdit_destroy :: Ptr (TQLineEdit a) -> IO () instance Qdestroy (QLineEditSc a) (()) where destroy x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy cobj_x0 instance Qdestroy (QLineEdit ()) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy1 cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_destroy1" qtc_QLineEdit_destroy1 :: Ptr (TQLineEdit a) -> CBool -> IO () instance Qdestroy (QLineEditSc a) ((Bool)) where destroy x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy1 cobj_x0 (toCBool x1) instance Qdestroy (QLineEdit ()) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy2 cobj_x0 (toCBool x1) (toCBool x2) foreign import ccall "qtc_QLineEdit_destroy2" qtc_QLineEdit_destroy2 :: Ptr (TQLineEdit a) -> CBool -> CBool -> IO () instance Qdestroy (QLineEditSc a) ((Bool, Bool)) where destroy x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_destroy2 cobj_x0 (toCBool x1) (toCBool x2) instance QdevType (QLineEdit ()) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_devType_h cobj_x0 foreign import ccall "qtc_QLineEdit_devType_h" qtc_QLineEdit_devType_h :: Ptr (TQLineEdit a) -> IO CInt instance QdevType (QLineEditSc a) (()) where devType x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_devType_h cobj_x0 instance QenabledChange (QLineEdit ()) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_enabledChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_enabledChange" qtc_QLineEdit_enabledChange :: Ptr (TQLineEdit a) -> CBool -> IO () instance QenabledChange (QLineEditSc a) ((Bool)) where enabledChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_enabledChange cobj_x0 (toCBool x1) instance QenterEvent (QLineEdit ()) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_enterEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_enterEvent_h" qtc_QLineEdit_enterEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent (QLineEditSc a) ((QEvent t1)) where enterEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_enterEvent_h cobj_x0 cobj_x1 instance QfocusNextChild (QLineEdit ()) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusNextChild cobj_x0 foreign import ccall "qtc_QLineEdit_focusNextChild" qtc_QLineEdit_focusNextChild :: Ptr (TQLineEdit a) -> IO CBool instance QfocusNextChild (QLineEditSc a) (()) where focusNextChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusNextChild cobj_x0 instance QfocusNextPrevChild (QLineEdit ()) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusNextPrevChild cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_focusNextPrevChild" qtc_QLineEdit_focusNextPrevChild :: Ptr (TQLineEdit a) -> CBool -> IO CBool instance QfocusNextPrevChild (QLineEditSc a) ((Bool)) where focusNextPrevChild x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusNextPrevChild cobj_x0 (toCBool x1) instance QfocusPreviousChild (QLineEdit ()) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusPreviousChild cobj_x0 foreign import ccall "qtc_QLineEdit_focusPreviousChild" qtc_QLineEdit_focusPreviousChild :: Ptr (TQLineEdit a) -> IO CBool instance QfocusPreviousChild (QLineEditSc a) (()) where focusPreviousChild x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_focusPreviousChild cobj_x0 instance QfontChange (QLineEdit ()) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_fontChange cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_fontChange" qtc_QLineEdit_fontChange :: Ptr (TQLineEdit a) -> Ptr (TQFont t1) -> IO () instance QfontChange (QLineEditSc a) ((QFont t1)) where fontChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_fontChange cobj_x0 cobj_x1 instance QheightForWidth (QLineEdit ()) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_heightForWidth_h cobj_x0 (toCInt x1) foreign import ccall "qtc_QLineEdit_heightForWidth_h" qtc_QLineEdit_heightForWidth_h :: Ptr (TQLineEdit a) -> CInt -> IO CInt instance QheightForWidth (QLineEditSc a) ((Int)) where heightForWidth x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_heightForWidth_h cobj_x0 (toCInt x1) instance QhideEvent (QLineEdit ()) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_hideEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_hideEvent_h" qtc_QLineEdit_hideEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent (QLineEditSc a) ((QHideEvent t1)) where hideEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_hideEvent_h cobj_x0 cobj_x1 instance QkeyReleaseEvent (QLineEdit ()) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_keyReleaseEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_keyReleaseEvent_h" qtc_QLineEdit_keyReleaseEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent (QLineEditSc a) ((QKeyEvent t1)) where keyReleaseEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_keyReleaseEvent_h cobj_x0 cobj_x1 instance QlanguageChange (QLineEdit ()) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_languageChange cobj_x0 foreign import ccall "qtc_QLineEdit_languageChange" qtc_QLineEdit_languageChange :: Ptr (TQLineEdit a) -> IO () instance QlanguageChange (QLineEditSc a) (()) where languageChange x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_languageChange cobj_x0 instance QleaveEvent (QLineEdit ()) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_leaveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_leaveEvent_h" qtc_QLineEdit_leaveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent (QLineEditSc a) ((QEvent t1)) where leaveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_leaveEvent_h cobj_x0 cobj_x1 instance Qmetric (QLineEdit ()) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_metric cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QLineEdit_metric" qtc_QLineEdit_metric :: Ptr (TQLineEdit a) -> CLong -> IO CInt instance Qmetric (QLineEditSc a) ((PaintDeviceMetric)) where metric x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_metric cobj_x0 (toCLong $ qEnum_toInt x1) instance Qmove (QLineEdit ()) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_move1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_move1" qtc_QLineEdit_move1 :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance Qmove (QLineEditSc a) ((Int, Int)) where move x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_move1 cobj_x0 (toCInt x1) (toCInt x2) instance Qmove (QLineEdit ()) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QLineEdit_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y foreign import ccall "qtc_QLineEdit_move_qth" qtc_QLineEdit_move_qth :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance Qmove (QLineEditSc a) ((Point)) where move x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPoint x1 $ \cpoint_x1_x cpoint_x1_y -> qtc_QLineEdit_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y instance Qqmove (QLineEdit ()) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_move cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_move" qtc_QLineEdit_move :: Ptr (TQLineEdit a) -> Ptr (TQPoint t1) -> IO () instance Qqmove (QLineEditSc a) ((QPoint t1)) where qmove x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_move cobj_x0 cobj_x1 instance QmoveEvent (QLineEdit ()) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_moveEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_moveEvent_h" qtc_QLineEdit_moveEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent (QLineEditSc a) ((QMoveEvent t1)) where moveEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_moveEvent_h cobj_x0 cobj_x1 instance QpaintEngine (QLineEdit ()) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_paintEngine_h cobj_x0 foreign import ccall "qtc_QLineEdit_paintEngine_h" qtc_QLineEdit_paintEngine_h :: Ptr (TQLineEdit a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine (QLineEditSc a) (()) where paintEngine x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_paintEngine_h cobj_x0 instance QpaletteChange (QLineEdit ()) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_paletteChange cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_paletteChange" qtc_QLineEdit_paletteChange :: Ptr (TQLineEdit a) -> Ptr (TQPalette t1) -> IO () instance QpaletteChange (QLineEditSc a) ((QPalette t1)) where paletteChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_paletteChange cobj_x0 cobj_x1 instance Qrepaint (QLineEdit ()) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_repaint cobj_x0 foreign import ccall "qtc_QLineEdit_repaint" qtc_QLineEdit_repaint :: Ptr (TQLineEdit a) -> IO () instance Qrepaint (QLineEditSc a) (()) where repaint x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_repaint cobj_x0 instance Qrepaint (QLineEdit ()) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QLineEdit_repaint2" qtc_QLineEdit_repaint2 :: Ptr (TQLineEdit a) -> CInt -> CInt -> CInt -> CInt -> IO () instance Qrepaint (QLineEditSc a) ((Int, Int, Int, Int)) where repaint x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance Qrepaint (QLineEdit ()) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_repaint1 cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_repaint1" qtc_QLineEdit_repaint1 :: Ptr (TQLineEdit a) -> Ptr (TQRegion t1) -> IO () instance Qrepaint (QLineEditSc a) ((QRegion t1)) where repaint x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_repaint1 cobj_x0 cobj_x1 instance QresetInputContext (QLineEdit ()) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_resetInputContext cobj_x0 foreign import ccall "qtc_QLineEdit_resetInputContext" qtc_QLineEdit_resetInputContext :: Ptr (TQLineEdit a) -> IO () instance QresetInputContext (QLineEditSc a) (()) where resetInputContext x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_resetInputContext cobj_x0 instance Qresize (QLineEdit ()) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_resize1 cobj_x0 (toCInt x1) (toCInt x2) foreign import ccall "qtc_QLineEdit_resize1" qtc_QLineEdit_resize1 :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance Qresize (QLineEditSc a) ((Int, Int)) (IO ()) where resize x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_resize1 cobj_x0 (toCInt x1) (toCInt x2) instance Qqresize (QLineEdit ()) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_resize cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_resize" qtc_QLineEdit_resize :: Ptr (TQLineEdit a) -> Ptr (TQSize t1) -> IO () instance Qqresize (QLineEditSc a) ((QSize t1)) where qresize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_resize cobj_x0 cobj_x1 instance Qresize (QLineEdit ()) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QLineEdit_resize_qth cobj_x0 csize_x1_w csize_x1_h foreign import ccall "qtc_QLineEdit_resize_qth" qtc_QLineEdit_resize_qth :: Ptr (TQLineEdit a) -> CInt -> CInt -> IO () instance Qresize (QLineEditSc a) ((Size)) (IO ()) where resize x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCSize x1 $ \csize_x1_w csize_x1_h -> qtc_QLineEdit_resize_qth cobj_x0 csize_x1_w csize_x1_h instance QresizeEvent (QLineEdit ()) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_resizeEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_resizeEvent_h" qtc_QLineEdit_resizeEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent (QLineEditSc a) ((QResizeEvent t1)) where resizeEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_resizeEvent_h cobj_x0 cobj_x1 instance QsetGeometry (QLineEdit ()) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) foreign import ccall "qtc_QLineEdit_setGeometry1" qtc_QLineEdit_setGeometry1 :: Ptr (TQLineEdit a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QLineEditSc a) ((Int, Int, Int, Int)) where setGeometry x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4) instance QqsetGeometry (QLineEdit ()) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_setGeometry cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_setGeometry" qtc_QLineEdit_setGeometry :: Ptr (TQLineEdit a) -> Ptr (TQRect t1) -> IO () instance QqsetGeometry (QLineEditSc a) ((QRect t1)) where qsetGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_setGeometry cobj_x0 cobj_x1 instance QsetGeometry (QLineEdit ()) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QLineEdit_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h foreign import ccall "qtc_QLineEdit_setGeometry_qth" qtc_QLineEdit_setGeometry_qth :: Ptr (TQLineEdit a) -> CInt -> CInt -> CInt -> CInt -> IO () instance QsetGeometry (QLineEditSc a) ((Rect)) where setGeometry x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h -> qtc_QLineEdit_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h instance QsetMouseTracking (QLineEdit ()) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setMouseTracking cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setMouseTracking" qtc_QLineEdit_setMouseTracking :: Ptr (TQLineEdit a) -> CBool -> IO () instance QsetMouseTracking (QLineEditSc a) ((Bool)) where setMouseTracking x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setMouseTracking cobj_x0 (toCBool x1) instance QsetVisible (QLineEdit ()) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setVisible_h cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_setVisible_h" qtc_QLineEdit_setVisible_h :: Ptr (TQLineEdit a) -> CBool -> IO () instance QsetVisible (QLineEditSc a) ((Bool)) where setVisible x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_setVisible_h cobj_x0 (toCBool x1) instance QshowEvent (QLineEdit ()) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_showEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_showEvent_h" qtc_QLineEdit_showEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent (QLineEditSc a) ((QShowEvent t1)) where showEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_showEvent_h cobj_x0 cobj_x1 instance QtabletEvent (QLineEdit ()) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_tabletEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_tabletEvent_h" qtc_QLineEdit_tabletEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent (QLineEditSc a) ((QTabletEvent t1)) where tabletEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_tabletEvent_h cobj_x0 cobj_x1 instance QupdateMicroFocus (QLineEdit ()) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_updateMicroFocus cobj_x0 foreign import ccall "qtc_QLineEdit_updateMicroFocus" qtc_QLineEdit_updateMicroFocus :: Ptr (TQLineEdit a) -> IO () instance QupdateMicroFocus (QLineEditSc a) (()) where updateMicroFocus x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_updateMicroFocus cobj_x0 instance QwheelEvent (QLineEdit ()) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_wheelEvent_h cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_wheelEvent_h" qtc_QLineEdit_wheelEvent_h :: Ptr (TQLineEdit a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent (QLineEditSc a) ((QWheelEvent t1)) where wheelEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_wheelEvent_h cobj_x0 cobj_x1 instance QwindowActivationChange (QLineEdit ()) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_windowActivationChange cobj_x0 (toCBool x1) foreign import ccall "qtc_QLineEdit_windowActivationChange" qtc_QLineEdit_windowActivationChange :: Ptr (TQLineEdit a) -> CBool -> IO () instance QwindowActivationChange (QLineEditSc a) ((Bool)) where windowActivationChange x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_windowActivationChange cobj_x0 (toCBool x1) instance QchildEvent (QLineEdit ()) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_childEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_childEvent" qtc_QLineEdit_childEvent :: Ptr (TQLineEdit a) -> Ptr (TQChildEvent t1) -> IO () instance QchildEvent (QLineEditSc a) ((QChildEvent t1)) where childEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_childEvent cobj_x0 cobj_x1 instance QconnectNotify (QLineEdit ()) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_connectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_connectNotify" qtc_QLineEdit_connectNotify :: Ptr (TQLineEdit a) -> CWString -> IO () instance QconnectNotify (QLineEditSc a) ((String)) where connectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_connectNotify cobj_x0 cstr_x1 instance QcustomEvent (QLineEdit ()) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_customEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_customEvent" qtc_QLineEdit_customEvent :: Ptr (TQLineEdit a) -> Ptr (TQEvent t1) -> IO () instance QcustomEvent (QLineEditSc a) ((QEvent t1)) where customEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_customEvent cobj_x0 cobj_x1 instance QdisconnectNotify (QLineEdit ()) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_disconnectNotify cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_disconnectNotify" qtc_QLineEdit_disconnectNotify :: Ptr (TQLineEdit a) -> CWString -> IO () instance QdisconnectNotify (QLineEditSc a) ((String)) where disconnectNotify x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_disconnectNotify cobj_x0 cstr_x1 instance QeventFilter (QLineEdit ()) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QLineEdit_eventFilter_h cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QLineEdit_eventFilter_h" qtc_QLineEdit_eventFilter_h :: Ptr (TQLineEdit a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter (QLineEditSc a) ((QObject t1, QEvent t2)) where eventFilter x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QLineEdit_eventFilter_h cobj_x0 cobj_x1 cobj_x2 instance Qreceivers (QLineEdit ()) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_receivers cobj_x0 cstr_x1 foreign import ccall "qtc_QLineEdit_receivers" qtc_QLineEdit_receivers :: Ptr (TQLineEdit a) -> CWString -> IO CInt instance Qreceivers (QLineEditSc a) ((String)) where receivers x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QLineEdit_receivers cobj_x0 cstr_x1 instance Qsender (QLineEdit ()) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sender cobj_x0 foreign import ccall "qtc_QLineEdit_sender" qtc_QLineEdit_sender :: Ptr (TQLineEdit a) -> IO (Ptr (TQObject ())) instance Qsender (QLineEditSc a) (()) where sender x0 () = withQObjectResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QLineEdit_sender cobj_x0 instance QtimerEvent (QLineEdit ()) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_timerEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QLineEdit_timerEvent" qtc_QLineEdit_timerEvent :: Ptr (TQLineEdit a) -> Ptr (TQTimerEvent t1) -> IO () instance QtimerEvent (QLineEditSc a) ((QTimerEvent t1)) where timerEvent x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QLineEdit_timerEvent cobj_x0 cobj_x1
keera-studios/hsQt
Qtc/Gui/QLineEdit.hs
Haskell
bsd-2-clause
59,042
{-# LANGUAGE BangPatterns #-} module AI.HMM.Type where import qualified Data.Vector as V import qualified Data.Vector.Unboxed as U import qualified Data.Vector.Generic as G import Numeric.LinearAlgebra.HMatrix import AI.Function -- constant: log (2*pi) m_log_2_pi :: Double m_log_2_pi = 1.8378770664093453 -- | multivariate normal distribution data MVN = MVN { _mean :: !(U.Vector Double) , _cov :: !(U.Vector Double) -- ^ row majored covariance matrix , _invcov :: !(U.Vector Double) , _logdet :: !Double -- ^ log determinant of covariance matrix , _dim :: !Int , _covType :: !CovType } deriving (Show) data CovType = Full | Diagonal deriving (Show) data CovEstimator = FullCov | DiagonalCov | LassoCov mvn :: U.Vector Double -> U.Vector Double -> MVN mvn m cov | d*d /= U.length cov = error "incompatible dimemsion of mean and covariance" | otherwise = MVN m cov (G.convert $ flatten invcov) logdet d Full where (invcov, (logdet, _)) = invlndet $ reshape d $ G.convert cov d = U.length m {-# INLINE mvn #-} mvnDiag :: U.Vector Double -> U.Vector Double -> MVN mvnDiag m cov | d /= U.length cov = error "incompatible dimemsion of mean and covariance" | otherwise = MVN m cov invcov logdet d Diagonal where invcov = U.map (1/) cov logdet = U.sum . U.map log $ cov d = U.length m {-# INLINE mvnDiag #-} {- -- | log probability of MVN logPDF :: MVN -> Vector Double -> Double logPDF (MVN m _ invcov logdet) x = -0.5 * ( d * log (2*pi) + logdet + (x' <> invcov <> tr x') ! 0 ! 0 ) where x' = asRow $ x - m d = fromIntegral . G.length $ m {-# INLINE logPDF #-} -} logPDF :: MVN -> U.Vector Double -> Double logPDF (MVN m _ invcov logdet d t) x = -0.5 * (fromIntegral d * m_log_2_pi + logdet + quadTerm) where quadTerm = case t of Full -> loop 0 0 Diagonal -> U.sum $ U.zipWith (*) invcov $ U.map (**2) x' where loop !acc !i | i < d*d = let r = i `div` d c = i `mod` d in acc + U.unsafeIndex invcov i * U.unsafeIndex x' r * U.unsafeIndex x' c | otherwise = acc x' = U.zipWith (-) x m {-# INLINE logPDF #-} -- | mixture of multivariate normal variables, weight is in log form newtype MixMVN = MixMVN (V.Vector (Double, MVN)) deriving (Show) getWeight :: MixMVN -> Int -> Double getWeight (MixMVN xs) i = fst $ xs V.! i {-# INLINE getWeight #-} logPDFMix :: MixMVN -> U.Vector Double -> Double logPDFMix (MixMVN v) xs = logSumExp . V.map (\(logw, m) -> logw + logPDF m xs) $ v {-# INLINE logPDFMix #-}
kaizhang/HMM
src/AI/HMM/Type.hs
Haskell
bsd-3-clause
2,750
module Paths_bogre_banana ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,0,1], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/home/david/.cabal/bin" libdir = "/home/david/.cabal/lib/bogre-banana-0.0.1/ghc-7.4.2" datadir = "/home/david/.cabal/share/bogre-banana-0.0.1" libexecdir = "/home/david/.cabal/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "bogre_banana_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "bogre_banana_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "bogre_banana_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "bogre_banana_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
DavidEichmann/boger-banana
.dist-buildwrapper/dist/build/autogen/Paths_bogre_banana.hs
Haskell
bsd-3-clause
1,156
module Main where import System.Environment (getArgs) import Budget.App (run, BudgetCommand(..)) main :: IO () main = do args <- getArgs case parseOpts args of Left m -> putStrLn m Right c -> run c parseOpts :: [String] -> Either String BudgetCommand parseOpts ("configure":options) = Right (Configure (parseDatapath options)) parseOpts ("start":options) = Right (Start (parsePort options) (parseDatapath options)) parseOpts _ = Left "configure | start" parseDatapath :: [String] -> String parseDatapath [] = ":memory:" parseDatapath ("-d":datapath:_) = datapath parseDatapath (_:xs) = parseDatapath xs parsePort :: [String] -> Int parsePort [] = 8080 parsePort ("-p":port:_) = read port parsePort (_:xs) = parsePort xs
utky/budget
app/Main.hs
Haskell
bsd-3-clause
808
{-# LANGUAGE DataKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-| Module : Numeric.AERN.RealArithmetic.Basis.MPFR.Effort Description : MPFR precision is an effort indicator Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable MPFR precision is an effort indicator. This is a private module reexported publicly via its parent. -} module Numeric.AERN.RealArithmetic.Basis.MPFR.Basics ( MPFR(..), RoundedTowardInf, liftRoundedToMPFR1, liftRoundedToMPFR2, MPFRPrec, defaultPrecision, getPrecision, samePrecision, withPrec, withPrecRoundDown ) where import Numeric.AERN.Basics.Effort import qualified Numeric.Rounded as R import GHC.TypeLits import Data.Proxy import Unsafe.Coerce --import qualified Data.Number.MPFR as M import Test.QuickCheck data MPFR = forall p. (R.Precision p) => MPFR (RoundedTowardInf p) type RoundedTowardInf p = R.Rounded R.TowardInf p deriving instance Show MPFR newtype MPFRPrec = MPFRPrec Int deriving (Eq, Ord, Show, Enum, EffortIndicator, Num, Real, Integral) withPrec :: MPFRPrec -> (forall p. (R.Precision p) => R.Rounded R.TowardInf p) -> MPFR withPrec (MPFRPrec p) computation | p < 2 = error "MPFR precision has to be at least 2" | otherwise = R.reifyPrecision p (\(_ :: Proxy p) -> MPFR (computation :: R.Rounded R.TowardInf p)) {-| This should be needed very rarely, in cases such as to get a lower bound on pi. -} withPrecRoundDown :: MPFRPrec -> (forall p. (R.Precision p) => R.Rounded R.TowardNegInf p) -> MPFR withPrecRoundDown (MPFRPrec p) computation | p < 2 = error "MPFR precision has to be at least 2" | otherwise = R.reifyPrecision p (\(_ :: Proxy p) -> MPFR (unsafeCoerce (computation :: R.Rounded R.TowardNegInf p) :: R.Rounded R.TowardInf p)) instance Arbitrary MPFRPrec where arbitrary = do p <- choose (10,1000) return (MPFRPrec (p :: Int)) defaultPrecision :: MPFRPrec defaultPrecision = 100 --type DefaultPrecision = 100 getPrecision :: MPFR -> MPFRPrec getPrecision (MPFR v) = MPFRPrec $ R.precision v samePrecision :: MPFR -> MPFR -> Bool samePrecision m1 m2 = p1 == p2 where p1 = getPrecision m1 p2 = getPrecision m2 withSamePrecision :: String -> (forall p. (R.Precision p) => (RoundedTowardInf p) -> (RoundedTowardInf p) -> t) -> MPFR -> MPFR -> t withSamePrecision context f m1@(MPFR v1) m2@(MPFR v2) | samePrecision m1 m2 = f v1 (unsafeCoerce v2) | otherwise = error $ mixPrecisionErrorMessage context m1 m2 mixPrecisionErrorMessage context m1 m2 = context ++ ": trying to mix precisions: " ++ show (getPrecision m1) ++ " vs " ++ show (getPrecision m2) instance Eq MPFR where (==) = withSamePrecision "==" (==) instance Ord MPFR where compare = withSamePrecision "compare" compare liftRoundedToMPFR1 :: (forall p. (R.Precision p) => (RoundedTowardInf p) -> (RoundedTowardInf p)) -> MPFR -> MPFR liftRoundedToMPFR1 f (MPFR v) = (MPFR (f v)) liftRoundedToMPFR2 :: String -> (forall p. (R.Precision p) => (RoundedTowardInf p) -> (RoundedTowardInf p) -> (RoundedTowardInf p)) -> MPFR -> MPFR -> MPFR liftRoundedToMPFR2 context f = withSamePrecision context (\ v1 v2 -> MPFR (f v1 v2)) instance Num MPFR where (+) = liftRoundedToMPFR2 "+" (+) (-) = liftRoundedToMPFR2 "-" (-) (*) = liftRoundedToMPFR2 "*" (*) negate = liftRoundedToMPFR1 negate -- fromInteger n = withPrec defaultPrecision $ fromInteger n -- useless fromInteger _ = error "MPFR type: fromInteger not implemented" abs = liftRoundedToMPFR1 abs signum = liftRoundedToMPFR1 signum instance Fractional MPFR where (/) = liftRoundedToMPFR2 "/" (/) fromRational _ = error "MPFR type: fromRational not implemented" instance Floating MPFR where pi = error "MPFR type: pi not implemented" exp = liftRoundedToMPFR1 exp sqrt = liftRoundedToMPFR1 sqrt log = liftRoundedToMPFR1 log sin = liftRoundedToMPFR1 sin tan = liftRoundedToMPFR1 tan cos = liftRoundedToMPFR1 cos asin = liftRoundedToMPFR1 asin atan = liftRoundedToMPFR1 atan acos = liftRoundedToMPFR1 acos sinh = liftRoundedToMPFR1 sinh tanh = liftRoundedToMPFR1 tanh cosh = liftRoundedToMPFR1 cosh asinh = liftRoundedToMPFR1 asinh atanh = liftRoundedToMPFR1 atanh acosh = liftRoundedToMPFR1 acosh instance Real MPFR where toRational (MPFR v) = toRational v {- local tests as a proof of concept: -} testRounded = R.reifyPrecision 512 (\(_ :: Proxy p) -> show (logBase 10 2 :: R.Rounded R.TowardNearest p)) a :: MPFR a = withPrec 100 pi b :: MPFR b = withPrec 1000 1 aPrec = getPrecision a mpfrPlus :: MPFR -> MPFR -> MPFR mpfrPlus = liftRoundedToMPFR2 "mpfrPlus" (+) aPa = a `mpfrPlus` a aPb = a `mpfrPlus` b -- throws exception
michalkonecny/aern
aern-mpfr-rounded/src/Numeric/AERN/RealArithmetic/Basis/MPFR/Basics.hs
Haskell
bsd-3-clause
5,210
{-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} module Home.Routes where import Servant import Servant.HTML.Blaze import Text.Blaze.Html5 type HomeRoutes = Home type Home = Get '[HTML] Html
hectorhon/autotrace2
app/Home/Routes.hs
Haskell
bsd-3-clause
204
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. module Duckling.Distance.KO.Tests ( tests ) where import Prelude import Data.String import Test.Tasty import Duckling.Dimensions.Types import Duckling.Testing.Asserts import Duckling.Distance.KO.Corpus tests :: TestTree tests = testGroup "KO Tests" [ makeCorpusTest [Seal Distance] corpus ]
facebookincubator/duckling
tests/Duckling/Distance/KO/Tests.hs
Haskell
bsd-3-clause
507
{-# LANGUAGE MultiParamTypeClasses #-} -- | Internal only. Do Not Eat. module Tea.TeaState ( TeaState (..) , EventState (..) ) where import Data.Map(Map) import Data.Array(Array) import Tea.Screen(Screen) import Tea.Input(KeyCode) data TeaState = TS { _screen :: Screen, _eventState :: EventState, _fpsCap :: Int, _lastUpdate :: Int, _channels :: Map Int Int} data EventState = ES { keyCodes :: Array KeyCode Bool , keysDown :: Int }
liamoc/tea-hs
Tea/TeaState.hs
Haskell
bsd-3-clause
524
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} module Fragment.Bool.Rules.Kind.Infer.Common ( BoolInferKindConstraint , boolInferKindInput ) where import Data.Proxy (Proxy(..)) import Control.Lens (review, preview) import Ast.Kind import Ast.Type import Rules.Kind.Infer.Common import Fragment.KiBase.Ast.Kind import Fragment.Bool.Ast.Type type BoolInferKindConstraint e w s r m ki ty a i = ( BasicInferKindConstraint e w s r m ki ty a i , AsKiBase ki , AsTyBool ki ty ) boolInferKindInput :: BoolInferKindConstraint e w s r m ki ty a i => Proxy (MonadProxy e w s r m) -> Proxy i -> InferKindInput e w s r m (InferKindMonad m ki a i) ki ty a boolInferKindInput m i = InferKindInput [] [ InferKindBase $ inferTyBool m (Proxy :: Proxy ki) (Proxy :: Proxy ty) (Proxy :: Proxy a) i ] inferTyBool :: BoolInferKindConstraint e w s r m ki ty a i => Proxy (MonadProxy e w s r m) -> Proxy ki -> Proxy ty -> Proxy a -> Proxy i -> Type ki ty a -> Maybe (InferKindMonad m ki a i (Kind ki a)) inferTyBool pm pki pty pa pi ty = do _ <- preview _TyBool ty return . return . review _KiBase $ ()
dalaing/type-systems
src/Fragment/Bool/Rules/Kind/Infer/Common.hs
Haskell
bsd-3-clause
1,494
----------------------------------------------------------------------------- -- -- Pretty-printing assembly language -- -- (c) The University of Glasgow 1993-2005 -- ----------------------------------------------------------------------------- {-# OPTIONS_GHC -fno-warn-orphans #-} module PPC.Ppr ( pprNatCmmDecl, pprBasicBlock, pprSectionHeader, pprData, pprInstr, pprFormat, pprImm, pprDataItem, ) where import PPC.Regs import PPC.Instr import PPC.Cond import PprBase import Instruction import Format import Reg import RegClass import TargetReg import Cmm hiding (topInfoTable) import BlockId import CLabel import Unique ( pprUnique, Uniquable(..) ) import Platform import FastString import Outputable import DynFlags import Data.Word import Data.Bits -- ----------------------------------------------------------------------------- -- Printing this stuff out pprNatCmmDecl :: NatCmmDecl CmmStatics Instr -> SDoc pprNatCmmDecl (CmmData section dats) = pprSectionHeader section $$ pprDatas dats pprNatCmmDecl proc@(CmmProc top_info lbl _ (ListGraph blocks)) = case topInfoTable proc of Nothing -> sdocWithPlatform $ \platform -> case blocks of [] -> -- special case for split markers: pprLabel lbl blocks -> -- special case for code without info table: pprSectionHeader Text $$ (case platformArch platform of ArchPPC_64 ELF_V1 -> pprFunctionDescriptor lbl ArchPPC_64 ELF_V2 -> pprFunctionPrologue lbl _ -> pprLabel lbl) $$ -- blocks guaranteed not null, -- so label needed vcat (map (pprBasicBlock top_info) blocks) Just (Statics info_lbl _) -> sdocWithPlatform $ \platform -> (if platformHasSubsectionsViaSymbols platform then pprSectionHeader Text $$ ppr (mkDeadStripPreventer info_lbl) <> char ':' else empty) $$ vcat (map (pprBasicBlock top_info) blocks) $$ -- above: Even the first block gets a label, because with branch-chain -- elimination, it might be the target of a goto. (if platformHasSubsectionsViaSymbols platform then -- See Note [Subsections Via Symbols] text "\t.long " <+> ppr info_lbl <+> char '-' <+> ppr (mkDeadStripPreventer info_lbl) else empty) pprFunctionDescriptor :: CLabel -> SDoc pprFunctionDescriptor lab = pprGloblDecl lab $$ text ".section \".opd\",\"aw\"" $$ text ".align 3" $$ ppr lab <> char ':' $$ text ".quad ." <> ppr lab <> text ",.TOC.@tocbase,0" $$ text ".previous" $$ text ".type " <> ppr lab <> text ", @function" $$ char '.' <> ppr lab <> char ':' pprFunctionPrologue :: CLabel ->SDoc pprFunctionPrologue lab = pprGloblDecl lab $$ text ".type " <> ppr lab <> text ", @function" $$ ppr lab <> char ':' $$ text "0:\taddis\t" <> pprReg toc <> text ",12,.TOC.-0b@ha" $$ text "\taddi\t" <> pprReg toc <> char ',' <> pprReg toc <> text ",.TOC.-0b@l" $$ text "\t.localentry\t" <> ppr lab <> text ",.-" <> ppr lab pprBasicBlock :: BlockEnv CmmStatics -> NatBasicBlock Instr -> SDoc pprBasicBlock info_env (BasicBlock blockid instrs) = maybe_infotable $$ pprLabel (mkAsmTempLabel (getUnique blockid)) $$ vcat (map pprInstr instrs) where maybe_infotable = case mapLookup blockid info_env of Nothing -> empty Just (Statics info_lbl info) -> pprSectionHeader Text $$ vcat (map pprData info) $$ pprLabel info_lbl pprDatas :: CmmStatics -> SDoc pprDatas (Statics lbl dats) = vcat (pprLabel lbl : map pprData dats) pprData :: CmmStatic -> SDoc pprData (CmmString str) = pprASCII str pprData (CmmUninitialised bytes) = keyword <> int bytes where keyword = sdocWithPlatform $ \platform -> case platformOS platform of OSDarwin -> ptext (sLit ".space ") _ -> ptext (sLit ".skip ") pprData (CmmStaticLit lit) = pprDataItem lit pprGloblDecl :: CLabel -> SDoc pprGloblDecl lbl | not (externallyVisibleCLabel lbl) = empty | otherwise = ptext (sLit ".globl ") <> ppr lbl pprTypeAndSizeDecl :: CLabel -> SDoc pprTypeAndSizeDecl lbl = sdocWithPlatform $ \platform -> if platformOS platform == OSLinux && externallyVisibleCLabel lbl then ptext (sLit ".type ") <> ppr lbl <> ptext (sLit ", @object") else empty pprLabel :: CLabel -> SDoc pprLabel lbl = pprGloblDecl lbl $$ pprTypeAndSizeDecl lbl $$ (ppr lbl <> char ':') pprASCII :: [Word8] -> SDoc pprASCII str = vcat (map do1 str) $$ do1 0 where do1 :: Word8 -> SDoc do1 w = ptext (sLit "\t.byte\t") <> int (fromIntegral w) -- ----------------------------------------------------------------------------- -- pprInstr: print an 'Instr' instance Outputable Instr where ppr instr = pprInstr instr pprReg :: Reg -> SDoc pprReg r = case r of RegReal (RealRegSingle i) -> ppr_reg_no i RegReal (RealRegPair{}) -> panic "PPC.pprReg: no reg pairs on this arch" RegVirtual (VirtualRegI u) -> text "%vI_" <> pprUnique u RegVirtual (VirtualRegHi u) -> text "%vHi_" <> pprUnique u RegVirtual (VirtualRegF u) -> text "%vF_" <> pprUnique u RegVirtual (VirtualRegD u) -> text "%vD_" <> pprUnique u RegVirtual (VirtualRegSSE u) -> text "%vSSE_" <> pprUnique u where ppr_reg_no :: Int -> SDoc ppr_reg_no i = sdocWithPlatform $ \platform -> case platformOS platform of OSDarwin -> ptext (case i of { 0 -> sLit "r0"; 1 -> sLit "r1"; 2 -> sLit "r2"; 3 -> sLit "r3"; 4 -> sLit "r4"; 5 -> sLit "r5"; 6 -> sLit "r6"; 7 -> sLit "r7"; 8 -> sLit "r8"; 9 -> sLit "r9"; 10 -> sLit "r10"; 11 -> sLit "r11"; 12 -> sLit "r12"; 13 -> sLit "r13"; 14 -> sLit "r14"; 15 -> sLit "r15"; 16 -> sLit "r16"; 17 -> sLit "r17"; 18 -> sLit "r18"; 19 -> sLit "r19"; 20 -> sLit "r20"; 21 -> sLit "r21"; 22 -> sLit "r22"; 23 -> sLit "r23"; 24 -> sLit "r24"; 25 -> sLit "r25"; 26 -> sLit "r26"; 27 -> sLit "r27"; 28 -> sLit "r28"; 29 -> sLit "r29"; 30 -> sLit "r30"; 31 -> sLit "r31"; 32 -> sLit "f0"; 33 -> sLit "f1"; 34 -> sLit "f2"; 35 -> sLit "f3"; 36 -> sLit "f4"; 37 -> sLit "f5"; 38 -> sLit "f6"; 39 -> sLit "f7"; 40 -> sLit "f8"; 41 -> sLit "f9"; 42 -> sLit "f10"; 43 -> sLit "f11"; 44 -> sLit "f12"; 45 -> sLit "f13"; 46 -> sLit "f14"; 47 -> sLit "f15"; 48 -> sLit "f16"; 49 -> sLit "f17"; 50 -> sLit "f18"; 51 -> sLit "f19"; 52 -> sLit "f20"; 53 -> sLit "f21"; 54 -> sLit "f22"; 55 -> sLit "f23"; 56 -> sLit "f24"; 57 -> sLit "f25"; 58 -> sLit "f26"; 59 -> sLit "f27"; 60 -> sLit "f28"; 61 -> sLit "f29"; 62 -> sLit "f30"; 63 -> sLit "f31"; _ -> sLit "very naughty powerpc register" }) _ | i <= 31 -> int i -- GPRs | i <= 63 -> int (i-32) -- FPRs | otherwise -> ptext (sLit "very naughty powerpc register") pprFormat :: Format -> SDoc pprFormat x = ptext (case x of II8 -> sLit "b" II16 -> sLit "h" II32 -> sLit "w" II64 -> sLit "d" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprFormat: no match") pprCond :: Cond -> SDoc pprCond c = ptext (case c of { ALWAYS -> sLit ""; EQQ -> sLit "eq"; NE -> sLit "ne"; LTT -> sLit "lt"; GE -> sLit "ge"; GTT -> sLit "gt"; LE -> sLit "le"; LU -> sLit "lt"; GEU -> sLit "ge"; GU -> sLit "gt"; LEU -> sLit "le"; }) pprImm :: Imm -> SDoc pprImm (ImmInt i) = int i pprImm (ImmInteger i) = integer i pprImm (ImmCLbl l) = ppr l pprImm (ImmIndex l i) = ppr l <> char '+' <> int i pprImm (ImmLit s) = s pprImm (ImmFloat _) = ptext (sLit "naughty float immediate") pprImm (ImmDouble _) = ptext (sLit "naughty double immediate") pprImm (ImmConstantSum a b) = pprImm a <> char '+' <> pprImm b pprImm (ImmConstantDiff a b) = pprImm a <> char '-' <> lparen <> pprImm b <> rparen pprImm (LO i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "lo16(", pprImm i, rparen ] else pprImm i <> text "@l" pprImm (HI i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "hi16(", pprImm i, rparen ] else pprImm i <> text "@h" pprImm (HA i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then hcat [ text "ha16(", pprImm i, rparen ] else pprImm i <> text "@ha" pprImm (HIGHERA i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then panic "PPC.pprImm: highera not implemented on Darwin" else pprImm i <> text "@highera" pprImm (HIGHESTA i) = sdocWithPlatform $ \platform -> if platformOS platform == OSDarwin then panic "PPC.pprImm: highesta not implemented on Darwin" else pprImm i <> text "@highesta" pprAddr :: AddrMode -> SDoc pprAddr (AddrRegReg r1 r2) = pprReg r1 <+> ptext (sLit ", ") <+> pprReg r2 pprAddr (AddrRegImm r1 (ImmInt i)) = hcat [ int i, char '(', pprReg r1, char ')' ] pprAddr (AddrRegImm r1 (ImmInteger i)) = hcat [ integer i, char '(', pprReg r1, char ')' ] pprAddr (AddrRegImm r1 imm) = hcat [ pprImm imm, char '(', pprReg r1, char ')' ] pprSectionHeader :: Section -> SDoc pprSectionHeader seg = sdocWithPlatform $ \platform -> let osDarwin = platformOS platform == OSDarwin ppc64 = not $ target32Bit platform in case seg of Text -> text ".text\n\t.align 2" Data | ppc64 -> text ".data\n.align 3" | otherwise -> text ".data\n.align 2" ReadOnlyData | osDarwin -> text ".const\n\t.align 2" | ppc64 -> text ".section .rodata\n\t.align 3" | otherwise -> text ".section .rodata\n\t.align 2" RelocatableReadOnlyData | osDarwin -> text ".const_data\n\t.align 2" | ppc64 -> text ".data\n\t.align 3" | otherwise -> text ".data\n\t.align 2" UninitialisedData | osDarwin -> text ".const_data\n\t.align 2" | ppc64 -> text ".section .bss\n\t.align 3" | otherwise -> text ".section .bss\n\t.align 2" ReadOnlyData16 | osDarwin -> text ".const\n\t.align 4" | otherwise -> text ".section .rodata\n\t.align 4" OtherSection _ -> panic "PprMach.pprSectionHeader: unknown section" pprDataItem :: CmmLit -> SDoc pprDataItem lit = sdocWithDynFlags $ \dflags -> vcat (ppr_item (cmmTypeFormat $ cmmLitType dflags lit) lit dflags) where imm = litToImm lit archPPC_64 dflags = not $ target32Bit $ targetPlatform dflags ppr_item II8 _ _ = [ptext (sLit "\t.byte\t") <> pprImm imm] ppr_item II32 _ _ = [ptext (sLit "\t.long\t") <> pprImm imm] ppr_item II64 _ dflags | archPPC_64 dflags = [ptext (sLit "\t.quad\t") <> pprImm imm] ppr_item FF32 (CmmFloat r _) _ = let bs = floatToBytes (fromRational r) in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs ppr_item FF64 (CmmFloat r _) _ = let bs = doubleToBytes (fromRational r) in map (\b -> ptext (sLit "\t.byte\t") <> pprImm (ImmInt b)) bs ppr_item II16 _ _ = [ptext (sLit "\t.short\t") <> pprImm imm] ppr_item II64 (CmmInt x _) dflags | not(archPPC_64 dflags) = [ptext (sLit "\t.long\t") <> int (fromIntegral (fromIntegral (x `shiftR` 32) :: Word32)), ptext (sLit "\t.long\t") <> int (fromIntegral (fromIntegral x :: Word32))] ppr_item _ _ _ = panic "PPC.Ppr.pprDataItem: no match" pprInstr :: Instr -> SDoc pprInstr (COMMENT _) = empty -- nuke 'em {- pprInstr (COMMENT s) = if platformOS platform == OSLinux then ptext (sLit "# ") <> ftext s else ptext (sLit "; ") <> ftext s -} pprInstr (DELTA d) = pprInstr (COMMENT (mkFastString ("\tdelta = " ++ show d))) pprInstr (NEWBLOCK _) = panic "PprMach.pprInstr: NEWBLOCK" pprInstr (LDATA _ _) = panic "PprMach.pprInstr: LDATA" {- pprInstr (SPILL reg slot) = hcat [ ptext (sLit "\tSPILL"), char '\t', pprReg reg, comma, ptext (sLit "SLOT") <> parens (int slot)] pprInstr (RELOAD slot reg) = hcat [ ptext (sLit "\tRELOAD"), char '\t', ptext (sLit "SLOT") <> parens (int slot), comma, pprReg reg] -} pprInstr (LD fmt reg addr) = hcat [ char '\t', ptext (sLit "l"), ptext (case fmt of II8 -> sLit "bz" II16 -> sLit "hz" II32 -> sLit "wz" II64 -> sLit "d" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprInstr: no match" ), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (LDFAR fmt reg (AddrRegImm source off)) = sdocWithPlatform $ \platform -> vcat [ pprInstr (ADDIS (tmpReg platform) source (HA off)), pprInstr (LD fmt reg (AddrRegImm (tmpReg platform) (LO off))) ] pprInstr (LDFAR _ _ _) = panic "PPC.Ppr.pprInstr LDFAR: no match" pprInstr (LA fmt reg addr) = hcat [ char '\t', ptext (sLit "l"), ptext (case fmt of II8 -> sLit "ba" II16 -> sLit "ha" II32 -> sLit "wa" II64 -> sLit "d" FF32 -> sLit "fs" FF64 -> sLit "fd" _ -> panic "PPC.Ppr.pprInstr: no match" ), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (ST fmt reg addr) = hcat [ char '\t', ptext (sLit "st"), pprFormat fmt, case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', char '\t', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (STFAR fmt reg (AddrRegImm source off)) = sdocWithPlatform $ \platform -> vcat [ pprInstr (ADDIS (tmpReg platform) source (HA off)), pprInstr (ST fmt reg (AddrRegImm (tmpReg platform) (LO off))) ] pprInstr (STFAR _ _ _) = panic "PPC.Ppr.pprInstr STFAR: no match" pprInstr (STU fmt reg addr) = hcat [ char '\t', ptext (sLit "st"), pprFormat fmt, ptext (sLit "u\t"), case addr of AddrRegImm _ _ -> empty AddrRegReg _ _ -> char 'x', pprReg reg, ptext (sLit ", "), pprAddr addr ] pprInstr (LIS reg imm) = hcat [ char '\t', ptext (sLit "lis"), char '\t', pprReg reg, ptext (sLit ", "), pprImm imm ] pprInstr (LI reg imm) = hcat [ char '\t', ptext (sLit "li"), char '\t', pprReg reg, ptext (sLit ", "), pprImm imm ] pprInstr (MR reg1 reg2) | reg1 == reg2 = empty | otherwise = hcat [ char '\t', sdocWithPlatform $ \platform -> case targetClassOfReg platform reg1 of RcInteger -> ptext (sLit "mr") _ -> ptext (sLit "fmr"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (CMP fmt reg ri) = hcat [ char '\t', op, char '\t', pprReg reg, ptext (sLit ", "), pprRI ri ] where op = hcat [ ptext (sLit "cmp"), pprFormat fmt, case ri of RIReg _ -> empty RIImm _ -> char 'i' ] pprInstr (CMPL fmt reg ri) = hcat [ char '\t', op, char '\t', pprReg reg, ptext (sLit ", "), pprRI ri ] where op = hcat [ ptext (sLit "cmpl"), pprFormat fmt, case ri of RIReg _ -> empty RIImm _ -> char 'i' ] pprInstr (BCC cond blockid) = hcat [ char '\t', ptext (sLit "b"), pprCond cond, char '\t', ppr lbl ] where lbl = mkAsmTempLabel (getUnique blockid) pprInstr (BCCFAR cond blockid) = vcat [ hcat [ ptext (sLit "\tb"), pprCond (condNegate cond), ptext (sLit "\t$+8") ], hcat [ ptext (sLit "\tb\t"), ppr lbl ] ] where lbl = mkAsmTempLabel (getUnique blockid) pprInstr (JMP lbl) = hcat [ -- an alias for b that takes a CLabel char '\t', ptext (sLit "b"), char '\t', ppr lbl ] pprInstr (MTCTR reg) = hcat [ char '\t', ptext (sLit "mtctr"), char '\t', pprReg reg ] pprInstr (BCTR _ _) = hcat [ char '\t', ptext (sLit "bctr") ] pprInstr (BL lbl _) = hcat [ ptext (sLit "\tbl\t"), ppr lbl ] pprInstr (BCTRL _) = hcat [ char '\t', ptext (sLit "bctrl") ] pprInstr (ADD reg1 reg2 ri) = pprLogic (sLit "add") reg1 reg2 ri pprInstr (ADDI reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "addi"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (ADDIS reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "addis"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (ADDC reg1 reg2 reg3) = pprLogic (sLit "addc") reg1 reg2 (RIReg reg3) pprInstr (ADDE reg1 reg2 reg3) = pprLogic (sLit "adde") reg1 reg2 (RIReg reg3) pprInstr (SUBF reg1 reg2 reg3) = pprLogic (sLit "subf") reg1 reg2 (RIReg reg3) pprInstr (SUBFC reg1 reg2 reg3) = pprLogic (sLit "subfc") reg1 reg2 (RIReg reg3) pprInstr (SUBFE reg1 reg2 reg3) = pprLogic (sLit "subfe") reg1 reg2 (RIReg reg3) pprInstr (MULLD reg1 reg2 ri@(RIReg _)) = pprLogic (sLit "mulld") reg1 reg2 ri pprInstr (MULLW reg1 reg2 ri@(RIReg _)) = pprLogic (sLit "mullw") reg1 reg2 ri pprInstr (MULLD reg1 reg2 ri@(RIImm _)) = pprLogic (sLit "mull") reg1 reg2 ri pprInstr (MULLW reg1 reg2 ri@(RIImm _)) = pprLogic (sLit "mull") reg1 reg2 ri pprInstr (DIVW reg1 reg2 reg3) = pprLogic (sLit "divw") reg1 reg2 (RIReg reg3) pprInstr (DIVD reg1 reg2 reg3) = pprLogic (sLit "divd") reg1 reg2 (RIReg reg3) pprInstr (DIVWU reg1 reg2 reg3) = pprLogic (sLit "divwu") reg1 reg2 (RIReg reg3) pprInstr (DIVDU reg1 reg2 reg3) = pprLogic (sLit "divdu") reg1 reg2 (RIReg reg3) pprInstr (MULLW_MayOflo reg1 reg2 reg3) = vcat [ hcat [ ptext (sLit "\tmullwo\t"), pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprReg reg3 ], hcat [ ptext (sLit "\tmfxer\t"), pprReg reg1 ], hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "), pprReg reg1, ptext (sLit ", "), ptext (sLit "2, 31, 31") ] ] pprInstr (MULLD_MayOflo reg1 reg2 reg3) = vcat [ hcat [ ptext (sLit "\tmulldo\t"), pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprReg reg3 ], hcat [ ptext (sLit "\tmfxer\t"), pprReg reg1 ], hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "), pprReg reg1, ptext (sLit ", "), ptext (sLit "2, 31, 31") ] ] -- for some reason, "andi" doesn't exist. -- we'll use "andi." instead. pprInstr (AND reg1 reg2 (RIImm imm)) = hcat [ char '\t', ptext (sLit "andi."), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (AND reg1 reg2 ri) = pprLogic (sLit "and") reg1 reg2 ri pprInstr (OR reg1 reg2 ri) = pprLogic (sLit "or") reg1 reg2 ri pprInstr (XOR reg1 reg2 ri) = pprLogic (sLit "xor") reg1 reg2 ri pprInstr (ORIS reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "oris"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (XORIS reg1 reg2 imm) = hcat [ char '\t', ptext (sLit "xoris"), char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprImm imm ] pprInstr (EXTS fmt reg1 reg2) = hcat [ char '\t', ptext (sLit "exts"), pprFormat fmt, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (NEG reg1 reg2) = pprUnary (sLit "neg") reg1 reg2 pprInstr (NOT reg1 reg2) = pprUnary (sLit "not") reg1 reg2 pprInstr (SL fmt reg1 reg2 ri) = let op = case fmt of II32 -> "slw" II64 -> "sld" _ -> panic "PPC.Ppr.pprInstr: shift illegal size" in pprLogic (sLit op) reg1 reg2 (limitShiftRI fmt ri) pprInstr (SR II32 reg1 reg2 (RIImm (ImmInt i))) | i > 31 || i < 0 = -- Handle the case where we are asked to shift a 32 bit register by -- less than zero or more than 31 bits. We convert this into a clear -- of the destination register. -- Fixes ticket http://ghc.haskell.org/trac/ghc/ticket/5900 pprInstr (XOR reg1 reg2 (RIReg reg2)) pprInstr (SR fmt reg1 reg2 ri) = let op = case fmt of II32 -> "srw" II64 -> "srd" _ -> panic "PPC.Ppr.pprInstr: shift illegal size" in pprLogic (sLit op) reg1 reg2 (limitShiftRI fmt ri) pprInstr (SRA fmt reg1 reg2 ri) = let op = case fmt of II32 -> "sraw" II64 -> "srad" _ -> panic "PPC.Ppr.pprInstr: shift illegal size" in pprLogic (sLit op) reg1 reg2 (limitShiftRI fmt ri) pprInstr (RLWINM reg1 reg2 sh mb me) = hcat [ ptext (sLit "\trlwinm\t"), pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), int sh, ptext (sLit ", "), int mb, ptext (sLit ", "), int me ] pprInstr (FADD fmt reg1 reg2 reg3) = pprBinaryF (sLit "fadd") fmt reg1 reg2 reg3 pprInstr (FSUB fmt reg1 reg2 reg3) = pprBinaryF (sLit "fsub") fmt reg1 reg2 reg3 pprInstr (FMUL fmt reg1 reg2 reg3) = pprBinaryF (sLit "fmul") fmt reg1 reg2 reg3 pprInstr (FDIV fmt reg1 reg2 reg3) = pprBinaryF (sLit "fdiv") fmt reg1 reg2 reg3 pprInstr (FNEG reg1 reg2) = pprUnary (sLit "fneg") reg1 reg2 pprInstr (FCMP reg1 reg2) = hcat [ char '\t', ptext (sLit "fcmpu\tcr0, "), -- Note: we're using fcmpu, not fcmpo -- The difference is with fcmpo, compare with NaN is an invalid operation. -- We don't handle invalid fp ops, so we don't care pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprInstr (FCTIWZ reg1 reg2) = pprUnary (sLit "fctiwz") reg1 reg2 pprInstr (FCTIDZ reg1 reg2) = pprUnary (sLit "fctidz") reg1 reg2 pprInstr (FCFID reg1 reg2) = pprUnary (sLit "fcfid") reg1 reg2 pprInstr (FRSP reg1 reg2) = pprUnary (sLit "frsp") reg1 reg2 pprInstr (CRNOR dst src1 src2) = hcat [ ptext (sLit "\tcrnor\t"), int dst, ptext (sLit ", "), int src1, ptext (sLit ", "), int src2 ] pprInstr (MFCR reg) = hcat [ char '\t', ptext (sLit "mfcr"), char '\t', pprReg reg ] pprInstr (MFLR reg) = hcat [ char '\t', ptext (sLit "mflr"), char '\t', pprReg reg ] pprInstr (FETCHPC reg) = vcat [ ptext (sLit "\tbcl\t20,31,1f"), hcat [ ptext (sLit "1:\tmflr\t"), pprReg reg ] ] pprInstr (FETCHTOC reg lab) = vcat [ hcat [ ptext (sLit "0:\taddis\t"), pprReg reg, ptext (sLit ",12,.TOC.-0b@ha") ], hcat [ ptext (sLit "\taddi\t"), pprReg reg, char ',', pprReg reg, ptext (sLit ",.TOC.-0b@l") ], hcat [ ptext (sLit "\t.localentry\t"), ppr lab, ptext (sLit ",.-"), ppr lab] ] pprInstr LWSYNC = ptext (sLit "\tlwsync") pprInstr NOP = ptext (sLit "\tnop") pprInstr (UPDATE_SP fmt amount@(ImmInt offset)) | fits16Bits offset = vcat [ pprInstr (LD fmt r0 (AddrRegImm sp (ImmInt 0))), pprInstr (STU fmt r0 (AddrRegImm sp amount)) ] pprInstr (UPDATE_SP fmt amount) = sdocWithPlatform $ \platform -> let tmp = tmpReg platform in vcat [ pprInstr (LD fmt r0 (AddrRegImm sp (ImmInt 0))), pprInstr (ADDIS tmp sp (HA amount)), pprInstr (ADD tmp tmp (RIImm (LO amount))), pprInstr (STU fmt r0 (AddrRegReg sp tmp)) ] -- pprInstr _ = panic "pprInstr (ppc)" pprLogic :: LitString -> Reg -> Reg -> RI -> SDoc pprLogic op reg1 reg2 ri = hcat [ char '\t', ptext op, case ri of RIReg _ -> empty RIImm _ -> char 'i', char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprRI ri ] pprUnary :: LitString -> Reg -> Reg -> SDoc pprUnary op reg1 reg2 = hcat [ char '\t', ptext op, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2 ] pprBinaryF :: LitString -> Format -> Reg -> Reg -> Reg -> SDoc pprBinaryF op fmt reg1 reg2 reg3 = hcat [ char '\t', ptext op, pprFFormat fmt, char '\t', pprReg reg1, ptext (sLit ", "), pprReg reg2, ptext (sLit ", "), pprReg reg3 ] pprRI :: RI -> SDoc pprRI (RIReg r) = pprReg r pprRI (RIImm r) = pprImm r pprFFormat :: Format -> SDoc pprFFormat FF64 = empty pprFFormat FF32 = char 's' pprFFormat _ = panic "PPC.Ppr.pprFFormat: no match" -- limit immediate argument for shift instruction to range 0..63 -- for 64 bit size and 0..32 otherwise limitShiftRI :: Format -> RI -> RI limitShiftRI II64 (RIImm (ImmInt i)) | i > 63 || i < 0 = panic $ "PPC.Ppr: Shift by " ++ show i ++ " bits is not allowed." limitShiftRI II32 (RIImm (ImmInt i)) | i > 31 || i < 0 = panic $ "PPC.Ppr: 32 bit: Shift by " ++ show i ++ " bits is not allowed." limitShiftRI _ x = x
ml9951/ghc
compiler/nativeGen/PPC/Ppr.hs
Haskell
bsd-3-clause
28,362
module Stars where import Rumpus -- Golden Section Spiral (via http://www.softimageblog.com/archives/115) pointsOnSphere :: Int -> [V3 GLfloat] pointsOnSphere (fromIntegral -> n) = map (\k -> let y = k * off - 1 + (off / 2) r = sqrt (1 - y*y) phi = k * inc in V3 (cos phi * r) y (sin phi * r) ) [0..n] where inc = pi * (3 - sqrt 5) off = 2 / n start :: Start start = do -- We only take half the request points to get the upper hemisphere let numPoints = 400 :: Int points = reverse $ drop (numPoints `div` 2) $ pointsOnSphere numPoints hues = map ((/ fromIntegral numPoints) . fromIntegral) [0..numPoints] forM_ (zip3 [0..] points hues) $ \(i, pos, hue) -> spawnChild $ do myTransformType ==> AbsolutePose myShape ==> Sphere mySize ==> 0.001 myColor ==> colorHSL hue 0.8 0.8 myPose ==> position (pos * 500) myStart ==> do setDelayedAction (fromIntegral i * 0.05) $ setSize 5 myUpdate ==> do now <- (fromIntegral i +) <$> getNow let offset = V3 (sin now * 50) 0 0 setColor (colorHSL (now*0.5) 0.8 0.5) setPosition (offset + pos * 500)
lukexi/rumpus
pristine/Intro/Stars.hs
Haskell
bsd-3-clause
1,339
module RevealHs.Sample.Env where import Data.Time.Clock import Data.Time.Format import Data.Time.LocalTime today :: IO String today = do tz <- getCurrentTimeZone t <- fmap (utcToLocalTime tz) getCurrentTime return $ formatTime defaultTimeLocale (iso8601DateFormat Nothing) t
KenetJervet/reveal-hs
app/RevealHs/Sample/Env.hs
Haskell
bsd-3-clause
313
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving #-} module Math.InfoRetrieval.TFIDF ( Document(..) , Term(..) , Corpus , emptyCorpus , addDocument , removeDocument , FreqScaling(..) , tfidf , search ) where import Control.Lens import Data.Function (on) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as M import Data.HashSet (HashSet) import qualified Data.HashSet as S import Data.Hashable import Data.List import Data.Monoid import qualified Data.Text as T import Data.String (IsString) type Score = Double newtype Document = Doc Int deriving (Show, Eq, Hashable) newtype Term = Term T.Text deriving (Show, Eq, Hashable, IsString) data Corpus = Corpus { _cDocuments :: HashSet Document , _cTerms :: HashMap Term (HashMap Document Int) } makeLenses ''Corpus emptyCorpus :: Corpus emptyCorpus = Corpus S.empty M.empty addDocument :: Document -> [Term] -> Corpus -> Corpus addDocument d ts c = addDocument' d ts' c where ts' = foldl' (flip $ \t->M.insertWith (+) t 1) M.empty ts addDocument' :: Document -> HashMap Term Int -> Corpus -> Corpus addDocument' d ts c = cDocuments %~ S.insert d $ M.foldlWithKey' (\c term n->cTerms %~ M.insertWith (<>) term (M.singleton d n) $ c) c ts removeDocument :: Document -> Corpus -> Corpus removeDocument d = (cDocuments %~ S.delete d) . (cTerms %~ M.map (M.delete d)) idf :: Corpus -> Term -> Double idf c t = log $ docs / docsWithTerm where docs = realToFrac $ views cDocuments S.size c docsWithTerm = realToFrac $ M.size $ M.lookupDefault M.empty t (c^.cTerms) data FreqScaling = BoolScaling | LogScaling | LinearScaling | NormedScaling tf :: FreqScaling -> Corpus -> Term -> Document -> Score tf LinearScaling c t d = realToFrac $ M.lookupDefault 0 d $ M.lookupDefault M.empty t (c^.cTerms) tf LogScaling c t d = log $ tf LinearScaling c t d tf BoolScaling c t d = if tf LinearScaling c t d > 0 then 1 else 0 tfidf :: FreqScaling -> Corpus -> Term -> Document -> Score tfidf scaling c t d = tf scaling c t d * idf c t search :: FreqScaling -> Corpus -> Term -> [(Document, Score)] search scaling c t = sortBy (flip (compare `on` snd)) $ map (\d->(d, tfidf scaling c t d)) $ views cDocuments S.toList c
bgamari/tf-idf
Math/InfoRetrieval/TFIDF.hs
Haskell
bsd-3-clause
2,526
{-| Module : Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators Description : convenience operators and functions with default effort Description : re-export of parent's operators for easier direct import Copyright : (c) Michal Konecny License : BSD3 Maintainer : mikkonecny@gmail.com Stability : experimental Portability : portable Re-export of operators from the parent module for easier direct import. -} module Numeric.AERN.RealArithmetic.RefinementOrderRounding.Operators ( (>+<), (<+>), (>-<), (<->), (>*<), (<*>), (>/<), (</>), -- (>/+<), (</+>), (/+), (>^<), (<^>), (|>+<), (|<+>), (|+), (>+<|), (<+>|), (+|), (|>*<), (|<*>), (|*), (>*<|), (<*>|), (*|), (>/<|), (</>|), (/|) ) where import Numeric.AERN.RealArithmetic.RefinementOrderRounding
michalkonecny/aern
aern-real/src/Numeric/AERN/RealArithmetic/RefinementOrderRounding/Operators.hs
Haskell
bsd-3-clause
862
import Language.Haskell.Exts.Parser import Language.Haskell.Exts.Syntax import System.FilePath import System.Directory import Control.Monad import Data.Maybe import Data.List import Control.Applicative import Data.GraphViz.Types.Graph import Data.GraphViz.Commands.IO import Data.GraphViz.Types.Canonical import Data.Text.Lazy (pack) relations :: Module -> (ModuleName, [ModuleName]) relations (Module _ name _ _ _ imports _) = (name, map importModule imports) findHsFiles :: String -> IO [String] findHsFiles path = do allFiles <- getDirectoryContents path let files = map (path </>) $ filter (flip notElem $ [".", ".."]) allFiles let hsFiles = filter (\x -> takeExtension x == ".hs") files directories <- filterM doesDirectoryExist files ((hsFiles ++) . concat) <$> mapM findHsFiles directories relationsFrom :: FilePath -> IO (Maybe (ModuleName, [ModuleName])) relationsFrom fileName = do src <- readFile fileName -- (parseFileWithMode (defaultParseMode { fixities = [] } ) case parseModuleWithMode (defaultParseMode { fixities = Just [] }) src of ParseOk parsed -> return $ Just (relations parsed) ParseFailed _ _ -> return Nothing --mkGraph nodes edges namesFromModules :: [ModuleName] -> [String] namesFromModules ((ModuleName name) : t) = [name] ++ namesFromModules t namesFromModules _ = [] nodesFromRelations :: [(ModuleName, [ModuleName])] -> [String] nodesFromRelations ((ModuleName name, imports) : t) = [name] ++ namesFromModules imports ++ nodesFromRelations t nodesFromRelations _ = [] edgesFromRelation :: (ModuleName, [ModuleName]) -> [(String, String)] edgesFromRelation (ModuleName name, imports) = zip (repeat name) (namesFromModules imports) edgesFromRelations :: [(ModuleName, [ModuleName])] -> [(String, String)] edgesFromRelations (h : t) = (edgesFromRelation h) ++ edgesFromRelations t edgesFromRelations _ = [] dotNodes :: [String] -> [DotNode String] dotNodes nodes = map (\nodeName -> DotNode nodeName []) nodes dotEdges :: [(String, String)] -> [DotEdge String] dotEdges edges = map (\(a, b) -> DotEdge a b []) edges main :: IO() main = do files <- findHsFiles "." maybeRelations <- mapM relationsFrom files let found = catMaybes maybeRelations let nodes = sort $ nub $ nodesFromRelations $ found let edges = sort $ nub $ edgesFromRelations $ found let graph = DotGraph False True (Just (Str (pack "h2dot"))) (DotStmts [] [] (dotNodes nodes) (dotEdges edges)) writeDotFile "hs2dot.dot" graph
bneijt/hs2dot
src/main/Main.hs
Haskell
bsd-3-clause
2,509
{-# LANGUAGE CPP #-} module Database.PostgreSQL.PQTypes.Internal.Monad ( DBT_(..) , DBT , runDBT , mapDBT ) where import Control.Applicative import Control.Concurrent.MVar import Control.Monad.Base import Control.Monad.Catch import Control.Monad.Error.Class import Control.Monad.Reader.Class import Control.Monad.State.Strict import Control.Monad.Trans.Control import Control.Monad.Writer.Class import qualified Control.Monad.Trans.State.Strict as S import qualified Control.Monad.Fail as MF import Database.PostgreSQL.PQTypes.Class import Database.PostgreSQL.PQTypes.Internal.Connection import Database.PostgreSQL.PQTypes.Internal.Error import Database.PostgreSQL.PQTypes.Internal.Notification import Database.PostgreSQL.PQTypes.Internal.Query import Database.PostgreSQL.PQTypes.Internal.State import Database.PostgreSQL.PQTypes.SQL import Database.PostgreSQL.PQTypes.SQL.Class import Database.PostgreSQL.PQTypes.Transaction import Database.PostgreSQL.PQTypes.Transaction.Settings import Database.PostgreSQL.PQTypes.Utils type InnerDBT m = StateT (DBState m) -- | Monad transformer for adding database -- interaction capabilities to the underlying monad. newtype DBT_ m n a = DBT { unDBT :: InnerDBT m n a } deriving (Alternative, Applicative, Functor, Monad, MF.MonadFail, MonadBase b, MonadCatch, MonadIO, MonadMask, MonadPlus, MonadThrow, MonadTrans) type DBT m = DBT_ m m -- | Evaluate monadic action with supplied -- connection source and transaction settings. {-# INLINABLE runDBT #-} runDBT :: (MonadBase IO m, MonadMask m) => ConnectionSourceM m -> TransactionSettings -> DBT m a -> m a runDBT cs ts m = withConnection cs $ \conn -> do evalStateT action $ DBState { dbConnection = conn , dbConnectionSource = cs , dbTransactionSettings = ts , dbLastQuery = SomeSQL (mempty::SQL) , dbRecordLastQuery = True , dbQueryResult = Nothing } where action = unDBT $ if tsAutoTransaction ts then withTransaction' (ts { tsAutoTransaction = False }) m else m -- | Transform the underlying monad. {-# INLINABLE mapDBT #-} mapDBT :: (DBState n -> DBState m) -> (m (a, DBState m) -> n (b, DBState n)) -> DBT m a -> DBT n b mapDBT f g m = DBT . StateT $ g . runStateT (unDBT m) . f ---------------------------------------- instance (m ~ n, MonadBase IO m, MonadMask m) => MonadDB (DBT_ m n) where runQuery sql = DBT . StateT $ liftBase . runQueryIO sql getLastQuery = DBT . gets $ dbLastQuery withFrozenLastQuery callback = DBT . StateT $ \st -> do let st' = st { dbRecordLastQuery = False } (x, st'') <- runStateT (unDBT callback) st' pure (x, st'' { dbRecordLastQuery = dbRecordLastQuery st }) getConnectionStats = do mconn <- DBT $ liftBase . readMVar =<< gets (unConnection . dbConnection) case mconn of Nothing -> throwDB $ HPQTypesError "getConnectionStats: no connection" Just cd -> return $ cdStats cd getQueryResult = DBT . gets $ \st -> dbQueryResult st clearQueryResult = DBT . modify $ \st -> st { dbQueryResult = Nothing } getTransactionSettings = DBT . gets $ dbTransactionSettings setTransactionSettings ts = DBT . modify $ \st -> st { dbTransactionSettings = ts } getNotification time = DBT . StateT $ \st -> (, st) <$> liftBase (getNotificationIO st time) withNewConnection m = DBT . StateT $ \st -> do let cs = dbConnectionSource st ts = dbTransactionSettings st res <- runDBT cs ts m return (res, st) {-# INLINABLE runQuery #-} {-# INLINABLE getLastQuery #-} {-# INLINABLE withFrozenLastQuery #-} {-# INLINABLE getConnectionStats #-} {-# INLINABLE getQueryResult #-} {-# INLINABLE clearQueryResult #-} {-# INLINABLE getTransactionSettings #-} {-# INLINABLE setTransactionSettings #-} {-# INLINABLE getNotification #-} {-# INLINABLE withNewConnection #-} ---------------------------------------- instance MonadTransControl (DBT_ m) where type StT (DBT_ m) a = StT (InnerDBT m) a liftWith = defaultLiftWith DBT unDBT restoreT = defaultRestoreT DBT {-# INLINE liftWith #-} {-# INLINE restoreT #-} instance (m ~ n, MonadBaseControl b m) => MonadBaseControl b (DBT_ m n) where type StM (DBT_ m n) a = ComposeSt (DBT_ m) m a liftBaseWith = defaultLiftBaseWith restoreM = defaultRestoreM {-# INLINE liftBaseWith #-} {-# INLINE restoreM #-} instance (m ~ n, MonadError e m) => MonadError e (DBT_ m n) where throwError = lift . throwError catchError m h = DBT $ S.liftCatch catchError (unDBT m) (unDBT . h) {-# INLINE throwError #-} {-# INLINE catchError #-} instance (m ~ n, MonadReader r m) => MonadReader r (DBT_ m n) where ask = lift ask local f = mapDBT id (local f) reader = lift . reader {-# INLINE ask #-} {-# INLINE local #-} {-# INLINE reader #-} instance (m ~ n, MonadState s m) => MonadState s (DBT_ m n) where get = lift get put = lift . put state = lift . state {-# INLINE get #-} {-# INLINE put #-} {-# INLINE state #-} instance (m ~ n, MonadWriter w m) => MonadWriter w (DBT_ m n) where writer = lift . writer tell = lift . tell listen = DBT . S.liftListen listen . unDBT pass = DBT . S.liftPass pass . unDBT {-# INLINE writer #-} {-# INLINE tell #-} {-# INLINE listen #-} {-# INLINE pass #-}
scrive/hpqtypes
src/Database/PostgreSQL/PQTypes/Internal/Monad.hs
Haskell
bsd-3-clause
5,271
{-# LANGUAGE EmptyDataDecls, FlexibleContexts, FlexibleInstances, RankNTypes #-} {-# LANGUAGE TypeSynonymInstances, UndecidableInstances #-} module Main where import Data.Constraint.Unsafely import Data.Proxy class Semigroup a where -- | binary operation which satisifies associative law: -- @(a .+. b) .+. c == a .+. (b .+. c)@ (.+.) :: a -> a -> a infixl 6 .+. -- | 'Int', 'Integer' and 'Rational' satisfies associative law. instance Semigroup Int where (.+.) = (+) instance Semigroup Integer where (.+.) = (+) instance Semigroup Rational where (.+.) = (+) -- | Dummy type indicating the computation which may /unsafely/ violates associative law. data ViolateAssocLaw -- | Helper function to use /unsafe/ instance for @Semigroup@ unsafelyViolate :: (Unsafely ViolateAssocLaw => a) -> a unsafelyViolate = unsafely (Proxy :: Proxy ViolateAssocLaw) -- | 'Double' doesn't satsfies associative law: -- -- > (1.9546929672907305 + 2.0) + 0.14197132377740074 == 4.096664291068132 -- > 1.9546929672907305 + (2.0 + 0.14197132377740074) == 4.096664291068131 -- -- But sometimes there is the case the instance for @Semigroup@ for Double is required. -- So we use @Unsafely@ to mark this instance is somewhat unsafe. instance Unsafely ViolateAssocLaw => Semigroup Double where (.+.) = (+) main :: IO () main = do print (1 .+. 2 :: Int) unsafelyViolate $ print (3 .+. 4 :: Double) -- You cannot done as above, if you drop @unsafelyViolate@. -- Uncommenting following line causes type error. -- print (5 .+. 6 :: Double)
konn/unsafely
examples/semigroup.hs
Haskell
bsd-3-clause
1,564
{- Author: George Karachalias <george.karachalias@cs.kuleuven.be> Haskell expressions (as used by the pattern matching checker) and utilities. -} {-# LANGUAGE CPP #-} module PmExpr ( PmExpr(..), PmLit(..), SimpleEq, ComplexEq, toComplex, eqPmLit, truePmExpr, falsePmExpr, isTruePmExpr, isFalsePmExpr, isNotPmExprOther, lhsExprToPmExpr, hsExprToPmExpr, substComplexEq, filterComplex, pprPmExprWithParens, runPmPprM ) where #include "HsVersions.h" import HsSyn import Id import Name import NameSet import DataCon import TysWiredIn import Outputable import Util import SrcLoc #if __GLASGOW_HASKELL__ < 709 import Data.Functor ((<$>)) #endif import Data.Maybe (mapMaybe) import Data.List (groupBy, sortBy, nubBy) import Control.Monad.Trans.State.Lazy {- %************************************************************************ %* * Lifted Expressions %* * %************************************************************************ -} {- Note [PmExprOther in PmExpr] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Since there is no plan to extend the (currently pretty naive) term oracle in the near future, instead of playing with the verbose (HsExpr Id), we lift it to PmExpr. All expressions the term oracle does not handle are wrapped by the constructor PmExprOther. Note that we do not perform substitution in PmExprOther. Because of this, we do not even print PmExprOther, since they may refer to variables that are otherwise substituted away. -} -- ---------------------------------------------------------------------------- -- ** Types -- | Lifted expressions for pattern match checking. data PmExpr = PmExprVar Name | PmExprCon DataCon [PmExpr] | PmExprLit PmLit | PmExprEq PmExpr PmExpr -- Syntactic equality | PmExprOther (HsExpr Id) -- Note [PmExprOther in PmExpr] -- | Literals (simple and overloaded ones) for pattern match checking. data PmLit = PmSLit HsLit -- simple | PmOLit Bool {- is it negated? -} (HsOverLit Id) -- overloaded -- | Equality between literals for pattern match checking. eqPmLit :: PmLit -> PmLit -> Bool eqPmLit (PmSLit l1) (PmSLit l2) = l1 == l2 eqPmLit (PmOLit b1 l1) (PmOLit b2 l2) = b1 == b2 && l1 == l2 -- See Note [Undecidable Equality for Overloaded Literals] eqPmLit _ _ = False {- Note [Undecidable Equality for Overloaded Literals] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Equality on overloaded literals is undecidable in the general case. Consider the following example: instance Num Bool where ... fromInteger 0 = False -- C-like representation of booleans fromInteger _ = True f :: Bool -> () f 1 = () -- Clause A f 2 = () -- Clause B Clause B is redundant but to detect this, we should be able to solve the constraint: False ~ (fromInteger 2 ~ fromInteger 1) which means that we have to look through function `fromInteger`, whose implementation could be anything. This poses difficulties for: 1. The expressive power of the check. We cannot expect a reasonable implementation of pattern matching to detect that fromInteger 2 ~ fromInteger 1 is True, unless we unfold function fromInteger. This puts termination at risk and is undecidable in the general case. 2. Performance. Having an unresolved constraint False ~ (fromInteger 2 ~ fromInteger 1) lying around could become expensive really fast. Ticket #11161 illustrates how heavy use of overloaded literals can generate plenty of those constraints, effectively undermining the term oracle's performance. 3. Error nessages/Warnings. What should our message for `f` above be? A reasonable approach would be to issue: Pattern matches are (potentially) redundant: f 2 = ... under the assumption that 1 == 2 but seems to complex and confusing for the user. We choose to treat overloaded literals that look different as different. The impact of this is the following: * Redundancy checking is rather conservative, since it cannot see that clause B above is redundant. * We have instant equality check for overloaded literals (we do not rely on the term oracle which is rather expensive, both in terms of performance and memory). This significantly improves the performance of functions `covered` `uncovered` and `divergent` in deSugar/Check.hs and effectively addresses #11161. * The warnings issued are simpler. * We do not play on the safe side, strictly speaking. The assumption that 1 /= 2 makes the redundancy check more conservative but at the same time makes its dual (exhaustiveness check) unsafe. This we can live with, mainly for two reasons: 1. At the moment we do not use the results of the check during compilation where this would be a disaster (could result in runtime errors even if our function was deemed exhaustive). 2. Pattern matcing on literals can never be considered exhaustive unless we have a catch-all clause. Hence, this assumption affects mainly the appearance of the warnings and is, in practice safe. -} nubPmLit :: [PmLit] -> [PmLit] nubPmLit = nubBy eqPmLit -- | Term equalities type SimpleEq = (Id, PmExpr) -- We always use this orientation type ComplexEq = (PmExpr, PmExpr) -- | Lift a `SimpleEq` to a `ComplexEq` toComplex :: SimpleEq -> ComplexEq toComplex (x,e) = (PmExprVar (idName x), e) -- | Expression `True' truePmExpr :: PmExpr truePmExpr = PmExprCon trueDataCon [] -- | Expression `False' falsePmExpr :: PmExpr falsePmExpr = PmExprCon falseDataCon [] -- ---------------------------------------------------------------------------- -- ** Predicates on PmExpr -- | Check if an expression is lifted or not isNotPmExprOther :: PmExpr -> Bool isNotPmExprOther (PmExprOther _) = False isNotPmExprOther _expr = True -- | Check whether a literal is negated isNegatedPmLit :: PmLit -> Bool isNegatedPmLit (PmOLit b _) = b isNegatedPmLit _other_lit = False -- | Check whether a PmExpr is syntactically equal to term `True'. isTruePmExpr :: PmExpr -> Bool isTruePmExpr (PmExprCon c []) = c == trueDataCon isTruePmExpr _other_expr = False -- | Check whether a PmExpr is syntactically equal to term `False'. isFalsePmExpr :: PmExpr -> Bool isFalsePmExpr (PmExprCon c []) = c == falseDataCon isFalsePmExpr _other_expr = False -- | Check whether a PmExpr is syntactically e isNilPmExpr :: PmExpr -> Bool isNilPmExpr (PmExprCon c _) = c == nilDataCon isNilPmExpr _other_expr = False -- | Check whether a PmExpr is syntactically equal to (x == y). -- Since (==) is overloaded and can have an arbitrary implementation, we use -- the PmExprEq constructor to represent only equalities with non-overloaded -- literals where it coincides with a syntactic equality check. isPmExprEq :: PmExpr -> Maybe (PmExpr, PmExpr) isPmExprEq (PmExprEq e1 e2) = Just (e1,e2) isPmExprEq _other_expr = Nothing -- | Check if a DataCon is (:). isConsDataCon :: DataCon -> Bool isConsDataCon con = consDataCon == con -- ---------------------------------------------------------------------------- -- ** Substitution in PmExpr -- | We return a boolean along with the expression. Hence, if substitution was -- a no-op, we know that the expression still cannot progress. substPmExpr :: Name -> PmExpr -> PmExpr -> (PmExpr, Bool) substPmExpr x e1 e = case e of PmExprVar z | x == z -> (e1, True) | otherwise -> (e, False) PmExprCon c ps -> let (ps', bs) = mapAndUnzip (substPmExpr x e1) ps in (PmExprCon c ps', or bs) PmExprEq ex ey -> let (ex', bx) = substPmExpr x e1 ex (ey', by) = substPmExpr x e1 ey in (PmExprEq ex' ey', bx || by) _other_expr -> (e, False) -- The rest are terminals (We silently ignore -- Other). See Note [PmExprOther in PmExpr] -- | Substitute in a complex equality. We return (Left eq) if the substitution -- affected the equality or (Right eq) if nothing happened. substComplexEq :: Name -> PmExpr -> ComplexEq -> Either ComplexEq ComplexEq substComplexEq x e (ex, ey) | bx || by = Left (ex', ey') | otherwise = Right (ex', ey') where (ex', bx) = substPmExpr x e ex (ey', by) = substPmExpr x e ey -- ----------------------------------------------------------------------- -- ** Lift source expressions (HsExpr Id) to PmExpr lhsExprToPmExpr :: LHsExpr Id -> PmExpr lhsExprToPmExpr (L _ e) = hsExprToPmExpr e hsExprToPmExpr :: HsExpr Id -> PmExpr hsExprToPmExpr (HsVar x) = PmExprVar (idName (unLoc x)) hsExprToPmExpr (HsOverLit olit) = PmExprLit (PmOLit False olit) hsExprToPmExpr (HsLit lit) = PmExprLit (PmSLit lit) hsExprToPmExpr e@(NegApp _ neg_e) | PmExprLit (PmOLit False ol) <- synExprToPmExpr neg_e = PmExprLit (PmOLit True ol) | otherwise = PmExprOther e hsExprToPmExpr (HsPar (L _ e)) = hsExprToPmExpr e hsExprToPmExpr e@(ExplicitTuple ps boxity) | all tupArgPresent ps = PmExprCon tuple_con tuple_args | otherwise = PmExprOther e where tuple_con = tupleDataCon boxity (length ps) tuple_args = [ lhsExprToPmExpr e | L _ (Present e) <- ps ] hsExprToPmExpr e@(ExplicitList _elem_ty mb_ol elems) | Nothing <- mb_ol = foldr cons nil (map lhsExprToPmExpr elems) | otherwise = PmExprOther e {- overloaded list: No PmExprApp -} where cons x xs = PmExprCon consDataCon [x,xs] nil = PmExprCon nilDataCon [] hsExprToPmExpr (ExplicitPArr _elem_ty elems) = PmExprCon (parrFakeCon (length elems)) (map lhsExprToPmExpr elems) -- we want this but we would have to make evrything monadic :/ -- ./compiler/deSugar/DsMonad.hs:397:dsLookupDataCon :: Name -> DsM DataCon -- -- hsExprToPmExpr (RecordCon c _ binds) = do -- con <- dsLookupDataCon (unLoc c) -- args <- mapM lhsExprToPmExpr (hsRecFieldsArgs binds) -- return (PmExprCon con args) hsExprToPmExpr e@(RecordCon _ _ _ _) = PmExprOther e hsExprToPmExpr (HsTick _ e) = lhsExprToPmExpr e hsExprToPmExpr (HsBinTick _ _ e) = lhsExprToPmExpr e hsExprToPmExpr (HsTickPragma _ _ _ e) = lhsExprToPmExpr e hsExprToPmExpr (HsSCC _ _ e) = lhsExprToPmExpr e hsExprToPmExpr (HsCoreAnn _ _ e) = lhsExprToPmExpr e hsExprToPmExpr (ExprWithTySig e _) = lhsExprToPmExpr e hsExprToPmExpr (ExprWithTySigOut e _) = lhsExprToPmExpr e hsExprToPmExpr (HsWrap _ e) = hsExprToPmExpr e hsExprToPmExpr e = PmExprOther e -- the rest are not handled by the oracle synExprToPmExpr :: SyntaxExpr Id -> PmExpr synExprToPmExpr = hsExprToPmExpr . syn_expr -- ignore the wrappers {- %************************************************************************ %* * Pretty printing %* * %************************************************************************ -} {- 1. Literals ~~~~~~~~~~~~~~ Starting with a function definition like: f :: Int -> Bool f 5 = True f 6 = True The uncovered set looks like: { var |> False == (var == 5), False == (var == 6) } Yet, we would like to print this nicely as follows: x , where x not one of {5,6} Function `filterComplex' takes the set of residual constraints and packs together the negative constraints that refer to the same variable so we can do just this. Since these variables will be shown to the programmer, we also give them better names (t1, t2, ..), hence the SDoc in PmNegLitCt. 2. Residual Constraints ~~~~~~~~~~~~~~~~~~~~~~~ Unhandled constraints that refer to HsExpr are typically ignored by the solver (it does not even substitute in HsExpr so they are even printed as wildcards). Additionally, the oracle returns a substitution if it succeeds so we apply this substitution to the vectors before printing them out (see function `pprOne' in Check.hs) to be more precice. -} -- ----------------------------------------------------------------------------- -- ** Transform residual constraints in appropriate form for pretty printing type PmNegLitCt = (Name, (SDoc, [PmLit])) filterComplex :: [ComplexEq] -> [PmNegLitCt] filterComplex = zipWith rename nameList . map mkGroup . groupBy name . sortBy order . mapMaybe isNegLitCs where order x y = compare (fst x) (fst y) name x y = fst x == fst y mkGroup l = (fst (head l), nubPmLit $ map snd l) rename new (old, lits) = (old, (new, lits)) isNegLitCs (e1,e2) | isFalsePmExpr e1, Just (x,y) <- isPmExprEq e2 = isNegLitCs' x y | isFalsePmExpr e2, Just (x,y) <- isPmExprEq e1 = isNegLitCs' x y | otherwise = Nothing isNegLitCs' (PmExprVar x) (PmExprLit l) = Just (x, l) isNegLitCs' (PmExprLit l) (PmExprVar x) = Just (x, l) isNegLitCs' _ _ = Nothing -- Try nice names p,q,r,s,t before using the (ugly) t_i nameList :: [SDoc] nameList = map text ["p","q","r","s","t"] ++ [ text ('t':show u) | u <- [(0 :: Int)..] ] -- ---------------------------------------------------------------------------- runPmPprM :: PmPprM a -> [PmNegLitCt] -> (a, [(SDoc,[PmLit])]) runPmPprM m lit_env = (result, mapMaybe is_used lit_env) where (result, (_lit_env, used)) = runState m (lit_env, emptyNameSet) is_used (x,(name, lits)) | elemNameSet x used = Just (name, lits) | otherwise = Nothing type PmPprM a = State ([PmNegLitCt], NameSet) a -- (the first part of the state is read only. make it a reader?) addUsed :: Name -> PmPprM () addUsed x = modify (\(negated, used) -> (negated, extendNameSet used x)) checkNegation :: Name -> PmPprM (Maybe SDoc) -- the clean name if it is negated checkNegation x = do negated <- gets fst return $ case lookup x negated of Just (new, _) -> Just new Nothing -> Nothing -- | Pretty print a pmexpr, but remember to prettify the names of the variables -- that refer to neg-literals. The ones that cannot be shown are printed as -- underscores. pprPmExpr :: PmExpr -> PmPprM SDoc pprPmExpr (PmExprVar x) = do mb_name <- checkNegation x case mb_name of Just name -> addUsed x >> return name Nothing -> return underscore pprPmExpr (PmExprCon con args) = pprPmExprCon con args pprPmExpr (PmExprLit l) = return (ppr l) pprPmExpr (PmExprEq _ _) = return underscore -- don't show pprPmExpr (PmExprOther _) = return underscore -- don't show needsParens :: PmExpr -> Bool needsParens (PmExprVar {}) = False needsParens (PmExprLit l) = isNegatedPmLit l needsParens (PmExprEq {}) = False -- will become a wildcard needsParens (PmExprOther {}) = False -- will become a wildcard needsParens (PmExprCon c es) | isTupleDataCon c || isPArrFakeCon c || isConsDataCon c || null es = False | otherwise = True pprPmExprWithParens :: PmExpr -> PmPprM SDoc pprPmExprWithParens expr | needsParens expr = parens <$> pprPmExpr expr | otherwise = pprPmExpr expr pprPmExprCon :: DataCon -> [PmExpr] -> PmPprM SDoc pprPmExprCon con args | isTupleDataCon con = mkTuple <$> mapM pprPmExpr args | isPArrFakeCon con = mkPArr <$> mapM pprPmExpr args | isConsDataCon con = pretty_list | dataConIsInfix con = case args of [x, y] -> do x' <- pprPmExprWithParens x y' <- pprPmExprWithParens y return (x' <+> ppr con <+> y') -- can it be infix but have more than two arguments? list -> pprPanic "pprPmExprCon:" (ppr list) | null args = return (ppr con) | otherwise = do args' <- mapM pprPmExprWithParens args return (fsep (ppr con : args')) where mkTuple, mkPArr :: [SDoc] -> SDoc mkTuple = parens . fsep . punctuate comma mkPArr = paBrackets . fsep . punctuate comma -- lazily, to be used in the list case only pretty_list :: PmPprM SDoc pretty_list = case isNilPmExpr (last list) of True -> brackets . fsep . punctuate comma <$> mapM pprPmExpr (init list) False -> parens . hcat . punctuate colon <$> mapM pprPmExpr list list = list_elements args list_elements [x,y] | PmExprCon c es <- y, nilDataCon == c = ASSERT(null es) [x,y] | PmExprCon c es <- y, consDataCon == c = x : list_elements es | otherwise = [x,y] list_elements list = pprPanic "list_elements:" (ppr list) instance Outputable PmLit where ppr (PmSLit l) = pmPprHsLit l ppr (PmOLit neg l) = (if neg then char '-' else empty) <> ppr l -- not really useful for pmexprs per se instance Outputable PmExpr where ppr e = fst $ runPmPprM (pprPmExpr e) []
GaloisInc/halvm-ghc
compiler/deSugar/PmExpr.hs
Haskell
bsd-3-clause
16,939
{-# LANGUAGE CPP #-} -- | Contains commons utilities when defining your own widget module Glazier.React.ReactDOM ( renderDOM ) where import Glazier.React.ReactElement import qualified JS.DOM.EventTarget.Node.Element as DOM -- | Using a React Element (first arg) give React rendering control over a DOM element (second arg). -- This should only be called for the topmost component. renderDOM :: ReactElement -> DOM.Element -> IO () renderDOM = js_render #ifdef __GHCJS__ foreign import javascript unsafe "hgr$ReactDOM().render($1, $2);" js_render :: ReactElement -> DOM.Element -> IO () #else js_render :: ReactElement -> DOM.Element -> IO () js_render _ _ = pure () #endif
louispan/glazier-react
src/Glazier/React/ReactDOM.hs
Haskell
bsd-3-clause
689
-- | This module supplies the types that are used in interacting with -- and parsing from the database. module Database.Influx.Types ( module Database.Influx.Types.Core , module Database.Influx.Types.FromInfluxPoint ) where import Database.Influx.Types.Core import Database.Influx.Types.FromInfluxPoint
factisresearch/influx
src/Database/Influx/Types.hs
Haskell
bsd-3-clause
316
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PackageImports #-} {-# LANGUAGE UnicodeSyntax #-} {-| [@ISO639-1@] fi [@ISO639-2B@] fin [@ISO639-3@] fin [@Native name@] suomi [@English name@] Finnish -} module Text.Numeral.Language.FIN ( -- * Language entry entry -- * Inflection , Inflection -- * Conversions , cardinal , ordinal -- * Structure , struct -- * Bounds , bounds ) where ------------------------------------------------------------------------------- -- Imports ------------------------------------------------------------------------------- import "base" Data.Bool ( otherwise ) import "base" Data.Function ( ($), fix, flip ) import "base" Data.Maybe ( Maybe(Just) ) import "base" Prelude ( Num, Integral, (-), negate, divMod ) import "base-unicode-symbols" Data.Bool.Unicode ( (∧) ) import "base-unicode-symbols" Data.Eq.Unicode ( (≡) ) import "base-unicode-symbols" Data.Function.Unicode ( (∘) ) import "base-unicode-symbols" Data.Ord.Unicode ( (≤) ) import qualified "containers" Data.Map as M ( fromList, lookup ) import "this" Text.Numeral import qualified "this" Text.Numeral.BigNum as BN import qualified "this" Text.Numeral.Exp as E import qualified "this" Text.Numeral.Grammar as G import "this" Text.Numeral.Misc ( dec ) import "this" Text.Numeral.Entry import "text" Data.Text ( Text ) ------------------------------------------------------------------------------- -- FIN ------------------------------------------------------------------------------- entry ∷ Entry entry = emptyEntry { entIso639_1 = Just "fi" , entIso639_2 = ["fin"] , entIso639_3 = Just "fin" , entNativeNames = ["suomi"] , entEnglishName = Just "Finnish" , entCardinal = Just Conversion { toNumeral = cardinal , toStructure = struct } , entOrdinal = Just Conversion { toNumeral = ordinal , toStructure = struct } } type Inflection i = ( G.Singular i , G.Plural i , G.Abessive i , G.Accusative i , G.Comitative i , G.Delative i , G.Distributive i , G.DistributiveTemporal i , G.Essive i , G.Genitive i , G.Instructive i , G.Lative i , G.LocativeInessive i , G.LocativeElative i , G.LocativeIllative i , G.LocativeAdessive i , G.LocativeAblative i , G.LocativeAllative i , G.Multiplicative i , G.Nominative i , G.Partitive i , G.Sublative i , G.SuperEssive i , G.Translative i ) cardinal ∷ (Inflection i, Integral α, E.Scale α) ⇒ i → α → Maybe Text cardinal inf = cardinalRepr inf ∘ struct ordinal ∷ (Inflection i, Integral α, E.Scale α) ⇒ i → α → Maybe Text ordinal inf = ordinalRepr inf ∘ struct struct ∷ ( Integral α, E.Scale α , E.Unknown β, E.Lit β, E.Add β, E.Mul β , E.Inflection β, E.Scale β , G.Singular (E.Inf β) , G.Nominative (E.Inf β) , G.Accusative (E.Inf β) , G.Partitive (E.Inf β) ) ⇒ α → β struct = fix $ rule `combine` pelletierScale R L BN.rule where rule = findRule ( 0, lit) [ ( 11, add 10 L) , ( 20, fi_mul 10) , ( 100, step 100 10 R L) , (1000, step 1000 1000 R L) ] (dec 6 - 1) -- | Like the normal 'mul' rule with the difference that the value -- that is multiplied is changed to the partitive case. fi_mul ∷ ( Integral α , E.Add β, E.Mul β, E.Inflection β , G.Singular (E.Inf β) , G.Nominative (E.Inf β) , G.Accusative (E.Inf β) , G.Partitive (E.Inf β) ) ⇒ α → Rule α β fi_mul val = \f n → let (m, a) = n `divMod` val mval = E.mul (f m) (E.inflection toPartitive $ f val) in if a ≡ 0 then mval else (flip E.add) (f a) mval where toPartitive ∷ (G.Singular i, G.Nominative i, G.Accusative i, G.Partitive i) ⇒ i → i toPartitive inf | G.isSingular inf ∧ G.isNominative inf = G.partitive inf | G.isSingular inf ∧ G.isAccusative inf = G.partitive inf | otherwise = inf bounds ∷ (Integral α) ⇒ (α, α) bounds = let x = dec 15 - 1 in (negate x, x) cardinalRepr ∷ (Inflection i) ⇒ i → Exp i → Maybe Text cardinalRepr = render defaultRepr { reprValue = \inf n → M.lookup n (syms inf) , reprScale = BN.pelletierRepr (BN.quantityName "iljoona" "iljoonaa") (BN.quantityName "iljardi" "iljardia") [] , reprAdd = Just $ \_ _ _ → "" , reprMul = Just $ \_ _ _ → "" } where syms inf = M.fromList [ (0, \c → infForms inf c -- singular "nolla" {- nom -} "nolla" {- acc -} "nollan" {- gen -} "nollaa" {- ptv -} "nollana" {- ess -} "nollaksi" {- transl -} "nollassa" {- ine -} "nollasta" {- ela -} "nollaan" {- ill -} "nollalla" {- ade -} "nollalta" {- abl -} "nollalle" {- all -} "nollatta" {- abe -} "?" {- other -} -- plural "nollat" {- nom -} "nollat" {- acc -} "nollien" {- gen -} "nollia" {- ptv -} "nollina" {- ess -} "nolliksi" {- transl -} "nollissa" {- ine -} "nollista" {- ela -} "nolliin" {- ill -} "nollilla" {- ade -} "nollilta" {- abl -} "nollille" {- all -} "nollitta" {- abe -} "nolline" {- com -} "nollin" {- instr -} "?" {- other -} ) , (1, \c → infForms inf c -- singular "yksi" {- nom -} "yksi" {- acc -} "yhden" {- gen -} "yhtä" {- ptv -} "yhtenä" {- ess -} "yhdeksi" {- transl -} "yhdessä" {- ine -} "yhdestä" {- ela -} "yhteen" {- ill -} "yhdellä" {- ade -} "yhdeltä" {- abl -} "yhdelle" {- all -} "yhdettä" {- abe -} (case inf of _ | G.isSuperEssive inf → "yhtäällä" | G.isDelative inf → "yhtäältä" | G.isSublative inf → "yhtäälle" | G.isLative inf → "yhä" | G.isMultiplicative inf → "yhdesti" | otherwise → "?" ) -- plural "yhdet" {- nom -} "yhdet" {- acc -} "yksien" {- gen -} "yksiä" {- ptv -} "yksinä" {- ess -} "yksiksi" {- transl -} "yksissä" {- ine -} "yksistä" {- ela -} "yksiin" {- ill -} "yksillä" {- ade -} "yksiltä" {- abl -} "yksille" {- all -} "yksittä" {- abe -} "yksine" {- com -} "yksin" {- instr -} (case inf of _ | G.isDistributive inf → "yksittäin" | otherwise → "?" ) ) , (2, \c → infForms inf c -- singular "kaksi" {- nom -} "kaksi" {- acc -} "kahden" {- gen -} "kahta" {- ptv -} "kahtena" {- ess -} "kahdeksi" {- transl -} "kahdessa" {- ine -} "kahdesta" {- ela -} "kahteen" {- ill -} "kahdella" {- ade -} "kahdelta" {- abl -} "kahdelle" {- all -} "kahdetta" {- abe -} (case inf of _ | G.isInstructive inf → "kahden" | G.isSuperEssive inf → "kahtaalla" | G.isDelative inf → "kahtaalta" | G.isSublative inf → "kahtaalle" | G.isLative inf → "kahtia" | G.isMultiplicative inf → "kahdesti" | otherwise → "?" ) -- plural "kahdet" {- nom -} "kahdet" {- acc -} "kaksien" {- gen -} "kaksia" {- ptv -} "kaksina" {- ess -} "kaksiksi" {- transl -} "kaksissa" {- ine -} "kaksista" {- ela -} "kaksiin" {- ill -} "kaksilla" {- ade -} "kaksilta" {- abl -} "kaksille" {- all -} "kaksitta" {- abe -} "kaksine" {- com -} "kaksin" {- instr -} (case inf of _ | G.isDistributive inf → "kaksittain" | otherwise → "?" ) ) , (3, \c → infForms inf c -- singular "kolme" {- nom -} "kolme" {- acc -} "kolmen" {- gen -} "kolmea" {- ptv -} "kolmena" {- ess -} "kolmeksi" {- transl -} "kolmessa" {- ine -} "kolmesta" {- ela -} "kolmeen" {- ill -} "kolmella" {- ade -} "kolmelta" {- abl -} "kolmelle" {- all -} "kolmetta" {- abe -} (case inf of _ | G.isInstructive inf → "kolmen" | G.isLative inf → "kolmia" | G.isMultiplicative inf → "kolmesti" | otherwise → "?" ) -- plural "kolmet" {- nom -} "kolmet" {- acc -} "kolmien" {- gen -} "kolmia" {- ptv -} "kolmina" {- ess -} "kolmiksi" {- transl -} "kolmissa" {- ine -} "kolmista" {- ela -} "kolmiin" {- ill -} "kolmilla" {- ade -} "kolmilta" {- abl -} "kolmille" {- all -} "kolmitta" {- abe -} "kolmine" {- com -} "kolmin" {- instr -} (case inf of _ | G.isDistributive inf → "kolmittain" | G.isDistributiveTemporal inf → "kolmisin" | otherwise → "?" ) ) , (4, \c → infForms inf c -- singular "neljä" {- nom -} "neljä" {- acc -} "neljän" {- gen -} "neljää" {- ptv -} "neljänä" {- ess -} "neljäksi" {- transl -} "neljässä" {- ine -} "neljästä" {- ela -} "neljään" {- ill -} "neljällä" {- ade -} "neljältä" {- abl -} "neljälle" {- all -} "neljättä" {- abe -} "?" {- other -} -- plural "neljät" {- nom -} "neljät" {- acc -} "neljien" {- gen -} "neljiä" {- ptv -} "neljinä" {- ess -} "neljiksi" {- transl -} "neljissä" {- ine -} "neljistä" {- ela -} "neljiin" {- ill -} "neljillä" {- ade -} "neljiltä" {- abl -} "neljille" {- all -} "neljittä" {- abe -} "neljine" {- com -} "neljin" {- instr -} "?" {- other -} ) , (5, \c → infForms inf c -- singular "viisi" {- nom -} "viisi" {- acc -} "viiden" {- gen -} "viittä" {- ptv -} "viitenä" {- ess -} "viideksi" {- transl -} "viidessä" {- ine -} "viidestä" {- ela -} "viiteen" {- ill -} "viidellä" {- ade -} "viideltä" {- abl -} "viidelle" {- all -} "viidettä" {- abe -} "?" {- other -} -- plural "viidet" {- nom -} "viidet" {- acc -} "viisien" {- gen -} "viisiä" {- ptv -} "viisinä" {- ess -} "viisiksi" {- transl -} "viisissä" {- ine -} "viisistä" {- ela -} "viisiin" {- ill -} "viisillä" {- ade -} "viisiltä" {- abl -} "viisille" {- all -} "viisittä" {- abe -} "viisine" {- com -} "viisin" {- instr -} "?" {- other -} ) , (6, \c → infForms inf c -- singular "kuusi" {- nom -} "kuusi" {- acc -} "kuuden" {- gen -} "kuutta" {- ptv -} "kuutena" {- ess -} "kuudeksi" {- transl -} "kuudessa" {- ine -} "kuudesta" {- ela -} "kuuteen" {- ill -} "kuudella" {- ade -} "kuudelta" {- abl -} "kuudelle" {- all -} "kuudetta" {- abe -} "?" {- other -} -- plural "kuudet" {- nom -} "kuudet" {- acc -} "kuusien" {- gen -} "kuusia" {- ptv -} "kuusina" {- ess -} "kuusiksi" {- transl -} "kuusissa" {- ine -} "kuusista" {- ela -} "kuusiin" {- ill -} "kuusilla" {- ade -} "kuusilta" {- abl -} "kuusille" {- all -} "kuusitta" {- abe -} "kuusine" {- com -} "kuusin" {- instr -} "?" {- other -} ) , (7, \c → infForms inf c -- singular "seitsemän" {- nom -} "seitsemän" {- acc -} "seitsemän" {- gen -} "seitsemää" {- ptv -} "seitsemänä" {- ess -} "seitsemäksi" {- transl -} "seitsemässä" {- ine -} "seitsemästä" {- ela -} "seitsemään" {- ill -} "seitsemällä" {- ade -} "seitsemältä" {- abl -} "seitsemälle" {- all -} "seitsemättä" {- abe -} "?" {- other -} -- plural "seitsemät" {- nom -} "seitsemät" {- acc -} "seitsemien" {- gen -} "seitsemiä" {- ptv -} "seitseminä" {- ess -} "seitsemiksi" {- transl -} "seitsemissä" {- ine -} "seitsemistä" {- ela -} "seitsemiin" {- ill -} "seitsemillä" {- ade -} "seitsemiltä" {- abl -} "seitsemille" {- all -} "seitsemittä" {- abe -} "seitsemine" {- com -} "seitsemin" {- instr -} "?" {- other -} ) , (8, \c → infForms inf c -- singular "kahdeksan" {- nom -} "kahdeksan" {- acc -} "kahdeksan" {- gen -} "kahdeksaa" {- ptv -} "kahdeksana" {- ess -} "kahdeksaksi" {- transl -} "kahdeksassa" {- ine -} "kahdeksasta" {- ela -} "kahdeksaan" {- ill -} "kahdeksalla" {- ade -} "kahdeksalta" {- abl -} "kahdeksalle" {- all -} "kahdeksatta" {- abe -} "?" {- other -} -- plural "kahdeksat" {- nom -} "kahdeksat" {- acc -} "kahdeksien" {- gen -} "kahdeksia" {- ptv -} "kahdeksina" {- ess -} "kahdeksiksi" {- transl -} "kahdeksissa" {- ine -} "kahdeksista" {- ela -} "kahdeksiin" {- ill -} "kahdeksilla" {- ade -} "kahdeksilta" {- abl -} "kahdeksille" {- all -} "kahdeksitta" {- abe -} "kahdeksine" {- com -} "kahdeksin" {- instr -} "?" {- other -} ) , (9, \c → infForms inf c -- singular "yhdeksän" {- nom -} "yhdeksän" {- acc -} "yhdeksän" {- gen -} "yhdeksää" {- ptv -} "yhdeksänä" {- ess -} "yhdeksäksi" {- transl -} "yhdeksässä" {- ine -} "yhdeksästä" {- ela -} "yhdeksään" {- ill -} "yhdeksällä" {- ade -} "yhdeksältä" {- abl -} "yhdeksälle" {- all -} "yhdeksättä" {- abe -} "?" {- other -} -- plural "yhdeksät" {- nom -} "yhdeksät" {- acc -} "yhdeksien" {- gen -} "yhdeksiä" {- ptv -} "yhdeksinä" {- ess -} "yhdeksiksi" {- transl -} "yhdeksissä" {- ine -} "yhdeksistä" {- ela -} "yhdeksiin" {- ill -} "yhdeksillä" {- ade -} "yhdeksiltä" {- abl -} "yhdeksille" {- all -} "yhdeksittä" {- abe -} "yhdeksine" {- com -} "yhdeksin" {- instr -} "?" {- other -} ) , (10, \c → case c of CtxAdd _ (Lit _) _ → "toista" -- singular partitive ordinal 2 _ → infForms inf c -- singular "kymmenen" {- nom -} "kymmenen" {- acc -} "kymmenen" {- gen -} "kymmentä" {- ptv -} "kymmenenä" {- ess -} "kymmeneksi" {- transl -} "kymmenessä" {- ine -} "kymmenestä" {- ela -} "kymmeneen" {- ill -} "kymmenellä" {- ade -} "kymmeneltä" {- abl -} "kymmenelle" {- all -} "kymmenettä" {- abe -} "?" {- other -} -- plural "kymmenet" {- nom -} "kymmenet" {- acc -} "kymmenien" {- gen -} "kymmeniä" {- ptv -} "kymmeninä" {- ess -} "kymmeniksi" {- transl -} "kymmenissä" {- ine -} "kymmenistä" {- ela -} "kymmeniin" {- ill -} "kymmenillä" {- ade -} "kymmeniltä" {- abl -} "kymmenille" {- all -} "kymmenittä" {- abe -} "kymmenine" {- com -} "kymmenin" {- instr -} "?" {- other -} ) , (100, \c → case c of CtxMul _ (Lit n) _ | n ≤ 9 → "sataa" _ → infForms inf c -- singular "sata" {- nom -} "sata" {- acc -} "sadan" {- gen -} "sataa" {- ptv -} "satana" {- ess -} "sadaksi" {- transl -} "sadassa" {- ine -} "sadasta" {- ela -} "sataan" {- ill -} "sadalla" {- ade -} "sadalta" {- abl -} "sadalle" {- all -} "sadatta" {- abe -} "?" {- other -} -- plural "sadat" {- nom -} "sadat" {- acc -} "satojen" {- gen -} "satoja" {- ptv -} "satoina" {- ess -} "sadoiksi" {- transl -} "sadoissa" {- ine -} "sadoista" {- ela -} "satoihin" {- ill -} "sadoilla" {- ade -} "sadoilta" {- abl -} "sadoille" {- all -} "sadoitta" {- abe -} "satoine" {- com -} "sadoin" {- instr -} "?" {- other -} ) , (1000, \c → case c of CtxMul {} → "tuhatta" _ → infForms inf c -- singular "tuhat" {- nom -} "tuhat" {- acc -} "tuhannen" {- gen -} "tuhatta" {- ptv -} "tuhantena" {- ess -} "tuhanneksi" {- transl -} "tuhannessa" {- ine -} "tuhannesta" {- ela -} "tuhanteen" {- ill -} "tuhannella" {- ade -} "tuhannelta" {- abl -} "tuhannelle" {- all -} "tuhannetta" {- abe -} "?" {- other -} -- plural "tuhannet" {- nom -} "tuhannet" {- acc -} "tuhansien" {- gen -} "tuhansia" {- ptv -} "tuhansina" {- ess -} "tuhansiksi" {- transl -} "tuhansissa" {- ine -} "tuhansista" {- ela -} "tuhansiin" {- ill -} "tuhansilla" {- ade -} "tuhansilta" {- abl -} "tuhansille" {- all -} "tuhansitta" {- abe -} "tuhansine" {- com -} "tuhansin" {- instr -} "?" {- other -} ) ] ordinalRepr ∷ (Inflection i) ⇒ i → Exp i → Maybe Text ordinalRepr = render defaultRepr { reprValue = \inf n → M.lookup n (syms inf) , reprScale = BN.pelletierRepr (BN.quantityName "iljoona" "iljoonaa") (BN.quantityName "iljardi" "iljardia") [] , reprAdd = Just $ \_ _ _ → "" , reprMul = Just $ \_ _ _ → "" } where syms inf = M.fromList [ (0, \c → infForms inf c -- singular "nollas" {- nom -} "nollas" {- acc -} "nollannen" {- gen -} "nollatta" {- ptv -} "nollantena" {- ess -} "nollanneksi" {- transl -} "nollannessa" {- ine -} "nollannesta" {- ela -} "nollanteen" {- ill -} "nollannella" {- ade -} "nollannelta" {- abl -} "nollannelle" {- all -} "nollannetta" {- abe -} "?" {- other -} -- plural "nollannet" {- nom -} "nollannet" {- acc -} "nollansien" {- gen -} "nollansia" {- ptv -} "nollansina" {- ess -} "nollansiksi" {- transl -} "nollansissa" {- ine -} "nollansista" {- ela -} "nollansiin" {- ill -} "nollansilla" {- ade -} "nollansilta" {- abl -} "nollansille" {- all -} "nollansitta" {- abe -} "nollansine" {- com -} "nollansin" {- instr -} "?" {- other -} ) , (1, \c → case c of CtxAdd _ (Lit 10) _ → infForms inf c -- singular "yhdes" {- nom -} "yhdes" {- acc -} "yhdennen" {- gen -} "yhdettä" {- ptv -} "yhdennessä" {- ess -} "yhdenneksi" {- transl -} "yhdennessä" {- ine -} "yhdennestä" {- ela -} "yhdenteen" {- ill -} "yhdennellä" {- ade -} "yhdenneltä" {- abl -} "yhdennelle" {- all -} "yhdennettä" {- abe -} "?" {- other -} -- plural "yhdennet" {- nom -} "yhdennet" {- acc -} "yhdensien" {- gen -} "yhdensiä" {- ptv -} "yhdensinä" {- ess -} "yhdensiksi" {- transl -} "yhdensissä" {- ine -} "yhdensistä" {- ela -} "yhdensiin" {- ill -} "yhdensillä" {- ade -} "yhdensitlä" {- abl -} "yhdensiin" {- all -} "yhdensittä" {- abe -} "yhdensine" {- com -} "yhdensin" {- instr -} "?" {- other -} _ → infForms inf c -- singular "ensimmäinen" {- nom -} "ensimmäinen" {- acc -} "ensimmäisen" {- gen -} "ensimmäistä" {- ptv -} "ensimmmäisenä" {- ess -} "ensimmäiseksi" {- transl -} "ensimmäisessä" {- ine -} "ensimmäisestä" {- ela -} "ensimmäiseen" {- ill -} "ensimmäisellä" {- ade -} "ensimmäiseltä" {- abl -} "ensimmäiselle" {- all -} "ensimmäisettä" {- abe -} "?" {- other -} -- plural "ensimmäiset" {- nom -} "ensimmäiset" {- acc -} "ensimmäisten" {- gen -} "ensimmäisiä" {- ptv -} "ensimmäisinä" {- ess -} "ensimmäisiksi" {- transl -} "ensimmäisissä" {- ine -} "ensimmäisistä" {- ela -} "ensimmäisiin" {- ill -} "ensimmäisillä" {- ade -} "ensimmäisiltä" {- abl -} "ensimmäisille" {- all -} "ensimmäisittä" {- abe -} "ensimmäisine" {- com -} "ensimmäisin" {- instr -} "?" {- other -} ) , (2, \c → case c of CtxAdd _ (Lit 10) _ → infForms inf c -- singular "kahdes" {- nom -} "kahdes" {- acc -} "kahdennen" {- gen -} "kahdetta" {- ptv -} "kahdentena" {- ess -} "kahdenneksi" {- transl -} "kahdennessa" {- ine -} "kahdennesta" {- ela -} "kahdenteen" {- ill -} "kahdennella" {- ade -} "kahdennelta" {- abl -} "kahdennelle" {- all -} "kahdennetta" {- abe -} "?" {- other -} -- plural "kahdennet" {- nom -} "kahdennet" {- acc -} "kahdensien" {- gen -} "kahdensia" {- ptv -} "kahdensina" {- ess -} "kahdensiksi" {- transl -} "kahdensissa" {- ine -} "kahdensista" {- ela -} "kahdensiin" {- ill -} "kahdensilla" {- ade -} "kahdensilta" {- abl -} "kahdensille" {- all -} "kahdensitta" {- abe -} "kahdensine" {- com -} "kahdensin" {- instr -} "?" {- other -} _ → infForms inf c -- singular "toinen" {- nom -} "toinen" {- acc -} "toisen" {- gen -} "toista" {- ptv -} "toisena" {- ess -} "toiseksi" {- transl -} "toisessa" {- ine -} "toisesta" {- ela -} "toiseen" {- ill -} "toisella" {- ade -} "toiselta" {- abl -} "toiselle" {- all -} "toisetta" {- abe -} "?" {- other -} -- plural "toiset" {- nom -} "toiset" {- acc -} "toisten" {- gen -} "toisia" {- ptv -} "toisina" {- ess -} "toisiksi" {- transl -} "toisissa" {- ine -} "toisista" {- ela -} "toisiin" {- ill -} "toisilla" {- ade -} "toisilta" {- abl -} "toisille" {- all -} "toisitta" {- abe -} "toisine" {- com -} "toisin" {- instr -} "?" {- other -} ) , (3, \c → infForms inf c -- singular "kolmas" {- nom -} "kolmas" {- acc -} "kolmannen" {- gen -} "kolmatta" {- ptv -} "kolmantena" {- ess -} "kolmanneksi" {- transl -} "kolmannessa" {- ine -} "kolmannesta" {- ela -} "kolmanteen" {- ill -} "kolmannella" {- ade -} "kolmannelta" {- abl -} "kolmannelle" {- all -} "kolmannetta" {- abe -} "?" {- other -} -- plural "kolmannet" {- nom -} "kolmannet" {- acc -} "kolmansien" {- gen -} "kolmansia" {- ptv -} "kolmansina" {- ess -} "kolmansiksi" {- transl -} "kolmansissa" {- ine -} "kolmansista" {- ela -} "kolmansiin" {- ill -} "kolmansilla" {- ade -} "kolmansilta" {- abl -} "kolmansille" {- all -} "kolmansitta" {- abe -} "kolmansine" {- com -} "kolmansin" {- instr -} "?" {- other -} ) , (4, \c → infForms inf c -- singular "neljäs" {- nom -} "neljäs" {- acc -} "neljännen" {- gen -} "neljättä" {- ptv -} "neljäntenä" {- ess -} "neljänneksi" {- transl -} "neljännessä" {- ine -} "neljännestä" {- ela -} "neljänteen" {- ill -} "neljännellä" {- ade -} "neljänneltä" {- abl -} "neljännelle" {- all -} "neljännettä" {- abe -} (case inf of _ | G.isComitative inf → "neljänsine" | G.isInstructive inf → "neljänsin" | otherwise → "?" ) -- plural "neljännet" {- nom -} "neljännet" {- acc -} "neljänsien" {- gen -} "neljänsiä" {- ptv -} "neljänsinä" {- ess -} "neljänsiksi" {- transl -} "neljänsissä" {- ine -} "neljänsistä" {- ela -} "neljänsiin" {- ill -} "neljänsillä" {- ade -} "neljänsiltä" {- abl -} "neljänsille" {- all -} "neljänsittä" {- abe -} "neljänsine" {- com -} "neljänsin" {- instr -} "?" {- other -} ) , (5, \c → infForms inf c -- singular "viides" {- nom -} "viides" {- acc -} "viidennen" {- gen -} "viidettä" {- ptv -} "viidentenä" {- ess -} "viidenneksi" {- transl -} "viidennessä" {- ine -} "viidennestä" {- ela -} "viidenteen" {- ill -} "viidennellä" {- ade -} "viidenneltä" {- abl -} "viidennelle" {- all -} "viidennettä" {- abe -} "?" {- other -} -- plural "viidennet" {- nom -} "viidennet" {- acc -} "viidensien" {- gen -} "viidensiä" {- ptv -} "viidensinä" {- ess -} "viidensiksi" {- transl -} "viidensissä" {- ine -} "viidensistä" {- ela -} "viidensiin" {- ill -} "viidensillä" {- ade -} "viidensiltä" {- abl -} "viidensille" {- all -} "viidensittä" {- abe -} "viidensine" {- com -} "viidensin" {- instr -} "?" {- other -} ) , (6, \c → infForms inf c -- singular "kuudes" {- nom -} "kuudes" {- acc -} "kuudennen" {- gen -} "kuudetta" {- ptv -} "kuudentena" {- ess -} "kuudenneksi" {- transl -} "kuudennessa" {- ine -} "kuudennesta" {- ela -} "kuudenteen" {- ill -} "kuudennella" {- ade -} "kuudennelta" {- abl -} "kuudennelle" {- all -} "kuudennetta" {- abe -} "?" {- other -} -- plural "kuudennet" {- nom -} "kuudennet" {- acc -} "kuudensien" {- gen -} "kuudensia" {- ptv -} "kuudensina" {- ess -} "kuudensiksi" {- transl -} "kuudensissa" {- ine -} "kuudensista" {- ela -} "kuudensiin" {- ill -} "kuudensilla" {- ade -} "kuudensilta" {- abl -} "kuudensille" {- all -} "kuudensitta" {- abe -} "kuudensine" {- com -} "kuudensin" {- instr -} "?" {- other -} ) , (7, \c → infForms inf c -- singular "seitsemäs" {- nom -} "seitsemäs" {- acc -} "seitsemännen" {- gen -} "seitsemättä" {- ptv -} "seitsemäntenä" {- ess -} "seitsemänneksi" {- transl -} "seitsemännessä" {- ine -} "seitsemännestä" {- ela -} "seitsemänteen" {- ill -} "seitsemännellä" {- ade -} "seitsemänneltä" {- abl -} "seitsemännelle" {- all -} "seitsemännettä" {- abe -} "?" {- other -} -- plural "seitsemännet" {- nom -} "seitsemännet" {- acc -} "seitsemänsien" {- gen -} "seitsemänsiä" {- ptv -} "seitsemänsinä" {- ess -} "seitsemänsiksi" {- transl -} "seitsemänsissä" {- ine -} "seitsemänsistä" {- ela -} "seitsemänsiin" {- ill -} "seitsemänsillä" {- ade -} "seitsemänsiltä" {- abl -} "seitsemänsille" {- all -} "seitsemänsittä" {- abe -} "seitsemänsine" {- com -} "seitsemänsin" {- instr -} "?" {- other -} ) , (8, \c → infForms inf c -- singular "kahdeksas" {- nom -} "kahdeksas" {- acc -} "kahdeksannen" {- gen -} "kahdeksatta" {- ptv -} "kahdeksantena" {- ess -} "kahdeksanneksi" {- transl -} "kahdeksannessa" {- ine -} "kahdeksannesta" {- ela -} "kahdeksanteen" {- ill -} "kahdeksannella" {- ade -} "kahdeksannelta" {- abl -} "kahdeksannelle" {- all -} "kahdeksannetta" {- abe -} "?" {- other -} -- plural "kahdeksannet" {- nom -} "kahdeksannet" {- acc -} "kahdeksansien" {- gen -} "kahdeksansia" {- ptv -} "kahdeksansina" {- ess -} "kahdeksansiksi" {- transl -} "kahdeksansissa" {- ine -} "kahdeksansista" {- ela -} "kahdeksansiin" {- ill -} "kahdeksansilla" {- ade -} "kahdeksansilta" {- abl -} "kahdeksansille" {- all -} "kahdeksansitta" {- abe -} "kahdeksansine" {- com -} "kahdeksansin" {- instr -} "?" {- other -} ) , (9, \c → infForms inf c -- singular "yhdeksäs" {- nom -} "yhdeksäs" {- acc -} "yhdeksännen" {- gen -} "yhdeksättä" {- ptv -} "yhdeksäntenä" {- ess -} "yhdeksänneksi" {- transl -} "yhdeksännessä" {- ine -} "yhdeksännestä" {- ela -} "yhdeksänteen" {- ill -} "yhdeksännellä" {- ade -} "yhdeksänneltä" {- abl -} "yhdeksännelle" {- all -} "yhdeksännettä" {- abe -} "?" {- other -} -- plural "yhdeksännet" {- nom -} "yhdeksännet" {- acc -} "yhdeksänsien" {- gen -} "yhdeksänsiä" {- ptv -} "yhdeksänsinä" {- ess -} "yhdeksänsiksi" {- transl -} "yhdeksänsissä" {- ine -} "yhdeksänsistä" {- ela -} "yhdeksänsiin" {- ill -} "yhdeksänsillä" {- ade -} "yhdeksänsiltä" {- abl -} "yhdeksänsille" {- all -} "yhdeksänsittä" {- abe -} "yhdeksänsine" {- com -} "yhdeksänsin" {- instr -} "?" {- other -} ) , (10, \c → case c of CtxAdd _ (Lit _) _ → "toista" -- singular partitive ordinal 2 _ → infForms inf c -- singular "kymmenes" {- nom -} "kymmenes" {- acc -} "kymmenennen" {- gen -} "kymmenettä" {- ptv -} "kymmenentenä" {- ess -} "kymmenenneksi" {- transl -} "kymmenennessä" {- ine -} "kymmenennestä" {- ela -} "kymmenenteen" {- ill -} "kymmenennellä" {- ade -} "kymmenenneltä" {- abl -} "kymmenennelle" {- all -} "kymmenennettä" {- abe -} "?" {- other -} -- plural "kymmenennet" {- nom -} "kymmenennet" {- acc -} "kymmenensien" {- gen -} "kymmenensiä" {- ptv -} "kymmenensinä" {- ess -} "kymmenensiksi" {- transl -} "kymmenensissä" {- ine -} "kymmenensistä" {- ela -} "kymmenensiin" {- ill -} "kymmenensillä" {- ade -} "kymmenensiltä" {- abl -} "kymmenensille" {- all -} "kymmenensittä" {- abe -} "kymmenensine" {- com -} "kymmenensin" {- instr -} "?" {- other -} ) , (100, \c → case c of _ → infForms inf c -- singular "sadas" {- nom -} "sadas" {- acc -} "sadannen" {- gen -} "sadatta" {- ptv -} "sadantena" {- ess -} "sadanneksi" {- transl -} "sadannessa" {- ine -} "sadannesta" {- ela -} "sadanteen" {- ill -} "sadannella" {- ade -} "sadannelta" {- abl -} "sadannelle" {- all -} "sadannetta" {- abe -} "?" {- other -} -- plural "sadannet" {- nom -} "sadannet" {- acc -} "sadansien" {- gen -} "sadansia" {- ptv -} "sadansina" {- ess -} "sadansiksi" {- transl -} "sadansissa" {- ine -} "sadansista" {- ela -} "sadansiin" {- ill -} "sadansilla" {- ade -} "sadansilta" {- abl -} "sadansille" {- all -} "sadansitta" {- abe -} "sadansine" {- com -} "sadansin" {- instr -} "?" {- other -} ) , (1000, \c → case c of _ → infForms inf c -- singular "tuhannes" {- nom -} "tuhannes" {- acc -} "tuhannennen" {- gen -} "tuhannetta" {- ptv -} "tuhannentena" {- ess -} "tuhannenneksi" {- transl -} "tuhannennessa" {- ine -} "tuhannennesta" {- ela -} "tuhannenteen" {- ill -} "tuhannennella" {- ade -} "tuhannennelta" {- abl -} "tuhannennelle" {- all -} "tuhannennetta" {- abe -} "?" {- other -} -- plural "tuhannennet" {- nom -} "tuhannennet" {- acc -} "tuhannensien" {- gen -} "tuhannensia" {- ptv -} "tuhannensina" {- ess -} "tuhannensiksi" {- transl -} "tuhannensissa" {- ine -} "tuhannensista" {- ela -} "tuhannensiin" {- ill -} "tuhannensilla" {- ade -} "tuhannensilta" {- abl -} "tuhannensille" {- all -} "tuhannensitta" {- abe -} "tuhannensine" {- com -} "tuhannensin" {- instr -} "?" {- other -} ) ] infForms ∷ (Inflection i) ⇒ i → Ctx (Exp i) → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text → Text infForms inf _ s_nom s_acc s_gen s_ptv s_ess s_transl s_ine s_ela s_ill s_ade s_abl s_all s_abe s_other p_nom p_acc p_gen p_ptv p_ess p_transl p_ine p_ela p_ill p_ade p_abl p_all p_abe p_com p_instr p_other | G.isSingular inf = singularForms | G.isPlural inf = pluralForms | otherwise = "?" where singularForms | G.isNominative inf = s_nom | G.isAccusative inf = s_acc | G.isGenitive inf = s_gen | G.isPartitive inf = s_ptv | G.isEssive inf = s_ess | G.isTranslative inf = s_transl | G.isLocativeInessive inf = s_ine | G.isLocativeElative inf = s_ela | G.isLocativeIllative inf = s_ill | G.isLocativeAdessive inf = s_ade | G.isLocativeAblative inf = s_abl | G.isLocativeAllative inf = s_all | G.isAbessive inf = s_abe | otherwise = s_other pluralForms | G.isNominative inf = p_nom | G.isAccusative inf = p_acc | G.isGenitive inf = p_gen | G.isPartitive inf = p_ptv | G.isEssive inf = p_ess | G.isTranslative inf = p_transl | G.isLocativeInessive inf = p_ine | G.isLocativeElative inf = p_ela | G.isLocativeIllative inf = p_ill | G.isLocativeAdessive inf = p_ade | G.isLocativeAblative inf = p_abl | G.isLocativeAllative inf = p_all | G.isAbessive inf = p_abe | G.isComitative inf = p_com | G.isInstructive inf = p_instr | otherwise = p_other
telser/numerals
src/Text/Numeral/Language/FIN.hs
Haskell
bsd-3-clause
49,160
module Main where import Test.HUnit hiding (path) import TestUtil import Database.TokyoCabinet.HDB import Data.Maybe (catMaybes) import Data.List (sort) import Control.Monad dbname :: String dbname = "foo.tch" withOpenedHDB :: String -> (HDB -> IO a) -> IO a withOpenedHDB name action = do h <- new open h name [OREADER, OWRITER, OCREAT] res <- action h close h return res test_ecode = withoutFile dbname $ \fn -> do h <- new open h fn [OREADER] ecode h >>= (ENOFILE @=?) test_new_delete = do hdb <- new delete hdb test_open_close = withoutFile dbname $ \fn -> do hdb <- new not `fmap` open hdb fn [OREADER] @? "file does not exist" open hdb fn [OREADER, OWRITER, OCREAT] @? "open" close hdb @? "close" not `fmap` close hdb @? "cannot close closed file" test_putxx = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "foo" "bar" get hdb "foo" >>= (Just "bar" @=?) putkeep hdb "foo" "baz" get hdb "foo" >>= (Just "bar" @=?) putcat hdb "foo" "baz" get hdb "foo" >>= (Just "barbaz" @=?) putasync hdb "bar" "baz" sync hdb get hdb "bar" >>= (Just "baz" @=?) test_out = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "foo" "bar" get hdb "foo" >>= (Just "bar" @=?) out hdb "foo" @? "out succeeded" get hdb "foo" >>= ((Nothing :: Maybe String) @=?) test_put_get = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "1" "foo" put hdb "2" "bar" put hdb "3" "baz" get hdb "1" >>= (Just "foo" @=?) get hdb "2" >>= (Just "bar" @=?) get hdb "3" >>= (Just "baz" @=?) test_vsiz = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "foo" "bar" vsiz hdb "foo" >>= (Just 3 @=?) vsiz hdb "bar" >>= ((Nothing :: Maybe Int) @=?) test_iterate = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do let keys = [1, 2, 3] :: [Int] vals = ["foo", "bar", "baz"] zipWithM_ (put hdb) keys vals iterinit hdb keys' <- sequence $ replicate (length keys) (iternext hdb) (sort $ catMaybes keys') @?= (sort keys) test_fwmkeys = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do mapM_ (uncurry (put hdb)) ([ ("foo", 100) , ("bar", 200) , ("baz", 201) , ("jkl", 300)] :: [(String, Int)]) fwmkeys hdb "ba" 10 >>= (["bar", "baz"] @=?) . sort fwmkeys hdb "ba" 1 >>= (["bar"] @=?) fwmkeys hdb "" 10 >>= (["bar", "baz", "foo", "jkl"] @=?) . sort test_addint = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do let ini = 32 :: Int put hdb "foo" ini get hdb "foo" >>= (Just ini @=?) addint hdb "foo" 3 get hdb "foo" >>= (Just (ini+3) @=?) addint hdb "bar" 1 >>= (Just 1 @=?) put hdb "bar" "foo" addint hdb "bar" 1 >>= (Nothing @=?) test_adddouble = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do let ini = 0.003 :: Double put hdb "foo" ini get hdb "foo" >>= (Just ini @=?) adddouble hdb "foo" 0.3 (get hdb "foo" >>= (isIn (ini+0.3))) @? "isIn" adddouble hdb "bar" 0.5 >>= (Just 0.5 @=?) put hdb "bar" "foo" adddouble hdb "bar" 1.2 >>= (Nothing @=?) where margin = 1e-30 isIn :: Double -> (Maybe Double) -> IO Bool isIn expected (Just actual) = let diff = expected - actual in return $ abs diff <= margin test_vanish = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do put hdb "foo" "111" put hdb "bar" "222" put hdb "baz" "333" rnum hdb >>= (3 @=?) vanish hdb rnum hdb >>= (0 @=?) test_copy = withoutFile dbname $ \fns -> withoutFile "bar.tch" $ \fnd -> withOpenedHDB fns $ \hdb -> do put hdb "foo" "bar" copy hdb fnd close hdb open hdb fnd [OREADER] get hdb "foo" >>= (Just "bar" @=?) test_txn = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> do tranbegin hdb put hdb "foo" "bar" get hdb "foo" >>= (Just "bar" @=?) tranabort hdb get hdb "foo" >>= ((Nothing :: Maybe String) @=?) tranbegin hdb put hdb "foo" "baz" get hdb "foo" >>= (Just "baz" @=?) trancommit hdb get hdb "foo" >>= (Just "baz" @=?) test_path = withoutFile dbname $ \fn -> withOpenedHDB fn $ \hdb -> path hdb >>= (Just dbname @=?) test_util = withoutFile dbname $ \fn -> do hdb <- new setcache hdb 1000000 @? "setcache" setxmsiz hdb 1000000 @? "setxmsiz" tune hdb 150000 5 11 [TLARGE, TBZIP] @? "tune" open hdb fn [OREADER, OWRITER, OCREAT] path hdb >>= (Just fn @=?) rnum hdb >>= (0 @=?) ((> 0) `fmap` fsiz hdb) @? "fsiz" sync hdb @? "sync" optimize hdb 0 (-1) (-1) [] @? "optimize" close hdb tests = test [ "new delete" ~: test_new_delete , "ecode" ~: test_ecode , "open close" ~: test_open_close , "put get" ~: test_put_get , "out" ~: test_out , "putxx" ~: test_putxx , "copy" ~: test_copy , "transaction" ~: test_txn , "fwmkeys" ~: test_fwmkeys , "path" ~: test_path , "addint" ~: test_addint , "adddouble" ~: test_adddouble , "util" ~: test_util , "vsiz" ~: test_vsiz , "vanish" ~: test_vanish , "iterate" ~: test_iterate ] main = runTestTT tests
tom-lpsd/tokyocabinet-haskell
tests/HDBTest.hs
Haskell
bsd-3-clause
6,050
module CRF.Control.Monad.Lazy ( mapM' -- , mapM_' , sequence' ) where import System.IO.Unsafe (unsafeInterleaveIO) sequence' (mx:xs) = unsafeInterleaveIO $ combine xs =<< mx where combine xs x = return . (x:) =<< sequence' xs sequence' [] = return [] mapM' f (x:xs) = unsafeInterleaveIO $ do y <- f x ys <- mapM' f xs return (y : ys) mapM' _ [] = return [] -- mapM_' f (x:xs) = unsafeInterleaveIO $ do -- y <- f x -- mapM_' f xs -- mapM_' _ [] = return ()
kawu/tagger
src/CRF/Control/Monad/Lazy.hs
Haskell
bsd-3-clause
488
-- From Thinking Functionally with Haskell -- One man went to mow -- Went to mow a meadow -- One man and his dog -- Went to mow a meadow -- Two men went to mow -- Went to mow a meadow -- Two men, one man and his dog -- Went to mow a meadow -- Three men went to mow -- Went to mow a meadow -- Three men, two men, one man and his dog -- Went to mow a meadow units :: [String] units = ["zero","one","two","three","four","five","six","seven","eight","nine"] convert1 :: Int -> String convert1 n = units!!n convert = convert1 men :: Int -> String men n | n <= 1 = convert n ++ " man" | otherwise = convert n ++ " men" s1 :: Int -> String s1 n = men n ++ " went to mow\n" s2 :: Int -> String s2 n = "Went to mow a meadow\n" s3 :: Int -> String s3 n | n <= 1 = men n ++ " and his dog\n" | otherwise = men n ++ ", " ++ s3 (n - 1) s4 :: Int -> String s4 = s2 song :: Int -> String song n | n == 0 = "" | n <10 = s1 n ++ s2 n ++ s3 n ++ s4 n | otherwise = ""
trymilix/cookbooks
Software/haskell/song.hs
Haskell
apache-2.0
992
{-# LANGUAGE OverloadedStrings #-} module Main where import Data.Word (Word8, Word16) import Data.List (unfoldr) import Data.Bits (shiftL, (.&.)) import Data.ByteString.Char8 () import Data.Monoid import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as L import qualified Data.Binary.BitBuilder as BB import Test.QuickCheck hiding ((.&.)) -- This test constructs random sequences of elements from the following list. -- The first element of each pair is some BitBuilder and the second element -- is a list of the bits that such a BitBuilder should append. Then we run -- the sequence of BitBuilders and concat the sequence of [Bool] and check -- that the output is the same type TestElement = (BB.BitBuilder, [Bool]) elems :: [TestElement] elems = [ (BB.singleton True, [True]) , (BB.singleton False, [False]) , (BB.fromByteString ("\x01\x02", 0), byteToBits 1 ++ byteToBits 2) , (BB.fromByteString ("\x01\x02", 4), byteToBits 1 ++ replicate 4 False) , (BB.fromByteString ("\x01\x02", 1), byteToBits 1 ++ [False]) , (BB.fromByteString ("", 0), []) , (BB.fromBits 0 (0::Int), []) , (BB.fromByteString ("\xfc", 7), replicate 6 True ++ [False]) , (BB.fromBits 7 (0xfe::Word8), replicate 6 True ++ [False]) , (BB.fromBits 3 (3::Word8), [False, True, True]) , (BB.fromBits 64 (0::Word16), replicate 64 False) ] lbsToBits = concatMap byteToBits . L.unpack byteToBits = unfoldr f . (,) 8 where f (0, _) = Nothing f (n, byte) = Just (byte .&. 0x80 == 0x80, (n-1, byte `shiftL` 1)) zeroExtend :: [Bool] -> [Bool] zeroExtend x = x ++ (replicate ((8 - (length x)) `mod` 8) False) prop_order xs = lbsToBits (BB.toLazyByteString bb) == zeroExtend list where es = map (\x -> elems !! (x `mod` (length elems))) xs bb = foldr mappend mempty $ map fst es list = concat $ map snd es main = quickCheckWith (stdArgs { maxSize = 10000}) prop_order
KrzyStar/binary-low-level
tests/BitBuilderTest.hs
Haskell
bsd-3-clause
1,956
-- | This module contains any objects relating to order theory module SubHask.Algebra.Ord where import qualified Prelude as P import qualified Data.List as L import qualified GHC.Arr as Arr import Data.Array.ST hiding (freeze,thaw) import Control.Monad import Control.Monad.Random import Control.Monad.ST import Prelude (take) import SubHask.Algebra import SubHask.Category import SubHask.Mutable import SubHask.SubType import SubHask.Internal.Prelude import SubHask.TemplateHaskell.Deriving -------------------------------------------------------------------------------- -- | This wrapper let's us convert between SubHask's Ord type and the Prelude's. -- See the "sort" function below for an example. newtype WithPreludeOrd a = WithPreludeOrd { unWithPreludeOrd :: a } deriving Storable instance Show a => Show (WithPreludeOrd a) where show (WithPreludeOrd a) = show a -- | FIXME: for some reason, our deriving mechanism doesn't work on Show here; -- It causes's Set's show to enter an infinite loop deriveHierarchyFiltered ''WithPreludeOrd [ ''Eq_, ''Enum, ''Boolean, ''Ring, ''Metric ] [ ''Show ] instance Eq a => P.Eq (WithPreludeOrd a) where {-# INLINE (==) #-} a==b = a==b instance Ord a => P.Ord (WithPreludeOrd a) where {-# INLINE (<=) #-} a<=b = a<=b -- | A wrapper around the Prelude's sort function. -- -- FIXME: -- We should put this in the container hierarchy so we can sort any data type sort :: Ord a => [a] -> [a] sort = map unWithPreludeOrd . L.sort . map WithPreludeOrd -- | Randomly shuffles a list in time O(n log n); see http://www.haskell.org/haskellwiki/Random_shuffle shuffle :: (Eq a, MonadRandom m) => [a] -> m [a] shuffle xs = do let l = length xs rands <- take l `liftM` getRandomRs (0, l-1) let ar = runSTArray ( do ar <- Arr.thawSTArray (Arr.listArray (0, l-1) xs) forM_ (L.zip [0..(l-1)] rands) $ \(i, j) -> do vi <- Arr.readSTArray ar i vj <- Arr.readSTArray ar j Arr.writeSTArray ar j vi Arr.writeSTArray ar i vj return ar ) return (Arr.elems ar)
abailly/subhask
src/SubHask/Algebra/Ord.hs
Haskell
bsd-3-clause
2,149
<?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="de-DE"> <title>Active Scan Rules - Alpha | 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>Suche</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>
0xkasun/security-tools
src/org/zaproxy/zap/extension/ascanrulesAlpha/resources/help_de_DE/helpset_de_DE.hs
Haskell
apache-2.0
986
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE ExtendedDefaultRules #-} -- | A first example in equalional reasoning. -- | From the definition of append we should be able to -- | semi-automatically prove the two axioms. -- | Note for soundness we need -- | totallity: all the cases should be covered -- | termination: we cannot have diverging things into proofs {-@ LIQUID "--autoproofs" @-} {-@ LIQUID "--totality" @-} {-@ LIQUID "--exact-data-cons" @-} module Append where import Axiomatize import Equational import Prelude hiding (map) data L a = N | C a (L a) instance Eq a => Eq (L a) where N == N = True (C x xs) == (C x' xs') = x == x' && xs == xs' {-@ axiomatize map @-} $(axiomatize [d| map :: (a -> b) -> L a -> L b map f N = N map f (C x xs) = f x `C` map f xs |]) -- axioms: -- axiom_map_N :: forall f. map f N == N -- axiom_map_C :: forall f x xs. map f (C x xs) == C (f x) (map f xs) {-@ axiomatize compose @-} $(axiomatize [d| compose :: (b -> c) ->(a -> b) -> (a -> c) compose f g x = f (g x) |]) {-@ prop_fusion :: f:(a -> a) -> g:(a -> a) -> xs:L a -> {v:Proof | map f (map g xs) == map (compose f g) xs } @-} prop_fusion :: Eq a => (a -> a) -> (a -> a) -> L a -> Proof prop_fusion f g N = -- refl e1 `by` pr1 `by` pr2 `by` pr3 auto 2 (map f (map g N) == map (compose f g) N) {- where e1 = map f (map g N) pr1 = axiom_map_N g e2 = map f N pr2 = axiom_map_N f e3 = N pr3 = axiom_map_N (compose f g) e4 = map (compose f g) N -} prop_fusion f g (C x xs) = auto 2 (map f (map g (C x xs)) == map (compose f g) (C x xs)) -- refl e1 `by` pr1 `by` pr2 `by` pr3 `by` pr4 `by` pr5 {- where e1 = map f (map g (C x xs)) pr1 = axiom_map_C g x xs e2 = map f (C (g x) (map g xs)) pr2 = axiom_map_C f (g x) (map g xs) e3 = C (f (g x)) (map f (map g xs)) pr3 = prop_fusion f g xs e4 = C (f (g x)) (map (compose f g) xs) pr4 = axiom_compose f g x e5 = C ((compose f g) x) (map (compose f g) xs) pr5 = axiom_map_C (compose f g) x xs e6 = map (compose f g) (C x xs) -} {-@ data L [llen] @-} {-@ invariant {v: L a | llen v >= 0} @-} {-@ measure llen @-} llen :: L a -> Int llen N = 0 llen (C x xs) = 1 + llen xs
abakst/liquidhaskell
tests/equationalproofs/pos/MapFusion.hs
Haskell
bsd-3-clause
2,338
module Lib where data Value = Finite Integer | Infinity deriving (Eq) instance Num Value where (+) = undefined (*) = undefined abs = undefined signum = undefined negate = undefined fromInteger = Finite -- | @litCon _@ should not elicit an overlapping patterns warning when it -- passes through the LitCon case. litCon :: Value -> Bool litCon Infinity = True litCon 0 = True litCon _ = False -- | @conLit Infinity@ should not elicit an overlapping patterns warning when -- it passes through the ConLit case. conLit :: Value -> Bool conLit 0 = True conLit Infinity = True conLit _ = False
sdiehl/ghc
testsuite/tests/pmcheck/should_compile/T16289.hs
Haskell
bsd-3-clause
667
<?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="ja-JP"> <title>FuzzDB Files</title> <maps> <homeID>fuzzdb</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/fuzzdb/src/main/javahelp/help_ja_JP/helpset_ja_JP.hs
Haskell
apache-2.0
960
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE Trustworthy #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Functor.Identity -- Copyright : (c) Andy Gill 2001, -- (c) Oregon Graduate Institute of Science and Technology 2001 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : ross@soi.city.ac.uk -- Stability : experimental -- Portability : portable -- -- The identity functor and monad. -- -- This trivial type constructor serves two purposes: -- -- * It can be used with functions parameterized by functor or monad classes. -- -- * It can be used as a base monad to which a series of monad -- transformers may be applied to construct a composite monad. -- Most monad transformer modules include the special case of -- applying the transformer to 'Identity'. For example, @State s@ -- is an abbreviation for @StateT s 'Identity'@. -- -- @since 4.8.0.0 ----------------------------------------------------------------------------- module Data.Functor.Identity ( Identity(..), ) where import Control.Monad.Fix import Data.Bits (Bits, FiniteBits) import Data.Coerce import Data.Foldable import Data.Functor.Utils ((#.)) import Foreign.Storable (Storable) import GHC.Arr (Ix) import GHC.Base ( Applicative(..), Eq(..), Functor(..), Monad(..) , Monoid, Ord(..), ($), (.) ) import GHC.Enum (Bounded, Enum) import GHC.Float (Floating, RealFloat) import GHC.Generics (Generic, Generic1) import GHC.Num (Num) import GHC.Read (Read(..), lex, readParen) import GHC.Real (Fractional, Integral, Real, RealFrac) import GHC.Show (Show(..), showParen, showString) import GHC.Types (Bool(..)) -- | Identity functor and monad. (a non-strict monad) -- -- @since 4.8.0.0 newtype Identity a = Identity { runIdentity :: a } deriving ( Bits, Bounded, Enum, Eq, FiniteBits, Floating, Fractional , Generic, Generic1, Integral, Ix, Monoid, Num, Ord , Real, RealFrac, RealFloat, Storable) -- | This instance would be equivalent to the derived instances of the -- 'Identity' newtype if the 'runIdentity' field were removed -- -- @since 4.8.0.0 instance (Read a) => Read (Identity a) where readsPrec d = readParen (d > 10) $ \ r -> [(Identity x,t) | ("Identity",s) <- lex r, (x,t) <- readsPrec 11 s] -- | This instance would be equivalent to the derived instances of the -- 'Identity' newtype if the 'runIdentity' field were removed -- -- @since 4.8.0.0 instance (Show a) => Show (Identity a) where showsPrec d (Identity x) = showParen (d > 10) $ showString "Identity " . showsPrec 11 x -- --------------------------------------------------------------------------- -- Identity instances for Functor and Monad -- | @since 4.8.0.0 instance Foldable Identity where foldMap = coerce elem = (. runIdentity) #. (==) foldl = coerce foldl' = coerce foldl1 _ = runIdentity foldr f z (Identity x) = f x z foldr' = foldr foldr1 _ = runIdentity length _ = 1 maximum = runIdentity minimum = runIdentity null _ = False product = runIdentity sum = runIdentity toList (Identity x) = [x] -- | @since 4.8.0.0 instance Functor Identity where fmap = coerce -- | @since 4.8.0.0 instance Applicative Identity where pure = Identity (<*>) = coerce -- | @since 4.8.0.0 instance Monad Identity where m >>= k = k (runIdentity m) -- | @since 4.8.0.0 instance MonadFix Identity where mfix f = Identity (fix (runIdentity . f))
olsner/ghc
libraries/base/Data/Functor/Identity.hs
Haskell
bsd-3-clause
3,919
import Control.Exception import System.Environment import Control.Monad.Par.Scheds.Trace -- NB. using Trace here, Direct is too strict and forces the fibs in -- the parent; see https://github.com/simonmar/monad-par/issues/27 -- <<fib fib :: Integer -> Integer fib 0 = 1 fib 1 = 1 fib n = fib (n-1) + fib (n-2) -- >> main = do args <- getArgs let [n,m] = map read args print $ -- <<runPar runPar $ do i <- new -- <1> j <- new -- <1> fork (put i (fib n)) -- <2> fork (put j (fib m)) -- <2> a <- get i -- <3> b <- get j -- <3> return (a+b) -- <4> -- >>
lywaterman/parconc-examples
parmonad.hs
Haskell
bsd-3-clause
747
{-# LANGUAGE TemplateHaskell #-} module T15502 where import Language.Haskell.TH.Syntax (Lift(lift)) main = print ( $( lift (toInteger (maxBound :: Int) + 1) ) , $( lift (minBound :: Int) ) )
sdiehl/ghc
testsuite/tests/th/T15502.hs
Haskell
bsd-3-clause
221
{-# LANGUAGE TypeFamilies #-} module C where import A data C type instance F (a,C) = Bool
shlevy/ghc
testsuite/tests/driver/recomp017/C2.hs
Haskell
bsd-3-clause
90
{-# LANGUAGE TypeFamilies #-} {-# OPTIONS_GHC -fno-unbox-small-strict-fields #-} -- Makes f2 a bit more challenging module Foo where h :: Int -> Int -> Bool h 0 y = y>0 h n y = h (n-1) y -- The main point: all of these functions can have the CPR property ------- f1 ----------- -- x is used strictly by h, so it'll be available -- unboxed before it is returned in the True branch f1 :: Int -> Int f1 x = case h x x of True -> x False -> f1 (x-1) ------- f2 ----------- -- x is a strict field of MkT2, so we'll pass it unboxed -- to $wf2, so it's available unboxed. This depends on -- the case expression analysing (a subcomponent of) one -- of the original arguments to the function, so it's -- a bit more delicate. data T2 = MkT2 !Int Int f2 :: T2 -> Int f2 (MkT2 x y) | y>0 = f2 (MkT2 x (y-1)) | y>1 = 1 | otherwise = x ------- f3 ----------- -- h is strict in x, so x will be unboxed before it -- is rerturned in the otherwise case. data T3 = MkT3 Int Int f1 :: T3 -> Int f1 (MkT3 x y) | h x y = f3 (MkT3 x (y-1)) | otherwise = x ------- f4 ----------- -- Just like f2, but MkT4 can't unbox its strict -- argument automatically, as f2 can data family Foo a newtype instance Foo Int = Foo Int data T4 a = MkT4 !(Foo a) Int f4 :: T4 Int -> Int f4 (MkT4 x@(Foo v) y) | y>0 = f4 (MkT4 x (y-1)) | otherwise = v
urbanslug/ghc
testsuite/tests/stranal/T10482a.hs
Haskell
bsd-3-clause
1,448
import Control.Exception import Control.DeepSeq main = evaluate (('a' : undefined) `deepseq` return () :: IO ())
ezyang/ghc
testsuite/tests/simplCore/should_fail/T7411.hs
Haskell
bsd-3-clause
113
-- !!! Monomorphism restriction -- This one should work fine, despite the monomorphism restriction -- Fails with GHC 5.00.1 module Test where import Control.Monad.ST import Data.STRef -- Should get -- apa :: forall s. ST s () apa = newSTRef () >> return () foo1 = runST apa
forked-upstream-packages-for-ghcjs/ghc
testsuite/tests/typecheck/should_compile/tc132.hs
Haskell
bsd-3-clause
278
module ShouldSucceed where f x = a a = (x,x) x = x
urbanslug/ghc
testsuite/tests/typecheck/should_compile/tc021.hs
Haskell
bsd-3-clause
54
module Main where import Tracks.Network import Tracks.Service import Tracks.Train import Tracks.Signals (Signals) import qualified Tracks.Signals as Signals import Control.Monad.STM import Control.Concurrent import qualified STMContainers.Set as Set import System.Random foxhole, riverford, tunwall, maccton, welbridge :: Station foxhole = Station "Foxhole" riverford = Station "Riverford" tunwall = Station "Tunwall" maccton = Station "Maccton" welbridge = Station "Welbridge" foxLine, newLine :: Line foxLine = Line "Fox" newLine = Line "New" main :: IO () main = do network <- readTracksFile "test.tracks" services <- readServicesFile "test.services" putStrLn $ writeTracksCommands network signals <- atomically Signals.clear forkIO $ startTrain "001" foxLine 1 services signals network forkIO $ startTrain "002" foxLine 1 services signals network forkIO $ startTrain "A01" newLine 1 services signals network getLine return () startTrain :: String -> Line -> Int -> Services -> Signals -> Network -> IO () startTrain name line num services signals network = do let service = getLineService num line services train <- atomically $ placeTrain name service line signals network case train of Just t -> do print t runTrain t Nothing -> do threadDelay (500 * 1000) startTrain name line num services signals network runTrain :: Train -> IO () runTrain train = do train' <- atomically $ stepTrain train print train' gen <- newStdGen let (delay, _) = randomR (200000, 500000) gen threadDelay delay runTrain train'
derkyjadex/tracks
Main.hs
Haskell
mit
1,749
import Algorithms.MDP.Examples.Ex_3_1 import Algorithms.MDP import Algorithms.MDP.ValueIteration import qualified Data.Vector as V converging :: Double -> (CF State Control Double, CF State Control Double) -> Bool converging tol (cf, cf') = abs (x - y) > tol where x = (\(_, _, c) -> c) (cf V.! 0) y = (\(_, _, c) -> c) (cf' V.! 0) iterations = valueIteration mdp main = do mapM_ (putStrLn . showAll) $ take 100 iterations where showCosts cf = V.map (\(_, _, c) -> c) cf showActions cf = V.map (\(_, a, _) -> a) cf showAll cf = show (showCosts cf) ++ " " ++ show (showActions cf)
prsteele/mdp
src/run-ex-3-1.hs
Haskell
mit
634
len = fromIntegral . length rnd n x = (fromIntegral (floor (x * t))) / t where t = 10^n put = putStrLn . show mean xs = sum xs / (len xs) stddev xs = sqrt $ var xs var xs = (/(n-1)) $ sum [(x - m)^2 | x <- xs] where m = mean xs n = len xs covar xs ys = (/(n - 1)) . sum $ zipWith (*) [x - xm | x <- xs] [y - ym | y <- ys] where xm = mean xs ym = mean ys n = len xs correl xs ys = (/ (sdx * sdy)) $ covar xs ys where sdx = stddev xs sdy = stddev ys linreg xs ys = \x -> b0 + b1 * x where r = correl xs ys b1 = r * (stddev ys)/(stddev xs) b0 = (mean ys) - b1*(mean xs) main = do let xs = [20,31,33,35,38,38,44] ys = [430,580,570,550,660,690,650] r = correl xs ys put $ r^2 put $ (linreg xs ys) 20 let b1 = r * (stddev ys)/(stddev xs) let b0 = (mean ys) - b1*(mean xs) put $ b1 put $ b0
wd0/-stats
correl.hs
Haskell
mit
903
module SimpSymb where az = ['a'..'z'] data XPlus = '+' | '=' -- false x = ('+',x,'+',x,'+')
HaskellForCats/HaskellForCats
simpSymb.hs
Haskell
mit
96
{-# LANGUAGE ScopedTypeVariables, ViewPatterns #-} {-| Module : Labyrinth.AStar Description : pathfinding Copyright : (c) deweyvm 2014 License : MIT Maintainer : deweyvm Stability : experimental Portability : unknown Implementation of the A* (A star) pathfinding algorithm. -} module Labyrinth.Pathing.AStar(pfind) where import Prelude hiding(elem, all) import qualified Data.Map as Map import qualified Data.PSQueue as Q import qualified Data.Set as Set import Labyrinth.Graph import Labyrinth.Util import Labyrinth.Pathing.Util data Path b = Path (Set.Set b) -- closed set (Map.Map b Float) -- g score (Q.PSQ b Float) -- f score, open set (Map.Map b b) -- path so far b -- goal node mkPath :: Ord a => Heuristic a -> a -> a -> Path a mkPath l start goal = Path Set.empty (Map.singleton start 0) (Q.singleton start $ l start goal) Map.empty goal pathHelper :: forall a b c.(Ord c, Graph a b c) => Heuristic c -> a b -> Path c -> Either String [c] pathHelper h graph (Path closedSet gs fsop path goal) = case Q.minView fsop of Just (current, newOpen) -> processCurrent (Q.key current) newOpen Nothing -> Left "Found no path" where processCurrent :: c -> Q.PSQ c Float -> Either String [c] processCurrent currentNode open = let newClosed = Set.insert currentNode closedSet in if currentNode == goal then Right $ rewindPath path goal [] else let ns = getNeighbors graph currentNode (gs', fsop', path') = foldl (updatePath h goal currentNode newClosed) (gs, open, path) ns in pathHelper h graph (Path newClosed gs' fsop' path' goal) updatePath :: Ord a => Heuristic a -> a -> a -> Set.Set a -> (Map.Map a Float, Q.PSQ a Float, Map.Map a a) -> (a, Float) -> (Map.Map a Float, Q.PSQ a Float, Map.Map a a) updatePath h goal current closed s@(gs, fs, p) (nnode, ncost) = if Set.member nnode closed then s else case Map.lookup current gs of Just g -> let g' = g + ncost in if g' < g || not (qMember nnode fs) then let f = (g' + h nnode goal) in let newPath = Map.insert nnode current p in let newGs = Map.insert nnode g' gs in let newFsop = Q.insert nnode f fs in (newGs, newFsop, newPath) else s Nothing -> error "data structure inconsistent" {- | Find a path from the start node to the goal node. Given an admissible heuristic, this will also be a shortest path.-} pfind :: (Ord c, Graph a b c) => Heuristic c -- ^ The pathfinding heuristic -> a b -- ^ The graph to be traversed -> c -- ^ The start node -> c -- ^ The goal node -> Either String [c] {- ^ Either a string explaining why a path could not be found, or the found shortest path in order from start to goal.-} pfind h graph start goal = pathHelper h graph $ mkPath h start goal
deweyvm/labyrinth
src/Labyrinth/Pathing/AStar.hs
Haskell
mit
3,410
module Cases.Prelude ( module Exports, (?:), (|>), (<|), (|$>), ) where -- base ------------------------- import Control.Applicative as Exports hiding (WrappedArrow(..)) import Control.Arrow as Exports hiding (first, second) import Control.Category as Exports import Control.Concurrent as Exports import Control.Exception as Exports import Control.Monad as Exports hiding (fail, mapM_, sequence_, forM_, msum, mapM, sequence, forM) import Control.Monad.IO.Class as Exports import Control.Monad.Fail as Exports import Control.Monad.Fix as Exports hiding (fix) import Control.Monad.ST as Exports import Data.Bifunctor as Exports import Data.Bits as Exports import Data.Bool as Exports import Data.Char as Exports import Data.Coerce as Exports import Data.Complex as Exports import Data.Data as Exports import Data.Dynamic as Exports import Data.Either as Exports import Data.Fixed as Exports import Data.Foldable as Exports hiding (toList) import Data.Function as Exports hiding (id, (.)) import Data.Functor as Exports import Data.Functor.Compose as Exports import Data.Int as Exports import Data.IORef as Exports import Data.Ix as Exports import Data.List as Exports hiding (sortOn, isSubsequenceOf, uncons, concat, foldr, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, find, maximumBy, minimumBy, mapAccumL, mapAccumR, foldl') import Data.List.NonEmpty as Exports (NonEmpty(..)) import Data.Maybe as Exports import Data.Monoid as Exports hiding (Alt, (<>)) import Data.Ord as Exports import Data.Proxy as Exports import Data.Ratio as Exports import Data.Semigroup as Exports hiding (First(..), Last(..)) import Data.STRef as Exports import Data.String as Exports import Data.Traversable as Exports import Data.Tuple as Exports import Data.Unique as Exports import Data.Version as Exports import Data.Void as Exports import Data.Word as Exports import Debug.Trace as Exports import Foreign.ForeignPtr as Exports import Foreign.Ptr as Exports import Foreign.StablePtr as Exports import Foreign.Storable as Exports import GHC.Conc as Exports hiding (orElse, withMVar, threadWaitWriteSTM, threadWaitWrite, threadWaitReadSTM, threadWaitRead) import GHC.Exts as Exports (IsList(..), lazy, inline, sortWith, groupWith) import GHC.Generics as Exports (Generic) import GHC.IO.Exception as Exports import GHC.OverloadedLabels as Exports import Numeric as Exports import Prelude as Exports hiding (Read, fail, concat, foldr, mapM_, sequence_, foldl1, maximum, minimum, product, sum, all, and, any, concatMap, elem, foldl, foldr1, notElem, or, mapM, sequence, id, (.)) import System.Environment as Exports import System.Exit as Exports import System.IO as Exports (Handle, hClose) import System.IO.Error as Exports import System.IO.Unsafe as Exports import System.Mem as Exports import System.Mem.StableName as Exports import System.Timeout as Exports import Text.ParserCombinators.ReadP as Exports (ReadP, readP_to_S, readS_to_P) import Text.ParserCombinators.ReadPrec as Exports (ReadPrec, readPrec_to_P, readP_to_Prec, readPrec_to_S, readS_to_Prec) import Text.Printf as Exports (printf, hPrintf) import Unsafe.Coerce as Exports (?:) :: Maybe a -> a -> a maybeA ?: b = fromMaybe b maybeA {-# INLINE (?:) #-} (|>) :: a -> (a -> b) -> b a |> aToB = aToB a {-# INLINE (|>) #-} (<|) :: (a -> b) -> a -> b aToB <| a = aToB a {-# INLINE (<|) #-} -- | -- The following are all the same: -- fmap f a == f <$> a == a |> fmap f == a |$> f -- -- This operator accomodates the left-to-right operators: >>=, >>>, |>. (|$>) = flip fmap {-# INLINE (|$>) #-}
nikita-volkov/cases
library/Cases/Prelude.hs
Haskell
mit
3,608
import BMSClipboard import System.Environment import Data.List import Debug.Trace import Data.Maybe sortObject a b | t1 < t2 = LT | t1 > t2 = GT | otherwise = compare c1 c2 where t1 = row(a) t2 = row(b) c1 = rawChannel(a) c2 = rawChannel(b) movePlayableNotesToBGM ([], bgmNotes) = bgmNotes movePlayableNotesToBGM ((noteToMove:otherPlayableNotes), bgmNotes) = let availableBGMChannels = iterate (+ 1) 1 matching channel note = ((row note) == (row noteToMove)) && (isBGM note) && ((bgmChannelIndex note) == channel) usable channel = isNothing $ find (matching channel) bgmNotes Just channelIndexToMoveTo = find usable availableBGMChannels movedNote = (setBGMChannel channelIndexToMoveTo) . (setLength 0) $ noteToMove in movePlayableNotesToBGM (otherPlayableNotes, (movedNote:bgmNotes)) bgmize objects = let sortedObjects = sortBy sortObject objects (bgmNotes, playableNotes) = partition isBGM sortedObjects in OK "Moved notes!" (movePlayableNotesToBGM (playableNotes, bgmNotes)) main = do contents <- getContents putStrLn $ processBMSClipboard bgmize contents
bemusic/bms-clipboarder
src/BGMize.hs
Haskell
mit
1,142
module Http.Response ( Response (..) , response ) where import Text.ParserCombinators.Parsec hiding (token) data Response = Response { statusLine :: StatusLine , headers :: [(String,String)] , body :: String } deriving (Show) data StatusLine = StatusLine { code :: Int , reasonPhrase :: String , version :: String } deriving (Show) statusLineDefaults :: StatusLine statusLineDefaults = StatusLine { code=500 , reasonPhrase="Unable to parse response" , version="HTTP/1.1" } responseDefaults :: Response responseDefaults = Response { statusLine=statusLineDefaults , headers=[] , body="" } -- TODO: better name (contrast with request) response :: String -> Response response text = case parse parseResponse "Response" text of Left err -> error $ "Parse error at " ++ show err Right res -> res crlf = string "\r\n" ctls = "\r\n" -- Any character (0-127), except for CTLs and separators token = many (alphaNum <|> oneOf "!#$%&'*+-.^_`|~") parseResponse :: Parser Response parseResponse = do sl <- parseStatusLine headers <- many parseHeader crlf body <- many anyChar eof return Response { statusLine = sl, headers = headers, body = body } parseHeader :: Parser (String,String) parseHeader = do name <- token char ':' spaces val <- many1 $ noneOf ctls crlf return (name,val) parseVersion :: Parser String parseVersion = do string vPrefix major <- many1 digit char '.' minor <- many1 digit return $ vPrefix ++ major ++ "." ++ minor where vPrefix = "HTTP/" parseStatusLine :: Parser StatusLine parseStatusLine = do version <- parseVersion space code <- count 3 digit space reason <- many $ noneOf "\r\n" crlf return StatusLine { code = read code :: Int, reasonPhrase = reason, version = version }
ndreynolds/hsURL
src/Http/Response.hs
Haskell
mit
2,472
{-# LANGUAGE MagicHash, MultiParamTypeClasses, TypeFamilies, DataKinds, FlexibleContexts #-} module JavaFX.Types where import Java data {-# CLASS "javafx.stage.Stage" #-} Stage = Stage (Object# Stage) deriving Class data {-# CLASS "javafx.scene.Scene" #-} Scene = Scene (Object# Scene) deriving Class data {-# CLASS "javafx.scene.Group" #-} Group = Group (Object# Group) deriving Class data {-# CLASS "javafx.scene.canvas.Canvas" #-} Canvas = Canvas (Object# Canvas) deriving Class data {-# CLASS "javafx.scene.canvas.Canvas[]" #-} Canvases = Canvases (Object# Canvases) deriving Class instance JArray Canvas Canvases data {-# CLASS "javafx.scene.canvas.GraphicsContext" #-} GraphicsContext = GraphicsContext (Object# GraphicsContext) deriving Class data {-# CLASS "javafx.scene.Node" #-} Node = Node (Object# Node) deriving Class data {-# CLASS "javafx.scene.Node[]" #-} Nodes = Nodes (Object# Nodes) deriving Class instance JArray Node Nodes data {-# CLASS "javafx.scene.Parent" #-} Parent = Parent (Object# Parent) deriving Class type instance Inherits Group = '[Parent] type instance Inherits Canvas = '[Node]
filippovitale/eta-playground
javafx-canvas-grid/src/JavaFX/Types.hs
Haskell
mit
1,166
module ProjectEuler.Problem004Spec (main, spec) where import Test.Hspec import ProjectEuler.Problem004 main :: IO () main = hspec spec spec :: Spec spec = parallel $ describe "solve" $ it "finds the largest palindrome product of two 3-digit numbers" $ solve 3 `shouldBe` 906609
hachibu/project-euler
test/ProjectEuler/Problem004Spec.hs
Haskell
mit
293
{-# LANGUAGE TupleSections #-} module Main where import SparseMatrix import Data.List (sortOn) import qualified System.IO.Strict as Strict import Data.Map.Strict (fromList, toList) main :: IO () main = Strict.readFile "hackage.graph.hs" >>= mapM_ print . (fmap . fmap) (*100) . take 20 . sortOn (negate . snd) . toList . pageRank 0.85 2 . fromList . (read :: String -> [(String,[String])])
Magnap/pagerank-hs
src/Main.hs
Haskell
mit
399
-- | Common helpers for the tests. module TestCommon ( mkApp' , key ) where import API (serveApp) import App (AppConfig(..), mkApp) import Control.Monad.Logger (runStderrLoggingT, filterLogger, LogLevel(..)) import qualified Data.Map.Strict as M import Mailgun.APIKey (APIKey(..)) import Network.Wai (Application) key :: APIKey key = APIKey "key-49487a3bbead016679ec337d1a99bcf1" testConfig :: AppConfig testConfig = AppConfig { _configMailgunApiKey = key , _configConnectionString = ":memory:" , _configConnections = 1 , _configSchedules = M.fromList [] , _configHttpPort = Nothing , _configHttpsPort = Nothing , _configCertificate = Nothing } mkApp' :: IO Application mkApp' = runStderrLoggingT . filterLogger (const (> LevelDebug)) $ serveApp <$> mkApp testConfig
fusionapp/catcher-in-the-rye
test/TestCommon.hs
Haskell
mit
845
-- | Functions for working with Jalaali calendar system. -- This library mimics the API of "Data.Time.Calendar.Gregorian". module Data.Time.Calendar.Jalaali ( isJalaaliLeapYear , toJalaali , fromJalaali , fromJalaaliValid , jalaaliMonthLength , showJalaali , addJalaaliMonthsClip , addJalaaliMonthsRollOver , addJalaaliYearsClip , addJalaaliYearsRollOver , addJalaaliDurationClip , addJalaaliDurationRollOver ) where import Data.List (foldl') import Data.Time.Calendar (Day, CalendarDiffDays(CalendarDiffDays), addDays, fromGregorian, toGregorian) -- | Convert to Jalaali calendar. First element of result is year, second month -- number (1-12), third day (1-31). toJalaali :: Day -> (Integer, Int, Int) toJalaali d = (toInteger jy, jm, jd) where (gy, gm, gd) = toGregorian d (jy, jm, jd) = d2j $ g2d (fromInteger gy) gm gd -- | Convert from Jalaali calendar. First argument is year, second month -- number (1-12), third day (1-31). Invalid values will be clipped to the -- correct range, month first, then day. fromJalaali :: Integer -> Int -> Int -> Day fromJalaali jy jm jd = fromGregorian (toInteger gy) gm gd where jmv = max 1 (min 12 jm) jdv = max 1 (min 31 jd) jdv2 = min jdv (jalaaliMonthLength jy jmv) (gy, gm, gd) = d2g $ j2d (fromInteger jy) jmv jdv2 -- | Convert from Jalaali calendar. First argument is year, second month -- number (1-12), third day (1-31). Invalid values will return Nothing. fromJalaaliValid :: Integer -> Int -> Int -> Maybe Day fromJalaaliValid jy jm jd | jy < (-61) = Nothing | jy > 3177 = Nothing | jm < 1 = Nothing | jm > 12 = Nothing | jd < 1 = Nothing | jd > jalaaliMonthLength jy jm = Nothing | otherwise = Just $ fromJalaali jy jm jd -- | Show in slash-separated format (yyyy/mm/dd). showJalaali :: Day -> String showJalaali d = show jy ++ "/" ++ zeroPad jm ++ "/" ++ zeroPad jd where (jy, jm, jd) = toJalaali d zeroPad n = if n < 10 then "0" ++ show n else show n -- | The number of days in a given month according to the Jalaali calendar. -- First argument is year, second is month. jalaaliMonthLength :: Integer -> Int -> Int jalaaliMonthLength jy jm | jm <= 6 = 31 | jm <= 11 = 30 | isJalaaliLeapYear jy = 30 | otherwise = 29 -- | Add months, with days past the last day of the month clipped to the last -- day. For instance, 1400/05/31 + 7 months = 1400/12/29. addJalaaliMonthsClip :: Integer -> Day -> Day addJalaaliMonthsClip m d = fromJalaali jyn jmn jdn where (jy, jm, jd) = toJalaali d jyn = toInteger (((fromInteger m) + jm - 1) `div` 12) + jy jmn = (((fromInteger m) + jm - 1) `mod` 12) + 1 jdn = min jd (jalaaliMonthLength jyn jmn) -- | Add months, with days past the last day of the month rolling over to the -- next month. For instance, 1400/05/31 + 7 months = 1401/01/02. addJalaaliMonthsRollOver :: Integer -> Day -> Day addJalaaliMonthsRollOver m d = addDays (toInteger (jd - jdn)) $ fromJalaali jyn jmn jdn where (jy, jm, jd) = toJalaali d jyn = toInteger (((fromInteger m) + jm - 1) `div` 12) + jy jmn = (((fromInteger m) + jm - 1) `mod` 12) + 1 jdn = min jd (jalaaliMonthLength jyn jmn) -- | Add years, matching month and day, with Esfand 30th clipped to Esfand 29th -- if necessary. For instance, 1399/12/30 + 1 year = 1400/12/29. addJalaaliYearsClip :: Integer -> Day -> Day addJalaaliYearsClip y d = fromJalaali jyn jmn jdn where (jy, jm, jd) = toJalaali d jyn = y + jy jmn = jm jdn = min jd (jalaaliMonthLength jyn jmn) -- | Add years, matching month and day, with Esfand 30th rolled over to -- Farvardin 1st if necessary. For instance, 1399/12/30 + 1 year = 1401/01/01. addJalaaliYearsRollOver :: Integer -> Day -> Day addJalaaliYearsRollOver y d = addDays (toInteger (jd - jdn)) $ fromJalaali jyn jmn jdn where (jy, jm, jd) = toJalaali d jyn = y + jy jmn = jm jdn = min jd (jalaaliMonthLength jyn jmn) -- | Add months (clipped to last day), then add days. addJalaaliDurationClip :: CalendarDiffDays -> Day -> Day addJalaaliDurationClip (CalendarDiffDays dm dd) d = addDays dd $ addJalaaliMonthsClip dm d -- | Add months (rolling over to next month), then add days. addJalaaliDurationRollOver :: CalendarDiffDays -> Day -> Day addJalaaliDurationRollOver (CalendarDiffDays dm dd) d = addDays dd $ addJalaaliMonthsRollOver dm d -- | Is this year a leap year according to the Jalaali calendar? isJalaaliLeapYear :: Integer -> Bool isJalaaliLeapYear jy = leap == 0 where (leap, _, _) = jalCal (fromInteger jy) ---------------------------------------------- type JalaaliYear = Int type JalaaliMonth = Int type JalaaliDay = Int type GregorianYear = Int type GregorianMonth = Int type GregorianDay = Int type JulianDayNumber = Int type DayInMarch = Int type LeapOffset = Int type JalaaliDate = (JalaaliYear, JalaaliMonth, JalaaliDay) type GregorianDate = (GregorianYear, GregorianMonth, GregorianDay) -- Jalaali years starting the 33-year rule. breaks :: [JalaaliYear] breaks = [ -61, 9, 38, 199, 426, 686, 756, 818, 1111, 1181, 1210 , 1635, 2060, 2097, 2192, 2262, 2324, 2394, 2456, 3178 ] {- This function determines if the Jalaali (Persian) year is leap (366-day long) or is the common year (365 days), and finds the day in March (Gregorian calendar) of the first day of the Jalaali year (jy). @param jy Jalaali calendar year (-61 to 3177) @return leap: number of years since the last leap year (0 to 4) gy: Gregorian year of the beginning of Jalaali year march: the March day of Farvardin the 1st (1st day of jy) @see: http://www.astro.uni.torun.pl/~kb/Papers/EMP/PersianC-EMP.htm @see: http://www.fourmilab.ch/documents/calendar/ -} jalCal :: JalaaliYear -> (LeapOffset, GregorianYear, DayInMarch) jalCal jy | jy < (-61) = error ("invalid Jalaali year " ++ show jy ++ ", should be >= -61") | jy > 3177 = error ("invalid Jalaali year " ++ show jy ++ ", should be <= 3177") | otherwise = (leap, gy, dayInMarch) where gy = jy + 621 quot4 = (`quot` 4) quot33 = (`quot` 33) mod33 = (`mod` 33) (before, after) = break (jy <) breaks n = jy - last before years = before ++ if null after then [] else [head after] jumps = zipWith (-) (drop 1 years) years lastJump = last jumps -- Find the limiting years for the Jalaali year jy. leapJ' = foldl' (\acc jump -> acc + quot33 jump * 8 + quot4 (mod33 jump)) (-14) (init jumps) -- Find the number of leap years from AD 621 to the beginning -- of the current Jalaali year in the Persian calendar. leapJ'' = leapJ' + quot33 n * 8 + quot4 (mod33 n + 3) leapJ = leapJ'' + if mod33 lastJump == 4 && (lastJump - n) == 4 then 1 else 0 -- And the same in the Gregorian calendar (until the year gy). leapG = quot4 gy - quot4 (((gy `quot` 100) + 1) * 3) - 150 -- Determine the Gregorian date of Farvardin the 1st. dayInMarch = 20 + leapJ - leapG -- Find how many years have passed since the last leap year. n' = n + if lastJump - n < 6 then quot33 (lastJump + 4) * 33 - lastJump else 0 leap' = (mod33 (n' + 1) - 1) `mod` 4 leap = if leap' == -1 then 4 else leap' {- Converts a date of the Jalaali calendar to the Julian Day number. @param jy Jalaali year (1 to 3100) @param jm Jalaali month (1 to 12) @param jd Jalaali day (1 to 29/31) @return Julian Day number -} j2d :: JalaaliYear -> JalaaliMonth -> JalaaliDay -> JulianDayNumber j2d jy jm jd = jdn + (jm - 1) * 31 - (jm `quot` 7) * (jm - 7) + jd - 1 where (_, gy, dayInMarch) = jalCal jy jdn = g2d gy 3 dayInMarch {- Converts the Julian Day number to a date in the Jalaali calendar. @param jdn Julian Day number @return jy: Jalaali year (1 to 3100) jm: Jalaali month (1 to 12) jd: Jalaali day (1 to 29/31) -} d2j :: JulianDayNumber -> JalaaliDate d2j jdn = (jy, jm, jd) where (gy, _, _) = d2g jdn jy' = gy - 621 (leap, _, dayInMarch) = jalCal jy' jdn1f = g2d gy 3 dayInMarch k' = jdn - jdn1f k | k' >= 0 && k' <= 185 = k' | k' >= 0 = k' - 186 | otherwise = k' + 179 + if leap == 1 then 1 else 0 jy = jy' - if k' < 0 then 1 else 0 -- Previous Jalaali year. jm = if k' >= 0 && k' <= 185 then 1 + (k `quot` 31) else 7 + (k `quot` 30) jd = (+) 1 (mod k (if k' >= 0 && k' <= 185 then 31 else 30)) {- Calculates the Julian Day number from Gregorian or Julian calendar dates. This integer number corresponds to the noon of the date (i.e. 12 hours of Universal Time). The procedure was tested to be good since 1 March, -100100 (of both calendars) up to a few million years into the future. @param gy Calendar year (years BC numbered 0, -1, -2, ...) @param gm Calendar month (1 to 12) @param gd Calendar day of the month (1 to 28/29/30/31) @return Julian Day number -} g2d :: GregorianYear -> GregorianMonth -> GregorianDay -> JulianDayNumber g2d gy gm gd = d - ((((gy + 100100 + ((gm - 8) `quot` 6)) `quot` 100) * 3) `quot` 4) + 752 where d = ((gy + ((gm - 8) `quot` 6) + 100100) * 1461) `quot` 4 + (153 * ((gm + 9) `mod` 12) + 2) `quot` 5 + gd - 34840408 {- Calculates Gregorian and Julian calendar dates from the Julian Day number (jdn) for the period since jdn=-34839655 (i.e. the year -100100 of both calendars) to some millions years ahead of the present. @param jdn Julian Day number @return gy: Calendar year (years BC numbered 0, -1, -2, ...) gm: Calendar month (1 to 12) gd: Calendar day of the month M (1 to 28/29/30/31) -} d2g :: JulianDayNumber -> GregorianDate d2g jdn = (gy, gm, gd) where j' = 4 * jdn + 139361631 j = j' + ((((4 * jdn + 183187720) `quot` 146097) * 3) `quot` 4) * 4 - 3908 i = ((j `mod` 1461) `quot` 4) * 5 + 308 gd = ((i `mod` 153) `quot` 5) + 1 gm = ((i `quot` 153) `mod` 12) + 1 gy = (j `quot` 1461) - 100100 + ((8 - gm) `quot` 6)
jalaali/jalaali-hs
src/Data/Time/Calendar/Jalaali.hs
Haskell
mit
10,023
import RecursiveContents (getRecursiveContents) simpleFind :: (FilePath -> Bool) -> FilePath -> IO [FilePath] simpleFind p path = do names <- getRecursiveContents path return (filter p names)
zhangjiji/real-world-haskell
ch9/SimpleFinder.hs
Haskell
mit
197
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} -- | -- Module : Network.OAuth.MuLens -- Copyright : (c) Joseph Abrahamson 2013 -- License : MIT -- -- Maintainer : me@jspha.com -- Stability : experimental -- Portability : non-portable -- -- Tiny, @Control.Lens@ compatibility layer. module Network.OAuth.MuLens ( -- * Basics view, set, -- * Generalizations over, foldMapOf, -- * Building (<&>), (&), (^.), (.~), (%~), ) where import Data.Functor.Identity import Data.Functor.Constant view :: ((a -> Constant a a) -> s -> Constant a s) -> s -> a view inj = foldMapOf inj id {-# INLINE view #-} over :: ((a -> Identity b) -> s -> Identity t) -> (a -> b) -> s -> t over inj f = runIdentity . inj (Identity . f) {-# INLINE over #-} set :: ((a -> Identity b) -> s -> Identity t) -> b -> s -> t set l = over l . const {-# INLINE set #-} foldMapOf :: ((a -> Constant r b) -> s -> Constant r t) -> (a -> r) -> s -> r foldMapOf inj f = getConstant . inj (Constant . f) {-# INLINE foldMapOf #-} infixl 5 <&> (<&>) :: Functor f => f a -> (a -> b) -> f b (<&>) = flip (<$>) {-# INLINE (<&>) #-} infixl 1 & (&) :: b -> (b -> c) -> c (&) = flip ($) {-# INLINE (&) #-} infixl 8 ^. (^.) :: s -> ((a -> Constant a a) -> s -> Constant a s) -> a (^.) = flip view {-# INLINE (^.) #-} infixr 4 .~ (.~) :: ((a -> Identity b) -> s -> Identity t) -> b -> s -> t (.~) = set {-# INLINE (.~) #-} infixr 4 %~ (%~) :: ((a -> Identity b) -> s -> Identity t) -> (a -> b) -> s -> t (%~) = over {-# INLINE (%~) #-}
tel/oauthenticated
src/Network/OAuth/MuLens.hs
Haskell
mit
1,573
-- If the numbers 1 to 5 are written out in words: one, two, three, -- four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in -- total. -- If all the numbers from 1 to 1000 (one thousand) inclusive were -- written out in words, how many letters would be used? -- NOTE: Do not count spaces or hyphens. For example, 342 (three -- hundred and forty-two) contains 23 letters and 115 (one hundred and -- fifteen) contains 20 letters. The use of "and" when writing out -- numbers is in compliance with British usage. module Euler.Problem017 ( solution , spell ) where import Data.Char (isLetter) import Data.List (intercalate) solution :: Int -> Integer solution ceil = sum . map (toInteger . length . filter isLetter . spell) $ [1..ceil] spell :: Int -> String spell = intercalate " " . digits digits :: Int -> [String] digits n | n < 1 = [] | n < 20 = [smallNumbers n] | n < 100 = [tensAndOnes $ n `divMod` 10] | n < 1000 = hundredsPlus $ n `divMod` 100 | otherwise = [smallNumbers 1, scaleNumbers 1] hundredsPlus :: (Int, Int) -> [String] hundredsPlus (h, 0) = hundreds h hundredsPlus (h, t) = hundreds h ++ ["and"] ++ digits t hundreds :: Int -> [String] hundreds h = [smallNumbers h, scaleNumbers 0] tensAndOnes :: (Int, Int) -> String tensAndOnes (t, 0) = tens t tensAndOnes (t, o) = tens t ++ "-" ++ smallNumbers o smallNumbers :: Int -> String smallNumbers = (!!) [ "zero" , "one" , "two" , "three" , "four" , "five" , "six" , "seven" , "eight" , "nine" , "ten" , "eleven" , "twelve" , "thirteen" , "fourteen" , "fifteen" , "sixteen" , "seventeen" , "eighteen" , "nineteen" ] tens :: Int -> String tens = (!!) [ "" , "" , "twenty" , "thirty" , "forty" , "fifty" , "sixty" , "seventy" , "eighty" , "ninety" ] scaleNumbers :: Int -> String scaleNumbers = (!!) [ "hundred" , "thousand" ]
whittle/euler
src/Euler/Problem017.hs
Haskell
mit
2,402
{-# LANGUAGE TypeOperators #-} module Language.Sigil.Stack ( push , pop ) where import Control.Monad.Free import Language.Sigil.Types push :: a -> SigilProgram a () push x = liftF $ Push x () pop :: SigilProgram a () pop = liftF $ Pop () {- swap :: (s :. a :. b) -> (s :. b :. a) -} {- swap (s :. a :. b) = s :. b :. a -} {- swapd :: s :. a :. b :. c -> s :. b :. a :. c -} {- swapd (s :. a :. b :. c) = s :. b :. a :. c -} {- push :: a -> s -> s :. a -} {- push a s = s :. a -} {- pop :: (s :. a) -> s -} {- pop (s :. _) = s -} {- nip :: (s :. a :. b) -> (s :. b) -} {- nip (s :. _ :. b) = s :. b -} {- nip2 :: (s :. a :. b :. c) -> (s :. c) -} {- nip2 (s :. _ :. _ :. c) = s :. c -} {- rotr :: (s :. a :. b :. c) -> (s :. c :. a :. b) -} {- rotr (s :. a :. b :. c) = s :. c :. a :. b -} {- rotl :: (s :. a :. b :. c) -> (s :. b :. c :. a) -} {- rotl (s :. a :. b :. c) = s :. b :. c :. a -} {- dup :: s :. a -> s :. a :. a -} {- dup s@(_ :. a) = s :. a -} {- dup2 :: s :. a :. b -> s :. a :. b :. a :. b -} {- dup2 s@(_ :. a :. b) = s :. a :. b -} {- dupd :: s :. a :. b -> s :. a :. a :. b -} {- dupd (s :. a :. b) = s :. a :. a :. b -} {- over :: s :. a :. b -> s :. a :. b :. a -} {- over s@(_ :. a :. _) = s :. a -} {- over2 :: s :. a :. b :. c -> s :. a :. b :. c :. a :. b -} {- over2 s@(_ :. a :. b :. _) = s :. a :. b -} {- pick :: s :. a :. b :. c -> s :. a :. b :. c :. a -} {- pick s@(_ :. a :. _ :. _) = s :. a -}
erochest/sigil
Language/Sigil/Stack.hs
Haskell
apache-2.0
1,482
module Lab4 where fp :: Eq a => (a -> a) -> a -> a fp f = \ x -> if x == f x then x else fp f (f x)
bartolkaruza/software-testing-2014-group-W1
week4/Lab4.hs
Haskell
apache-2.0
103
module HEP.Automation.EventAnalysis.Command where import HEP.Automation.EventAnalysis.ProgType import HEP.Automation.EventAnalysis.Job commandLineProcess :: EventAnalysis -> IO () commandLineProcess (Single lhefp pdffp) = do putStrLn "test called" startSingle lhefp pdffp commandLineProcess (JsonTest fp) = do putStrLn "jsontest called" startJsonTest fp commandLineProcess (MultiAnalysis fp) = do putStrLn "jsontest called" startMultiAnalysis fp commandLineProcess (Junjie lhefp outfp) = do putStrLn "test called" startJunjie lhefp outfp commandLineProcess (LowMassAnalysis hsfp) = do startLowMassAnalysis hsfp
wavewave/EventAnalysis
lib/HEP/Automation/EventAnalysis/Command.hs
Haskell
bsd-2-clause
640
module Distribution.VcsRevision.Svn ( getRevision ) where import Control.Exception import System.Process import System.Exit import Data.List tryIO :: IO a -> IO (Either IOException a) tryIO = try -- | Nothing if we're not in a svn repo, Just (revision,modified) if we're in a repo. getRevision :: IO (Maybe (String, Bool)) getRevision = do res <- tryIO $ readProcessWithExitCode "svn" ["info"] "" case res of Left ex -> return Nothing Right (exit,info,_) -> case exit of ExitSuccess -> do let prefix = "Last Changed Rev: " let rev = drop (length prefix) $ head $ filter (prefix `isPrefixOf`) (lines info) (_,out,_) <- readProcessWithExitCode "svn" ["st", "-q"] "" return $ Just (rev, out /= "") _ -> return Nothing
jkff/vcs-revision
Distribution/VcsRevision/Svn.hs
Haskell
bsd-2-clause
775
module Module2.Task10 where avg :: Int -> Int -> Int -> Double avg a b c = fromIntegral (a + b + c) / 3
dstarcev/stepic-haskell
src/Module2/Task10.hs
Haskell
bsd-3-clause
105
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-} module Database.Dedalus.PrettyPrint where -- This code is initially based on -- https://github.com/pchiusano/datalog-refactoring/blob/master/src/PrettyPrint.hs import qualified Text.PrettyPrint as PP import Text.PrettyPrint (($$),(<>),(<+>)) import Control.Applicative import Database.Dedalus.Backend class Pretty p where doc :: p -> PP.Doc instance Pretty Con where doc = PP.text . conName instance Pretty Var where doc = PP.text . varName instance Pretty Term where doc = eitherTerm doc doc instance Pretty a => Pretty (Atom a) where doc (Atom p b) = doc p <> PP.parens (PP.hsep $ PP.punctuate PP.comma (doc <$> b)) instance Pretty Pat where doc (Pat p) = doc p doc (Not p) = PP.text "\\+" <+> doc p instance Pretty Rule where doc (Rule h b ts) = doc h <+> doc ts <+> PP.text ":-" <+> (PP.hsep $ PP.punctuate PP.comma (doc <$> b)) instance Pretty TimeSuffix where doc TSImplicit = PP.empty doc TSAsync = PP.text "@async" doc TSNext = PP.text "@next" doc (TS v) = PP.text "@" <> PP.text (show v) instance Pretty Fact where doc (Fact f ts) = doc f <+> doc ts instance Pretty [Rule] where doc [] = PP.empty doc (a:as) = doc a <> PP.text "." $$ doc as instance Pretty [Fact] where doc [] = PP.empty doc (a:as) = doc a <> PP.text "." $$ doc as instance Pretty ([Fact],[Rule]) where doc (x,y) = doc x $$ doc y -- instance Pretty Subst instance Pretty [(Var,Con)] where doc vs = PP.vcat $ map (\(v,n) -> doc v <+> PP.text "=" <+> doc n) vs instance Pretty [QueryResult] where doc [] = PP.text "no queries" doc rs = PP.vcat $ map (\(q,qr) -> doc q <+> PP.text " : " <+> doc qr) rs
alanz/hdedalus
src/Database/Dedalus/PrettyPrint.hs
Haskell
bsd-3-clause
1,773