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 CFDI.Types.ProductDescription where import CFDI.Chainable import CFDI.Types.Type import Data.Text (Text, pack, unpack) import Text.Regex (mkRegex) import Text.Regex.Posix (matchTest) newtype ProductDescription = ProductDescription Text deriving (Eq, Show) instance Chainable ProductDescription where chain (ProductDescription d) = d instance Type ProductDescription where parseExpr str | matchTest regExp str = Right . ProductDescription $ pack str | otherwise = Left $ DoesNotMatchExpr "[^|]{1,1000}" where regExp = mkRegex "^(.|á|é|í|ó|ú|ñ|Á|É|Í|Ó|Ú|Ñ){1,1000}$" render (ProductDescription d) = unpack d
yusent/cfdis
src/CFDI/Types/ProductDescription.hs
Haskell
mit
667
{-# LANGUAGE PackageImports, RecordWildCards #-} module GameState where import "GLFW-b" Graphics.UI.GLFW as GLFW import Graphics.Gloss.Rendering import Graphics.Gloss.Data.Color import Graphics.Gloss.Data.Picture import Control.Applicative import qualified Data.List as L import Math.Geometry.Grid.Hexagonal import Math.Geometry.Grid.HexagonalInternal import Math.Geometry.GridMap ((!)) import Board import Drawing import Textures -- | Definition for the game state data type. data GameState = GameState { tileMapState :: TileMap , mapPosition :: (Float, Float) , mapZoom :: Float , civColor :: Color , nextUnitInLine :: Maybe TileCoord , blinkAnimation :: (Float, Bool) } deriving Show -- | The main function to render the game state. renderView :: TextureMap -> GameState -> Picture renderView txMap gS@GameState{..} = views where (x, y) = mapPosition views = translate x y $ scale mapZoom mapZoom $ pictures (map (tilePicture txMap gS) tiles) -- | Renders a picture for a single tile. tilePicture :: TextureMap -> GameState -> TileCoord -- ^ The coordinate of the tile to be rendered. -> Picture tilePicture txMap gS@GameState{..} t = translate x y $ pictures [ tileView txMap tile , (improvementView txMap . tileImprovement) tile , (resourceView txMap . tileResource) tile , (unitView txMap gS t . tileUnit) tile ] where tile = tileMapState ! t (x, y) = tileLocationCenter t grey = makeColor (x/(x+y+0.2)) 1 (y/(x+y+0.2)) 1 -- | Basic drawing of a unit. unitView :: TextureMap -> GameState -> TileCoord -> Maybe Unit -> Picture unitView _ _ _ Nothing = Blank unitView txMap GameState{..} coord (Just Unit{..}) = pictures [ case unitKind of Settler -> "settler" `from` txMap Worker -> "worker" `from` txMap -- Worker -> color (blinky red) $ "worker" `from` txMap _ -> Blank , color (blinky civColor) $ thickCircle 80 10 ] where s = 50 blinky :: Color -> Color blinky c = case nextUnitInLine of Just x -> if coord == x then setAlpha c (fst blinkAnimation) else c _ -> c ------------------------------ -- Game state change functions ------------------------------ -- | The default settings of a game state. It is semi-random. initGameState :: IO GameState initGameState = do randomTMap <- randomTileMap -- example units added let tMap = replaceUnit (0,0) (Just $ Unit Settler 1 True) $ replaceUnit (2,3) (Just $ Unit Worker 1 True) $ replaceImprovement (0,0) (Just City) randomTMap return $ GameState tMap (0,0) 0.6 blue (Just (0,0)) (1.0, False) -- | Moves map to the opposite direction of the key, by the float number given. moveMap :: (Float, Float) -- ^ Indicates directions coming from getCursorKeyDirections. -> Float -- ^ Translation offset. -> GameState -- ^ Game state to be changed. -> GameState -- ^ New game state. moveMap (x,y) i gs@GameState{..} = gs { mapPosition = (x' + x * i, y' + y * i) } where (x', y') = mapPosition -- | Moves the unit in the given coordinate according to the key. moveUnitWithKey :: Maybe TileCoord -- ^ The coordinate of the unit to be moved. -> [Key] -- ^ The direction keys to determine the direction. -> GameState -- ^ Game state to be changed. -> GameState -- ^ New game state. moveUnitWithKey mCoord [k] gS@GameState{..} = case mCoord of Nothing -> gS Just c -> gS { tileMapState = moveUnitToDirection c dir tileMapState , nextUnitInLine = findNextUnitInLine $ deactivateNextUnitInLine c tileMapState } where dir = keyToDirection k moveUnitWithKey _ _ gS = gS -- | Assigns a hexagonal direction to the keys W,E,D,X,Z,A. -- Note that this is a partial function and it fails on other keys. keyToDirection :: Key -> HexDirection keyToDirection k = case k of Key'W -> Northwest Key'E -> Northeast Key'D -> East Key'X -> Southeast Key'Z -> Southwest Key'A -> West _ -> error "No hexagonal direction assigned for this key." -- | Takes keys about turn action and changes the game state. turnAction :: [Key] -- ^ Should only contain space. -> GameState -> GameState turnAction [Key'Space] gS@GameState{..} = case nextUnitInLine of Just c -> let newTMap = deactivateNextUnitInLine c tileMapState in gS { tileMapState = newTMap , nextUnitInLine = findNextUnitInLine newTMap } _ -> gS -- end turn or activate all units again turnAction _ gS = gS -- | Changes zoom scale in the game state with respect to a coefficient. changeScale :: Float -- ^ The coefficient to respond to. -> GameState -- ^ Game state to be changed. -> GameState -- ^ New game state. changeScale coeff gS@GameState{..} = gS { mapZoom = limited } where newZoom = mapZoom * ((coeff + 100.0) / 100) limited | newZoom < 0.2 = 0.2 | newZoom > 0.9 = 0.9 | otherwise = newZoom -- | Set state for blink animation. blink :: GameState -> GameState blink gS@GameState{..} = gS { blinkAnimation = y } where (x, inc) = blinkAnimation op = if inc then (+) else (-) i = 0.05 -- offset y = case () of _ | x < 0.3 && not inc -> (x + i, True) | x > 0.9 && inc -> (x - i, False) | otherwise -> (x `op` i, inc)
joom/civ
src/GameState.hs
Haskell
mit
5,819
-- These are the tests for our api. The only real interesting part is the -- 'main' function, were we specific that the test database is different -- from the production database. {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module Main (main) where import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (NoLoggingT(..)) import Data.Aeson (ToJSON, encode) import Data.ByteString (ByteString) import Database.Persist ((>=.), deleteWhere) import Database.Persist.Sql (toSqlKey) import Database.Persist.Sqlite (runMigration, runSqlConn, withSqliteConn) import Network.HTTP.Types.Method (methodPost, methodPut) import Network.Wai (Application) import Network.Wai.Test (SResponse) import Servant.Server (serve) import Test.Hspec (Spec, describe, hspec, it) import Test.Hspec.Wai ( WaiExpectation, WaiSession, delete, get, matchBody, request , shouldRespondWith, with ) import Lib (BlogPost(..), EntityField(..), blogPostApiProxy, migrateAll, server) -- | These are our actual unit tests. They should be relatively -- straightforward. -- -- This function is using 'app', which in turn accesses our testing -- database. spec :: IO Application -> Spec spec app = with app $ do describe "GET blogpost" $ do it "responds with 200 after inserting something" $ do postJson "/create" testBlogPost `shouldRespondWith` 201 get "/read/1" `shouldRespondWithJson` (200, testBlogPost) it "responds with 404 because nothing has been inserted" $ do get "/read/1" `shouldRespondWith` 404 describe "PUT blogpost" $ do it "responds with 204 even when key doesn't exist in DB" $ do putJson "/update/1" testBlogPost `shouldRespondWith` 204 it "can't GET after PUT" $ do putJson "/update/1" testBlogPost `shouldRespondWith` 204 get "/read/1" `shouldRespondWith` 404 describe "DELETE blogpost" $ do it "responds with 204 even when key doesn't exist in DB" $ do delete "/delete/1" `shouldRespondWith` 204 it "GET after DELETE returns 404" $ do postJson "/create" testBlogPost `shouldRespondWith` 201 get "/read/1" `shouldRespondWith` 200 delete "/delete/1" `shouldRespondWith` 204 get "/read/1" `shouldRespondWith` 404 where -- Send a type that can be turned into JSON (@a@) to the Wai -- 'Application' at the 'ByteString' url. This returns a 'SResponse' -- in the 'WaiSession' monad. This is similar to the 'post' function. postJson :: (ToJSON a) => ByteString -> a -> WaiSession SResponse postJson path = request methodPost path [("Content-Type", "application/json")] . encode -- Similar to 'postJson'. putJson :: (ToJSON a) => ByteString -> a -> WaiSession SResponse putJson path = request methodPut path [("Content-Type", "application/json")] . encode -- Similar to 'shouldRespondWith', but converts the second argument to -- JSON before it compares with the 'SResponse'. shouldRespondWithJson :: (ToJSON a) => WaiSession SResponse -> (Integer, a) -> WaiExpectation shouldRespondWithJson req (expectedStatus, expectedValue) = let matcher = (fromInteger expectedStatus) { matchBody = Just $ encode expectedValue } in shouldRespondWith req matcher -- An example blog post to use in tests. testBlogPost :: BlogPost testBlogPost = BlogPost "title" "content" -- | This is almost identical to the 'defaultMain' defined in "Lib", except -- that is it running against "testing.sqlite" instead of -- "production.sqlite". main :: IO () main = runNoLoggingT $ withSqliteConn "testing.sqlite" $ \conn -> do liftIO $ runSqlConn (runMigration migrateAll) conn liftIO $ putStrLn "\napi running on port 8080..." liftIO $ hspec $ spec $ do -- Before running each test, we have to remove all of the -- existing blog posts from the database. This ensures that -- it doesn't matter which order the tests are run in. runSqlConn (deleteWhere [BlogPostId >=. toSqlKey 0]) conn return . serve blogPostApiProxy $ server conn
cdepillabout/testing-code-that-accesses-db-in-haskell
with-db/testing-db/test/Test.hs
Haskell
apache-2.0
4,579
{-# LANGUAGE PackageImports #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE NoImplicitPrelude #-} {- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Internal.Color where import qualified "codeworld-api" CodeWorld as CW import Internal.Num import Internal.Truth import qualified "base" Prelude as P import "base" Prelude ((.)) -- | A color. -- -- Colors can be described in several ways: -- -- 1. Using common color names: 'red', 'blue', 'yellow', 'green', -- 'orange', 'purple', 'pink', 'black', 'white', 'brown', and -- 'gray'. -- 2. Transforming other colors with functions such as 'light', -- 'dark', 'bright', 'dull', 'translucent', and 'mixed'. -- 3. Constructing colors from coordinates in a color space, such -- as 'RGB', 'RGBA', or 'HSL'. -- -- Note that transparency is included in a color. Common color -- names and the 'RGB' and 'HSL' constructors only produce opaque -- colors, but 'RGBA' and the 'translucent' function work with -- transparency. newtype Color = Color {toCWColor :: CW.Color} deriving (P.Eq) -- | A synonym for 'Color', using the non-US spelling. type Colour = Color {-# RULES "equality/color" forall (x :: Color). (==) x = (P.==) x #-} pattern RGBA :: (Number, Number, Number, Number) -> Color pattern RGBA components <- (toRGBA -> components) where RGBA components = let (r, g, b, a) = components in Color ( CW.RGBA (toDouble r) (toDouble g) (toDouble b) (toDouble a) ) -- Utility function for RGB pattern synonym. toRGBA :: Color -> (Number, Number, Number, Number) toRGBA (Color (CW.RGBA r g b a)) = (fromDouble r, fromDouble g, fromDouble b, fromDouble a) pattern RGB :: (Number, Number, Number) -> Color pattern RGB components <- (toRGB -> P.Just components) where RGB components = let (r, g, b) = components in Color ( CW.RGBA (toDouble r) (toDouble g) (toDouble b) (toDouble 1) ) -- Utility function for RGB pattern synonym. toRGB :: Color -> P.Maybe (Number, Number, Number) toRGB (Color (CW.RGBA r g b (fromDouble -> 1))) = P.Just (fromDouble r, fromDouble g, fromDouble b) toRGB _ = P.Nothing pattern HSL :: (Number, Number, Number) -> Color pattern HSL components <- (toHSL -> P.Just components) where HSL components = fromHSL components -- Utility functions for HSL pattern synonym. toHSL :: Color -> P.Maybe (Number, Number, Number) toHSL c@(RGBA (_, _, _, 1)) = P.Just (hue c, saturation c, luminosity c) toHSL _ = P.Nothing fromHSL :: (Number, Number, Number) -> Color fromHSL (h, s, l) = Color (CW.HSL (toDouble (pi * h / 180)) (toDouble s) (toDouble l)) -- | Produces a color by mixing other colors in equal proportion. -- -- The order of colors is unimportant. Colors may be mixed in uneven -- proportions by listing a color more than once, such as -- @mixed([red, red, orange])@. mixed :: [Color] -> Color mixed = Color . CW.mixed . P.map toCWColor -- | Increases the luminosity of a color by the given amount. -- -- The amount should be between -1 and 1, where: -- -- * @lighter(c, 1)@ is always white, regardless of @c@. -- * @lighter(c, 0)@ is the same as @c@. -- * @lighter(c, -1)@ is always black, regardless of @c@. lighter :: (Color, Number) -> Color lighter (c, d) = Color (CW.lighter (toDouble d) (toCWColor c)) -- | Produces a lighter shade of the given color. -- -- This function may be nested more than once to produce an even -- lighter shade, as in @light(light(blue))@. light :: Color -> Color light = Color . CW.light . toCWColor -- | Decreases the luminosity of a color by the given amount. -- -- The amount should be between -1 and 1, where: -- -- * @darker(c, 1)@ is always black, regardless of @c@. -- * @darker(c, 0)@ is the same as @c@. -- * @darker(c, -1)@ is always white, regardless of @c@. darker :: (Color, Number) -> Color darker (c, d) = Color (CW.darker (toDouble d) (toCWColor c)) -- | Produces a darker shade of the given color. -- -- This function may be nested more than once to produce an even -- darker shade, as in @dark(dark(green))@. dark :: Color -> Color dark = Color . CW.dark . toCWColor -- | Increases the saturation of a color by the given amount. -- -- The amount should be between -1 and 1, where: -- -- * @brighter(c, 1)@ is a fully saturated version of @c@. -- * @brighter(c, 0)@ is the same as @c@. -- * @brighter(c, -1)@ is just a shade of gray with no color. brighter :: (Color, Number) -> Color brighter (c, d) = Color (CW.brighter (toDouble d) (toCWColor c)) -- | Produces a brighter shade of the given color; that is, less -- gray and more colorful. -- -- This function may be nested more than once to produce an even -- brighter shade, as in @bright(bright(yellow))@. bright :: Color -> Color bright = Color . CW.bright . toCWColor -- | Decreases the saturation of a color by the given amount. -- -- The amount should be between -1 and 1, where: -- -- * @duller(c, 1)@ is just a shade of gray with no color. -- * @duller(c, 0)@ is the same as @c@. -- * @duller(c, -1)@ is a fully saturated version of @c@. duller :: (Color, Number) -> Color duller (c, d) = Color (CW.duller (toDouble d) (toCWColor c)) -- | Produces a duller shade of the given color; that is, more -- gray and less colorful. -- -- This function may be nested more than once to produce an even -- duller shade, as in @dull(dull(purple))@. dull :: Color -> Color dull = Color . CW.dull . toCWColor -- | Produces a partially transparent color. -- -- This function may be nested more than once to produce an even -- more transparent color, as in @translucent(translucent(brown))@. translucent :: Color -> Color translucent = Color . CW.translucent . toCWColor -- | An infinite list of various colors. -- -- The list is chosen to contain a variety of different hues as -- spread out as possible to create colorful effects. assortedColors :: [Color] assortedColors = P.map Color CW.assortedColors hue, saturation, luminosity, alpha :: Color -> Number hue = (180 *) . (/ pi) . fromDouble . CW.hue . toCWColor saturation = fromDouble . CW.saturation . toCWColor luminosity = fromDouble . CW.luminosity . toCWColor alpha = fromDouble . CW.alpha . toCWColor -- New style colors -- | The color white white :: Color white = Color CW.white -- | The color black black :: Color black = Color CW.black -- | The color gray gray :: Color gray = Color CW.gray -- | The color grey -- -- This is the same color as 'gray', but with a non-US -- spelling. grey :: Color grey = Color CW.grey -- | The color red red :: Color red = Color CW.red -- | The color orange orange :: Color orange = Color CW.orange -- | The color yellow yellow :: Color yellow = Color CW.yellow -- | The color green green :: Color green = Color CW.green -- | The color blue blue :: Color blue = Color CW.blue -- | The color purple purple :: Color purple = Color CW.purple -- | The color pink pink :: Color pink = Color CW.pink -- | The color brown brown :: Color brown = Color CW.brown
google/codeworld
codeworld-base/src/Internal/Color.hs
Haskell
apache-2.0
7,724
{-# LANGUAGE MultiParamTypeClasses #-} -- |Collections which support efficient bulk insertion. module Data.Collections.BulkInsertable where import qualified Data.Set as S -- |The class of data structures to which can be appended. class BulkInsertable a b where bulkInsert :: a -> b -> b instance Ord a => BulkInsertable [a] (S.Set a) where bulkInsert xs ys = S.fromList xs `S.union` ys instance Ord a => BulkInsertable (S.Set a) (S.Set a) where bulkInsert = S.union instance BulkInsertable [a] [a] where bulkInsert = (++)
jtapolczai/Hephaestos
Data/Collections/BulkInsertable.hs
Haskell
apache-2.0
541
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} #include "version-compatibility-macros.h" -- | Common symbols composed out of the ASCII subset of Unicode. For non-ASCII -- symbols, see "Prettyprinter.Symbols.Unicode". module Prettyprinter.Symbols.Ascii where import Prettyprinter.Internal -- | >>> squotes "·" -- '·' squotes :: Doc ann -> Doc ann squotes = enclose squote squote -- | >>> dquotes "·" -- "·" dquotes :: Doc ann -> Doc ann dquotes = enclose dquote dquote -- | >>> parens "·" -- (·) parens :: Doc ann -> Doc ann parens = enclose lparen rparen -- | >>> angles "·" -- <·> angles :: Doc ann -> Doc ann angles = enclose langle rangle -- | >>> brackets "·" -- [·] brackets :: Doc ann -> Doc ann brackets = enclose lbracket rbracket -- | >>> braces "·" -- {·} braces :: Doc ann -> Doc ann braces = enclose lbrace rbrace -- | >>> squote -- ' squote :: Doc ann squote = Char '\'' -- | >>> dquote -- " dquote :: Doc ann dquote = Char '"' -- | >>> lparen -- ( lparen :: Doc ann lparen = Char '(' -- | >>> rparen -- ) rparen :: Doc ann rparen = Char ')' -- | >>> langle -- < langle :: Doc ann langle = Char '<' -- | >>> rangle -- > rangle :: Doc ann rangle = Char '>' -- | >>> lbracket -- [ lbracket :: Doc ann lbracket = Char '[' -- | >>> rbracket -- ] rbracket :: Doc ann rbracket = Char ']' -- | >>> lbrace -- { lbrace :: Doc ann lbrace = Char '{' -- | >>> rbrace -- } rbrace :: Doc ann rbrace = Char '}' -- | >>> semi -- ; semi :: Doc ann semi = Char ';' -- | >>> colon -- : colon :: Doc ann colon = Char ':' -- | >>> comma -- , comma :: Doc ann comma = Char ',' -- | >>> "a" <> space <> "b" -- a b -- -- This is mostly used via @'<+>'@, -- -- >>> "a" <+> "b" -- a b space :: Doc ann space = Char ' ' -- | >>> dot -- . dot :: Doc ann dot = Char '.' -- | >>> slash -- / slash :: Doc ann slash = Char '/' -- | >>> backslash -- \\ backslash :: Doc ann backslash = "\\" -- | >>> equals -- = equals :: Doc ann equals = Char '=' -- | >>> pipe -- | pipe :: Doc ann pipe = Char '|' -- $setup -- -- (Definitions for the doctests) -- -- >>> :set -XOverloadedStrings -- >>> import Data.Semigroup -- >>> import Prettyprinter.Render.Text -- >>> import Prettyprinter.Util
quchen/prettyprinter
prettyprinter/src/Prettyprinter/Symbols/Ascii.hs
Haskell
bsd-2-clause
2,232
{- This module is used to preprocess the AST before we - actually use it -} module DuckTest.AST.Preprocess (preprocess) where import DuckTest.Internal.Common import DuckTest.AST.Util import DuckTest.AST.BinaryOperators import qualified Data.Map as Map dunderFunctions :: Map String String dunderFunctions = Map.fromList [ ("len", "__len__"), ("str", "__str__"), ("int", "__int__") ] preprocess :: [Statement e] -> [Statement e] preprocess = map (mapExpressions proc) where proc (BinaryOp op@(In _) ex1 ex2 pos) = {- The in operator is backwards -} mapExpressions proc $ Call (Dot ex2 (Ident (toDunderName op) pos) pos) [ArgExpr ex1 pos] pos proc (BinaryOp op ex1 ex2 pos) = {- Convert all binary operators to their actual function calls - to make things easier -} mapExpressions proc $ Call (Dot ex1 (Ident (toDunderName op) pos) pos) [ArgExpr ex2 pos] pos proc ex@(Call (Var (Ident str _) _) [ArgExpr ex1 _] pos) {- Change known calls to dunder attributes. -} = mapExpressions proc $ maybe' (Map.lookup str dunderFunctions) ex $ \dunder -> Call (Dot ex1 (Ident dunder pos) pos) [] pos {- Expand out literals into functions -} proc ex@(Int _ _ pos) = Call (Var (Ident "int" pos) pos) [ArgExpr ex pos] pos proc ex@(Strings _ pos) = Call (Var (Ident "str" pos) pos) [ArgExpr ex pos] pos proc ex = mapExpressions proc ex
jrahm/DuckTest
src/DuckTest/AST/Preprocess.hs
Haskell
bsd-2-clause
1,593
module Kis ( KisRequest(..) , KisConfig(..) , KisClient , Kis(..) , KisException(..) , KisClock(..) , KisRead(..) , KisWrite(..) , NotificationHandler(..) , SqliteBackendType(..) , constClock , realTimeClock , runClient , runSingleClientSqlite , runKis , withSqliteKis , withSqliteKisWithNotifs , module Kis.Model ) where import Kis.Kis import Kis.Model import Kis.Notifications import Kis.Time import Kis.SqliteBackend import Control.Concurrent.Async import Control.Monad.RWS import qualified Data.Text as T runKis :: [KisClient IO a] -> [NotificationHandler] -> T.Text -> IO () runKis clients notifHandlers dbFile = withSqliteKisWithNotifs poolbackend kisConfig notifHandlers $ \kis -> do allClients <- forM clients $ \client -> async (runClient kis client) mapM_ wait allClients where poolbackend = PoolBackendType dbFile 10 kisConfig = KisConfig realTimeClock
lslah/kis-proto
src/Kis.hs
Haskell
bsd-3-clause
983
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.AmountOfMoney.EN.TT.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import Data.String import Data.Text (Text) import Prelude import Duckling.AmountOfMoney.Helpers import Duckling.AmountOfMoney.Types (Currency(..)) import Duckling.Numeral.Helpers (isPositive) import Duckling.Regex.Types import Duckling.Types import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import qualified Duckling.AmountOfMoney.Helpers as Helpers import qualified Duckling.Numeral.Types as TNumeral ruleAGrand :: Rule ruleAGrand = Rule { name = "a grand" , pattern = [ regex "a grand" ] , prod = \_ -> Just . Token AmountOfMoney . withValue 1000 $ currencyOnly TTD } ruleGrand :: Rule ruleGrand = Rule { name = "<amount> grand" , pattern = [ Predicate isPositive , regex "grand" ] , prod = \case (Token Numeral TNumeral.NumeralData{TNumeral.value = v}:_) -> Just . Token AmountOfMoney . withValue (1000 * v) $ currencyOnly TTD _ -> Nothing } ruleDollarCoin :: Rule ruleDollarCoin = Rule { name = "dollar coin" , pattern = [ regex "(nickel|dime|quarter)s?" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do c <- HashMap.lookup (Text.toLower match) Helpers.dollarCoins Just . Token AmountOfMoney . withValue c $ currencyOnly TTD _ -> Nothing } rules :: [Rule] rules = [ ruleAGrand , ruleGrand , ruleDollarCoin ]
facebookincubator/duckling
Duckling/AmountOfMoney/EN/TT/Rules.hs
Haskell
bsd-3-clause
1,819
-- | -- Module: Control.Wire.Event -- Copyright: (c) 2013 Ertugrul Soeylemez -- License: BSD3 -- Maintainer: Ertugrul Soeylemez <es@ertes.de> module Control.Wire.Event ( -- * Events Event, -- * Time-based at, never, now, periodic, periodicList, -- * Signal analysis became, noLonger, edge, -- * Modifiers (<&), (&>), dropE, dropWhileE, filterE, merge, mergeL, mergeR, notYet, once, takeE, takeWhileE, -- * Scans accumE, accum1E, iterateE, -- ** Special scans maximumE, minimumE, productE, sumE ) where import Control.Applicative import Control.Arrow import Control.Monad.Fix import Control.Wire.Core import Control.Wire.Session import Control.Wire.Unsafe.Event import Data.Fixed -- | Merge events with the leftmost event taking precedence. Equivalent -- to using the monoid interface with 'First'. Infixl 5. -- -- * Depends: now on both. -- -- * Inhibits: when any of the two wires inhibit. (<&) :: (Monad m) => Wire s e m a (Event b) -> Wire s e m a (Event b) -> Wire s e m a (Event b) (<&) = liftA2 (merge const) infixl 5 <& -- | Merge events with the rightmost event taking precedence. -- Equivalent to using the monoid interface with 'Last'. Infixl 5. -- -- * Depends: now on both. -- -- * Inhibits: when any of the two wires inhibit. (&>) :: (Monad m) => Wire s e m a (Event b) -> Wire s e m a (Event b) -> Wire s e m a (Event b) (&>) = liftA2 (merge (const id)) infixl 5 &> -- | Left scan for events. Each time an event occurs, apply the given -- function. -- -- * Depends: now. accumE :: (b -> a -> b) -- ^ Fold function -> b -- ^ Initial value. -> Wire s e m (Event a) (Event b) accumE f = loop' where loop' x' = mkSFN $ event (NoEvent, loop' x') (\y -> let x = f x' y in (Event x, loop' x)) -- | Left scan for events with no initial value. Each time an event -- occurs, apply the given function. The first event is produced -- unchanged. -- -- * Depends: now. accum1E :: (a -> a -> a) -- ^ Fold function -> Wire s e m (Event a) (Event a) accum1E f = initial where initial = mkSFN $ event (NoEvent, initial) (Event &&& accumE f) -- | At the given point in time. -- -- * Depends: now when occurring. at :: (HasTime t s) => t -- ^ Time of occurrence. -> Wire s e m a (Event a) at t' = mkSF $ \ds x -> let t = t' - dtime ds in if t <= 0 then (Event x, never) else (NoEvent, at t) -- | Occurs each time the predicate becomes true for the input signal, -- for example each time a given threshold is reached. -- -- * Depends: now. became :: (a -> Bool) -> Wire s e m a (Event a) became p = off where off = mkSFN $ \x -> if p x then (Event x, on) else (NoEvent, off) on = mkSFN $ \x -> (NoEvent, if p x then on else off) -- | Forget the first given number of occurrences. -- -- * Depends: now. dropE :: Int -> Wire s e m (Event a) (Event a) dropE n | n <= 0 = mkId dropE n = fix $ \again -> mkSFN $ \mev -> (NoEvent, if occurred mev then dropE (pred n) else again) -- | Forget all initial occurrences until the given predicate becomes -- false. -- -- * Depends: now. dropWhileE :: (a -> Bool) -> Wire s e m (Event a) (Event a) dropWhileE p = fix $ \again -> mkSFN $ \mev -> case mev of Event x | not (p x) -> (mev, mkId) _ -> (NoEvent, again) -- | Forget all occurrences for which the given predicate is false. -- -- * Depends: now. filterE :: (a -> Bool) -> Wire s e m (Event a) (Event a) filterE p = mkSF_ $ \mev -> case mev of Event x | p x -> mev _ -> NoEvent -- | On each occurrence, apply the function the event carries. -- -- * Depends: now. iterateE :: a -> Wire s e m (Event (a -> a)) (Event a) iterateE = accumE (\x f -> f x) -- | Maximum of all events. -- -- * Depends: now. maximumE :: (Ord a) => Wire s e m (Event a) (Event a) maximumE = accum1E max -- | Minimum of all events. -- -- * Depends: now. minimumE :: (Ord a) => Wire s e m (Event a) (Event a) minimumE = accum1E min -- | Left-biased event merge. mergeL :: Event a -> Event a -> Event a mergeL = merge const -- | Right-biased event merge. mergeR :: Event a -> Event a -> Event a mergeR = merge (const id) -- | Never occurs. never :: Wire s e m a (Event b) never = mkConst (Right NoEvent) -- | Occurs each time the predicate becomes false for the input signal, -- for example each time a given threshold is no longer exceeded. -- -- * Depends: now. noLonger :: (a -> Bool) -> Wire s e m a (Event a) noLonger p = off where off = mkSFN $ \x -> if p x then (NoEvent, off) else (Event x, on) on = mkSFN $ \x -> (NoEvent, if p x then off else on) -- | Events occur first when the predicate is false then when it is -- true, and then this pattern repeats. -- -- * Depends: now. edge :: (a -> Bool) -> Wire s e m a (Event a) edge p = off where off = mkSFN $ \x -> if p x then (Event x, on) else (NoEvent, off) on = mkSFN $ \x -> if p x then (NoEvent, on) else (Event x, off) -- | Forget the first occurrence. -- -- * Depends: now. notYet :: Wire s e m (Event a) (Event a) notYet = mkSFN $ event (NoEvent, notYet) (const (NoEvent, mkId)) -- | Occurs once immediately. -- -- * Depends: now when occurring. now :: Wire s e m a (Event a) now = mkSFN $ \x -> (Event x, never) -- | Forget all occurrences except the first. -- -- * Depends: now when occurring. once :: Wire s e m (Event a) (Event a) once = mkSFN $ \mev -> (mev, if occurred mev then never else once) -- | Periodic occurrence with the given time period. First occurrence -- is now. -- -- * Depends: now when occurring. periodic :: (HasTime t s) => t -> Wire s e m a (Event a) periodic int | int <= 0 = error "periodic: Non-positive interval" periodic int = mkSFN $ \x -> (Event x, loop' int) where loop' 0 = loop' int loop' t' = mkSF $ \ds x -> let t = t' - dtime ds in if t <= 0 then (Event x, loop' (mod' t int)) else (NoEvent, loop' t) -- | Periodic occurrence with the given time period. First occurrence -- is now. The event values are picked one by one from the given list. -- When the list is exhausted, the event does not occur again. periodicList :: (HasTime t s) => t -> [b] -> Wire s e m a (Event b) periodicList int _ | int <= 0 = error "periodic: Non-positive interval" periodicList _ [] = never periodicList int (x:xs) = mkSFN $ \_ -> (Event x, loop' int xs) where loop' _ [] = never loop' 0 xs' = loop' int xs' loop' t' xs0@(x':xs') = mkSF $ \ds _ -> let t = t' - dtime ds in if t <= 0 then (Event x', loop' (mod' t int) xs') else (NoEvent, loop' t xs0) -- | Product of all events. -- -- * Depends: now. productE :: (Num a) => Wire s e m (Event a) (Event a) productE = accumE (*) 1 -- | Sum of all events. -- -- * Depends: now. sumE :: (Num a) => Wire s e m (Event a) (Event a) sumE = accumE (+) 0 -- | Forget all but the first given number of occurrences. -- -- * Depends: now. takeE :: Int -> Wire s e m (Event a) (Event a) takeE n | n <= 0 = never takeE n = fix $ \again -> mkSFN $ \mev -> (mev, if occurred mev then takeE (pred n) else again) -- | Forget all but the initial occurrences for which the given -- predicate is true. -- -- * Depends: now. takeWhileE :: (a -> Bool) -> Wire s e m (Event a) (Event a) takeWhileE p = fix $ \again -> mkSFN $ \mev -> case mev of Event x | not (p x) -> (NoEvent, never) _ -> (mev, again)
Teaspot-Studio/netwire
Control/Wire/Event.hs
Haskell
bsd-3-clause
7,886
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE Rank2Types #-} ----------------------------------------------------------------------------- -- | -- Copyright : Andrew Martin -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Andrew Martin <andrew.thaddeus@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- There are two vector types provided by this module: 'Vector' and -- 'MVector'. They must be parameterized over a type that unifies -- with 'Rec Identity rs'. An example would be: -- -- > foo :: Vector (Rec Identity '[Int,Char,Bool]) -- -- This vector stores records that have an 'Int', a 'Char', and a 'Bool'. ----------------------------------------------------------------------------- module Data.Vector.Vinyl.Default.Empty.Monomorphic ( Vector, MVector -- * Accessors -- ** Length information , length, null -- ** Indexing , (!), (!?), head, last , unsafeIndex, unsafeHead, unsafeLast -- ** Monadic indexing , indexM, headM, lastM , unsafeIndexM, unsafeHeadM, unsafeLastM -- ** Extracting subvectors (slicing) , slice, init, tail, take, drop, splitAt , unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop -- * Construction -- ** Initialisation , empty, singleton, replicate, generate, iterateN -- ** Monadic initialisation , replicateM, generateM, create -- ** Unfolding , unfoldr, unfoldrN , constructN, constructrN -- -- ** Enumeration -- , enumFromN, enumFromStepN, enumFromTo, enumFromThenTo -- ** Concatenation , cons, snoc, (++), concat -- ** Restricting memory usage , force -- * Modifying vectors -- ** Bulk updates , (//) , unsafeUpd -- , update_, unsafeUpdate_ -- ** Accumulations , accum, unsafeAccum -- , accumulate_, unsafeAccumulate_ -- ** Permutations , reverse -- , backpermute, unsafeBackpermute -- ** Safe destructive updates , modify -- * Elementwise operations -- ** Mapping , map, imap, concatMap -- ** Monadic mapping , mapM, mapM_, forM, forM_ -- ** Zipping - Omitted due to me being lazy -- , zipWith, zipWith3, zipWith4, zipWith5, zipWith6 -- , izipWith, izipWith3, izipWith4, izipWith5, izipWith6 -- ** Monadic zipping , zipWithM, zipWithM_ -- * Working with predicates -- ** Filtering , filter, ifilter, filterM , takeWhile, dropWhile -- ** Partitioning , partition, unstablePartition, span, break -- ** Searching , elem, notElem, find, findIndex , elemIndex -- , findIndices, elemIndices -- * Folding , foldl, foldl1, foldl', foldl1', foldr, foldr1, foldr', foldr1' , ifoldl, ifoldl', ifoldr, ifoldr' -- ** Specialised folds , all, any -- , sum, product , maximum, maximumBy, minimum, minimumBy , minIndex, minIndexBy, maxIndex, maxIndexBy -- ** Monadic folds , foldM, foldM', fold1M, fold1M' , foldM_, foldM'_, fold1M_, fold1M'_ -- * Prefix sums (scans) , prescanl, prescanl' , postscanl, postscanl' , scanl, scanl', scanl1, scanl1' , prescanr, prescanr' , postscanr, postscanr' , scanr, scanr', scanr1, scanr1' -- ** Lists , toList, fromList, fromListN -- ** Other vector types , G.convert -- ** Mutable vectors , freeze, thaw, copy, unsafeFreeze, unsafeThaw, unsafeCopy ) where import Control.Monad.Primitive import Control.Monad.ST import Data.Vector.Vinyl.Default.Empty.Monomorphic.Internal import Data.Vinyl.Core import Data.Vinyl.Functor (Identity(..)) import qualified Data.Vector.Generic as G import Prelude hiding ( length, null, replicate, (++), concat, head, last, init, tail, take, drop, splitAt, reverse, map, concatMap, zipWith, zipWith3, zip, zip3, unzip, unzip3, filter, takeWhile, dropWhile, span, break, elem, notElem, foldl, foldl1, foldr, foldr1, all, any, sum, product, minimum, maximum, scanl, scanl1, scanr, scanr1, enumFromTo, enumFromThenTo, mapM, mapM_ ) -- Length -- ------ -- | /O(1)/ Yield the length of the vector. length :: Vector (Rec Identity rs) -> Int length (V i _) = i {-# INLINE length #-} -- | /O(1)/ Test whether a vector if empty null :: Vector (Rec Identity rs) -> Bool null (V i _) = i == 0 {-# INLINE null #-} -- Indexing -- -------- -- | O(1) Indexing (!) :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Int -> Rec Identity rs (!) = (G.!) {-# INLINE (!) #-} -- | O(1) Safe indexing (!?) :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Int -> Maybe (Rec Identity rs) (!?) = (G.!?) {-# INLINE (!?) #-} -- | /O(1)/ First element head :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs head = G.head {-# INLINE head #-} -- | /O(1)/ Last element last :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs last = G.last {-# INLINE last #-} -- | /O(1)/ Unsafe indexing without bounds checking unsafeIndex :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Int -> Rec Identity rs {-# INLINE unsafeIndex #-} unsafeIndex = G.unsafeIndex -- | /O(1)/ First element without checking if the vector is empty unsafeHead :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE unsafeHead #-} unsafeHead = G.unsafeHead -- | /O(1)/ Last element without checking if the vector is empty unsafeLast :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE unsafeLast #-} unsafeLast = G.unsafeLast -- Monadic indexing -- ---------------- -- | /O(1)/ Indexing in a monad. -- -- The monad allows operations to be strict in the vector when necessary. -- Suppose vector copying is implemented like this: -- -- > copy mv v = ... write mv i (v ! i) ... -- -- For lazy vectors, @v ! i@ would not be evaluated which means that @mv@ -- would unnecessarily retain a reference to @v@ in each element written. -- -- With 'indexM', copying can be implemented like this instead: -- -- > copy mv v = ... do -- > x <- indexM v i -- > write mv i x -- -- Here, no references to @v@ are retained because indexing (but /not/ the -- elements) is evaluated eagerly. -- indexM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> Int -> m (Rec Identity rs) indexM = G.indexM {-# INLINE indexM #-} -- | /O(1)/ First element of a vector in a monad. See 'indexM' for an -- explanation of why this is useful. headM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (Rec Identity rs) headM = G.headM {-# INLINE headM #-} -- | /O(1)/ Last element of a vector in a monad. See 'indexM' for an -- explanation of why this is useful. lastM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (Rec Identity rs) lastM = G.lastM {-# INLINE lastM #-} -- | /O(1)/ Indexing in a monad without bounds checks. See 'indexM' for an -- explanation of why this is useful. unsafeIndexM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> Int -> m (Rec Identity rs) unsafeIndexM = G.unsafeIndexM {-# INLINE unsafeIndexM #-} -- | /O(1)/ First element in a monad without checking for empty vectors. -- See 'indexM' for an explanation of why this is useful. unsafeHeadM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (Rec Identity rs) unsafeHeadM = G.unsafeHeadM {-# INLINE unsafeHeadM #-} -- | /O(1)/ Last element in a monad without checking for empty vectors. -- See 'indexM' for an explanation of why this is useful. unsafeLastM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (Rec Identity rs) unsafeLastM = G.unsafeLastM {-# INLINE unsafeLastM #-} -- Extracting subvectors (slicing) -- ------------------------------- -- | /O(1)/ Yield a slice of the vector without copying it. The vector must -- contain at least @i+n@ elements. slice :: G.Vector Vector (Rec Identity rs) => Int -- ^ @i@ starting index -> Int -- ^ @n@ length -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) slice = G.slice {-# INLINE slice #-} -- | /O(1)/ Yield all but the last element without copying. The vector may not -- be empty. init :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) init = G.init {-# INLINE init #-} -- | /O(1)/ Yield all but the first element without copying. The vector may not -- be empty. tail :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) tail = G.tail {-# INLINE tail #-} -- | /O(1)/ Yield at the first @n@ elements without copying. The vector may -- contain less than @n@ elements in which case it is returned unchanged. take :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) take = G.take {-# INLINE take #-} -- | /O(1)/ Yield all but the first @n@ elements without copying. The vector may -- contain less than @n@ elements in which case an empty vector is returned. drop :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) drop = G.drop {-# INLINE drop #-} -- | /O(1)/ Yield the first @n@ elements paired with the remainder without copying. -- -- Note that @'splitAt' n v@ is equivalent to @('take' n v, 'drop' n v)@ -- but slightly more efficient. splitAt :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) splitAt = G.splitAt {-# INLINE splitAt #-} -- | /O(1)/ Yield a slice of the vector without copying. The vector must -- contain at least @i+n@ elements but this is not checked. unsafeSlice :: G.Vector Vector (Rec Identity rs) => Int -- ^ @i@ starting index -> Int -- ^ @n@ length -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeSlice = G.unsafeSlice {-# INLINE unsafeSlice #-} -- | /O(1)/ Yield all but the last element without copying. The vector may not -- be empty but this is not checked. unsafeInit :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeInit = G.unsafeInit {-# INLINE unsafeInit #-} -- | /O(1)/ Yield all but the first element without copying. The vector may not -- be empty but this is not checked. unsafeTail :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeTail = G.unsafeTail {-# INLINE unsafeTail #-} -- | /O(1)/ Yield the first @n@ elements without copying. The vector must -- contain at least @n@ elements but this is not checked. unsafeTake :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeTake = G.unsafeTake {-# INLINE unsafeTake #-} -- | /O(1)/ Yield all but the first @n@ elements without copying. The vector -- must contain at least @n@ elements but this is not checked. unsafeDrop :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeDrop = G.unsafeDrop {-# INLINE unsafeDrop #-} -- Initialisation -- -------------- -- | /O(1)/ Empty vector empty :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) empty = G.empty {-# INLINE empty #-} -- | /O(1)/ Vector with exactly one element singleton :: G.Vector Vector (Rec Identity rs) => Rec Identity rs -> Vector (Rec Identity rs) singleton = G.singleton {-# INLINE singleton #-} -- | /O(n)/ Vector of the given length with the same value in each position replicate :: G.Vector Vector (Rec Identity rs) => Int -> Rec Identity rs -> Vector (Rec Identity rs) replicate = G.replicate {-# INLINE replicate #-} -- | /O(n)/ Construct a vector of the given length by applying the function to -- each index generate :: G.Vector Vector (Rec Identity rs) => Int -> (Int -> Rec Identity rs) -> Vector (Rec Identity rs) generate = G.generate {-# INLINE generate #-} -- | /O(n)/ Apply function n times to value. Zeroth element is original value. iterateN :: G.Vector Vector (Rec Identity rs) => Int -> (Rec Identity rs -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity rs) iterateN = G.iterateN {-# INLINE iterateN #-} -- Unfolding -- --------- -- | /O(n)/ Construct a vector by repeatedly applying the generator function -- to a seed. The generator function yields 'Just' the next element and the -- new seed or 'Nothing' if there are no more elements. -- -- > unfoldr (\n -> if n == 0 then Nothing else Just (n,n-1)) 10 -- > = <10,9,8,7,6,5,4,3,2,1> unfoldr :: G.Vector Vector (Rec Identity rs) => (c -> Maybe (Rec Identity rs, c)) -> c -> Vector (Rec Identity rs) unfoldr = G.unfoldr {-# INLINE unfoldr #-} -- | /O(n)/ Construct a vector with at most @n@ by repeatedly applying the -- generator function to the a seed. The generator function yields 'Just' the -- next element and the new seed or 'Nothing' if there are no more elements. -- -- > unfoldrN 3 (\n -> Just (n,n-1)) 10 = <10,9,8> unfoldrN :: G.Vector Vector (Rec Identity rs) => Int -> (c -> Maybe (Rec Identity rs, c)) -> c -> Vector (Rec Identity rs) unfoldrN = G.unfoldrN {-# INLINE unfoldrN #-} -- | /O(n)/ Construct a vector with @n@ elements by repeatedly applying the -- generator function to the already constructed part of the vector. -- -- > constructN 3 f = let a = f <> ; b = f <a> ; c = f <a,b> in f <a,b,c> -- constructN :: G.Vector Vector (Rec Identity rs) => Int -> (Vector (Rec Identity rs) -> Rec Identity rs) -> Vector (Rec Identity rs) constructN = G.constructN {-# INLINE constructN #-} -- | /O(n)/ Construct a vector with @n@ elements from right to left by -- repeatedly applying the generator function to the already constructed part -- of the vector. -- -- > constructrN 3 f = let a = f <> ; b = f<a> ; c = f <b,a> in f <c,b,a> -- constructrN :: G.Vector Vector (Rec Identity rs) => Int -> (Vector (Rec Identity rs) -> Rec Identity rs) -> Vector (Rec Identity rs) constructrN = G.constructrN {-# INLINE constructrN #-} -- Concatenation -- ------------- -- | /O(n)/ Prepend an element cons :: G.Vector Vector (Rec Identity rs) => Rec Identity rs -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE cons #-} cons = G.cons -- | /O(n)/ Append an element snoc :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity rs) {-# INLINE snoc #-} snoc = G.snoc infixr 5 ++ -- | /O(m+n)/ Concatenate two vectors (++) :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE (++) #-} (++) = (G.++) -- | /O(n)/ Concatenate all vectors in the list concat :: G.Vector Vector (Rec Identity rs) => [Vector (Rec Identity rs)] -> Vector (Rec Identity rs) {-# INLINE concat #-} concat = G.concat -- Monadic initialisation -- ---------------------- -- | /O(n)/ Execute the monadic action the given number of times and store the -- results in a vector. replicateM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Int -> m (Rec Identity rs) -> m (Vector (Rec Identity rs)) replicateM = G.replicateM {-# INLINE replicateM #-} -- | /O(n)/ Construct a vector of the given length by applying the monadic -- action to each index generateM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Int -> (Int -> m (Rec Identity rs)) -> m (Vector (Rec Identity rs)) generateM = G.generateM {-# INLINE generateM #-} -- | Execute the monadic action and freeze the resulting vector. -- -- @ -- create (do { v \<- new 2; write v 0 \'a\'; write v 1 \'b\'; return v }) = \<'a','b'\> -- @ create :: G.Vector Vector (Rec Identity rs) => (forall s. ST s (G.Mutable Vector s (Rec Identity rs))) -> Vector (Rec Identity rs) -- NOTE: eta-expanded due to http://hackage.haskell.org/trac/ghc/ticket/4120 create p = G.create p {-# INLINE create #-} -- Restricting memory usage -- ------------------------ -- | /O(n)/ Yield the argument but force it not to retain any extra memory, -- possibly by copying it. -- -- This is especially useful when dealing with slices. For example: -- -- > force (slice 0 2 <huge vector>) -- -- Here, the slice retains a reference to the huge vector. Forcing it creates -- a copy of just the elements that belong to the slice and allows the huge -- vector to be garbage collected. force :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) force = G.force {-# INLINE force #-} -- Bulk updates -- ------------ -- | /O(m+n)/ For each pair @(i,a)@ from the list, replace the vector -- element at position @i@ by @a@. -- -- > <5,9,2,7> // [(2,1),(0,3),(2,8)] = <3,9,8,7> -- (//) :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -- ^ initial vector (of length @m@) -> [(Int, Rec Identity rs)] -- ^ list of index/value pairs (of length @n@) -> Vector (Rec Identity rs) (//) = (G.//) {-# INLINE (//) #-} -- | Same as ('//') but without bounds checking. unsafeUpd :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> [(Int, Rec Identity rs)] -> Vector (Rec Identity rs) unsafeUpd = G.unsafeUpd {-# INLINE unsafeUpd #-} -- Accumulations -- ------------- -- | /O(m+n)/ For each pair @(i,c)@ from the list, replace the vector element -- @a@ at position @i@ by @f a c@. -- -- > accum (+) <5,9,2> [(2,4),(1,6),(0,3),(1,7)] = <5+3, 9+6+7, 2+4> accum :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> c -> Rec Identity rs) -- ^ accumulating function @f@ -> Vector (Rec Identity rs) -- ^ initial vector (of length @m@) -> [(Int,c)] -- ^ list of index/value pairs (of length @n@) -> Vector (Rec Identity rs) accum = G.accum {-# INLINE accum #-} -- | Same as 'accum' but without bounds checking. unsafeAccum :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> c -> Rec Identity rs) -> Vector (Rec Identity rs) -> [(Int,c)] -> Vector (Rec Identity rs) unsafeAccum = G.unsafeAccum {-# INLINE unsafeAccum #-} -- Permutations -- ------------ -- | /O(n)/ Reverse a vector reverse :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE reverse #-} reverse = G.reverse -- Safe destructive updates -- ------------------------ -- | Apply a destructive operation to a vector. The operation will be -- performed in place if it is safe to do so and will modify a copy of the -- vector otherwise. -- -- @ -- modify (\\v -> write v 0 \'x\') ('replicate' 3 \'a\') = \<\'x\',\'a\',\'a\'\> -- @ modify :: (G.Vector Vector (Rec Identity rs)) => (forall s. G.Mutable Vector s (Rec Identity rs) -> ST s ()) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE modify #-} modify p = G.modify p -- Mapping -- ------- -- | /O(n)/ Map a function over a vector map :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) map = G.map {-# INLINE map #-} -- | /O(n)/ Apply a function to every element of a vector and its index imap :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Int -> Rec Identity rs -> Rec Identity ss) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) imap = G.imap {-# INLINE imap #-} -- | Map a function over a vector and concatenate the results. concatMap :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Vector (Rec Identity ss)) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) concatMap = G.concatMap {-# INLINE concatMap #-} -- Monadic mapping -- --------------- -- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a -- vector of results mapM :: (Monad m, G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> m (Rec Identity ss)) -> Vector (Rec Identity rs) -> m (Vector (Rec Identity ss)) mapM = G.mapM {-# INLINE mapM #-} -- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the -- results mapM_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> m b) -> Vector (Rec Identity rs) -> m () mapM_ = G.mapM_ {-# INLINE mapM_ #-} -- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a -- vector of results. Equvalent to @flip 'mapM'@. forM :: (Monad m, G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => Vector (Rec Identity rs) -> (Rec Identity rs -> m (Rec Identity ss)) -> m (Vector (Rec Identity ss)) forM = G.forM {-# INLINE forM #-} -- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the -- results. Equivalent to @flip 'mapM_'@. forM_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> (Rec Identity rs -> m b) -> m () forM_ = G.forM_ {-# INLINE forM_ #-} -- Zipping -- ------- -- -- | /O(min(m,n))/ Zip two vectors with the given function. -- zipWith :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- ) => ((a,a') -> (b,b') -> (c,c')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -- zipWith = G.zipWith -- {-# INLINE zipWith #-} -- -- -- | Zip three vectors with the given function. -- -- zipWith3 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- ) => ((a,a') -> (b,b') -> (c,c') -> (d, d')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -- zipWith3 = G.zipWith3 -- {-# INLINE zipWith3 #-} -- -- zipWith4 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- ) => ((a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -- zipWith4 = G.zipWith4 -- {-# INLINE zipWith4 #-} -- -- zipWith5 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- , G.Vector u f, G.Vector v f' -- ) => ((a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e') -> (f,f')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -> Vector u v (f,f') -- zipWith5 = G.zipWith5 -- {-# INLINE zipWith5 #-} -- -- zipWith6 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- , G.Vector u f, G.Vector v f' -- , G.Vector u g, G.Vector v g' -- ) => ((a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e') -> (f,f') -> (g,g')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -> Vector u v (f,f') -> Vector u v (g,g') -- zipWith6 = G.zipWith6 -- {-# INLINE zipWith6 #-} -- -- -- | /O(min(m,n))/ Zip two vectors with a function that also takes the -- -- elements' indices. -- izipWith :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- ) => (Int -> (a,a') -> (b,b') -> (c,c')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -- izipWith = G.izipWith -- {-# INLINE izipWith #-} -- -- -- | Zip three vectors and their indices with the given function. -- izipWith3 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- ) => (Int -> (a,a') -> (b,b') -> (c,c') -> (d, d')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -- izipWith3 = G.izipWith3 -- {-# INLINE izipWith3 #-} -- -- izipWith4 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- ) => (Int -> (a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -- izipWith4 = G.izipWith4 -- {-# INLINE izipWith4 #-} -- -- izipWith5 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- , G.Vector u f, G.Vector v f' -- ) => (Int -> (a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e') -> (f,f')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -> Vector u v (f,f') -- izipWith5 = G.izipWith5 -- {-# INLINE izipWith5 #-} -- -- izipWith6 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- , G.Vector u f, G.Vector v f' -- , G.Vector u g, G.Vector v g' -- ) => (Int -> (a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e') -> (f,f') -> (g,g')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -> Vector u v (f,f') -> Vector u v (g,g') -- izipWith6 = G.izipWith6 -- {-# INLINE izipWith6 #-} -- Monadic zipping -- --------------- -- | /O(min(m,n))/ Zip the two vectors with the monadic action and yield a -- vector of results zipWithM :: (Monad m, G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss), G.Vector Vector (Rec Identity ts)) => (Rec Identity rs -> Rec Identity ss -> m (Rec Identity ts)) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) -> m (Vector (Rec Identity ts)) zipWithM = G.zipWithM {-# INLINE zipWithM #-} -- | /O(min(m,n))/ Zip the two vectors with the monadic action and ignore the -- results zipWithM_ :: (Monad m, G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> m e) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss)-> m () zipWithM_ = G.zipWithM_ {-# INLINE zipWithM_ #-} -- Filtering -- --------- -- | /O(n)/ Drop elements that do not satisfy the predicate filter :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) filter = G.filter {-# INLINE filter #-} -- | /O(n)/ Drop elements that do not satisfy the predicate which is applied to -- values and their indices ifilter :: G.Vector Vector (Rec Identity rs) => (Int -> Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) ifilter = G.ifilter {-# INLINE ifilter #-} -- | /O(n)/ Drop elements that do not satisfy the monadic predicate filterM :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> m Bool) -> Vector (Rec Identity rs) -> m (Vector (Rec Identity rs)) filterM = G.filterM {-# INLINE filterM #-} -- | /O(n)/ Yield the longest prefix of elements satisfying the predicate -- without copying. takeWhile :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) takeWhile = G.takeWhile {-# INLINE takeWhile #-} -- | /O(n)/ Drop the longest prefix of elements that satisfy the predicate -- without copying. dropWhile :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) dropWhile = G.dropWhile {-# INLINE dropWhile #-} -- Parititioning -- ------------- -- | /O(n)/ Split the vector in two parts, the first one containing those -- elements that satisfy the predicate and the second one those that don't. The -- relative order of the elements is preserved at the cost of a sometimes -- reduced performance compared to 'unstablePartition'. partition :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) {-# INLINE partition #-} partition = G.partition -- | /O(n)/ Split the vector in two parts, the first one containing those -- elements that satisfy the predicate and the second one those that don't. -- The order of the elements is not preserved but the operation is often -- faster than 'partition'. unstablePartition :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) {-# INLINE unstablePartition #-} unstablePartition = G.unstablePartition -- | /O(n)/ Split the vector into the longest prefix of elements that satisfy -- the predicate and the rest without copying. span :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) {-# INLINE span #-} span = G.span -- | /O(n)/ Split the vector into the longest prefix of elements that do not -- satisfy the predicate and the rest without copying. break :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) {-# INLINE break #-} break = G.break -- Searching -- --------- infix 4 `elem` -- | /O(n)/ Check if the vector contains an element elem :: (G.Vector Vector (Rec Identity rs), Eq (Rec Identity rs)) => Rec Identity rs -> Vector (Rec Identity rs) -> Bool elem = G.elem {-# INLINE elem #-} infix 4 `notElem` -- | /O(n)/ Check if the vector does not contain an element (inverse of 'elem') notElem :: (G.Vector Vector (Rec Identity rs), Eq (Rec Identity rs)) => Rec Identity rs -> Vector (Rec Identity rs) -> Bool notElem = G.notElem {-# INLINE notElem #-} -- | /O(n)/ Yield 'Just' the first element matching the predicate or 'Nothing' -- if no such element exists. find :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Maybe (Rec Identity rs) find = G.find {-# INLINE find #-} -- | /O(n)/ Yield 'Just' the index of the first element matching the predicate -- or 'Nothing' if no such element exists. findIndex :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Maybe Int findIndex = G.findIndex {-# INLINE findIndex #-} {- -- | /O(n)/ Yield the indices of elements satisfying the predicate in ascending -- order. findIndices :: ((a, b) -> Bool) -> Vector (Rec Identity rs) -> Vector u v Int findIndices = G.findIndices {-# INLINE findIndices #-} -} -- | /O(n)/ Yield 'Just' the index of the first occurence of the given element or -- 'Nothing' if the vector does not contain the element. This is a specialised -- version of 'findIndex'. elemIndex :: (G.Vector Vector (Rec Identity rs), Eq (Rec Identity rs)) => Rec Identity rs -> Vector (Rec Identity rs) -> Maybe Int elemIndex = G.elemIndex {-# INLINE elemIndex #-} {- -- | /O(n)/ Yield the indices of all occurences of the given element in -- ascending order. This is a specialised version of 'findIndices'. elemIndices :: (a, b) -> Vector (Rec Identity rs) -> Vector Int elemIndices = G.elemIndices {-# INLINE elemIndices #-} -} -- Folding -- ------- -- | /O(n)/ Left fold foldl :: G.Vector Vector (Rec Identity rs) => (r -> Rec Identity rs -> r) -> r -> Vector (Rec Identity rs) -> r foldl = G.foldl {-# INLINE foldl #-} -- | /O(n)/ Left fold on non-empty vectors foldl1 :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Rec Identity rs foldl1 = G.foldl1 {-# INLINE foldl1 #-} -- | /O(n)/ Left fold with strict accumulator foldl' :: G.Vector Vector (Rec Identity rs) => (r -> Rec Identity rs -> r) -> r -> Vector (Rec Identity rs) -> r foldl' = G.foldl' {-# INLINE foldl' #-} -- | /O(n)/ Left fold on non-empty vectors with strict accumulator foldl1' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Rec Identity rs foldl1' = G.foldl1' {-# INLINE foldl1' #-} -- | /O(n)/ Right fold foldr :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> r -> r) -> r -> Vector (Rec Identity rs) -> r foldr = G.foldr {-# INLINE foldr #-} -- | /O(n)/ Right fold on non-empty vectors foldr1 :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Rec Identity rs foldr1 = G.foldr1 {-# INLINE foldr1 #-} -- | /O(n)/ Right fold with a strict accumulator foldr' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> r -> r) -> r -> Vector (Rec Identity rs) -> r foldr' = G.foldr' {-# INLINE foldr' #-} -- | /O(n)/ Right fold on non-empty vectors with strict accumulator foldr1' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Rec Identity rs foldr1' = G.foldr1' {-# INLINE foldr1' #-} -- | /O(n)/ Left fold (function applied to each element and its index) ifoldl :: G.Vector Vector (Rec Identity rs) => (r -> Int -> Rec Identity rs -> r) -> r -> Vector (Rec Identity rs) -> r ifoldl = G.ifoldl {-# INLINE ifoldl #-} -- | /O(n)/ Left fold with strict accumulator (function applied to each element -- and its index) ifoldl' :: G.Vector Vector (Rec Identity rs) => (r -> Int -> Rec Identity rs -> r) -> r -> Vector (Rec Identity rs) -> r ifoldl' = G.ifoldl' {-# INLINE ifoldl' #-} -- | /O(n)/ Right fold (function applied to each element and its index) ifoldr :: G.Vector Vector (Rec Identity rs) => (Int -> Rec Identity rs -> r -> r) -> r -> Vector (Rec Identity rs) -> r ifoldr = G.ifoldr {-# INLINE ifoldr #-} -- | /O(n)/ Right fold with strict accumulator (function applied to each -- element and its index) ifoldr' :: G.Vector Vector (Rec Identity rs) => (Int -> Rec Identity rs -> r -> r) -> r -> Vector (Rec Identity rs) -> r ifoldr' = G.ifoldr' {-# INLINE ifoldr' #-} -- Specialised folds -- ----------------- -- | /O(n)/ Check if all elements satisfy the predicate. all :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Bool {-# INLINE all #-} all = G.all -- | /O(n)/ Check if any element satisfies the predicate. any :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Bool {-# INLINE any #-} any = G.any {- -- | /O(n)/ Compute the sum of the elements sum :: Vector (Rec Identity rs) -> (a, b) {-# INLINE sum #-} sum = G.sum -- | /O(n)/ Compute the product of the elements product :: Vector (Rec Identity rs) -> (a, b) {-# INLINE product #-} product = G.product -} -- | /O(n)/ Yield the maximum element of the vector. The vector may not be -- empty. maximum :: (G.Vector Vector (Rec Identity rs), Ord (Rec Identity rs)) => Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE maximum #-} maximum = G.maximum -- | /O(n)/ Yield the maximum element of the vector according to the given -- comparison function. The vector may not be empty. maximumBy :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Ordering) -> Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE maximumBy #-} maximumBy = G.maximumBy -- | /O(n)/ Yield the minimum element of the vector. The vector may not be -- empty. minimum :: (G.Vector Vector (Rec Identity rs), Ord (Rec Identity rs)) => Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE minimum #-} minimum = G.minimum -- | /O(n)/ Yield the minimum element of the vector according to the given -- comparison function. The vector may not be empty. minimumBy :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Ordering) -> Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE minimumBy #-} minimumBy = G.minimumBy -- | /O(n)/ Yield the index of the maximum element of the vector. The vector -- may not be empty. maxIndex :: (G.Vector Vector (Rec Identity rs), Ord (Rec Identity rs)) => Vector (Rec Identity rs) -> Int {-# INLINE maxIndex #-} maxIndex = G.maxIndex -- | /O(n)/ Yield the index of the maximum element of the vector according to -- the given comparison function. The vector may not be empty. maxIndexBy :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Ordering) -> Vector (Rec Identity rs) -> Int {-# INLINE maxIndexBy #-} maxIndexBy = G.maxIndexBy -- | /O(n)/ Yield the index of the minimum element of the vector. The vector -- may not be empty. minIndex :: (G.Vector Vector (Rec Identity rs), Ord (Rec Identity rs)) => Vector (Rec Identity rs) -> Int {-# INLINE minIndex #-} minIndex = G.minIndex -- | /O(n)/ Yield the index of the minimum element of the vector according to -- the given comparison function. The vector may not be empty. minIndexBy :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Ordering) -> Vector (Rec Identity rs) -> Int {-# INLINE minIndexBy #-} minIndexBy = G.minIndexBy -- Monadic folds -- ------------- -- | /O(n)/ Monadic fold foldM :: (Monad m, G.Vector Vector (Rec Identity rs)) => (r -> Rec Identity rs -> m r) -> r -> Vector (Rec Identity rs) -> m r foldM = G.foldM {-# INLINE foldM #-} -- | /O(n)/ Monadic fold over non-empty vectors fold1M :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> Rec Identity rs -> m (Rec Identity rs)) -> Vector (Rec Identity rs) -> m (Rec Identity rs) {-# INLINE fold1M #-} fold1M = G.fold1M -- | /O(n)/ Monadic fold with strict accumulator foldM' :: (Monad m, G.Vector Vector (Rec Identity rs)) => (r -> Rec Identity rs -> m r) -> r -> Vector (Rec Identity rs) -> m r {-# INLINE foldM' #-} foldM' = G.foldM' -- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator fold1M' :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> Rec Identity rs -> m (Rec Identity rs)) -> Vector (Rec Identity rs) -> m (Rec Identity rs) {-# INLINE fold1M' #-} fold1M' = G.fold1M' -- | /O(n)/ Monadic fold that discards the result foldM_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (r -> Rec Identity rs -> m r) -> r -> Vector (Rec Identity rs) -> m () {-# INLINE foldM_ #-} foldM_ = G.foldM_ -- | /O(n)/ Monadic fold over non-empty vectors that discards the result fold1M_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> Rec Identity rs -> m (Rec Identity rs)) -> Vector (Rec Identity rs) -> m () {-# INLINE fold1M_ #-} fold1M_ = G.fold1M_ -- | /O(n)/ Monadic fold with strict accumulator that discards the result foldM'_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (r -> Rec Identity rs -> m r) -> r -> Vector (Rec Identity rs) -> m () {-# INLINE foldM'_ #-} foldM'_ = G.foldM'_ -- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator -- that discards the result fold1M'_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> Rec Identity rs -> m (Rec Identity rs)) -> Vector (Rec Identity rs) -> m () {-# INLINE fold1M'_ #-} fold1M'_ = G.fold1M'_ -- Prefix sums (scans) -- ------------------- -- | /O(n)/ Prescan -- -- @ -- prescanl f z = 'init' . 'scanl' f z -- @ -- -- Example: @prescanl (+) 0 \<1,2,3,4\> = \<0,1,3,6\>@ -- prescanl :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) prescanl = G.prescanl {-# INLINE prescanl #-} -- | /O(n)/ Prescan with strict accumulator prescanl' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) prescanl' = G.prescanl' {-# INLINE prescanl' #-} -- | /O(n)/ Scan -- -- @ -- postscanl f z = 'tail' . 'scanl' f z -- @ -- -- Example: @postscanl (+) 0 \<1,2,3,4\> = \<1,3,6,10\>@ -- postscanl :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) postscanl = G.postscanl {-# INLINE postscanl #-} -- | /O(n)/ Scan with strict accumulator postscanl' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) postscanl' = G.postscanl' {-# INLINE postscanl' #-} -- | /O(n)/ Haskell-style scan -- -- > scanl f z <x1,...,xn> = <y1,...,y(n+1)> -- > where y1 = z -- > yi = f y(i-1) x(i-1) -- -- Example: @scanl (+) 0 \<1,2,3,4\> = \<0,1,3,6,10\>@ -- scanl :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) scanl = G.scanl {-# INLINE scanl #-} -- | /O(n)/ Haskell-style scan with strict accumulator scanl' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) scanl' = G.scanl' {-# INLINE scanl' #-} -- | /O(n)/ Scan over a non-empty vector -- -- > scanl f <x1,...,xn> = <y1,...,yn> -- > where y1 = x1 -- > yi = f y(i-1) xi -- scanl1 :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) scanl1 = G.scanl1 {-# INLINE scanl1 #-} -- | /O(n)/ Scan over a non-empty vector with a strict accumulator scanl1' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) scanl1' = G.scanl1' {-# INLINE scanl1' #-} -- | /O(n)/ Right-to-left prescan -- -- @ -- prescanr f z = 'reverse' . 'prescanl' (flip f) z . 'reverse' -- @ -- prescanr :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) {-# INLINE prescanr #-} prescanr = G.prescanr -- | /O(n)/ Right-to-left prescan with strict accumulator prescanr' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) prescanr' = G.prescanr' {-# INLINE prescanr' #-} -- | /O(n)/ Right-to-left scan postscanr :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) postscanr = G.postscanr {-# INLINE postscanr #-} -- | /O(n)/ Right-to-left scan with strict accumulator postscanr' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) postscanr' = G.postscanr' {-# INLINE postscanr' #-} -- | /O(n)/ Right-to-left Haskell-style scan scanr :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) scanr = G.scanr {-# INLINE scanr #-} -- | /O(n)/ Right-to-left Haskell-style scan with strict accumulator scanr' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) scanr' = G.scanr' {-# INLINE scanr' #-} -- | /O(n)/ Right-to-left scan over a non-empty vector scanr1 :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE scanr1 #-} scanr1 = G.scanr1 -- | /O(n)/ Right-to-left scan over a non-empty vector with a strict -- accumulator scanr1' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE scanr1' #-} scanr1' = G.scanr1' -- | /O(n)/ Convert a vector to a list toList :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> [Rec Identity rs] toList = G.toList {-# INLINE toList #-} -- | /O(n)/ Convert a list to a vector fromList :: G.Vector Vector (Rec Identity rs) => [Rec Identity rs] -> Vector (Rec Identity rs) fromList = G.fromList {-# INLINE fromList #-} -- | /O(n)/ Convert the first @n@ elements of a list to a vector -- -- @ -- fromListN n xs = 'fromList' ('take' n xs) -- @ fromListN :: G.Vector Vector (Rec Identity rs) => Int -> [Rec Identity rs] -> Vector (Rec Identity rs) fromListN = G.fromListN {-# INLINE fromListN #-} -- Conversions - Mutable vectors -- ----------------------------- -- | /O(1)/ Unsafe convert a mutable vector to an immutable one without -- copying. The mutable vector may not be used after this operation. unsafeFreeze :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => G.Mutable Vector (PrimState m) (Rec Identity rs) -> m (Vector (Rec Identity rs)) unsafeFreeze = G.unsafeFreeze {-# INLINE unsafeFreeze #-} -- | /O(1)/ Unsafely convert an immutable vector to a mutable one without -- copying. The immutable vector may not be used after this operation. unsafeThaw :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (G.Mutable Vector (PrimState m) (Rec Identity rs)) unsafeThaw = G.unsafeThaw {-# INLINE unsafeThaw #-} -- | /O(n)/ Yield a mutable copy of the immutable vector. thaw :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (G.Mutable Vector (PrimState m) (Rec Identity rs)) thaw = G.thaw {-# INLINE thaw #-} -- | /O(n)/ Yield an immutable copy of the mutable vector. freeze :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => G.Mutable Vector (PrimState m) (Rec Identity rs) -> m (Vector (Rec Identity rs)) freeze = G.freeze {-# INLINE freeze #-} -- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must -- have the same length. This is not checked. unsafeCopy :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => G.Mutable Vector (PrimState m) (Rec Identity rs) -> Vector (Rec Identity rs) -> m () unsafeCopy = G.unsafeCopy {-# INLINE unsafeCopy #-} -- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must -- have the same length. copy :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => G.Mutable Vector (PrimState m) (Rec Identity rs) -> Vector (Rec Identity rs) -> m () copy = G.copy {-# INLINE copy #-}
andrewthad/vinyl-vectors
src/Data/Vector/Vinyl/Default/Empty/Monomorphic.hs
Haskell
bsd-3-clause
48,286
{-# LANGUAGE BangPatterns #-} module Main where import Control.Arrow as A import GalFld.GalFld import GalFld.More.SpecialPolys {-import System.Random-} import Data.List import Debug.Trace import Data.Maybe import GalFld.Core.Polynomials.FFTTuple {-import GalFld.Core.Polynomials.Conway-} {----------------------------------------------------------------------------------} {--- Beispiele-} e2f2Mipo = pList [1::F2,1,1] -- x²+x+1 e2f2 = FFElem (pList [0,1::F2]) e2f2Mipo e40f2Mipo = pList [1::F2,1,0,1,0,1,0,0,1,0,0,0,1,1,0,1,1,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] e40f2 = FFElem (pList [0,1::F2]) e40f2Mipo e10f3Mipo = pList [2::F3,1,0,0,2,2,2,0,0,0,1] e10f3 = FFElem (pTupUnsave [(1,1::F3)]) e10f3Mipo {- F16=E2(E2) - als Grad 2 Erweiterung von E2 durch MPol x²+x+e2f2 - Mit einer Nullstelle: e2e2f2 -} e2e2f2Mipo = pList [e2f2,one,one] -- x²+x+e2f2 e2e2f2 = FFElem (pList [0,one]) e2e2f2Mipo --e2e2f2 = FFElem (pList [0,e2f2]) e2e2f2Mipo {- F16=E4 - als Grad 4 Erweiterung con F2 durch MPol x⁴+x²+1 - Mit einer Nullstelle: e4f2 -} e4f2Mipo = pList [1::F2,1::F2,0,0,1::F2] -- x⁴+x²+1 e4f2 = FFElem (pList [0,1::F2]) e4f2Mipo {- - Beispiel in F3[x]: - f = X¹¹+2x⁹+2x⁸+x⁶+x⁵+2x³+2x²+1 - = (x+1)(x²+1)³(x+2)⁴ -} {-f=pList [1::F3,0,2,2,0,1,1,0,2,2,0,1]-} {-f = pTupUnsave [(11,1),(8,2::F3),(6,1),(5,1),(3,2),(2,2),(0,1)]-} {-f' = poly LE [1::F3,0,2,2,0,1,1,0,2,2,0,1] -} f = pTupUnsave [(11::Int,1),(8,2),(6,1),(5,1),(3,2),(2,2),(0,1)] a = pTupUnsave [(6,3::F5),(5,2),(4,1),(3,1),(1,2),(0,3)] b = pTupUnsave [(6,2::F5),(5,1),(4,3),(2,4)] c = pTupUnsave [(4,1::F5)] testPoly1 = pList $ listFFElem e40f2Mipo [ pList [0::F2,0,1,1] , 1 , pList [1::F2,1,1] , pList [0::F2,1] , pList [1::F2,1,0,1] ] testPoly2 = pList $ listFFElem e4f2Mipo [ pList [0::F2,0,1,1] , 1 , pList [1::F2,1,0,1] ] testPoly3 = pList $ listFFElem e4f2Mipo [ pList [0::F2,0,1,1] , 1 , 1 , pList [1::F2,1,0,1] ] testPoly = testPoly1^2 * testPoly2 * testPoly3 testPolyF5 = pList $ listFFElem (pList [2::F5,4,1]) [ pList [0::F5,0,1,1] , 1 , pList [1::F5,1,1] , pList [0::F5,1] , pList [1::F5,1,0,1] ] testPolyE10F3 = pList $ listFFElem e10f3Mipo [ pList [0::F3,0,1,1] , 1 , pList [1::F3,1,1] , pList [0::F3,1] , pList [1::F3,1,0,1] ] multMyPoly mulFunk f g = mulFunk f g {-multMyPoly' f 1 = f-} {-multMyPoly' f n = multPoly f $ multMyPoly' f (n-1)-} {-m = fromListsM [ [0::F5, 1, 0, 1, 0 ]-} {-, [0, -2, 0, 0, 0 ]-} {-, [0, 0, 0, 0, 0 ]-} {-, [0, 0, 0, -2, 0 ]-} {-, [0, 1, 0, 1, 0 ]]-} genBigM n = replicate n $ take n $ cycle $ elems (1::F101) m = fromListsM $ genBigM 100 {-m' = M.fromLists $ genBigM 100-} problem1d e deg = do print $ "Berechne monischen irred Polynome /=0 von Grad " ++ show deg print $ length $ findIrreds $ getAllMonicPs (elems e) [deg] prob1d e deg = map (\x -> map (\(i,f) -> berlekamp f) x) $ findTrivialsSff $ getAllMonicPs (elems e) [deg] l = take 100 $ getAllMonicPs (elems (1::F3)) [100] heavyBench mul f 0 = f heavyBench mul f n = mul f g where g = heavyBench mul f (n-1) main :: IO () {-main = print $ map fst $ sffAndBerlekamp testPoly-} {-main = print $ berlekampBasis testPoly-} {-main = print $ multMyPoly f 400-} {-main = print $ multMyPoly' f' 400-} {-main = print $ multMyPoly m' 10000-} {-main = print $ echelonM m-} {-main = print $ luDecomp' m'-} {-main = print $ map (\n -> (length $ prob1d (1::F2) n)) [1..10]-} {-main = print $ prob1d (1::F2) 9-} {-main = problem1d (1::F2) 13-} {-main = print $ berlekamp fFail-} {-main = print $ length $ filter (\x -> x) $ map (\f -> rabin f) $ getAllMonicPs (elems (1::F3)) [8]-} {-main = print $ map (\f -> hasNs f (elems (1::F3))) $ getAllMonicPs (elems (1::F3)) [2]-} {-main = mapM_ print $ map appBerlekamp $ map appSff $ findTrivialsNs $ getAllMonicPs (elems (1::F3)) [2]-} {-main = print $ length $ filter (\x -> x) $ map (rabin . toPMS) $ getAllMonicPs (elems (1::F3)) [8]-} {-main = print $ length $ findIrreds $ getAllMonicPs (elems (1::F3)) [9]-} {-main = mapM_ print $ map sffAndBerlekamp $ getAllMonicPs (elems (1::F3)) [3]-} {-main = print $ length $ findIrredsRabin $ getAllMonicPs (elems (1::F3)) [9]-} {-main = print $ snd $ (divPInv (pTupUnsave [(3^11,1),(1,-1)]) f)-} {-main = print $ foldr1 (+) $ map (snd) $ p2Tup $ heavyBench testPoly1 200-} {-main = print $ foldr1 (+) $ map (snd) $ heavyBench (p2Tup testPoly1) 200-} {-main = do-} {-print $ divP (pTup [(3^20,1::F3), (0,-1)]) (pTup [(40,1::F3), (1,1),(0,2)])-} {-main = print $ multPMKaratsuba (p2Tup (testPolyF5^1000)) (p2Tup (testPolyF5^1000))-} {-main = print $ foldr1 (+) $ map snd $ p2Tup $ heavyBench (multPK) testPolyF5 300-} {-main = print $ modMonom (5^21) a-} {-main = print $ m-} {-where m = factorP $ ggTP (piPoly $ pTupUnsave [(5,1::F3),(0,-1)]) (cyclotomicPoly (3^5-1) (1::F3))-} main = do let list = getAllP (elems (1::F5)) 8 putStrLn $ (\(f,g,a,b) -> "f="++show f++"\ng="++show g++"\ndivP f g = "++show a++"\ndivPInv="++show b) $ head $ filter (\(_,_,a,b) -> a /= b) $ map (\(x,y) -> (x,y,divP x y, divPInv x y)) $ zip list $ reverse list
maximilianhuber/softwareProjekt
profiling/AlgProfiling.hs
Haskell
bsd-3-clause
5,861
module Internal.X86.Default where import Foreign import Foreign.C.Types import Data.List (dropWhileEnd) import Hapstone.Internal.Util import Hapstone.Internal.X86 import Test.QuickCheck import Test.QuickCheck.Instances -- generators for our datatypes instance Arbitrary X86Reg where arbitrary = elements [minBound..maxBound] instance Arbitrary X86OpType where arbitrary = elements [minBound..maxBound] instance Arbitrary X86AvxBcast where arbitrary = elements [minBound..maxBound] instance Arbitrary X86SseCc where arbitrary = elements [minBound..maxBound] instance Arbitrary X86AvxCc where arbitrary = elements [minBound..maxBound] instance Arbitrary X86AvxRm where arbitrary = elements [minBound..maxBound] instance Arbitrary X86Prefix where arbitrary = elements [minBound..maxBound] instance Arbitrary X86OpMemStruct where arbitrary = X86OpMemStruct <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary CsX86Op where arbitrary = CsX86Op <$> oneof [ Reg <$> arbitrary , Imm <$> arbitrary -- , Fp <$> arbitrary , Mem <$> arbitrary , pure Undefined ] <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary CsX86 where arbitrary = CsX86 <$> tuple <*> list <*> arbitrary <*> arbitrary <*> arbitrary <*> nZ <*> nZ <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> (take 8 <$> arbitrary) where tuple = (,,,) <$> nZ <*> nZ <*> nZ <*> nZ nZ :: (Arbitrary a, Eq a, Num a) => Gen (Maybe a) nZ = fromZero <$> arbitrary list = (dropWhileEnd (==0) . take 4) <$> arbitrary instance Arbitrary X86Insn where arbitrary = elements [minBound..maxBound] instance Arbitrary X86InsnGroup where arbitrary = elements [minBound..maxBound]
ibabushkin/hapstone
test/Internal/X86/Default.hs
Haskell
bsd-3-clause
1,915
{-# language CPP #-} {-# language MultiParamTypeClasses #-} #if __GLASGOW_HASKELL__ >= 800 {-# options_ghc -Wno-redundant-constraints #-} #endif module OpenCV.Internal.ImgProc.MiscImgTransform.ColorCodes where import "base" Data.Int ( Int32 ) import "base" Data.Proxy ( Proxy(..) ) import "base" Data.Word import "base" GHC.TypeLits import "this" OpenCV.Internal.ImgProc.MiscImgTransform import "this" OpenCV.TypeLevel -------------------------------------------------------------------------------- {- | Valid color conversions described by the following graph: <<doc/color_conversions.png>> -} class ColorConversion (fromColor :: ColorCode) (toColor :: ColorCode) where colorConversionCode :: Proxy fromColor -> Proxy toColor -> Int32 -- | Names of color encodings data ColorCode = BayerBG -- ^ ('bayerBG') Bayer pattern with BG in the second row, second and third column | BayerGB -- ^ ('bayerGB') Bayer pattern with GB in the second row, second and third column | BayerGR -- ^ ('bayerGR') Bayer pattern with GR in the second row, second and third column | BayerRG -- ^ ('bayerRG') Bayer pattern with RG in the second row, second and third column | BGR -- ^ ('bgr') 24 bit RGB color space with channels: (B8:G8:R8) | BGR555 -- ^ ('bgr555') 15 bit RGB color space | BGR565 -- ^ ('bgr565') 16 bit RGB color space | BGRA -- ^ ('bgra') 32 bit RGBA color space with channels: (B8:G8:R8:A8) | BGRA_I420 -- ^ ('bgra_I420') | BGRA_IYUV -- ^ ('bgra_IYUV') | BGRA_NV12 -- ^ ('bgra_NV12') | BGRA_NV21 -- ^ ('bgra_NV21') | BGRA_UYNV -- ^ ('bgra_UYNV') | BGRA_UYVY -- ^ ('bgra_UYVY') | BGRA_Y422 -- ^ ('bgra_Y422') | BGRA_YUNV -- ^ ('bgra_YUNV') | BGRA_YUY2 -- ^ ('bgra_YUY2') | BGRA_YUYV -- ^ ('bgra_YUYV') | BGRA_YV12 -- ^ ('bgra_YV12') | BGRA_YVYU -- ^ ('bgra_YVYU') | BGR_EA -- ^ ('bgr_EA') Edge-Aware | BGR_FULL -- ^ ('bgr_FULL') | BGR_I420 -- ^ ('bgr_I420') | BGR_IYUV -- ^ ('bgr_IYUV') | BGR_NV12 -- ^ ('bgr_NV12') | BGR_NV21 -- ^ ('bgr_NV21') | BGR_UYNV -- ^ ('bgr_UYNV') | BGR_UYVY -- ^ ('bgr_UYVY') | BGR_VNG -- ^ ('bgr_VNG') | BGR_Y422 -- ^ ('bgr_Y422') | BGR_YUNV -- ^ ('bgr_YUNV') | BGR_YUY2 -- ^ ('bgr_YUY2') | BGR_YUYV -- ^ ('bgr_YUYV') | BGR_YV12 -- ^ ('bgr_YV12') | BGR_YVYU -- ^ ('bgr_YVYU') | GRAY -- ^ ('gray') 8 bit single channel color space | GRAY_420 -- ^ ('gray_420') | GRAY_I420 -- ^ ('gray_I420') | GRAY_IYUV -- ^ ('gray_IYUV') | GRAY_NV12 -- ^ ('gray_NV12') | GRAY_NV21 -- ^ ('gray_NV21') | GRAY_UYNV -- ^ ('gray_UYNV') | GRAY_UYVY -- ^ ('gray_UYVY') | GRAY_Y422 -- ^ ('gray_Y422') | GRAY_YUNV -- ^ ('gray_YUNV') | GRAY_YUY2 -- ^ ('gray_YUY2') | GRAY_YUYV -- ^ ('gray_YUYV') | GRAY_YV12 -- ^ ('gray_YV12') | GRAY_YVYU -- ^ ('gray_YVYU') | HLS -- ^ ('hls') | HLS_FULL -- ^ ('hls_FULL') | HSV -- ^ ('hsv') | HSV_FULL -- ^ ('hsv_FULL') | Lab -- ^ ('lab') | LBGR -- ^ ('lbgr') | LRGB -- ^ ('lrgb') | Luv -- ^ ('luv') | MRGBA -- ^ ('mrgba') | RGB -- ^ ('rgb') 24 bit RGB color space with channels: (R8:G8:B8) | RGBA -- ^ ('rgba') | RGBA_I420 -- ^ ('rgba_I420') | RGBA_IYUV -- ^ ('rgba_IYUV') | RGBA_NV12 -- ^ ('rgba_NV12') | RGBA_NV21 -- ^ ('rgba_NV21') | RGBA_UYNV -- ^ ('rgba_UYNV') | RGBA_UYVY -- ^ ('rgba_UYVY') | RGBA_Y422 -- ^ ('rgba_Y422') | RGBA_YUNV -- ^ ('rgba_YUNV') | RGBA_YUY2 -- ^ ('rgba_YUY2') | RGBA_YUYV -- ^ ('rgba_YUYV') | RGBA_YV12 -- ^ ('rgba_YV12') | RGBA_YVYU -- ^ ('rgba_YVYU') | RGB_EA -- ^ ('rgb_EA') Edge-Aware | RGB_FULL -- ^ ('rgb_FULL') | RGB_I420 -- ^ ('rgb_I420') | RGB_IYUV -- ^ ('rgb_IYUV') | RGB_NV12 -- ^ ('rgb_NV12') | RGB_NV21 -- ^ ('rgb_NV21') | RGB_UYNV -- ^ ('rgb_UYNV') | RGB_UYVY -- ^ ('rgb_UYVY') | RGB_VNG -- ^ ('rgb_VNG') | RGB_Y422 -- ^ ('rgb_Y422') | RGB_YUNV -- ^ ('rgb_YUNV') | RGB_YUY2 -- ^ ('rgb_YUY2') | RGB_YUYV -- ^ ('rgb_YUYV') | RGB_YV12 -- ^ ('rgb_YV12') | RGB_YVYU -- ^ ('rgb_YVYU') | XYZ -- ^ ('xyz') | YCrCb -- ^ ('yCrCb') | YUV -- ^ ('yuv') | YUV420p -- ^ ('yuv420p') | YUV420sp -- ^ ('yuv420sp') | YUV_I420 -- ^ ('yuv_I420') | YUV_IYUV -- ^ ('yuv_IYUV') | YUV_YV12 -- ^ ('yuv_YV12') -------------------------------------------------------------------------------- bayerBG :: Proxy 'BayerBG ; bayerBG = Proxy bayerGB :: Proxy 'BayerGB ; bayerGB = Proxy bayerGR :: Proxy 'BayerGR ; bayerGR = Proxy bayerRG :: Proxy 'BayerRG ; bayerRG = Proxy bgr :: Proxy 'BGR ; bgr = Proxy bgr555 :: Proxy 'BGR555 ; bgr555 = Proxy bgr565 :: Proxy 'BGR565 ; bgr565 = Proxy bgra :: Proxy 'BGRA ; bgra = Proxy bgra_I420 :: Proxy 'BGRA_I420; bgra_I420 = Proxy bgra_IYUV :: Proxy 'BGRA_IYUV; bgra_IYUV = Proxy bgra_NV12 :: Proxy 'BGRA_NV12; bgra_NV12 = Proxy bgra_NV21 :: Proxy 'BGRA_NV21; bgra_NV21 = Proxy bgra_UYNV :: Proxy 'BGRA_UYNV; bgra_UYNV = Proxy bgra_UYVY :: Proxy 'BGRA_UYVY; bgra_UYVY = Proxy bgra_Y422 :: Proxy 'BGRA_Y422; bgra_Y422 = Proxy bgra_YUNV :: Proxy 'BGRA_YUNV; bgra_YUNV = Proxy bgra_YUY2 :: Proxy 'BGRA_YUY2; bgra_YUY2 = Proxy bgra_YUYV :: Proxy 'BGRA_YUYV; bgra_YUYV = Proxy bgra_YV12 :: Proxy 'BGRA_YV12; bgra_YV12 = Proxy bgra_YVYU :: Proxy 'BGRA_YVYU; bgra_YVYU = Proxy bgr_EA :: Proxy 'BGR_EA ; bgr_EA = Proxy bgr_FULL :: Proxy 'BGR_FULL ; bgr_FULL = Proxy bgr_I420 :: Proxy 'BGR_I420 ; bgr_I420 = Proxy bgr_IYUV :: Proxy 'BGR_IYUV ; bgr_IYUV = Proxy bgr_NV12 :: Proxy 'BGR_NV12 ; bgr_NV12 = Proxy bgr_NV21 :: Proxy 'BGR_NV21 ; bgr_NV21 = Proxy bgr_UYNV :: Proxy 'BGR_UYNV ; bgr_UYNV = Proxy bgr_UYVY :: Proxy 'BGR_UYVY ; bgr_UYVY = Proxy bgr_VNG :: Proxy 'BGR_VNG ; bgr_VNG = Proxy bgr_Y422 :: Proxy 'BGR_Y422 ; bgr_Y422 = Proxy bgr_YUNV :: Proxy 'BGR_YUNV ; bgr_YUNV = Proxy bgr_YUY2 :: Proxy 'BGR_YUY2 ; bgr_YUY2 = Proxy bgr_YUYV :: Proxy 'BGR_YUYV ; bgr_YUYV = Proxy bgr_YV12 :: Proxy 'BGR_YV12 ; bgr_YV12 = Proxy bgr_YVYU :: Proxy 'BGR_YVYU ; bgr_YVYU = Proxy gray :: Proxy 'GRAY ; gray = Proxy gray_420 :: Proxy 'GRAY_420 ; gray_420 = Proxy gray_I420 :: Proxy 'GRAY_I420; gray_I420 = Proxy gray_IYUV :: Proxy 'GRAY_IYUV; gray_IYUV = Proxy gray_NV12 :: Proxy 'GRAY_NV12; gray_NV12 = Proxy gray_NV21 :: Proxy 'GRAY_NV21; gray_NV21 = Proxy gray_UYNV :: Proxy 'GRAY_UYNV; gray_UYNV = Proxy gray_UYVY :: Proxy 'GRAY_UYVY; gray_UYVY = Proxy gray_Y422 :: Proxy 'GRAY_Y422; gray_Y422 = Proxy gray_YUNV :: Proxy 'GRAY_YUNV; gray_YUNV = Proxy gray_YUY2 :: Proxy 'GRAY_YUY2; gray_YUY2 = Proxy gray_YUYV :: Proxy 'GRAY_YUYV; gray_YUYV = Proxy gray_YV12 :: Proxy 'GRAY_YV12; gray_YV12 = Proxy gray_YVYU :: Proxy 'GRAY_YVYU; gray_YVYU = Proxy hls :: Proxy 'HLS ; hls = Proxy hls_FULL :: Proxy 'HLS_FULL ; hls_FULL = Proxy hsv :: Proxy 'HSV ; hsv = Proxy hsv_FULL :: Proxy 'HSV_FULL ; hsv_FULL = Proxy lab :: Proxy 'Lab ; lab = Proxy lbgr :: Proxy 'LBGR ; lbgr = Proxy lrgb :: Proxy 'LRGB ; lrgb = Proxy luv :: Proxy 'Luv ; luv = Proxy mrgba :: Proxy 'MRGBA ; mrgba = Proxy rgb :: Proxy 'RGB ; rgb = Proxy rgba :: Proxy 'RGBA ; rgba = Proxy rgba_I420 :: Proxy 'RGBA_I420; rgba_I420 = Proxy rgba_IYUV :: Proxy 'RGBA_IYUV; rgba_IYUV = Proxy rgba_NV12 :: Proxy 'RGBA_NV12; rgba_NV12 = Proxy rgba_NV21 :: Proxy 'RGBA_NV21; rgba_NV21 = Proxy rgba_UYNV :: Proxy 'RGBA_UYNV; rgba_UYNV = Proxy rgba_UYVY :: Proxy 'RGBA_UYVY; rgba_UYVY = Proxy rgba_Y422 :: Proxy 'RGBA_Y422; rgba_Y422 = Proxy rgba_YUNV :: Proxy 'RGBA_YUNV; rgba_YUNV = Proxy rgba_YUY2 :: Proxy 'RGBA_YUY2; rgba_YUY2 = Proxy rgba_YUYV :: Proxy 'RGBA_YUYV; rgba_YUYV = Proxy rgba_YV12 :: Proxy 'RGBA_YV12; rgba_YV12 = Proxy rgba_YVYU :: Proxy 'RGBA_YVYU; rgba_YVYU = Proxy rgb_EA :: Proxy 'RGB_EA ; rgb_EA = Proxy rgb_FULL :: Proxy 'RGB_FULL ; rgb_FULL = Proxy rgb_I420 :: Proxy 'RGB_I420 ; rgb_I420 = Proxy rgb_IYUV :: Proxy 'RGB_IYUV ; rgb_IYUV = Proxy rgb_NV12 :: Proxy 'RGB_NV12 ; rgb_NV12 = Proxy rgb_NV21 :: Proxy 'RGB_NV21 ; rgb_NV21 = Proxy rgb_UYNV :: Proxy 'RGB_UYNV ; rgb_UYNV = Proxy rgb_UYVY :: Proxy 'RGB_UYVY ; rgb_UYVY = Proxy rgb_VNG :: Proxy 'RGB_VNG ; rgb_VNG = Proxy rgb_Y422 :: Proxy 'RGB_Y422 ; rgb_Y422 = Proxy rgb_YUNV :: Proxy 'RGB_YUNV ; rgb_YUNV = Proxy rgb_YUY2 :: Proxy 'RGB_YUY2 ; rgb_YUY2 = Proxy rgb_YUYV :: Proxy 'RGB_YUYV ; rgb_YUYV = Proxy rgb_YV12 :: Proxy 'RGB_YV12 ; rgb_YV12 = Proxy rgb_YVYU :: Proxy 'RGB_YVYU ; rgb_YVYU = Proxy xyz :: Proxy 'XYZ ; xyz = Proxy yCrCb :: Proxy 'YCrCb ; yCrCb = Proxy yuv :: Proxy 'YUV ; yuv = Proxy yuv420p :: Proxy 'YUV420p ; yuv420p = Proxy yuv420sp :: Proxy 'YUV420sp ; yuv420sp = Proxy yuv_I420 :: Proxy 'YUV_I420 ; yuv_I420 = Proxy yuv_IYUV :: Proxy 'YUV_IYUV ; yuv_IYUV = Proxy yuv_YV12 :: Proxy 'YUV_YV12 ; yuv_YV12 = Proxy -------------------------------------------------------------------------------- instance ColorConversion 'BGR 'BGRA where colorConversionCode _ _ = c'COLOR_BGR2BGRA instance ColorConversion 'RGB 'RGBA where colorConversionCode _ _ = c'COLOR_RGB2RGBA instance ColorConversion 'BGRA 'BGR where colorConversionCode _ _ = c'COLOR_BGRA2BGR instance ColorConversion 'RGBA 'RGB where colorConversionCode _ _ = c'COLOR_RGBA2RGB instance ColorConversion 'BGR 'RGBA where colorConversionCode _ _ = c'COLOR_BGR2RGBA instance ColorConversion 'RGB 'BGRA where colorConversionCode _ _ = c'COLOR_RGB2BGRA instance ColorConversion 'RGBA 'BGR where colorConversionCode _ _ = c'COLOR_RGBA2BGR instance ColorConversion 'BGRA 'RGB where colorConversionCode _ _ = c'COLOR_BGRA2RGB instance ColorConversion 'BGR 'RGB where colorConversionCode _ _ = c'COLOR_BGR2RGB instance ColorConversion 'RGB 'BGR where colorConversionCode _ _ = c'COLOR_RGB2BGR instance ColorConversion 'BGRA 'RGBA where colorConversionCode _ _ = c'COLOR_BGRA2RGBA instance ColorConversion 'RGBA 'BGRA where colorConversionCode _ _ = c'COLOR_RGBA2BGRA instance ColorConversion 'BGR 'GRAY where colorConversionCode _ _ = c'COLOR_BGR2GRAY instance ColorConversion 'RGB 'GRAY where colorConversionCode _ _ = c'COLOR_RGB2GRAY instance ColorConversion 'GRAY 'BGR where colorConversionCode _ _ = c'COLOR_GRAY2BGR instance ColorConversion 'GRAY 'RGB where colorConversionCode _ _ = c'COLOR_GRAY2RGB instance ColorConversion 'GRAY 'BGRA where colorConversionCode _ _ = c'COLOR_GRAY2BGRA instance ColorConversion 'GRAY 'RGBA where colorConversionCode _ _ = c'COLOR_GRAY2RGBA instance ColorConversion 'BGRA 'GRAY where colorConversionCode _ _ = c'COLOR_BGRA2GRAY instance ColorConversion 'RGBA 'GRAY where colorConversionCode _ _ = c'COLOR_RGBA2GRAY instance ColorConversion 'BGR 'BGR565 where colorConversionCode _ _ = c'COLOR_BGR2BGR565 instance ColorConversion 'RGB 'BGR565 where colorConversionCode _ _ = c'COLOR_RGB2BGR565 instance ColorConversion 'BGR565 'BGR where colorConversionCode _ _ = c'COLOR_BGR5652BGR instance ColorConversion 'BGR565 'RGB where colorConversionCode _ _ = c'COLOR_BGR5652RGB instance ColorConversion 'BGRA 'BGR565 where colorConversionCode _ _ = c'COLOR_BGRA2BGR565 instance ColorConversion 'RGBA 'BGR565 where colorConversionCode _ _ = c'COLOR_RGBA2BGR565 instance ColorConversion 'BGR565 'BGRA where colorConversionCode _ _ = c'COLOR_BGR5652BGRA instance ColorConversion 'BGR565 'RGBA where colorConversionCode _ _ = c'COLOR_BGR5652RGBA instance ColorConversion 'GRAY 'BGR565 where colorConversionCode _ _ = c'COLOR_GRAY2BGR565 instance ColorConversion 'BGR565 'GRAY where colorConversionCode _ _ = c'COLOR_BGR5652GRAY instance ColorConversion 'BGR 'BGR555 where colorConversionCode _ _ = c'COLOR_BGR2BGR555 instance ColorConversion 'RGB 'BGR555 where colorConversionCode _ _ = c'COLOR_RGB2BGR555 instance ColorConversion 'BGR555 'BGR where colorConversionCode _ _ = c'COLOR_BGR5552BGR instance ColorConversion 'BGR555 'RGB where colorConversionCode _ _ = c'COLOR_BGR5552RGB instance ColorConversion 'BGRA 'BGR555 where colorConversionCode _ _ = c'COLOR_BGRA2BGR555 instance ColorConversion 'RGBA 'BGR555 where colorConversionCode _ _ = c'COLOR_RGBA2BGR555 instance ColorConversion 'BGR555 'BGRA where colorConversionCode _ _ = c'COLOR_BGR5552BGRA instance ColorConversion 'BGR555 'RGBA where colorConversionCode _ _ = c'COLOR_BGR5552RGBA instance ColorConversion 'GRAY 'BGR555 where colorConversionCode _ _ = c'COLOR_GRAY2BGR555 instance ColorConversion 'BGR555 'GRAY where colorConversionCode _ _ = c'COLOR_BGR5552GRAY instance ColorConversion 'BGR 'XYZ where colorConversionCode _ _ = c'COLOR_BGR2XYZ instance ColorConversion 'RGB 'XYZ where colorConversionCode _ _ = c'COLOR_RGB2XYZ instance ColorConversion 'XYZ 'BGR where colorConversionCode _ _ = c'COLOR_XYZ2BGR instance ColorConversion 'XYZ 'RGB where colorConversionCode _ _ = c'COLOR_XYZ2RGB instance ColorConversion 'BGR 'YCrCb where colorConversionCode _ _ = c'COLOR_BGR2YCrCb instance ColorConversion 'RGB 'YCrCb where colorConversionCode _ _ = c'COLOR_RGB2YCrCb instance ColorConversion 'YCrCb 'BGR where colorConversionCode _ _ = c'COLOR_YCrCb2BGR instance ColorConversion 'YCrCb 'RGB where colorConversionCode _ _ = c'COLOR_YCrCb2RGB instance ColorConversion 'BGR 'HSV where colorConversionCode _ _ = c'COLOR_BGR2HSV instance ColorConversion 'RGB 'HSV where colorConversionCode _ _ = c'COLOR_RGB2HSV instance ColorConversion 'BGR 'Lab where colorConversionCode _ _ = c'COLOR_BGR2Lab instance ColorConversion 'RGB 'Lab where colorConversionCode _ _ = c'COLOR_RGB2Lab instance ColorConversion 'BGR 'Luv where colorConversionCode _ _ = c'COLOR_BGR2Luv instance ColorConversion 'RGB 'Luv where colorConversionCode _ _ = c'COLOR_RGB2Luv instance ColorConversion 'BGR 'HLS where colorConversionCode _ _ = c'COLOR_BGR2HLS instance ColorConversion 'RGB 'HLS where colorConversionCode _ _ = c'COLOR_RGB2HLS instance ColorConversion 'HSV 'BGR where colorConversionCode _ _ = c'COLOR_HSV2BGR instance ColorConversion 'HSV 'RGB where colorConversionCode _ _ = c'COLOR_HSV2RGB instance ColorConversion 'Lab 'BGR where colorConversionCode _ _ = c'COLOR_Lab2BGR instance ColorConversion 'Lab 'RGB where colorConversionCode _ _ = c'COLOR_Lab2RGB instance ColorConversion 'Luv 'BGR where colorConversionCode _ _ = c'COLOR_Luv2BGR instance ColorConversion 'Luv 'RGB where colorConversionCode _ _ = c'COLOR_Luv2RGB instance ColorConversion 'HLS 'BGR where colorConversionCode _ _ = c'COLOR_HLS2BGR instance ColorConversion 'HLS 'RGB where colorConversionCode _ _ = c'COLOR_HLS2RGB instance ColorConversion 'BGR 'HSV_FULL where colorConversionCode _ _ = c'COLOR_BGR2HSV_FULL instance ColorConversion 'RGB 'HSV_FULL where colorConversionCode _ _ = c'COLOR_RGB2HSV_FULL instance ColorConversion 'BGR 'HLS_FULL where colorConversionCode _ _ = c'COLOR_BGR2HLS_FULL instance ColorConversion 'RGB 'HLS_FULL where colorConversionCode _ _ = c'COLOR_RGB2HLS_FULL instance ColorConversion 'HSV 'BGR_FULL where colorConversionCode _ _ = c'COLOR_HSV2BGR_FULL instance ColorConversion 'HSV 'RGB_FULL where colorConversionCode _ _ = c'COLOR_HSV2RGB_FULL instance ColorConversion 'HLS 'BGR_FULL where colorConversionCode _ _ = c'COLOR_HLS2BGR_FULL instance ColorConversion 'HLS 'RGB_FULL where colorConversionCode _ _ = c'COLOR_HLS2RGB_FULL instance ColorConversion 'LBGR 'Lab where colorConversionCode _ _ = c'COLOR_LBGR2Lab instance ColorConversion 'LRGB 'Lab where colorConversionCode _ _ = c'COLOR_LRGB2Lab instance ColorConversion 'LBGR 'Luv where colorConversionCode _ _ = c'COLOR_LBGR2Luv instance ColorConversion 'LRGB 'Luv where colorConversionCode _ _ = c'COLOR_LRGB2Luv instance ColorConversion 'Lab 'LBGR where colorConversionCode _ _ = c'COLOR_Lab2LBGR instance ColorConversion 'Lab 'LRGB where colorConversionCode _ _ = c'COLOR_Lab2LRGB instance ColorConversion 'Luv 'LBGR where colorConversionCode _ _ = c'COLOR_Luv2LBGR instance ColorConversion 'Luv 'LRGB where colorConversionCode _ _ = c'COLOR_Luv2LRGB instance ColorConversion 'BGR 'YUV where colorConversionCode _ _ = c'COLOR_BGR2YUV instance ColorConversion 'RGB 'YUV where colorConversionCode _ _ = c'COLOR_RGB2YUV instance ColorConversion 'YUV 'BGR where colorConversionCode _ _ = c'COLOR_YUV2BGR instance ColorConversion 'YUV 'RGB where colorConversionCode _ _ = c'COLOR_YUV2RGB instance ColorConversion 'YUV 'RGB_NV12 where colorConversionCode _ _ = c'COLOR_YUV2RGB_NV12 instance ColorConversion 'YUV 'BGR_NV12 where colorConversionCode _ _ = c'COLOR_YUV2BGR_NV12 instance ColorConversion 'YUV 'RGB_NV21 where colorConversionCode _ _ = c'COLOR_YUV2RGB_NV21 instance ColorConversion 'YUV 'BGR_NV21 where colorConversionCode _ _ = c'COLOR_YUV2BGR_NV21 instance ColorConversion 'YUV420sp 'RGB where colorConversionCode _ _ = c'COLOR_YUV420sp2RGB instance ColorConversion 'YUV420sp 'BGR where colorConversionCode _ _ = c'COLOR_YUV420sp2BGR instance ColorConversion 'YUV 'RGBA_NV12 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_NV12 instance ColorConversion 'YUV 'BGRA_NV12 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_NV12 instance ColorConversion 'YUV 'RGBA_NV21 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_NV21 instance ColorConversion 'YUV 'BGRA_NV21 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_NV21 instance ColorConversion 'YUV420sp 'RGBA where colorConversionCode _ _ = c'COLOR_YUV420sp2RGBA instance ColorConversion 'YUV420sp 'BGRA where colorConversionCode _ _ = c'COLOR_YUV420sp2BGRA instance ColorConversion 'YUV 'RGB_YV12 where colorConversionCode _ _ = c'COLOR_YUV2RGB_YV12 instance ColorConversion 'YUV 'BGR_YV12 where colorConversionCode _ _ = c'COLOR_YUV2BGR_YV12 instance ColorConversion 'YUV 'RGB_IYUV where colorConversionCode _ _ = c'COLOR_YUV2RGB_IYUV instance ColorConversion 'YUV 'BGR_IYUV where colorConversionCode _ _ = c'COLOR_YUV2BGR_IYUV instance ColorConversion 'YUV 'RGB_I420 where colorConversionCode _ _ = c'COLOR_YUV2RGB_I420 instance ColorConversion 'YUV 'BGR_I420 where colorConversionCode _ _ = c'COLOR_YUV2BGR_I420 instance ColorConversion 'YUV420p 'RGB where colorConversionCode _ _ = c'COLOR_YUV420p2RGB instance ColorConversion 'YUV420p 'BGR where colorConversionCode _ _ = c'COLOR_YUV420p2BGR instance ColorConversion 'YUV 'RGBA_YV12 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YV12 instance ColorConversion 'YUV 'BGRA_YV12 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YV12 instance ColorConversion 'YUV 'RGBA_IYUV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_IYUV instance ColorConversion 'YUV 'BGRA_IYUV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_IYUV instance ColorConversion 'YUV 'RGBA_I420 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_I420 instance ColorConversion 'YUV 'BGRA_I420 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_I420 instance ColorConversion 'YUV420p 'RGBA where colorConversionCode _ _ = c'COLOR_YUV420p2RGBA instance ColorConversion 'YUV420p 'BGRA where colorConversionCode _ _ = c'COLOR_YUV420p2BGRA instance ColorConversion 'YUV 'GRAY_420 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_420 instance ColorConversion 'YUV 'GRAY_NV21 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_NV21 instance ColorConversion 'YUV 'GRAY_NV12 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_NV12 instance ColorConversion 'YUV 'GRAY_YV12 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YV12 instance ColorConversion 'YUV 'GRAY_IYUV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_IYUV instance ColorConversion 'YUV 'GRAY_I420 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_I420 instance ColorConversion 'YUV420sp 'GRAY where colorConversionCode _ _ = c'COLOR_YUV420sp2GRAY instance ColorConversion 'YUV420p 'GRAY where colorConversionCode _ _ = c'COLOR_YUV420p2GRAY instance ColorConversion 'YUV 'RGB_UYVY where colorConversionCode _ _ = c'COLOR_YUV2RGB_UYVY instance ColorConversion 'YUV 'BGR_UYVY where colorConversionCode _ _ = c'COLOR_YUV2BGR_UYVY instance ColorConversion 'YUV 'RGB_Y422 where colorConversionCode _ _ = c'COLOR_YUV2RGB_Y422 instance ColorConversion 'YUV 'BGR_Y422 where colorConversionCode _ _ = c'COLOR_YUV2BGR_Y422 instance ColorConversion 'YUV 'RGB_UYNV where colorConversionCode _ _ = c'COLOR_YUV2RGB_UYNV instance ColorConversion 'YUV 'BGR_UYNV where colorConversionCode _ _ = c'COLOR_YUV2BGR_UYNV instance ColorConversion 'YUV 'RGBA_UYVY where colorConversionCode _ _ = c'COLOR_YUV2RGBA_UYVY instance ColorConversion 'YUV 'BGRA_UYVY where colorConversionCode _ _ = c'COLOR_YUV2BGRA_UYVY instance ColorConversion 'YUV 'RGBA_Y422 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_Y422 instance ColorConversion 'YUV 'BGRA_Y422 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_Y422 instance ColorConversion 'YUV 'RGBA_UYNV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_UYNV instance ColorConversion 'YUV 'BGRA_UYNV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_UYNV instance ColorConversion 'YUV 'RGB_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUY2 instance ColorConversion 'YUV 'BGR_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUY2 instance ColorConversion 'YUV 'RGB_YVYU where colorConversionCode _ _ = c'COLOR_YUV2RGB_YVYU instance ColorConversion 'YUV 'BGR_YVYU where colorConversionCode _ _ = c'COLOR_YUV2BGR_YVYU instance ColorConversion 'YUV 'RGB_YUYV where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUYV instance ColorConversion 'YUV 'BGR_YUYV where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUYV instance ColorConversion 'YUV 'RGB_YUNV where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUNV instance ColorConversion 'YUV 'BGR_YUNV where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUNV instance ColorConversion 'YUV 'RGBA_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUY2 instance ColorConversion 'YUV 'BGRA_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUY2 instance ColorConversion 'YUV 'RGBA_YVYU where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YVYU instance ColorConversion 'YUV 'BGRA_YVYU where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YVYU instance ColorConversion 'YUV 'RGBA_YUYV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUYV instance ColorConversion 'YUV 'BGRA_YUYV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUYV instance ColorConversion 'YUV 'RGBA_YUNV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUNV instance ColorConversion 'YUV 'BGRA_YUNV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUNV instance ColorConversion 'YUV 'GRAY_UYVY where colorConversionCode _ _ = c'COLOR_YUV2GRAY_UYVY instance ColorConversion 'YUV 'GRAY_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUY2 instance ColorConversion 'YUV 'GRAY_Y422 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_Y422 instance ColorConversion 'YUV 'GRAY_UYNV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_UYNV instance ColorConversion 'YUV 'GRAY_YVYU where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YVYU instance ColorConversion 'YUV 'GRAY_YUYV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUYV instance ColorConversion 'YUV 'GRAY_YUNV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUNV instance ColorConversion 'RGBA 'MRGBA where colorConversionCode _ _ = c'COLOR_RGBA2mRGBA instance ColorConversion 'MRGBA 'RGBA where colorConversionCode _ _ = c'COLOR_mRGBA2RGBA instance ColorConversion 'RGB 'YUV_I420 where colorConversionCode _ _ = c'COLOR_RGB2YUV_I420 instance ColorConversion 'BGR 'YUV_I420 where colorConversionCode _ _ = c'COLOR_BGR2YUV_I420 instance ColorConversion 'RGB 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_RGB2YUV_IYUV instance ColorConversion 'BGR 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_BGR2YUV_IYUV instance ColorConversion 'RGBA 'YUV_I420 where colorConversionCode _ _ = c'COLOR_RGBA2YUV_I420 instance ColorConversion 'BGRA 'YUV_I420 where colorConversionCode _ _ = c'COLOR_BGRA2YUV_I420 instance ColorConversion 'RGBA 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_RGBA2YUV_IYUV instance ColorConversion 'BGRA 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_BGRA2YUV_IYUV instance ColorConversion 'RGB 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_RGB2YUV_YV12 instance ColorConversion 'BGR 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_BGR2YUV_YV12 instance ColorConversion 'RGBA 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_RGBA2YUV_YV12 instance ColorConversion 'BGRA 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_BGRA2YUV_YV12 instance ColorConversion 'BayerBG 'BGR where colorConversionCode _ _ = c'COLOR_BayerBG2BGR instance ColorConversion 'BayerGB 'BGR where colorConversionCode _ _ = c'COLOR_BayerGB2BGR instance ColorConversion 'BayerRG 'BGR where colorConversionCode _ _ = c'COLOR_BayerRG2BGR instance ColorConversion 'BayerGR 'BGR where colorConversionCode _ _ = c'COLOR_BayerGR2BGR instance ColorConversion 'BayerBG 'RGB where colorConversionCode _ _ = c'COLOR_BayerBG2RGB instance ColorConversion 'BayerGB 'RGB where colorConversionCode _ _ = c'COLOR_BayerGB2RGB instance ColorConversion 'BayerRG 'RGB where colorConversionCode _ _ = c'COLOR_BayerRG2RGB instance ColorConversion 'BayerGR 'RGB where colorConversionCode _ _ = c'COLOR_BayerGR2RGB instance ColorConversion 'BayerBG 'GRAY where colorConversionCode _ _ = c'COLOR_BayerBG2GRAY instance ColorConversion 'BayerGB 'GRAY where colorConversionCode _ _ = c'COLOR_BayerGB2GRAY instance ColorConversion 'BayerRG 'GRAY where colorConversionCode _ _ = c'COLOR_BayerRG2GRAY instance ColorConversion 'BayerGR 'GRAY where colorConversionCode _ _ = c'COLOR_BayerGR2GRAY instance ColorConversion 'BayerBG 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerBG2BGR_VNG instance ColorConversion 'BayerGB 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerGB2BGR_VNG instance ColorConversion 'BayerRG 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerRG2BGR_VNG instance ColorConversion 'BayerGR 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerGR2BGR_VNG instance ColorConversion 'BayerBG 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerBG2RGB_VNG instance ColorConversion 'BayerGB 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerGB2RGB_VNG instance ColorConversion 'BayerRG 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerRG2RGB_VNG instance ColorConversion 'BayerGR 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerGR2RGB_VNG instance ColorConversion 'BayerBG 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerBG2BGR_EA instance ColorConversion 'BayerGB 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerGB2BGR_EA instance ColorConversion 'BayerRG 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerRG2BGR_EA instance ColorConversion 'BayerGR 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerGR2BGR_EA instance ColorConversion 'BayerBG 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerBG2RGB_EA instance ColorConversion 'BayerGB 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerGB2RGB_EA instance ColorConversion 'BayerRG 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerRG2RGB_EA instance ColorConversion 'BayerGR 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerGR2RGB_EA -- | Gives the number of channels associated with a particular color encoding type family ColorCodeChannels (cc :: ColorCode) :: Nat where ColorCodeChannels 'BayerBG = 1 ColorCodeChannels 'BayerGB = 1 ColorCodeChannels 'BayerGR = 1 ColorCodeChannels 'BayerRG = 1 ColorCodeChannels 'BGR = 3 ColorCodeChannels 'BGR555 = 2 ColorCodeChannels 'BGR565 = 2 ColorCodeChannels 'BGRA = 4 ColorCodeChannels 'BGRA_I420 = 4 ColorCodeChannels 'BGRA_IYUV = 4 ColorCodeChannels 'BGRA_NV12 = 4 ColorCodeChannels 'BGRA_NV21 = 4 ColorCodeChannels 'BGRA_UYNV = 4 ColorCodeChannels 'BGRA_UYVY = 4 ColorCodeChannels 'BGRA_Y422 = 4 ColorCodeChannels 'BGRA_YUNV = 4 ColorCodeChannels 'BGRA_YUY2 = 4 ColorCodeChannels 'BGRA_YUYV = 4 ColorCodeChannels 'BGRA_YV12 = 4 ColorCodeChannels 'BGRA_YVYU = 4 ColorCodeChannels 'BGR_EA = 3 ColorCodeChannels 'BGR_FULL = 3 ColorCodeChannels 'BGR_I420 = 3 ColorCodeChannels 'BGR_IYUV = 3 ColorCodeChannels 'BGR_NV12 = 3 ColorCodeChannels 'BGR_NV21 = 3 ColorCodeChannels 'BGR_UYNV = 3 ColorCodeChannels 'BGR_UYVY = 3 ColorCodeChannels 'BGR_VNG = 3 ColorCodeChannels 'BGR_Y422 = 3 ColorCodeChannels 'BGR_YUNV = 3 ColorCodeChannels 'BGR_YUY2 = 3 ColorCodeChannels 'BGR_YUYV = 3 ColorCodeChannels 'BGR_YV12 = 3 ColorCodeChannels 'BGR_YVYU = 3 ColorCodeChannels 'GRAY = 1 ColorCodeChannels 'GRAY_420 = 1 ColorCodeChannels 'GRAY_I420 = 1 ColorCodeChannels 'GRAY_IYUV = 1 ColorCodeChannels 'GRAY_NV12 = 1 ColorCodeChannels 'GRAY_NV21 = 1 ColorCodeChannels 'GRAY_UYNV = 1 ColorCodeChannels 'GRAY_UYVY = 1 ColorCodeChannels 'GRAY_Y422 = 1 ColorCodeChannels 'GRAY_YUNV = 1 ColorCodeChannels 'GRAY_YUY2 = 1 ColorCodeChannels 'GRAY_YUYV = 1 ColorCodeChannels 'GRAY_YV12 = 1 ColorCodeChannels 'GRAY_YVYU = 1 ColorCodeChannels 'HLS = 3 ColorCodeChannels 'HLS_FULL = 3 ColorCodeChannels 'HSV = 3 ColorCodeChannels 'HSV_FULL = 3 ColorCodeChannels 'Lab = 3 ColorCodeChannels 'LBGR = 3 ColorCodeChannels 'LRGB = 3 ColorCodeChannels 'Luv = 3 ColorCodeChannels 'MRGBA = 4 ColorCodeChannels 'RGB = 3 ColorCodeChannels 'RGBA = 4 ColorCodeChannels 'RGBA_I420 = 4 ColorCodeChannels 'RGBA_IYUV = 4 ColorCodeChannels 'RGBA_NV12 = 4 ColorCodeChannels 'RGBA_NV21 = 4 ColorCodeChannels 'RGBA_UYNV = 4 ColorCodeChannels 'RGBA_UYVY = 4 ColorCodeChannels 'RGBA_Y422 = 4 ColorCodeChannels 'RGBA_YUNV = 4 ColorCodeChannels 'RGBA_YUY2 = 4 ColorCodeChannels 'RGBA_YUYV = 4 ColorCodeChannels 'RGBA_YV12 = 4 ColorCodeChannels 'RGBA_YVYU = 4 ColorCodeChannels 'RGB_EA = 3 ColorCodeChannels 'RGB_FULL = 3 ColorCodeChannels 'RGB_I420 = 3 ColorCodeChannels 'RGB_IYUV = 3 ColorCodeChannels 'RGB_NV12 = 3 ColorCodeChannels 'RGB_NV21 = 3 ColorCodeChannels 'RGB_UYNV = 3 ColorCodeChannels 'RGB_UYVY = 3 ColorCodeChannels 'RGB_VNG = 3 ColorCodeChannels 'RGB_Y422 = 3 ColorCodeChannels 'RGB_YUNV = 3 ColorCodeChannels 'RGB_YUY2 = 3 ColorCodeChannels 'RGB_YUYV = 3 ColorCodeChannels 'RGB_YV12 = 3 ColorCodeChannels 'RGB_YVYU = 3 ColorCodeChannels 'XYZ = 3 ColorCodeChannels 'YCrCb = 3 ColorCodeChannels 'YUV = 3 ColorCodeChannels 'YUV420p = 3 ColorCodeChannels 'YUV420sp = 3 ColorCodeChannels 'YUV_I420 = 1 ColorCodeChannels 'YUV_IYUV = 1 ColorCodeChannels 'YUV_YV12 = 1 class ColorCodeMatchesChannels (code :: ColorCode) (channels :: DS Nat) instance ColorCodeMatchesChannels code 'D instance (ColorCodeChannels code ~ channels) => ColorCodeMatchesChannels code ('S channels) type family ColorCodeDepth (srcCode :: ColorCode) (dstCode :: ColorCode) (srcDepth :: DS *) :: DS * where ColorCodeDepth 'BGR 'BGRA ('S depth) = 'S depth ColorCodeDepth 'RGB 'BGRA ('S depth) = 'S depth ColorCodeDepth 'BGRA 'BGR ('S depth) = 'S depth ColorCodeDepth 'RGBA 'BGR ('S depth) = 'S depth ColorCodeDepth 'RGB 'BGR ('S depth) = 'S depth ColorCodeDepth 'BGRA 'RGBA ('S depth) = 'S depth ColorCodeDepth 'BGR 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'BGRA 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'BGRA 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'BGR565 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BGR565 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'BGR565 'BGRA ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'BGRA ('S Word8) = 'S Word8 ColorCodeDepth 'BGR565 'RGBA ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'RGBA ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'GRAY ('S depth) = 'S depth ColorCodeDepth 'BGRA 'GRAY ('S depth) = 'S depth ColorCodeDepth 'RGB 'GRAY ('S depth) = 'S depth ColorCodeDepth 'RGBA 'GRAY ('S depth) = 'S depth ColorCodeDepth 'BGR565 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'GRAY 'BGR ('S depth) = 'S depth ColorCodeDepth 'GRAY 'BGRA ('S depth) = 'S depth ColorCodeDepth 'GRAY 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'GRAY 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'YCrCb ('S depth) = 'S depth ColorCodeDepth 'BGR 'YUV ('S depth) = 'S depth ColorCodeDepth 'RGB 'YCrCb ('S depth) = 'S depth ColorCodeDepth 'RGB 'YUV ('S depth) = 'S depth ColorCodeDepth 'YCrCb 'BGR ('S depth) = 'S depth ColorCodeDepth 'YCrCb 'RGB ('S depth) = 'S depth ColorCodeDepth 'YUV 'BGR ('S depth) = 'S depth ColorCodeDepth 'YUV 'RGB ('S depth) = 'S depth ColorCodeDepth 'BGR 'XYZ ('S depth) = 'S depth ColorCodeDepth 'RGB 'XYZ ('S depth) = 'S depth ColorCodeDepth 'XYZ 'BGR ('S depth) = 'S depth ColorCodeDepth 'XYZ 'RGB ('S depth) = 'S depth ColorCodeDepth 'BGR 'HSV ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'HSV ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'HSV_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'HSV_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'HLS ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'HLS ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'HLS_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'HLS_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'HSV ('S Float) = 'S Float ColorCodeDepth 'RGB 'HSV ('S Float) = 'S Float ColorCodeDepth 'BGR 'HSV_FULL ('S Float) = 'S Float ColorCodeDepth 'RGB 'HSV_FULL ('S Float) = 'S Float ColorCodeDepth 'BGR 'HLS ('S Float) = 'S Float ColorCodeDepth 'RGB 'HLS ('S Float) = 'S Float ColorCodeDepth 'BGR 'HLS_FULL ('S Float) = 'S Float ColorCodeDepth 'RGB 'HLS_FULL ('S Float) = 'S Float ColorCodeDepth 'HSV 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'HSV 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'HSV 'BGR_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'HSV 'RGB_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'HLS 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'HLS 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'HLS 'BGR_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'HLS 'RGB_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'HSV 'BGR ('S Float) = 'S Float ColorCodeDepth 'HSV 'RGB ('S Float) = 'S Float ColorCodeDepth 'HSV 'BGR_FULL ('S Float) = 'S Float ColorCodeDepth 'HSV 'RGB_FULL ('S Float) = 'S Float ColorCodeDepth 'HLS 'BGR ('S Float) = 'S Float ColorCodeDepth 'HLS 'RGB ('S Float) = 'S Float ColorCodeDepth 'HLS 'BGR_FULL ('S Float) = 'S Float ColorCodeDepth 'HLS 'RGB_FULL ('S Float) = 'S Float ColorCodeDepth 'BGR 'Lab ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'Lab ('S Word8) = 'S Word8 ColorCodeDepth 'LBGR 'Lab ('S Word8) = 'S Word8 ColorCodeDepth 'LRGB 'Lab ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'Luv ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'Luv ('S Word8) = 'S Word8 ColorCodeDepth 'LBGR 'Luv ('S Word8) = 'S Word8 ColorCodeDepth 'LRGB 'Luv ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'Lab ('S Float) = 'S Float ColorCodeDepth 'RGB 'Lab ('S Float) = 'S Float ColorCodeDepth 'LBGR 'Lab ('S Float) = 'S Float ColorCodeDepth 'LRGB 'Lab ('S Float) = 'S Float ColorCodeDepth 'BGR 'Luv ('S Float) = 'S Float ColorCodeDepth 'RGB 'Luv ('S Float) = 'S Float ColorCodeDepth 'LBGR 'Luv ('S Float) = 'S Float ColorCodeDepth 'LRGB 'Luv ('S Float) = 'S Float ColorCodeDepth 'Lab 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'Lab 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'Lab 'LBGR ('S Word8) = 'S Word8 ColorCodeDepth 'Lab 'LRGB ('S Word8) = 'S Word8 ColorCodeDepth 'Luv 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'Luv 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'Luv 'LBGR ('S Word8) = 'S Word8 ColorCodeDepth 'Luv 'LRGB ('S Word8) = 'S Word8 ColorCodeDepth 'Lab 'BGR ('S Float) = 'S Float ColorCodeDepth 'Lab 'RGB ('S Float) = 'S Float ColorCodeDepth 'Lab 'LBGR ('S Float) = 'S Float ColorCodeDepth 'Lab 'LRGB ('S Float) = 'S Float ColorCodeDepth 'Luv 'BGR ('S Float) = 'S Float ColorCodeDepth 'Luv 'RGB ('S Float) = 'S Float ColorCodeDepth 'Luv 'LBGR ('S Float) = 'S Float ColorCodeDepth 'Luv 'LRGB ('S Float) = 'S Float ColorCodeDepth 'BayerBG 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BayerBG 'GRAY ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGB 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGB 'GRAY ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGR 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGR 'GRAY ('S Word16) = 'S Word16 ColorCodeDepth 'BayerRG 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BayerRG 'GRAY ('S Word16) = 'S Word16 ColorCodeDepth 'BayerBG 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BayerBG 'BGR ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGB 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGB 'BGR ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGR 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGR 'BGR ('S Word16) = 'S Word16 ColorCodeDepth 'BayerRG 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BayerRG 'BGR ('S Word16) = 'S Word16 ColorCodeDepth 'BayerBG 'BGR_VNG ('S Word8) = 'S Word8 ColorCodeDepth 'BayerBG 'BGR_VNG ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGB 'BGR_VNG ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGB 'BGR_VNG ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGR 'BGR_VNG ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGR 'BGR_VNG ('S Word16) = 'S Word16 ColorCodeDepth 'BayerRG 'BGR_VNG ('S Word8) = 'S Word8 ColorCodeDepth 'BayerRG 'BGR_VNG ('S Word16) = 'S Word16 ColorCodeDepth 'BayerBG 'BGR_EA ('S Word8) = 'S Word8 ColorCodeDepth 'BayerBG 'BGR_EA ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGB 'BGR_EA ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGB 'BGR_EA ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGR 'BGR_EA ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGR 'BGR_EA ('S Word16) = 'S Word16 ColorCodeDepth 'BayerRG 'BGR_EA ('S Word8) = 'S Word8 ColorCodeDepth 'BayerRG 'BGR_EA ('S Word16) = 'S Word16 ColorCodeDepth 'YUV 'BGR_NV21 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_NV21 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_NV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_NV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_NV21 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_NV21 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_NV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_NV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'GRAY_420 ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'YUV_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'YUV_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'YUV_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'BGRA 'YUV_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'YUV_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'YUV_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'YUV_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'BGRA 'YUV_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_YVYU ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_YVYU ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_YVYU ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_YVYU ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'GRAY_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'GRAY_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'MRGBA ('S Word8) = 'S Word8 ColorCodeDepth 'MRGBA 'RGBA ('S Word8) = 'S Word8 ColorCodeDepth srcCode dstCode 'D = 'D
Cortlandd/haskell-opencv
src/OpenCV/Internal/ImgProc/MiscImgTransform/ColorCodes.hs
Haskell
bsd-3-clause
43,738
import Control.Monad import Data.MessagePack {- main = do sb <- newSimpleBuffer pc <- newPacker sb pack pc [(1,2),(2,3),(3::Int,4::Int)] pack pc [4,5,6::Int] pack pc "hoge" bs <- simpleBufferData sb print bs up <- newUnpacker defaultInitialBufferSize unpackerFeed up bs let f = do res <- unpackerExecute up when (res==1) $ do obj <- unpackerData up print obj f f return () -} main = do bs <- packb [(1,2),(2,3),(3::Int,4::Int)] print bs dat <- unpackb bs print (dat :: Result [(Int, Int)])
tanakh/hsmsgpack
test/Test.hs
Haskell
bsd-3-clause
587
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} module Ast.Error.Common ( module X ) where import Ast.Error.Common.Kind as X import Ast.Error.Common.Type as X
dalaing/type-systems
src/Ast/Error/Common.hs
Haskell
bsd-3-clause
271
{-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE EmptyCase #-} module Language.BCoPL.TypeLevel.MetaTheory.CompareNat where import Language.BCoPL.TypeLevel.Peano import Language.BCoPL.TypeLevel.CompareNat -- | 定理 2.11 (CompareNat1: 0 < 1+a) zeroLtSucc1 :: Nat' n -> LessThan1 Z (S n) zeroLtSucc1 n = case n of Z' -> LSucc1 Z' S' n' -> LTrans1 Z' n (S' n) (zeroLtSucc1 n') (LSucc1 n) -- | 定理 2.11 (CompareNat2: 0 < 1+a) zeroLtSucc2 :: Nat' n -> LessThan2 Z (S n) zeroLtSucc2 = LZero2 -- | 定理 2.11 (CompareNat3: 0 < 1+a) zeroLtSucc3 :: Nat' n -> LessThan3 Z (S n) zeroLtSucc3 n = case n of Z' -> LSucc3 Z' S' n' -> LSuccR3 Z' n (zeroLtSucc3 n') -- | 定理 2.12 (CompareNat1: 1+a < 1+b => a < b) ltPred1 :: Nat' n1 -> Nat' n2 -> LessThan1 (S n1) (S n2) -> LessThan1 n1 n2 ltPred1 n1 n2 lt = case lt of LSucc1 _ -> LSucc1 n1 LTrans1 _ n3 _ lt1 lt2 -> LTrans1 n1 (S' n1) n2 (LSucc1 n1) (lemma1 (S' n1) n3 n2 lt1 lt2) lemma1 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan1 n1 n2 -> LessThan1 n2 (S n3) -> LessThan1 n1 n3 lemma1 n1 n2 n3 lt1 lt2 = case lt2 of LSucc1 _ -> lt1 LTrans1 _ n4 _ lt3 lt4 -> LTrans1 n1 n2 n3 lt1 (lemma1 n2 n4 n3 lt3 lt4) -- | 定理 2.12 (CompareNat2: 1+a < 1+b => a < b) ltPred2 :: Nat' n1 -> Nat' n2 -> LessThan2 (S n1) (S n2) -> LessThan2 n1 n2 ltPred2 n1 n2 lt = case lt of LSuccSucc2 _ _ lt' -> lt' pat -> case pat of {} -- | 定理 2.12 (CompareNat3: 1+a < 1+b => a < b) ltPred3 :: Nat' n1 -> Nat' n2 -> LessThan3 (S n1) (S n2) -> LessThan3 n1 n2 ltPred3 n1 n2 lt = case lt of LSucc3 _ -> LSucc3 n1 LSuccR3 n1' n2' lt' -> lemma3 n1 n1' n2 (LSucc3 n1) lt' lemma3 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan3 n1 n2 -> LessThan3 n2 n3 -> LessThan3 n1 n3 lemma3 n1 n2 n3 lt1 lt2 = case lt2 of LSucc3 _ -> LSuccR3 n1 n2 lt1 LSuccR3 _ n4 lt3 -> lemma3 n1 n4 n3 (lemma3 n1 n2 n4 lt1 lt3) (LSucc3 n4) -- 定理 2.13 -- | 定理 2.13 (CompareNat1: a < b, b < c => a < c) trans1 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan1 n1 n2 -> LessThan1 n2 n3 -> LessThan1 n1 n3 trans1 = LTrans1 -- | 定理 2.13 (CompareNat2: a < b, b < c => a < c) trans2 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan2 n1 n2 -> LessThan2 n2 n3 -> LessThan2 n1 n3 trans2 n1 n2 n3 lt1 lt2 = case lt2 of LSuccSucc2 n4 n5 lt3 -> case lt1 of LZero2 _ -> LZero2 n5 LSuccSucc2 n6 _ lt4 -> LSuccSucc2 n6 n5 (trans2 n6 n4 n5 lt4 lt3) pat -> case pat of {} -- | 定理 2.13 (CompareNat3: a < b, b < c => a < c) trans3 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan3 n1 n2 -> LessThan3 n2 n3 -> LessThan3 n1 n3 trans3 = lemma3 -- | 定理 2.14 eqv13 :: Nat' n1 -> Nat' n2 -> LessThan1 n1 n2 -> LessThan3 n1 n2 eqv13 n1 n2 lt1 = case lt1 of LSucc1 _ -> LSucc3 n1 LTrans1 _ n3 _ lt2 lt3 -> trans3 n1 n3 n2 (eqv13 n1 n3 lt2) (eqv13 n3 n2 lt3) eqv32 :: Nat' n1 -> Nat' n2 -> LessThan3 n1 n2 -> LessThan2 n1 n2 eqv32 n1 n2 lt1 = case lt1 of LSucc3 _ -> case n1 of Z' -> LZero2 n1 S' n1' -> LSuccSucc2 n1' n1 (eqv32 n1' n1 (LSucc3 n1')) LSuccR3 _ n3 lt2 -> trans2 n1 n3 n2 (eqv32 n1 n3 lt2) (eqv32 n3 n2 (LSucc3 n3)) eqv21 :: Nat' n1 -> Nat' n2 -> LessThan2 n1 n2 -> LessThan1 n1 n2 eqv21 n1 n2 lt1 = case lt1 of LZero2 n3 -> case n3 of Z' -> LSucc1 n3 S' n4 -> trans1 n1 n3 n2 (eqv21 n1 n3 (LZero2 n4)) (LSucc1 n3) LSuccSucc2 n5 n6 lt2 -> succSucc1 n5 n6 (eqv21 n5 n6 lt2) succSucc1 :: Nat' n1 -> Nat' n2 -> LessThan1 n1 n2 -> LessThan1 (S n1) (S n2) succSucc1 n1 n2 lt = case lt of LSucc1 _ -> LSucc1 n2 LTrans1 _ n3 _ lt' lt'' -> LTrans1 (S' n1) (S' n3) (S' n2) (succSucc1 n1 n3 lt') (succSucc1 n3 n2 lt'')
nobsun/hs-bcopl
src/Language/BCoPL/TypeLevel/MetaTheory/CompareNat.hs
Haskell
bsd-3-clause
3,794
module Web.Plurk.Types ( Return (..) , Message (..) , User (..) , Privacy (..) , Gender (..) , Relationship (..) , Qualifier (..) , ReadStat (..) , MsgType (..) , CommentStat (..) , KarmaStat (..) , Profile (..) , jsToInt , jsToDouble , jsToStr , jsToBool , jsToEnum , jsToDateTime , jsToList , jsToMap , jsToIntMap , jsToErrorMsg , jsToUser , jsToMessage , jsToKarmaStat , jsToProfile ) where import Data.IntMap (IntMap) import qualified Data.IntMap as IM import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import Data.Ratio import Data.Time import Data.Time.Clock.POSIX import System.Locale import Text.JSON data Return a = PData a | PSucc | PError String data Message = Message { msg_plurk_id :: Int , msg_qualifier :: Qualifier , msg_is_unread :: ReadStat , msg_plurk_type :: MsgType , msg_user_id :: Int , msg_owner_id :: Int , msg_posted :: UTCTime , msg_no_comments :: CommentStat , msg_content :: String , msg_content_raw :: String , msg_response_count :: Int , msg_responses_seen :: Int , msg_limited_to :: [Int] } deriving Show data User = User { user_id :: Int , user_nick_name :: String , user_display_name :: String , user_has_profile_image :: Bool , user_avatar :: Int , user_location :: String , user_date_of_birth :: Day , user_full_name :: String , user_gender :: Gender , user_page_title :: String , user_karma :: Double , user_recruited :: Int , user_relationship :: Relationship } deriving Show data KarmaStat = KarmaStat { karma_stat_karma_trend :: [(UTCTime, Double)] , karma_stat_karma_fall_reason :: String , karma_stat_current_karma :: Double , karma_stat_karma_graph :: String } deriving Show data Profile = Profile { profile_friends_count :: Int , profile_fans_count :: Int , profile_unread_count :: Int , profile_alerts_count :: Int , profile_are_friends :: Bool , profile_is_fan :: Bool , profile_is_following :: Bool , profile_has_read_permission :: Bool , profile_user_info :: User , profile_privacy :: Privacy , profile_plurks_users :: IntMap User , profile_plurks :: [Message] } deriving Show data Privacy = World | OnlyFriends | OnlyMe instance Show Privacy where show World = "world" show OnlyFriends = "only_friends" show OnlyMe = "only_me" instance Read Privacy where readsPrec 0 "world" = [(World, "")] readsPrec 0 "only_friends" = [(OnlyFriends, "")] readsPrec 0 "only_me" = [(OnlyMe, "")] readsPrec _ _ = [(World, "")] data Gender = Female | Male | Other deriving Enum instance Show Gender where show Female = "female" show Male = "male" show Other = "other" data Relationship = NotSaying | Single | Married | Divorced | Engaged | InRelationship | Complicated | Widowed | OpenRelationship instance Show Relationship where show NotSaying = "not_saying" show Single = "single" show Married = "married" show Divorced = "divorced" show Engaged = "engaged" show InRelationship = "in_relationship" show Complicated = "complicated" show Widowed = "widowed" show OpenRelationship = "open_relationship" instance Read Relationship where readsPrec 0 "not_saying" = [(NotSaying, "")] readsPrec 0 "single" = [(Single, "")] readsPrec 0 "married" = [(Married, "")] readsPrec 0 "divorced" = [(Divorced, "")] readsPrec 0 "engaged" = [(Engaged, "")] readsPrec 0 "in_relationship" = [(InRelationship, "")] readsPrec 0 "complicated" = [(Complicated, "")] readsPrec 0 "widowed" = [(Widowed, "")] readsPrec 0 "open_relationship" = [(OpenRelationship, "")] readsPrec _ _ = [(NotSaying, "")] data Qualifier = Loves | Likes | Shares | Gives | Hates | Wants | Has | Will | Asks | Wishes | Was | Feels | Thinks | Says | Is | Colon | Freestyle | Hopes | Needs | Wonders instance Show Qualifier where show Loves = "loves" show Likes = "likes" show Shares = "shares" show Gives = "gives" show Hates = "hates" show Wants = "wants" show Has = "has" show Will = "will" show Asks = "asks" show Wishes = "wishes" show Was = "was" show Feels = "feels" show Thinks = "thinks" show Says = "says" show Is = "is" show Colon = ":" show Freestyle = "freestyle" show Hopes = "hopes" show Needs = "needs" show Wonders = "wonders" instance Read Qualifier where readsPrec 0 "loves" = [(Loves, "")] readsPrec 0 "likes" = [(Likes, "")] readsPrec 0 "shares" = [(Shares, "")] readsPrec 0 "gives" = [(Gives, "")] readsPrec 0 "hates" = [(Hates, "")] readsPrec 0 "wants" = [(Wants, "")] readsPrec 0 "has" = [(Has, "")] readsPrec 0 "will" = [(Will, "")] readsPrec 0 "asks" = [(Asks, "")] readsPrec 0 "wishes" = [(Wishes, "")] readsPrec 0 "was" = [(Was, "")] readsPrec 0 "feels" = [(Feels, "")] readsPrec 0 "thinks" = [(Thinks, "")] readsPrec 0 "says" = [(Says, "")] readsPrec 0 "is" = [(Is, "")] readsPrec 0 ":" = [(Colon, "")] readsPrec 0 "freestyle" = [(Freestyle, "")] readsPrec 0 "hopes" = [(Hopes, "")] readsPrec 0 "needs" = [(Needs, "")] readsPrec 0 "wonders" = [(Wonders, "")] readsPrec _ _ = [(Colon, "")] data ReadStat = Read | UnRead | Muted deriving (Enum, Show) data MsgType = Public | Private | PubLogged | PrivLogged deriving (Enum, Show) data CommentStat = EnResp | DisResp | OnlyFriendResp deriving (Enum, Show) jsToDouble :: JSValue -> Double jsToDouble JSNull = 0 jsToDouble (JSRational _ n) = fromRational n jsToDouble v = error $ "jsToDouble: " ++ show v jsToInt :: JSValue -> Int jsToInt JSNull = 0 jsToInt (JSRational _ n) = fromInteger $ numerator n jsToInt v = error $ "jsToInt: " ++ show v jsToStr :: JSValue -> String jsToStr JSNull = "" jsToStr (JSString s) = fromJSString s jsToStr v = error $ "jsToStr: " ++ show v jsToBool :: JSValue -> Bool jsToBool JSNull = False jsToBool (JSBool b) = b jsToBool v = error $ "jsToBool: " ++ show v jsToList :: JSValue -> [JSValue] jsToList JSNull = [] jsToList (JSArray a) = a jsToList v = error $ "jsToList: " ++ show v jsToMap :: JSValue -> Map String JSValue jsToMap JSNull = M.empty jsToMap (JSObject o) = M.fromList $ fromJSObject o jsToMap v = error $ "jsToMap: " ++ show v jsToIntMap :: JSValue -> IntMap JSValue jsToIntMap JSNull = IM.empty jsToIntMap (JSObject o) = IM.fromList $ map (\(k, v) -> (read k, v)) $ fromJSObject o jsToIntMap v = error $ "jsToIntMap: " ++ show v jsToEnum :: Enum a => JSValue -> a jsToEnum = toEnum . jsToInt jsToDateTime :: ParseTime a => JSValue -> Maybe a jsToDateTime = parseTime defaultTimeLocale fmt . jsToStr where fmt = "%a, %d %b %Y %H:%M:%S %Z" jsToErrorMsg :: JSValue -> String jsToErrorMsg = jsToStr . M.findWithDefault JSNull "error_text" . jsToMap getMapVal :: String -> Map String JSValue -> JSValue getMapVal = M.findWithDefault JSNull nullMsg = Message { msg_plurk_id = 0 , msg_qualifier = Colon , msg_is_unread = Read , msg_plurk_type = Public , msg_user_id = 0 , msg_owner_id = 0 , msg_posted = UTCTime (ModifiedJulianDay 0) (secondsToDiffTime 0) , msg_no_comments = EnResp , msg_content = "" , msg_content_raw = "" , msg_response_count = 0 , msg_responses_seen = 0 , msg_limited_to = [] } jsToMessage :: JSValue -> Message jsToMessage obj = msg where msg = nullMsg { msg_plurk_id = jsToInt $ val "plurk_id" , msg_qualifier = read $ jsToStr $ val "qualifier" , msg_is_unread = jsToEnum $ val "is_unread" , msg_plurk_type = jsToEnum $ val "plurk_type" , msg_user_id = jsToInt $ val "user_id" , msg_owner_id = jsToInt $ val "owner_id" , msg_posted = maybeTime $ jsToDateTime $ val "posted" , msg_no_comments = jsToEnum $ val "no_comments" , msg_content = jsToStr $ val "content" , msg_content_raw = jsToStr $ val "content_raw" , msg_response_count = jsToInt $ val "response_count" , msg_responses_seen = jsToInt $ val "responses_seen" , msg_limited_to = toList $ jsToStr $ val "limited_to" } val n = getMapVal n m m = jsToMap obj maybeTime = maybe (msg_posted nullMsg) id toList = go [] where go ls [] = ls go ls (_:ss) = let (uid, rest) = span (/= '|') ss in go (read uid : ls) (tail rest) nullUser = User { user_id = 0 , user_nick_name = "" , user_display_name = "" , user_has_profile_image = False , user_avatar = 0 , user_location = "" , user_date_of_birth = ModifiedJulianDay 0 , user_full_name = "" , user_gender = Female , user_page_title = "" , user_karma = 0 , user_recruited = 0 , user_relationship = NotSaying } jsToUser :: JSValue -> User jsToUser (JSObject o) = user where user = nullUser { user_id = jsToInt $ val "id" , user_nick_name = jsToStr $ val "nick_name" , user_display_name = jsToStr $ val "display_name" , user_has_profile_image = toEnum $ jsToInt $ val "has_profile_image" , user_avatar = jsToInt $ val "avatar" , user_gender = jsToEnum $ val "gender" , user_location = jsToStr $ val "location" , user_date_of_birth = maybeDay $ jsToDateTime $ val "date_of_birth" , user_full_name = jsToStr $ val "full_name" , user_page_title = jsToStr $ val "page_title" , user_karma = jsToDouble $ val "karma" , user_recruited = jsToInt $ val "recruited" , user_relationship = read $ jsToStr $ val "relationship" } val n = getMapVal n m m = M.fromList $ fromJSObject o maybeDay = maybe (user_date_of_birth nullUser) id jsToUser v = error $ "jsToUser: " ++ show v nullKarmaStat = KarmaStat { karma_stat_karma_trend = [] , karma_stat_karma_fall_reason = "" , karma_stat_current_karma = 0 , karma_stat_karma_graph = "" } jsToKarmaStat (JSObject o) = stat where stat = nullKarmaStat { karma_stat_karma_trend = toStats $ val "karma_trend" , karma_stat_karma_fall_reason = jsToStr $ val "karma_fall_reason" , karma_stat_current_karma = jsToDouble $ val "current_karma" , karma_stat_karma_graph = jsToStr $ val "karma_graph" } toStats = map (strToStat . span (/= '-') . jsToStr) . jsToList strToStat (t, k) = (intToTime t, read $ tail k) intToTime = posixSecondsToUTCTime . fromInteger . read val n = getMapVal n m m = M.fromList $ fromJSObject o jsToKarmaStat v = error $ "jsToKarmaStat: " ++ show v nullProfile = Profile { profile_friends_count = 0 , profile_fans_count = 0 , profile_unread_count = 0 , profile_alerts_count = 0 , profile_are_friends = False , profile_is_fan = False , profile_is_following = False , profile_has_read_permission = False , profile_user_info = nullUser , profile_privacy = World , profile_plurks_users = IM.empty , profile_plurks = [] } jsToProfile own obj = if own then owner else public where owner = common { profile_unread_count = jsToInt $ val "unread_count" , profile_alerts_count = jsToInt $ val "alerts_count" , profile_plurks_users = IM.map jsToUser $ jsToIntMap $ val "plurks_users" } public = common { profile_are_friends = jsToBool $ val "are_friends" , profile_is_fan = jsToBool $ val "is_fan" , profile_is_following = jsToBool $ val "is_following" , profile_has_read_permission = jsToBool $ val "has_read_permission" } common = nullProfile { profile_friends_count = jsToInt $ val "friends_count" , profile_fans_count = jsToInt $ val "fans_count" , profile_user_info = jsToUser $ val "user_info" , profile_privacy = read $ jsToStr $ val "privacy" , profile_plurks = map jsToMessage $ jsToList $ val "plurks" } val n = getMapVal n m m = jsToMap obj
crabtw/hsplurk
Web/Plurk/Types.hs
Haskell
bsd-3-clause
15,627
{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} --------------------------------------------------------------- -- | -- Module : Data.Minecraft.Release17.Protocol -- Copyright : (c) 2016 Michael Carpenter -- License : BSD3 -- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com> -- Stability : experimental -- Portability : portable -- --------------------------------------------------------------- module Data.Minecraft.Release17.Protocol ( ServerBoundHandshakingPacket (..) , ClientBoundStatusPacket (..) , ServerBoundStatusPacket (..) , ClientBoundLoginPacket (..) , ServerBoundLoginPacket (..) , ClientBoundPlayPacket (..) , ServerBoundPlayPacket (..) ) where import Data.Attoparsec.ByteString import Data.ByteString as B import Data.ByteString.Builder as BB import Data.Int import Data.Fixed import Data.Minecraft.Types import Data.NBT import Data.Serialize hiding (putByteString,getByteString) import Data.Text as T import Data.UUID import Data.Word data ServerBoundHandshakingPacket = ServerBoundSetProtocol VarInt Text Word16 VarInt | ServerBoundLegacyServerListPing Word8 deriving (Show,Eq) data ClientBoundStatusPacket = ClientBoundServerInfo Text | ClientBoundPing Int64 deriving (Show,Eq) data ServerBoundStatusPacket = ServerBoundPingStart | ServerBoundPing Int64 deriving (Show,Eq) data ClientBoundLoginPacket = ClientBoundDisconnect Text | ClientBoundEncryptionBegin Text Buffer Buffer | ClientBoundSuccess Text Text deriving (Show,Eq) data ServerBoundLoginPacket = ServerBoundLoginStart Text | ServerBoundEncryptionBegin Buffer Buffer deriving (Show,Eq) data ClientBoundPlayPacket = ClientBoundKeepAlive Int32 | ClientBoundLogin Int32 Word8 Int8 Word8 Word8 Text | ClientBoundChat Text | ClientBoundUpdateTime Int64 Int64 | ClientBoundEntityEquipment Int32 Int16 Slot | ClientBoundSpawnPosition PositionIII | ClientBoundUpdateHealth Float Int16 Float | ClientBoundRespawn Int32 Word8 Word8 Text | ClientBoundPosition Double Double Double Float Float Bool | ClientBoundHeldItemSlot Int8 | ClientBoundBed Int32 PositionIBI | ClientBoundAnimation VarInt Word8 | ClientBoundNamedEntitySpawn VarInt Text Text Array Int32 Int32 Int32 Int8 Int8 Int16 EntityMetadata | ClientBoundCollect Int32 Int32 | ClientBoundSpawnEntity VarInt Int8 Int32 Int32 Int32 Int8 Int8 Container | ClientBoundSpawnEntityLiving VarInt Word8 Int32 Int32 Int32 Int8 Int8 Int8 Int16 Int16 Int16 EntityMetadata | ClientBoundSpawnEntityPainting VarInt Text PositionIII Word8 | ClientBoundSpawnEntityExperienceOrb VarInt Int32 Int32 Int32 Int16 | ClientBoundEntityVelocity Int32 Int16 Int16 Int16 | ClientBoundEntityDestroy Array | ClientBoundEntity Int32 | ClientBoundRelEntityMove Int32 Int8 Int8 Int8 | ClientBoundEntityLook Int32 Int8 Int8 | ClientBoundEntityMoveLook Int32 Int8 Int8 Int8 Int8 Int8 | ClientBoundEntityTeleport Int32 Int32 Int32 Int32 Int8 Int8 | ClientBoundEntityHeadRotation Int32 Int8 | ClientBoundEntityStatus Int32 Int8 | ClientBoundAttachEntity Int32 Int32 Bool | ClientBoundEntityMetadata Int32 EntityMetadata | ClientBoundEntityEffect Int32 Int8 Int8 Int16 | ClientBoundRemoveEntityEffect Int32 Int8 | ClientBoundExperience Float Int16 Int16 | ClientBoundUpdateAttributes Int32 Array | ClientBoundMapChunk Int32 Int32 Bool Word16 Word16 Buffer | ClientBoundMultiBlockChange Int32 Int32 (Count Int16) Int32 Array | ClientBoundBlockChange PositionIBI VarInt Word8 | ClientBoundBlockAction PositionISI Word8 Word8 VarInt | ClientBoundBlockBreakAnimation VarInt PositionIII Int8 | ClientBoundMapChunkBulk (Count Int16) (Count Int32) Bool Buffer Array | ClientBoundExplosion Float Float Float Float Array Float Float Float | ClientBoundWorldEvent Int32 PositionIBI Int32 Bool | ClientBoundNamedSoundEffect Text Int32 Int32 Int32 Float Word8 | ClientBoundWorldParticles Text Float Float Float Float Float Float Float Int32 | ClientBoundGameStateChange Word8 Float | ClientBoundSpawnEntityWeather VarInt Int8 Int32 Int32 Int32 | ClientBoundOpenWindow Word8 Word8 Text Word8 Bool (Maybe Int32) | ClientBoundCloseWindow Word8 | ClientBoundSetSlot Int8 Int16 Slot | ClientBoundWindowItems Word8 Array | ClientBoundCraftProgressBar Word8 Int16 Int16 | ClientBoundTransaction Word8 Int16 Bool | ClientBoundUpdateSign PositionISI Text Text Text Text | ClientBoundMap VarInt Buffer | ClientBoundTileEntityData PositionISI Word8 CompressedNBT | ClientBoundOpenSignEntity PositionIII | ClientBoundStatistics Array | ClientBoundPlayerInfo Text Bool Int16 | ClientBoundAbilities Int8 Float Float | ClientBoundTabComplete Array | ClientBoundScoreboardObjective Text Text Int8 | ClientBoundScoreboardScore Text Int8 Text (Maybe Int32) | ClientBoundScoreboardDisplayObjective Int8 Text | ClientBoundScoreboardTeam Text Int8 (Maybe Text) (Maybe Text) (Maybe Text) (Maybe Int8) (Maybe Text) (Maybe Int8) (Maybe Array) | ClientBoundCustomPayload Text Buffer | ClientBoundKickDisconnect Text deriving (Show,Eq) data ServerBoundPlayPacket = ServerBoundKeepAlive Int32 | ServerBoundChat Text | ServerBoundUseEntity Int32 Int8 (Maybe Float) (Maybe Float) (Maybe Float) | ServerBoundFlying Bool | ServerBoundPosition Double Double Double Double Bool | ServerBoundLook Float Float Bool | ServerBoundPositionLook Double Double Double Double Float Float Bool | ServerBoundBlockDig Int8 PositionIBI Int8 | ServerBoundBlockPlace PositionIBI Int8 Slot Int8 Int8 Int8 | ServerBoundHeldItemSlot Int16 | ServerBoundArmAnimation Int32 Int8 | ServerBoundEntityAction Int32 Int8 Int32 | ServerBoundSteerVehicle Float Float Bool Bool | ServerBoundCloseWindow Word8 | ServerBoundWindowClick Int8 Int16 Int8 Int16 Int8 Slot | ServerBoundTransaction Int8 Int16 Bool | ServerBoundSetCreativeSlot Int16 Slot | ServerBoundEnchantItem Int8 Int8 | ServerBoundUpdateSign PositionISI Text Text Text Text | ServerBoundAbilities Int8 Float Float | ServerBoundTabComplete Text | ServerBoundSettings Text Int8 Int8 Bool Word8 Bool | ServerBoundClientCommand Int8 | ServerBoundCustomPayload Text Buffer deriving (Show,Eq) instance Serialize ServerBoundHandshakingPacket where put (ServerBoundSetProtocol protocolVersion serverHost serverPort nextState) = do putWord8 0x00 putVarInt protocolVersion putText serverHost putWord16 serverPort putVarInt nextState put (ServerBoundLegacyServerListPing payload) = do putWord8 0xfe putWord8 payload get = do packetId <- getWord8 case packetId of 0x00 -> do protocolVersion <- getVarInt serverHost <- getText serverPort <- getWord16 nextState <- getVarInt return $ ServerBoundSetProtocol protocolVersion serverHost serverPort nextState 0xfe -> do payload <- getWord8 return $ ServerBoundLegacyServerListPing payload instance Serialize ClientBoundStatusPacket where put (ClientBoundServerInfo response) = do putWord8 0x00 putText response put (ClientBoundPing time) = do putWord8 0x01 putInt64 time get = do packetId <- getWord8 case packetId of 0x00 -> do response <- getText return $ ClientBoundServerInfo response 0x01 -> do time <- getInt64 return $ ClientBoundPing time instance Serialize ServerBoundStatusPacket where put (ServerBoundPingStart ) = do putWord8 0x00 put (ServerBoundPing time) = do putWord8 0x01 putInt64 time get = do packetId <- getWord8 case packetId of 0x00 -> do return $ ServerBoundPingStart 0x01 -> do time <- getInt64 return $ ServerBoundPing time instance Serialize ClientBoundLoginPacket where put (ClientBoundDisconnect reason) = do putWord8 0x00 putText reason put (ClientBoundEncryptionBegin serverId publicKey verifyToken) = do putWord8 0x01 putText serverId putBuffer publicKey putBuffer verifyToken put (ClientBoundSuccess uuid username) = do putWord8 0x02 putText uuid putText username get = do packetId <- getWord8 case packetId of 0x00 -> do reason <- getText return $ ClientBoundDisconnect reason 0x01 -> do serverId <- getText publicKey <- getBuffer verifyToken <- getBuffer return $ ClientBoundEncryptionBegin serverId publicKey verifyToken 0x02 -> do uuid <- getText username <- getText return $ ClientBoundSuccess uuid username instance Serialize ServerBoundLoginPacket where put (ServerBoundLoginStart username) = do putWord8 0x00 putText username put (ServerBoundEncryptionBegin sharedSecret verifyToken) = do putWord8 0x01 putBuffer sharedSecret putBuffer verifyToken get = do packetId <- getWord8 case packetId of 0x00 -> do username <- getText return $ ServerBoundLoginStart username 0x01 -> do sharedSecret <- getBuffer verifyToken <- getBuffer return $ ServerBoundEncryptionBegin sharedSecret verifyToken instance Serialize ClientBoundPlayPacket where put (ClientBoundKeepAlive keepAliveId) = do putWord8 0x00 putInt32 keepAliveId put (ClientBoundLogin entityId gameMode dimension difficulty maxPlayers levelType) = do putWord8 0x01 putInt32 entityId putWord8 gameMode putInt8 dimension putWord8 difficulty putWord8 maxPlayers putText levelType put (ClientBoundChat message) = do putWord8 0x02 putText message put (ClientBoundUpdateTime age time) = do putWord8 0x03 putInt64 age putInt64 time put (ClientBoundEntityEquipment entityId slot item) = do putWord8 0x04 putInt32 entityId putInt16 slot putSlot item put (ClientBoundSpawnPosition location) = do putWord8 0x05 putPositionIII location put (ClientBoundUpdateHealth health food foodSaturation) = do putWord8 0x06 putFloat health putInt16 food putFloat foodSaturation put (ClientBoundRespawn dimension difficulty gamemode levelType) = do putWord8 0x07 putInt32 dimension putWord8 difficulty putWord8 gamemode putText levelType put (ClientBoundPosition x y z yaw pitch onGround) = do putWord8 0x08 putDouble x putDouble y putDouble z putFloat yaw putFloat pitch putBool onGround put (ClientBoundHeldItemSlot slot) = do putWord8 0x09 putInt8 slot put (ClientBoundBed entityId location) = do putWord8 0x0a putInt32 entityId putPositionIBI location put (ClientBoundAnimation entityId animation) = do putWord8 0x0b putVarInt entityId putWord8 animation put (ClientBoundNamedEntitySpawn entityId playerUUID playerName pData x y z yaw pitch currentItem metadata) = do putWord8 0x0c putVarInt entityId putText playerUUID putText playerName putArray pData putInt32 x putInt32 y putInt32 z putInt8 yaw putInt8 pitch putInt16 currentItem putEntityMetadata metadata put (ClientBoundCollect collectedEntityId collectorEntityId) = do putWord8 0x0d putInt32 collectedEntityId putInt32 collectorEntityId put (ClientBoundSpawnEntity entityId pType x y z pitch yaw objectData) = do putWord8 0x0e putVarInt entityId putInt8 pType putInt32 x putInt32 y putInt32 z putInt8 pitch putInt8 yaw putContainer objectData put (ClientBoundSpawnEntityLiving entityId pType x y z yaw pitch headPitch velocityX velocityY velocityZ metadata) = do putWord8 0x0f putVarInt entityId putWord8 pType putInt32 x putInt32 y putInt32 z putInt8 yaw putInt8 pitch putInt8 headPitch putInt16 velocityX putInt16 velocityY putInt16 velocityZ putEntityMetadata metadata put (ClientBoundSpawnEntityPainting entityId title location direction) = do putWord8 0x10 putVarInt entityId putText title putPositionIII location putWord8 direction put (ClientBoundSpawnEntityExperienceOrb entityId x y z count) = do putWord8 0x11 putVarInt entityId putInt32 x putInt32 y putInt32 z putInt16 count put (ClientBoundEntityVelocity entityId velocityX velocityY velocityZ) = do putWord8 0x12 putInt32 entityId putInt16 velocityX putInt16 velocityY putInt16 velocityZ put (ClientBoundEntityDestroy entityIds) = do putWord8 0x13 putArray entityIds put (ClientBoundEntity entityId) = do putWord8 0x14 putInt32 entityId put (ClientBoundRelEntityMove entityId dX dY dZ) = do putWord8 0x15 putInt32 entityId putInt8 dX putInt8 dY putInt8 dZ put (ClientBoundEntityLook entityId yaw pitch) = do putWord8 0x16 putInt32 entityId putInt8 yaw putInt8 pitch put (ClientBoundEntityMoveLook entityId dX dY dZ yaw pitch) = do putWord8 0x17 putInt32 entityId putInt8 dX putInt8 dY putInt8 dZ putInt8 yaw putInt8 pitch put (ClientBoundEntityTeleport entityId x y z yaw pitch) = do putWord8 0x18 putInt32 entityId putInt32 x putInt32 y putInt32 z putInt8 yaw putInt8 pitch put (ClientBoundEntityHeadRotation entityId headYaw) = do putWord8 0x19 putInt32 entityId putInt8 headYaw put (ClientBoundEntityStatus entityId entityStatus) = do putWord8 0x1a putInt32 entityId putInt8 entityStatus put (ClientBoundAttachEntity entityId vehicleId leash) = do putWord8 0x1b putInt32 entityId putInt32 vehicleId putBool leash put (ClientBoundEntityMetadata entityId metadata) = do putWord8 0x1c putInt32 entityId putEntityMetadata metadata put (ClientBoundEntityEffect entityId effectId amplifier duration) = do putWord8 0x1d putInt32 entityId putInt8 effectId putInt8 amplifier putInt16 duration put (ClientBoundRemoveEntityEffect entityId effectId) = do putWord8 0x1e putInt32 entityId putInt8 effectId put (ClientBoundExperience experienceBar level totalExperience) = do putWord8 0x1f putFloat experienceBar putInt16 level putInt16 totalExperience put (ClientBoundUpdateAttributes entityId properties) = do putWord8 0x20 putInt32 entityId putArray properties put (ClientBoundMapChunk x z groundUp bitMap addBitMap compressedChunkData) = do putWord8 0x21 putInt32 x putInt32 z putBool groundUp putWord16 bitMap putWord16 addBitMap putBuffer compressedChunkData put (ClientBoundMultiBlockChange chunkX chunkZ recordCount dataLength records) = do putWord8 0x22 putInt32 chunkX putInt32 chunkZ putCount recordCount putInt32 dataLength putArray records put (ClientBoundBlockChange location pType metadata) = do putWord8 0x23 putPositionIBI location putVarInt pType putWord8 metadata put (ClientBoundBlockAction location byte1 byte2 blockId) = do putWord8 0x24 putPositionISI location putWord8 byte1 putWord8 byte2 putVarInt blockId put (ClientBoundBlockBreakAnimation entityId location destroyStage) = do putWord8 0x25 putVarInt entityId putPositionIII location putInt8 destroyStage put (ClientBoundMapChunkBulk chunkColumnCount dataLength skyLightSent compressedChunkData meta) = do putWord8 0x26 putCount chunkColumnCount putCount dataLength putBool skyLightSent putBuffer compressedChunkData putArray meta put (ClientBoundExplosion x y z radius affectedBlockOffsets playerMotionX playerMotionY playerMotionZ) = do putWord8 0x27 putFloat x putFloat y putFloat z putFloat radius putArray affectedBlockOffsets putFloat playerMotionX putFloat playerMotionY putFloat playerMotionZ put (ClientBoundWorldEvent effectId location pData global) = do putWord8 0x28 putInt32 effectId putPositionIBI location putInt32 pData putBool global put (ClientBoundNamedSoundEffect soundName x y z volume pitch) = do putWord8 0x29 putText soundName putInt32 x putInt32 y putInt32 z putFloat volume putWord8 pitch put (ClientBoundWorldParticles particleName x y z offsetX offsetY offsetZ particleData particles) = do putWord8 0x2a putText particleName putFloat x putFloat y putFloat z putFloat offsetX putFloat offsetY putFloat offsetZ putFloat particleData putInt32 particles put (ClientBoundGameStateChange reason gameMode) = do putWord8 0x2b putWord8 reason putFloat gameMode put (ClientBoundSpawnEntityWeather entityId pType x y z) = do putWord8 0x2c putVarInt entityId putInt8 pType putInt32 x putInt32 y putInt32 z put (ClientBoundOpenWindow windowId inventoryType windowTitle slotCount useProvidedTitle entityId) = do putWord8 0x2d putWord8 windowId putWord8 inventoryType putText windowTitle putWord8 slotCount putBool useProvidedTitle case entityId of Just entityId' -> putInt32 entityId' Nothing -> return () put (ClientBoundCloseWindow windowId) = do putWord8 0x2e putWord8 windowId put (ClientBoundSetSlot windowId slot item) = do putWord8 0x2f putInt8 windowId putInt16 slot putSlot item put (ClientBoundWindowItems windowId items) = do putWord8 0x30 putWord8 windowId putArray items put (ClientBoundCraftProgressBar windowId property value) = do putWord8 0x31 putWord8 windowId putInt16 property putInt16 value put (ClientBoundTransaction windowId action accepted) = do putWord8 0x32 putWord8 windowId putInt16 action putBool accepted put (ClientBoundUpdateSign location text1 text2 text3 text4) = do putWord8 0x33 putPositionISI location putText text1 putText text2 putText text3 putText text4 put (ClientBoundMap itemDamage pData) = do putWord8 0x34 putVarInt itemDamage putBuffer pData put (ClientBoundTileEntityData location action nbtData) = do putWord8 0x35 putPositionISI location putWord8 action putCompressedNBT nbtData put (ClientBoundOpenSignEntity location) = do putWord8 0x36 putPositionIII location put (ClientBoundStatistics entries) = do putWord8 0x37 putArray entries put (ClientBoundPlayerInfo playerName online ping) = do putWord8 0x38 putText playerName putBool online putInt16 ping put (ClientBoundAbilities flags flyingSpeed walkingSpeed) = do putWord8 0x39 putInt8 flags putFloat flyingSpeed putFloat walkingSpeed put (ClientBoundTabComplete matches) = do putWord8 0x3a putArray matches put (ClientBoundScoreboardObjective name displayText action) = do putWord8 0x3b putText name putText displayText putInt8 action put (ClientBoundScoreboardScore itemName action scoreName value) = do putWord8 0x3c putText itemName putInt8 action putText scoreName case value of Just value' -> putInt32 value' Nothing -> return () put (ClientBoundScoreboardDisplayObjective position name) = do putWord8 0x3d putInt8 position putText name put (ClientBoundScoreboardTeam team mode name prefix suffix friendlyFire nameTagVisibility color players) = do putWord8 0x3e putText team putInt8 mode case name of Just name' -> putText name' Nothing -> return () case prefix of Just prefix' -> putText prefix' Nothing -> return () case suffix of Just suffix' -> putText suffix' Nothing -> return () case friendlyFire of Just friendlyFire' -> putInt8 friendlyFire' Nothing -> return () case nameTagVisibility of Just nameTagVisibility' -> putText nameTagVisibility' Nothing -> return () case color of Just color' -> putInt8 color' Nothing -> return () case players of Just players' -> putArray players' Nothing -> return () put (ClientBoundCustomPayload channel pData) = do putWord8 0x3f putText channel putBuffer pData put (ClientBoundKickDisconnect reason) = do putWord8 0x40 putText reason get = do packetId <- getWord8 case packetId of 0x00 -> do keepAliveId <- getInt32 return $ ClientBoundKeepAlive keepAliveId 0x01 -> do entityId <- getInt32 gameMode <- getWord8 dimension <- getInt8 difficulty <- getWord8 maxPlayers <- getWord8 levelType <- getText return $ ClientBoundLogin entityId gameMode dimension difficulty maxPlayers levelType 0x02 -> do message <- getText return $ ClientBoundChat message 0x03 -> do age <- getInt64 time <- getInt64 return $ ClientBoundUpdateTime age time 0x04 -> do entityId <- getInt32 slot <- getInt16 item <- getSlot return $ ClientBoundEntityEquipment entityId slot item 0x05 -> do location <- getPositionIII return $ ClientBoundSpawnPosition location 0x06 -> do health <- getFloat food <- getInt16 foodSaturation <- getFloat return $ ClientBoundUpdateHealth health food foodSaturation 0x07 -> do dimension <- getInt32 difficulty <- getWord8 gamemode <- getWord8 levelType <- getText return $ ClientBoundRespawn dimension difficulty gamemode levelType 0x08 -> do x <- getDouble y <- getDouble z <- getDouble yaw <- getFloat pitch <- getFloat onGround <- getBool return $ ClientBoundPosition x y z yaw pitch onGround 0x09 -> do slot <- getInt8 return $ ClientBoundHeldItemSlot slot 0x0a -> do entityId <- getInt32 location <- getPositionIBI return $ ClientBoundBed entityId location 0x0b -> do entityId <- getVarInt animation <- getWord8 return $ ClientBoundAnimation entityId animation 0x0c -> do entityId <- getVarInt playerUUID <- getText playerName <- getText pData <- getArray x <- getInt32 y <- getInt32 z <- getInt32 yaw <- getInt8 pitch <- getInt8 currentItem <- getInt16 metadata <- getEntityMetadata return $ ClientBoundNamedEntitySpawn entityId playerUUID playerName pData x y z yaw pitch currentItem metadata 0x0d -> do collectedEntityId <- getInt32 collectorEntityId <- getInt32 return $ ClientBoundCollect collectedEntityId collectorEntityId 0x0e -> do entityId <- getVarInt pType <- getInt8 x <- getInt32 y <- getInt32 z <- getInt32 pitch <- getInt8 yaw <- getInt8 objectData <- getContainer return $ ClientBoundSpawnEntity entityId pType x y z pitch yaw objectData 0x0f -> do entityId <- getVarInt pType <- getWord8 x <- getInt32 y <- getInt32 z <- getInt32 yaw <- getInt8 pitch <- getInt8 headPitch <- getInt8 velocityX <- getInt16 velocityY <- getInt16 velocityZ <- getInt16 metadata <- getEntityMetadata return $ ClientBoundSpawnEntityLiving entityId pType x y z yaw pitch headPitch velocityX velocityY velocityZ metadata 0x10 -> do entityId <- getVarInt title <- getText location <- getPositionIII direction <- getWord8 return $ ClientBoundSpawnEntityPainting entityId title location direction 0x11 -> do entityId <- getVarInt x <- getInt32 y <- getInt32 z <- getInt32 count <- getInt16 return $ ClientBoundSpawnEntityExperienceOrb entityId x y z count 0x12 -> do entityId <- getInt32 velocityX <- getInt16 velocityY <- getInt16 velocityZ <- getInt16 return $ ClientBoundEntityVelocity entityId velocityX velocityY velocityZ 0x13 -> do entityIds <- getArray return $ ClientBoundEntityDestroy entityIds 0x14 -> do entityId <- getInt32 return $ ClientBoundEntity entityId 0x15 -> do entityId <- getInt32 dX <- getInt8 dY <- getInt8 dZ <- getInt8 return $ ClientBoundRelEntityMove entityId dX dY dZ 0x16 -> do entityId <- getInt32 yaw <- getInt8 pitch <- getInt8 return $ ClientBoundEntityLook entityId yaw pitch 0x17 -> do entityId <- getInt32 dX <- getInt8 dY <- getInt8 dZ <- getInt8 yaw <- getInt8 pitch <- getInt8 return $ ClientBoundEntityMoveLook entityId dX dY dZ yaw pitch 0x18 -> do entityId <- getInt32 x <- getInt32 y <- getInt32 z <- getInt32 yaw <- getInt8 pitch <- getInt8 return $ ClientBoundEntityTeleport entityId x y z yaw pitch 0x19 -> do entityId <- getInt32 headYaw <- getInt8 return $ ClientBoundEntityHeadRotation entityId headYaw 0x1a -> do entityId <- getInt32 entityStatus <- getInt8 return $ ClientBoundEntityStatus entityId entityStatus 0x1b -> do entityId <- getInt32 vehicleId <- getInt32 leash <- getBool return $ ClientBoundAttachEntity entityId vehicleId leash 0x1c -> do entityId <- getInt32 metadata <- getEntityMetadata return $ ClientBoundEntityMetadata entityId metadata 0x1d -> do entityId <- getInt32 effectId <- getInt8 amplifier <- getInt8 duration <- getInt16 return $ ClientBoundEntityEffect entityId effectId amplifier duration 0x1e -> do entityId <- getInt32 effectId <- getInt8 return $ ClientBoundRemoveEntityEffect entityId effectId 0x1f -> do experienceBar <- getFloat level <- getInt16 totalExperience <- getInt16 return $ ClientBoundExperience experienceBar level totalExperience 0x20 -> do entityId <- getInt32 properties <- getArray return $ ClientBoundUpdateAttributes entityId properties 0x21 -> do x <- getInt32 z <- getInt32 groundUp <- getBool bitMap <- getWord16 addBitMap <- getWord16 compressedChunkData <- getBuffer return $ ClientBoundMapChunk x z groundUp bitMap addBitMap compressedChunkData 0x22 -> do chunkX <- getInt32 chunkZ <- getInt32 recordCount <- get(Count Int16) dataLength <- getInt32 records <- getArray return $ ClientBoundMultiBlockChange chunkX chunkZ recordCount dataLength records 0x23 -> do location <- getPositionIBI pType <- getVarInt metadata <- getWord8 return $ ClientBoundBlockChange location pType metadata 0x24 -> do location <- getPositionISI byte1 <- getWord8 byte2 <- getWord8 blockId <- getVarInt return $ ClientBoundBlockAction location byte1 byte2 blockId 0x25 -> do entityId <- getVarInt location <- getPositionIII destroyStage <- getInt8 return $ ClientBoundBlockBreakAnimation entityId location destroyStage 0x26 -> do chunkColumnCount <- get(Count Int16) dataLength <- get(Count Int32) skyLightSent <- getBool compressedChunkData <- getBuffer meta <- getArray return $ ClientBoundMapChunkBulk chunkColumnCount dataLength skyLightSent compressedChunkData meta 0x27 -> do x <- getFloat y <- getFloat z <- getFloat radius <- getFloat affectedBlockOffsets <- getArray playerMotionX <- getFloat playerMotionY <- getFloat playerMotionZ <- getFloat return $ ClientBoundExplosion x y z radius affectedBlockOffsets playerMotionX playerMotionY playerMotionZ 0x28 -> do effectId <- getInt32 location <- getPositionIBI pData <- getInt32 global <- getBool return $ ClientBoundWorldEvent effectId location pData global 0x29 -> do soundName <- getText x <- getInt32 y <- getInt32 z <- getInt32 volume <- getFloat pitch <- getWord8 return $ ClientBoundNamedSoundEffect soundName x y z volume pitch 0x2a -> do particleName <- getText x <- getFloat y <- getFloat z <- getFloat offsetX <- getFloat offsetY <- getFloat offsetZ <- getFloat particleData <- getFloat particles <- getInt32 return $ ClientBoundWorldParticles particleName x y z offsetX offsetY offsetZ particleData particles 0x2b -> do reason <- getWord8 gameMode <- getFloat return $ ClientBoundGameStateChange reason gameMode 0x2c -> do entityId <- getVarInt pType <- getInt8 x <- getInt32 y <- getInt32 z <- getInt32 return $ ClientBoundSpawnEntityWeather entityId pType x y z 0x2d -> do windowId <- getWord8 inventoryType <- getWord8 windowTitle <- getText slotCount <- getWord8 useProvidedTitle <- getBool let entityId = case inventoryType of EntityHorse -> _ -> return $ ClientBoundOpenWindow windowId inventoryType windowTitle slotCount useProvidedTitle entityId 0x2e -> do windowId <- getWord8 return $ ClientBoundCloseWindow windowId 0x2f -> do windowId <- getInt8 slot <- getInt16 item <- getSlot return $ ClientBoundSetSlot windowId slot item 0x30 -> do windowId <- getWord8 items <- getArray return $ ClientBoundWindowItems windowId items 0x31 -> do windowId <- getWord8 property <- getInt16 value <- getInt16 return $ ClientBoundCraftProgressBar windowId property value 0x32 -> do windowId <- getWord8 action <- getInt16 accepted <- getBool return $ ClientBoundTransaction windowId action accepted 0x33 -> do location <- getPositionISI text1 <- getText text2 <- getText text3 <- getText text4 <- getText return $ ClientBoundUpdateSign location text1 text2 text3 text4 0x34 -> do itemDamage <- getVarInt pData <- getBuffer return $ ClientBoundMap itemDamage pData 0x35 -> do location <- getPositionISI action <- getWord8 nbtData <- getCompressedNBT return $ ClientBoundTileEntityData location action nbtData 0x36 -> do location <- getPositionIII return $ ClientBoundOpenSignEntity location 0x37 -> do entries <- getArray return $ ClientBoundStatistics entries 0x38 -> do playerName <- getText online <- getBool ping <- getInt16 return $ ClientBoundPlayerInfo playerName online ping 0x39 -> do flags <- getInt8 flyingSpeed <- getFloat walkingSpeed <- getFloat return $ ClientBoundAbilities flags flyingSpeed walkingSpeed 0x3a -> do matches <- getArray return $ ClientBoundTabComplete matches 0x3b -> do name <- getText displayText <- getText action <- getInt8 return $ ClientBoundScoreboardObjective name displayText action 0x3c -> do itemName <- getText action <- getInt8 scoreName <- getText let value = case action of 1 -> _ -> return $ ClientBoundScoreboardScore itemName action scoreName value 0x3d -> do position <- getInt8 name <- getText return $ ClientBoundScoreboardDisplayObjective position name 0x3e -> do team <- getText mode <- getInt8 let name = case mode of 0 -> 2 -> _ -> let prefix = case mode of 0 -> 2 -> _ -> let suffix = case mode of 0 -> 2 -> _ -> let friendlyFire = case mode of 0 -> 2 -> _ -> let nameTagVisibility = case mode of 0 -> 2 -> _ -> let color = case mode of 0 -> 2 -> _ -> let players = case mode of 0 -> 4 -> 3 -> _ -> return $ ClientBoundScoreboardTeam team mode name prefix suffix friendlyFire nameTagVisibility color players 0x3f -> do channel <- getText pData <- getBuffer return $ ClientBoundCustomPayload channel pData 0x40 -> do reason <- getText return $ ClientBoundKickDisconnect reason instance Serialize ServerBoundPlayPacket where put (ServerBoundKeepAlive keepAliveId) = do putWord8 0x00 putInt32 keepAliveId put (ServerBoundChat message) = do putWord8 0x01 putText message put (ServerBoundUseEntity target mouse x y z) = do putWord8 0x02 putInt32 target putInt8 mouse case x of Just x' -> putFloat x' Nothing -> return () case y of Just y' -> putFloat y' Nothing -> return () case z of Just z' -> putFloat z' Nothing -> return () put (ServerBoundFlying onGround) = do putWord8 0x03 putBool onGround put (ServerBoundPosition x stance y z onGround) = do putWord8 0x04 putDouble x putDouble stance putDouble y putDouble z putBool onGround put (ServerBoundLook yaw pitch onGround) = do putWord8 0x05 putFloat yaw putFloat pitch putBool onGround put (ServerBoundPositionLook x stance y z yaw pitch onGround) = do putWord8 0x06 putDouble x putDouble stance putDouble y putDouble z putFloat yaw putFloat pitch putBool onGround put (ServerBoundBlockDig status location face) = do putWord8 0x07 putInt8 status putPositionIBI location putInt8 face put (ServerBoundBlockPlace location direction heldItem cursorX cursorY cursorZ) = do putWord8 0x08 putPositionIBI location putInt8 direction putSlot heldItem putInt8 cursorX putInt8 cursorY putInt8 cursorZ put (ServerBoundHeldItemSlot slotId) = do putWord8 0x09 putInt16 slotId put (ServerBoundArmAnimation entityId animation) = do putWord8 0x0a putInt32 entityId putInt8 animation put (ServerBoundEntityAction entityId actionId jumpBoost) = do putWord8 0x0b putInt32 entityId putInt8 actionId putInt32 jumpBoost put (ServerBoundSteerVehicle sideways forward jump unmount) = do putWord8 0x0c putFloat sideways putFloat forward putBool jump putBool unmount put (ServerBoundCloseWindow windowId) = do putWord8 0x0d putWord8 windowId put (ServerBoundWindowClick windowId slot mouseButton action mode item) = do putWord8 0x0e putInt8 windowId putInt16 slot putInt8 mouseButton putInt16 action putInt8 mode putSlot item put (ServerBoundTransaction windowId action accepted) = do putWord8 0x0f putInt8 windowId putInt16 action putBool accepted put (ServerBoundSetCreativeSlot slot item) = do putWord8 0x10 putInt16 slot putSlot item put (ServerBoundEnchantItem windowId enchantment) = do putWord8 0x11 putInt8 windowId putInt8 enchantment put (ServerBoundUpdateSign location text1 text2 text3 text4) = do putWord8 0x12 putPositionISI location putText text1 putText text2 putText text3 putText text4 put (ServerBoundAbilities flags flyingSpeed walkingSpeed) = do putWord8 0x13 putInt8 flags putFloat flyingSpeed putFloat walkingSpeed put (ServerBoundTabComplete text) = do putWord8 0x14 putText text put (ServerBoundSettings locale viewDistance chatFlags chatColors difficulty showCape) = do putWord8 0x15 putText locale putInt8 viewDistance putInt8 chatFlags putBool chatColors putWord8 difficulty putBool showCape put (ServerBoundClientCommand payload) = do putWord8 0x16 putInt8 payload put (ServerBoundCustomPayload channel pData) = do putWord8 0x17 putText channel putBuffer pData get = do packetId <- getWord8 case packetId of 0x00 -> do keepAliveId <- getInt32 return $ ServerBoundKeepAlive keepAliveId 0x01 -> do message <- getText return $ ServerBoundChat message 0x02 -> do target <- getInt32 mouse <- getInt8 let x = case mouse of 2 -> _ -> let y = case mouse of 2 -> _ -> let z = case mouse of 2 -> _ -> return $ ServerBoundUseEntity target mouse x y z 0x03 -> do onGround <- getBool return $ ServerBoundFlying onGround 0x04 -> do x <- getDouble stance <- getDouble y <- getDouble z <- getDouble onGround <- getBool return $ ServerBoundPosition x stance y z onGround 0x05 -> do yaw <- getFloat pitch <- getFloat onGround <- getBool return $ ServerBoundLook yaw pitch onGround 0x06 -> do x <- getDouble stance <- getDouble y <- getDouble z <- getDouble yaw <- getFloat pitch <- getFloat onGround <- getBool return $ ServerBoundPositionLook x stance y z yaw pitch onGround 0x07 -> do status <- getInt8 location <- getPositionIBI face <- getInt8 return $ ServerBoundBlockDig status location face 0x08 -> do location <- getPositionIBI direction <- getInt8 heldItem <- getSlot cursorX <- getInt8 cursorY <- getInt8 cursorZ <- getInt8 return $ ServerBoundBlockPlace location direction heldItem cursorX cursorY cursorZ 0x09 -> do slotId <- getInt16 return $ ServerBoundHeldItemSlot slotId 0x0a -> do entityId <- getInt32 animation <- getInt8 return $ ServerBoundArmAnimation entityId animation 0x0b -> do entityId <- getInt32 actionId <- getInt8 jumpBoost <- getInt32 return $ ServerBoundEntityAction entityId actionId jumpBoost 0x0c -> do sideways <- getFloat forward <- getFloat jump <- getBool unmount <- getBool return $ ServerBoundSteerVehicle sideways forward jump unmount 0x0d -> do windowId <- getWord8 return $ ServerBoundCloseWindow windowId 0x0e -> do windowId <- getInt8 slot <- getInt16 mouseButton <- getInt8 action <- getInt16 mode <- getInt8 item <- getSlot return $ ServerBoundWindowClick windowId slot mouseButton action mode item 0x0f -> do windowId <- getInt8 action <- getInt16 accepted <- getBool return $ ServerBoundTransaction windowId action accepted 0x10 -> do slot <- getInt16 item <- getSlot return $ ServerBoundSetCreativeSlot slot item 0x11 -> do windowId <- getInt8 enchantment <- getInt8 return $ ServerBoundEnchantItem windowId enchantment 0x12 -> do location <- getPositionISI text1 <- getText text2 <- getText text3 <- getText text4 <- getText return $ ServerBoundUpdateSign location text1 text2 text3 text4 0x13 -> do flags <- getInt8 flyingSpeed <- getFloat walkingSpeed <- getFloat return $ ServerBoundAbilities flags flyingSpeed walkingSpeed 0x14 -> do text <- getText return $ ServerBoundTabComplete text 0x15 -> do locale <- getText viewDistance <- getInt8 chatFlags <- getInt8 chatColors <- getBool difficulty <- getWord8 showCape <- getBool return $ ServerBoundSettings locale viewDistance chatFlags chatColors difficulty showCape 0x16 -> do payload <- getInt8 return $ ServerBoundClientCommand payload 0x17 -> do channel <- getText pData <- getBuffer return $ ServerBoundCustomPayload channel pData
oldmanmike/hs-minecraft-protocol
src/Data/Minecraft/Release17/Protocol.hs
Haskell
bsd-3-clause
41,010
module Queue ( Queue , queue , mqueue, push, pop, popWhile, runFold, size, ) where import Data.Foldable -- A double ended queue which keeps track of a front and a back, as well as -- an accumulation function. Inspired by https://people.cs.uct.ac.za/~ksmith/articles/sliding_window_minimum.html#sliding-window-minimum-algorithm -- -- It uses Okasaki's two-stack implementation. The core idea is two maintain -- a front and a back stack. At any point, each stack contains all its -- elements as well as the partial accumulations up to that point. For -- instance, if the accumulation function is (+), the stack might look like -- [3,2,1] -> [(3,6), (2,3), (1,1)] -- Holding all the partial sums alongside the elements of the stack. -- That makes a perfectly good stack with partial sums, but how do we get a -- FIFO queue with rolling sums? -- The trick is two maintain two stacks, one is the front with elements -- 'on the way in', and the other is the back with elements 'on the way out'. -- That way, we have partial sums for both stacks and to calculate -- the partial (or 'rolling') sum for the whole queue we just add the -- top partial sums together. -- Consider the list [1,2,3,4,2,1] (which is currently split in the middle) -- [3,2,1] [1,2,4] -> [(3,6), (2,3), (1,1)] [(1,7), (2,6), (4,4)] -- To grab the sum for the whole queue we just add 6 and 7 resulting in 13. -- This property that the front and back partial sums sum to the final result -- is invariant with pushes and pops. To convince yourself, try a pop: -- [3,2,1] [2,4] -> [(3,6), (2,3), (1,1)] [(2,6), (4,4)] -- Adding the partial sums gives 12. -- -- The last key to the implementation is that pushes only affect the front -- queue, and pops only affect the back queue. Except, if the back queue is -- empty, we pop all the elements of the front queue and push them onto the -- back queue, recalculating all the partial sums in between. -- [(3,6), (2,3), (1,1)] [] -- -> [] [(1,6), (2,5), (3,3)] -- This keeps the invariant that both stacks have their partial sums -- calculated correctly! -- -- This scheme happens to work for any commutative accumulation function! -- So I have extended it to accept a user-provided function. -- IMPORTANT: The accumulation function MUST be commutative or the whole -- thing fails, since the algorithm rests on being able to combine the two -- partial sums 'somewhere in the middle'. I am not aware of this algorithm -- extending to arbitrary associative functions. data Queue a = Queue { acc :: (a -> a -> a) , sz :: Int , front :: [(a, a)] , back :: [(a, a)] } push :: a -> Queue a -> Queue a push a (Queue f sz [] back) = Queue f (succ sz) [(a, a)] back push a (Queue f sz ((x, y) : xs) back) = Queue f (succ sz) front back where front = (a, f a y) : (x, y) : xs queue :: (a -> a -> a) -> Queue a queue f = Queue f 0 [] [] -- queue implementation for a monoid mqueue :: Monoid m => Queue m mqueue = queue mappend size :: Queue a -> Int size = sz pop :: Queue a -> Maybe (a, Queue a) pop (Queue f sz [] []) = Nothing pop (Queue f sz xs (y:ys)) = Just (fst y, Queue f (pred sz) xs ys) -- When the back is empty, fill it with elements from the front. -- This does two things, it reverses the elements (so the queue is FIFO) -- and it recalculates the fold over the back end of the queue. -- While this is an O(n) operation it is amortized O(1) since it only -- happens once per element. pop (Queue f sz xs []) = pop (Queue f sz [] (foldl' go [] xs)) where go [] (a, _) = [(a, a)] go ((y, b):ys) (a, _) = (a, f a b) : (y, b) : ys popWhile :: (a -> Bool) -> Queue a -> Queue a popWhile pred d@(Queue f sz _ _) = case pop d of Nothing -> d Just (a, d') -> if pred a then popWhile pred d' else d -- Simulate running a foldl1 over the queue. Note that while it is -- semantically the same as running a foldl1, performance-wise it is O(1) -- since the partial updates have been being calculated all along. runFold :: Queue a -> Maybe a runFold (Queue _ _ [] []) = Nothing runFold (Queue _ _ ((x,b):xs) []) = Just b runFold (Queue _ _ [] ((y,c):ys)) = Just c runFold (Queue f _ ((x,b):xs) ((y,c):ys)) = Just (f b c)
charles-cooper/hroll
src/Queue.hs
Haskell
bsd-3-clause
4,255
module GPipeFPSMaterial where import Graphics.GPipe import qualified Data.ByteString.Char8 as SB identityLight :: Float identityLight = 1 data Entity = Entity { eAmbientLight :: Vec4 (Vertex Float) , eDirectedLight :: Vec4 (Vertex Float) , eLightDir :: Vec3 (Vertex Float) , eShaderRGBA :: Vec4 (Vertex Float) } data WaveType = WT_Sin | WT_Triangle | WT_Square | WT_Sawtooth | WT_InverseSawtooth | WT_Noise data Wave = Wave WaveType Float Float Float Float data Deform = D_AutoSprite | D_AutoSprite2 | D_Bulge Float Float Float | D_Move (Vec3 Float) Wave | D_Normal Float Float | D_ProjectionShadow | D_Text0 | D_Text1 | D_Text2 | D_Text3 | D_Text4 | D_Text5 | D_Text6 | D_Text7 | D_Wave Float Wave data CommonAttrs = CommonAttrs { caSkyParms :: () -- TODO , caFogParms :: () -- TODO , caPortal :: Bool , caSort :: Int -- default: 3 or 6 depends on blend function , caEntityMergable :: Bool , caFogOnly :: Bool , caCull :: () -- TODO, default = front , caDeformVertexes :: [Deform] , caNoMipMaps :: Bool , caPolygonOffset :: Maybe Float , caStages :: [StageAttrs] } defaultCommonAttrs :: CommonAttrs defaultCommonAttrs = CommonAttrs { caSkyParms = () , caFogParms = () , caPortal = False , caSort = 3 , caEntityMergable = False , caFogOnly = False , caCull = () , caDeformVertexes = [] , caNoMipMaps = False , caPolygonOffset = Nothing , caStages = [] } data RGBGen = RGB_Wave Wave | RGB_Const Float Float Float | RGB_Identity | RGB_IdentityLighting | RGB_Entity | RGB_OneMinusEntity | RGB_ExactVertex | RGB_Vertex | RGB_LightingDiffuse | RGB_OneMinusVertex data AlphaGen = A_Wave Wave | A_Const Float | A_Portal | A_Identity | A_Entity | A_OneMinusEntity | A_Vertex | A_LightingSpecular | A_OneMinusVertex data TCGen = TG_Base | TG_Lightmap | TG_Environment -- TODO, check: RB_CalcEnvironmentTexCoords | TG_Vector (Vec3 Float) (Vec3 Float) data TCMod = TM_EntityTranslate | TM_Rotate Float | TM_Scroll Float Float | TM_Scale Float Float | TM_Stretch Wave | TM_Transform Float Float Float Float Float Float | TM_Turb Float Float Float Float data StageTexture = ST_Map SB.ByteString | ST_ClampMap SB.ByteString | ST_AnimMap Float [SB.ByteString] | ST_Lightmap | ST_WhiteImage data StageAttrs = StageAttrs { saBlend :: Maybe (BlendingFactor,BlendingFactor) , saRGBGen :: RGBGen , saAlphaGen :: AlphaGen , saTCGen :: TCGen , saTCMod :: [TCMod] , saTexture :: StageTexture , saDepthWrite :: Bool , saDepthFunc :: ComparisonFunction , saAlphaFunc :: () } defaultStageAttrs :: StageAttrs defaultStageAttrs = StageAttrs { saBlend = Nothing , saRGBGen = RGB_Identity , saAlphaGen = A_Identity , saTCGen = TG_Base , saTCMod = [] , saTexture = ST_WhiteImage , saDepthWrite = False , saDepthFunc = Lequal , saAlphaFunc = () } fixAttribOrder ca = ca { caDeformVertexes = reverse $ caDeformVertexes ca , caStages = reverse $ map fixStage $ caStages ca } where fixStage sa = sa { saTCMod = reverse $ saTCMod sa }
csabahruska/GFXDemo
GPipeFPSMaterial.hs
Haskell
bsd-3-clause
3,629
module UI.Geometry where import Control.Applicative (liftA, liftA2) import Data.Functor.Classes import Data.Functor.Listable import Data.Semigroup data Rect a = Rect { origin :: !(Point a), size :: !(Size a) } deriving (Eq, Foldable, Functor, Ord, Traversable) containsPoint :: Real a => Rect a -> Point a -> Bool containsPoint r p = and (liftA2 (<=) (origin r) p) && and (liftA2 (<=) p (rectExtent r)) rectExtent :: Num a => Rect a -> Point a rectExtent r = liftA2 (+) (origin r) (sizeExtent (size r)) data Point a = Point { x :: !a, y :: !a } deriving (Eq, Foldable, Functor, Ord, Traversable) pointSize :: Point a -> Size a pointSize (Point x y) = Size x y data Size a = Size { width :: !a, height :: !a } deriving (Eq, Foldable, Functor, Ord, Traversable) encloses :: Ord a => Size a -> Size a -> Bool encloses a b = and ((>=) <$> a <*> b) sizeExtent :: Size a -> Point a sizeExtent (Size w h) = Point w h -- Instances instance Show1 Rect where liftShowsPrec sp sl d (Rect origin size) = showsBinaryWith (liftShowsPrec sp sl) (liftShowsPrec sp sl) "Rect" d origin size instance Show a => Show (Rect a) where showsPrec = liftShowsPrec showsPrec showList instance Eq1 Rect where liftEq eq (Rect o1 s1) (Rect o2 s2) = liftEq eq o1 o2 && liftEq eq s1 s2 instance Listable1 Rect where liftTiers t = liftCons2 (liftTiers t) (liftTiers t) Rect instance Listable a => Listable (Rect a) where tiers = tiers1 instance Applicative Point where pure a = Point a a Point f g <*> Point a b = Point (f a) (g b) instance Show1 Point where liftShowsPrec sp _ d (Point x y) = showsBinaryWith sp sp "Point" d x y instance Show a => Show (Point a) where showsPrec = liftShowsPrec showsPrec showList instance Eq1 Point where liftEq eq (Point x1 y1) (Point x2 y2) = eq x1 x2 && eq y1 y2 instance Listable1 Point where liftTiers t = liftCons2 t t Point instance Listable a => Listable (Point a) where tiers = tiers1 instance Applicative Size where pure a = Size a a Size f g <*> Size a b = Size (f a) (g b) instance Num a => Num (Size a) where fromInteger = pure . fromInteger abs = liftA abs signum = liftA signum negate = liftA negate (+) = liftA2 (+) (*) = liftA2 (*) instance Semigroup a => Semigroup (Size a) where (<>) = liftA2 (<>) instance Monoid a => Monoid (Size a) where mempty = pure mempty mappend = liftA2 mappend instance Show1 Size where liftShowsPrec sp _ d (Size w h) = showsBinaryWith sp sp "Size" d w h instance Show a => Show (Size a) where showsPrec = liftShowsPrec showsPrec showList instance Eq1 Size where liftEq eq (Size w1 h1) (Size w2 h2) = eq w1 w2 && eq h1 h2 instance Listable1 Size where liftTiers t = liftCons2 t t Size instance Listable a => Listable (Size a) where tiers = tiers1
robrix/ui-effects
src/UI/Geometry.hs
Haskell
bsd-3-clause
2,792
-- | Half-memory implementation of symmetric matrices with -- null-diagonal. module Math.VectorSpaces.DistanceMatrix ( DistanceMatrix, RealDistanceMatrix, BooleanDistanceMatrix, generate, (?), (!), Math.VectorSpaces.DistanceMatrix.map ) where import qualified Data.Vector.Generic as GV import qualified Data.Vector.Unboxed as UV import qualified Math.Algebra.Monoid as M data DistanceMatrix v a = C Int (v a) type RealDistanceMatrix = DistanceMatrix UV.Vector Double type BooleanDistanceMatrix = DistanceMatrix UV.Vector Bool generate :: (GV.Vector v a, M.AdditiveMonoid a) => Int -> ((Int, Int) -> a) -> DistanceMatrix v a generate n f = C n (GV.unfoldrN ((n*(n-1)) `quot` 2) helper (0,1)) where helper (i, j) | j == n-1 = Just (f (i, j), (i+1, i+2)) | otherwise = Just (f (i, j), (i, j+1)) -- | Indexing as if the matrix were infact square. {-# INLINE (?) #-} (?) :: (GV.Vector v a, M.AdditiveMonoid a) => DistanceMatrix v a -> (Int, Int) -> a (C n x) ? (i,j) | i == j = M.nil | j < i = x GV.! (unroll n (j,i)) | otherwise = x GV.! (unroll n (i,j)) -- | Indexing in upper right triangle (off-diagonal) only. {-# INLINE (!) #-} (!) :: (GV.Vector v a) => DistanceMatrix v a -> (Int, Int) -> a (C n x) ! (i,j) = x GV.! (unroll n (i,j)) map :: (GV.Vector v a, GV.Vector v b) => (a -> b) -> DistanceMatrix v a -> DistanceMatrix v b map f (C n x) = C n (GV.map f x) -- | Index unrolling. {-# INLINE unroll #-} unroll :: Int -> (Int, Int) -> Int unroll n (i, j) = n*i + j - (((i+1)*(i+2)) `quot` 2)
michiexile/hplex
pershom/src/Math/VectorSpaces/DistanceMatrix.hs
Haskell
bsd-3-clause
1,675
module Network.MtGoxAPI.DepthStore.Monitor ( monitorDepth ) where import Control.Applicative import Control.Concurrent import Control.Monad import Data.Maybe import Text.Printf import Network.MtGoxAPI.DepthStore monitorDepth :: DepthStoreHandle -> IO () monitorDepth handle = forever $ do putStrLn "" putStrLn "-- Fees --" simulateCircle handle $ 1* 10^(5::Integer) simulateCircle handle $ 2 * 10^(5::Integer) simulateCircle handle $ 5 * 10^(5::Integer) simulateCircle handle $ 10 * 10^(5::Integer) simulateCircle handle $ 15 * 10^(5::Integer) simulateCircle handle $ 20 * 10^(5::Integer) simulateCircle handle $ 100 * 10^(5::Integer) simulateCircle handle $ 500 * 10^(5::Integer) simulateCircle handle $ 1000 * 10^(5::Integer) simulateCircle handle $ 2000 * 10^(5::Integer) simulateCircle handle $ 5000 * 10^(5::Integer) threadDelay $ 10 * 10^(6::Integer) mtgoxFee :: Double mtgoxFee = 0.006 afterMtgoxFee :: Integer -> Integer afterMtgoxFee = round . (* (1 - mtgoxFee)) . fromIntegral simulateCircle :: DepthStoreHandle -> Integer -> IO () simulateCircle handle usdAmount = do btc <- fromMaybe 0 <$> simulateUSDSell handle usdAmount let btc' = afterMtgoxFee btc usd <- fromMaybe 0 <$> simulateBTCSell handle btc' let usd' = afterMtgoxFee usd cost = usdAmount - usd' inPercent = if usdAmount > 0 then (fromIntegral cost * 100) / fromIntegral usdAmount else 0 putStrLn $ formatUSD usdAmount ++ ": " ++ formatPercent (inPercent / 2) ++ " per transaction fee" putStrLn $ "\tSell " ++ formatUSD usdAmount ++ " --> " ++ formatBTC btc ++ " --> after fees --> " ++ formatBTC btc' ++ " --> sell again\n\t --> " ++ formatUSD usd ++ " --> after fees --> " ++ formatUSD usd' ++ " --> fees in percent: " ++ formatPercent inPercent formatUSD :: Integer -> String formatUSD a = let a' = fromIntegral a / 10 ^ (5 :: Integer) :: Double in printf "%.5f EUR" a' formatBTC :: Integer -> String formatBTC a = let a' = fromIntegral a / 10 ^ (8 :: Integer) :: Double in printf "%.8f BTC" a' formatPercent :: Double -> String formatPercent = printf "%.2f %%"
javgh/mtgoxapi
Network/MtGoxAPI/DepthStore/Monitor.hs
Haskell
bsd-3-clause
2,311
{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeOperators #-} module Serv.Server.Core.Runtime ( runCore ) where import Control.Lens import Control.Monad.Except import Control.Monad.Reader (ReaderT, runReaderT) import Control.Monad.Reader.Class import Data.Aeson.Encode.Pretty (encodePretty) import qualified Data.ByteString.Lazy.Char8 as BL8 import Data.Text.Encoding (encodeUtf8) import Network.Wai (Application) import Network.Wai.Handler.Warp (run) import qualified Network.Wai.Handler.Warp as WP import Network.Wai.Metrics import qualified Network.Wai.Middleware.Cors as CS import qualified Network.Wai.Middleware.Gzip as GZ import Network.Wai.Middleware.RequestLogger import qualified Network.Wai.Middleware.StripHeaders as SH import Serv.Api import Serv.Api.Types import Serv.Server.Core.Config import qualified Serv.Server.Core.Config as Cfg import Serv.Server.Core.HealthApi import Serv.Server.Core.HealthHandler import Serv.Server.Core.InfoApi import Serv.Server.Core.ManagmentAuth import Serv.Server.Core.Metrics import Serv.Server.Core.MetricsApi import Serv.Server.Core.MetricsHandler import Serv.Server.Features.EntityHandler import Serv.Server.ServerEnv import Servant import Servant.Extentions.Server import System.Log.FastLogger -- | System API: info, health, metrics type SysApi = InfoApi :<|> HealthApi :<|> MetricsApi coreServer :: ServerEnv -> Server SysApi coreServer serverEnv = handleInfo serverEnv :<|> handleHealth serverEnv :<|> handleMetrics serverEnv coreApp :: ServerEnv -> Application coreApp serverEnv@ServerEnv{..} = serveWithContextEx (Proxy :: Proxy SysApi) (managementAuthContext (managementConf serverConfig)) (coreServer serverEnv) runCore :: ServerEnv -> IO () runCore serverEnv@ServerEnv{..} = do putStrLn ("[Sys] Listening on " ++ show port) WP.runSettings settings $ middleware $ coreApp serverEnv where middleware = GZ.gzip GZ.def . CS.simpleCors settings = WP.setServerName (encodeUtf8(serverName (serverConf serverConfig))) . WP.setPort port $ WP.defaultSettings port = Cfg.port (managementConf serverConfig)
orangefiredragon/bear
src/Serv/Server/Core/Runtime.hs
Haskell
bsd-3-clause
2,550
{-# LINE 1 "GHC.Conc.Signal.hs" #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} module GHC.Conc.Signal ( Signal , HandlerFun , setHandler , runHandlers , runHandlersPtr ) where import Control.Concurrent.MVar (MVar, newMVar, withMVar) import Data.Dynamic (Dynamic) import Foreign.C.Types (CInt) import Foreign.ForeignPtr (ForeignPtr, newForeignPtr) import Foreign.StablePtr (castPtrToStablePtr, castStablePtrToPtr, deRefStablePtr, freeStablePtr, newStablePtr) import Foreign.Ptr (Ptr, castPtr) import Foreign.Marshal.Alloc (finalizerFree) import GHC.Arr (inRange) import GHC.Base import GHC.Conc.Sync (forkIO) import GHC.IO (mask_, unsafePerformIO) import GHC.IOArray (IOArray, boundsIOArray, newIOArray, unsafeReadIOArray, unsafeWriteIOArray) import GHC.Real (fromIntegral) import GHC.Word (Word8) ------------------------------------------------------------------------ -- Signal handling type Signal = CInt maxSig :: Int maxSig = 64 type HandlerFun = ForeignPtr Word8 -> IO () -- Lock used to protect concurrent access to signal_handlers. Symptom -- of this race condition is GHC bug #1922, although that bug was on -- Windows a similar bug also exists on Unix. signal_handlers :: MVar (IOArray Int (Maybe (HandlerFun,Dynamic))) signal_handlers = unsafePerformIO $ do arr <- newIOArray (0, maxSig) Nothing m <- newMVar arr sharedCAF m getOrSetGHCConcSignalSignalHandlerStore {-# NOINLINE signal_handlers #-} foreign import ccall unsafe "getOrSetGHCConcSignalSignalHandlerStore" getOrSetGHCConcSignalSignalHandlerStore :: Ptr a -> IO (Ptr a) setHandler :: Signal -> Maybe (HandlerFun, Dynamic) -> IO (Maybe (HandlerFun, Dynamic)) setHandler sig handler = do let int = fromIntegral sig withMVar signal_handlers $ \arr -> if not (inRange (boundsIOArray arr) int) then errorWithoutStackTrace "GHC.Conc.setHandler: signal out of range" else do old <- unsafeReadIOArray arr int unsafeWriteIOArray arr int handler return old runHandlers :: ForeignPtr Word8 -> Signal -> IO () runHandlers p_info sig = do let int = fromIntegral sig withMVar signal_handlers $ \arr -> if not (inRange (boundsIOArray arr) int) then return () else do handler <- unsafeReadIOArray arr int case handler of Nothing -> return () Just (f,_) -> do _ <- forkIO (f p_info) return () -- It is our responsibility to free the memory buffer, so we create a -- foreignPtr. runHandlersPtr :: Ptr Word8 -> Signal -> IO () runHandlersPtr p s = do fp <- newForeignPtr finalizerFree p runHandlers fp s -- Machinery needed to ensure that we only have one copy of certain -- CAFs in this module even when the base package is present twice, as -- it is when base is dynamically loaded into GHCi. The RTS keeps -- track of the single true value of the CAF, so even when the CAFs in -- the dynamically-loaded base package are reverted, nothing bad -- happens. -- sharedCAF :: a -> (Ptr a -> IO (Ptr a)) -> IO a sharedCAF a get_or_set = mask_ $ do stable_ref <- newStablePtr a let ref = castPtr (castStablePtrToPtr stable_ref) ref2 <- get_or_set ref if ref == ref2 then return a else do freeStablePtr stable_ref deRefStablePtr (castPtrToStablePtr (castPtr ref2))
phischu/fragnix
builtins/base/GHC.Conc.Signal.hs
Haskell
bsd-3-clause
3,458
module Main where import System.Environment import Arion.Runner main :: IO () main = getArgs >>= run
saturday06/arion
src/Main.hs
Haskell
mit
103
{-# OPTIONS_GHC -fno-warn-type-defaults #-} import Data.Foldable (for_) import Test.Hspec (Spec, describe, it, shouldBe) import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith) import Triangle ( TriangleType ( Equilateral , Illegal , Isosceles , Scalene ) , triangleType ) main :: IO () main = hspecWith defaultConfig {configFastFail = True} specs specs :: Spec specs = describe "triangle" $ describe "triangleType" $ for_ cases test where test (description, (a, b, c), expected) = it description assertion where assertion = triangleType a b c `shouldBe` expected -- Test cases adapted from `exercism/x-common/triangle.json` on 2016-08-03. cases = [ ( "equilateral triangle has all sides equal" , (2, 2, 2) , Equilateral ) , ( "larger equilateral triangle" , (10, 10, 10) , Equilateral ) , ( "isosceles triangle with last two sides equal" , (3, 4, 4) , Isosceles ) , ( "isosceles triangle with first two sides equal" , (4, 4, 3) , Isosceles ) , ( "isosceles triangle with first and last sides equal" , (4, 3, 4) , Isosceles ) , ( "isosceles triangle with unequal side larger than equal sides" , (4, 7, 4) , Isosceles ) , ( "scalene triangle has no equal sides" , (3, 4, 5) , Scalene ) , ( "larger scalene triangle" , (10, 11, 12) , Scalene ) , ( "scalene triangle with sides in descending order" , (5, 4, 2) , Scalene ) , ( "small scalene triangle with floating point values" , (0.4, 0.6, 0.3) , Scalene ) , ( "a triangle violating the triangle inequality is illegal" , (7, 3, 2) , Illegal ) , ( "two sides equal, but still violates triangle inequality" , (1, 1, 3) , Illegal ) , ( "triangles with all sides zero are illegal" , (0, 0, 0) , Illegal ) ]
xTVaser/Exercism-Solutions
haskell/triangle/test/Tests.hs
Haskell
mit
2,496
module Main where import HTrees import Control.Monad.IO.Class import Data.CSV.Conduit import Data.List import qualified Data.Map.Lazy as Map import Data.Maybe import Data.Vector (Vector, fromList, toList, (!)) import System.Environment (getArgs) -- Main main :: IO () main = do args <- getArgs let filename = head args -- Read and parse the data set putStr $ "Reading " ++ filename ++ "... " dataset <- readDataset filename putStrLn $ (show . length . examples $ dataset) ++ " samples." -- Construct a tree putStr "Builing tree..." let config = Config { maxDepth = 30, minNodeSize = 20, leafModel = meanModel, stat = Stat { aggregator = toMoment, summary = variance } } let tree = buildWith config dataset putStrLn "Done!" putStrLn $ show tree -- Evaluation the tree on the training set putStrLn "Evaluating ..." let evaluation = evaluate squareLoss tree (examples dataset) putStrLn $ "MSE = " ++ show evaluation -- Reads in the "SSV" (semi-colon separated) file and turn it into data readDataset :: MonadIO m => FilePath -> m (DataSet Double) readDataset filename = do csv <- readCSVFile defCSVSettings { csvSep = ';' } filename let (names, instances) = parseInstances (toList csv) let keys = delete "quality" names let attrs = [ Attr k (! (fromJust . elemIndex k $ names)) | k <- keys ] let target = (! (fromJust . elemIndex "quality" $ names)) return $ DS attrs (makeExamplesWith target instances) makeExamplesWith :: (Instance -> l) -> [Instance] -> [Example l] makeExamplesWith f is = [ Ex i (f i) | i <- is ] -------------------------------------------------------------------------------- -- Data IO and other wrangling parseInstances :: [MapRow String] -> ([String], [Vector Double]) parseInstances rows = (names, instances) where names = Map.keys . head $ rows instances = map (makeInstance names) rows makeInstance :: [String] -> MapRow String -> Instance makeInstance names row = fromList . map (makeValue . fromJust . flip Map.lookup row) $ names makeValue :: String -> Double makeValue s = case reads s :: [(Double, String)] of [(v, "")] -> v _ -> error $ "Could not parse '" ++ s ++ "' as Double" -- Wine data set columns: -- "fixed acidity"; -- "volatile acidity"; -- "citric acid"; -- "residual sugar"; -- "chlorides"; -- "free sulfur dioxide"; -- "total sulfur dioxide"; -- "density"; -- "pH"; -- "sulphates"; -- "alcohol"; -- "quality"
mreid/HTrees
src/run.hs
Haskell
mit
2,545
{-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE CPP #-} module Foundation.Collection.Copy ( Copy(..) ) where import GHC.ST (runST) import Basement.Compat.Base ((>>=)) import Basement.Nat import Basement.Types.OffsetSize import qualified Basement.Block as BLK import qualified Basement.UArray as UA import qualified Basement.BoxedArray as BA import qualified Basement.String as S #if MIN_VERSION_base(4,9,0) import qualified Basement.Sized.Block as BLKN import qualified Basement.Sized.List as LN #endif class Copy a where copy :: a -> a instance Copy [ty] where copy a = a instance UA.PrimType ty => Copy (BLK.Block ty) where copy blk = runST (BLK.thaw blk >>= BLK.unsafeFreeze) instance UA.PrimType ty => Copy (UA.UArray ty) where copy = UA.copy instance Copy (BA.Array ty) where copy = BA.copy instance Copy S.String where copy = S.copy #if MIN_VERSION_base(4,9,0) instance Copy (LN.ListN n ty) where copy a = a instance (Countable ty n, UA.PrimType ty, KnownNat n) => Copy (BLKN.BlockN n ty) where copy blk = runST (BLKN.thaw blk >>= BLKN.freeze) #endif
vincenthz/hs-foundation
foundation/Foundation/Collection/Copy.hs
Haskell
bsd-3-clause
1,146
{-# OPTIONS_GHC -Wall #-} module Optimize.Case (optimize) where import Control.Arrow (second) import qualified Data.Map as Map import Data.Map ((!)) import qualified Data.Maybe as Maybe import qualified AST.Expression.Optimized as Opt import qualified AST.Pattern as P import qualified Optimize.DecisionTree as DT -- OPTIMIZE A CASE EXPRESSION optimize :: DT.VariantDict -> String -> [(P.Canonical, Opt.Expr)] -> Opt.Expr optimize variantDict exprName optBranches = let (patterns, indexedBranches) = unzip (zipWith indexify [0..] optBranches) decisionTree = DT.compile variantDict patterns in treeToExpr exprName decisionTree indexedBranches indexify :: Int -> (a,b) -> ((a,Int), (Int,b)) indexify index (pattern, branch) = ( (pattern, index) , (index, branch) ) -- CONVERT A TREE TO AN EXPRESSION treeToExpr :: String -> DT.DecisionTree -> [(Int, Opt.Expr)] -> Opt.Expr treeToExpr name decisionTree allJumps = let decider = treeToDecider decisionTree targetCounts = countTargets decider (choices, maybeJumps) = unzip (map (createChoices targetCounts) allJumps) in Opt.Case name (insertChoices (Map.fromList choices) decider) (Maybe.catMaybes maybeJumps) -- TREE TO DECIDER -- -- Decision trees may have some redundancies, so we convert them to a Decider -- which has special constructs to avoid code duplication when possible. treeToDecider :: DT.DecisionTree -> Opt.Decider Int treeToDecider tree = case tree of DT.Match target -> Opt.Leaf target -- zero options DT.Decision _ [] Nothing -> error "compiler bug, somehow created an empty decision tree" -- one option DT.Decision _ [(_, subTree)] Nothing -> treeToDecider subTree DT.Decision _ [] (Just subTree) -> treeToDecider subTree -- two options DT.Decision path [(test, successTree)] (Just failureTree) -> toChain path test successTree failureTree DT.Decision path [(test, successTree), (_, failureTree)] Nothing -> toChain path test successTree failureTree -- many options DT.Decision path edges Nothing -> let (necessaryTests, fallback) = (init edges, snd (last edges)) in Opt.FanOut path (map (second treeToDecider) necessaryTests) (treeToDecider fallback) DT.Decision path edges (Just fallback) -> Opt.FanOut path (map (second treeToDecider) edges) (treeToDecider fallback) toChain :: DT.Path -> DT.Test -> DT.DecisionTree -> DT.DecisionTree -> Opt.Decider Int toChain path test successTree failureTree = let failure = treeToDecider failureTree in case treeToDecider successTree of Opt.Chain testChain success subFailure | failure == subFailure -> Opt.Chain ((path, test) : testChain) success failure success -> Opt.Chain [(path, test)] success failure -- INSERT CHOICES -- -- If a target appears exactly once in a Decider, the corresponding expression -- can be inlined. Whether things are inlined or jumps is called a "choice". countTargets :: Opt.Decider Int -> Map.Map Int Int countTargets decisionTree = case decisionTree of Opt.Leaf target -> Map.singleton target 1 Opt.Chain _ success failure -> Map.unionWith (+) (countTargets success) (countTargets failure) Opt.FanOut _ tests fallback -> Map.unionsWith (+) (map countTargets (fallback : map snd tests)) createChoices :: Map.Map Int Int -> (Int, Opt.Expr) -> ( (Int, Opt.Choice), Maybe (Int, Opt.Expr) ) createChoices targetCounts (target, branch) = if targetCounts ! target == 1 then ( (target, Opt.Inline branch) , Nothing ) else ( (target, Opt.Jump target) , Just (target, branch) ) insertChoices :: Map.Map Int Opt.Choice -> Opt.Decider Int -> Opt.Decider Opt.Choice insertChoices choiceDict decider = let go = insertChoices choiceDict in case decider of Opt.Leaf target -> Opt.Leaf (choiceDict ! target) Opt.Chain testChain success failure -> Opt.Chain testChain (go success) (go failure) Opt.FanOut path tests fallback -> Opt.FanOut path (map (second go) tests) (go fallback)
mgold/Elm
src/Optimize/Case.hs
Haskell
bsd-3-clause
4,385
----------------------------------------------------------------------------- -- | -- Module : Data.Ratio -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : stable -- Portability : portable -- -- Standard functions on rational numbers -- ----------------------------------------------------------------------------- module Data.Ratio ( Ratio , Rational , (%) -- :: (Integral a) => a -> a -> Ratio a , numerator -- :: (Integral a) => Ratio a -> a , denominator -- :: (Integral a) => Ratio a -> a , approxRational -- :: (RealFrac a) => a -> a -> Rational -- Ratio instances: -- (Integral a) => Eq (Ratio a) -- (Integral a) => Ord (Ratio a) -- (Integral a) => Num (Ratio a) -- (Integral a) => Real (Ratio a) -- (Integral a) => Fractional (Ratio a) -- (Integral a) => RealFrac (Ratio a) -- (Integral a) => Enum (Ratio a) -- (Read a, Integral a) => Read (Ratio a) -- (Integral a) => Show (Ratio a) ) where import Prelude #ifdef __GLASGOW_HASKELL__ import GHC.Real -- The basic defns for Ratio #endif #ifdef __HUGS__ import Hugs.Prelude(Ratio(..), (%), numerator, denominator) #endif #ifdef __NHC__ import Ratio (Ratio(..), (%), numerator, denominator, approxRational) #else -- ----------------------------------------------------------------------------- -- approxRational -- | 'approxRational', applied to two real fractional numbers @x@ and @epsilon@, -- returns the simplest rational number within @epsilon@ of @x@. -- A rational number @y@ is said to be /simpler/ than another @y'@ if -- -- * @'abs' ('numerator' y) <= 'abs' ('numerator' y')@, and -- -- * @'denominator' y <= 'denominator' y'@. -- -- Any real interval contains a unique simplest rational; -- in particular, note that @0\/1@ is the simplest rational of all. -- Implementation details: Here, for simplicity, we assume a closed rational -- interval. If such an interval includes at least one whole number, then -- the simplest rational is the absolutely least whole number. Otherwise, -- the bounds are of the form q%1 + r%d and q%1 + r'%d', where abs r < d -- and abs r' < d', and the simplest rational is q%1 + the reciprocal of -- the simplest rational between d'%r' and d%r. approxRational :: (RealFrac a) => a -> a -> Rational approxRational rat eps = simplest (rat-eps) (rat+eps) where simplest x y | y < x = simplest y x | x == y = xr | x > 0 = simplest' n d n' d' | y < 0 = - simplest' (-n') d' (-n) d | otherwise = 0 :% 1 where xr = toRational x n = numerator xr d = denominator xr nd' = toRational y n' = numerator nd' d' = denominator nd' simplest' n d n' d' -- assumes 0 < n%d < n'%d' | r == 0 = q :% 1 | q /= q' = (q+1) :% 1 | otherwise = (q*n''+d'') :% n'' where (q,r) = quotRem n d (q',r') = quotRem n' d' nd'' = simplest' d' r' d r n'' = numerator nd'' d'' = denominator nd'' #endif
alekar/hugs
packages/base/Data/Ratio.hs
Haskell
bsd-3-clause
3,206
{-# LANGUAGE BangPatterns, CPP, GADTs #-} module MkGraph ( CmmAGraph, CmmAGraphScoped, CgStmt(..) , (<*>), catAGraphs , mkLabel, mkMiddle, mkLast, outOfLine , lgraphOfAGraph, labelAGraph , stackStubExpr , mkNop, mkAssign, mkStore , mkUnsafeCall, mkFinalCall, mkCallReturnsTo , mkJumpReturnsTo , mkJump, mkJumpExtra , mkRawJump , mkCbranch, mkSwitch , mkReturn, mkComment, mkCallEntry, mkBranch , mkUnwind , copyInOflow, copyOutOflow , noExtraStack , toCall, Transfer(..) ) where import GhcPrelude (($),Int,Bool,Eq(..)) -- avoid importing (<*>) import BlockId import Cmm import CmmCallConv import CmmSwitch (SwitchTargets) import Hoopl.Block import Hoopl.Graph import Hoopl.Label import DynFlags import FastString import ForeignCall import OrdList import SMRep (ByteOff) import UniqSupply import Control.Monad import Data.List import Data.Maybe #include "HsVersions.h" ----------------------------------------------------------------------------- -- Building Graphs -- | CmmAGraph is a chunk of code consisting of: -- -- * ordinary statements (assignments, stores etc.) -- * jumps -- * labels -- * out-of-line labelled blocks -- -- The semantics is that control falls through labels and out-of-line -- blocks. Everything after a jump up to the next label is by -- definition unreachable code, and will be discarded. -- -- Two CmmAGraphs can be stuck together with <*>, with the meaning that -- control flows from the first to the second. -- -- A 'CmmAGraph' can be turned into a 'CmmGraph' (closed at both ends) -- by providing a label for the entry point and a tick scope; see -- 'labelAGraph'. type CmmAGraph = OrdList CgStmt -- | Unlabeled graph with tick scope type CmmAGraphScoped = (CmmAGraph, CmmTickScope) data CgStmt = CgLabel BlockId CmmTickScope | CgStmt (CmmNode O O) | CgLast (CmmNode O C) | CgFork BlockId CmmAGraph CmmTickScope flattenCmmAGraph :: BlockId -> CmmAGraphScoped -> CmmGraph flattenCmmAGraph id (stmts_t, tscope) = CmmGraph { g_entry = id, g_graph = GMany NothingO body NothingO } where body = foldr addBlock emptyBody $ flatten id stmts_t tscope [] -- -- flatten: given an entry label and a CmmAGraph, make a list of blocks. -- -- NB. avoid the quadratic-append trap by passing in the tail of the -- list. This is important for Very Long Functions (e.g. in T783). -- flatten :: Label -> CmmAGraph -> CmmTickScope -> [Block CmmNode C C] -> [Block CmmNode C C] flatten id g tscope blocks = flatten1 (fromOL g) block' blocks where !block' = blockJoinHead (CmmEntry id tscope) emptyBlock -- -- flatten0: we are outside a block at this point: any code before -- the first label is unreachable, so just drop it. -- flatten0 :: [CgStmt] -> [Block CmmNode C C] -> [Block CmmNode C C] flatten0 [] blocks = blocks flatten0 (CgLabel id tscope : stmts) blocks = flatten1 stmts block blocks where !block = blockJoinHead (CmmEntry id tscope) emptyBlock flatten0 (CgFork fork_id stmts_t tscope : rest) blocks = flatten fork_id stmts_t tscope $ flatten0 rest blocks flatten0 (CgLast _ : stmts) blocks = flatten0 stmts blocks flatten0 (CgStmt _ : stmts) blocks = flatten0 stmts blocks -- -- flatten1: we have a partial block, collect statements until the -- next last node to make a block, then call flatten0 to get the rest -- of the blocks -- flatten1 :: [CgStmt] -> Block CmmNode C O -> [Block CmmNode C C] -> [Block CmmNode C C] -- The current block falls through to the end of a function or fork: -- this code should not be reachable, but it may be referenced by -- other code that is not reachable. We'll remove it later with -- dead-code analysis, but for now we have to keep the graph -- well-formed, so we terminate the block with a branch to the -- beginning of the current block. flatten1 [] block blocks = blockJoinTail block (CmmBranch (entryLabel block)) : blocks flatten1 (CgLast stmt : stmts) block blocks = block' : flatten0 stmts blocks where !block' = blockJoinTail block stmt flatten1 (CgStmt stmt : stmts) block blocks = flatten1 stmts block' blocks where !block' = blockSnoc block stmt flatten1 (CgFork fork_id stmts_t tscope : rest) block blocks = flatten fork_id stmts_t tscope $ flatten1 rest block blocks -- a label here means that we should start a new block, and the -- current block should fall through to the new block. flatten1 (CgLabel id tscp : stmts) block blocks = blockJoinTail block (CmmBranch id) : flatten1 stmts (blockJoinHead (CmmEntry id tscp) emptyBlock) blocks ---------- AGraph manipulation (<*>) :: CmmAGraph -> CmmAGraph -> CmmAGraph (<*>) = appOL catAGraphs :: [CmmAGraph] -> CmmAGraph catAGraphs = concatOL -- | created a sequence "goto id; id:" as an AGraph mkLabel :: BlockId -> CmmTickScope -> CmmAGraph mkLabel bid scp = unitOL (CgLabel bid scp) -- | creates an open AGraph from a given node mkMiddle :: CmmNode O O -> CmmAGraph mkMiddle middle = unitOL (CgStmt middle) -- | created a closed AGraph from a given node mkLast :: CmmNode O C -> CmmAGraph mkLast last = unitOL (CgLast last) -- | A labelled code block; should end in a last node outOfLine :: BlockId -> CmmAGraphScoped -> CmmAGraph outOfLine l (c,s) = unitOL (CgFork l c s) -- | allocate a fresh label for the entry point lgraphOfAGraph :: CmmAGraphScoped -> UniqSM CmmGraph lgraphOfAGraph g = do u <- getUniqueM return (labelAGraph (mkBlockId u) g) -- | use the given BlockId as the label of the entry point labelAGraph :: BlockId -> CmmAGraphScoped -> CmmGraph labelAGraph lbl ag = flattenCmmAGraph lbl ag ---------- No-ops mkNop :: CmmAGraph mkNop = nilOL mkComment :: FastString -> CmmAGraph #if defined(DEBUG) -- SDM: generating all those comments takes time, this saved about 4% for me mkComment fs = mkMiddle $ CmmComment fs #else mkComment _ = nilOL #endif ---------- Assignment and store mkAssign :: CmmReg -> CmmExpr -> CmmAGraph mkAssign l (CmmReg r) | l == r = mkNop mkAssign l r = mkMiddle $ CmmAssign l r mkStore :: CmmExpr -> CmmExpr -> CmmAGraph mkStore l r = mkMiddle $ CmmStore l r ---------- Control transfer mkJump :: DynFlags -> Convention -> CmmExpr -> [CmmExpr] -> UpdFrameOffset -> CmmAGraph mkJump dflags conv e actuals updfr_off = lastWithArgs dflags Jump Old conv actuals updfr_off $ toCall e Nothing updfr_off 0 -- | A jump where the caller says what the live GlobalRegs are. Used -- for low-level hand-written Cmm. mkRawJump :: DynFlags -> CmmExpr -> UpdFrameOffset -> [GlobalReg] -> CmmAGraph mkRawJump dflags e updfr_off vols = lastWithArgs dflags Jump Old NativeNodeCall [] updfr_off $ \arg_space _ -> toCall e Nothing updfr_off 0 arg_space vols mkJumpExtra :: DynFlags -> Convention -> CmmExpr -> [CmmExpr] -> UpdFrameOffset -> [CmmExpr] -> CmmAGraph mkJumpExtra dflags conv e actuals updfr_off extra_stack = lastWithArgsAndExtraStack dflags Jump Old conv actuals updfr_off extra_stack $ toCall e Nothing updfr_off 0 mkCbranch :: CmmExpr -> BlockId -> BlockId -> Maybe Bool -> CmmAGraph mkCbranch pred ifso ifnot likely = mkLast (CmmCondBranch pred ifso ifnot likely) mkSwitch :: CmmExpr -> SwitchTargets -> CmmAGraph mkSwitch e tbl = mkLast $ CmmSwitch e tbl mkReturn :: DynFlags -> CmmExpr -> [CmmExpr] -> UpdFrameOffset -> CmmAGraph mkReturn dflags e actuals updfr_off = lastWithArgs dflags Ret Old NativeReturn actuals updfr_off $ toCall e Nothing updfr_off 0 mkBranch :: BlockId -> CmmAGraph mkBranch bid = mkLast (CmmBranch bid) mkFinalCall :: DynFlags -> CmmExpr -> CCallConv -> [CmmExpr] -> UpdFrameOffset -> CmmAGraph mkFinalCall dflags f _ actuals updfr_off = lastWithArgs dflags Call Old NativeDirectCall actuals updfr_off $ toCall f Nothing updfr_off 0 mkCallReturnsTo :: DynFlags -> CmmExpr -> Convention -> [CmmExpr] -> BlockId -> ByteOff -> UpdFrameOffset -> [CmmExpr] -> CmmAGraph mkCallReturnsTo dflags f callConv actuals ret_lbl ret_off updfr_off extra_stack = do lastWithArgsAndExtraStack dflags Call (Young ret_lbl) callConv actuals updfr_off extra_stack $ toCall f (Just ret_lbl) updfr_off ret_off -- Like mkCallReturnsTo, but does not push the return address (it is assumed to be -- already on the stack). mkJumpReturnsTo :: DynFlags -> CmmExpr -> Convention -> [CmmExpr] -> BlockId -> ByteOff -> UpdFrameOffset -> CmmAGraph mkJumpReturnsTo dflags f callConv actuals ret_lbl ret_off updfr_off = do lastWithArgs dflags JumpRet (Young ret_lbl) callConv actuals updfr_off $ toCall f (Just ret_lbl) updfr_off ret_off mkUnsafeCall :: ForeignTarget -> [CmmFormal] -> [CmmActual] -> CmmAGraph mkUnsafeCall t fs as = mkMiddle $ CmmUnsafeForeignCall t fs as -- | Construct a 'CmmUnwind' node for the given register and unwinding -- expression. mkUnwind :: GlobalReg -> CmmExpr -> CmmAGraph mkUnwind r e = mkMiddle $ CmmUnwind [(r, Just e)] -------------------------------------------------------------------------- -- Why are we inserting extra blocks that simply branch to the successors? -- Because in addition to the branch instruction, @mkBranch@ will insert -- a necessary adjustment to the stack pointer. -- For debugging purposes, we can stub out dead stack slots: stackStubExpr :: Width -> CmmExpr stackStubExpr w = CmmLit (CmmInt 0 w) -- When we copy in parameters, we usually want to put overflow -- parameters on the stack, but sometimes we want to pass the -- variables in their spill slots. Therefore, for copying arguments -- and results, we provide different functions to pass the arguments -- in an overflow area and to pass them in spill slots. copyInOflow :: DynFlags -> Convention -> Area -> [CmmFormal] -> [CmmFormal] -> (Int, [GlobalReg], CmmAGraph) copyInOflow dflags conv area formals extra_stk = (offset, gregs, catAGraphs $ map mkMiddle nodes) where (offset, gregs, nodes) = copyIn dflags conv area formals extra_stk -- Return the number of bytes used for copying arguments, as well as the -- instructions to copy the arguments. copyIn :: DynFlags -> Convention -> Area -> [CmmFormal] -> [CmmFormal] -> (ByteOff, [GlobalReg], [CmmNode O O]) copyIn dflags conv area formals extra_stk = (stk_size, [r | (_, RegisterParam r) <- args], map ci (stk_args ++ args)) where ci (reg, RegisterParam r) = CmmAssign (CmmLocal reg) (CmmReg (CmmGlobal r)) ci (reg, StackParam off) = CmmAssign (CmmLocal reg) (CmmLoad (CmmStackSlot area off) ty) where ty = localRegType reg init_offset = widthInBytes (wordWidth dflags) -- infotable (stk_off, stk_args) = assignStack dflags init_offset localRegType extra_stk (stk_size, args) = assignArgumentsPos dflags stk_off conv localRegType formals -- Factoring out the common parts of the copyout functions yielded something -- more complicated: data Transfer = Call | JumpRet | Jump | Ret deriving Eq copyOutOflow :: DynFlags -> Convention -> Transfer -> Area -> [CmmExpr] -> UpdFrameOffset -> [CmmExpr] -- extra stack args -> (Int, [GlobalReg], CmmAGraph) -- Generate code to move the actual parameters into the locations -- required by the calling convention. This includes a store for the -- return address. -- -- The argument layout function ignores the pointer to the info table, -- so we slot that in here. When copying-out to a young area, we set -- the info table for return and adjust the offsets of the other -- parameters. If this is a call instruction, we adjust the offsets -- of the other parameters. copyOutOflow dflags conv transfer area actuals updfr_off extra_stack_stuff = (stk_size, regs, graph) where (regs, graph) = foldr co ([], mkNop) (setRA ++ args ++ stack_params) co (v, RegisterParam r) (rs, ms) = (r:rs, mkAssign (CmmGlobal r) v <*> ms) co (v, StackParam off) (rs, ms) = (rs, mkStore (CmmStackSlot area off) v <*> ms) (setRA, init_offset) = case area of Young id -> -- Generate a store instruction for -- the return address if making a call case transfer of Call -> ([(CmmLit (CmmBlock id), StackParam init_offset)], widthInBytes (wordWidth dflags)) JumpRet -> ([], widthInBytes (wordWidth dflags)) _other -> ([], 0) Old -> ([], updfr_off) (extra_stack_off, stack_params) = assignStack dflags init_offset (cmmExprType dflags) extra_stack_stuff args :: [(CmmExpr, ParamLocation)] -- The argument and where to put it (stk_size, args) = assignArgumentsPos dflags extra_stack_off conv (cmmExprType dflags) actuals mkCallEntry :: DynFlags -> Convention -> [CmmFormal] -> [CmmFormal] -> (Int, [GlobalReg], CmmAGraph) mkCallEntry dflags conv formals extra_stk = copyInOflow dflags conv Old formals extra_stk lastWithArgs :: DynFlags -> Transfer -> Area -> Convention -> [CmmExpr] -> UpdFrameOffset -> (ByteOff -> [GlobalReg] -> CmmAGraph) -> CmmAGraph lastWithArgs dflags transfer area conv actuals updfr_off last = lastWithArgsAndExtraStack dflags transfer area conv actuals updfr_off noExtraStack last lastWithArgsAndExtraStack :: DynFlags -> Transfer -> Area -> Convention -> [CmmExpr] -> UpdFrameOffset -> [CmmExpr] -> (ByteOff -> [GlobalReg] -> CmmAGraph) -> CmmAGraph lastWithArgsAndExtraStack dflags transfer area conv actuals updfr_off extra_stack last = copies <*> last outArgs regs where (outArgs, regs, copies) = copyOutOflow dflags conv transfer area actuals updfr_off extra_stack noExtraStack :: [CmmExpr] noExtraStack = [] toCall :: CmmExpr -> Maybe BlockId -> UpdFrameOffset -> ByteOff -> ByteOff -> [GlobalReg] -> CmmAGraph toCall e cont updfr_off res_space arg_space regs = mkLast $ CmmCall e cont regs arg_space res_space updfr_off
shlevy/ghc
compiler/cmm/MkGraph.hs
Haskell
bsd-3-clause
14,778
-- | A CPS IR. module Ivory.Compile.ACL2.CPS ( Proc (..) , Value (..) , Literal (..) , Cont (..) , Var , variables , contFreeVars , explicitStack , replaceCont , commonSubExprElim , removeAsserts , removeNullEffect ) where import Data.List import Text.Printf import Ivory.Compile.ACL2.Expr hiding (Expr (..)) import qualified Ivory.Compile.ACL2.Expr as E -- | A procedure is a name, a list of arguments, an optional measure, and its continuation (body). data Proc = Proc Var [Var] (Maybe E.Expr) Cont deriving Eq instance Show Proc where show (Proc name args Nothing body) = printf "%s(%s)\n%s\n" name (intercalate ", " args) (indent $ show body) show (Proc name args (Just m) body) = printf "%s(%s)\n\tmeasure %s\n%s\n" name (intercalate ", " args) (show m) (indent $ show body) -- | Values used in let bindings. data Value = Var Var -- ^ A variable reference. | Literal Literal -- ^ A constant. | Pop -- ^ Pop a value off the stack. | Deref Var -- ^ Dereference a ref. | Alloc -- ^ Allocate one word from the heap. | Array [Var] -- ^ Array construction. | Struct [(String, Var)] -- ^ Struct construction. | ArrayIndex Var Var -- ^ Array indexing. | StructIndex Var String -- ^ Structure indexing. | Intrinsic Intrinsic [Var] -- ^ An application of an intrinsic to a list of arguments. deriving Eq instance Show Value where show a = case a of Var a -> a Literal a -> show a Pop -> "pop" Deref a -> "deref " ++ a Alloc -> printf "alloc" Array a -> printf "array [%s]" $ intercalate ", " a Struct a -> printf "struct {%s}" $ intercalate ", " [ printf "%s: %s" n v | (n, v) <- a ] ArrayIndex a b -> printf "%s[%s]" a b StructIndex a b -> printf "%s.%s" a b Intrinsic a args -> printf "%s(%s)" (show a) (intercalate ", " args) instance Num Value where (+) = error "Method not supported for Num Value." (-) = error "Method not supported for Num Value." (*) = error "Method not supported for Num Value." negate = error "Method not supported for Num Value." abs = error "Method not supported for Num Value." signum = error "Method not supported for Num Value." fromInteger = Literal . fromInteger -- | Continuations. data Cont = Halt -- ^ End the program or loop. | Call Var [Var] (Maybe Cont) -- ^ Push the continuation onto the stack (if one exists) and call a function with arguments. | Return (Maybe Var) -- ^ Pop a continuation off the stack and execute it. Saves the return value to the ReturnValue register. | Push Var Cont -- ^ Push a value onto the stack. | Let Var Value Cont -- ^ Brings a new variable into scope and assigns it a value. | Store Var Var Cont -- ^ Store a value to a ref. | If Var Cont Cont -- ^ Conditionally follow one continuation or another. | Assert Var Cont -- ^ Assert a value and continue. | Assume Var Cont -- ^ State an assumption and continue. deriving Eq instance Show Cont where show a = case a of Halt -> "halt\n" Call a b Nothing -> printf "%s(%s)\n" a (intercalate ", " b) Call a b (Just c) -> printf "%s(%s)\n%s" a (intercalate ", " b) (show c) Return (Just a) -> printf "return %s\n" a Return Nothing -> "return\n" Push a b -> printf "push %s\n" a ++ show b If a b c -> printf "if (%s)\n" a ++ indent (show b) ++ "\nelse\n" ++ indent (show c) Assert a b -> printf "assert %s\n%s" a (show b) Assume a b -> printf "assume %s\n%s" a (show b) Let a b c -> printf "let %s = %s\n%s" a (show b) (show c) Store a b c -> printf "store %s = %s\n%s" a b (show c) indent :: String -> String indent = intercalate "\n" . map ("\t" ++) . lines -- | All the variables in a CPS program. variables :: [Proc] -> [Var] variables = nub . ("retval" :) . concatMap proc where proc :: Proc -> [Var] proc (Proc _ args _ body) = args ++ cont body cont :: Cont -> [Var] cont a = case a of Halt -> [] Call _ a b -> a ++ case b of { Nothing -> []; Just b -> cont b } Return (Just a) -> [a] Return Nothing -> [] Push a b -> a : cont b If a b c -> a : cont b ++ cont c Assert a b -> a : cont b Assume a b -> a : cont b Let a b c -> a : value b ++ cont c Store a b c -> [a, b] ++ cont c value :: Value -> [Var] value a = case a of Var a -> [a] Literal _ -> [] Pop -> [] Deref a -> [a] Alloc -> [] Array a -> a Struct a -> snd $ unzip a ArrayIndex a b -> [a, b] StructIndex a _ -> [a] Intrinsic _ a -> a -- | All free (unbound) variables in a continuation. contFreeVars :: Cont -> [Var] contFreeVars = nub . cont ["retval"] where cont :: [Var] -> Cont -> [Var] cont i a = case a of Call _ a b -> concatMap var a ++ case b of { Nothing -> []; Just a -> cont i a } Return Nothing -> [] Return (Just a) -> var a Push a b -> var a ++ cont i b Let a b c -> value b ++ cont (a : i) c Store a b c -> var a ++ var b ++ cont i c Halt -> [] If a b c -> var a ++ cont i b ++ cont i c Assert a b -> var a ++ cont i b Assume a b -> var a ++ cont i b where var :: Var -> [Var] var a = if elem a i then [] else [a] value :: Value -> [Var] value a = case a of Var a -> var a Literal _ -> [] Pop -> [] Deref a -> var a Alloc -> [] Array a -> concatMap var a Struct a -> concatMap var $ snd $ unzip a ArrayIndex a b -> var a ++ var b StructIndex a _ -> var a Intrinsic _ a -> concatMap var a -- | Convert a procedure to make explicit use of the stack to save and restore variables across procedure calls. explicitStack :: Proc -> Proc explicitStack (Proc name args measure body) = Proc name args measure $ cont body where cont :: Cont -> Cont cont a = case a of Call a b (Just c) -> f1 freeVars where freeVars = contFreeVars c f1 vars = case vars of [] -> Call a b $ Just $ f2 $ reverse freeVars a : b -> Push a $ f1 b f2 vars = case vars of [] -> cont c a : b -> Let a Pop $ f2 b Call a b Nothing -> Call a b Nothing Halt -> Halt Return a -> Return a Push a b -> Push a $ cont b If a b c -> If a (cont b) (cont c) Assert a b -> Assert a $ cont b Assume a b -> Assume a $ cont b Let a b c -> Let a b $ cont c Store a b c -> Store a b $ cont c -- | Replace a continuation given a pattern to match. replaceCont :: (Cont -> Maybe Cont) -> Cont -> Cont replaceCont replacement a = case replacement a of Just a -> a Nothing -> case a of Halt -> Halt Call a b c -> Call a b c Return a -> Return a Push a b -> Push a $ rep b Let a b c -> Let a b $ rep c Store a b c -> Store a b $ rep c If a b c -> If a (rep b) (rep c) Assert a b -> Assert a $ rep b Assume a b -> Assume a $ rep b where rep = replaceCont replacement -- | Common sub expression elim. commonSubExprElim :: Proc -> Proc commonSubExprElim (Proc name args measure body) = Proc name args measure $ elim [] [] body where elim :: [(Value, Var)] -> [(Var, Var)] -> Cont -> Cont elim env vars a = case a of Halt -> Halt Call a b Nothing -> Call a (map var b) Nothing Call a b (Just c) -> Call a (map var b) $ Just $ elim' c Return Nothing -> Return Nothing Return (Just a) -> Return $ Just $ var a Push a b -> Push (var a) $ elim' b Let a b c -> case b' of Var b -> elim env ((a, b) : vars) c _ -> case lookup b' env of Nothing -> Let a b' $ elim env' vars c Just a' -> elim env ((a, a') : vars) c where b' = value b env' = if stateful then env else (b', a) : env stateful :: Bool stateful = case b' of Pop -> True Alloc -> True _ -> False Store a b c -> Store (var a) (var b) $ elim' c If a b c -> If (var a) (elim' b) (elim' c) Assert a b -> Assert (var a) $ elim' b Assume a b -> Assume (var a) $ elim' b where elim' = elim env vars var :: Var -> Var var a = case lookup a vars of Nothing -> a Just b -> b value :: Value -> Value value a = case a of Var a -> Var $ var a Literal a -> Literal a Pop -> Pop Deref a -> Deref $ var a Alloc -> Alloc Array a -> Array $ map var a Struct a -> Struct [ (n, var v) | (n, v) <- a ] ArrayIndex a b -> ArrayIndex (var a) (var b) StructIndex a b -> StructIndex (var a) b Intrinsic a args -> Intrinsic a $ map var args -- | Remove assertions. removeAsserts :: Proc -> Proc removeAsserts (Proc name args measure body) = Proc name args measure $ r body where r :: Cont -> Cont r a = case a of Halt -> Halt Call a b Nothing -> Call a b Nothing Call a b (Just c) -> Call a b $ Just $ r c Return a -> Return a Push a b -> Push a $ r b Let a b c -> Let a b $ r c Store a b c -> Store a b $ r c If a b c -> If a (r b) (r c) Assert _ b -> r b Assume _ b -> r b -- | Remove unused lets. removeNullEffect :: Proc -> Proc removeNullEffect (Proc name args measure body) = Proc name args measure $ r body where r :: Cont -> Cont r a = case a of Halt -> Halt Call a b Nothing -> Call a b Nothing Call a b (Just c) -> Call a b $ Just $ r c Return a -> Return a Push a b -> Push a $ r b Let a b c' | elem a $ contFreeVars c -> Let a b c | otherwise -> c where c = r c' Store a b c -> Store a b $ r c If a b c -> If a (r b) (r c) Assert a b -> Assert a $ r b Assume a b -> Assume a $ r b
GaloisInc/ivory-backend-acl2
src/Ivory/Compile/ACL2/CPS.hs
Haskell
bsd-3-clause
10,661
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} -- | A wrapper around hoogle. module Stack.Hoogle ( hoogleCmd ) where import Stack.Prelude import qualified Data.ByteString.Lazy.Char8 as BL8 import Data.Char (isSpace) import qualified Data.Text as T import Distribution.PackageDescription (packageDescription, package) import Distribution.Types.PackageName (mkPackageName) import Distribution.Version (mkVersion) import Lens.Micro ((?~)) import Path (parseAbsFile) import Path.IO hiding (findExecutable) import qualified Stack.Build import Stack.Build.Target (NeedTargets(NeedTargets)) import Stack.Runners import Stack.Types.Config import Stack.Types.SourceMap import qualified RIO.Map as Map import RIO.Process -- | Helper type to duplicate log messages data Muted = Muted | NotMuted -- | Hoogle command. hoogleCmd :: ([String],Bool,Bool,Bool) -> RIO Runner () hoogleCmd (args,setup,rebuild,startServer) = local (over globalOptsL modifyGO) $ withConfig YesReexec $ withDefaultEnvConfig $ do hooglePath <- ensureHoogleInPath generateDbIfNeeded hooglePath runHoogle hooglePath args' where modifyGO :: GlobalOpts -> GlobalOpts modifyGO = globalOptsBuildOptsMonoidL . buildOptsMonoidHaddockL ?~ True args' :: [String] args' = if startServer then ["server", "--local", "--port", "8080"] else [] ++ args generateDbIfNeeded :: Path Abs File -> RIO EnvConfig () generateDbIfNeeded hooglePath = do databaseExists <- checkDatabaseExists if databaseExists && not rebuild then return () else if setup || rebuild then do logWarn (if rebuild then "Rebuilding database ..." else "No Hoogle database yet. Automatically building haddocks and hoogle database (use --no-setup to disable) ...") buildHaddocks logInfo "Built docs." generateDb hooglePath logInfo "Generated DB." else do logError "No Hoogle database. Not building one due to --no-setup" bail generateDb :: Path Abs File -> RIO EnvConfig () generateDb hooglePath = do do dir <- hoogleRoot createDirIfMissing True dir runHoogle hooglePath ["generate", "--local"] buildHaddocks :: RIO EnvConfig () buildHaddocks = do config <- view configL runRIO config $ -- a bit weird that we have to drop down like this catch (withDefaultEnvConfig $ Stack.Build.build Nothing) (\(_ :: ExitCode) -> return ()) hooglePackageName = mkPackageName "hoogle" hoogleMinVersion = mkVersion [5, 0] hoogleMinIdent = PackageIdentifier hooglePackageName hoogleMinVersion installHoogle :: RIO EnvConfig (Path Abs File) installHoogle = requiringHoogle Muted $ do Stack.Build.build Nothing mhooglePath' <- findExecutable "hoogle" case mhooglePath' of Right hooglePath -> parseAbsFile hooglePath Left _ -> do logWarn "Couldn't find hoogle in path after installing. This shouldn't happen, may be a bug." bail requiringHoogle :: Muted -> RIO EnvConfig x -> RIO EnvConfig x requiringHoogle muted f = do hoogleTarget <- do sourceMap <- view $ sourceMapL . to smDeps case Map.lookup hooglePackageName sourceMap of Just hoogleDep -> case dpLocation hoogleDep of PLImmutable pli -> T.pack . packageIdentifierString <$> restrictMinHoogleVersion muted (packageLocationIdent pli) plm@(PLMutable _) -> do T.pack . packageIdentifierString . package . packageDescription <$> loadCabalFile plm Nothing -> do -- not muted because this should happen only once logWarn "No hoogle version was found, trying to install the latest version" mpir <- getLatestHackageVersion YesRequireHackageIndex hooglePackageName UsePreferredVersions let hoogleIdent = case mpir of Nothing -> hoogleMinIdent Just (PackageIdentifierRevision _ ver _) -> PackageIdentifier hooglePackageName ver T.pack . packageIdentifierString <$> restrictMinHoogleVersion muted hoogleIdent config <- view configL let boptsCLI = defaultBuildOptsCLI { boptsCLITargets = [hoogleTarget] } runRIO config $ withEnvConfig NeedTargets boptsCLI f restrictMinHoogleVersion :: HasLogFunc env => Muted -> PackageIdentifier -> RIO env PackageIdentifier restrictMinHoogleVersion muted ident = do if ident < hoogleMinIdent then do muteableLog LevelWarn muted $ "Minimum " <> fromString (packageIdentifierString hoogleMinIdent) <> " is not in your index. Installing the minimum version." pure hoogleMinIdent else do muteableLog LevelInfo muted $ "Minimum version is " <> fromString (packageIdentifierString hoogleMinIdent) <> ". Found acceptable " <> fromString (packageIdentifierString ident) <> " in your index, requiring its installation." pure ident muteableLog :: HasLogFunc env => LogLevel -> Muted -> Utf8Builder -> RIO env () muteableLog logLevel muted msg = case muted of Muted -> pure () NotMuted -> logGeneric "" logLevel msg runHoogle :: Path Abs File -> [String] -> RIO EnvConfig () runHoogle hooglePath hoogleArgs = do config <- view configL menv <- liftIO $ configProcessContextSettings config envSettings dbpath <- hoogleDatabasePath let databaseArg = ["--database=" ++ toFilePath dbpath] withProcessContext menv $ proc (toFilePath hooglePath) (hoogleArgs ++ databaseArg) runProcess_ bail :: RIO EnvConfig a bail = exitWith (ExitFailure (-1)) checkDatabaseExists = do path <- hoogleDatabasePath liftIO (doesFileExist path) ensureHoogleInPath :: RIO EnvConfig (Path Abs File) ensureHoogleInPath = do config <- view configL menv <- liftIO $ configProcessContextSettings config envSettings mhooglePath <- runRIO menv (findExecutable "hoogle") <> requiringHoogle NotMuted (findExecutable "hoogle") eres <- case mhooglePath of Left _ -> return $ Left "Hoogle isn't installed." Right hooglePath -> do result <- withProcessContext menv $ proc hooglePath ["--numeric-version"] $ tryAny . fmap fst . readProcess_ let unexpectedResult got = Left $ T.concat [ "'" , T.pack hooglePath , " --numeric-version' did not respond with expected value. Got: " , got ] return $ case result of Left err -> unexpectedResult $ T.pack (show err) Right bs -> case parseVersion (takeWhile (not . isSpace) (BL8.unpack bs)) of Nothing -> unexpectedResult $ T.pack (BL8.unpack bs) Just ver | ver >= hoogleMinVersion -> Right hooglePath | otherwise -> Left $ T.concat [ "Installed Hoogle is too old, " , T.pack hooglePath , " is version " , T.pack $ versionString ver , " but >= 5.0 is required." ] case eres of Right hooglePath -> parseAbsFile hooglePath Left err | setup -> do logWarn $ display err <> " Automatically installing (use --no-setup to disable) ..." installHoogle | otherwise -> do logWarn $ display err <> " Not installing it due to --no-setup." bail envSettings = EnvSettings { esIncludeLocals = True , esIncludeGhcPackagePath = True , esStackExe = True , esLocaleUtf8 = False , esKeepGhcRts = False }
juhp/stack
src/Stack/Hoogle.hs
Haskell
bsd-3-clause
8,978
{-# LANGUAGE DataKinds, TypeOperators, TypeFamilies #-} {-# OPTIONS_GHC -fwarn-redundant-constraints #-} module TcTypeNatSimple where import GHC.TypeLits import Data.Proxy type family SomeFun (n :: Nat) -- See the ticket; whether this succeeds or fails is distinctly random -- upon creation, commit f861fc6ad8e5504a4fecfc9bb0945fe2d313687c, this failed -- with Simon's optimization to the flattening algorithm, commit -- 37b3646c9da4da62ae95aa3a9152335e485b261e, this succeeded -- with the change to stop Deriveds from rewriting Deriveds (around Dec. 12, 2014), -- this failed again -- 2016-01-23: it just started passing again, when -- -fwarn-redundant-constraints was removed from the default warning set. -- Turning the warning back on for this module, ghc reports (and probably has -- for some time): -- Redundant constraints: (x <= y, y <= x) -- In the type signature for: -- ti7 :: (x <= y, y <= x) => Proxy (SomeFun x) -> Proxy y -> () ti7 :: (x <= y, y <= x) => Proxy (SomeFun x) -> Proxy y -> () ti7 _ _ = ()
sdiehl/ghc
testsuite/tests/typecheck/should_compile/T9708.hs
Haskell
bsd-3-clause
1,047
{-# LANGUAGE DeriveDataTypeable #-} module HsTypeStruct where import Data.Generics -------- Types ----------------------------------------------------------------- data TI i t = HsTyFun t t -- | HsTyTuple [t] | HsTyApp t t | HsTyVar i | HsTyCon i | HsTyForall [i] [t] t -- forall is . Ps => t deriving (Ord,Eq,Show,Read, Data, Typeable)
kmate/HaRe
old/tools/base/AST/HsTypeStruct.hs
Haskell
bsd-3-clause
369
{-# OPTIONS_GHC -cpp #-} {-# OPTIONS -fglasgow-exts #-} {-# LANGUAGE MultiParamTypeClasses, OverlappingInstances, UndecidableInstances, FunctionalDependencies, NoMonomorphismRestriction #-} {-+ Type environments. For efficiency, a type environment is represented as a pair of an environment and the set of (nongeneric) type variables that occur free in the environment. The type checker needs this information when it generalizes a type, and traversing the whole environment every time is too costly. -} module TiTEnv(TEnv,extenv1,extenv,empty,TiTEnv.lookup,domain,range) where import HsIdent(HsIdentI) import TiTypes(Scheme,Types(..)) import TiNames(TypeVar) import qualified TiEnvFM as E import Set60204 #if __GLASGOW_HASKELL__ >= 604 import qualified Data.Set as S (Set) #else import qualified Sets as S (Set) #endif type TEnv' i = E.Env (HsIdentI i) (Scheme i) -- types of value identifiers data TEnv i = TEnv (TEnv' i) (S.Set i) extenv1 x t (TEnv env vs) = TEnv (E.extenv1 x t env) (vs `unionS` fromListS (tv t)) extenv bs1 (TEnv bs2 vs) = TEnv (E.extenv bs1 bs2) (vs `unionS` fromListS (tv (map snd bs1))) empty = TEnv E.empty emptyS lookup (TEnv env _) x = E.lookup env x domain (TEnv env _) = E.domain env range (TEnv env _) = E.range env --instance Functor TEnv where ... instance TypeVar i => Types i (TEnv i) where tv (TEnv env vs) = elemsS vs -- tmap -- of questionable use...
kmate/HaRe
old/tools/base/TI/TiTEnv.hs
Haskell
bsd-3-clause
1,402
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- This is a non-exposed internal module. -- -- This code contains utility function and data structures that are used -- to improve the efficiency of several instances in the Data.* namespace. ----------------------------------------------------------------------------- module Data.Functor.Utils where import Data.Coerce (Coercible, coerce) import GHC.Base ( Applicative(..), Functor(..), Maybe(..), Monoid(..), Ord(..) , Semigroup(..), ($), otherwise ) -- We don't expose Max and Min because, as Edward Kmett pointed out to me, -- there are two reasonable ways to define them. One way is to use Maybe, as we -- do here; the other way is to impose a Bounded constraint on the Monoid -- instance. We may eventually want to add both versions, but we don't want to -- trample on anyone's toes by imposing Max = MaxMaybe. newtype Max a = Max {getMax :: Maybe a} newtype Min a = Min {getMin :: Maybe a} -- | @since 4.11.0.0 instance Ord a => Semigroup (Max a) where {-# INLINE (<>) #-} m <> Max Nothing = m Max Nothing <> n = n (Max m@(Just x)) <> (Max n@(Just y)) | x >= y = Max m | otherwise = Max n -- | @since 4.8.0.0 instance Ord a => Monoid (Max a) where mempty = Max Nothing -- | @since 4.11.0.0 instance Ord a => Semigroup (Min a) where {-# INLINE (<>) #-} m <> Min Nothing = m Min Nothing <> n = n (Min m@(Just x)) <> (Min n@(Just y)) | x <= y = Min m | otherwise = Min n -- | @since 4.8.0.0 instance Ord a => Monoid (Min a) where mempty = Min Nothing -- left-to-right state transformer newtype StateL s a = StateL { runStateL :: s -> (s, a) } -- | @since 4.0 instance Functor (StateL s) where fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v) -- | @since 4.0 instance Applicative (StateL s) where pure x = StateL (\ s -> (s, x)) StateL kf <*> StateL kv = StateL $ \ s -> let (s', f) = kf s (s'', v) = kv s' in (s'', f v) liftA2 f (StateL kx) (StateL ky) = StateL $ \s -> let (s', x) = kx s (s'', y) = ky s' in (s'', f x y) -- right-to-left state transformer newtype StateR s a = StateR { runStateR :: s -> (s, a) } -- | @since 4.0 instance Functor (StateR s) where fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v) -- | @since 4.0 instance Applicative (StateR s) where pure x = StateR (\ s -> (s, x)) StateR kf <*> StateR kv = StateR $ \ s -> let (s', v) = kv s (s'', f) = kf s' in (s'', f v) liftA2 f (StateR kx) (StateR ky) = StateR $ \ s -> let (s', y) = ky s (s'', x) = kx s' in (s'', f x y) -- See Note [Function coercion] (#.) :: Coercible b c => (b -> c) -> (a -> b) -> (a -> c) (#.) _f = coerce {-# INLINE (#.) #-} {- Note [Function coercion] ~~~~~~~~~~~~~~~~~~~~~~~ Several functions here use (#.) instead of (.) to avoid potential efficiency problems relating to #7542. The problem, in a nutshell: If N is a newtype constructor, then N x will always have the same representation as x (something similar applies for a newtype deconstructor). However, if f is a function, N . f = \x -> N (f x) This looks almost the same as f, but the eta expansion lifts it--the lhs could be _|_, but the rhs never is. This can lead to very inefficient code. Thus we steal a technique from Shachaf and Edward Kmett and adapt it to the current (rather clean) setting. Instead of using N . f, we use N #. f, which is just coerce f `asTypeOf` (N . f) That is, we just *pretend* that f has the right type, and thanks to the safety of coerce, the type checker guarantees that nothing really goes wrong. We still have to be a bit careful, though: remember that #. completely ignores the *value* of its left operand. -}
ezyang/ghc
libraries/base/Data/Functor/Utils.hs
Haskell
bsd-3-clause
3,943
module D2 where y = 0 f z x = x + z f_gen = (y + 1) sumFun xs = sum $ (map (f (y + 1)) xs)
kmate/HaRe
old/testing/generaliseDef/D2_AstOut.hs
Haskell
bsd-3-clause
98
{-# LANGUAGE RecordWildCards #-} module T9437 where data Foo = Foo { x :: Int } test :: Foo -> Foo test foo = foo { .. }
ezyang/ghc
testsuite/tests/rename/should_fail/T9437.hs
Haskell
bsd-3-clause
124
-- Area of a Circle -- http://www.codewars.com/kata/537baa6f8f4b300b5900106c module Circle where circleArea :: Double -> Maybe Double circleArea r | r > 0 = Just( pi * r^2) | otherwise = Nothing
gafiatulin/codewars
src/7 kyu/Circle.hs
Haskell
mit
210
module Main where import System.Environment(getArgs) import Scheme(eval) -- The driver function for the executable parser that simply runs the parser on -- the first command-line argument and prints the resulting error or Expr. main :: IO () main = do args <- getArgs case eval (head args) of Left err -> print err Right res -> print res
mjdwitt/a-scheme
src/Main.hs
Haskell
mit
356
module Main where addOne :: Num a => a -> a addOne a = a + 1 addTwo :: Num a => a -> a addTwo a = a + 2 result :: Num b => [b] -> [b] result xs = map addOne xs main :: IO () main = do let ans = result [10] print ans
calvinchengx/learnhaskell
functors/functors.hs
Haskell
mit
233
import Control.Monad (replicateM, fmap, forM_) import Control.Parallel import Data.IORef import Data.List ((\\)) import Graphics.UI.GLUT import System.Random (getStdRandom, randomR, setStdGen, mkStdGen, getStdGen) import System.Random.Shuffle (shuffle') import qualified Data.Map as Map (findMax, findMin, fromList) initSeed = 997 numCities = 30 popSize = ceiling (fromIntegral numCities * 1.5) mutRate = 0.03 elitism = ceiling (fromIntegral popSize / 10) debug = False type City = (Float, Float) type Tour = [City] type Population = [Tour] type GLPoint = (GLfloat, GLfloat, GLfloat) randFloat :: Float -> Float -> IO Float randFloat a b = getStdRandom . randomR $ (a, b) randInt :: Int -> Int -> IO Int randInt a b = getStdRandom . randomR $ (a, b) randomCity :: IO City randomCity = do r1 <- randFloat 0 1 r2 <- randFloat 0 1 return (r1, r2) randomTour :: Int -> IO Tour randomTour 0 = return [] randomTour n = do rc <- randomCity rt <- randomTour (n - 1) return (rc : rt) shuffleTour :: Tour -> IO Tour shuffleTour [] = return [] shuffleTour t = do g <- getStdGen return $ shuffle' t (length t) g randomizedPop :: Int -> Tour -> IO Population randomizedPop 0 _ = return [] randomizedPop n t = do t' <- shuffleTour t ts <- randomizedPop (n - 1) t' return (t' : ts) distance :: City -> City -> Float distance (x1, y1) (x2, y2) = sqrt $ (x2 - x1)^2 + (y2 - y1)^2 tourDistance :: Tour -> Float tourDistance t@(x:xs) = sum $ zipWith distance t t' where t' = xs ++ [x] fitness :: Tour -> Float fitness = (1/) . tourDistance select :: Population -> IO Tour select [] = return [] select p = do i <- randInt 0 (length p - 1) r <- randFloat 0 1 if r < fitness (p !! i) / (maximum . map fitness $ p) then return (p !! i) else select p crossover :: Tour -> Tour -> IO Tour crossover [] _ = return [] crossover _ [] = return [] crossover m f = do i <- randInt 0 (length m - 1) j <- randInt i (length m - 1) let s = sub i j f return $ take i (m\\s) ++ s ++ drop i (m\\s) sub :: Int -> Int -> [a] -> [a] sub _ _ [] = [] sub i j t | i > j = sub j i t | otherwise = drop i . take (j + 1) $ t mutate :: Tour -> IO Tour mutate [] = return [] mutate t = do i <- randInt 0 (length t - 1) j <- randInt 0 (length t - 1) c <- randFloat 0 1 if c < mutRate then return . swap i j $ t else return t swap :: Int -> Int -> [a] -> [a] swap _ _ [] = [] swap i j l = map t $ zip [0..] l where t (k, v) | k == i = l !! j | k == j = l !! i | otherwise = v generateNewPop :: Int -> Population -> IO Population generateNewPop _ [] = return [] generateNewPop 0 _ = return [] generateNewPop n p = do m <- select p f <- select p c' <- crossover m f c <- fmap last . replicateM numCities $ mutate c' cs <- generateNewPop (n - 1) p return (c : cs) elite :: Int -> Population -> Population elite _ [] = [] elite 0 _ = [] elite n p = best : elite (n - 1) (p\\[best]) where best = snd . Map.findMax . Map.fromList . makeMap $ p makeMap :: Population -> [(Float, Tour)] makeMap [] = [] makeMap (t:ts) = (fitness t, t) `par` makeMap ts `pseq` (fitness t, t) : makeMap ts evolve :: Population -> IO Population evolve p = do let bestTours = elite elitism p np <- generateNewPop (popSize - elitism) p return (np ++ bestTours) nearest :: Tour -> Tour nearest [] = [] nearest (x:[]) = [x] nearest (x:xs) = x : nearest (snd best : (xs\\[snd best]) ) where best = Map.findMin (Map.fromList $ zip (map (distance x) xs) xs) altPop :: Int -> Tour -> Population altPop 0 _ = [] altPop n t = k : altPop (n - 1) t where k = nearest (take numCities . drop n . cycle $ t) main :: IO () main = do (_progName, _args) <- getArgsAndInitialize _window <- createWindow "TSP" if debug == True then setStdGen (mkStdGen initSeed) else return () destinationCities <- randomTour numCities let p1 = altPop numCities destinationCities p2 <- randomizedPop (popSize - numCities) destinationCities let p = p1 ++ p2 pv <- newIORef p gen <- newIORef 0 idleCallback $= Just (idle pv gen) displayCallback $= (display pv gen) mainLoop idle :: IORef Population -> IORef Int -> IdleCallback idle pv gen = do p <- get pv pn <- evolve p pv $= pn gen $~! (+1) postRedisplay Nothing display :: IORef Population -> IORef Int -> DisplayCallback display pv gen = do clear [ColorBuffer] loadIdentity p <- get pv g <- get gen let bestT = Map.findMax . Map.fromList . makeMap $ p let points = map cityToGLPoint (snd bestT) color $ Color3 0.6 0.6 (0.6 :: GLfloat) scale 0.9 0.9 (0.9 :: GLfloat) renderPrimitive LineLoop $ mapM_ (\(x,y,z) -> vertex $ Vertex3 x y z) points forM_ points $ \(x, y, z) -> preservingMatrix $ do color $ Color3 0.4 0.8 (0.4 :: GLfloat) translate $ Vector3 x y z square 0.02 translate $ Vector3 (- 1) 0.95 (0 :: GLfloat) scale 0.0005 0.0005 (0.0005 :: GLfloat) renderString MonoRoman ("Generation:" ++ show g ++ " Distance:" ++ show (1 / fst bestT)) flush cityToGLPoint :: City -> GLPoint cityToGLPoint (a, b) = (x, y, 0) where x = (realToFrac a) * 2 - 1 y = (realToFrac b) * 2 - 1 square :: GLfloat -> IO () square w = renderPrimitive Quads $ mapM_ vertex3f [ (-l, -l, 0), (l, -l, 0), ( l, l, 0), (-l, l, 0) ] where l = w/2 vertex3f :: (GLfloat, GLfloat, GLfloat) -> IO () vertex3f (x, y, z) = vertex $ Vertex3 x y z
7lb/tsp-haskell
nn.hs
Haskell
mit
5,837
----------------------------------------------------------------------------- -- -- Module : Parcial2.App -- Copyright : -- License : MIT -- -- Maintainer : - -- Stability : -- Portability : -- -- | -- module Parcial2.App where import Data.Maybe import Data.Typeable import GeneticAlgorithm import Parcial2.Labyrinth import CArgs ----------------------------------------------------------------------------- appDescr = [ "Searches the shortest path in a labyrinth with Genetic Algorithm." ] ----------------------------------------------------------------------------- ---- Arguments appArgs = CArgs { positionalArguments = Positional "Labyrinth File" text ["path to labyrinth file"] :. Positional "Population Size" int [] :. Nil , optionalArguments = [ Opt optChromGenMaxChains , Opt optChromGenMaxChainLen , Opt optMutateMaxChainsGen , Opt optMutateMaxChainLen , Opt optMaxUnchangedIter , Opt optMaxIters , Opt optSelIntactFrac , Opt optSelCrossoverFrac , Opt optSelMutateFrac , Opt optSelFracs , Opt helpArg ] } ----------------------------------------------------------------------------- ---- Options optChromGenMaxChains :: Optional1 Int optChromGenMaxChains = optional "" ["gen-max-chains"] ["Chromosome Generation: maximum chain number."] [] optChromGenMaxChainLen :: Optional1 Int optChromGenMaxChainLen = optional "" ["gen-max-chain-len"] ["Chromosome Generation: maximum chain length."] [] optMutateMaxChainsGen :: Optional1 Int optMutateMaxChainsGen = optional "" ["mut-max-chains"] ["Chromosome Mutation: maximum chains to insert."] [] optMutateMaxChainLen :: Optional1 Int optMutateMaxChainLen = optional "" ["mut-max-chain-len"] ["Chromosome Mutation: maximum insert chain length."] [] optMaxUnchangedIter :: Optional1 Int optMaxUnchangedIter = optional "U" ["max-unchanged"] ["Maximum number of iterations without best fitness change before stopping."] [] optMaxIters :: Optional1 Int optMaxIters = optional "I" ["max-iter"] ["Maximum number of iterations."] [] optSelIntactFrac :: Optional1 Float optSelIntactFrac = optional "" ["frac-intact"] ["Fraction of population left intact."] [] optSelCrossoverFrac :: Optional1 Float optSelCrossoverFrac = optional "" ["frac-crossover"] ["Fraction of population used for crossover."] [] optSelMutateFrac :: Optional1 Float optSelMutateFrac = optional "" ["frac-mutation"] ["Fraction of population used for mutation."] [] optSelFracs :: OptionalT3 Float Float Float optSelFracs = optional3' "f" ["fracs"] ["Set all the fractions at once."] "intact" ["intact fraction"] "crossover" ["crossover fraction"] "mutation" ["mutation fraction"] ----------------------------------------------------------------------------- ---- Defaults readParams opts = let orElse :: (Typeable a) => Optional vs a -> a -> a opt `orElse` def = fromMaybe def $ opts `get` opt intact' = optSelIntactFrac `orElse` 0.4 crossover' = optSelCrossoverFrac `orElse` 0.3 mutation' = optSelMutateFrac `orElse` 0.3 (intact, crossover, mutation) = optSelFracs `orElse` (intact', crossover', mutation') in GAParams { gaChromGenMaxChainLen = optChromGenMaxChainLen `orElse` 5 , gaChromGenMaxChains = optChromGenMaxChains `orElse` 3 , gaMutateMaxChainsGen = optMutateMaxChainsGen `orElse` 2 , gaMutateMaxChainLen = optMutateMaxChainLen `orElse` 3 , gaMaxUnchangedIter = optMaxUnchangedIter `orElse` 5 , gaMaxIters = optMaxIters `orElse` (10*1000) , gaSelIntactFrac = toRational intact , gaSelCrossoverFrac = toRational crossover , gaSelMutateFrac = toRational mutation } ----------------------------------------------------------------------------- ---- Assert assertPos name x | x < 1 = error $ "'" ++ name ++ "' cannot be less than 1." assertPos _ _ = return () assertUnit name x | x > 1 || x < 0 = error $ "'" ++ name ++ "' must be in [0,1]." | otherwise = return () assertSumOne precision msg vs | abs (1 - sum vs) > precision = error msg | otherwise = return () assertParams p = do assertPos "gen-max-chain-len" $ gaChromGenMaxChainLen p assertPos "gen-max-chais" $ gaChromGenMaxChains p assertPos "mut-max-chain-len" $ gaMutateMaxChainLen p assertPos "mut-max-chains" $ gaMutateMaxChainsGen p assertPos "max-unchanged" $ gaMaxUnchangedIter p assertPos "max-iter" $ gaMaxIters p assertUnit "frac-intact" $ gaSelIntactFrac p assertUnit "frac-crossover" $ gaSelCrossoverFrac p assertUnit "frac-mutation" $ gaSelMutateFrac p assertSumOne 0.0001 "The sum of fractions must be 1." $ ($p) <$> [ gaSelIntactFrac, gaSelCrossoverFrac, gaSelMutateFrac] ----------------------------------------------------------------------------- ---- Main appMain appName args = do let cargs = parseArgs appArgs args params = readParams (optionalValues cargs) (file, pop) = case positionalValues cargs of Right (file' :. pop' :. Nil) -> (text2str $ posValue file', posValue pop') labyrinth' <- readLabyrinth2D file let l = case labyrinth' of Left err -> error $ unlines err Right l -> l execGA = printAppResult =<< runApp l params pop withHelp appName appDescr appArgs cargs execGA runApp labyrinth params pop = do assertPos "population size" pop assertParams params ga <- newGA (labyrinth, params) :: IO GA runGA ga pop printAppResult (res, debug) = do putStrLn "DEBUG\n=====\n" print debug putStrLn "RESULT\n======\n" print res
fehu/itesm-ga
src/Parcial2/App.hs
Haskell
mit
6,832
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, InstanceSigs #-} module CompilerUtility (compilerSettings) where import Control.Applicative import Data.List.Utils import System.FilePath.Posix import System.IO import Data.ConfigFile import CompilationUtility import qualified ConfigFile import Printer import Utility data COMPILER_SETTINGS = COMPILER_SETTINGS { cs_executable :: FilePath, cs_options :: String, cs_compiler :: FilePath, cs_externs :: [FilePath], cs_readable :: String, cs_debug :: String, cs_flags :: String, cs_quick :: String, cs_standard :: String, cs_extended :: String, cs_js :: [FilePath], cs_js_output_file :: FilePath, cs_create_source_map :: FilePath, cs_property_renaming_report :: FilePath, cs_verbose :: Bool } instance UtilitySettings COMPILER_SETTINGS where executable = cs_executable toStringList cs = concat [ words $ cs_options cs, ["-jar", cs_compiler cs, "--js_output_file=" ++ (cs_js_output_file cs), "--create_source_map=" ++ (cs_create_source_map cs), "--property_renaming_report=" ++ (cs_property_renaming_report cs)], fmap ("--externs=" ++) $ cs_externs cs, words $ cs_readable cs, words $ cs_debug cs, words $ cs_flags cs, words $ cs_quick cs, words $ cs_standard cs, words $ cs_extended cs, fmap ("--js=" ++) $ cs_js cs] utitle _ = Just "Closure Compiler" verbose = cs_verbose compilerSettings :: ConfigParser -> [FilePath] -> EitherT String IO COMPILER_SETTINGS compilerSettings cp files = do readable <- hoistEither $ ConfigFile.getBool cp "DEFAULT" "readable" production <- hoistEither $ ConfigFile.getBool cp "DEFAULT" "production" quick <- hoistEither $ ConfigFile.getBool cp "DEFAULT" "quick" extended <- hoistEither $ ConfigFile.getBool cp "DEFAULT" "extended" COMPILER_SETTINGS <$> ConfigFile.getFile cp "DEFAULT" "utility.compiler.executable" <*> getString "utility.compiler.options" <*> ConfigFile.getFile cp "DEFAULT" "utility.compiler.compiler" <*> ConfigFile.getFiles cp "DEFAULT" "utility.compiler.externs" <*> (if readable then do getString "utility.compiler.readable" else return "") <*> (if not production then do getString "utility.compiler.debug" else return "") <*> getString "utility.compiler.flags" <*> getString "utility.compiler.quick" <*> (if not quick then do getString "utility.compiler.standard" else return "") <*> (if not quick && extended then do getString "utility.compiler.extended" else return "") <*> pure files <*> getString "utility.compiler.js_output_file" <*> getString "utility.compiler.create_source_map" <*> getString "utility.compiler.property_renaming_report" <*> (hoistEither $ ConfigFile.getBool cp "DEFAULT" "verbose") where getString :: String -> EitherT String IO String getString = hoistEither . ConfigFile.get cp "DEFAULT" instance CompilationUtility COMPILER_SETTINGS () where defaultValue :: COMPILER_SETTINGS -> () defaultValue _ = () failure :: UtilityResult COMPILER_SETTINGS -> EitherT String IO () failure r = do errors <- catchIO $ hGetContents $ ur_stderr r dPut [Failure, Str errors, Ln $ "Exit code: " ++ (show $ ur_exit_code r)] throwT "CompilerUtility failure" success :: UtilityResult COMPILER_SETTINGS -> EitherT String IO () success _ = dPut [Success]
Prinhotels/goog-closure
src/CompilerUtility.hs
Haskell
mit
3,421
{- DOC: Paste all the following commented lines in the file importing this module (don’t forget to update constant ‘filename’). import qualified SRC.Log as Log -- write code here -- boilerplate for logging filename = "-.hs" fatal :: Show a => String -> a -> b fatal msg line = Log.reportFatal filename msg line fixme, bug, err :: Show a => a -> b fixme = fatal L.fixMe bug = fatal L.bug err = fatal L.err -} module SRC.Log ( reportFatal , fixMe , bug , err ) where reportFatal :: Show a => String -> String -> a -> b reportFatal filename msg line = let message = filename ++ ":" ++ (show line) ++ ": " ++ msg in error message fixMe = "FixMe" bug = "BUG" err = "error"
Fornost461/drafts-and-stuff
Haskell/samples/Template/SRC/Log.hs
Haskell
cc0-1.0
716
{-# LANGUAGE OverloadedStrings #-} module Main where import Web.Scotty import Data.Monoid (mconcat) import Data.Time.Clock -- monoid main = scotty 3000 $ do get "/:word" $ do beam <- param "word" html $ mconcat ["<h1>Scotty, ", beam, " me up!</h1>"] -- mconcat = foldr mappend mempty -- functor offsetCurrentTime :: NominalDiffTime -> IO UTCTime offsetCurrentTime offset = fmap (addUTCTime (offset * 24 * 3600)) $ getCurrentTime
prt2121/haskell-practice
ch6-11-17-25/src/Main.hs
Haskell
apache-2.0
445
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Openshift.V1.ImageStreamTag where import GHC.Generics import Data.Text import Kubernetes.V1.ObjectMeta import Openshift.V1.Image import qualified Data.Aeson -- | data ImageStreamTag = ImageStreamTag { kind :: Maybe Text -- ^ Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#types-kinds , apiVersion :: Maybe Text -- ^ APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: http://releases.k8s.io/HEAD/docs/devel/api-conventions.md#resources , metadata :: Maybe ObjectMeta -- ^ , image :: Image -- ^ the image associated with the ImageStream and tag } deriving (Show, Eq, Generic) instance Data.Aeson.FromJSON ImageStreamTag instance Data.Aeson.ToJSON ImageStreamTag
minhdoboi/deprecated-openshift-haskell-api
openshift/lib/Openshift/V1/ImageStreamTag.hs
Haskell
apache-2.0
1,216
{-# LANGUAGE OverloadedStrings #-} -- Copyright 2014 (c) Diego Souza <dsouza@c0d3.xxx> -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. module Leela.Data.EventTree ( Distribution () , makeDistribution , stopDistribution , startDistribution , makeStartDistribution , attach , detach , publish , subscribe , unsubscribe ) where import Data.List (delete) import Data.IORef import Control.Monad import Leela.DataHelpers import Control.Concurrent import Control.Applicative data Distribution a b = Distribution { dThread :: MVar ThreadId , dSource :: MVar a , dSelect :: a -> Maybe b , dClients :: IORef [MVar b] } makeDistribution :: (a -> Maybe b) -> IO (Distribution a b) makeDistribution select = Distribution <$> newEmptyMVar <*> newEmptyMVar <*> pure select <*> newIORef [] makeStartDistribution :: (a -> Maybe b) -> IO (Distribution a b) makeStartDistribution select = do dist <- makeDistribution select startDistribution dist return dist startDistribution :: Distribution a b -> IO () startDistribution d = do pid <- forkFinally (forever $ do a <- takeMVar (dSource d) case (dSelect d a) of Nothing -> return () Just b -> distribute b =<< readIORef (dClients d)) (\_ -> void (tryTakeMVar (dSource d))) putMVar (dThread d) pid where distribute v group = do let limit = 1000 chunks = chunked limit group broadcast = mapM_ (flip putMVar v) if (length group < limit) then broadcast group else do wait <- newQSemN 0 mapM_ (flip forkFinally (\_ -> signalQSemN wait 1) . broadcast) chunks waitQSemN wait (length chunks) stopDistribution :: Distribution a b -> IO () stopDistribution d = maybe (return ()) killThread =<< tryTakeMVar (dThread d) attach :: Distribution a b -> Distribution b c -> IO () attach src dst = atomicModifyIORef' (dClients src) (\list -> (dSource dst : list, ())) detach :: Distribution a b -> Distribution b c -> IO () detach src dst = atomicModifyIORef' (dClients src) (\list -> (delete (dSource dst) list, ())) subscribe :: Distribution a b -> IO (MVar b) subscribe dist = do mvar <- newEmptyMVar atomicModifyIORef' (dClients dist) (\list -> (mvar : list, mvar)) unsubscribe :: Distribution a b -> MVar b -> IO () unsubscribe dist mvar = atomicModifyIORef' (dClients dist) (\list -> (delete mvar list, ())) publish :: Distribution a b -> a -> IO () publish dist = putMVar (dSource dist)
locaweb/leela
src/warpdrive/src/Leela/Data/EventTree.hs
Haskell
apache-2.0
3,232
module External.A143481Spec (main, spec) where import Test.Hspec import External.A143481 (a143481) main :: IO () main = hspec spec spec :: Spec spec = describe "A143481" $ it "correctly computes the first 20 elements" $ take 20 (map a143481 [1..]) `shouldBe` expectedValue where expectedValue = [1,2,6,8,20,24,42,48,54,64,110,112,120,132,144,160,192,216,288,320]
peterokagey/haskellOEIS
test/External/A143481Spec.hs
Haskell
apache-2.0
377
{-| Module describing an instance. The instance data type holds very few fields, the algorithm intelligence is in the "Node" and "Cluster" modules. -} {- 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.HTools.Instance ( Instance(..) , Disk(..) , AssocList , List , create , isRunning , isOffline , notOffline , instanceDown , usesSecMem , applyIfOnline , setIdx , setName , setAlias , setPri , setSec , setBoth , setMovable , specOf , getTotalSpindles , instBelowISpec , instAboveISpec , instMatchesPolicy , shrinkByType , localStorageTemplates , hasSecondary , requiredNodes , allNodes , usesLocalStorage , mirrorType ) where import Control.Monad (liftM2) import Ganeti.BasicTypes import qualified Ganeti.HTools.Types as T import qualified Ganeti.HTools.Container as Container import Ganeti.HTools.Nic (Nic) import Ganeti.Utils -- * Type declarations data Disk = Disk { dskSize :: Int -- ^ Size in bytes , dskSpindles :: Maybe Int -- ^ Number of spindles } deriving (Show, Eq) -- | The instance type. data Instance = Instance { name :: String -- ^ The instance name , alias :: String -- ^ The shortened name , mem :: Int -- ^ Memory of the instance , dsk :: Int -- ^ Total disk usage of the instance , disks :: [Disk] -- ^ Sizes of the individual disks , vcpus :: Int -- ^ Number of VCPUs , runSt :: T.InstanceStatus -- ^ Original run status , pNode :: T.Ndx -- ^ Original primary node , sNode :: T.Ndx -- ^ Original secondary node , idx :: T.Idx -- ^ Internal index , util :: T.DynUtil -- ^ Dynamic resource usage , movable :: Bool -- ^ Can and should the instance be moved? , autoBalance :: Bool -- ^ Is the instance auto-balanced? , diskTemplate :: T.DiskTemplate -- ^ The disk template of the instance , spindleUse :: Int -- ^ The numbers of used spindles , allTags :: [String] -- ^ List of all instance tags , exclTags :: [String] -- ^ List of instance exclusion tags , arPolicy :: T.AutoRepairPolicy -- ^ Instance's auto-repair policy , nics :: [Nic] -- ^ NICs of the instance } deriving (Show, Eq) instance T.Element Instance where nameOf = name idxOf = idx setAlias = setAlias setIdx = setIdx allNames n = [name n, alias n] -- | Check if instance is running. isRunning :: Instance -> Bool isRunning (Instance {runSt = T.Running}) = True isRunning (Instance {runSt = T.ErrorUp}) = True isRunning _ = False -- | Check if instance is offline. isOffline :: Instance -> Bool isOffline (Instance {runSt = T.StatusOffline}) = True isOffline _ = False -- | Helper to check if the instance is not offline. notOffline :: Instance -> Bool notOffline = not . isOffline -- | Check if instance is down. instanceDown :: Instance -> Bool instanceDown inst | isRunning inst = False instanceDown inst | isOffline inst = False instanceDown _ = True -- | Apply the function if the instance is online. Otherwise use -- the initial value applyIfOnline :: Instance -> (a -> a) -> a -> a applyIfOnline = applyIf . notOffline -- | Helper for determining whether an instance's memory needs to be -- taken into account for secondary memory reservation. usesSecMem :: Instance -> Bool usesSecMem inst = notOffline inst && autoBalance inst -- | Constant holding the local storage templates. -- -- /Note:/ Currently Ganeti only exports node total/free disk space -- for LVM-based storage; file-based storage is ignored in this model, -- so even though file-based storage uses in reality disk space on the -- node, in our model it won't affect it and we can't compute whether -- there is enough disk space for a file-based instance. Therefore we -- will treat this template as \'foreign\' storage. localStorageTemplates :: [T.DiskTemplate] localStorageTemplates = [ T.DTDrbd8, T.DTPlain ] -- | Constant holding the movable disk templates. -- -- This only determines the initial 'movable' state of the -- instance. Further the movable state can be restricted more due to -- user choices, etc. movableDiskTemplates :: [T.DiskTemplate] movableDiskTemplates = [ T.DTDrbd8 , T.DTBlock , T.DTSharedFile , T.DTGluster , T.DTRbd , T.DTExt ] -- | A simple name for the int, instance association list. type AssocList = [(T.Idx, Instance)] -- | A simple name for an instance map. type List = Container.Container Instance -- * Initialization -- | Create an instance. -- -- Some parameters are not initialized by function, and must be set -- later (via 'setIdx' for example). create :: String -> Int -> Int -> [Disk] -> Int -> T.InstanceStatus -> [String] -> Bool -> T.Ndx -> T.Ndx -> T.DiskTemplate -> Int -> [Nic] -> Instance create name_init mem_init dsk_init disks_init vcpus_init run_init tags_init auto_balance_init pn sn dt su nics_init = Instance { name = name_init , alias = name_init , mem = mem_init , dsk = dsk_init , disks = disks_init , vcpus = vcpus_init , runSt = run_init , pNode = pn , sNode = sn , idx = -1 , util = T.baseUtil , movable = supportsMoves dt , autoBalance = auto_balance_init , diskTemplate = dt , spindleUse = su , allTags = tags_init , exclTags = [] , arPolicy = T.ArNotEnabled , nics = nics_init } -- | Changes the index. -- -- This is used only during the building of the data structures. setIdx :: Instance -- ^ The original instance -> T.Idx -- ^ New index -> Instance -- ^ The modified instance setIdx t i = t { idx = i } -- | Changes the name. -- -- This is used only during the building of the data structures. setName :: Instance -- ^ The original instance -> String -- ^ New name -> Instance -- ^ The modified instance setName t s = t { name = s, alias = s } -- | Changes the alias. -- -- This is used only during the building of the data structures. setAlias :: Instance -- ^ The original instance -> String -- ^ New alias -> Instance -- ^ The modified instance setAlias t s = t { alias = s } -- * Update functions -- | Changes the primary node of the instance. setPri :: Instance -- ^ the original instance -> T.Ndx -- ^ the new primary node -> Instance -- ^ the modified instance setPri t p = t { pNode = p } -- | Changes the secondary node of the instance. setSec :: Instance -- ^ the original instance -> T.Ndx -- ^ the new secondary node -> Instance -- ^ the modified instance setSec t s = t { sNode = s } -- | Changes both nodes of the instance. setBoth :: Instance -- ^ the original instance -> T.Ndx -- ^ new primary node index -> T.Ndx -- ^ new secondary node index -> Instance -- ^ the modified instance setBoth t p s = t { pNode = p, sNode = s } -- | Sets the movable flag on an instance. setMovable :: Instance -- ^ The original instance -> Bool -- ^ New movable flag -> Instance -- ^ The modified instance setMovable t m = t { movable = m } -- | Try to shrink the instance based on the reason why we can't -- allocate it. shrinkByType :: Instance -> T.FailMode -> Result Instance shrinkByType inst T.FailMem = let v = mem inst - T.unitMem in if v < T.unitMem then Bad "out of memory" else Ok inst { mem = v } shrinkByType inst T.FailDisk = let newdisks = [d {dskSize = dskSize d - T.unitDsk}| d <- disks inst] v = dsk inst - (length . disks $ inst) * T.unitDsk in if any (< T.unitDsk) $ map dskSize newdisks then Bad "out of disk" else Ok inst { dsk = v, disks = newdisks } shrinkByType inst T.FailCPU = let v = vcpus inst - T.unitCpu in if v < T.unitCpu then Bad "out of vcpus" else Ok inst { vcpus = v } shrinkByType inst T.FailSpindles = case disks inst of [Disk ds sp] -> case sp of Nothing -> Bad "No spindles, shouldn't have happened" Just sp' -> let v = sp' - T.unitSpindle in if v < T.unitSpindle then Bad "out of spindles" else Ok inst { disks = [Disk ds (Just v)] } d -> Bad $ "Expected one disk, but found " ++ show d shrinkByType _ f = Bad $ "Unhandled failure mode " ++ show f -- | Get the number of disk spindles getTotalSpindles :: Instance -> Maybe Int getTotalSpindles inst = foldr (liftM2 (+) . dskSpindles ) (Just 0) (disks inst) -- | Return the spec of an instance. specOf :: Instance -> T.RSpec specOf Instance { mem = m, dsk = d, vcpus = c, disks = dl } = let sp = case dl of [Disk _ (Just sp')] -> sp' _ -> 0 in T.RSpec { T.rspecCpu = c, T.rspecMem = m, T.rspecDsk = d, T.rspecSpn = sp } -- | Checks if an instance is smaller/bigger than a given spec. Returns -- OpGood for a correct spec, otherwise Bad one of the possible -- failure modes. instCompareISpec :: Ordering -> Instance-> T.ISpec -> Bool -> T.OpResult () instCompareISpec which inst ispec exclstor | which == mem inst `compare` T.iSpecMemorySize ispec = Bad T.FailMem | which `elem` map ((`compare` T.iSpecDiskSize ispec) . dskSize) (disks inst) = Bad T.FailDisk | which == vcpus inst `compare` T.iSpecCpuCount ispec = Bad T.FailCPU | exclstor && case getTotalSpindles inst of Nothing -> True Just sp_sum -> which == sp_sum `compare` T.iSpecSpindleUse ispec = Bad T.FailSpindles | not exclstor && which == spindleUse inst `compare` T.iSpecSpindleUse ispec = Bad T.FailSpindles | diskTemplate inst /= T.DTDiskless && which == length (disks inst) `compare` T.iSpecDiskCount ispec = Bad T.FailDiskCount | otherwise = Ok () -- | Checks if an instance is smaller than a given spec. instBelowISpec :: Instance -> T.ISpec -> Bool -> T.OpResult () instBelowISpec = instCompareISpec GT -- | Checks if an instance is bigger than a given spec. instAboveISpec :: Instance -> T.ISpec -> Bool -> T.OpResult () instAboveISpec = instCompareISpec LT -- | Checks if an instance matches a min/max specs pair instMatchesMinMaxSpecs :: Instance -> T.MinMaxISpecs -> Bool -> T.OpResult () instMatchesMinMaxSpecs inst minmax exclstor = do instAboveISpec inst (T.minMaxISpecsMinSpec minmax) exclstor instBelowISpec inst (T.minMaxISpecsMaxSpec minmax) exclstor -- | Checks if an instance matches any specs of a policy instMatchesSpecs :: Instance -> [T.MinMaxISpecs] -> Bool -> T.OpResult () -- Return Ok for no constraints, though this should never happen instMatchesSpecs _ [] _ = Ok () instMatchesSpecs inst minmaxes exclstor = -- The initial "Bad" should be always replaced by a real result foldr eithermatch (Bad T.FailInternal) minmaxes where eithermatch mm (Bad _) = instMatchesMinMaxSpecs inst mm exclstor eithermatch _ y@(Ok ()) = y -- | Checks if an instance matches a policy. instMatchesPolicy :: Instance -> T.IPolicy -> Bool -> T.OpResult () instMatchesPolicy inst ipol exclstor = do instMatchesSpecs inst (T.iPolicyMinMaxISpecs ipol) exclstor if diskTemplate inst `elem` T.iPolicyDiskTemplates ipol then Ok () else Bad T.FailDisk -- | Checks whether the instance uses a secondary node. -- -- /Note:/ This should be reconciled with @'sNode' == -- 'Node.noSecondary'@. hasSecondary :: Instance -> Bool hasSecondary = (== T.DTDrbd8) . diskTemplate -- | Computed the number of nodes for a given disk template. requiredNodes :: T.DiskTemplate -> Int requiredNodes T.DTDrbd8 = 2 requiredNodes _ = 1 -- | Computes all nodes of an instance. allNodes :: Instance -> [T.Ndx] allNodes inst = case diskTemplate inst of T.DTDrbd8 -> [pNode inst, sNode inst] _ -> [pNode inst] -- | Checks whether a given disk template uses local storage. usesLocalStorage :: Instance -> Bool usesLocalStorage = (`elem` localStorageTemplates) . diskTemplate -- | Checks whether a given disk template supported moves. supportsMoves :: T.DiskTemplate -> Bool supportsMoves = (`elem` movableDiskTemplates) -- | A simple wrapper over 'T.templateMirrorType'. mirrorType :: Instance -> T.MirrorType mirrorType = T.templateMirrorType . diskTemplate
ganeti-github-testing/ganeti-test-1
src/Ganeti/HTools/Instance.hs
Haskell
bsd-2-clause
13,980
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} -- | Observation schema blocks for Nerf. module NLP.Nerf.Schema ( -- * Types Ox , Schema , void , sequenceS_ -- * Usage , schematize -- ** Configuration , Body (..) , Entry , entry , entryWith , SchemaConf (..) , nullConf , defaultConf , fromConf -- ** Schema blocks , Block , fromBlock , orthB , splitOrthB , lowPrefixesB , lowSuffixesB , lemmaB , shapeB , packedB , shapePairB , packedPairB , dictB ) where import Prelude hiding (Word) import Control.Applicative ((<$>), (<*>)) import Control.Monad (forM_, join) import Data.Maybe (maybeToList) import Data.Binary (Binary, put, get) import qualified Data.Char as C import qualified Data.Set as S import qualified Data.Vector as V import qualified Data.Text as T import qualified Data.DAWG.Static as D import qualified Data.CRF.Chain1 as CRF import qualified Control.Monad.Ox as Ox import qualified Control.Monad.Ox.Text as Ox import NLP.Nerf.Types import NLP.Nerf.Dict (Dict) -- | The Ox monad specialized to word token type and text observations. type Ox a = Ox.Ox Word T.Text a -- | A schema is a block of the Ox computation performed within the -- context of the sentence and the absolute sentence position. type Schema a = V.Vector Word -> Int -> Ox a -- | A dummy schema block. void :: a -> Schema a void x _ _ = return x -- | Sequence the list of schemas (or blocks) and discard individual values. sequenceS_ :: [V.Vector Word -> a -> Ox b] -> V.Vector Word -> a -> Ox () sequenceS_ xs sent = let ys = map ($sent) xs in \k -> sequence_ (map ($k) ys) -- | Record structure of the basic observation types. data BaseOb = BaseOb { orth :: Int -> Maybe T.Text , lowOrth :: Int -> Maybe T.Text } -- | Construct the 'BaseOb' structure given the sentence. mkBaseOb :: V.Vector Word -> BaseOb mkBaseOb sent = BaseOb { orth = _orth , lowOrth = _lowOrth } where at = Ox.atWith sent _orth = (id `at`) _lowOrth i = T.toLower <$> _orth i -- | A block is a chunk of the Ox computation performed within the -- context of the sentence and the list of absolute sentence positions. type Block a = V.Vector Word -> [Int] -> Ox a -- | Transform the block to the schema depending on the list of -- relative sentence positions. fromBlock :: Block a -> [Int] -> Schema a fromBlock blk xs sent = let blkSent = blk sent in \k -> blkSent [x + k | x <- xs] -- | Orthographic form at the current position. orthB :: Block () orthB sent = \ks -> let orthOb = Ox.atWith sent id in mapM_ (Ox.save . orthOb) ks -- | Orthographic form split into two observations: the lowercased form and -- the original form (only when different than the lowercased one). splitOrthB :: Block () splitOrthB sent = \ks -> do mapM_ (Ox.save . lowOrth) ks mapM_ (Ox.save . upOnlyOrth) ks where BaseOb{..} = mkBaseOb sent upOnlyOrth i = orth i >>= \x -> case T.any C.isUpper x of True -> Just x False -> Nothing -- | List of lowercased prefixes of given lengths. lowPrefixesB :: [Int] -> Block () lowPrefixesB ns sent = \ks -> forM_ ks $ \i -> mapM_ (Ox.save . lowPrefix i) ns where BaseOb{..} = mkBaseOb sent lowPrefix i j = Ox.prefix j =<< lowOrth i -- | List of lowercased suffixes of given lengths. lowSuffixesB :: [Int] -> Block () lowSuffixesB ns sent = \ks -> forM_ ks $ \i -> mapM_ (Ox.save . lowSuffix i) ns where BaseOb{..} = mkBaseOb sent lowSuffix i j = Ox.suffix j =<< lowOrth i -- | Lemma substitute parametrized by the number specifying the span -- over which lowercased prefixes and suffixes will be 'Ox.save'd. -- For example, @lemmaB 2@ will take affixes of lengths @0, -1@ and @-2@ -- on account. lemmaB :: Int -> Block () lemmaB n sent = \ks -> do mapM_ lowLemma ks where BaseOb{..} = mkBaseOb sent lowPrefix i j = Ox.prefix j =<< lowOrth i lowSuffix i j = Ox.suffix j =<< lowOrth i lowLemma i = Ox.group $ do mapM_ (Ox.save . lowPrefix i) [0, -1 .. -n] mapM_ (Ox.save . lowSuffix i) [0, -1 .. -n] -- | Shape of the word. shapeB :: Block () shapeB sent = \ks -> do mapM_ (Ox.save . shape) ks where BaseOb{..} = mkBaseOb sent shape i = Ox.shape <$> orth i -- | Packed shape of the word. packedB :: Block () packedB sent = \ks -> do mapM_ (Ox.save . shapeP) ks where BaseOb{..} = mkBaseOb sent shape i = Ox.shape <$> orth i shapeP i = Ox.pack <$> shape i -- -- | Shape and packed shape of the word. -- shapeAndPackedB :: Block () -- shapeAndPackedB sent = \ks -> do -- mapM_ (Ox.save . shape) ks -- mapM_ (Ox.save . shapeP) ks -- where -- BaseOb{..} = mkBaseOb sent -- shape i = Ox.shape <$> orth i -- shapeP i = Ox.pack <$> shape i -- | Combined shapes of two consecutive (at @k-1@ and @k@ positions) words. shapePairB :: Block () shapePairB sent = \ks -> forM_ ks $ \i -> do Ox.save $ link <$> shape i <*> shape (i - 1) where BaseOb{..} = mkBaseOb sent shape i = Ox.shape <$> orth i link x y = T.concat [x, "-", y] -- | Combined packed shapes of two consecutive (at @k-1@ and @k@ positions) -- words. packedPairB :: Block () packedPairB sent = \ks -> forM_ ks $ \i -> do Ox.save $ link <$> shapeP i <*> shapeP (i - 1) where BaseOb{..} = mkBaseOb sent shape i = Ox.shape <$> orth i shapeP i = Ox.pack <$> shape i link x y = T.concat [x, "-", y] -- | Plain dictionary search determined with respect to the list of -- relative positions. dictB :: Dict -> Block () dictB dict sent = \ks -> do mapM_ (Ox.saves . searchDict) ks where BaseOb{..} = mkBaseOb sent searchDict i = join . maybeToList $ S.toList <$> (orth i >>= flip D.lookup dict . T.unpack) -- | Body of configuration entry. data Body a = Body { -- | Range argument for the schema block. range :: [Int] -- | Additional arguments for the schema block. , args :: a } deriving (Show) instance Binary a => Binary (Body a) where put Body{..} = put range >> put args get = Body <$> get <*> get -- | Maybe entry. type Entry a = Maybe (Body a) -- | Entry with additional arguemnts. entryWith :: a -> [Int] -> Entry a entryWith v xs = Just (Body xs v) -- | Maybe entry with additional arguemnts. entryWith'Mb :: Maybe a -> [Int] -> Entry a entryWith'Mb (Just v) xs = Just (Body xs v) entryWith'Mb Nothing _ = Nothing -- | Plain entry with no additional arugments. entry :: [Int] -> Entry () entry = entryWith () -- | Configuration of the schema. All configuration elements specify the -- range over which a particular observation type should be taken on account. -- For example, the @[-1, 0, 2]@ range means that observations of particular -- type will be extracted with respect to previous (@k - 1@), current (@k@) -- and after the next (@k + 2@) positions when identifying the observation -- set for position @k@ in the input sentence. data SchemaConf = SchemaConf { -- | The 'orthB' schema block. orthC :: Entry () -- | The 'splitOrthB' schema block. , splitOrthC :: Entry () -- | The 'lowPrefixesB' schema block. The first list of ints -- represents lengths of prefixes. , lowPrefixesC :: Entry [Int] -- | The 'lowSuffixesB' schema block. The first list of ints -- represents lengths of suffixes. , lowSuffixesC :: Entry [Int] -- | The 'lemmaB' schema block. , lemmaC :: Entry Int -- | The 'shapeB' schema block. , shapeC :: Entry () -- | The 'packedB' schema block. , packedC :: Entry () -- | The 'shapePairB' schema block. , shapePairC :: Entry () -- | The 'packedPairB' schema block. , packedPairC :: Entry () -- | Dictionaries of NEs ('dictB' schema block). , dictC :: Entry [Dict] -- | Dictionary of internal triggers. , intTrigsC :: Entry Dict -- | Dictionary of external triggers. , extTrigsC :: Entry Dict } deriving (Show) instance Binary SchemaConf where put SchemaConf{..} = do put orthC put splitOrthC put lowPrefixesC put lowSuffixesC put lemmaC put shapeC put packedC put shapePairC put packedPairC put dictC put intTrigsC put extTrigsC get = SchemaConf <$> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get <*> get -- | Null configuration of the observation schema. nullConf :: SchemaConf nullConf = SchemaConf Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing -- | Default configuration of the observation schema. defaultConf :: [Dict] -- ^ Named Entity dictionaries -> Maybe Dict -- ^ Dictionary of internal triggers -> Maybe Dict -- ^ Dictionary of external triggers -> IO SchemaConf defaultConf neDicts intDict extDict = do return $ SchemaConf { orthC = Nothing , splitOrthC = entry [-1, 0] , lowPrefixesC = Nothing , lowSuffixesC = entryWith [2, 3, 4] [0] , lemmaC = entryWith 3 [-1, 0] , shapeC = entry [-1, 0] , packedC = entry [-1, 0] , shapePairC = entry [0] , packedPairC = entry [0] , dictC = entryWith neDicts [-1, 0] , intTrigsC = entryWith'Mb intDict [0] , extTrigsC = entryWith'Mb extDict [-1] } mkArg0 :: Block () -> Entry () -> Schema () mkArg0 blk (Just x) = fromBlock blk (range x) mkArg0 _ Nothing = void () mkArg1 :: (a -> Block ()) -> Entry a -> Schema () mkArg1 blk (Just x) = fromBlock (blk (args x)) (range x) mkArg1 _ Nothing = void () mkArgs1 :: (a -> Block ()) -> Entry [a] -> Schema () mkArgs1 blk (Just x) = sequenceS_ [ fromBlock (blk dict) (range x) | dict <- args x ] mkArgs1 _ Nothing = void () -- | Build the schema based on the configuration. fromConf :: SchemaConf -> Schema () fromConf SchemaConf{..} = sequenceS_ [ mkArg0 orthB orthC , mkArg0 splitOrthB splitOrthC , mkArg1 lowPrefixesB lowPrefixesC , mkArg1 lowSuffixesB lowSuffixesC , mkArg1 lemmaB lemmaC , mkArg0 shapeB shapeC , mkArg0 packedB packedC , mkArg0 shapePairB shapePairC , mkArg0 packedPairB packedPairC , mkArgs1 dictB dictC , mkArg1 dictB intTrigsC , mkArg1 dictB extTrigsC ] -- | Use the schema to extract observations from the sentence. schematize :: Schema a -> [Word] -> CRF.Sent Ob schematize schema xs = map (S.fromList . Ox.execOx . schema v) [0 .. n - 1] where v = V.fromList xs n = V.length v
kawu/nerf
src/NLP/Nerf/Schema.hs
Haskell
bsd-2-clause
11,056
module Utilities.Bits where import Emulator.Types import Data.Bits import Data.Int -- This is what the halfWordExtend function is doing but we've opted for -- the fromIntegral approach which has a chance to be faster (untested) --halfWordExtend :: HalfWord -> MWord --halfWordExtend h = val .|. orVal -- where -- val = fromIntegral (h .&. 0xFFFF) :: MWord -- orVal = case testBit h 15 of -- True -> 0xFFFF0000 -- False -> 0x00000000 halfWordExtend :: HalfWord -> MWord halfWordExtend h = fromIntegral (fromIntegral (fromIntegral h :: Int16) :: Int32) byteExtend :: Byte -> MWord byteExtend b = fromIntegral (fromIntegral (fromIntegral b :: Int8) :: Int32) arithExtend :: MWord -> Int -> MWord arithExtend v n = clearBit (if (testBit v n) then setBit v 31 else v) n -- For when we cant use the TemplateHaskell version staticBitmask :: Int -> Int -> MWord -> MWord staticBitmask x y w = (w .&. mask) `shiftR` y where a, b :: MWord a = 1 `shiftL` fromIntegral x b = 1 `shiftL` fromIntegral y mask :: MWord mask = ((a - 1) .&. complement (b - 1)) .|. a
intolerable/GroupProject
src/Utilities/Bits.hs
Haskell
bsd-2-clause
1,095
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExtendedDefaultRules #-} {-# LANGUAGE ForeignFunctionInterface #-} module Main where -- External dependencies imports -- import CATerms -- import Filesystem hiding (writeFile, readFile, withFile, openFile) -- import Language.Java.Pretty -- import Language.Java.Syntax -- import qualified Filesystem as FS import ATerm.AbstractSyntax import ATerm.Generics as G import ATerm.ReadWrite import ATerm.Unshared import Codec.Archive.Zip import Control.Applicative import Control.Exception.Base import Control.Monad import Control.Monad.State import Data.List import Data.Maybe import Data.String import Data.Tree import Data.Tree.ATerm import Data.Tree.AntiUnification import Data.Tree.Types import Data.Tree.Weaver import Data.Tree.Yang import Data.Vector (Vector) import Filesystem.Path hiding (concat, (<.>), null) import Foreign.C.Types import Foreign.ForeignPtr import Foreign.Marshal.Array import Foreign.Ptr import JavaATerms () import Language.Java.Parser import Prelude hiding (FilePath) import Shelly hiding (FilePath, (</>),get,put) import System.Console.GetOpt import System.Environment import System.Exit import System.IO hiding (FilePath) import Text.CSV import WeaveUtils import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as BL import qualified Data.Map as M import qualified Data.Set as S import qualified Data.Text as T import qualified Data.Vector as V -- Recommended by Shelly default (T.Text) ----------------------------------------------------------------------- -- * Option Parsing data Options = Options { optVerbose :: Bool , optSandbox :: FilePath , optMode :: Mode , optThreshold :: Double , optNumChanges:: Int } data Mode = GenerateATerms | AntiUnifyATerms | AntiUnifyGroup | Graphviz | Unparse | Weave | Similarity deriving (Read, Show, Eq, Ord) defaultOptions :: Options defaultOptions = Options { optVerbose = False , optSandbox = "/tmp/version-patterns" , optMode = GenerateATerms , optThreshold = 0 , optNumChanges = 100 } options :: [ OptDescr (Options -> IO Options) ] options = [ Option "s" ["sandbox"] (ReqArg (\arg o -> return o { optSandbox = fromString arg }) "DIRECTORY") "Directory for storing or reading aterms" , Option "v" ["verbose"] (NoArg (\o -> return o { optVerbose = True })) "Enable verbose output" , Option "m" ["mode"] (ReqArg (\arg o -> do let mode = fromMaybe (error "Unrecognized mode") (parseMode arg) return o { optMode = mode }) "MODE") "Mode of operation, MODE is one of: generate-aterms, antiunify-aterms, antiunify-group, graphviz, similarity, unparse, weave" , Option "t" ["threshold"] (ReqArg (\arg o -> do let threshold = read arg :: Double threshold `seq` return o { optThreshold = threshold }) "THRESHOLD") "Threshold for similarity, as a floating point value, in the range [0..1]" , Option "n" ["num"] (ReqArg (\arg o -> do let num = read arg :: Int num `seq` return o { optNumChanges = num }) "NUM") "The number of changes to consume" , Option "h" ["help"] (NoArg (\_ -> do prg <- getProgName hPutStrLn stderr (usageInfo prg options) exitWith ExitSuccess)) "Show help" ] parseMode :: String -> Maybe Mode parseMode "generate-aterms" = Just GenerateATerms parseMode "antiunify-aterms" = Just AntiUnifyATerms parseMode "antiunify-group" = Just AntiUnifyGroup parseMode "graphviz" = Just Graphviz parseMode "similarity" = Just Similarity parseMode "unparse" = Just Unparse parseMode "weave" = Just Weave parseMode _ = Nothing ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- * Git Diff -- Ignore permissons on files: -- drivers/char/mmtimer.c /tmp/IV5Cnd_mmtimer.c 58eddfdd3110a3a7168f2b8bdbfabefb9691016a 100644 /tmp/9W7Cnd_mmtimer.c 12006182f575a4f3cd09827bcaaea6523077e7b3 100644 data GitDiffArgs = GitDiffArgs { gdaFilePath :: T.Text , gdaBeforeCommit :: T.Text , gdaAfterCommit :: T.Text } deriving (Show, Read, Eq, Ord) ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- * Main program main :: IO () main = do args <- getArgs let (actions, rest, _) = getOpt RequireOrder options args opts <- foldl (>>=) (return defaultOptions) actions let verbosity = if optVerbose opts then verbosely else silently shelly $ verbosity $ do case optMode opts of GenerateATerms -> generateTerms (optSandbox opts) AntiUnifyATerms -> processTerms (optSandbox opts) AntiUnifyGroup -> antiUnifyTerms (optSandbox opts) "antiunify.gv" (map read rest) Graphviz -> generateGraphs (optSandbox opts) Similarity -> similarTrees (optSandbox opts) (optThreshold opts) Unparse -> unparseTerms (optSandbox opts) Weave -> weaveTerms (optSandbox opts) (optNumChanges opts) ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- * Heavy lifting -- | generateTerms Assumes that the current working directory is a git repository. -- It builds a list of pairs from the history of the repository. Visits each of those -- commits and requests the arguments that git-diff would use between those versions. -- Then it parses the source code that changed between each revision in the context it was -- commited in. The parsed representations are saved as ATerms in a zip archive. generateTerms :: FilePath -> Sh () generateTerms sandbox = do -- We add "master" so that if the repo is currently at a weird revision or branch, we get -- reasonable view of the history of master. cs <- T.lines <$> run "git" ["log", "master", "--pretty=format:%H", "--reverse"] -- TODO: use the full history let pairs = {- take 10 -} (zip cs (drop 1 cs)) -- Log the version pairs for later processing mkdir_p sandbox let initArchive = versionPairs `addEntryToArchive` emptyArchive versionPairsFP = "version-pairs.hs" :: String versionPairs = toEntry versionPairsFP 0 (BL.pack (show pairs)) archiveFP = T.unpack (toTextIgnore (sandbox </> "version-patterns.zip")) writeFileInChunks archiveFP (fromArchive initArchive) flipFoldM_ pairs initArchive $ \archive' (first,second) -> do setenv "GIT_EXTERNAL_DIFF" "echo" diffLines <- T.lines <$> run "git" ["diff", first, second] -- Git should always return the same information, eg., if this fails something has gone wrong -- TODO: what about multiple files? would that generate multiple lines? let parseDiffArgs :: [T.Text] -> GitDiffArgs parseDiffArgs [fp,_,_,_,_,_,_] = GitDiffArgs { gdaFilePath = fp , gdaBeforeCommit = first , gdaAfterCommit = second } parseDiffArgs l | otherwise = error ("unexpected output from git diff: " ++ T.unpack (T.concat l)) diffArgs :: [GitDiffArgs] diffArgs = map parseDiffArgs (map T.words diffLines) saveATerms :: Archive -> T.Text -> [GitDiffArgs] -> Sh Archive saveATerms a commit gdas = do -- To properly parse files we need the context that the repository was in -- when the commit was made. So we do a checkout. We may also need to -- run configure or other commands. We have no support for that yet. void (run "git" ["checkout", commit]) ------------------------------- -- Hacks for configuring/building the linux kernel enough to make it -- parsable by ROSE -- just take the default config -- escaping False (run "yes \"\" | make oldconfig" []) -- setup the asm symlink -- run "make" ["include/asm"] -- End Hacks for the kernel ------------------------------- ------------------------------- -- Hacks for configuring/building freetype2 enough to make it -- parsable by ROSE -- void (run "./configure" []) `catchany_sh` (const (return ())) -- End Hacks for the kernel ------------------------------- flipFoldM gdas a $ \archive gda -> do let commitDir = fromText commit gdasFP = T.unpack (toTextIgnore (commitDir </> "gdas.hs")) gdasEntry = toEntry gdasFP 0 (BL.pack (show gdas)) gdasArchive = gdasEntry `addEntryToArchive` archive -- parse (gdaFilePath gda) using src2trm and save the result in destDir -- Only handle C source for now if fileFilter (gdaFilePath gda) then do liftIO (putStrLn ("running src2term for " ++ (T.unpack (gdaFilePath gda)))) let from = fromText (gdaFilePath gda) to = commitDir </> (replaceExtension from "trm") catchany_sh (do trm <- B.pack <$> writeSharedATerm <$> src2term from let trmArchive = toEntry (T.unpack (toTextIgnore to)) 0 (BL.fromChunks [trm]) `addEntryToArchive` gdasArchive writeFileInChunks archiveFP (fromArchive trmArchive) liftIO (putStrLn ("Wrote: " ++ T.unpack (toTextIgnore to) ++ " in archive.")) liftIO (toArchive <$> (BL.readFile archiveFP))) (\e -> do liftIO (putStr "Error running src2term: ") liftIO (putStrLn (show e)) return gdasArchive) else return gdasArchive -- Finally, save off the term files archive'' <- saveATerms archive' first diffArgs saveATerms archive'' second diffArgs src2term :: FilePath -> Sh ATermTable src2term from = do cs <- liftIO (readFile (T.unpack (toTextIgnore from))) case parser compilationUnit cs of Right prog -> return (toATermTable (toATerm prog)) Left e -> fail (show e) -- | processTerms looks in the version-patterns.zip archive -- for version-pairs.hs. When it finds it, then it starts -- looking for GitDiffArgs in gdas.hs in each commit directory. -- When it reads GitDiffArgs it loads the two term representations -- mentioned in the GitDiffArgs and computes the antiunification -- of the two and adds that to the zip archive. processTerms :: FilePath -> Sh () processTerms dir = do let archiveFP = T.unpack (toTextIgnore (dir </> "version-patterns.zip")) initArchiveBS <- liftIO (BL.readFile archiveFP) -- find version-pairs.hs in the archive let mb_ds = readFromArchive initArchive "version-pairs.hs" :: Maybe [(T.Text,T.Text)] initArchive = toArchive initArchiveBS case mb_ds of Just ds -> do liftIO (putStrLn ("length ds = " ++ show (length ds))) -- process each diff pair flipFoldM_ ds initArchive $ \archive' (commitBefore,commitAfter) -> do liftIO (putStrLn ("processing " ++ show (commitBefore,commitAfter))) let commitDir = fromText commitBefore liftIO (putStrLn ("Looking in " ++ show commitDir)) -- Look for the GitDiffArgs stored in the current commit directory of the archive let gdasFilePath = commitDir </> "gdas.hs" mb_gdas = readFromArchive archive' gdasFilePath :: Maybe [GitDiffArgs] case mb_gdas of Just gdas -> do liftIO (putStrLn ("Found gdas.hs")) -- For each GitDiffArg we will antiunify them separately flipFoldM gdas archive' $ \archive gda -> do catchany_sh -- Make sure we can process this file (if fileFilter (gdaFilePath gda) then do liftIO (putStrLn ("Antiunify using " ++ show gda)) let diffDir = fromText (commitBefore `T.append` ".." `T.append` commitAfter) antiunifiedFilePath = diffDir </> (replaceExtension (fromText (gdaFilePath gda)) "hs") antiTerms = antiUnifySh archive gda case antiTerms of -- Something went wrong Left e -> liftIO (putStrLn e) >> return archive Right (t,s1,s2) -> do let entry = toEntry (T.unpack (toTextIgnore antiunifiedFilePath)) 0 (BL.pack (show (t,s1,s2))) newArchive = entry `addEntryToArchive` archive liftIO (putStrLn ("Wrote antiunification to: " ++ (T.unpack (toTextIgnore antiunifiedFilePath)))) writeFileInChunks archiveFP (fromArchive newArchive) liftIO (putStrLn "Done writing archive.") liftIO (toArchive <$> (BL.readFile archiveFP)) else return archive) -- Log the error and move on (\e -> do liftIO (putStr "Error processingTerms: ") liftIO (putStrLn (show e)) return archive) Nothing -> return archive' Nothing -> return () -- | antiUnifySh Looks at the GitDiffArgs and pulls two terms out of the archive -- computes the antiunfication and returns the results antiUnifySh :: Archive -> GitDiffArgs -> Either String (Term, Subs, Subs) antiUnifySh archive gda = do let termBeforeFilePath = fromText (gdaBeforeCommit gda) </> replaceExtension (fromText (gdaFilePath gda)) "trm" termAfterFilePath = fromText (gdaAfterCommit gda) </> replaceExtension (fromText (gdaFilePath gda)) "trm" mb_tb = findEntryByPath (T.unpack (toTextIgnore termBeforeFilePath)) archive mb_ta = findEntryByPath (T.unpack (toTextIgnore termAfterFilePath)) archive case (mb_tb, mb_ta) of (Just tb, Just ta) -> let termToTree t = atermToTree (getATerm t) t termBefore = replaceFileInfos (termToTree (readATerm (BL.unpack (fromEntry tb)))) termAfter = replaceFileInfos (termToTree (readATerm (BL.unpack (fromEntry ta)))) in Right (termBefore `antiunify` termAfter) _ -> Left "Failed to load terms" -- |Find all terms whose filename ends in one of the ids passed in -- eg., find . -name '*-id.trm', where id is one of the passed in ints antiUnifyTerms :: FilePath -> String -> [Int] -> Sh () antiUnifyTerms dir fname termIds = do liftIO (putStrLn ("antiUnifyTerms: " ++ unwords (map show termIds))) -- findWhen :: (FilePath -> Sh Bool) -> FilePath -> Sh [FilePath] fs <- findWhen match (dir </> fromString "weaves") ts <- loadTerms fs if length ts < 1 then error "not enough terms to antiunify" else return () let (t,_) = fromJust (antiunifyList ts) gv = (concat ["digraph {\n",unlines (treeToGraphviz t),"}"]) liftIO (writeFile fname gv) where match :: FilePath -> Sh Bool match fp = return (or [("-" ++ show i ++ ".trm") `isSuffixOf` T.unpack (toTextIgnore fp) | i <- termIds]) loadTerms :: [FilePath] -> Sh [Term] loadTerms = mapM loadTerm loadTerm :: FilePath -> Sh Term loadTerm fp = do cs <- liftIO (readFile (T.unpack (toTextIgnore fp))) let t = readATerm cs length cs `seq` return (atermToTree (getATerm t) t) generateGraphs :: FilePath -> Sh () generateGraphs dir = do let archiveFP = T.unpack (toTextIgnore (dir </> "version-patterns.zip")) initArchiveBS <- liftIO (BL.readFile archiveFP) -- find version-pairs.hs in the archive let mb_ds = readFromArchive initArchive "version-pairs.hs" :: Maybe [(T.Text,T.Text)] initArchive = toArchive initArchiveBS index = filesInArchive initArchive case mb_ds of Nothing -> return () Just ds -> do liftIO (putStrLn "just ds") forM_ ds $ \(commitBefore,commitAfter) -> do let diffDir = T.unpack (commitBefore `T.append` ".." `T.append` commitAfter `T.append` "/") inDir = filter (diffDir `isPrefixOf`) index hs = filter (".hs" `isSuffixOf`) inDir forM_ hs $ \h -> do liftIO (putStrLn h) let term = readFromArchive initArchive (fromText (T.pack h)) :: Maybe (Term,Subs,Subs) case term of Nothing -> return () Just (_,s1,s2) -> do let destPath = "/tmp/dagit" </> directory (fromString h) mkdir_p destPath makeGraphFromSubs (destPath </> filename (fromString h) <.> "s1") s1 makeGraphFromSubs (destPath </> filename (fromString h) <.> "s2") s2 makeGraphFromSubs :: FilePath -> Subs -> Sh () makeGraphFromSubs fp subs = do let ps = M.assocs (extractMap subs) gs = map (\(k,v) -> (extractName k, treeToGraphviz v)) ps cs = map (\(k,v) -> (k,unlines v)) gs o k = (T.unpack (toTextIgnore fp)) ++ "-" ++ k ++ ".gv" forM_ cs (\(k,v) -> liftIO (writeFile (o k) (concat ["digraph {\n",v,"}"]))) where extractName (Node (LBLString n) _) = n extractName _ = "" extractMap (Subs t) = t unparseTerms :: FilePath -> Sh () unparseTerms dir = do let archiveFP = T.unpack (toTextIgnore (dir </> "version-patterns.zip")) initArchiveBS <- liftIO (BL.readFile archiveFP) -- find version-pairs.hs in the archive let mb_ds = readFromArchive initArchive "version-pairs.hs" :: Maybe [(T.Text,T.Text)] initArchive = toArchive initArchiveBS index = filesInArchive initArchive case mb_ds of Nothing -> return () Just ds -> do liftIO (putStrLn "just ds") forM_ ds $ \(commitBefore,commitAfter) -> do let diffDir = T.unpack (commitBefore `T.append` ".." `T.append` commitAfter `T.append` "/") inDir = filter (diffDir `isPrefixOf`) index hs = filter (".hs" `isSuffixOf`) inDir forM_ hs $ \h -> do liftIO (putStrLn h) let term = readFromArchive initArchive (fromText (T.pack h)) :: Maybe (Term,Subs,Subs) case term of Nothing -> return () Just (_,s1,s2) -> do let destPath = "/tmp/dagit" </> directory (fromString h) mkdir_p destPath term2src s1 >>= liftIO . putStrLn term2src s2 >>= liftIO . putStrLn term2src :: Subs -> Sh String term2src subs = do let ps = M.assocs (extractMap subs) gs = map (\(k,v) -> (extractName k, treeToATerm v)) ps cs = map (\(k,v) -> (k, getATermFull v)) gs return (show cs) where extractName (Node (LBLString n) _) = n extractName _ = "" extractMap (Subs t) = t weaveTerms :: FilePath -> Int -> Sh () weaveTerms dir num = do let archiveFP = T.unpack (toTextIgnore (dir </> "version-patterns.zip")) initArchiveBS <- liftIO (BL.readFile archiveFP) -- find version-pairs.hs in the archive let mb_ds = readFromArchive archive "version-pairs.hs" :: Maybe [(T.Text,T.Text)] archive = toArchive initArchiveBS case mb_ds of Just ds -> do liftIO (putStrLn ("length ds = " ++ show (length ds))) -- process each diff pair (_,ps,ts) <- flipFoldM (take num ds) (0,[],[]) $ \(count,ps,ts) (commitBefore,commitAfter) -> do liftIO (putStrLn ("processing " ++ show (commitBefore,commitAfter))) let commitDir = fromText commitBefore liftIO (putStrLn ("Looking in " ++ show commitDir)) -- Look for the GitDiffArgs stored in the current commit directory of the archive let gdasFilePath = commitDir </> "gdas.hs" mb_gdas = readFromArchive archive gdasFilePath :: Maybe [GitDiffArgs] case mb_gdas of Just gdas -> do liftIO (putStrLn ("Found gdas.hs")) -- For each GitDiffArg we will weave them separately flipFoldM gdas (count,ps,ts) $ \(prevCount,prevPs,prevTs) gda -> do catchany_sh -- Make sure we can process this file (if fileFilter (gdaFilePath gda) then do liftIO (putStrLn ("weave using " ++ show gda)) let diffDir = fromText (commitBefore `T.append` ".." `T.append` commitAfter) weaveFilePath = diffDir </> (replaceExtension (fromText (gdaFilePath gda)) "hs") woven = weaveSh archive gda case woven of -- Something went wrong Left e -> liftIO (putStrLn e) >> return (prevCount,prevPs,prevTs) Right w -> do let destPath = "weaves" </> directory weaveFilePath outfp = destPath </> (filename (replaceExtension weaveFilePath "gv")) outgvfps = [directory outfp </> (fromText (toTextIgnore (basename outfp) `T.append` "-" `T.append` T.pack (show x))) <.> "gv" | x <- [(prevCount::Int)..]] outtrmfps = [directory outfp </> (fromText (toTextIgnore (basename outfp) `T.append` "-" `T.append` T.pack (show x))) <.> "trm" | x <- [(prevCount::Int)..]] mkGV l = concat ["digraph {\n", unlines l,"}"] gvs = map (mkGV . eTreeToGraphviz) ws' ws' = extract2 w terms = map treeToATerm (extract w) ts' = map treeType ws' ps' = let ws = extract w in zip ws (map (size . toSizedTree) ws) if length ps' /= length ts' then error "ps' /= ts'" else return () mkdir_p destPath liftIO (forM_ (zip (map (T.unpack . toTextIgnore) outgvfps) gvs) (\(fp,gv) -> do putStrLn ("Writing: " ++ fp) writeFile fp gv putStrLn ("Wrote graphviz of weave to: " ++ fp))) liftIO (forM_ (zip (map (T.unpack . toTextIgnore) outtrmfps) terms) (\(fp,term) -> do putStrLn ("Writing: " ++ fp) writeFile fp (writeSharedATerm term) putStrLn ("Wrote aterm of weave to: " ++ fp))) return (prevCount+length ps',prevPs ++ ps',prevTs++ts') else return (prevCount,prevPs,prevTs)) -- Log the error and move on (\e -> do liftIO (putStr "Error processingTerms: ") liftIO (putStrLn (show e)) return (prevCount,prevPs,prevTs)) Nothing -> return (0,[],[]) if length ps /= length ts then error "ps /= ts" else return () let dists :: MismatchType -> [((LabeledTree,Int),Maybe MismatchType)] -> [Double] dists ty xs = [ let -- score = fromIntegral (treedist t1 t2 (==))/fromIntegral(max s1 s2) -- score = fromIntegral (treedist t1 t2 (==))/fromIntegral s1 scorel = fromIntegral (treedist t1 t2 (==)) scorer = fromIntegral (treedist t2 t1 (==)) -- score = min (scorel / fromIntegral s1) -- (scorer / fromIntegral s2) score = min scorel scorer / fromIntegral (max s1 s2) in if ty1 == ty2 && ty1 == Just ty then score else 0 | ((t1,s1),ty1) <- xs, ((t2,s2),ty2) <- xs ] csvShow xs = unlines (map csvShow' xs) where csvShow' ys = intercalate "," (map show ys) pairs = zip ps ts chunkSize = length pairs forestBefore = dists MismatchTypeLeft pairs forestAfter = dists MismatchTypeRight pairs forestDelete = dists RightHoleType pairs forestAdd = dists LeftHoleType pairs liftIO (writeFile "treetypes.csv" (intercalate "," (map (show.fromEnum') ts))) liftIO (writeFile "treesimilarity-before.csv" (csvShow (chunk chunkSize forestBefore))) liftIO (writeFile "treesimilarity-after.csv" (csvShow (chunk chunkSize forestAfter))) liftIO (writeFile "treesimilarity-delete.csv" (csvShow (chunk chunkSize forestDelete))) liftIO (writeFile "treesimilarity-add.csv" (csvShow (chunk chunkSize forestAdd))) -- liftIO (writeFile "treesimilarity-all.csv" (csvShow (chunk (length ps) (dists ps)))) Nothing -> return () weaveSh :: IsString a => Archive -> GitDiffArgs -> Either a (WeaveTree Bool) weaveSh archive gda = do let termBeforeFilePath = fromText (gdaBeforeCommit gda) </> replaceExtension (fromText (gdaFilePath gda)) "trm" termAfterFilePath = fromText (gdaAfterCommit gda) </> replaceExtension (fromText (gdaFilePath gda)) "trm" mb_tb = findEntryByPath (T.unpack (toTextIgnore termBeforeFilePath)) archive mb_ta = findEntryByPath (T.unpack (toTextIgnore termAfterFilePath)) archive case (mb_tb, mb_ta) of (Just tb, Just ta) -> let termToTree t = atermToTree (getATerm t) t termBefore = termToTree (readATerm (BL.unpack (fromEntry tb))) termAfter = termToTree (readATerm (BL.unpack (fromEntry ta))) (y1,y2) = treediff termBefore termAfter (==) w = weave y1 y2 False in Right w _ -> Left "Failed to load terms" similarTrees :: FilePath -> Double -> Sh () similarTrees dir thres = do let fps = map (\nm -> T.unpack (toTextIgnore (dir </> fromString ("treesimilarity-" ++ nm ++ ".csv")))) alts alts = ["before","after","delete","add"] -- d3 <- liftIO (modexp d2 sz sz) liftIO (putStrLn ("Similarity threshold: " ++ show thres)) similars <- zip alts <$> mapM load fps mapM_ dumpGV similars where dumpGV (prefix,m) = forM_ (M.toAscList m) $ \(k,is) -> do let set = S.toAscList is antiUnifyTerms dir ("antiunify-" ++ prefix ++ "-" ++ show k ++ ".gv") set -- horribly inefficient, but for some reason the csv parser -- treats the final newline in a file as a record. So, -- we strip it out. dropTrailingNewline [] = [] dropTrailingNewline xs | last xs == '\n' = init xs | otherwise = xs load fp = do cs <- liftIO (readFile fp) let csvDat = case parseCSV fp (dropTrailingNewline cs) of Right c -> map read <$> c :: [[Double]] Left e -> error (show e) d = V.fromList (concat csvDat) d2 = (>= thres) <$> d sz = length csvDat return (similarityMatrix d2 sz) similarityMatrix m sz = similar where sm = chunk sz (V.toList m) filterSimilar :: M.Map Int (S.Set Int) -> M.Map Int (S.Set Int) filterSimilar m = M.fromList $ case mapAccumL go S.empty (M.toList m) of (_, ys) -> catMaybes ys where go :: S.Set Int -> (Int, S.Set Int) -> (S.Set Int, Maybe (Int,S.Set Int)) go seen (i,rs) = (seen', irs) where seen' = S.singleton i `S.union` seen `S.union` rs irs = if i `S.notMember` seen then Just (i,rs) else Nothing similar :: M.Map Int (S.Set Int) similar = filterSimilar $ M.fromList $ do (i,r) <- zip [0..] sm let js = elemIndices True r guard (not (null js)) return (i,S.fromList js) ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- * Visualize Differences wtreeToGraphviz :: WeaveTree a -- ^ Tree to print -> [String] -- ^ DOT-file lines wtreeToGraphviz t = snd $ evalIDGen t wToGV wpLabel :: WeavePoint a -> String wpLabel (Match _) = "MATCH" wpLabel (Mismatch _ _) = "MISMATCH" wpLabel (RightHole _) = "RHOLE" wpLabel (LeftHole _) = "LHOLE" wpToGV :: WeavePoint a -> IDGen (Int, [String]) wpToGV wp = do myID <- genID let self = makeNode myID [cGreen] (wpLabel wp) case wp of Match t -> do (kidID, kidStrings) <- wToGV t let kEdge = makeEdge myID kidID return (myID, self:kEdge:kidStrings) Mismatch a b -> do (kidID1, kidStrings1) <- wToGV a (kidID2, kidStrings2) <- wToGV b let kEdge1 = makeEdge myID kidID1 kEdge2 = makeEdge myID kidID2 return (myID, self:kEdge1:kEdge2:(kidStrings1++kidStrings2)) LeftHole t -> do (kidID, kidStrings) <- wToGV t let kEdge = makeEdge myID kidID return (myID, self:kEdge:kidStrings) RightHole t -> do (kidID, kidStrings) <- wToGV t let kEdge = makeEdge myID kidID return (myID, self:kEdge:kidStrings) wToGV :: WeaveTree a -> IDGen (Int, [String]) wToGV (WLeaf t) = do myID <- genID let self = makeNode myID [cGreen] "WLeaf" (kidID, kidStrings) <- tToGV gvShowLabel t let kidEdge = makeEdge myID kidID return (myID, self:kidEdge:kidStrings) wToGV (WNode lbl _ wps) = do myID <- genID let self = makeNode myID [cGreen] ("WNode:"++(gvShowLabel lbl)) processed <- mapM wpToGV wps let (kIDs, kSs) = unzip processed kidEdges = map (makeEdge myID) kIDs return (myID, self:(kidEdges++(concat kSs))) -- | This code is taken from the compose-hpc rulegen: {-| Take a LabeledTree and return a list of lines for the corresponding graphviz DOT file. -} treeToGraphviz :: LabeledTree -- ^ Tree to print -> [String] -- ^ DOT-file lines treeToGraphviz t = snd $ evalIDGen t (tToGV gvShowLabel) -- -- node attributes for different node types -- tToGV :: (a -> String) -> Tree a -> IDGen (Int, [String]) tToGV showIt (Node label kids) = do myID <- genID --let self = makeNode myID [cRed] (gvShowLabel label) let self = makeNode myID [cRed] (showIt label) processedKids <- mapM (tToGV showIt) kids let (kidIDs, kidStrings) = unzip processedKids kidEdges = map (makeEdge myID) kidIDs return (myID, self:(kidEdges++(concat kidStrings))) eTreeToGraphviz :: Tree (Label,Maybe MismatchType) -> [String] eTreeToGraphviz t = snd $ evalIDGen t (tToGV gvShowLabelMismatch) gvShowLabel :: Label -> String gvShowLabel (LBLString s) = s gvShowLabel (LBLList ) = "LIST" gvShowLabel (LBLInt i ) = show i gvShowLabelMismatch :: (Label,Maybe MismatchType) -> String gvShowLabelMismatch (l, Just m) = gvShowLabel l ++ ": " ++ show m gvShowLabelMismatch (l, Nothing) = gvShowLabel l -- use state monad for generating unique identifiers type IDGen = State Int -- generate sequence of unique ID numbers genID :: IDGen Int genID = do i <- get put (i+1) return i -- generate variables with a fixed prefix and a unique suffix. For -- example, with prefix "x", a sequence of invocations of this -- function will yield the names "x0", "x1", "x2", and so on. genName :: String -> IDGen String genName n = do i <- genID return $ n ++ (show i) evalIDGen :: a -> (a -> IDGen b) -> b evalIDGen x f = evalState (f x) 0 -- helper for common case with no attribute : avoid having to write Nothing -- all over the place makeEdge :: Int -> Int -> String makeEdge i j = makeAttrEdge i j Nothing -- node maker makeNode :: Int -> [String] -> String -> String makeNode i attrs lbl = "NODE"++(show i)++" ["++a++"];" where a = intercalate "," (("label=\""++(cleanlabel lbl)++"\""):attrs) cGreen :: String cGreen = "color=green" cRed :: String cRed = "color=red" cBlue :: String cBlue = "color=blue" cBlack :: String cBlack = "color=black" aBold :: String aBold = "style=bold" -- -- edge makers -- makeAttrEdge :: Int -> Int -> Maybe [String] -> String makeAttrEdge i j Nothing = "NODE"++(show i)++" -> NODE"++(show j)++";" makeAttrEdge i j (Just as) = "NODE"++(show i)++" -> NODE"++(show j)++" ["++a++"];" where a = intercalate "," as cleanlabel :: String -> String cleanlabel lbl = filter (\c -> c /= '\\' && c /= '\'' && c /= '\"') lbl ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- * Utility Functions -- | Lazily pulls a Readable value out of the requested file in the archive. readFromArchive :: Read a => Archive -> FilePath -> Maybe a readFromArchive archive fp = (read . BL.unpack . fromEntry) <$> findEntryByPath (T.unpack (toTextIgnore fp)) archive -- | Like the normal withFile except that internally it uses -- 'shelly' and 'liftIO' to make the type Sh instead of IO. withFileSh :: String -> IOMode -> (Handle -> Sh r) -> Sh r withFileSh fp mode f = liftIO (bracket (openFile fp mode) hClose (\h -> shelly (f h))) -- | We make an attempt to be somewhat atomic: -- We throw ".tmp" onto the file extension, write to it in chunks -- and when the chunks are written we move the file over top of -- the requested file name. writeFileInChunks :: String -> BL.ByteString -> Sh () writeFileInChunks fp bl = do withFileSh (fp++".tmp") WriteMode $ \h -> do forM_ (BL.toChunks bl) $ \b -> do liftIO (B.hPut h b) mv (fromText (T.pack (fp++".tmp"))) (fromText (T.pack fp)) -- | We're mostly interested in C at the moment, so that means -- .c and .h files. fileFilter :: T.Text -> Bool fileFilter fp = (".java" `T.isSuffixOf` fp) flipFoldM_ :: Monad m => [b] -> a -> (a -> b -> m a) -> m () flipFoldM_ xs a f = foldM_ f a xs flipFoldM :: Monad m => [b] -> a -> (a -> b -> m a) -> m a flipFoldM xs a f = foldM f a xs -- | Remove file_infos from the tree filterFileInfos :: LabeledTree -> Maybe LabeledTree filterFileInfos tree = removeSubtrees (LBLString "file_info") tree -- | Homogenize the file_infos in the tree replaceFileInfos :: LabeledTree -> LabeledTree replaceFileInfos t = replaceSubtrees (LBLString "file_info") (Node (LBLString "file_info") [Node (LBLString "\"compilerGenerated\"") [] ,Node (LBLInt 0) [] ,Node (LBLInt 0) []]) t size :: SizedTree a -> Int size (Node (_,s) _) = s treeType :: Tree (a,Maybe b) -> Maybe b treeType (Node (_,Just b) _) = Just b treeType (Node (_,Nothing) kids) = foldl' (<|>) Nothing (map treeType kids) chunk :: Int -> [a] -> [[a]] chunk _ [] = [] chunk n xs = take n xs : chunk n (drop n xs) fromEnum' :: Enum a => Maybe a -> Int fromEnum' (Just a) = fromEnum a fromEnum' Nothing = -1 -- Haskell doesn't know C99's bool type, so we use CChar foreign import ccall "mult" c_mult :: Ptr CChar -> Ptr CChar -> Ptr CChar -> CInt -> IO () true :: Int -> Int -> Vector Bool true nrs ncs = V.fromList (replicate (nrs*ncs) True) -- | Computes x ^ y for an sz by sz matrix where -- we use Bool as the field with 2 elements modexp :: Vector Bool -> Int -> Int -> IO (Vector Bool) modexp _ sz 0 = return (true sz sz) modexp x sz y | even y = do z <- xx mult z z sz | otherwise = do z <- xx z' <- mult z z sz mult x z' sz where xx = mult x x sz -- | Calculates an exponentiation of the matrix in the field with two elements. -- Take a square matrix as a vector, the size of the matrix in one dimension, -- the power to raise the matrix to and returns the result. mult :: Vector Bool -> Vector Bool -> Int -> IO (Vector Bool) mult x y sz = do let len = V.length x x' = toChar <$> x y' = toChar <$> y a <- mallocForeignPtrBytes len b <- mallocForeignPtrBytes len c <- mallocForeignPtrBytes len withForeignPtr a $ \ptrX -> do pokeArray ptrX (V.toList x') withForeignPtr b $ \ptrY -> do pokeArray ptrY (V.toList y') withForeignPtr c $ \ptrC -> do c_mult ptrX ptrY ptrC (fromIntegral sz) V.map toBool <$> V.fromList <$> peekArray len ptrC where toBool :: CChar -> Bool toBool = toEnum . fromEnum toChar :: Bool -> CChar toChar = toEnum . fromEnum -----------------------------------------------------------------------
dagit/edit-patterns
Main.hs
Haskell
bsd-3-clause
37,050
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# OPTIONS_GHC -fno-warn-unused-do-bind #-} ----------------------------------------------------------------------------- -- | -- Module : Text.CSL.Input.Bibtex -- Copyright : (c) John MacFarlane -- License : BSD-style (see LICENSE) -- -- Maintainer : John MacFarlane <fiddlosopher@gmail.com> -- Stability : unstable-- Portability : unportable -- ----------------------------------------------------------------------------- module Text.CSL.Input.Bibtex ( readBibtex , readBibtexString , Lang(..) , langToLocale , getLangFromEnv ) where import Prelude import Control.Applicative import qualified Control.Exception as E import Control.Monad import Control.Monad.RWS hiding ((<>)) import Data.Char (isAlphaNum, isDigit, isUpper, toLower, toUpper) import Data.List (foldl', intercalate) import Data.List.Split (splitOn, splitWhen, wordsBy) import qualified Data.Map as Map import Data.Maybe import System.Environment (getEnvironment) import Text.CSL.Compat.Pandoc (readLaTeX) import Text.CSL.Exception (CiteprocException (ErrorReadingBib, ErrorReadingBibFile)) import Text.CSL.Parser (parseLocale) import Text.CSL.Reference import Text.CSL.Style (Agent (..), emptyAgent, CslTerm (..), Formatted (..), Locale (..)) import Text.CSL.Util (onBlocks, protectCase, safeRead, splitStrWhen, trim, unTitlecase) import Text.Pandoc.Definition import qualified Text.Pandoc.UTF8 as UTF8 import qualified Text.Pandoc.Walk as Walk import Text.Parsec hiding (State, many, (<|>)) blocksToFormatted :: [Block] -> Bib Formatted blocksToFormatted bs = case bs of [Plain xs] -> inlinesToFormatted xs [Para xs] -> inlinesToFormatted xs _ -> inlinesToFormatted $ Walk.query (:[]) bs adjustSpans :: Lang -> Inline -> [Inline] adjustSpans _ (Span ("",[],[]) xs) = xs adjustSpans lang (RawInline (Format "latex") s) | s == "\\hyphen" || s == "\\hyphen " = [Str "-"] | otherwise = Walk.walk (concatMap (adjustSpans lang)) $ parseRawLaTeX lang s adjustSpans _ x = [x] parseRawLaTeX :: Lang -> String -> [Inline] parseRawLaTeX lang ('\\':xs) = case latex' contents of [Para ys] -> f command ys [Plain ys] -> f command ys _ -> [] where (command', contents') = break (=='{') xs command = trim command' contents = drop 1 $ reverse $ drop 1 $ reverse contents' f "mkbibquote" ils = [Quoted DoubleQuote ils] f "mkbibemph" ils = [Emph ils] f "mkbibitalic" ils = [Emph ils] -- TODO: italic/=emph f "mkbibbold" ils = [Strong ils] f "mkbibparens" ils = [Str "("] ++ ils ++ [Str ")"] -- TODO: ... f "mkbibbrackets" ils = [Str "["] ++ ils ++ [Str "]"] -- TODO: ... -- ... both should be nestable & should work in year fields f "autocap" ils = ils -- TODO: should work in year fields f "textnormal" ils = [Span ("",["nodecor"],[]) ils] f "bibstring" [Str s] = [Str $ resolveKey' lang s] f _ ils = [Span nullAttr ils] parseRawLaTeX _ _ = [] inlinesToFormatted :: [Inline] -> Bib Formatted inlinesToFormatted ils = do lang <- gets localeLanguage return $ Formatted $ Walk.walk (concatMap (adjustSpans lang)) ils data Item = Item{ identifier :: String , entryType :: String , fields :: Map.Map String String } -- | Get 'Lang' from the environment variable LANG, defaulting to en-US. getLangFromEnv :: IO Lang getLangFromEnv = do env <- getEnvironment return $ case lookup "LANG" env of Just x -> case splitWhen (\c -> c == '.' || c == '_' || c == '-') x of (w:z:_) -> Lang w z [w] | not (null w) -> Lang w mempty _ -> Lang "en" "US" Nothing -> Lang "en" "US" -- | Parse a BibTeX or BibLaTeX file into a list of 'Reference's. -- The first parameter is a predicate to filter identifiers. -- If the second parameter is true, the file will be treated as -- BibTeX; otherwse as BibLaTeX. If the third parameter is -- true, an "untitlecase" transformation will be performed. readBibtex :: (String -> Bool) -> Bool -> Bool -> FilePath -> IO [Reference] readBibtex idpred isBibtex caseTransform f = do contents <- UTF8.readFile f E.catch (readBibtexString idpred isBibtex caseTransform contents) (\e -> case e of ErrorReadingBib es -> E.throwIO $ ErrorReadingBibFile f es _ -> E.throwIO e) -- | Like 'readBibtex' but operates on a String rather than a file. readBibtexString :: (String -> Bool) -> Bool -> Bool -> String -> IO [Reference] readBibtexString idpred isBibtex caseTransform contents = do lang <- getLangFromEnv locale <- parseLocale (langToLocale lang) case runParser (bibEntries <* eof) (Map.empty) "stdin" contents of -- drop 8 to remove "stdin" + space Left err -> E.throwIO $ ErrorReadingBib $ drop 8 $ show err Right xs -> return $ mapMaybe (itemToReference lang locale isBibtex caseTransform) (filter (idpred . identifier) (resolveCrossRefs isBibtex xs)) type BibParser = Parsec String (Map.Map String String) bibEntries :: BibParser [Item] bibEntries = do skipMany nonEntry many (bibItem <* skipMany nonEntry) where nonEntry = bibSkip <|> try (char '@' >> (bibComment <|> bibPreamble <|> bibString)) bibSkip :: BibParser () bibSkip = skipMany1 (satisfy (/='@')) bibComment :: BibParser () bibComment = do cistring "comment" spaces void inBraces <|> bibSkip <|> return () bibPreamble :: BibParser () bibPreamble = do cistring "preamble" spaces void inBraces bibString :: BibParser () bibString = do cistring "string" spaces char '{' spaces (k,v) <- entField char '}' updateState (Map.insert k v) return () inBraces :: BibParser String inBraces = try $ do char '{' res <- manyTill ( many1 (noneOf "{}\\") <|> (char '\\' >> ( (char '{' >> return "\\{") <|> (char '}' >> return "\\}") <|> return "\\")) <|> (braced <$> inBraces) ) (char '}') return $ concat res braced :: String -> String braced s = "{" ++ s ++ "}" inQuotes :: BibParser String inQuotes = do char '"' concat <$> manyTill ( many1 (noneOf "\"\\{") <|> (char '\\' >> (\c -> ['\\',c]) <$> anyChar) <|> braced <$> inBraces ) (char '"') fieldName :: BibParser String fieldName = resolveAlias . map toLower <$> many1 (letter <|> digit <|> oneOf "-_:+") isBibtexKeyChar :: Char -> Bool isBibtexKeyChar c = isAlphaNum c || c `elem` ".:;?!`'()/*@_+=-[]*&" bibItem :: BibParser Item bibItem = do char '@' enttype <- map toLower <$> many1 letter spaces char '{' spaces entid <- many1 (satisfy isBibtexKeyChar) spaces char ',' spaces entfields <- entField `sepEndBy` (char ',' >> spaces) spaces char '}' return $ Item entid enttype (Map.fromList entfields) entField :: BibParser (String, String) entField = do k <- fieldName spaces char '=' spaces vs <- (expandString <|> inQuotes <|> inBraces <|> rawWord) `sepBy` try (spaces >> char '#' >> spaces) spaces return (k, concat vs) resolveAlias :: String -> String resolveAlias "archiveprefix" = "eprinttype" resolveAlias "primaryclass" = "eprintclass" resolveAlias s = s rawWord :: BibParser String rawWord = many1 alphaNum expandString :: BibParser String expandString = do k <- fieldName strs <- getState case Map.lookup k strs of Just v -> return v Nothing -> return k -- return raw key if not found cistring :: String -> BibParser String cistring s = try (go s) where go [] = return [] go (c:cs) = do x <- char (toLower c) <|> char (toUpper c) xs <- go cs return (x:xs) resolveCrossRefs :: Bool -> [Item] -> [Item] resolveCrossRefs isBibtex entries = map (resolveCrossRef isBibtex entries) entries splitKeys :: String -> [String] splitKeys = wordsBy (\c -> c == ' ' || c == ',') getXrefFields :: Bool -> Item -> [Item] -> String -> [(String, String)] getXrefFields isBibtex baseEntry entries keys = do let keys' = splitKeys keys xrefEntry <- [e | e <- entries, identifier e `elem` keys'] (k, v) <- Map.toList $ fields xrefEntry if k == "crossref" || k == "xdata" then do xs <- mapM (getXrefFields isBibtex baseEntry entries) (splitKeys v) (x, y) <- xs guard $ isNothing $ Map.lookup x $ fields xrefEntry return (x, y) else do k' <- if isBibtex then return k else transformKey (entryType xrefEntry) (entryType baseEntry) k guard $ isNothing $ Map.lookup k' $ fields baseEntry return (k',v) resolveCrossRef :: Bool -> [Item] -> Item -> Item resolveCrossRef isBibtex entries entry = Map.foldrWithKey go entry (fields entry) where go key val entry' = if key == "crossref" || key == "xdata" then entry'{ fields = fields entry' <> Map.fromList (getXrefFields isBibtex entry entries val) } else entry' -- transformKey source target key -- derived from Appendix C of bibtex manual transformKey :: String -> String -> String -> [String] transformKey _ _ "ids" = [] transformKey _ _ "crossref" = [] transformKey _ _ "xref" = [] transformKey _ _ "entryset" = [] transformKey _ _ "entrysubtype" = [] transformKey _ _ "execute" = [] transformKey _ _ "label" = [] transformKey _ _ "options" = [] transformKey _ _ "presort" = [] transformKey _ _ "related" = [] transformKey _ _ "relatedoptions" = [] transformKey _ _ "relatedstring" = [] transformKey _ _ "relatedtype" = [] transformKey _ _ "shorthand" = [] transformKey _ _ "shorthandintro" = [] transformKey _ _ "sortkey" = [] transformKey x y "author" | x `elem` ["mvbook", "book"] && y `elem` ["inbook", "bookinbook", "suppbook"] = ["bookauthor", "author"] -- note: this next clause is not in the biblatex manual, but it makes -- sense in the context of CSL conversion: transformKey x y "author" | x == "mvbook" && y == "book" = ["bookauthor", "author"] transformKey "mvbook" y z | y `elem` ["book", "inbook", "bookinbook", "suppbook"] = standardTrans z transformKey x y z | x `elem` ["mvcollection", "mvreference"] && y `elem` ["collection", "reference", "incollection", "inreference", "suppcollection"] = standardTrans z transformKey "mvproceedings" y z | y `elem` ["proceedings", "inproceedings"] = standardTrans z transformKey "book" y z | y `elem` ["inbook", "bookinbook", "suppbook"] = bookTrans z transformKey x y z | x `elem` ["collection", "reference"] && y `elem` ["incollection", "inreference", "suppcollection"] = bookTrans z transformKey "proceedings" "inproceedings" z = bookTrans z transformKey "periodical" y z | y `elem` ["article", "suppperiodical"] = case z of "title" -> ["journaltitle"] "subtitle" -> ["journalsubtitle"] "shorttitle" -> [] "sorttitle" -> [] "indextitle" -> [] "indexsorttitle" -> [] _ -> [z] transformKey _ _ x = [x] standardTrans :: String -> [String] standardTrans z = case z of "title" -> ["maintitle"] "subtitle" -> ["mainsubtitle"] "titleaddon" -> ["maintitleaddon"] "shorttitle" -> [] "sorttitle" -> [] "indextitle" -> [] "indexsorttitle" -> [] _ -> [z] bookTrans :: String -> [String] bookTrans z = case z of "title" -> ["booktitle"] "subtitle" -> ["booksubtitle"] "titleaddon" -> ["booktitleaddon"] "shorttitle" -> [] "sorttitle" -> [] "indextitle" -> [] "indexsorttitle" -> [] _ -> [z] -- | A representation of a language and localization. data Lang = Lang String String -- e.g. "en" "US" -- | Prints a 'Lang' in BCP 47 format. langToLocale :: Lang -> String langToLocale (Lang x y) = x ++ ('-':y) -- Biblatex Localization Keys (see Biblatex manual) -- Currently we only map a subset likely to be used in Biblatex *databases* -- (in fields such as `type`, and via `\bibstring{}` commands). resolveKey :: Lang -> Formatted -> Formatted resolveKey lang (Formatted ils) = Formatted (Walk.walk go ils) where go (Str s) = Str $ resolveKey' lang s go x = x -- biblatex localization keys, from files at -- http://github.com/plk/biblatex/tree/master/tex/latex/biblatex/lbx -- Some keys missing in these were added from csl locale files at -- http://github.com/citation-style-language/locales -- labeled "csl" resolveKey' :: Lang -> String -> String resolveKey' (Lang "ca" "AD") k = case map toLower k of "inpreparation" -> "en preparació" "submitted" -> "enviat" "forthcoming" -> "disponible en breu" "inpress" -> "a impremta" "prepublished" -> "pre-publicat" "mathesis" -> "tesi de màster" "phdthesis" -> "tesi doctoral" "candthesis" -> "tesi de candidatura" "techreport" -> "informe tècnic" "resreport" -> "informe de recerca" "software" -> "programari" "datacd" -> "CD de dades" "audiocd" -> "CD d’àudio" "patent" -> "patent" "patentde" -> "patent alemana" "patenteu" -> "patent europea" "patentfr" -> "patent francesa" "patentuk" -> "patent britànica" "patentus" -> "patent estatunidenca" "patreq" -> "soŀlicitud de patent" "patreqde" -> "soŀlicitud de patent alemana" "patreqeu" -> "soŀlicitud de patent europea" "patreqfr" -> "soŀlicitud de patent francesa" "patrequk" -> "soŀlicitud de patent britànica" "patrequs" -> "soŀlicitud de patent estatunidenca" "countryde" -> "Alemanya" "countryeu" -> "Unió Europea" "countryep" -> "Unió Europea" "countryfr" -> "França" "countryuk" -> "Regne Unit" "countryus" -> "Estats Units d’Amèrica" "newseries" -> "sèrie nova" "oldseries" -> "sèrie antiga" _ -> k resolveKey' (Lang "da" "DK") k = case map toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "kommende" -- csl "inpress" -> "i tryk" -- csl -- "prepublished" -> "" -- missing "mathesis" -> "speciale" "phdthesis" -> "ph.d.-afhandling" "candthesis" -> "kandidatafhandling" "techreport" -> "teknisk rapport" "resreport" -> "forskningsrapport" "software" -> "software" "datacd" -> "data-cd" "audiocd" -> "lyd-cd" "patent" -> "patent" "patentde" -> "tysk patent" "patenteu" -> "europæisk patent" "patentfr" -> "fransk patent" "patentuk" -> "britisk patent" "patentus" -> "amerikansk patent" "patreq" -> "ansøgning om patent" "patreqde" -> "ansøgning om tysk patent" "patreqeu" -> "ansøgning om europæisk patent" "patreqfr" -> "ansøgning om fransk patent" "patrequk" -> "ansøgning om britisk patent" "patrequs" -> "ansøgning om amerikansk patent" "countryde" -> "Tyskland" "countryeu" -> "Europæiske Union" "countryep" -> "Europæiske Union" "countryfr" -> "Frankrig" "countryuk" -> "Storbritanien" "countryus" -> "USA" "newseries" -> "ny serie" "oldseries" -> "gammel serie" _ -> k resolveKey' (Lang "de" "DE") k = case map toLower k of "inpreparation" -> "in Vorbereitung" "submitted" -> "eingereicht" "forthcoming" -> "im Erscheinen" "inpress" -> "im Druck" "prepublished" -> "Vorveröffentlichung" "mathesis" -> "Magisterarbeit" "phdthesis" -> "Dissertation" -- "candthesis" -> "" -- missing "techreport" -> "Technischer Bericht" "resreport" -> "Forschungsbericht" "software" -> "Computer-Software" "datacd" -> "CD-ROM" "audiocd" -> "Audio-CD" "patent" -> "Patent" "patentde" -> "deutsches Patent" "patenteu" -> "europäisches Patent" "patentfr" -> "französisches Patent" "patentuk" -> "britisches Patent" "patentus" -> "US-Patent" "patreq" -> "Patentanmeldung" "patreqde" -> "deutsche Patentanmeldung" "patreqeu" -> "europäische Patentanmeldung" "patreqfr" -> "französische Patentanmeldung" "patrequk" -> "britische Patentanmeldung" "patrequs" -> "US-Patentanmeldung" "countryde" -> "Deutschland" "countryeu" -> "Europäische Union" "countryep" -> "Europäische Union" "countryfr" -> "Frankreich" "countryuk" -> "Großbritannien" "countryus" -> "USA" "newseries" -> "neue Folge" "oldseries" -> "alte Folge" _ -> k resolveKey' (Lang "en" "US") k = case map toLower k of "audiocd" -> "audio CD" "by" -> "by" "candthesis" -> "Candidate thesis" "countryde" -> "Germany" "countryep" -> "European Union" "countryeu" -> "European Union" "countryfr" -> "France" "countryuk" -> "United Kingdom" "countryus" -> "United States of America" "datacd" -> "data CD" "edition" -> "ed." "forthcoming" -> "forthcoming" "inpreparation" -> "in preparation" "inpress" -> "in press" "introduction" -> "introduction" "jourser" -> "ser." "mathesis" -> "Master’s thesis" "newseries" -> "new series" "nodate" -> "n. d." "number" -> "no." "numbers" -> "nos." "oldseries" -> "old series" "patent" -> "patent" "patentde" -> "German patent" "patenteu" -> "European patent" "patentfr" -> "French patent" "patentuk" -> "British patent" "patentus" -> "U.S. patent" "patreq" -> "patent request" "patreqde" -> "German patent request" "patreqeu" -> "European patent request" "patreqfr" -> "French patent request" "patrequk" -> "British patent request" "patrequs" -> "U.S. patent request" "phdthesis" -> "PhD thesis" "prepublished" -> "pre-published" "pseudonym" -> "pseud." "recorded" -> "recorded" "resreport" -> "research report" "reviewof" -> "Review of" "revisededition" -> "rev. ed." "software" -> "computer software" "submitted" -> "submitted" "techreport" -> "technical report" "volume" -> "vol." _ -> k resolveKey' (Lang "es" "ES") k = case map toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "previsto" -- csl "inpress" -> "en imprenta" -- csl -- "prepublished" -> "" -- missing "mathesis" -> "Tesis de licenciatura" "phdthesis" -> "Tesis doctoral" -- "candthesis" -> "" -- missing "techreport" -> "informe técnico" -- "resreport" -> "" -- missing -- "software" -> "" -- missing -- "datacd" -> "" -- missing -- "audiocd" -> "" -- missing "patent" -> "patente" "patentde" -> "patente alemana" "patenteu" -> "patente europea" "patentfr" -> "patente francesa" "patentuk" -> "patente británica" "patentus" -> "patente americana" "patreq" -> "solicitud de patente" "patreqde" -> "solicitud de patente alemana" "patreqeu" -> "solicitud de patente europea" "patreqfr" -> "solicitud de patente francesa" "patrequk" -> "solicitud de patente británica" "patrequs" -> "solicitud de patente americana" "countryde" -> "Alemania" "countryeu" -> "Unión Europea" "countryep" -> "Unión Europea" "countryfr" -> "Francia" "countryuk" -> "Reino Unido" "countryus" -> "Estados Unidos de América" "newseries" -> "nueva época" "oldseries" -> "antigua época" _ -> k resolveKey' (Lang "fi" "FI") k = case map toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "tulossa" -- csl "inpress" -> "painossa" -- csl -- "prepublished" -> "" -- missing "mathesis" -> "tutkielma" "phdthesis" -> "tohtorinväitöskirja" "candthesis" -> "kandidat" "techreport" -> "tekninen raportti" "resreport" -> "tutkimusraportti" "software" -> "ohjelmisto" "datacd" -> "data-CD" "audiocd" -> "ääni-CD" "patent" -> "patentti" "patentde" -> "saksalainen patentti" "patenteu" -> "Euroopan Unionin patentti" "patentfr" -> "ranskalainen patentti" "patentuk" -> "englantilainen patentti" "patentus" -> "yhdysvaltalainen patentti" "patreq" -> "patenttihakemus" "patreqde" -> "saksalainen patenttihakemus" "patreqeu" -> "Euroopan Unionin patenttihakemus" "patreqfr" -> "ranskalainen patenttihakemus" "patrequk" -> "englantilainen patenttihakemus" "patrequs" -> "yhdysvaltalainen patenttihakemus" "countryde" -> "Saksa" "countryeu" -> "Euroopan Unioni" "countryep" -> "Euroopan Unioni" "countryfr" -> "Ranska" "countryuk" -> "Iso-Britannia" "countryus" -> "Yhdysvallat" "newseries" -> "uusi sarja" "oldseries" -> "vanha sarja" _ -> k resolveKey' (Lang "fr" "FR") k = case map toLower k of "inpreparation" -> "en préparation" "submitted" -> "soumis" "forthcoming" -> "à paraître" "inpress" -> "sous presse" "prepublished" -> "prépublié" "mathesis" -> "mémoire de master" "phdthesis" -> "thèse de doctorat" "candthesis" -> "thèse de candidature" "techreport" -> "rapport technique" "resreport" -> "rapport scientifique" "software" -> "logiciel" "datacd" -> "cédérom" "audiocd" -> "disque compact audio" "patent" -> "brevet" "patentde" -> "brevet allemand" "patenteu" -> "brevet européen" "patentfr" -> "brevet français" "patentuk" -> "brevet britannique" "patentus" -> "brevet américain" "patreq" -> "demande de brevet" "patreqde" -> "demande de brevet allemand" "patreqeu" -> "demande de brevet européen" "patreqfr" -> "demande de brevet français" "patrequk" -> "demande de brevet britannique" "patrequs" -> "demande de brevet américain" "countryde" -> "Allemagne" "countryeu" -> "Union européenne" "countryep" -> "Union européenne" "countryfr" -> "France" "countryuk" -> "Royaume-Uni" "countryus" -> "États-Unis" "newseries" -> "nouvelle série" "oldseries" -> "ancienne série" _ -> k resolveKey' (Lang "it" "IT") k = case map toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "futuro" -- csl "inpress" -> "in stampa" -- "prepublished" -> "" -- missing "mathesis" -> "tesi di laurea magistrale" "phdthesis" -> "tesi di dottorato" -- "candthesis" -> "" -- missing "techreport" -> "rapporto tecnico" "resreport" -> "rapporto di ricerca" -- "software" -> "" -- missing -- "datacd" -> "" -- missing -- "audiocd" -> "" -- missing "patent" -> "brevetto" "patentde" -> "brevetto tedesco" "patenteu" -> "brevetto europeo" "patentfr" -> "brevetto francese" "patentuk" -> "brevetto britannico" "patentus" -> "brevetto americano" "patreq" -> "brevetto richiesto" "patreqde" -> "brevetto tedesco richiesto" "patreqeu" -> "brevetto europeo richiesto" "patreqfr" -> "brevetto francese richiesto" "patrequk" -> "brevetto britannico richiesto" "patrequs" -> "brevetto U.S.A. richiesto" "countryde" -> "Germania" "countryeu" -> "Unione Europea" "countryep" -> "Unione Europea" "countryfr" -> "Francia" "countryuk" -> "Regno Unito" "countryus" -> "Stati Uniti d’America" "newseries" -> "nuova serie" "oldseries" -> "vecchia serie" _ -> k resolveKey' (Lang "nl" "NL") k = case map toLower k of "inpreparation" -> "in voorbereiding" "submitted" -> "ingediend" "forthcoming" -> "onderweg" "inpress" -> "in druk" "prepublished" -> "voorpublicatie" "mathesis" -> "masterscriptie" "phdthesis" -> "proefschrift" -- "candthesis" -> "" -- missing "techreport" -> "technisch rapport" "resreport" -> "onderzoeksrapport" "software" -> "computersoftware" "datacd" -> "cd-rom" "audiocd" -> "audio-cd" "patent" -> "patent" "patentde" -> "Duits patent" "patenteu" -> "Europees patent" "patentfr" -> "Frans patent" "patentuk" -> "Brits patent" "patentus" -> "Amerikaans patent" "patreq" -> "patentaanvraag" "patreqde" -> "Duitse patentaanvraag" "patreqeu" -> "Europese patentaanvraag" "patreqfr" -> "Franse patentaanvraag" "patrequk" -> "Britse patentaanvraag" "patrequs" -> "Amerikaanse patentaanvraag" "countryde" -> "Duitsland" "countryeu" -> "Europese Unie" "countryep" -> "Europese Unie" "countryfr" -> "Frankrijk" "countryuk" -> "Verenigd Koninkrijk" "countryus" -> "Verenigde Staten van Amerika" "newseries" -> "nieuwe reeks" "oldseries" -> "oude reeks" _ -> k resolveKey' (Lang "pl" "PL") k = case map toLower k of "inpreparation" -> "przygotowanie" "submitted" -> "prezentacja" "forthcoming" -> "przygotowanie" "inpress" -> "wydrukowane" "prepublished" -> "przedwydanie" "mathesis" -> "praca magisterska" "phdthesis" -> "praca doktorska" "techreport" -> "sprawozdanie techniczne" "resreport" -> "sprawozdanie naukowe" "software" -> "oprogramowanie" "datacd" -> "CD-ROM" "audiocd" -> "audio CD" "patent" -> "patent" "patentde" -> "patent Niemiec" "patenteu" -> "patent Europy" "patentfr" -> "patent Francji" "patentuk" -> "patent Wielkiej Brytanji" "patentus" -> "patent USA" "patreq" -> "podanie na patent" "patreqeu" -> "podanie na patent Europy" "patrequs" -> "podanie na patent USA" "countryde" -> "Niemcy" "countryeu" -> "Unia Europejska" "countryep" -> "Unia Europejska" "countryfr" -> "Francja" "countryuk" -> "Wielka Brytania" "countryus" -> "Stany Zjednoczone Ameryki" "newseries" -> "nowa serja" "oldseries" -> "stara serja" _ -> k resolveKey' (Lang "pt" "PT") k = case map toLower k of -- "candthesis" -> "" -- missing "techreport" -> "relatório técnico" "resreport" -> "relatório de pesquisa" "software" -> "software" "datacd" -> "CD-ROM" "patent" -> "patente" "patentde" -> "patente alemã" "patenteu" -> "patente européia" "patentfr" -> "patente francesa" "patentuk" -> "patente britânica" "patentus" -> "patente americana" "patreq" -> "pedido de patente" "patreqde" -> "pedido de patente alemã" "patreqeu" -> "pedido de patente européia" "patreqfr" -> "pedido de patente francesa" "patrequk" -> "pedido de patente britânica" "patrequs" -> "pedido de patente americana" "countryde" -> "Alemanha" "countryeu" -> "União Europeia" "countryep" -> "União Europeia" "countryfr" -> "França" "countryuk" -> "Reino Unido" "countryus" -> "Estados Unidos da América" "newseries" -> "nova série" "oldseries" -> "série antiga" -- "inpreparation" -> "" -- missing "forthcoming" -> "a publicar" -- csl "inpress" -> "na imprensa" -- "prepublished" -> "" -- missing "mathesis" -> "tese de mestrado" "phdthesis" -> "tese de doutoramento" "audiocd" -> "CD áudio" _ -> k resolveKey' (Lang "pt" "BR") k = case map toLower k of -- "candthesis" -> "" -- missing "techreport" -> "relatório técnico" "resreport" -> "relatório de pesquisa" "software" -> "software" "datacd" -> "CD-ROM" "patent" -> "patente" "patentde" -> "patente alemã" "patenteu" -> "patente européia" "patentfr" -> "patente francesa" "patentuk" -> "patente britânica" "patentus" -> "patente americana" "patreq" -> "pedido de patente" "patreqde" -> "pedido de patente alemã" "patreqeu" -> "pedido de patente européia" "patreqfr" -> "pedido de patente francesa" "patrequk" -> "pedido de patente britânica" "patrequs" -> "pedido de patente americana" "countryde" -> "Alemanha" "countryeu" -> "União Europeia" "countryep" -> "União Europeia" "countryfr" -> "França" "countryuk" -> "Reino Unido" "countryus" -> "Estados Unidos da América" "newseries" -> "nova série" "oldseries" -> "série antiga" "inpreparation" -> "em preparação" "forthcoming" -> "aceito para publicação" "inpress" -> "no prelo" "prepublished" -> "pré-publicado" "mathesis" -> "dissertação de mestrado" "phdthesis" -> "tese de doutorado" "audiocd" -> "CD de áudio" _ -> k resolveKey' (Lang "sv" "SE") k = case map toLower k of -- "inpreparation" -> "" -- missing -- "submitted" -> "" -- missing "forthcoming" -> "kommande" -- csl "inpress" -> "i tryck" -- csl -- "prepublished" -> "" -- missing "mathesis" -> "examensarbete" "phdthesis" -> "doktorsavhandling" "candthesis" -> "kandidatavhandling" "techreport" -> "teknisk rapport" "resreport" -> "forskningsrapport" "software" -> "datorprogram" "datacd" -> "data-cd" "audiocd" -> "ljud-cd" "patent" -> "patent" "patentde" -> "tyskt patent" "patenteu" -> "europeiskt patent" "patentfr" -> "franskt patent" "patentuk" -> "brittiskt patent" "patentus" -> "amerikanskt patent" "patreq" -> "patentansökan" "patreqde" -> "ansökan om tyskt patent" "patreqeu" -> "ansökan om europeiskt patent" "patreqfr" -> "ansökan om franskt patent" "patrequk" -> "ansökan om brittiskt patent" "patrequs" -> "ansökan om amerikanskt patent" "countryde" -> "Tyskland" "countryeu" -> "Europeiska unionen" "countryep" -> "Europeiska unionen" "countryfr" -> "Frankrike" "countryuk" -> "Storbritannien" "countryus" -> "USA" "newseries" -> "ny följd" "oldseries" -> "gammal följd" _ -> k resolveKey' _ k = resolveKey' (Lang "en" "US") k parseMonth :: String -> Maybe Int parseMonth s = case map toLower s of "jan" -> Just 1 "feb" -> Just 2 "mar" -> Just 3 "apr" -> Just 4 "may" -> Just 5 "jun" -> Just 6 "jul" -> Just 7 "aug" -> Just 8 "sep" -> Just 9 "oct" -> Just 10 "nov" -> Just 11 "dec" -> Just 12 _ -> safeRead s data BibState = BibState{ untitlecase :: Bool , localeLanguage :: Lang } type Bib = RWST Item () BibState Maybe notFound :: String -> Bib a notFound f = fail $ f ++ " not found" getField :: String -> Bib Formatted getField f = do fs <- asks fields case Map.lookup f fs of Just x -> latex x Nothing -> notFound f getPeriodicalTitle :: String -> Bib Formatted getPeriodicalTitle f = do fs <- asks fields case Map.lookup f fs of Just x -> blocksToFormatted $ onBlocks protectCase $ latex' $ trim x Nothing -> notFound f getTitle :: String -> Bib Formatted getTitle f = do fs <- asks fields case Map.lookup f fs of Just x -> latexTitle x Nothing -> notFound f getShortTitle :: Bool -> String -> Bib Formatted getShortTitle requireColon f = do fs <- asks fields utc <- gets untitlecase let processTitle = if utc then onBlocks unTitlecase else id case Map.lookup f fs of Just x -> case processTitle $ latex' x of bs | not requireColon || containsColon bs -> blocksToFormatted $ upToColon bs | otherwise -> return mempty Nothing -> notFound f containsColon :: [Block] -> Bool containsColon [Para xs] = Str ":" `elem` xs containsColon [Plain xs] = containsColon [Para xs] containsColon _ = False upToColon :: [Block] -> [Block] upToColon [Para xs] = [Para $ takeWhile (/= Str ":") xs] upToColon [Plain xs] = upToColon [Para xs] upToColon bs = bs getDates :: String -> Bib [RefDate] getDates f = parseEDTFDate <$> getRawField f isNumber :: String -> Bool isNumber ('-':d:ds) = all isDigit (d:ds) isNumber (d:ds) = all isDigit (d:ds) isNumber _ = False -- A negative (BC) year might be written with -- or --- in bibtex: fixLeadingDash :: String -> String fixLeadingDash (c:d:ds) | (c == '–' || c == '—') && isDigit d = '-':d:ds fixLeadingDash xs = xs getOldDates :: String -> Bib [RefDate] getOldDates prefix = do year' <- fixLeadingDash <$> getRawField (prefix ++ "year") <|> return "" month' <- (parseMonth <$> getRawField (prefix ++ "month")) <|> return Nothing day' <- (safeRead <$> getRawField (prefix ++ "day")) <|> return Nothing endyear' <- (fixLeadingDash <$> getRawField (prefix ++ "endyear")) <|> return "" endmonth' <- (parseMonth <$> getRawField (prefix ++ "endmonth")) <|> return Nothing endday' <- (safeRead <$> getRawField (prefix ++ "endday")) <|> return Nothing let start' = RefDate { year = safeRead year' , month = month' , season = Nothing , day = day' , other = Literal $ if isNumber year' then "" else year' , circa = False } let end' = RefDate { year = safeRead endyear' , month = endmonth' , day = endday' , season = Nothing , other = Literal $ if isNumber endyear' then "" else endyear' , circa = False } let hasyear r = isJust (year r) return $ filter hasyear [start', end'] getRawField :: String -> Bib String getRawField f = do fs <- asks fields case Map.lookup f fs of Just x -> return x Nothing -> notFound f getAuthorList :: Options -> String -> Bib [Agent] getAuthorList opts f = do fs <- asks fields case Map.lookup f fs of Just x -> latexAuthors opts x Nothing -> notFound f getLiteralList :: String -> Bib [Formatted] getLiteralList f = do fs <- asks fields case Map.lookup f fs of Just x -> toLiteralList $ latex' x Nothing -> notFound f -- separates items with semicolons getLiteralList' :: String -> Bib Formatted getLiteralList' f = (Formatted . intercalate [Str ";", Space] . map unFormatted) <$> getLiteralList f splitByAnd :: [Inline] -> [[Inline]] splitByAnd = splitOn [Space, Str "and", Space] toLiteralList :: [Block] -> Bib [Formatted] toLiteralList [Para xs] = mapM inlinesToFormatted $ splitByAnd xs toLiteralList [Plain xs] = toLiteralList [Para xs] toLiteralList _ = mzero toAuthorList :: Options -> [Block] -> Bib [Agent] toAuthorList opts [Para xs] = filter (/= emptyAgent) <$> mapM (toAuthor opts) (splitByAnd xs) toAuthorList opts [Plain xs] = toAuthorList opts [Para xs] toAuthorList _ _ = mzero toAuthor :: Options -> [Inline] -> Bib Agent toAuthor _ [Str "others"] = return Agent { givenName = [] , droppingPart = mempty , nonDroppingPart = mempty , familyName = mempty , nameSuffix = mempty , literal = Formatted [Str "others"] , commaSuffix = False , parseNames = False } toAuthor _ [Span ("",[],[]) ils] = return -- corporate author Agent { givenName = [] , droppingPart = mempty , nonDroppingPart = mempty , familyName = mempty , nameSuffix = mempty , literal = Formatted ils , commaSuffix = False , parseNames = False } -- extended BibLaTeX name format - see #266 toAuthor _ ils@(Str ys:_) | '=' `elem` ys = do let commaParts = splitWhen (== Str ",") $ splitStrWhen (\c -> c == ',' || c == '=' || c == '\160') $ ils let addPart ag (Str "given" : Str "=" : xs) = ag{ givenName = givenName ag ++ [Formatted xs] } addPart ag (Str "family" : Str "=" : xs) = ag{ familyName = Formatted xs } addPart ag (Str "prefix" : Str "=" : xs) = ag{ droppingPart = Formatted xs } addPart ag (Str "useprefix" : Str "=" : Str "true" : _) = ag{ nonDroppingPart = droppingPart ag, droppingPart = mempty } addPart ag (Str "suffix" : Str "=" : xs) = ag{ nameSuffix = Formatted xs } addPart ag (Space : xs) = addPart ag xs addPart ag _ = ag return $ foldl' addPart emptyAgent commaParts -- First von Last -- von Last, First -- von Last, Jr ,First -- NOTE: biblatex and bibtex differ on: -- Drummond de Andrade, Carlos -- bibtex takes "Drummond de" as the von; -- biblatex takes the whole as a last name. -- See https://github.com/plk/biblatex/issues/236 -- Here we implement the more sensible biblatex behavior. toAuthor opts ils = do let useprefix = optionSet "useprefix" opts let usecomma = optionSet "juniorcomma" opts let bibtex = optionSet "bibtex" opts let words' = wordsBy (\x -> x == Space || x == Str "\160") let commaParts = map words' $ splitWhen (== Str ",") $ splitStrWhen (\c -> c == ',' || c == '\160') ils let (first, vonlast, jr) = case commaParts of --- First is the longest sequence of white-space separated -- words starting with an uppercase and that is not the -- whole string. von is the longest sequence of whitespace -- separated words whose last word starts with lower case -- and that is not the whole string. [fvl] -> let (caps', rest') = span isCapitalized fvl in if null rest' && not (null caps') then (init caps', [last caps'], []) else (caps', rest', []) [vl,f] -> (f, vl, []) (vl:j:f:_) -> (f, vl, j ) [] -> ([], [], []) let (von, lastname) = if bibtex then case span isCapitalized $ reverse vonlast of ([],w:ws) -> (reverse ws, [w]) (vs, ws) -> (reverse ws, reverse vs) else case break isCapitalized vonlast of (vs@(_:_), []) -> (init vs, [last vs]) (vs, ws) -> (vs, ws) let prefix = Formatted $ intercalate [Space] von let family = Formatted $ intercalate [Space] lastname let suffix = Formatted $ intercalate [Space] jr let givens = map Formatted first return Agent { givenName = givens , droppingPart = if useprefix then mempty else prefix , nonDroppingPart = if useprefix then prefix else mempty , familyName = family , nameSuffix = suffix , literal = mempty , commaSuffix = usecomma , parseNames = False } isCapitalized :: [Inline] -> Bool isCapitalized (Str (c:cs) : rest) | isUpper c = True | isDigit c = isCapitalized (Str cs : rest) | otherwise = False isCapitalized (_:rest) = isCapitalized rest isCapitalized [] = True optionSet :: String -> Options -> Bool optionSet key opts = case lookup key opts of Just "true" -> True Just s -> s == mempty _ -> False latex' :: String -> [Block] latex' s = Walk.walk removeSoftBreak bs where Pandoc _ bs = readLaTeX s removeSoftBreak :: Inline -> Inline removeSoftBreak SoftBreak = Space removeSoftBreak x = x latex :: String -> Bib Formatted latex s = blocksToFormatted $ latex' $ trim s latexTitle :: String -> Bib Formatted latexTitle s = do utc <- gets untitlecase let processTitle = if utc then onBlocks unTitlecase else id blocksToFormatted $ processTitle $ latex' s latexAuthors :: Options -> String -> Bib [Agent] latexAuthors opts = toAuthorList opts . latex' . trim bib :: Bib Reference -> Item -> Maybe Reference bib m entry = fst Control.Applicative.<$> evalRWST m entry (BibState True (Lang "en" "US")) toLocale :: String -> String toLocale "english" = "en-US" -- "en-EN" unavailable in CSL toLocale "usenglish" = "en-US" toLocale "american" = "en-US" toLocale "british" = "en-GB" toLocale "ukenglish" = "en-GB" toLocale "canadian" = "en-US" -- "en-CA" unavailable in CSL toLocale "australian" = "en-GB" -- "en-AU" unavailable in CSL toLocale "newzealand" = "en-GB" -- "en-NZ" unavailable in CSL toLocale "afrikaans" = "af-ZA" toLocale "arabic" = "ar" toLocale "basque" = "eu" toLocale "bulgarian" = "bg-BG" toLocale "catalan" = "ca-AD" toLocale "croatian" = "hr-HR" toLocale "czech" = "cs-CZ" toLocale "danish" = "da-DK" toLocale "dutch" = "nl-NL" toLocale "estonian" = "et-EE" toLocale "finnish" = "fi-FI" toLocale "canadien" = "fr-CA" toLocale "acadian" = "fr-CA" toLocale "french" = "fr-FR" toLocale "francais" = "fr-FR" toLocale "austrian" = "de-AT" toLocale "naustrian" = "de-AT" toLocale "german" = "de-DE" toLocale "germanb" = "de-DE" toLocale "ngerman" = "de-DE" toLocale "greek" = "el-GR" toLocale "polutonikogreek" = "el-GR" toLocale "hebrew" = "he-IL" toLocale "hungarian" = "hu-HU" toLocale "icelandic" = "is-IS" toLocale "italian" = "it-IT" toLocale "japanese" = "ja-JP" toLocale "latvian" = "lv-LV" toLocale "lithuanian" = "lt-LT" toLocale "magyar" = "hu-HU" toLocale "mongolian" = "mn-MN" toLocale "norsk" = "nb-NO" toLocale "nynorsk" = "nn-NO" toLocale "farsi" = "fa-IR" toLocale "polish" = "pl-PL" toLocale "brazil" = "pt-BR" toLocale "brazilian" = "pt-BR" toLocale "portugues" = "pt-PT" toLocale "portuguese" = "pt-PT" toLocale "romanian" = "ro-RO" toLocale "russian" = "ru-RU" toLocale "serbian" = "sr-RS" toLocale "serbianc" = "sr-RS" toLocale "slovak" = "sk-SK" toLocale "slovene" = "sl-SL" toLocale "spanish" = "es-ES" toLocale "swedish" = "sv-SE" toLocale "thai" = "th-TH" toLocale "turkish" = "tr-TR" toLocale "ukrainian" = "uk-UA" toLocale "vietnamese" = "vi-VN" toLocale "latin" = "la" toLocale x = x concatWith :: Char -> [Formatted] -> Formatted concatWith sep = Formatted . foldl' go mempty . map unFormatted where go :: [Inline] -> [Inline] -> [Inline] go accum [] = accum go accum s = case reverse accum of [] -> s (Str x:_) | not (null x) && last x `elem` "!?.,:;" -> accum ++ (Space : s) _ -> accum ++ (Str [sep] : Space : s) type Options = [(String, String)] parseOptions :: String -> Options parseOptions = map breakOpt . splitWhen (==',') where breakOpt x = case break (=='=') x of (w,v) -> (map toLower $ trim w, map toLower $ trim $ drop 1 v) ordinalize :: Locale -> String -> String ordinalize locale n = case [termSingular c | c <- terms, cslTerm c == ("ordinal-" ++ pad0 n)] ++ [termSingular c | c <- terms, cslTerm c == "ordinal"] of (suff:_) -> n ++ suff [] -> n where pad0 [c] = ['0',c] pad0 s = s terms = localeTerms locale itemToReference :: Lang -> Locale -> Bool -> Bool -> Item -> Maybe Reference itemToReference lang locale bibtex caseTransform = bib $ do modify $ \st -> st{ localeLanguage = lang, untitlecase = case lang of Lang "en" _ -> caseTransform _ -> False } id' <- asks identifier otherIds <- (map trim . splitWhen (==',') <$> getRawField "ids") <|> return [] et <- asks entryType guard $ et /= "xdata" opts <- (parseOptions <$> getRawField "options") <|> return [] let getAuthorList' = getAuthorList (("bibtex", map toLower $ show bibtex):opts) st <- getRawField "entrysubtype" <|> return mempty isEvent <- (True <$ (getRawField "eventdate" <|> getRawField "eventtitle" <|> getRawField "venue")) <|> return False reftype' <- resolveKey lang <$> getField "type" <|> return mempty let (reftype, refgenre) = case et of "article" | st == "magazine" -> (ArticleMagazine,mempty) | st == "newspaper" -> (ArticleNewspaper,mempty) | otherwise -> (ArticleJournal,mempty) "book" -> (Book,mempty) "booklet" -> (Pamphlet,mempty) "bookinbook" -> (Chapter,mempty) "collection" -> (Book,mempty) "electronic" -> (Webpage,mempty) "inbook" -> (Chapter,mempty) "incollection" -> (Chapter,mempty) "inreference" -> (EntryEncyclopedia,mempty) "inproceedings" -> (PaperConference,mempty) "manual" -> (Book,mempty) "mastersthesis" -> (Thesis, if reftype' == mempty then Formatted [Str $ resolveKey' lang "mathesis"] else reftype') "misc" -> (NoType,mempty) "mvbook" -> (Book,mempty) "mvcollection" -> (Book,mempty) "mvproceedings" -> (Book,mempty) "mvreference" -> (Book,mempty) "online" -> (Webpage,mempty) "patent" -> (Patent,mempty) "periodical" | st == "magazine" -> (ArticleMagazine,mempty) | st == "newspaper" -> (ArticleNewspaper,mempty) | otherwise -> (ArticleJournal,mempty) "phdthesis" -> (Thesis, if reftype' == mempty then Formatted [Str $ resolveKey' lang "phdthesis"] else reftype') "proceedings" -> (Book,mempty) "reference" -> (Book,mempty) "report" -> (Report,mempty) "suppbook" -> (Chapter,mempty) "suppcollection" -> (Chapter,mempty) "suppperiodical" | st == "magazine" -> (ArticleMagazine,mempty) | st == "newspaper" -> (ArticleNewspaper,mempty) | otherwise -> (ArticleJournal,mempty) "techreport" -> (Report,mempty) "thesis" -> (Thesis,mempty) "unpublished" -> (if isEvent then Speech else Manuscript,mempty) "www" -> (Webpage,mempty) -- biblatex, "unsupported" "artwork" -> (Graphic,mempty) "audio" -> (Song,mempty) -- for audio *recordings* "commentary" -> (Book,mempty) "image" -> (Graphic,mempty) -- or "figure" ? "jurisdiction" -> (LegalCase,mempty) "legislation" -> (Legislation,mempty) -- or "bill" ? "legal" -> (Treaty,mempty) "letter" -> (PersonalCommunication,mempty) "movie" -> (MotionPicture,mempty) "music" -> (Song,mempty) -- for musical *recordings* "performance" -> (Speech,mempty) "review" -> (Review,mempty) -- or "review-book" ? "software" -> (Book,mempty) -- for lack of any better match "standard" -> (Legislation,mempty) "video" -> (MotionPicture,mempty) -- biblatex-apa: "data" -> (Dataset,mempty) "letters" -> (PersonalCommunication,mempty) "newsarticle" -> (ArticleNewspaper,mempty) _ -> (NoType,mempty) -- hyphenation: let defaultHyphenation = case lang of Lang x y -> x ++ "-" ++ y let getLangId = do langid <- (trim . map toLower) <$> getRawField "langid" idopts <- (trim . map toLower) <$> getRawField "langidopts" <|> return "" case (langid, idopts) of ("english","variant=british") -> return "british" ("english","variant=american") -> return "american" ("english","variant=us") -> return "american" ("english","variant=usmax") -> return "american" ("english","variant=uk") -> return "british" ("english","variant=australian") -> return "australian" ("english","variant=newzealand") -> return "newzealand" (x,_) -> return x hyphenation <- ((toLocale . map toLower) <$> (getLangId <|> getRawField "hyphenation")) <|> return mempty -- authors: author' <- getAuthorList' "author" <|> return [] containerAuthor' <- getAuthorList' "bookauthor" <|> return [] translator' <- getAuthorList' "translator" <|> return [] editortype <- getRawField "editortype" <|> return mempty editor'' <- getAuthorList' "editor" <|> return [] director'' <- getAuthorList' "director" <|> return [] let (editor', director') = case editortype of "director" -> ([], editor'') _ -> (editor'', director'') -- FIXME: add same for editora, editorb, editorc -- titles let isArticle = et `elem` ["article", "periodical", "suppperiodical", "review"] let isPeriodical = et == "periodical" let isChapterlike = et `elem` ["inbook","incollection","inproceedings","inreference","bookinbook"] hasMaintitle <- (True <$ getRawField "maintitle") <|> return False let hyphenation' = if null hyphenation then defaultHyphenation else hyphenation let la = case splitWhen (== '-') hyphenation' of (x:_) -> x [] -> mempty modify $ \s -> s{ untitlecase = caseTransform && la == "en" } title' <- (guard isPeriodical >> getTitle "issuetitle") <|> (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "maintitle") <|> getTitle "title" <|> return mempty subtitle' <- (guard isPeriodical >> getTitle "issuesubtitle") <|> (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "mainsubtitle") <|> getTitle "subtitle" <|> return mempty titleaddon' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "maintitleaddon") <|> getTitle "titleaddon" <|> return mempty volumeTitle' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "title") <|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booktitle") <|> return mempty volumeSubtitle' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "subtitle") <|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booksubtitle") <|> return mempty volumeTitleAddon' <- (guard hasMaintitle >> guard (not isChapterlike) >> getTitle "titleaddon") <|> (guard hasMaintitle >> guard isChapterlike >> getTitle "booktitleaddon") <|> return mempty containerTitle' <- (guard isPeriodical >> getPeriodicalTitle "title") <|> (guard isChapterlike >> getTitle "maintitle") <|> (guard isChapterlike >> getTitle "booktitle") <|> getPeriodicalTitle "journaltitle" <|> getPeriodicalTitle "journal" <|> return mempty containerSubtitle' <- (guard isPeriodical >> getPeriodicalTitle "subtitle") <|> (guard isChapterlike >> getTitle "mainsubtitle") <|> (guard isChapterlike >> getTitle "booksubtitle") <|> getPeriodicalTitle "journalsubtitle" <|> return mempty containerTitleAddon' <- (guard isPeriodical >> getPeriodicalTitle "titleaddon") <|> (guard isChapterlike >> getTitle "maintitleaddon") <|> (guard isChapterlike >> getTitle "booktitleaddon") <|> return mempty containerTitleShort' <- (guard isPeriodical >> guard (not hasMaintitle) >> getField "shorttitle") <|> getPeriodicalTitle "shortjournal" <|> return mempty -- change numerical series title to e.g. 'series 3' let fixSeriesTitle (Formatted [Str xs]) | all isDigit xs = Formatted [Str (ordinalize locale xs), Space, Str (resolveKey' lang "ser.")] fixSeriesTitle x = x seriesTitle' <- (fixSeriesTitle . resolveKey lang) <$> getTitle "series" <|> return mempty shortTitle' <- (guard (not hasMaintitle || isChapterlike) >> getTitle "shorttitle") <|> if (subtitle' /= mempty || titleaddon' /= mempty) && not hasMaintitle then getShortTitle False "title" else getShortTitle True "title" <|> return mempty eventTitle' <- getTitle "eventtitle" <|> return mempty origTitle' <- getTitle "origtitle" <|> return mempty -- publisher pubfields <- mapM (\f -> Just `fmap` (if bibtex || f == "howpublished" then getField f else getLiteralList' f) <|> return Nothing) ["school","institution","organization", "howpublished","publisher"] let publisher' = concatWith ';' $ catMaybes pubfields origpublisher' <- getField "origpublisher" <|> return mempty -- places venue' <- getField "venue" <|> return mempty address' <- (if bibtex then getField "address" else getLiteralList' "address" <|> (guard (et /= "patent") >> getLiteralList' "location")) <|> return mempty origLocation' <- (if bibtex then getField "origlocation" else getLiteralList' "origlocation") <|> return mempty jurisdiction' <- if et == "patent" then ((concatWith ';' . map (resolveKey lang)) <$> getLiteralList "location") <|> return mempty else return mempty -- locators pages' <- getField "pages" <|> return mempty volume' <- getField "volume" <|> return mempty part' <- getField "part" <|> return mempty volumes' <- getField "volumes" <|> return mempty pagetotal' <- getField "pagetotal" <|> return mempty chapter' <- getField "chapter" <|> return mempty edition' <- getField "edition" <|> return mempty version' <- getField "version" <|> return mempty (number', collectionNumber', issue') <- (getField "number" <|> return mempty) >>= \x -> if et `elem` ["book","collection","proceedings","reference", "mvbook","mvcollection","mvproceedings", "mvreference", "bookinbook","inbook", "incollection","inproceedings", "inreference", "suppbook","suppcollection"] then return (mempty,x,mempty) else if isArticle then (getField "issue" >>= \y -> return (mempty,mempty,concatWith ',' [x,y])) <|> return (mempty,mempty,x) else return (x,mempty,mempty) -- dates issued' <- getDates "date" <|> getOldDates mempty <|> return [] eventDate' <- getDates "eventdate" <|> getOldDates "event" <|> return [] origDate' <- getDates "origdate" <|> getOldDates "orig" <|> return [] accessed' <- getDates "urldate" <|> getOldDates "url" <|> return [] -- url, doi, isbn, etc.: -- note that with eprinttype = arxiv, we take eprint to be a partial url -- archivePrefix is an alias for eprinttype url' <- (guard (et == "online" || lookup "url" opts /= Just "false") >> getRawField "url") <|> (do etype <- getRawField "eprinttype" eprint <- getRawField "eprint" let baseUrl = case map toLower etype of "arxiv" -> "http://arxiv.org/abs/" "jstor" -> "http://www.jstor.org/stable/" "pubmed" -> "http://www.ncbi.nlm.nih.gov/pubmed/" "googlebooks" -> "http://books.google.com?id=" _ -> "" if null baseUrl then mzero else return $ baseUrl ++ eprint) <|> return mempty doi' <- (guard (lookup "doi" opts /= Just "false") >> getRawField "doi") <|> return mempty isbn' <- getRawField "isbn" <|> return mempty issn' <- getRawField "issn" <|> return mempty pmid' <- getRawField "pmid" <|> return mempty pmcid' <- getRawField "pmcid" <|> return mempty callNumber' <- getRawField "library" <|> return mempty -- notes annotation' <- getField "annotation" <|> getField "annote" <|> return mempty abstract' <- getField "abstract" <|> return mempty keywords' <- getField "keywords" <|> return mempty note' <- if et == "periodical" then return mempty else getField "note" <|> return mempty addendum' <- if bibtex then return mempty else getField "addendum" <|> return mempty pubstate' <- resolveKey lang `fmap` ( getField "pubstate" <|> case issued' of (x:_) | other x == Literal "forthcoming" -> return (Formatted [Str "forthcoming"]) _ -> return mempty ) let convertEnDash (Str s) = Str (map (\c -> if c == '–' then '-' else c) s) convertEnDash x = x let takeDigits (Str xs : _) = case takeWhile isDigit xs of [] -> [] ds -> [Str ds] takeDigits x = x return $ emptyReference { refId = Literal id' , refOtherIds = map Literal otherIds , refType = reftype , author = author' , editor = editor' , translator = translator' -- , recipient = undefined -- :: [Agent] -- , interviewer = undefined -- :: [Agent] -- , composer = undefined -- :: [Agent] , director = director' -- , illustrator = undefined -- :: [Agent] -- , originalAuthor = undefined -- :: [Agent] , containerAuthor = containerAuthor' -- , collectionEditor = undefined -- :: [Agent] -- , editorialDirector = undefined -- :: [Agent] -- , reviewedAuthor = undefined -- :: [Agent] , issued = issued' , eventDate = eventDate' , accessed = accessed' -- , container = undefined -- :: [RefDate] , originalDate = origDate' -- , submitted = undefined -- :: [RefDate] , title = concatWith '.' [ concatWith ':' [title', subtitle'] , titleaddon' ] , titleShort = shortTitle' -- , reviewedTitle = undefined -- :: String , containerTitle = concatWith '.' [ concatWith ':' [ containerTitle' , containerSubtitle'] , containerTitleAddon' ] , collectionTitle = seriesTitle' , volumeTitle = concatWith '.' [ concatWith ':' [ volumeTitle' , volumeSubtitle'] , volumeTitleAddon' ] , containerTitleShort = containerTitleShort' , collectionNumber = collectionNumber' , originalTitle = origTitle' , publisher = publisher' , originalPublisher = origpublisher' , publisherPlace = address' , originalPublisherPlace = origLocation' , jurisdiction = jurisdiction' , event = eventTitle' , eventPlace = venue' , page = Formatted $ Walk.walk convertEnDash $ unFormatted pages' , pageFirst = Formatted $ takeDigits $ unFormatted pages' , numberOfPages = pagetotal' , version = version' , volume = Formatted $ intercalate [Str "."] $ filter (not . null) [unFormatted volume', unFormatted part'] , numberOfVolumes = volumes' , issue = issue' , chapterNumber = chapter' -- , medium = undefined -- :: String , status = pubstate' , edition = edition' -- , section = undefined -- :: String -- , source = undefined -- :: String , genre = if refgenre == mempty then reftype' else refgenre , note = concatWith '.' [note', addendum'] , annote = annotation' , abstract = abstract' , keyword = keywords' , number = number' , url = Literal url' , doi = Literal doi' , isbn = Literal isbn' , issn = Literal issn' , pmcid = Literal pmcid' , pmid = Literal pmid' , language = Literal hyphenation , callNumber = Literal callNumber' }
adunning/pandoc-citeproc
src/Text/CSL/Input/Bibtex.hs
Haskell
bsd-3-clause
66,320
module Noobing.Experimenting.IO ( hello ) where hello :: IO () hello = do putStrLn "hello!"
markmq/Noobing
src/Noobing/Experimenting/IO.hs
Haskell
bsd-3-clause
95
{-# LANGUAGE TupleSections #-} module Day17 where -- Improvements to Day12 import Control.Monad.Reader import Control.Monad.Trans.Either import qualified Data.Map as Map data Type = Function Type Type | RecordT [(String, Type)] | VariantT [(String, Type)] deriving (Eq, Show) data CheckTerm -- neither a constructor nor change of direction = Let InferTerm Type (InferTerm -> CheckTerm) -- | Fresh -- switch direction (check -> infer) | Neutral InferTerm -- constructors -- \x -> CheckedTerm | Abs (CheckTerm -> CheckTerm) | Record [(String, CheckTerm)] | Variant String CheckTerm data InferTerm -- switch direction (infer -> check) = Annot CheckTerm Type -- eliminators -- -- note that eliminators always take an InferTerm as the inspected term, -- since that's the neutral position, then CheckTerms for the rest | App InferTerm CheckTerm | AccessField InferTerm String Type | Case InferTerm Type [(String, CheckTerm -> CheckTerm)] xxx = error "not yet implemented" eval :: InferTerm -> EvalCtx CheckTerm eval t = case t of Annot cTerm _ -> return cTerm App f x -> do f' <- eval f case f' of Neutral _ -> xxx Abs f'' -> return $ f'' x AccessField iTm name _ -> do evaled <- eval iTm case evaled of Neutral _ -> return $ Neutral (AccessField xxx xxx xxx) Record fields -> case Map.lookup name (Map.fromList fields) of Just field -> return field Nothing -> left "didn't find field in record" _ -> left "unexpected" Case iTm _ branches -> do evaled <- eval iTm case evaled of Neutral _ -> xxx Variant name cTm -> case Map.lookup name (Map.fromList branches) of Just branch -> return $ branch evaled -- evalC :: CheckTerm -> EvalCtx CheckTerm -- evalC t = case t of -- Let iTm _ body -> return $ body iTm -- Neutral _ -> return t -- Abs body -> -- -- Record [(String, CheckTerm)] -- -- Variant String CheckTerm type EvalCtx = EitherT String (Reader [CheckTerm]) type CheckCtx = EitherT String (Reader [Type]) runChecker :: CheckCtx () -> Maybe String runChecker calc = case runReader (runEitherT calc) [] of Right () -> Nothing Left str -> Just str unifyTy :: Type -> Type -> CheckCtx Type unifyTy (Function dom1 codom1) (Function dom2 codom2) = Function <$> unifyTy dom1 dom2 <*> unifyTy codom1 codom2 unifyTy (RecordT lTy) (RecordT rTy) = do -- RecordT [(String, Type)] -- Take the intersection of possible records. Make sure the overlap matches! let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy) isect' <- mapM (uncurry unifyTy) isect return $ RecordT (Map.toList isect') unifyTy (VariantT lTy) (VariantT rTy) = do -- Take the union of possible variants. Make sure overlap matches! let isect = Map.intersectionWith (,) (Map.fromList lTy) (Map.fromList rTy) isect' <- mapM (uncurry unifyTy) isect let union = Map.union (Map.fromList lTy) (Map.fromList rTy) -- Overwrite with extra data we may have learned from unifying the types in -- the intersection let result = Map.union isect' union return $ VariantT (Map.toList result) unifyTy l r = left ("failed unification " ++ show (l, r)) check :: CheckTerm -> Type -> CheckCtx () check tm ty = case tm of -- t1: infered, t2: infer -> check Let t1 ty' body -> do t1Ty <- infer t1 _ <- unifyTy t1Ty ty' let bodyVal = body t1 check bodyVal ty Neutral iTm -> do iTy <- infer iTm unifyTy ty iTy return () Abs t' -> do let Function domain codomain = ty check t' codomain Record fields -> do -- Record [(String, CheckTerm)] -- -- Here we define our notion of record subtyping -- we check that the -- record we've been given has at least the fields expected of it and of -- the right type. let fieldMap = Map.fromList fields case ty of RecordT fieldTys -> mapM_ (\(name, subTy) -> do case Map.lookup name fieldMap of Just subTm -> check subTm subTy Nothing -> left "failed to find required field in record" ) fieldTys _ -> left "failed to check a record against a non-record type" Variant name t' -> do -- Variant String CheckTerm -- -- Here we define our notion of variant subtyping -- we check that the -- variant we've been given is in the row case ty of VariantT fieldTys -> case Map.lookup name (Map.fromList fieldTys) of Just expectedTy -> check t' expectedTy Nothing -> left "failed to find required field in record" _ -> left "failed to check a record against a non-record type" Neutral tm' -> do ty' <- infer tm' _ <- unifyTy ty ty' return () infer :: InferTerm -> CheckCtx Type infer t = case t of Annot _ ty -> pure ty App t1 t2 -> do Function domain codomain <- infer t1 check t2 domain return codomain -- k (rec.name : ty) AccessField recTm name ty' kTm -> do inspectTy <- infer recTm case inspectTy of RecordT parts -> case Map.lookup name (Map.fromList parts) of Just subTy -> do local (subTy:) (check kTm ty') return ty' Nothing -> left "didn't find the accessed key" _ -> left "found non-record unexpectedly" Case varTm ty cases -> do varTmTy <- infer varTm case varTmTy of VariantT tyParts -> do let tyMap = Map.fromList tyParts caseMap = Map.fromList cases bothMatch = (Map.null (tyMap Map.\\ caseMap)) && (Map.null (caseMap Map.\\ tyMap)) when (not bothMatch) (left "case misalignment") let mergedMap = Map.mergeWithKey (\k a b -> Just (k, a, b)) (const (Map.fromList [])) (const (Map.fromList [])) tyMap caseMap mapM_ (\(_name, branchTy, rhs) -> local (branchTy:) (check rhs ty)) mergedMap _ -> left "found non-variant in case" return ty main :: IO () main = do let unit = Record [] unitTy = RecordT [] xy = Record [ ("x", unit) , ("y", unit) ] xyTy = RecordT [ ("x", unitTy) , ("y", unitTy) ] -- boring print $ runChecker $ let tm = Abs (\x -> Neutral x) ty = Function unitTy unitTy in check tm ty -- standard record print $ runChecker $ let tm = Let (Annot xy xyTy) xyTy (\x -> Neutral (AccessField x "x" unitTy (Neutral x)) ) in check tm unitTy -- record subtyping print $ runChecker $ let xRecTy = RecordT [("x", unitTy)] tm = Let (Annot xy xRecTy) xRecTy (\x -> Neutral (AccessField x "x" unitTy (Neutral x)) ) in check tm unitTy -- variant subtyping print $ runChecker $ let eitherTy = VariantT [ ("left", unitTy) , ("right", unitTy) ] tm = Let (Annot (Variant "left" unit) eitherTy) eitherTy (Abs (\x -> Neutral (Case x unitTy [ ("left", (Neutral x)) , ("right", (Neutral x)) ] ) )) in check tm unitTy
joelburget/daily-typecheckers
src/Day17.hs
Haskell
bsd-3-clause
7,281
{-# LANGUAGE GADTs #-} module Term where data Term t where Zero :: Term Int Succ :: Term Int -> Term Int Pred :: Term Int -> Term Int IsZero :: Term Int -> Term Bool If :: Term Bool -> Term a -> Term a -> Term a eval :: Term t -> t eval Zero = 0 eval (Succ e) = succ (eval e) eval (Pred e) = pred (eval e) eval (IsZero e) = eval e == 0 eval (If p t f) = if eval p then eval t else eval f one = Succ Zero true = IsZero Zero false = IsZero one
maoe/fop
12-Fun-with-Phantom-Types/Term.hs
Haskell
bsd-3-clause
478
{-# OPTIONS_GHC -Wall #-} module System.Console.ShSh.Builtins.Cmp ( cmp ) where import System.Console.ShSh.Builtins.Args ( withArgs, flagOn, flag ) import System.Console.ShSh.Builtins.Util ( readFileOrStdin ) import System.Console.ShSh.Shell ( Shell ) import System.Exit ( ExitCode(..) ) {-# NOINLINE cmp #-} cmp :: [String] -> Shell ExitCode cmp = withArgs "cmp" header args run where run [] = fail "missing operand" run [s] = fail $ "missing operand after `"++s++"'" run [a,b] = do aa <- filter (/='\r') `fmap` readFileOrStdin a bb <- filter (/='\r') `fmap` readFileOrStdin b if length aa == length bb && aa == bb then return ExitSuccess else fail' $ unwords ["files",a,"and",b, "differ.", show $ length aa, show $ length bb] run as = fail $ "too many arguments: "++ show (length as) fail' msg = do silent <- flag 's' if silent then return $ ExitFailure 1 else fail msg args = [flagOn "s" ["quiet","silent"] 's' "No output; only exitcode." ] header = "Usage: cmp [OPTIONS...] FILE1 FILE2\n"++ "Compare two files byte by byte."
shicks/shsh
System/Console/ShSh/Builtins/Cmp.hs
Haskell
bsd-3-clause
1,457
{-# LANGUAGE QuasiQuotes #-} module LLVM.General.Quote.Test.DataLayout where import Test.Tasty import Test.Tasty.HUnit import Test.HUnit import Data.Maybe import qualified Data.Set as Set import qualified Data.Map as Map import LLVM.General.Quote.LLVM import LLVM.General.AST import LLVM.General.AST.DataLayout import LLVM.General.AST.AddrSpace import qualified LLVM.General.AST.Global as G m s = "; ModuleID = '<string>'\n" ++ s t s = "target datalayout = \"" ++ s ++ "\"\n" tests = testGroup "DataLayout" [ testCase name $ sdl @?= (Module "<string>" mdl Nothing []) | (name, mdl, sdl) <- [ ("none", Nothing, [llmod||]), ("little-endian", Just defaultDataLayout { endianness = Just LittleEndian }, [llmod|target datalayout = "e"|]), ("big-endian", Just defaultDataLayout { endianness = Just BigEndian }, [llmod|target datalayout = "E"|]), ("native", Just defaultDataLayout { nativeSizes = Just (Set.fromList [8,32]) }, [llmod|target datalayout = "n8:32"|]), ( "no pref", Just defaultDataLayout { pointerLayouts = Map.singleton (AddrSpace 0) ( 8, AlignmentInfo { abiAlignment = 64, preferredAlignment = Nothing } ) }, [llmod|target datalayout = "p:8:64"|] ), ( "no pref", Just defaultDataLayout { pointerLayouts = Map.singleton (AddrSpace 1) ( 8, AlignmentInfo { abiAlignment = 32, preferredAlignment = Just 64 } ) }, [llmod|target datalayout = "p1:8:32:64"|] ), ( "big", Just DataLayout { endianness = Just LittleEndian, stackAlignment = Just 128, pointerLayouts = Map.fromList [ (AddrSpace 0, (64, AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64})) ], typeLayouts = Map.fromList [ ((IntegerAlign, 1), AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 8}), ((IntegerAlign, 8), AlignmentInfo {abiAlignment = 8, preferredAlignment = Just 8}), ((IntegerAlign, 16), AlignmentInfo {abiAlignment = 16, preferredAlignment = Just 16}), ((IntegerAlign, 32), AlignmentInfo {abiAlignment = 32, preferredAlignment = Just 32}), ((IntegerAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64}), ((VectorAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64}), ((VectorAlign, 128), AlignmentInfo {abiAlignment = 128, preferredAlignment = Just 128}), ((FloatAlign, 32), AlignmentInfo {abiAlignment = 32, preferredAlignment = Just 32}), ((FloatAlign, 64), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64}), ((FloatAlign, 80), AlignmentInfo {abiAlignment = 128, preferredAlignment = Just 128}), ((AggregateAlign, 0), AlignmentInfo {abiAlignment = 0, preferredAlignment = Just 64}), ((StackAlign, 0), AlignmentInfo {abiAlignment = 64, preferredAlignment = Just 64}) ], nativeSizes = Just (Set.fromList [8,16,32,64]) }, [llmod|target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64-S128"|] ) ] ]
tvh/llvm-general-quote
test/LLVM/General/Quote/Test/DataLayout.hs
Haskell
bsd-3-clause
3,333
{-| Module : Database.Relational.Project Description : Definition of PROJECT and friends. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE PatternSynonyms #-} module Database.Relational.Project ( PROJECT(..) , type (:|:) , pattern (:|:) {- , ProjectColumns , ProjectTableNames , ProjectAliases , ProjectTypes -} ) where import Data.Proxy import Database.Relational.Column -- | Intended use: give a column and a table name for the left parameter, so as -- to resolve a column within a query ("my_table.my_column"), and then give -- an alias for this column. -- The right parameter is either another PROJECT with the same contract, or -- P. data PROJECT left right where PROJECT :: left -> right -> PROJECT left right infixr 8 :|: type (:|:) = PROJECT pattern left :|: right = PROJECT left right {- type family ProjectColumns project where ProjectColumns P = '[] ProjectColumns (PROJECT '(tableName, column, alias) rest) = column ': (ProjectColumns rest) type family ProjectTableNames project where ProjectTableNames P = '[] ProjectTableNames (PROJECT '(tableName, column, alias) rest) = tableName ': (ProjectTableNames rest) type family ProjectAliases project where ProjectAliases P = '[] ProjectAliases (PROJECT '(tableName, column, alias) rest) = alias ': (ProjectAliases rest) type family ProjectTypes project where ProjectTypes P = '[] ProjectTypes (PROJECT '(tableName, column, alias) rest) = ColumnType column ': ProjectTypes rest -}
avieth/Relational
Database/Relational/Project.hs
Haskell
bsd-3-clause
1,841
{-# OPTIONS_GHC -Wall #-} {-# LANGUAGE OverloadedStrings #-} module Develop.Generate.Index ( toHtml , getProject , moveToRoot ) where import Control.Monad (filterM) import Data.Aeson ((.=)) import qualified Data.Aeson as Json import qualified Data.ByteString.Lazy.UTF8 as BSU8 import qualified Data.List as List import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified System.Directory as Dir import System.FilePath ((</>), joinPath, splitDirectories, takeExtension) import qualified Text.Blaze.Html5 as H import qualified Develop.Generate.Help as Help import qualified Develop.StaticFiles as StaticFiles -- PROJECT data Project = Project { _root :: FilePath , _info :: PerhapsInfo } data PerhapsInfo = Bad (Maybe FilePath) | Good Info data Info = Info { _pwd :: [String] , _dirs :: [FilePath] , _files :: [(FilePath, Bool)] , _readme :: Maybe String , _config :: Text.Text } -- JSON goodToJson :: FilePath -> Info -> String goodToJson root info = BSU8.toString $ Json.encode $ Json.object $ [ "root" .= root , "pwd" .= _pwd info , "dirs" .= _dirs info , "files" .= _files info , "readme" .= _readme info , "config" .= _config info ] badJson :: FilePath -> Maybe FilePath -> String badJson root potentialRoot = BSU8.toString $ Json.encode $ Json.object $ [ "root" .= root , "suggestion" .= potentialRoot ] -- GENERATE HTML toHtml :: Project -> H.Html toHtml (Project root perhapsInfo) = case perhapsInfo of Good info@(Info pwd _ _ _ _) -> Help.makeHtml (List.intercalate "/" ("~" : pwd)) ("/" ++ StaticFiles.elmPath) ("Elm.Index.fullscreen(" ++ goodToJson root info ++ ");") Bad suggestion -> Help.makeHtml (maybe "New Project!" (const "Existing Project?") suggestion) ("/" ++ StaticFiles.elmPath) ("Elm.Start.fullscreen(" ++ badJson root suggestion ++ ");") -- GET PROJECT getProject :: FilePath -> IO Project getProject directory = do root <- Dir.getCurrentDirectory exists <- Dir.doesFileExist "elm.json" Project root <$> case exists of False -> Bad <$> findNearestConfig (splitDirectories root) True -> do json <- Text.readFile "elm.json" Good <$> getInfo json directory findNearestConfig :: [String] -> IO (Maybe FilePath) findNearestConfig dirs = if null dirs then return Nothing else do exists <- Dir.doesFileExist (joinPath dirs </> "elm.json") if exists then return (Just (joinPath dirs)) else findNearestConfig (init dirs) moveToRoot :: IO () moveToRoot = do subDir <- Dir.getCurrentDirectory maybeRoot <- findNearestConfig (splitDirectories subDir) case maybeRoot of Nothing -> return () Just root -> Dir.setCurrentDirectory root -- GET INFO getInfo :: Text.Text -> FilePath -> IO Info getInfo config directory = do (dirs, files) <- getDirectoryInfo directory readme <- getReadme directory return $ Info { _pwd = dropWhile ("." ==) (splitDirectories directory) , _dirs = dirs , _files = files , _readme = readme , _config = config } -- README getReadme :: FilePath -> IO (Maybe String) getReadme dir = do let readmePath = dir </> "README.md" exists <- Dir.doesFileExist readmePath if exists then Just <$> readFile readmePath else return Nothing -- DIRECTORIES / FILES getDirectoryInfo :: FilePath -> IO ([FilePath], [(FilePath, Bool)]) getDirectoryInfo dir = do contents <- Dir.getDirectoryContents dir allDirs <- filterM (Dir.doesDirectoryExist . (dir </>)) contents rawFiles <- filterM (Dir.doesFileExist . (dir </>)) contents files <- mapM (inspectFile dir) rawFiles return (allDirs, files) inspectFile :: FilePath -> FilePath -> IO (FilePath, Bool) inspectFile dir filePath = if takeExtension filePath == ".elm" then do source <- Text.readFile (dir </> filePath) let hasMain = Text.isInfixOf "\nmain " source return (filePath, hasMain) else return (filePath, False)
evancz/cli
src/Develop/Generate/Index.hs
Haskell
bsd-3-clause
4,285
-- | Internal array type used by the B-tree types {-# LANGUAGE BangPatterns, CPP, MagicHash, Rank2Types, UnboxedTuples #-} module Data.BTree.Array ( -- * Types Array , MArray -- * Creating arrays , run , new , unsafeWrite , unsafeCopy -- * Inspecting arrays , unsafeIndex -- * Debugging , fromList , toList ) where import GHC.ST (ST (..), runST) import GHC.Exts -- | Frozen array data Array a = Array (Array# a) -- | Mutable array data MArray s a = MArray (MutableArray# s a) -- | Create and freeze an array run :: (forall s. ST s (MArray s a)) -> Array a run act = runST $ act >>= unsafeFreeze {-# INLINE run #-} -- | Create a new array of the specified size new :: Int -> ST s (MArray s a) new (I# n#) = ST $ \s# -> case newArray# n# element s# of (# s'#, mar# #) -> (# s'#, MArray mar# #) where element = error "Data.BTree.Array: unitialized element!" {-# INLINE new #-} -- | Freeze a mutable array unsafeFreeze :: MArray s a -> ST s (Array a) unsafeFreeze (MArray mar#) = ST $ \s# -> case unsafeFreezeArray# mar# s# of (# s'#, ar# #) -> (# s'#, Array ar# #) {-# INLINE unsafeFreeze #-} -- | Write to a position in an array unsafeWrite :: MArray s a -> Int -> a -> ST s () unsafeWrite (MArray mar#) (I# i#) x = ST $ \s# -> case writeArray# mar# i# x s# of s'# -> (# s'#, () #) {-# INLINE unsafeWrite #-} -- | Copy a range from an array unsafeCopy :: Array a -- ^ Array to copy from -> Int -- ^ Source index -> MArray s a -- ^ Destination to copy into -> Int -- ^ Destination index -> Int -- ^ Number of elements to copy -> ST s () -- ^ No result -- TODO: Check this! #if __GLASGOW_HASKELL__ >= 702 unsafeCopy (Array ar#) (I# si#) (MArray mar#) (I# di#) (I# n#) = ST $ \s# -> case copyArray# ar# si# mar# di# n# s# of s'# -> (# s'#, () #) #else unsafeCopy ar si mar di n = go si di 0 where go !i !j !c | c >= n = return () | otherwise = do let x = unsafeIndex ar i unsafeWrite mar j x go (i + 1) (j + 1) (c + 1) #endif {-# INLINE unsafeCopy #-} -- | Index an array, bounds are not checked unsafeIndex :: Array a -> Int -> a unsafeIndex (Array ar#) (I# i#) | i# <# 0# = error "herp" | otherwise = case indexArray# ar# i# of (# x #) -> x {-# INLINE unsafeIndex #-} -- | Convert a list to an array. For debugging purposes only. fromList :: [a] -> Array a fromList ls = run $ do mar <- new (length ls) let go _ [] = return mar go i (x : xs) = do unsafeWrite mar i x go (i + 1) xs go 0 ls -- | Convert an array to a list. For debugging purposes only. toList :: Int -- ^ Length -> Array a -- ^ Array to convert to a list -> [a] -- ^ Resulting list toList n arr = go 0 where go !i | i >= n = [] | otherwise = unsafeIndex arr i : go (i + 1)
jaspervdj/b-tree
src/Data/BTree/Array.hs
Haskell
bsd-3-clause
2,991
{-# LANGUAGE RankNTypes, OverloadedStrings #-} module Saturnin.Types ( MachineDescription , Hostname , BuildRequest (..) , JobRequest (..) , TestType (..) , GitSource (..) , YBServer , YBServerState (..) , YBSSharedState , fst3 , TestResult (..) , anyEither , isPassed , JobID (..) , JobRequestListenerConnectionHandler , logError , logInfo , logToConnection , logToConnection' ) where import Control.Applicative hiding (empty) import Control.Concurrent.STM import Control.Monad.State import Data.Text.Lazy hiding (empty) import Data.Default import Data.HashMap.Strict import Data.Monoid import Formatting import Network.Socket import System.IO import Saturnin.Git import Saturnin.Server.Config data BuildRequest = GitBuildRequest { brUri :: String , brHead :: String } type MachinesRegister = HashMap MachineDescription Hostname -- | JobRequest specifies job to be run. This is what client send to the -- job server. data JobRequest = TestRequest { testType :: TestType , dataSource :: GitSource , testMachines :: [MachineDescription] } deriving (Show, Read) data TestType = CabalTest | MakeCheckTest deriving (Show, Read) data YBServerState = YBServerState { ybssConfig :: ConfigServer , pState :: YBServerPersistentState , freeMachines :: MachinesRegister , logHandle :: Handle } deriving (Show) instance Default YBServerState where def = YBServerState def def empty stderr type YBSSharedState = TVar YBServerState type YBServer a = StateT YBSSharedState IO a logServer :: Text -> YBServer () logServer x = do liftIO . hPutStr stderr $ unpack x ts <- get lh <- liftIO . atomically $ logHandle <$> readTVar ts liftIO . hPutStr lh $ unpack x logError :: Text -> YBServer () logError = logServer . format ("error: " % text % "\n") logInfo :: Text -> YBServer () logInfo = logServer . format ("info: " % text % "\n") type JobRequestListenerConnectionHandler a = StateT (Socket, SockAddr) (StateT YBSSharedState IO) a logToConnection :: Text -> JobRequestListenerConnectionHandler () logToConnection x = do c <- (fst <$> get) liftIO $ logToConnection' c x logToConnection' :: Socket -> Text -> IO () logToConnection' c x = void . send c $ unpack x <> "\n" -- | fst for three-tuple fst3 :: forall t t1 t2. (t, t1, t2) -> t fst3 (x, _, _) = x data TestResult = Passed | Failed | FailedSetup deriving (Show, Read) isPassed :: TestResult -> Bool isPassed Passed = True isPassed _ = False -- | Returns any thing in Either. Be it Left or Right. anyEither :: Either a a -> a anyEither (Left x) = x anyEither (Right x) = x
yaccz/saturnin
library/Saturnin/Types.hs
Haskell
bsd-3-clause
2,738
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} import Data.String (fromString) import System.Environment (getArgs) import qualified Network.Wai.Handler.Warp as Warp import qualified Network.Wai as Wai import qualified Network.HTTP.Types as H import qualified Network.Wai.Application.Static as Static import Data.Maybe (fromJust) import Data.FileEmbed (embedDir) import WaiAppStatic.Types (toPieces) import Data.Text as T import Data.Text.Encoding (decodeUtf8) import qualified Data.ByteString as BS import Network.Transport.InMemory (createTransport) import Control.Distributed.Process.Node (LocalNode,newLocalNode,initRemoteTable,forkProcess,runProcess) import Control.Distributed.Process (Process,ProcessId,send,receiveWait,match) import Control.Monad.Trans (liftIO) import Data.Map.Strict as Map import Network.Wai.Handler.WebSockets (websocketsOr) import qualified Network.WebSockets as WS import Data.Word8 (_question) import Data.List (delete) import Control.Monad.Reader(ReaderT,runReaderT,ask) import GHC.Generics (Generic) import Data.Typeable (Typeable) import Data.Binary (Binary) data MainMsg = RegistClient ProcessId String | UnregistClient ProcessId | StringData ProcessId String deriving (Generic,Typeable) instance Binary MainMsg main :: IO () main = do node <- createTransport >>= (\t -> newLocalNode t initRemoteTable) mpid <- forkMain node host:port:_ <- getArgs return () Warp.runSettings ( Warp.setHost (fromString host) $ Warp.setPort (read port) $ Warp.defaultSettings ) $ websocketsOr WS.defaultConnectionOptions (wsRouterApp node mpid) staticApp type IO' = ReaderT (LocalNode,ProcessId) IO type WaiApplication' = Wai.Request -> (Wai.Response -> IO Wai.ResponseReceived) -> IO' Wai.ResponseReceived type WSServerApp' = WS.PendingConnection -> IO' () staticApp :: Wai.Application staticApp = Static.staticApp $ settings { Static.ssIndices = indices } where settings = Static.embeddedSettings $(embedDir "static") indices = fromJust $ toPieces ["WaiChat.htm"] -- default content wsRouterApp :: LocalNode -> ProcessId -> WS.ServerApp wsRouterApp node mpid pconn = runReaderT (f pconn) (node,mpid) where f pconn | ("/client" == path) = clientApp pconn | otherwise = liftIO $ WS.rejectRequest pconn "endpoint not found" requestPath = WS.requestPath $ WS.pendingRequest pconn path = BS.takeWhile (/=_question) requestPath clientApp :: WSServerApp' clientApp pconn = do conn <- liftIO $ WS.acceptRequest pconn cpid <- forkClient conn registClient cpid name loop conn cpid where loop :: WS.Connection -> ProcessId -> IO' () loop conn cpid = do msg <- liftIO $ WS.receive conn case msg of WS.ControlMessage (WS.Close _ _) -> do unregistClient cpid -- [TODO] kill process liftIO $ putStrLn "close complete!!" WS.DataMessage (WS.Text lbs) -> do tellString cpid $ T.unpack $ WS.fromLazyByteString lbs loop conn cpid _ -> loop conn cpid requestPath = WS.requestPath $ WS.pendingRequest pconn query = BS.drop 1 $ BS.dropWhile (/=_question) requestPath name = T.unpack $ decodeUtf8 $ H.urlDecode True query registClient :: ProcessId -> String -> IO' () registClient pid name = do (node,mnid) <- ask liftIO $ runProcess node $ send mnid (RegistClient pid name) -- [TODO] link or monitor nid unregistClient :: ProcessId -> IO' () unregistClient pid = do (node,mnid) <- ask liftIO $ runProcess node $ send mnid (UnregistClient pid) -- [TODO] kill pid tellString :: ProcessId -> String -> IO' () tellString pid msg = do (node,mnid) <- ask liftIO $ runProcess node $ send mnid (StringData pid msg) forkClient :: WS.Connection -> IO' ProcessId forkClient conn = do (node,_) <- ask liftIO $ forkProcess node $ clientProcess conn clientProcess :: WS.Connection -> Process () clientProcess conn = do receiveWait [match (p conn)] clientProcess conn where p :: WS.Connection-> String -> Process () p conn msg = let txt = T.pack $ msg in liftIO $ WS.sendTextData conn txt forkMain :: LocalNode -> IO ProcessId forkMain node = forkProcess node $ mainProcess Map.empty type MainState = Map.Map ProcessId String mainProcess :: MainState -> Process () mainProcess state = do state' <- receiveWait [match (p state)] mainProcess state' where p :: MainState -> MainMsg -> Process MainState p state (RegistClient sender name) = return $ Map.insert sender name state p state (UnregistClient sender) = return $ Map.delete sender state p state (StringData sender msg) = do let sname = case Map.lookup sender state of Just name -> name Nothing -> "[unknown]" liftIO $ putStrLn $ "StringData " ++ sname ++ " " ++ msg mapM_ (\(t,_)-> send t $ sname ++ ": " ++ msg) $ Map.toList state return $ state
mitsuji/exp-CloudHaskell
app/WaiChat.hs
Haskell
bsd-3-clause
5,093
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} import Language.JsonGrammar import Types import Prelude hiding (id, (.)) import Control.Category (Category(..)) import Data.Aeson.Types (Value, parseMaybe) import Data.Char (toLower) import Data.Monoid ((<>)) import Data.StackPrism (StackPrism) import Data.StackPrism.TH (deriveStackPrismsWith) import Language.TypeScript (renderDeclarationSourceFile) import Test.Framework (Test, defaultMain) import Test.Framework.Providers.HUnit (testCase) import Test.HUnit (assertBool) -- Create stack prisms for our three datatypes (defined in module Types) deriveStackPrismsWith (map toLower) ''Person deriveStackPrismsWith (map toLower) ''Coords deriveStackPrismsWith (map toLower) ''Gender -- Write Json instances for the datatypes instance Json Gender where grammar = fromPrism male . literal "male" <> fromPrism female . literal "female" instance Json Person where grammar = label "Person" $ fromPrism person . object ( prop "name" . prop "gender" . (prop "age" <> defaultValue 42) . fromPrism coords . property "coords" (array (el . el)) ) -- Create two example values alice :: Person alice = Person "Alice" Female 21 (Coords 52 5) bob :: Person bob = Person "Bob" Male 22 (Coords 53 6) -- Two tests: one for lists, the other for tuples test1, test2 :: Test test1 = testCase "PersonList" $ assertBool "" (checkInverse [alice, bob]) test2 = testCase "PersonTuple" $ assertBool "" (checkInverse (alice, bob)) checkInverse :: (Json a, Eq a) => a -> Bool checkInverse value = value == value' where Just json = serialize grammar value Just value' = parseMaybe (parse grammar) json -- Write the TypeScript definition to stdout and run the tests main :: IO () main = do printInterfaces [SomeGrammar personGrammar] defaultMain [test1, test2] personGrammar :: Grammar 'Val (Value :- t) (Person :- t) personGrammar = grammar printInterfaces :: [SomeGrammar 'Val] -> IO () printInterfaces gs = putStrLn (renderDeclarationSourceFile (interfaces gs))
MedeaMelana/JsonGrammar2
tests/Tests.hs
Haskell
bsd-3-clause
2,169
module Control.Monad.Syntax.Three where (===<<) :: Monad m => (a -> b -> c -> m d) -> m a -> b -> c -> m d (===<<) mf inp b c = inp >>= (\a -> mf a b c) infixl 1 ===<< (=.=<<) :: Monad m => (a -> b -> c -> m d) -> m b -> a -> c -> m d (=.=<<) mf inp a c = inp >>= (\b -> mf a b c) infixl 1 =.=<< (==.<<) :: Monad m => (a -> b -> c -> m d) -> m c -> a -> b -> m d (==.<<) mf inp a b = inp >>= mf a b infixl 1 ==.<<
athanclark/composition-extra
src/Control/Monad/Syntax/Three.hs
Haskell
bsd-3-clause
502
{-# LANGUAGE FlexibleContexts, UndecidableInstances, TypeSynonymInstances, FlexibleInstances, RankNTypes, TupleSections #-} -- Ref.) https://stackoverflow.com/questions/13352205/what-are-free-monads/13352580 module Free where import Control.Arrow import Control.Monad.State data Free f a = Pure a | Roll (f (Free f a)) pure' = Pure roll = Roll -- In = [pure, roll] -- Ta <-------------- a + F(Ta) -- | | -- | u | 1 + Fu -- | | -- v v -- X <-------------- a + FX -- [f, g] cata (f, g) (Pure x) = f x cata (f, g) (Roll x) = g (fmap (cata (f, g)) x) -- this fmap is over F not T (= Free f) instance Functor f => Functor (Free f) where fmap f = cata (pure' . f, roll) -- fmap f (Pure x) = pure' (f x) -- fmap f (Roll x) = roll (fmap (fmap f) x) -- 1st fmap is over F and 2nd fmap is the same as lhs (= Free f) mu :: Functor f => Free f (Free f a) -> Free f a mu = cata (id, roll) -- mu (Pure x) = x -- mu (Roll x) = roll (fmap mu x) -- Ref.) https://stackoverflow.com/questions/22121960/applicative-instance-for-free-monad instance Functor f => Applicative (Free f) where pure = pure' f <*> x = cata ((<$> x), roll) f -- cata ((`fmap` x), roll) f -- (<*> x) (Pure f) = (<$> x) f -- (<*> x) (Roll f) = roll (fmap (<*> x) f) instance (Functor f, Applicative (Free f)) => Monad (Free f) where return = pure x >>= f = f =<< x where (=<<) = (mu.).fmap -- example. -- L(A) = F(GA, HA) where G,H are unary functor. -- phi :: H <- L imples H <- TG where (alpha, T) is initial type over F(AOP exercise 2.39) -- -- And then, consider the case when substituted G to Identity functor,and substitute H to `B'. -- So, the initial F-Algebra of TA <- F(A, G(TA))) means Binary Tree(Leafy). data B a = B a a deriving Show instance Functor B where fmap f (B x y) = B (f x) (f y) type Tree a = Free B a tip :: a -> Tree a tip x = pure x bin :: Tree a -> Tree a -> Tree a bin l r = Roll (B l r) instance Show a => Show (Tree a) where show (Pure a) = "Pure " ++ show a show (Roll (B x y)) = "Roll (B {" ++ show x ++ "," ++ show y ++ "})" size :: Tree a -> Int size = cata (const 1, plus) where plus (B x y) = x + y depth :: Tree a -> Int depth = cata (const 0, (+1).maxB) where maxB (B x y) = max x y withDepth :: Tree a -> Tree (a, Int) withDepth = sub 0 where sub d (Pure x) = tip (x, d) sub d (Roll (B x y)) = bin (sub (d+1) x) (sub (d+1) y) data LR = L | R deriving (Show, Eq, Ord) instance Semigroup LR where (<>) = max instance Monoid LR where mempty = L mappend = (<>) -- cata lr (l, r) L = l lr (l, r) R = r assocr :: ((a, b), c) -> (a, (b, c)) assocr ((x, y), z) = (x, (y, z)) withRoute :: Tree a -> Tree (a, [LR]) withRoute = sub [] where sub lrs (Pure x) = tip (x, lrs) sub lrs (Roll (B x y)) = bin (sub (L:lrs) x) (sub (R:lrs) y) type Context = LR trimR = sub "" "" where sub fix tmp [] = fix sub fix tmp (' ':cs) = sub fix (' ':tmp) cs sub fix tmp (c:cs) = sub (fix ++ tmp ++ [c]) "" cs drawTree :: Show a => Tree a -> IO () drawTree = putStr . showTree showTree :: (Show a) => Tree a -> String showTree t = (draw . withRoute) t where branch L L = (" ", "+--") branch L R = ("| ", "+--") branch R L = ("| ", "+ ") branch R R = (" ", " ") sub :: Context -> [LR] -> ([String], [String]) -> ([String], [String]) sub _ [] (l1, l2) = (l1, l2) sub c (x:xs) (l1, l2) = sub (c <> x) xs $ ((:l1) *** (:l2)) (branch c x) draw (Pure (x, lrs)) = unlines [ trimR (concat l1s) , concat l2s ++ " " ++ show x ] where (l1s, l2s) = sub L lrs ([], []) draw (Roll (B l r)) = draw l ++ draw r tag :: (Int -> a -> b) -> Tree a -> Tree b tag f tree = evalState (tagStep f tree) 0 tagStep :: (Int -> a -> b) -> Tree a -> State Int (Tree b) tagStep f (Pure x) = do c <- get put (c+1) return (tip (f c x)) tagStep f (Roll (B l r)) = do l' <- tagStep f l r' <- tagStep f r return (bin l' r') -- -- putStr $ showTree $ tag const test9 -- putStr $ showTree $ tag (,) test9 -- putStr $ showTree $ tag (,) $ fmap assocr . withRoute . withDepth $ test9 -- dup x = (x, x) double = uncurry bin . dup genNumTree n = tag const $ iterate double (tip ()) !! n test = do x <- tip 1 y <- tip 'a' return (x, y) test1 = do x <- bin (tip 1) (tip 2) y <- tip 3 return (x, y) test2 = do x <- tip 1 y <- bin (tip 2) (tip 3) return (x, y) test3 = do x <- bin (tip 1) (tip 2) y <- bin (tip 'a') (tip 'b') return (x, y) test4 = do x <- bin (tip 1) (tip 2) y <- bin (tip 'a') (bin (tip 'b') (tip 'c')) return (x, y) test5 = do x <- bin (tip 1) (tip 2) y <- bin (tip 'a') (bin (tip 'b') (tip 'c')) return (y, x) test6 = do x <- bin (tip 'a') (bin (tip 'b') (tip 'c')) y <- bin (tip 1) (tip 2) return (x, y) test7 = do x <- bin (bin (tip 1) (tip 2)) (tip 3) y <- bin (tip 'a') (bin (tip 'b') (tip 'c')) return (x, y) test8 = bin (tip 1) (bin (tip 2) (bin (tip 3) (bin (tip 4) (bin (tip 4) (tip 6))))) test9 = bin (tip 0) (bin (bin (bin (bin (tip 1) (tip 2)) (bin (tip 3) (tip 4))) (bin (tip 5) (bin (tip 6) (tip 7)))) (tip 8)) -- >>> let tr = bin (tip 2) (tip 1) -- >>> let tl = bin (tip 4) (tip 3) -- >>> let t = bin (tip 5) (bin tl tr) -- >>> let f1 = tip (*2) -- >>> fmap (*2) t -- >>> f1 <*> t -- >>> let f2 = bin (tip (*2)) (tip (+2)) -- >>> f2 <*> tl -- >>> f2 <*> t monadTest = do x <- bin (tip 'a') (bin (tip 'b') (tip 'c')) y <- bin (bin (tip 1) (tip 2)) (tip 3) return (x,y) monadTest2 = do f <- bin (tip (+2)) (bin (tip (*2)) (tip (^2))) x <- bin (bin (tip 1) (tip 2)) (tip 3) return (f x) monadTest3 = do f <- tip $ bin (tip (+2)) (bin (tip (*2)) (tip (^2))) x <- tip $ bin (bin (tip 1) (tip 2)) (tip 3) f <*> x {- -- the case of f is Identity -- F(A, TA) = A + TA data Free a = Pure a | Roll (Free a) deriving (Show, Eq) pure' = Pure roll = Roll -- In = [pure, roll] -- Ta <-------------- a + Ta -- | | -- | u | 1 + u -- | | -- v v -- X <-------------- a + X -- [f, g] cata :: (a -> b, b -> b) -> Free a -> b cata (f, g) (Pure x) = f x cata (f, g) (Roll x) = g (cata (f, g) x) -- T f = cata (alpha . F(f, id)) -- = cata ([pure, roll] . (f + id)) -- = cata (pure . f, roll) freeMap :: (a -> b) -> Free a -> Free b freeMap f = cata (pure' . f, roll) instance Functor Free where fmap = freeMap instance Applicative Free where pure = pure' (<*>) = cata (fmap, (roll.)) mu :: Free (Free a) -> Free a mu = cata (id, roll) instance Monad Free where return = pure x >>= f = f =<< x where (=<<) = (mu.).fmap -}
cutsea110/aop
src/Free.hs
Haskell
bsd-3-clause
6,957
{-# LANGUAGE TemplateHaskell, OverloadedStrings #-} module Monto.RegisterServiceRequest where import Data.Aeson.TH import Data.Aeson (Value) import Data.Vector (Vector) import qualified Data.Vector as V import Data.Text (Text) import qualified Data.Text as T import Data.Maybe (fromMaybe) import Monto.Types data RegisterServiceRequest = RegisterServiceRequest { serviceID :: ServiceID , label :: Text , description :: Text , language :: Language , product :: Product , options :: Maybe Value , dependencies :: Maybe (Vector String) } deriving (Eq) $(deriveJSON (defaultOptions { fieldLabelModifier = \s -> case s of "serviceID" -> "service_id" label' -> label' }) ''RegisterServiceRequest) registerServiceRequestDependencies :: RegisterServiceRequest -> Vector String registerServiceRequestDependencies = fromMaybe V.empty . dependencies instance Show RegisterServiceRequest where show (RegisterServiceRequest i _ _ l p _ _) = concat [ "{", T.unpack i , ",", T.unpack l , ",", T.unpack p , "}" ]
wpmp/monto-broker
src/Monto/RegisterServiceRequest.hs
Haskell
bsd-3-clause
1,180
{-# LANGUAGE OverloadedStrings #-} module Unit.Service.CrawlerServiceTest (tests) where import Control.Applicative ((<$>)) import Data.Text import Service.CrawlerService import Test.HUnit import Text.HTML.TagSoup (Tag(..)) tests = [ "runs crawler" ~: test [ testIO (runCrawler fetcherMock1 "git.io" ["http://k.net"]) (@?= [("http://k.net",True)]) ,testIO (runCrawler fetcherMock2 "git.io" ["http://k.net"]) (@?= [("http://k.net",True)]) ,testIO (runCrawler fetcherMock3 "git.io" ["http://k.net"]) (@?= [("http://k.net",True)]) ,testIO (runCrawler fetcherMock4 "git.io" ["http://k.net"]) (@?= [("http://k.net",False)]) ] ] fetcherMock1 "http://k.net" = return [TagOpen "a" [("href", "git.io")]] fetcherMock2 "http://k.net" = return [TagOpen "a" [("href", "/a")]] fetcherMock2 "http://k.net/a" = return [TagOpen "a" [("href", "git.io")]] fetcherMock3 "http://k.net" = return [TagOpen "a" [("href", "/a")]] fetcherMock3 "http://k.net/a" = return [TagOpen "a" [("href", "/b")]] fetcherMock3 "http://k.net/b" = return [TagOpen "a" [("href", "git.io")]] fetcherMock4 "http://k.net" = return [TagOpen "a" [("href", "/a")]] fetcherMock4 "http://k.net/a" = return [TagOpen "a" [("href", "/b")]] fetcherMock4 "http://k.net/b" = return [TagOpen "a" [("href", "/c")]] fetcherMock4 "http://k.net/c" = return [TagOpen "a" [("href", "git.io")]] testIO action assertion = assertion <$> action
ptek/sclent
tests/Unit/Service/CrawlerServiceTest.hs
Haskell
bsd-3-clause
1,416
{-# LANGUAGE FlexibleInstances #-} module Network.SPDY.Internal.Serialize where import Blaze.ByteString.Builder import Data.Bits (setBit, shiftL, shiftR, (.&.)) import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.List (foldl') import Data.Monoid import Data.Word (Word8, Word16, Word32) import Network.SPDY.Compression (Deflate, compress) import Network.SPDY.Flags import Network.SPDY.Frames import Network.SPDY.Internal.Constants import Network.SPDY.Internal.ToWord8 rawFrameBuilder :: RawFrame -> Builder rawFrameBuilder frame = rawHeaderBuilder (frameHeader frame) `mappend` fromWord8 (flagsByte frame) `mappend` toBuilder (payloadLength frame) `mappend` fromByteString (payload frame) instance ToBuilder DataLength where toBuilder (DataLength dl) = fromWord24be dl fromWord24be :: Word32 -> Builder fromWord24be w = fromWord8 wHi8 `mappend` fromWord16be wLo16 where wHi8 = fromIntegral $ (w `shiftR` 16) .&. 0xff wLo16 = fromIntegral $ w .&. 0xffff rawHeaderBuilder :: RawFrameHeader -> Builder rawHeaderBuilder header = case header of ControlFrameHeader v ct -> fromWord16be (setBit (rawSPDYVersion v) 15) `mappend` fromWord16be ct DataFrameHeader sid -> fromWord32be (rawStreamID sid) toRawFrameHeader :: Frame -> RawFrameHeader toRawFrameHeader frame = case frame of AControlFrame v cf -> ControlFrameHeader v $ toControlType cf ADataFrame d -> DataFrameHeader (streamID d) toControlType :: ControlFrame -> Word16 toControlType details = case details of ASynStreamFrame _ -> cftSynStream ASynReplyFrame _ -> cftSynReply ARstStreamFrame _ -> cftRstStream ASettingsFrame _ -> cftSettings APingFrame _ -> cftPing AGoAwayFrame _ -> cftGoAway AHeadersFrame _ -> cftHeaders AWindowUpdateFrame _ -> cftWindowUpdate ACredentialFrame _ -> cftCredential toFlagsByte :: Frame -> Word8 toFlagsByte frame = case frame of AControlFrame _ cf -> case cf of ASynStreamFrame ss -> toWord8 $ synStreamFlags ss ASynReplyFrame sr -> toWord8 $ synReplyFlags sr ASettingsFrame s -> toWord8 $ settingsFlags s AHeadersFrame h -> toWord8 $ headersFlags h _ -> 0x0 ADataFrame d -> toWord8 $ dataFlags d toPayload :: Deflate -> Frame -> IO ByteString toPayload deflate frame = case frame of AControlFrame _ cf -> toControlPayload deflate cf ADataFrame d -> return $ dataBytes d toControlPayload :: Deflate -> ControlFrame -> IO ByteString toControlPayload deflate = fmap toByteString . toControlPayloadBuilder deflate toControlPayloadBuilder :: Deflate -> ControlFrame -> IO Builder toControlPayloadBuilder deflate cf = case cf of ASynStreamFrame ss -> fmap (toBuilder (synStreamNewStreamID ss) `mappend` toBuilder (synStreamAssociatedTo ss) `mappend` toBuilder (synStreamPriority ss) `mappend` toBuilder (synStreamSlot ss) `mappend`) $ compressHeaderBlock deflate $ synStreamHeaderBlock ss ASynReplyFrame sr -> fmap (toBuilder (synReplyNewStreamID sr) `mappend`) $ compressHeaderBlock deflate $ synReplyHeaderBlock sr ARstStreamFrame rs -> return $ toBuilder (rstStreamTermStreamID rs) `mappend` toBuilder (rstStreamTermStatus rs) ASettingsFrame s -> return $ toBuilder (settingsPairs s) APingFrame p -> return $ toBuilder (pingID p) AGoAwayFrame g -> return $ toBuilder (goAwayLastGoodStreamID g) `mappend` toBuilder (goAwayStatus g) AHeadersFrame h -> return $ toBuilder (headersStreamID h) `mappend` toBuilder (headersHeaderBlock h) AWindowUpdateFrame w -> return $ toBuilder (windowUpdateStreamID w) `mappend` toBuilder (windowUpdateDeltaWindowSize w) ACredentialFrame c -> return $ toBuilder (credentialSlot c) `mappend` toBuilder (credentialProof c) `mappend` toBuilder (credentialCertificates c) compressHeaderBlock :: Deflate -> HeaderBlock -> IO Builder compressHeaderBlock deflate hb = compress deflate $ toByteString $ toBuilder hb class ToBuilder a where toBuilder :: a -> Builder instance ToBuilder StreamID where toBuilder (StreamID w) = fromWord32be w instance ToBuilder (Maybe StreamID) where toBuilder = maybe (fromWord32be 0x0) toBuilder instance ToBuilder Priority where toBuilder (Priority w) = fromWord8 (w `shiftL` 5) instance ToBuilder Slot where toBuilder (Slot w) = fromWord8 w instance ToBuilder HeaderBlock where toBuilder hb = toBuilder (headerCount hb) `mappend` headerPairsBuilder (headerPairs hb) instance ToBuilder HeaderCount where toBuilder (HeaderCount w) = fromWord32be w instance ToBuilder HeaderName where toBuilder (HeaderName bs) = lengthAndBytes bs instance ToBuilder HeaderValue where toBuilder (HeaderValue bs) = lengthAndBytes bs lengthAndBytes :: ByteString -> Builder lengthAndBytes bs = fromWord32be (fromIntegral $ B.length bs) `mappend` fromByteString bs headerPairsBuilder :: [(HeaderName, HeaderValue)] -> Builder headerPairsBuilder = foldl' mappend mempty . map fromPair where fromPair (name, val) = toBuilder name `mappend` toBuilder val instance ToBuilder PingID where toBuilder (PingID w) = fromWord32be w instance ToBuilder DeltaWindowSize where toBuilder (DeltaWindowSize w) = fromWord32be w instance ToBuilder TerminationStatus where toBuilder ts = fromWord32be $ case ts of ProtocolError -> tsProtocolError InvalidStream -> tsInvalidStream RefusedStream -> tsRefusedStream UnsupportedVersion -> tsUnsupportedVersion Cancel -> tsCancel InternalError -> tsInternalError FlowControlError -> tsFlowControlError StreamInUse -> tsStreamInUse StreamAlreadyClosed -> tsStreamAlreadyClosed InvalidCredentials -> tsInvalidCredentials FrameTooLarge -> tsFrameTooLarge TerminationStatusUnknown w -> w instance ToBuilder [(SettingIDAndFlags, SettingValue)] where toBuilder pairs = fromWord32be (fromIntegral $ length pairs) `mappend` foldl' mappend mempty (map fromPair pairs) where fromPair (idfs, v) = toBuilder idfs `mappend` toBuilder v instance ToBuilder SettingIDAndFlags where toBuilder stidfs = toBuilder (settingIDFlags stidfs) `mappend` toBuilder (settingID stidfs) instance ToBuilder SettingID where toBuilder stid = fromWord24be $ case stid of SettingsUploadBandwidth -> stidSettingsUploadBandwidth SettingsDownloadBandwidth -> stidSettingsDownloadBandwidth SettingsRoundTripTime -> stidSettingsRoundTripTime SettingsMaxConcurrentStreams -> stidSettingsMaxConcurrentStreams SettingsCurrentCWND -> stidSettingsCurrentCWND SettingsDownloadRetransRate -> stidSettingsDownloadRetransRate SettingsInitialWindowSize -> stidSettingsInitialWindowSize SettingsClientCertificateVectorSize -> stidSettingsClientCertificateVectorSize SettingsOther w -> w instance ToBuilder SettingValue where toBuilder (SettingValue sv) = fromWord32be sv instance ToBuilder GoAwayStatus where toBuilder s = fromWord32be $ case s of GoAwayOK -> gsGoAwayOK GoAwayProtocolError -> gsGoAwayProtocolError GoAwayInternalError -> gsGoAwayInternalError GoAwayStatusUnknown w -> w instance ToBuilder Slot16 where toBuilder (Slot16 w) = fromWord16be w instance ToBuilder Proof where toBuilder (Proof bs) = lengthAndBytes bs instance ToBuilder [Certificate] where toBuilder = foldl' mappend mempty . map toBuilder instance ToBuilder Certificate where toBuilder (Certificate bs) = lengthAndBytes bs instance ToBuilder (Flags f) where toBuilder (Flags w) = fromWord8 w
kcharter/spdy-base
src/Network/SPDY/Internal/Serialize.hs
Haskell
bsd-3-clause
7,641
module Problem16 ( powerDigitSum ) where import Lib (digits) powerDigitSum :: Integer -> Integer -> Integer powerDigitSum x pow = sum.digits $ x^pow
candidtim/euler
src/Problem16.hs
Haskell
bsd-3-clause
157
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} -- | A @Trajectory@ instance based on a chronologically ordered -- list of data. The start and end times are determined by the -- first and last datum in the list. module Astro.Trajectory.EphemTrajectory ( EphemTrajectory (ET) ) where import Numeric.Units.Dimensional.Prelude import Astro.Orbit.MEOE import Astro.Orbit.Types import Astro.Trajectory import Astro.Time import Astro.Time.At import Astro.Orbit.Interpolate import qualified Prelude -- | Interpolate linearly in an ordered list of ephemeris to obtain -- the MEOE at the given time. If the given time is outside the -- range covered by the list the end element are extrapolated. meoeAt :: (RealFloat a, Ord a) => [Datum t a] -> E t a -> MEOE Mean a meoeAt [] _ = error "Can not interpolate an empty list" meoeAt (x:[]) _ = value x meoeAt (x1:x2:[]) t = linearPolateMEOEm x1 x2 t meoeAt (x1:x2:xs) t = if t < epoch x2 then linearPolateMEOEm x1 x2 t else meoeAt (x2:xs) t -- | Interpolate linearly in an ordered list of ephemeris to obtain -- the MEOE at the given time. If the given time is outside the -- range covered by the list @Nothing@ is returned. meoeAtMaybe :: (RealFloat a, Ord a) => [Datum t a] -> E t a -> Maybe (MEOE Mean a) meoeAtMaybe [] _ = Nothing meoeAtMaybe [m`At`t0] t = if t == t0 then Just m else Nothing meoeAtMaybe (x1:x2:xs) t = if t > epoch x2 then meoeAtMaybe (x2:xs) t else if t < epoch x1 then Nothing else Just (linearPolateMEOEm x1 x2 t) -- The input arrays must be chronologically ordered. meoes :: (RealFloat a, Ord a) => [Datum t a] -> [E t a] -> [Datum t a] meoes [] _ = [] meoes (x:xs) ts = go (x:xs) $ dropWhile (< epoch x) ts where -- We already know that @xs@ is non-empty and @t >= epoch x@. go :: (RealFloat a, Ord a) => [Datum t a] -> [E t a] -> [Datum t a] go _ [] = [] go [x] (t:_) = if t == epoch x then [x] else [] go (x0:x1:xs) (t:ts) | t == epoch x0 = x0:go (x0:x1:xs) ts | t >= epoch x1 = go (x1:xs) (t:ts) | otherwise = linearPolateMEOEm x0 x1 t`At`t:go (x0:x1:xs) ts newtype EphemTrajectory t a = ET [Datum t a] -- Should I skip this newtype and just define an instance for the list?? instance (RealFloat a) => Trajectory EphemTrajectory t a where startTime (ET []) = mjd' 0 startTime (ET xs) = epoch (head xs) endTime (ET []) = mjd' 0 endTime (ET xs) = epoch (last xs) ephemeris (ET xs) ts = meoes xs ts
bjornbm/astro-orbit
Astro/Trajectory/EphemTrajectory.hs
Haskell
bsd-3-clause
2,598
{-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# LANGUAGE TypeSynonymInstances, StandaloneDeriving, DeriveDataTypeable, FlexibleInstances, TypeOperators #-} module Database.PostgreSQL.Simple.Tuple.Common ( groupJoin , tuple2 , tuple3 , tuple4 , tuple5 , tuple6 , tuple7 , tuple8 , tuple9 , tuple10 , tuple11 , tuple1of3 , tuple2of3 , tuple1of4 , tuple2of4 , tuple3of4 , tuple1of5 , tuple2of5 , tuple3of5 , tuple4of5 , tuple1of6 , tuple2of6 , tuple3of6 , tuple4of6 , tuple5of6 , tuple1of7 , tuple2of7 , tuple3of7 , tuple4of7 , tuple5of7 , tuple6of7 , tuple1of8 , tuple2of8 , tuple3of8 , tuple4of8 , tuple5of8 , tuple6of8 , tuple7of8 , tuple1of9 , tuple2of9 , tuple3of9 , tuple4of9 , tuple5of9 , tuple6of9 , tuple7of9 , tuple8of9 , tuple1of10 , tuple2of10 , tuple3of10 , tuple4of10 , tuple5of10 , tuple6of10 , tuple7of10 , tuple8of10 , tuple9of10 , tuple1of11 , tuple2of11 , tuple3of11 , tuple4of11 , tuple5of11 , tuple6of11 , tuple7of11 , tuple8of11 , tuple9of11 , tuple10of11 ) where import Control.Arrow (second) import Data.Maybe (catMaybes, mapMaybe, isJust) import Data.List (groupBy) import Data.Function (on) import Database.PostgreSQL.Simple ((:.)(..)) groupJoin :: Eq a => [(a, b)] -> [(a, [b])] groupJoin xs = map reduce $ groupBy ((==) `on` fst) xs where reduce xs' = (fst $ head xs', map snd xs') {----------------------------------------------------------------------------------------------------{ | Simple Tuples }----------------------------------------------------------------------------------------------------} tuple2 :: (a :. b) -> (a, b) tuple2 (a:.b) = (a,b) tuple3 :: (a :. (b :. c)) -> (a, b, c) tuple3 (a:.b:.c) = (a,b,c) tuple4 :: (a :. (b :. (c :. d))) -> (a, b, c, d) tuple4 (a:.b:.c:.d) = (a,b,c,d) tuple5 :: (a :. (b :. (c :. (d :. e)))) -> (a, b, c, d, e) tuple5 (a:.b:.c:.d:.e) = (a,b,c,d,e) tuple6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> (a, b, c, d, e, f) tuple6 (a:.b:.c:.d:.e:.f) = (a,b,c,d,e,f) tuple7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> (a, b, c, d, e, f, g) tuple7 (a:.b:.c:.d:.e:.f:.g) = (a,b,c,d,e,f,g) tuple8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> (a, b, c, d, e, f, g, h) tuple8 (a:.b:.c:.d:.e:.f:.g:.h) = (a,b,c,d,e,f,g,h) tuple9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> (a, b, c, d, e, f, g, h, i) tuple9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = (a,b,c,d,e,f,g,h,i) tuple10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> (a, b, c, d, e, f, g, h, i, j) tuple10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = (a,b,c,d,e,f,g,h,i,j) tuple11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> (a, b, c, d, e, f, g, h, i, j, k) tuple11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = (a,b,c,d,e,f,g,h,i,j,k) {----------------------------------------------------------------------------------------------------{ | Grouped Tuples }----------------------------------------------------------------------------------------------------} ---------------------------------------------------------------------- | Groups of 3 tuple1of3 :: (a :. (b :. c)) -> (a, (b, c)) tuple1of3 (a:.b:.c) = (a,(b,c)) tuple2of3 :: (a :. (b :. c)) -> ((a, b), c) tuple2of3 (a:.b:.c) = ((a,b),c) ---------------------------------------------------------------------- | Groups of 4 tuple1of4 :: (a :. (b :. (c :. d))) -> (a, (b, c, d)) tuple1of4 (a:.b:.c:.d) = (a,(b,c,d)) tuple2of4 :: (a :. (b :. (c :. d))) -> ((a, b), (c, d)) tuple2of4 (a:.b:.c:.d) = ((a,b),(c,d)) tuple3of4 :: (a :. (b :. (c :. d))) -> ((a, b, c), d) tuple3of4 (a:.b:.c:.d) = ((a,b,c),d) ---------------------------------------------------------------------- | Groups of 5 tuple1of5 :: (a :. (b :. (c :. (d :. e)))) -> (a, (b, c, d, e)) tuple1of5 (a:.b:.c:.d:.e) = (a,(b,c,d,e)) tuple2of5 :: (a :. (b :. (c :. (d :. e)))) -> ((a, b), (c, d, e)) tuple2of5 (a:.b:.c:.d:.e) = ((a,b),(c,d,e)) tuple3of5 :: (a :. (b :. (c :. (d :. e)))) -> ((a, b, c), (d, e)) tuple3of5 (a:.b:.c:.d:.e) = ((a,b,c),(d,e)) tuple4of5 :: (a :. (b :. (c :. (d :. e)))) -> ((a, b, c, d), e) tuple4of5 (a:.b:.c:.d:.e) = ((a,b,c,d),e) ---------------------------------------------------------------------- | Groups of 6 tuple1of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> (a, (b, c, d, e, f)) tuple1of6 (a:.b:.c:.d:.e:.f) = (a,(b,c,d,e,f)) tuple2of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> ((a, b), (c, d, e, f)) tuple2of6 (a:.b:.c:.d:.e:.f) = ((a,b),(c,d,e,f)) tuple3of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> ((a, b, c), (d, e, f)) tuple3of6 (a:.b:.c:.d:.e:.f) = ((a,b,c),(d,e,f)) tuple4of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> ((a, b, c, d), (e, f)) tuple4of6 (a:.b:.c:.d:.e:.f) = ((a,b,c,d),(e,f)) tuple5of6 :: (a :. (b :. (c :. (d :. (e :. f))))) -> ((a, b, c, d, e), f) tuple5of6 (a:.b:.c:.d:.e:.f) = ((a,b,c,d,e),f) ---------------------------------------------------------------------- | Groups of 7 tuple1of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> (a, (b, c, d, e, f, g)) tuple1of7 (a:.b:.c:.d:.e:.f:.g) = (a,(b,c,d,e,f,g)) tuple2of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b), (c, d, e, f, g)) tuple2of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b),(c,d,e,f,g)) tuple3of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b, c), (d, e, f, g)) tuple3of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b,c),(d,e,f,g)) tuple4of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b, c, d), (e, f, g)) tuple4of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b,c,d),(e,f,g)) tuple5of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b, c, d, e), (f, g)) tuple5of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b,c,d,e),(f,g)) tuple6of7 :: (a :. (b :. (c :. (d :. (e :. (f :. g)))))) -> ((a, b, c, d, e, f), g) tuple6of7 (a:.b:.c:.d:.e:.f:.g) = ((a,b,c,d,e,f),g) ---------------------------------------------------------------------- | Groups of 8 tuple1of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> (a, (b, c, d, e, f, g, h)) tuple1of8 (a:.b:.c:.d:.e:.f:.g:.h) = (a,(b,c,d,e,f,g,h)) tuple2of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b), (c, d, e, f, g, h)) tuple2of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b),(c,d,e,f,g,h)) tuple3of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c), (d, e, f, g, h)) tuple3of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c),(d,e,f,g,h)) tuple4of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c, d), (e, f, g, h)) tuple4of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c,d),(e,f,g,h)) tuple5of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c, d, e), (f, g, h)) tuple5of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c,d,e),(f,g,h)) tuple6of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c, d, e, f), (g, h)) tuple6of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c,d,e,f),(g,h)) tuple7of8 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. h))))))) -> ((a, b, c, d, e, f, g), h) tuple7of8 (a:.b:.c:.d:.e:.f:.g:.h) = ((a,b,c,d,e,f,g),h) ---------------------------------------------------------------------- | Groups of 9 tuple1of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> (a, (b, c, d, e, f, g, h, i)) tuple1of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = (a,(b,c,d,e,f,g,h,i)) tuple2of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b), (c, d, e, f, g, h, i)) tuple2of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b),(c,d,e,f,g,h,i)) tuple3of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c), (d, e, f, g, h, i)) tuple3of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c),(d,e,f,g,h,i)) tuple4of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d), (e, f, g, h, i)) tuple4of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d),(e,f,g,h,i)) tuple5of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d, e), (f, g, h, i)) tuple5of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d,e),(f,g,h,i)) tuple6of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d, e, f), (g, h, i)) tuple6of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d,e,f),(g,h,i)) tuple7of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d, e, f, g), (h, i)) tuple7of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d,e,f,g),(h,i)) tuple8of9 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. i)))))))) -> ((a, b, c, d, e, f, g, h), i) tuple8of9 (a:.b:.c:.d:.e:.f:.g:.h:.i) = ((a,b,c,d,e,f,g,h),i) ---------------------------------------------------------------------- | Groups of 10 tuple1of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> (a, (b, c, d, e, f, g, h, i, j)) tuple1of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = (a,(b,c,d,e,f,g,h,i,j)) tuple2of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b), (c, d, e, f, g, h, i, j)) tuple2of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b),(c,d,e,f,g,h,i,j)) tuple3of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c), (d, e, f, g, h, i, j)) tuple3of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c),(d,e,f,g,h,i,j)) tuple4of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d), (e, f, g, h, i, j)) tuple4of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d),(e,f,g,h,i,j)) tuple5of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e), (f, g, h, i, j)) tuple5of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e),(f,g,h,i,j)) tuple6of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e, f), (g, h, i, j)) tuple6of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e,f),(g,h,i,j)) tuple7of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e, f, g), (h, i, j)) tuple7of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e,f,g),(h,i,j)) tuple8of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e, f, g, h), (i, j)) tuple8of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e,f,g,h),(i,j)) tuple9of10 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. j))))))))) -> ((a, b, c, d, e, f, g, h, i), j) tuple9of10 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j) = ((a,b,c,d,e,f,g,h,i),j) ---------------------------------------------------------------------- | Groups of 11 tuple1of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> (a, (b, c, d, e, f, g, h, i, j, k)) tuple1of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = (a,(b,c,d,e,f,g,h,i,j,k)) tuple2of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b), (c, d, e, f, g, h, i, j, k)) tuple2of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b),(c,d,e,f,g,h,i,j,k)) tuple3of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c), (d, e, f, g, h, i, j, k)) tuple3of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c),(d,e,f,g,h,i,j,k)) tuple4of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d), (e, f, g, h, i, j, k)) tuple4of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d),(e,f,g,h,i,j,k)) tuple5of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e), (f, g, h, i, j, k)) tuple5of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e),(f,g,h,i,j,k)) tuple6of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f), (g, h, i, j, k)) tuple6of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f),(g,h,i,j,k)) tuple7of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f, g), (h, i, j, k)) tuple7of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f,g),(h,i,j,k)) tuple8of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f, g, h), (i, j, k)) tuple8of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f,g,h),(i,j,k)) tuple9of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f, g, h, i), (j, k)) tuple9of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f,g,h,i),(j,k)) tuple10of11 :: (a :. (b :. (c :. (d :. (e :. (f :. (g :. (h :. (i :. (j :. k)))))))))) -> ((a, b, c, d, e, f, g, h, i, j), k) tuple10of11 (a:.b:.c:.d:.e:.f:.g:.h:.i:.j:.k) = ((a,b,c,d,e,f,g,h,i,j),k)
cimmanon/postgresql-simple-tuple
src/Database/PostgreSQL/Simple/Tuple/Common.hs
Haskell
bsd-3-clause
12,425
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-missing-fields #-} {-# OPTIONS_GHC -fno-warn-missing-signatures #-} {-# OPTIONS_GHC -fno-warn-name-shadowing #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} {-# OPTIONS_GHC -fno-warn-unused-matches #-} ----------------------------------------------------------------- -- Autogenerated by Thrift -- -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- module TestService_Client(init) where import Data.IORef import Prelude ( Bool(..), Enum, Float, IO, Double, String, Maybe(..), Eq, Show, Ord, concat, error, fromIntegral, fromEnum, length, map, maybe, not, null, otherwise, return, show, toEnum, enumFromTo, Bounded, minBound, maxBound, seq, (.), (&&), (||), (==), (++), ($), (-), (>>=), (>>)) import qualified Control.Applicative as Applicative (ZipList(..)) import Control.Applicative ( (<*>) ) import qualified Control.DeepSeq as DeepSeq import qualified Control.Exception as Exception import qualified Control.Monad as Monad ( liftM, ap, when ) import qualified Data.ByteString.Lazy as BS import Data.Functor ( (<$>) ) import qualified Data.Hashable as Hashable import qualified Data.Int as Int import qualified Data.Maybe as Maybe (catMaybes) import qualified Data.Text.Lazy.Encoding as Encoding ( decodeUtf8, encodeUtf8 ) import qualified Data.Text.Lazy as LT import qualified Data.Typeable as Typeable ( Typeable ) import qualified Data.HashMap.Strict as Map import qualified Data.HashSet as Set import qualified Data.Vector as Vector import qualified Test.QuickCheck.Arbitrary as Arbitrary ( Arbitrary(..) ) import qualified Test.QuickCheck as QuickCheck ( elements ) import qualified Thrift import qualified Thrift.Types as Types import qualified Thrift.Serializable as Serializable import qualified Thrift.Arbitraries as Arbitraries import qualified Module_Types import qualified TestService seqid = newIORef 0 init (ip,op) arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16 = do send_init op arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16 recv_init ip send_init op arg_int1 arg_int2 arg_int3 arg_int4 arg_int5 arg_int6 arg_int7 arg_int8 arg_int9 arg_int10 arg_int11 arg_int12 arg_int13 arg_int14 arg_int15 arg_int16 = do seq <- seqid seqn <- readIORef seq Thrift.writeMessage op ("init", Types.M_CALL, seqn) $ TestService.write_Init_args op (TestService.Init_args{TestService.init_args_int1=arg_int1,TestService.init_args_int2=arg_int2,TestService.init_args_int3=arg_int3,TestService.init_args_int4=arg_int4,TestService.init_args_int5=arg_int5,TestService.init_args_int6=arg_int6,TestService.init_args_int7=arg_int7,TestService.init_args_int8=arg_int8,TestService.init_args_int9=arg_int9,TestService.init_args_int10=arg_int10,TestService.init_args_int11=arg_int11,TestService.init_args_int12=arg_int12,TestService.init_args_int13=arg_int13,TestService.init_args_int14=arg_int14,TestService.init_args_int15=arg_int15,TestService.init_args_int16=arg_int16}) Thrift.tFlush (Thrift.getTransport op) recv_init ip = Thrift.readMessage ip $ \(fname,mtype,rseqid) -> do Monad.when (mtype == Types.M_EXCEPTION) $ Thrift.readAppExn ip >>= Exception.throw res <- TestService.read_Init_result ip return $ TestService.init_result_success res
Orvid/fbthrift
thrift/compiler/test/fixtures/service-fuzzer/gen-hs/TestService_Client.hs
Haskell
apache-2.0
3,722
{-# LANGUAGE PackageImports #-} module Propellor.Property where import System.Directory import Control.Monad import Data.Monoid import Control.Monad.IfElse import "mtl" Control.Monad.Reader import Propellor.Types import Propellor.Info import Propellor.Engine import Utility.Monad import System.FilePath -- Constructs a Property. property :: Desc -> Propellor Result -> Property property d s = Property d s mempty -- | Combines a list of properties, resulting in a single property -- that when run will run each property in the list in turn, -- and print out the description of each as it's run. Does not stop -- on failure; does propigate overall success/failure. propertyList :: Desc -> [Property] -> Property propertyList desc ps = Property desc (ensureProperties ps) (combineInfos ps) -- | Combines a list of properties, resulting in one property that -- ensures each in turn. Does not stop on failure; does propigate -- overall success/failure. combineProperties :: Desc -> [Property] -> Property combineProperties desc ps = Property desc (go ps NoChange) (combineInfos ps) where go [] rs = return rs go (l:ls) rs = do r <- ensureProperty l case r of FailedChange -> return FailedChange _ -> go ls (r <> rs) -- | Combines together two properties, resulting in one property -- that ensures the first, and if the first succeeds, ensures the second. -- The property uses the description of the first property. before :: Property -> Property -> Property p1 `before` p2 = p2 `requires` p1 `describe` (propertyDesc p1) -- | Makes a perhaps non-idempotent Property be idempotent by using a flag -- file to indicate whether it has run before. -- Use with caution. flagFile :: Property -> FilePath -> Property flagFile p = flagFile' p . return flagFile' :: Property -> IO FilePath -> Property flagFile' p getflagfile = adjustProperty p $ \satisfy -> do flagfile <- liftIO getflagfile go satisfy flagfile =<< liftIO (doesFileExist flagfile) where go _ _ True = return NoChange go satisfy flagfile False = do r <- satisfy when (r == MadeChange) $ liftIO $ unlessM (doesFileExist flagfile) $ do createDirectoryIfMissing True (takeDirectory flagfile) writeFile flagfile "" return r --- | Whenever a change has to be made for a Property, causes a hook -- Property to also be run, but not otherwise. onChange :: Property -> Property -> Property p `onChange` hook = Property (propertyDesc p) satisfy (combineInfo p hook) where satisfy = do r <- ensureProperty p case r of MadeChange -> do r' <- ensureProperty hook return $ r <> r' _ -> return r (==>) :: Desc -> Property -> Property (==>) = flip describe infixl 1 ==> -- | Makes a Property only need to do anything when a test succeeds. check :: IO Bool -> Property -> Property check c p = adjustProperty p $ \satisfy -> ifM (liftIO c) ( satisfy , return NoChange ) -- | Marks a Property as trivial. It can only return FailedChange or -- NoChange. -- -- Useful when it's just as expensive to check if a change needs -- to be made as it is to just idempotently assure the property is -- satisfied. For example, chmodding a file. trivial :: Property -> Property trivial p = adjustProperty p $ \satisfy -> do r <- satisfy if r == MadeChange then return NoChange else return r doNothing :: Property doNothing = property "noop property" noChange -- | Makes a property that is satisfied differently depending on the host's -- operating system. -- -- Note that the operating system may not be declared for some hosts. withOS :: Desc -> (Maybe System -> Propellor Result) -> Property withOS desc a = property desc $ a =<< getOS boolProperty :: Desc -> IO Bool -> Property boolProperty desc a = property desc $ ifM (liftIO a) ( return MadeChange , return FailedChange ) -- | Undoes the effect of a property. revert :: RevertableProperty -> RevertableProperty revert (RevertableProperty p1 p2) = RevertableProperty p2 p1 -- | Starts accumulating the properties of a Host. -- -- > host "example.com" -- > & someproperty -- > ! oldproperty -- > & otherproperty host :: HostName -> Host host hn = Host hn [] mempty -- | Adds a property to a Host -- -- Can add Properties and RevertableProperties (&) :: IsProp p => Host -> p -> Host (Host hn ps as) & p = Host hn (ps ++ [toProp p]) (as <> getInfo p) infixl 1 & -- | Adds a property to the Host in reverted form. (!) :: Host -> RevertableProperty -> Host h ! p = h & revert p infixl 1 ! -- Changes the action that is performed to satisfy a property. adjustProperty :: Property -> (Propellor Result -> Propellor Result) -> Property adjustProperty p f = p { propertySatisfy = f (propertySatisfy p) } -- Combines the Info of two properties. combineInfo :: (IsProp p, IsProp q) => p -> q -> Info combineInfo p q = getInfo p <> getInfo q combineInfos :: IsProp p => [p] -> Info combineInfos = mconcat . map getInfo makeChange :: IO () -> Propellor Result makeChange a = liftIO a >> return MadeChange noChange :: Propellor Result noChange = return NoChange
abailly/propellor-test2
src/Propellor/Property.hs
Haskell
bsd-2-clause
5,033
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings #-} {-# OPTIONS -Wall #-} module Main(main) where import qualified Data.Text.IO as T import Data.Typeable import Hydro import qualified Language.Paraiso.Annotation as Anot import qualified Language.Paraiso.Annotation.Allocation as Alloc import Language.Paraiso.Name import Language.Paraiso.Generator (generateIO) import qualified Language.Paraiso.Generator.Native as Native import Language.Paraiso.OM import Language.Paraiso.OM.Builder import Language.Paraiso.OM.Builder.Boolean import Language.Paraiso.OM.DynValue as DVal import Language.Paraiso.OM.Graph import Language.Paraiso.OM.PrettyPrint import Language.Paraiso.OM.Realm import qualified Language.Paraiso.OM.Reduce as Reduce import Language.Paraiso.Optimization import Language.Paraiso.Prelude import Language.Paraiso.Tensor import System.Directory (createDirectoryIfMissing) realDV :: DynValue realDV = DynValue{DVal.realm = Local, DVal.typeRep = typeOf (0::Real)} intGDV :: DynValue intGDV = DynValue{DVal.realm = Global, DVal.typeRep = typeOf (0::Int)} realGDV :: DynValue realGDV = DynValue{DVal.realm = Global, DVal.typeRep = typeOf (0::Real)} -- the list of static variables for this machine hydroVars :: [Named DynValue] hydroVars = [Named (mkName "generation") intGDV] ++ [Named (mkName "time") realGDV] ++ [Named (mkName "cfl") realGDV] ++ foldMap (\name0 -> [Named name0 realGDV]) dRNames ++ foldMap (\name0 -> [Named name0 realGDV]) extentNames ++ [Named (mkName "density") realDV] ++ foldMap (\name0 -> [Named name0 realDV]) velocityNames ++ [Named (mkName "pressure") realDV] velocityNames :: Dim (Name) velocityNames = compose (\axis -> mkName $ "velocity" ++ showT (axisIndex axis)) dRNames :: Dim (Name) dRNames = compose (\axis -> mkName $ "dR" ++ showT (axisIndex axis)) extentNames :: Dim (Name) extentNames = compose (\axis -> mkName $ "extent" ++ showT (axisIndex axis)) loadReal :: Name -> BR loadReal = load TLocal (undefined::Real) loadGReal :: Name -> BGR loadGReal = load TGlobal (undefined::Real) ---------------------------------------------------------------- -- Hydro Implementations ---------------------------------------------------------------- buildInit :: B () buildInit = do dRG <- mapM (bind . loadGReal) dRNames extentG <- mapM (bind . loadGReal) extentNames dR <- mapM (bind . broadcast) dRG extent <- mapM (bind . broadcast) extentG icoord <- sequenceA $ compose (\axis -> bind $ loadIndex (0::Real) axis) coord <- mapM bind $ compose (\i -> dR!i * icoord!i) let ex = Axis 0 ey = Axis 1 vplus, vminus :: Dim BR vplus = Vec :~ ( 6) :~ 0 vminus = Vec :~ ( 0) :~ 0 region <- bind $ (coord!ey) `gt` (0.47*extent!ey) && (coord!ey) `lt` (0.53*extent!ey) && (coord!ex) `lt` 0 velo <- sequence $ compose (\i -> bind $ select region (vplus!i) (vminus!i)) factor <- bind $ 1 + 1e-3 * sin (6 * pi * coord ! ex) store (mkName "density") $ factor * kGamma * (kGamma::BR) * (select region 1 10) _ <- sequence $ compose(\i -> store (velocityNames!i) $ velo !i) store (mkName "pressure") $ factor * 0.6 boundaryCondition :: Hydro BR -> B (Hydro BR) boundaryCondition cell = do dRG <- mapM (bind . loadGReal) dRNames extentG <- mapM (bind . loadGReal) extentNames dR <- mapM (bind . broadcast) dRG extent <- mapM (bind . broadcast) extentG icoord <- sequenceA $ compose (\axis -> bind $ loadIndex (0::Real) axis) isize <- sequenceA $ compose (\axis -> bind $ loadSize TLocal (0::Real) axis) coord <- mapM bind $ compose (\i -> dR!i * icoord!i) let ex = Axis 0 ey = Axis 1 vplus, vminus :: Dim BR vplus = Vec :~ ( 6) :~ 0 vminus = Vec :~ ( 0) :~ 0 region <- bind $ (coord!ey) `gt` (0.47*extent!ey) && (coord!ey) `lt` (0.53*extent!ey) && (coord!ex) `lt` 0 cell0 <- bindPrimitive (kGamma * (kGamma::BR) * (select region 1 10)) (compose (\i -> select region (vplus!i) (vminus!i))) (0.6) outOf <- bind $ (foldl1 (||) $ compose (\i -> icoord !i `lt` 0)) || (foldl1 (||) $ compose (\i -> (icoord !i) `ge` (isize !i))) return $ (\a b -> Anot.add Alloc.Manifest <?> (select outOf a b)) <$> cell0 <*> cell buildProceed :: B () buildProceed = do dens <- bind $ loadReal $ mkName "density" velo <- mapM (bind . loadReal) velocityNames pres <- bind $ loadReal $ mkName "pressure" timeG <- bind $ loadGReal $ mkName "time" cflG <- bind $ loadGReal $ mkName "cfl" dRG <- mapM (bind . loadGReal) dRNames dR <- mapM (bind . broadcast) dRG cell0 <- bindPrimitive dens velo pres cell <- boundaryCondition cell0 let timescale i = dR!i / (soundSpeed cell + abs (velocity cell !i)) dts <- bind $ foldl1 min $ compose timescale dtG <- bind $ cflG * reduce Reduce.Min dts dt <- bind $ broadcast dtG cell2 <- proceedSingle 1 (dt/2) dR cell cell cell3 <- proceedSingle 2 dt dR cell2 cell store (mkName "time") $ timeG + dtG store (mkName "density") $ density cell3 _ <- sequence $ compose(\i -> store (velocityNames!i) $ velocity cell3 !i) store (mkName "pressure") $ pressure cell3 proceedSingle :: Int -> BR -> Dim BR -> Hydro BR -> Hydro BR -> B (Hydro BR) proceedSingle order dt dR cellF cellS = do let calcWall i = do (lp,rp) <- interpolate order i cellF hllc i lp rp wall <- sequence $ compose calcWall cellN <- foldl1 (.) (compose (\i -> (>>= addFlux dt dR wall i))) $ return cellS bindPrimitive (max 1e-2 $ density cellN) (velocity cellN) (max 1e-2 $ pressure cellN) -- cx <- addFlux dt dR wall (Axis 0) cellS -- addFlux dt dR wall (Axis 1) cx addFlux :: BR -> Dim BR -> Dim (Hydro BR) -> Axis Dim -> Hydro BR -> B (Hydro BR) addFlux dt dR wall ex cell = do dtdx <- bind $ dt / dR!ex leftWall <- mapM bind $ wall ! ex rightWall <- mapM (bind . shift (negate $ unitVector ex)) $ wall!ex dens1 <- bind $ density cell + dtdx * (densityFlux leftWall - densityFlux rightWall)!ex mome1 <- sequence $ compose (\j -> bind $ (momentum cell !j + dtdx * (momentumFlux leftWall - momentumFlux rightWall) !j!ex)) enrg1 <- bind $ energy cell + dtdx * (energyFlux leftWall - energyFlux rightWall) !ex bindConserved dens1 mome1 enrg1 interpolate :: Int -> Axis Dim -> Hydro BR -> B (Hydro BR, Hydro BR) interpolate order i cell = do let shifti n = shift $ compose (\j -> if i==j then n else 0) a0 <- mapM (bind . shifti ( 2)) cell a1 <- mapM (bind . shifti ( 1)) cell a2 <- mapM (bind . shifti ( 0)) cell a3 <- mapM (bind . shifti (-1)) cell intp <- sequence $ interpolateSingle order <$> a0 <*> a1 <*> a2 <*> a3 let (l,r) = (fmap fst intp , fmap snd intp) bp :: Hydro BR -> B (Hydro BR) bp x = do dens1 <- bind $ density x velo1 <- mapM bind $ velocity x pres1 <- bind $ pressure x bindPrimitive dens1 velo1 pres1 lp <- bp l rp <- bp r return (lp,rp) interpolateSingle :: Int -> BR -> BR -> BR -> BR -> B (BR,BR) interpolateSingle order x0 x1 x2 x3 = if order == 1 then do return (x1, x2) else if order == 2 then do d01 <- bind $ x1-x0 d12 <- bind $ x2-x1 d23 <- bind $ x3-x2 let absmaller a b = select ((a*b) `le` 0) 0 $ select (abs a `lt` abs b) a b d1 <- bind $ absmaller d01 d12 d2 <- bind $ absmaller d12 d23 l <- bind $ x1 + d1/2 r <- bind $ x2 - d2/2 return (l, r) else error $ show order ++ "th order spatial interpolation is not yet implemented" hllc :: Axis Dim -> Hydro BR -> Hydro BR -> B (Hydro BR) hllc i left right = do densMid <- bind $ (density left + density right ) / 2 soundMid <- bind $ (soundSpeed left + soundSpeed right) / 2 let speedLeft = velocity left !i speedRight = velocity right !i presStar <- bind $ max 0 $ (pressure left + pressure right ) / 2 - densMid * soundMid * (speedRight - speedLeft) shockLeft <- bind $ velocity left !i - soundSpeed left * hllcQ presStar (pressure left) shockRight <- bind $ velocity right !i + soundSpeed right * hllcQ presStar (pressure right) shockStar <- bind $ (pressure right - pressure left + density left * speedLeft * (shockLeft - speedLeft) - density right * speedRight * (shockRight - speedRight) ) / (density left * (shockLeft - speedLeft ) - density right * (shockRight - speedRight) ) lesta <- starState shockStar shockLeft left rista <- starState shockStar shockRight right let selector a b c d = select (0 `lt` shockLeft) a $ select (0 `lt` shockStar) b $ select (0 `lt` shockRight) c d mapM bind $ selector <$> left <*> lesta <*> rista <*> right where hllcQ sp p = select (p `le` sp) 1 $ sqrt(1 + (kGamma + 1)/(2*kGamma) * (sp / p - 1)) starState starShock shock x = do let speed = velocity x !i dens <- bind $ density x * (shock - speed) / (shock - starShock) mome <- sequence $ compose (\j -> bind $ dens * if i==j then starShock else velocity x !j) enrg <- bind $ dens * (energy x / density x + (starShock - speed) * (starShock + pressure x/density x/(shock - speed))) bindConserved dens mome enrg -- compose the machine. myOM :: OM Dim Int Anot.Annotation myOM = optimize O3 $ makeOM (mkName "Hydro") [] hydroVars [(mkName "init" , buildInit), (mkName "proceed", buildProceed)] cpuSetup :: Native.Setup Vec2 Int cpuSetup = (Native.defaultSetup $ Vec :~ 1024 :~ 1024) { Native.directory = "./dist/" } gpuSetup :: Native.Setup Vec2 Int gpuSetup = (Native.defaultSetup $ Vec :~ 1024 :~ 1024) { Native.directory = "./dist-cuda/" , Native.language = Native.CUDA } main :: IO () main = do createDirectoryIfMissing True "output" -- output the intermediate state. T.writeFile "output/OM.txt" $ prettyPrintA1 $ myOM -- generate the cpu library _ <- generateIO cpuSetup myOM -- generate the gpu library _ <- generateIO gpuSetup myOM return ()
nushio3/Paraiso
examples-old/Hydro-exampled/HydroMain.hs
Haskell
bsd-3-clause
10,530
-- | Miscellaneous utilities for various parts of the library module Reddit.Utilities ( unescape ) where import Data.Text (Text) import qualified Data.Text as Text -- | Quick-'n'-dirty unescaping function for posts / wiki pages etc.. unescape :: Text -> Text unescape = replace "&gt;" ">" . replace "&lt;" "<" . replace "&amp;" "&" -- | Swap all instances of a certain string in another string replace :: Text -- ^ String to replace -> Text -- ^ String to replace with -> Text -- ^ String to search -> Text replace s r = Text.intercalate r . Text.splitOn s
intolerable/reddit
src/Reddit/Utilities.hs
Haskell
bsd-2-clause
586
{-# LANGUAGE CPP, BangPatterns #-} module Aws.S3.Core where import Aws.Core import Control.Arrow ((***)) import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Resource (MonadThrow, throwM) import Crypto.Hash import Data.Byteable import Data.Conduit (($$+-)) import Data.Function import Data.Functor ((<$>)) import Data.IORef import Data.List import Data.Maybe import Data.Monoid import Control.Applicative ((<|>)) import Data.Time import Data.Typeable #if MIN_VERSION_time(1,5,0) import Data.Time.Format #else import System.Locale #endif import Text.XML.Cursor (($/), (&|)) import qualified Blaze.ByteString.Builder as Blaze import qualified Blaze.ByteString.Builder.Char8 as Blaze8 import qualified Control.Exception as C import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Base64 as Base64 import qualified Data.CaseInsensitive as CI import qualified Data.Conduit as C import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Network.HTTP.Conduit as HTTP import qualified Network.HTTP.Types as HTTP import qualified Text.XML as XML import qualified Text.XML.Cursor as Cu data S3Authorization = S3AuthorizationHeader | S3AuthorizationQuery deriving (Show) data RequestStyle = PathStyle -- ^ Requires correctly setting region endpoint, but allows non-DNS compliant bucket names in the US standard region. | BucketStyle -- ^ Bucket name must be DNS compliant. | VHostStyle deriving (Show) data S3Configuration qt = S3Configuration { s3Protocol :: Protocol , s3Endpoint :: B.ByteString , s3RequestStyle :: RequestStyle , s3Port :: Int , s3ServerSideEncryption :: Maybe ServerSideEncryption , s3UseUri :: Bool , s3DefaultExpiry :: NominalDiffTime } deriving (Show) instance DefaultServiceConfiguration (S3Configuration NormalQuery) where defServiceConfig = s3 HTTPS s3EndpointUsClassic False debugServiceConfig = s3 HTTP s3EndpointUsClassic False instance DefaultServiceConfiguration (S3Configuration UriOnlyQuery) where defServiceConfig = s3 HTTPS s3EndpointUsClassic True debugServiceConfig = s3 HTTP s3EndpointUsClassic True s3EndpointUsClassic :: B.ByteString s3EndpointUsClassic = "s3.amazonaws.com" s3EndpointUsWest :: B.ByteString s3EndpointUsWest = "s3-us-west-1.amazonaws.com" s3EndpointUsWest2 :: B.ByteString s3EndpointUsWest2 = "s3-us-west-2.amazonaws.com" s3EndpointEu :: B.ByteString s3EndpointEu = "s3-eu-west-1.amazonaws.com" s3EndpointApSouthEast :: B.ByteString s3EndpointApSouthEast = "s3-ap-southeast-1.amazonaws.com" s3EndpointApSouthEast2 :: B.ByteString s3EndpointApSouthEast2 = "s3-ap-southeast-2.amazonaws.com" s3EndpointApNorthEast :: B.ByteString s3EndpointApNorthEast = "s3-ap-northeast-1.amazonaws.com" s3 :: Protocol -> B.ByteString -> Bool -> S3Configuration qt s3 protocol endpoint uri = S3Configuration { s3Protocol = protocol , s3Endpoint = endpoint , s3RequestStyle = BucketStyle , s3Port = defaultPort protocol , s3ServerSideEncryption = Nothing , s3UseUri = uri , s3DefaultExpiry = 15*60 } type ErrorCode = T.Text data S3Error = S3Error { s3StatusCode :: HTTP.Status , s3ErrorCode :: ErrorCode -- Error/Code , s3ErrorMessage :: T.Text -- Error/Message , s3ErrorResource :: Maybe T.Text -- Error/Resource , s3ErrorHostId :: Maybe T.Text -- Error/HostId , s3ErrorAccessKeyId :: Maybe T.Text -- Error/AWSAccessKeyId , s3ErrorStringToSign :: Maybe B.ByteString -- Error/StringToSignBytes (hexadecimal encoding) , s3ErrorBucket :: Maybe T.Text -- Error/Bucket , s3ErrorEndpointRaw :: Maybe T.Text -- Error/Endpoint (i.e. correct bucket location) , s3ErrorEndpoint :: Maybe B.ByteString -- Error/Endpoint without the bucket prefix } deriving (Show, Typeable) instance C.Exception S3Error data S3Metadata = S3Metadata { s3MAmzId2 :: Maybe T.Text , s3MRequestId :: Maybe T.Text } deriving (Show, Typeable) instance Monoid S3Metadata where mempty = S3Metadata Nothing Nothing S3Metadata a1 r1 `mappend` S3Metadata a2 r2 = S3Metadata (a1 `mplus` a2) (r1 `mplus` r2) instance Loggable S3Metadata where toLogText (S3Metadata id2 rid) = "S3: request ID=" `mappend` fromMaybe "<none>" rid `mappend` ", x-amz-id-2=" `mappend` fromMaybe "<none>" id2 data S3Query = S3Query { s3QMethod :: Method , s3QBucket :: Maybe B.ByteString , s3QObject :: Maybe B.ByteString , s3QSubresources :: HTTP.Query , s3QQuery :: HTTP.Query , s3QContentType :: Maybe B.ByteString , s3QContentMd5 :: Maybe (Digest MD5) , s3QAmzHeaders :: HTTP.RequestHeaders , s3QOtherHeaders :: HTTP.RequestHeaders #if MIN_VERSION_http_conduit(2, 0, 0) , s3QRequestBody :: Maybe HTTP.RequestBody #else , s3QRequestBody :: Maybe (HTTP.RequestBody (C.ResourceT IO)) #endif } instance Show S3Query where show S3Query{..} = "S3Query [" ++ " method: " ++ show s3QMethod ++ " ; bucket: " ++ show s3QBucket ++ " ; subresources: " ++ show s3QSubresources ++ " ; query: " ++ show s3QQuery ++ " ; request body: " ++ (case s3QRequestBody of Nothing -> "no"; _ -> "yes") ++ "]" s3SignQuery :: S3Query -> S3Configuration qt -> SignatureData -> SignedQuery s3SignQuery S3Query{..} S3Configuration{..} SignatureData{..} = SignedQuery { sqMethod = s3QMethod , sqProtocol = s3Protocol , sqHost = B.intercalate "." $ catMaybes host , sqPort = s3Port , sqPath = mconcat $ catMaybes path , sqQuery = sortedSubresources ++ s3QQuery ++ authQuery :: HTTP.Query , sqDate = Just signatureTime , sqAuthorization = authorization , sqContentType = s3QContentType , sqContentMd5 = s3QContentMd5 , sqAmzHeaders = amzHeaders , sqOtherHeaders = s3QOtherHeaders , sqBody = s3QRequestBody , sqStringToSign = stringToSign } where amzHeaders = merge $ sortBy (compare `on` fst) (s3QAmzHeaders ++ (fmap (\(k, v) -> (CI.mk k, v)) iamTok)) where merge (x1@(k1,v1):x2@(k2,v2):xs) | k1 == k2 = merge ((k1, B8.intercalate "," [v1, v2]) : xs) | otherwise = x1 : merge (x2 : xs) merge xs = xs urlEncodedS3QObject = HTTP.urlEncode False <$> s3QObject (host, path) = case s3RequestStyle of PathStyle -> ([Just s3Endpoint], [Just "/", fmap (`B8.snoc` '/') s3QBucket, urlEncodedS3QObject]) BucketStyle -> ([s3QBucket, Just s3Endpoint], [Just "/", urlEncodedS3QObject]) VHostStyle -> ([Just $ fromMaybe s3Endpoint s3QBucket], [Just "/", urlEncodedS3QObject]) sortedSubresources = sort s3QSubresources canonicalizedResource = Blaze8.fromChar '/' `mappend` maybe mempty (\s -> Blaze.copyByteString s `mappend` Blaze8.fromChar '/') s3QBucket `mappend` maybe mempty Blaze.copyByteString urlEncodedS3QObject `mappend` HTTP.renderQueryBuilder True sortedSubresources ti = case (s3UseUri, signatureTimeInfo) of (False, ti') -> ti' (True, AbsoluteTimestamp time) -> AbsoluteExpires $ s3DefaultExpiry `addUTCTime` time (True, AbsoluteExpires time) -> AbsoluteExpires time sig = signature signatureCredentials HmacSHA1 stringToSign iamTok = maybe [] (\x -> [("x-amz-security-token", x)]) (iamToken signatureCredentials) stringToSign = Blaze.toByteString . mconcat . intersperse (Blaze8.fromChar '\n') . concat $ [[Blaze.copyByteString $ httpMethod s3QMethod] , [maybe mempty (Blaze.copyByteString . Base64.encode . toBytes) s3QContentMd5] , [maybe mempty Blaze.copyByteString s3QContentType] , [Blaze.copyByteString $ case ti of AbsoluteTimestamp time -> fmtRfc822Time time AbsoluteExpires time -> fmtTimeEpochSeconds time] , map amzHeader amzHeaders , [canonicalizedResource] ] where amzHeader (k, v) = Blaze.copyByteString (CI.foldedCase k) `mappend` Blaze8.fromChar ':' `mappend` Blaze.copyByteString v (authorization, authQuery) = case ti of AbsoluteTimestamp _ -> (Just $ return $ B.concat ["AWS ", accessKeyID signatureCredentials, ":", sig], []) AbsoluteExpires time -> (Nothing, HTTP.toQuery $ makeAuthQuery time) makeAuthQuery time = [("Expires" :: B8.ByteString, fmtTimeEpochSeconds time) , ("AWSAccessKeyId", accessKeyID signatureCredentials) , ("SignatureMethod", "HmacSHA256") , ("Signature", sig)] ++ iamTok s3ResponseConsumer :: HTTPResponseConsumer a -> IORef S3Metadata -> HTTPResponseConsumer a s3ResponseConsumer inner metadataRef = s3BinaryResponseConsumer inner' metadataRef where inner' resp = do !res <- inner resp C.closeResumableSource (HTTP.responseBody resp) return res s3BinaryResponseConsumer :: HTTPResponseConsumer a -> IORef S3Metadata -> HTTPResponseConsumer a s3BinaryResponseConsumer inner metadata resp = do let headerString = fmap T.decodeUtf8 . flip lookup (HTTP.responseHeaders resp) let amzId2 = headerString "x-amz-id-2" let requestId = headerString "x-amz-request-id" let m = S3Metadata { s3MAmzId2 = amzId2, s3MRequestId = requestId } liftIO $ tellMetadataRef metadata m if HTTP.responseStatus resp >= HTTP.status300 then s3ErrorResponseConsumer resp else inner resp s3XmlResponseConsumer :: (Cu.Cursor -> Response S3Metadata a) -> IORef S3Metadata -> HTTPResponseConsumer a s3XmlResponseConsumer parse metadataRef = s3ResponseConsumer (xmlCursorConsumer parse metadataRef) metadataRef s3ErrorResponseConsumer :: HTTPResponseConsumer a s3ErrorResponseConsumer resp = do doc <- HTTP.responseBody resp $$+- XML.sinkDoc XML.def let cursor = Cu.fromDocument doc liftIO $ case parseError cursor of Right err -> throwM err Left otherErr -> throwM otherErr where parseError :: Cu.Cursor -> Either C.SomeException S3Error parseError root = do code <- force "Missing error Code" $ root $/ elContent "Code" message <- force "Missing error Message" $ root $/ elContent "Message" let resource = listToMaybe $ root $/ elContent "Resource" hostId = listToMaybe $ root $/ elContent "HostId" accessKeyId = listToMaybe $ root $/ elContent "AWSAccessKeyId" bucket = listToMaybe $ root $/ elContent "Bucket" endpointRaw = listToMaybe $ root $/ elContent "Endpoint" endpoint = T.encodeUtf8 <$> (T.stripPrefix (fromMaybe "" bucket <> ".") =<< endpointRaw) stringToSign = do unprocessed <- listToMaybe $ root $/ elCont "StringToSignBytes" bytes <- mapM readHex2 $ words unprocessed return $ B.pack bytes return S3Error { s3StatusCode = HTTP.responseStatus resp , s3ErrorCode = code , s3ErrorMessage = message , s3ErrorResource = resource , s3ErrorHostId = hostId , s3ErrorAccessKeyId = accessKeyId , s3ErrorStringToSign = stringToSign , s3ErrorBucket = bucket , s3ErrorEndpointRaw = endpointRaw , s3ErrorEndpoint = endpoint } type CanonicalUserId = T.Text data UserInfo = UserInfo { userId :: CanonicalUserId , userDisplayName :: T.Text } deriving (Show) parseUserInfo :: MonadThrow m => Cu.Cursor -> m UserInfo parseUserInfo el = do id_ <- force "Missing user ID" $ el $/ elContent "ID" displayName <- force "Missing user DisplayName" $ el $/ elContent "DisplayName" return UserInfo { userId = id_, userDisplayName = displayName } data CannedAcl = AclPrivate | AclPublicRead | AclPublicReadWrite | AclAuthenticatedRead | AclBucketOwnerRead | AclBucketOwnerFullControl | AclLogDeliveryWrite deriving (Show) writeCannedAcl :: CannedAcl -> T.Text writeCannedAcl AclPrivate = "private" writeCannedAcl AclPublicRead = "public-read" writeCannedAcl AclPublicReadWrite = "public-read-write" writeCannedAcl AclAuthenticatedRead = "authenticated-read" writeCannedAcl AclBucketOwnerRead = "bucket-owner-read" writeCannedAcl AclBucketOwnerFullControl = "bucket-owner-full-control" writeCannedAcl AclLogDeliveryWrite = "log-delivery-write" data StorageClass = Standard | StandardInfrequentAccess | ReducedRedundancy | Glacier | OtherStorageClass T.Text deriving (Show) parseStorageClass :: T.Text -> StorageClass parseStorageClass "STANDARD" = Standard parseStorageClass "STANDARD_IA" = StandardInfrequentAccess parseStorageClass "REDUCED_REDUNDANCY" = ReducedRedundancy parseStorageClass "GLACIER" = Glacier parseStorageClass s = OtherStorageClass s writeStorageClass :: StorageClass -> T.Text writeStorageClass Standard = "STANDARD" writeStorageClass StandardInfrequentAccess = "STANDARD_IA" writeStorageClass ReducedRedundancy = "REDUCED_REDUNDANCY" writeStorageClass Glacier = "GLACIER" writeStorageClass (OtherStorageClass s) = s data ServerSideEncryption = AES256 deriving (Show) parseServerSideEncryption :: MonadThrow m => T.Text -> m ServerSideEncryption parseServerSideEncryption "AES256" = return AES256 parseServerSideEncryption s = throwM . XmlException $ "Invalid Server Side Encryption: " ++ T.unpack s writeServerSideEncryption :: ServerSideEncryption -> T.Text writeServerSideEncryption AES256 = "AES256" type Bucket = T.Text data BucketInfo = BucketInfo { bucketName :: Bucket , bucketCreationDate :: UTCTime } deriving (Show) type Object = T.Text data ObjectId = ObjectId { oidBucket :: Bucket , oidObject :: Object , oidVersion :: Maybe T.Text } deriving (Show) data ObjectInfo = ObjectInfo { objectKey :: T.Text , objectLastModified :: UTCTime , objectETag :: T.Text , objectSize :: Integer , objectStorageClass :: StorageClass , objectOwner :: Maybe UserInfo } deriving (Show) parseObjectInfo :: MonadThrow m => Cu.Cursor -> m ObjectInfo parseObjectInfo el = do key <- force "Missing object Key" $ el $/ elContent "Key" let time s = case (parseTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%QZ" $ T.unpack s) <|> (parseTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%Q%Z" $ T.unpack s) of Nothing -> throwM $ XmlException "Invalid time" Just v -> return v lastModified <- forceM "Missing object LastModified" $ el $/ elContent "LastModified" &| time eTag <- force "Missing object ETag" $ el $/ elContent "ETag" size <- forceM "Missing object Size" $ el $/ elContent "Size" &| textReadInt storageClass <- forceM "Missing object StorageClass" $ el $/ elContent "StorageClass" &| return . parseStorageClass owner <- case el $/ Cu.laxElement "Owner" &| parseUserInfo of (x:_) -> fmap' Just x [] -> return Nothing return ObjectInfo{ objectKey = key , objectLastModified = lastModified , objectETag = eTag , objectSize = size , objectStorageClass = storageClass , objectOwner = owner } where fmap' :: Monad m => (a -> b) -> m a -> m b fmap' f ma = ma >>= return . f data ObjectMetadata = ObjectMetadata { omDeleteMarker :: Bool , omETag :: T.Text , omLastModified :: UTCTime , omVersionId :: Maybe T.Text -- TODO: -- , omExpiration :: Maybe (UTCTime, T.Text) , omUserMetadata :: [(T.Text, T.Text)] , omMissingUserMetadata :: Maybe T.Text , omServerSideEncryption :: Maybe ServerSideEncryption } deriving (Show) parseObjectMetadata :: MonadThrow m => HTTP.ResponseHeaders -> m ObjectMetadata parseObjectMetadata h = ObjectMetadata `liftM` deleteMarker `ap` etag `ap` lastModified `ap` return versionId -- `ap` expiration `ap` return userMetadata `ap` return missingUserMetadata `ap` serverSideEncryption where deleteMarker = case B8.unpack `fmap` lookup "x-amz-delete-marker" h of Nothing -> return False Just "true" -> return True Just "false" -> return False Just x -> throwM $ HeaderException ("Invalid x-amz-delete-marker " ++ x) etag = case T.decodeUtf8 `fmap` lookup "ETag" h of Just x -> return x Nothing -> throwM $ HeaderException "ETag missing" lastModified = case B8.unpack `fmap` lookup "Last-Modified" h of Just ts -> case parseHttpDate ts of Just t -> return t Nothing -> throwM $ HeaderException ("Invalid Last-Modified: " ++ ts) Nothing -> throwM $ HeaderException "Last-Modified missing" versionId = T.decodeUtf8 `fmap` lookup "x-amz-version-id" h -- expiration = return undefined userMetadata = flip mapMaybe ht $ \(k, v) -> do i <- T.stripPrefix "x-amz-meta-" k return (i, v) missingUserMetadata = T.decodeUtf8 `fmap` lookup "x-amz-missing-meta" h serverSideEncryption = case T.decodeUtf8 `fmap` lookup "x-amz-server-side-encryption" h of Just x -> return $ parseServerSideEncryption x Nothing -> return Nothing ht = map ((T.decodeUtf8 . CI.foldedCase) *** T.decodeUtf8) h type LocationConstraint = T.Text locationUsClassic, locationUsWest, locationUsWest2, locationEu, locationEuFrankfurt, locationApSouthEast, locationApSouthEast2, locationApNorthEast, locationSA :: LocationConstraint locationUsClassic = "" locationUsWest = "us-west-1" locationUsWest2 = "us-west-2" locationEu = "EU" locationEuFrankfurt = "eu-central-1" locationApSouthEast = "ap-southeast-1" locationApSouthEast2 = "ap-southeast-2" locationApNorthEast = "ap-northeast-1" locationSA = "sa-east-1" normaliseLocation :: LocationConstraint -> LocationConstraint normaliseLocation location | location == "eu-west-1" = locationEu | otherwise = location
romanb/aws
Aws/S3/Core.hs
Haskell
bsd-3-clause
20,800
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module Stack.ConfigSpec where import Data.Aeson.Extended import Data.Yaml import Path import Path.IO hiding (withSystemTempDir) import Stack.Config import Stack.Prelude import Stack.Types.Config import Stack.Types.Runner import System.Directory import System.Environment import System.IO (writeFile) import Test.Hspec sampleConfig :: String sampleConfig = "resolver: lts-2.10\n" ++ "packages: ['.']\n" buildOptsConfig :: String buildOptsConfig = "resolver: lts-2.10\n" ++ "packages: ['.']\n" ++ "build:\n" ++ " library-profiling: true\n" ++ " executable-profiling: true\n" ++ " haddock: true\n" ++ " haddock-deps: true\n" ++ " copy-bins: true\n" ++ " prefetch: true\n" ++ " force-dirty: true\n" ++ " keep-going: true\n" ++ " test: true\n" ++ " test-arguments:\n" ++ " rerun-tests: true\n" ++ " additional-args: ['-fprof']\n" ++ " coverage: true\n" ++ " no-run-tests: true\n" ++ " bench: true\n" ++ " benchmark-opts:\n" ++ " benchmark-arguments: -O2\n" ++ " no-run-benchmarks: true\n" ++ " reconfigure: true\n" ++ " cabal-verbose: true\n" hpackConfig :: String hpackConfig = "resolver: lts-2.10\n" ++ "with-hpack: /usr/local/bin/hpack\n" ++ "packages: ['.']\n" stackDotYaml :: Path Rel File stackDotYaml = $(mkRelFile "stack.yaml") setup :: IO () setup = unsetEnv "STACK_YAML" noException :: Selector SomeException noException = const False spec :: Spec spec = beforeAll setup $ do let logLevel = LevelDebug -- TODO(danburton): not use inTempDir let inTempDir action = do currentDirectory <- getCurrentDirectory withSystemTempDirectory "Stack_ConfigSpec" $ \tempDir -> do let enterDir = setCurrentDirectory tempDir let exitDir = setCurrentDirectory currentDirectory bracket_ enterDir exitDir action -- TODO(danburton): a safer version of this? let withEnvVar name newValue action = do originalValue <- fromMaybe "" <$> lookupEnv name let setVar = setEnv name newValue let resetVar = setEnv name originalValue bracket_ setVar resetVar action describe "loadConfig" $ do let loadConfig' inner = withRunner logLevel True False ColorAuto Nothing False $ \runner -> do lc <- runRIO runner $ loadConfig mempty Nothing SYLDefault inner lc -- TODO(danburton): make sure parent dirs also don't have config file it "works even if no config file exists" $ example $ loadConfig' $ const $ return () it "works with a blank config file" $ inTempDir $ do writeFile (toFilePath stackDotYaml) "" -- TODO(danburton): more specific test for exception loadConfig' (const (return ())) `shouldThrow` anyException it "parses config option with-hpack" $ inTempDir $ do writeFile (toFilePath stackDotYaml) hpackConfig loadConfig' $ \lc -> do let Config{..} = lcConfig lc configOverrideHpack `shouldBe` HpackCommand "/usr/local/bin/hpack" it "parses config bundled hpack" $ inTempDir $ do writeFile (toFilePath stackDotYaml) sampleConfig loadConfig' $ \lc -> do let Config{..} = lcConfig lc configOverrideHpack `shouldBe` HpackBundled it "parses build config options" $ inTempDir $ do writeFile (toFilePath stackDotYaml) buildOptsConfig loadConfig' $ \lc -> do let BuildOpts{..} = configBuild $ lcConfig lc boptsLibProfile `shouldBe` True boptsExeProfile `shouldBe` True boptsHaddock `shouldBe` True boptsHaddockDeps `shouldBe` Just True boptsInstallExes `shouldBe` True boptsPreFetch `shouldBe` True boptsKeepGoing `shouldBe` Just True boptsForceDirty `shouldBe` True boptsTests `shouldBe` True boptsTestOpts `shouldBe` TestOpts {toRerunTests = True ,toAdditionalArgs = ["-fprof"] ,toCoverage = True ,toDisableRun = True} boptsBenchmarks `shouldBe` True boptsBenchmarkOpts `shouldBe` BenchmarkOpts {beoAdditionalArgs = Just "-O2" ,beoDisableRun = True} boptsReconfigure `shouldBe` True boptsCabalVerbose `shouldBe` True it "finds the config file in a parent directory" $ inTempDir $ do writeFile (toFilePath stackDotYaml) sampleConfig parentDir <- getCurrentDirectory >>= parseAbsDir let childDir = "child" createDirectory childDir setCurrentDirectory childDir loadConfig' $ \LoadConfig{..} -> do bc <- liftIO (lcLoadBuildConfig Nothing) view projectRootL bc `shouldBe` parentDir it "respects the STACK_YAML env variable" $ inTempDir $ do withSystemTempDir "config-is-here" $ \dir -> do let stackYamlFp = toFilePath (dir </> stackDotYaml) writeFile stackYamlFp sampleConfig withEnvVar "STACK_YAML" stackYamlFp $ loadConfig' $ \LoadConfig{..} -> do BuildConfig{..} <- lcLoadBuildConfig Nothing bcStackYaml `shouldBe` dir </> stackDotYaml parent bcStackYaml `shouldBe` dir it "STACK_YAML can be relative" $ inTempDir $ do parentDir <- getCurrentDirectory >>= parseAbsDir let childRel = $(mkRelDir "child") yamlRel = childRel </> $(mkRelFile "some-other-name.config") yamlAbs = parentDir </> yamlRel createDirectoryIfMissing True $ toFilePath $ parent yamlAbs writeFile (toFilePath yamlAbs) "resolver: ghc-7.8" withEnvVar "STACK_YAML" (toFilePath yamlRel) $ loadConfig' $ \LoadConfig{..} -> do BuildConfig{..} <- lcLoadBuildConfig Nothing bcStackYaml `shouldBe` yamlAbs describe "defaultConfigYaml" $ it "is parseable" $ \_ -> do curDir <- getCurrentDir let parsed :: Either String (Either String (WithJSONWarnings ConfigMonoid)) parsed = parseEither (parseConfigMonoid curDir) <$> decodeEither defaultConfigYaml case parsed of Right (Right _) -> return () :: IO () _ -> fail "Failed to parse default config yaml"
MichielDerhaeg/stack
src/test/Stack/ConfigSpec.hs
Haskell
bsd-3-clause
6,310
module GetContents where import qualified Github.Repos as Github import Data.List import Prelude hiding (truncate, getContents) main = do putStrLn "Root" putStrLn "====" getContents "" putStrLn "LICENSE" putStrLn "=======" getContents "LICENSE" getContents path = do contents <- Github.contentsFor "mike-burns" "ohlaunch" path Nothing putStrLn $ either (("Error: " ++) . show) formatContents contents formatContents (Github.ContentFile fileData) = formatContentInfo (Github.contentFileInfo fileData) ++ unlines [ show (Github.contentFileSize fileData) ++ " bytes" , "encoding: " ++ Github.contentFileEncoding fileData , "data: " ++ truncate (Github.contentFileContent fileData) ] formatContents (Github.ContentDirectory items) = intercalate "\n\n" $ map formatItem items formatContentInfo contentInfo = unlines [ "name: " ++ Github.contentName contentInfo , "path: " ++ Github.contentPath contentInfo , "sha: " ++ Github.contentSha contentInfo , "url: " ++ Github.contentUrl contentInfo , "git url: " ++ Github.contentGitUrl contentInfo , "html url: " ++ Github.contentHtmlUrl contentInfo ] formatItem item = "type: " ++ show (Github.contentItemType item) ++ "\n" ++ formatContentInfo (Github.contentItemInfo item) truncate str = take 40 str ++ "... (truncated)"
bitemyapp/github
samples/Repos/Contents.hs
Haskell
bsd-3-clause
1,346
module Parse.Binop (binops, OpTable) where import qualified Data.List as List import qualified Data.Map as Map import Text.Parsec ((<|>), choice, getState, try) import AST.Declaration (Assoc(L, N, R)) import AST.Expression.General (Expr'(Binop)) import qualified AST.Expression.Source as Source import qualified AST.Variable as Var import Parse.Helpers (IParser, OpTable, commitIf, failure, whitespace) import qualified Reporting.Annotation as A opLevel :: OpTable -> String -> Int opLevel table op = fst $ Map.findWithDefault (9,L) op table opAssoc :: OpTable -> String -> Assoc opAssoc table op = snd $ Map.findWithDefault (9,L) op table hasLevel :: OpTable -> Int -> (String, Source.Expr) -> Bool hasLevel table n (op,_) = opLevel table op == n binops :: IParser Source.Expr -> IParser Source.Expr -> IParser String -> IParser Source.Expr binops term last anyOp = do e <- term table <- getState split table 0 e =<< nextOps where nextOps = choice [ commitIf (whitespace >> anyOp) $ do whitespace op <- anyOp whitespace expr <- Left <$> try term <|> Right <$> last case expr of Left t -> (:) (op,t) <$> nextOps Right e -> return [(op,e)] , return [] ] split :: OpTable -> Int -> Source.Expr -> [(String, Source.Expr)] -> IParser Source.Expr split _ _ e [] = return e split table n e eops = do assoc <- getAssoc table n eops es <- sequence (splitLevel table n e eops) let ops = map fst (filter (hasLevel table n) eops) case assoc of R -> joinR es ops _ -> joinL es ops splitLevel :: OpTable -> Int -> Source.Expr -> [(String, Source.Expr)] -> [IParser Source.Expr] splitLevel table n e eops = case break (hasLevel table n) eops of (lops, (_op,e'):rops) -> split table (n+1) e lops : splitLevel table n e' rops (lops, []) -> [ split table (n+1) e lops ] joinL :: [Source.Expr] -> [String] -> IParser Source.Expr joinL exprs ops = case (exprs, ops) of ([expr], []) -> return expr (a:b:remainingExprs, op:remainingOps) -> let binop = A.merge a b (Binop (Var.Raw op) a b) in joinL (binop : remainingExprs) remainingOps (_, _) -> failure "Ill-formed binary expression. Report a compiler bug." joinR :: [Source.Expr] -> [String] -> IParser Source.Expr joinR exprs ops = case (exprs, ops) of ([expr], []) -> return expr (a:b:remainingExprs, op:remainingOps) -> do e <- joinR (b:remainingExprs) remainingOps return (A.merge a e (Binop (Var.Raw op) a e)) (_, _) -> failure "Ill-formed binary expression. Report a compiler bug." getAssoc :: OpTable -> Int -> [(String,Source.Expr)] -> IParser Assoc getAssoc table n eops | all (==L) assocs = return L | all (==R) assocs = return R | all (==N) assocs = case assocs of [_] -> return N _ -> failure (msg "precedence") | otherwise = failure (msg "associativity") where levelOps = filter (hasLevel table n) eops assocs = map (opAssoc table . fst) levelOps msg problem = concat [ "Conflicting " ++ problem ++ " for binary operators (" , List.intercalate ", " (map fst eops), "). " , "Consider adding parentheses to disambiguate." ]
laszlopandy/elm-compiler
src/Parse/Binop.hs
Haskell
bsd-3-clause
3,497
module T16114 where data T a instance Eq a => Eq a => Eq (T a) where (==) = undefined
sdiehl/ghc
testsuite/tests/rename/should_fail/T16114.hs
Haskell
bsd-3-clause
87
{-# htermination enumFromTo :: Int -> Int -> [Int] #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_enumFromTo_4.hs
Haskell
mit
55
{-# LANGUAGE LambdaCase, ConstraintKinds #-} ------------------------------------------------------------------------------ -- | -- Module : RemindHelpers -- Copyright : (C) 2014 Samuli Thomasson -- License : BSD-style (see the file LICENSE) -- Maintainer : Samuli Thomasson <samuli.thomasson@paivola.fi> -- Stability : experimental -- Portability : non-portable ------------------------------------------------------------------------------ module RemindHelpers where import Prelude import Yesod import Model import Control.Applicative import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.IO as T import Database.Persist.Sql import qualified System.Process as P import System.Exit (ExitCode(..)) import System.IO (hClose) type RemindRes = Either Text Text type RemindCtx site = (Yesod site, YesodPersist site, YesodPersistBackend site ~ SqlBackend) -- | Run a remind command remindRun :: MonadIO m => [String] -> Text -> m RemindRes remindRun ps ctx = liftIO $ do (Just inp, Just out, Just err, pid) <- P.createProcess ( (P.proc "remind" (ps ++ ["-"])) { P.std_in = P.CreatePipe , P.std_out = P.CreatePipe , P.std_err = P.CreatePipe } ) T.hPutStr inp ctx >> hClose inp out' <- T.hGetContents out err' <- T.hGetContents err P.waitForProcess pid >>= return . \case ExitSuccess -> Right out' ExitFailure _ -> Left err' -- | Print a reminder line formatted inside an <i> element. prettyRemindI :: Text -> WidgetT site IO () prettyRemindI txt = case T.words txt of date : _ : _ : _ : _ : time : msg -> [whamlet|<i>#{date} #{time} - #{T.unwords msg}|] _ -> [whamlet|error: no parse: #{txt}|] -- | <li> entries for next reminders. remindListS :: RemindCtx site => Text -> WidgetT site IO () remindListS txt = do res <- fmap T.lines <$> remindRun ["-r", "-s+2"] txt [whamlet| $case res $of Right xs $forall x <- xs <li.light>^{prettyRemindI x} $of Left err <li.alert-error>err |] -- | Combine all remind entries from DB to a single text that can be fed to -- 'remind'. combineReminds :: RemindCtx site => HandlerT site IO Text combineReminds = do txts <- runDB (selectList [] []) return $ T.unlines . concat $ map (T.lines . T.replace "\r\n" "\n" . calendarRemind . entityVal) txts remindNextWeeks :: RemindCtx site => WidgetT site IO () remindNextWeeks = remindListS =<< handlerToWidget combineReminds -- | A simple ascii calendar (remind -c) remindAsciiCalendar :: RemindCtx site => HandlerT site IO RemindRes remindAsciiCalendar = remindRun ["-c+4" -- generate four week calendar , "-b1" -- 24h time format , "-m" -- week begins at monday , "-r" -- disable RUN and shell() , "-w110,0,0" -- 110 character cells ] =<< combineReminds
TK009/loyly
RemindHelpers.hs
Haskell
mit
2,973
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE QuasiQuotes #-} import Control.Applicative ((<$>), (<*>)) import Control.Monad (mzero) import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (runNoLoggingT, NoLoggingT) import Control.Monad.Trans.Resource (runResourceT, ResourceT) import Control.Monad.Trans.Either import Data.Aeson import Data.Maybe (fromMaybe) import qualified Data.Text as Text import Data.Proxy import qualified Database.Persist.Class as DB import qualified Database.Persist.Sqlite as Sqlite import Database.Persist.TH import Network.HTTP.Types import Network.Wai import Network.Wai.Handler.Warp (run) import Network.Wai.Middleware.AddHeaders import Servant import System.Environment import Web.PathPieces share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase| Todo title String completed Bool order Int deriving Show |] runDb :: Sqlite.SqlPersistT (ResourceT (NoLoggingT IO)) a -> IO a runDb = runNoLoggingT . runResourceT . Sqlite.withSqliteConn "dev.sqlite3" . Sqlite.runSqlConn instance ToJSON (Sqlite.Entity Todo) where toJSON entity = object [ "id" .= key , "url" .= ("http://127.0.0.1:3000/todos/" ++ keyText) , "title" .= todoTitle val , "completed" .= todoCompleted val , "order" .= todoOrder val ] where key = Sqlite.entityKey entity val = Sqlite.entityVal entity keyText = Text.unpack $ toPathPiece key data TodoAction = TodoAction { actTitle :: Maybe String , actCompleted :: Maybe Bool , actOrder :: Maybe Int } deriving Show instance FromJSON TodoAction where parseJSON (Object o) = TodoAction <$> o .:? "title" <*> o .:? "completed" <*> o .:? "order" parseJSON _ = mzero instance ToJSON TodoAction where toJSON (TodoAction mTitle mCompl mOrder) = noNullsObject [ "title" .= mTitle , "completed" .= mCompl , "order" .= mOrder ] where noNullsObject = object . filter notNull notNull (_, Null) = False notNull _ = True actionToTodo :: TodoAction -> Todo actionToTodo (TodoAction mTitle mCompleted mOrder) = Todo title completed order where title = fromMaybe "" mTitle completed = fromMaybe False mCompleted order = fromMaybe 0 mOrder actionToUpdates :: TodoAction -> [Sqlite.Update Todo] actionToUpdates act = updateTitle ++ updateCompl ++ updateOrd where updateTitle = maybe [] (\title -> [TodoTitle Sqlite.=. title]) (actTitle act) updateCompl = maybe [] (\compl -> [TodoCompleted Sqlite.=. compl]) (actCompleted act) updateOrd = maybe [] (\ord -> [TodoOrder Sqlite.=. ord]) (actOrder act) allowCors :: Middleware allowCors = addHeaders [ ("Access-Control-Allow-Origin", "*"), ("Access-Control-Allow-Headers", "Accept, Content-Type"), ("Access-Control-Allow-Methods", "GET, HEAD, POST, DELETE, OPTIONS, PUT, PATCH") ] allowOptions :: Middleware allowOptions app req resp = case requestMethod req of "OPTIONS" -> resp $ responseLBS status200 [] "Ok" _ -> app req resp type TodoApi = "todos" :> Get '[JSON] [Sqlite.Entity Todo] :<|> "todos" :> Delete '[JSON] () :<|> "todos" :> ReqBody '[JSON] TodoAction :> Post '[JSON] (Sqlite.Entity Todo) :<|> "todos" :> Capture "todoid" Integer :> Get '[JSON] (Sqlite.Entity Todo) :<|> "todos" :> Capture "todoid" Integer :> Delete '[JSON] () :<|> "todos" :> Capture "todoid" Integer :> ReqBody '[JSON] TodoAction :> Patch '[JSON] (Sqlite.Entity Todo) todoApi :: Proxy TodoApi todoApi = Proxy getTodos :: EitherT ServantErr IO [Sqlite.Entity Todo] getTodos = liftIO $ runDb $ DB.selectList [] ([] :: [Sqlite.SelectOpt Todo]) deleteTodos :: EitherT ServantErr IO () deleteTodos = liftIO $ runDb $ DB.deleteWhere ([] :: [Sqlite.Filter Todo]) getTodo :: Integer -> EitherT ServantErr IO (Sqlite.Entity Todo) getTodo tid = do let tKey = Sqlite.toSqlKey (fromIntegral tid) Just todo <- liftIO $ runDb $ DB.get tKey return $ Sqlite.Entity tKey todo deleteTodo :: Integer -> EitherT ServantErr IO () deleteTodo tid = do let tKey = Sqlite.toSqlKey (fromIntegral tid) liftIO $ runDb $ DB.delete (tKey :: Sqlite.Key Todo) postTodo :: TodoAction -> EitherT ServantErr IO (Sqlite.Entity Todo) postTodo todoAct = do let todo = actionToTodo todoAct tid <- liftIO $ runDb $ DB.insert todo return $ Sqlite.Entity tid todo patchTodo :: Integer -> TodoAction -> EitherT ServantErr IO (Sqlite.Entity Todo) patchTodo tid todoAct = do let tKey = Sqlite.toSqlKey (fromIntegral tid) updates = actionToUpdates todoAct todo <- liftIO $ runDb $ DB.updateGet tKey updates return $ Sqlite.Entity tKey todo server :: Server TodoApi server = getTodos :<|> deleteTodos :<|> postTodo :<|> getTodo :<|> deleteTodo :<|> patchTodo waiApp :: Application waiApp = allowCors $ allowOptions $ serve todoApi server main :: IO () main = do runDb $ Sqlite.runMigration migrateAll port <- read <$> getEnv "PORT" run port waiApp
jhedev/todobackend-servant
src/Main.hs
Haskell
mit
5,848
{-# OPTIONS_GHC -XTypeFamilies -XRank2Types #-} {-| This library provides a collection of monad transformers that can be combined to produce various monads. -} module MonadLib ( -- * Types -- $Types Id, Lift, IdT, ReaderT, WriterT, StateT, ExceptionT, ChoiceT, ContT, -- * Lifting -- $Lifting MonadT(..), HasBase(..), -- * Effect Classes -- $Effects ReaderM(..), WriterM(..), StateM(..), ExceptionM(..), ContM(..), Label, labelCC, jump, -- * Execution -- ** Eliminating Effects -- $Execution runId, runLift, runIdT, runReaderT, runWriterT, runStateT, runExceptionT, runContT, runChoiceT, findOne, findAll, -- ** Nested Execution -- $Nested_Exec RunReaderM(..), RunWriterM(..), RunExceptionM(..), -- * Deriving functions Iso(..), derive_fmap, derive_return, derive_bind, derive_fail, derive_mfix, derive_ask, derive_put, derive_get, derive_set, derive_raise, derive_callCC, derive_local, derive_collect, derive_try, derive_mzero, derive_mplus, derive_lift, derive_inBase, -- * Miscellaneous version, module Control.Monad ) where import Control.Monad import Control.Monad.Fix import Data.Monoid import Prelude hiding (Ordering(..)) -- | The current version of the library. version :: (Int,Int,Int) version = (3,4,0) -- $Types -- -- The following types define the representations of the -- computation types supported by the library. -- Each type adds support for a different effect. -- | Computations with no effects. newtype Id a = I a -- | Computation with no effects (strict). data Lift a = L a -- | Add nothing. Useful as a placeholder. newtype IdT m a = IT (m a) -- | Add support for propagating a context. newtype ReaderT i m a = R (i -> m a) -- | Add support for collecting values. newtype WriterT i m a = W (m (a,i)) -- | Add support for threading state. newtype StateT i m a = S (i -> m (a,i)) -- | Add support for exceptions. newtype ExceptionT i m a = X (m (Either i a)) -- | Add support for multiple answers. data ChoiceT m a = NoAnswer | Answer a | Choice (ChoiceT m a) (ChoiceT m a) | ChoiceEff (m (ChoiceT m a)) -- | Add support for jumps. newtype ContT i m a = C ((a -> m i) -> m i) -- $Execution -- -- The following functions eliminate the outermost effect -- of a computation by translating a computation into an -- equivalent computation in the underlying monad. -- (The exceptions are 'Id' and 'Lift' which are not transformers -- but ordinary monas and so, their run operations simply -- eliminate the monad.) -- | Get the result of a pure computation. runId :: Id a -> a runId (I a) = a -- | Get the result of a pure strict computation. runLift :: Lift a -> a runLift (L a) = a -- | Remove an identity layer. runIdT :: IdT m a -> m a runIdT (IT a) = a -- | Execute a reader computation in the given context. runReaderT :: i -> ReaderT i m a -> m a runReaderT i (R m) = m i -- | Execute a writer computation. -- Returns the result and the collected output. runWriterT :: WriterT i m a -> m (a,i) runWriterT (W m) = m -- | Execute a stateful computation in the given initial state. -- The second component of the result is the final state. runStateT :: i -> StateT i m a -> m (a,i) runStateT i (S m) = m i -- | Execute a computation with exceptions. -- Successful results are tagged with 'Right', -- exceptional results are tagged with 'Left'. runExceptionT :: ExceptionT i m a -> m (Either i a) runExceptionT (X m) = m -- | Execute a computation that may return multiple answers. -- The resulting computation computation returns 'Nothing' -- if no answers were found, or @Just (answer,new_comp)@, -- where @answer@ is an answer, and @new_comp@ is a computation -- that may produce more answers. -- The search is depth-first and left-biased with respect to the -- 'mplus' operation. runChoiceT :: (Monad m) => ChoiceT m a -> m (Maybe (a,ChoiceT m a)) runChoiceT (Answer a) = return (Just (a,NoAnswer)) runChoiceT NoAnswer = return Nothing runChoiceT (Choice l r) = do x <- runChoiceT l case x of Nothing -> runChoiceT r Just (a,l1) -> return (Just (a,Choice l1 r)) runChoiceT (ChoiceEff m) = runChoiceT =<< m -- | Execute a computation that may return multiple answers, -- returning at most one answer. findOne :: (Monad m) => ChoiceT m a -> m (Maybe a) findOne m = fmap fst `liftM` runChoiceT m -- | Executie a computation that may return multiple answers, -- collecting all possible answers. findAll :: (Monad m) => ChoiceT m a -> m [a] findAll m = all =<< runChoiceT m where all Nothing = return [] all (Just (a,as)) = (a:) `liftM` findAll as -- | Execute a computation with the given continuation. runContT :: (a -> m i) -> ContT i m a -> m i runContT i (C m) = m i -- $Lifting -- -- The following operations allow us to promote computations -- in the underlying monad to computations that support an extra -- effect. Computations defined in this way do not make use of -- the new effect but can be combined with other operations that -- utilize the effect. class MonadT t where -- | Promote a computation from the underlying monad. lift :: (Monad m) => m a -> t m a -- It is interesting to note that these use something the resembles -- the non-transformer 'return's. instance MonadT IdT where lift m = IT m instance MonadT (ReaderT i) where lift m = R (\_ -> m) instance MonadT (StateT i) where lift m = S (\s -> liftM (\a -> (a,s)) m) instance (Monoid i) => MonadT (WriterT i) where lift m = W (liftM (\a -> (a,mempty)) m) instance MonadT (ExceptionT i) where lift m = X (liftM Right m) instance MonadT ChoiceT where lift m = ChoiceEff (liftM Answer m) instance MonadT (ContT i) where lift m = C (m >>=) class Monad m => HasBase m where type BaseM m :: * -> * -- How to specify: Monad (Base m) -- | Promote a computation from the base monad. inBase :: BaseM m a -> m a instance HasBase IO where type BaseM IO = IO; inBase = id instance HasBase Maybe where type BaseM Maybe = Maybe; inBase = id instance HasBase [] where type BaseM [] = []; inBase = id instance HasBase Id where type BaseM Id = Id; inBase = id instance HasBase Lift where type BaseM Lift = Lift; inBase = id instance HasBase m => HasBase (IdT m) where type BaseM (IdT m) = BaseM m inBase m = lift (inBase m) instance (HasBase m) => HasBase (ReaderT i m) where type BaseM (ReaderT i m) = BaseM m inBase m = lift (inBase m) instance (HasBase m) => HasBase (StateT i m) where type BaseM (StateT i m) = BaseM m inBase m = lift (inBase m) instance (HasBase m,Monoid i) => HasBase (WriterT i m) where type BaseM (WriterT i m) = BaseM m inBase m = lift (inBase m) instance (HasBase m) => HasBase (ExceptionT i m) where type BaseM (ExceptionT i m) = BaseM m inBase m = lift (inBase m) instance (HasBase m) => HasBase (ChoiceT m) where type BaseM (ChoiceT m) = BaseM m inBase m = lift (inBase m) instance (HasBase m) => HasBase (ContT i m) where type BaseM (ContT i m) = BaseM m inBase m = lift (inBase m) instance Monad Id where return x = I x fail x = error x m >>= k = k (runId m) instance Monad Lift where return x = L x fail x = error x L x >>= k = k x -- For the monad transformers, the definition of 'return' -- is completely determined by the 'lift' operations. -- None of the transformers make essential use of the 'fail' method. -- Instead they delegate its behavior to the underlying monad. instance (Monad m) => Monad (IdT m) where return x = lift (return x) fail x = lift (fail x) m >>= k = IT (runIdT m >>= (runIdT . k)) instance (Monad m) => Monad (ReaderT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = R (\r -> runReaderT r m >>= \a -> runReaderT r (k a)) instance (Monad m) => Monad (StateT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = S (\s -> runStateT s m >>= \ ~(a,s') -> runStateT s' (k a)) instance (Monad m,Monoid i) => Monad (WriterT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = W $ runWriterT m >>= \ ~(a,w1) -> runWriterT (k a) >>= \ ~(b,w2) -> return (b,mappend w1 w2) instance (Monad m) => Monad (ExceptionT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = X $ runExceptionT m >>= \a -> case a of Left x -> return (Left x) Right a -> runExceptionT (k a) instance (Monad m) => Monad (ChoiceT m) where return x = Answer x fail x = lift (fail x) Answer a >>= k = k a NoAnswer >>= _ = NoAnswer Choice m1 m2 >>= k = Choice (m1 >>= k) (m2 >>= k) ChoiceEff m >>= k = ChoiceEff (liftM (>>= k) m) instance (Monad m) => Monad (ContT i m) where return x = lift (return x) fail x = lift (fail x) m >>= k = C $ \c -> runContT (\a -> runContT c (k a)) m instance Functor Id where fmap = liftM instance Functor Lift where fmap = liftM instance (Monad m) => Functor (IdT m) where fmap = liftM instance (Monad m) => Functor (ReaderT i m) where fmap = liftM instance (Monad m) => Functor (StateT i m) where fmap = liftM instance (Monad m,Monoid i) => Functor (WriterT i m) where fmap = liftM instance (Monad m) => Functor (ExceptionT i m) where fmap = liftM instance (Monad m) => Functor (ChoiceT m) where fmap = liftM instance (Monad m) => Functor (ContT i m) where fmap = liftM -- $Monadic_Value_Recursion -- -- Recursion that does not duplicate side-effects. -- For details see Levent Erkok's dissertation. -- -- Monadic types built with 'ContT' do not support -- monadic value recursion. instance MonadFix Id where mfix f = let m = f (runId m) in m instance MonadFix Lift where mfix f = let m = f (runLift m) in m instance (MonadFix m) => MonadFix (IdT m) where mfix f = IT (mfix (runIdT . f)) instance (MonadFix m) => MonadFix (ReaderT i m) where mfix f = R $ \r -> mfix (runReaderT r . f) instance (MonadFix m) => MonadFix (StateT i m) where mfix f = S $ \s -> mfix (runStateT s . f . fst) instance (MonadFix m,Monoid i) => MonadFix (WriterT i m) where mfix f = W $ mfix (runWriterT . f . fst) -- No instance for ChoiceT instance (MonadFix m) => MonadFix (ExceptionT i m) where mfix f = X $ mfix (runExceptionT . f . fromRight) where fromRight (Right a) = a fromRight _ = error "ExceptionT: mfix looped." -- No instance for ContT instance (MonadPlus m) => MonadPlus (IdT m) where mzero = lift mzero mplus (IT m) (IT n) = IT (mplus m n) instance (MonadPlus m) => MonadPlus (ReaderT i m) where mzero = lift mzero mplus (R m) (R n) = R (\r -> mplus (m r) (n r)) instance (MonadPlus m) => MonadPlus (StateT i m) where mzero = lift mzero mplus (S m) (S n) = S (\s -> mplus (m s) (n s)) instance (MonadPlus m,Monoid i) => MonadPlus (WriterT i m) where mzero = lift mzero mplus (W m) (W n) = W (mplus m n) instance (MonadPlus m) => MonadPlus (ExceptionT i m) where mzero = lift mzero mplus (X m) (X n) = X (mplus m n) instance (Monad m) => MonadPlus (ChoiceT m) where mzero = NoAnswer mplus m n = Choice m n -- Alternatives share the continuation. instance (MonadPlus m) => MonadPlus (ContT i m) where mzero = lift mzero mplus (C m) (C n) = C (\k -> m k `mplus` n k) -- $Effects -- -- The following classes define overloaded operations -- that can be used to define effectful computations. -- | Classifies monads that provide access to a context of type @i@. class (Monad m) => ReaderM m where type Reads m -- | Get the context. ask :: m (Reads m) instance (Monad m) => ReaderM (ReaderT i m) where type Reads (ReaderT i m) = i ask = R return instance (ReaderM m) => ReaderM (IdT m) where type Reads (IdT m) = Reads m ask = lift ask instance (ReaderM m, Monoid i) => ReaderM (WriterT i m) where type Reads (WriterT i m) = Reads m ask = lift ask instance (ReaderM m) => ReaderM (StateT i m) where type Reads (StateT i m) = Reads m ask = lift ask instance (ReaderM m) => ReaderM (ExceptionT i m) where type Reads (ExceptionT i m) = Reads m ask = lift ask instance (ReaderM m) => ReaderM (ChoiceT m) where type Reads (ChoiceT m) = Reads m ask = lift ask instance (ReaderM m) => ReaderM (ContT i m) where type Reads (ContT i m) = Reads m ask = lift ask -- t -- | Classifies monads that can collect values. class (Monad m) => WriterM m where -- | The types of the collection that we modify. type Writes m -- | Add a value to the collection. put :: Writes m -> m () instance (Monad m,Monoid i) => WriterM (WriterT i m) where type Writes (WriterT i m) = i put x = W (return ((),x)) instance (WriterM m) => WriterM (IdT m) where type Writes (IdT m) = Writes m put x = lift (put x) instance (WriterM m) => WriterM (ReaderT i m) where type Writes (ReaderT i m) = Writes m put x = lift (put x) instance (WriterM m) => WriterM (StateT i m) where type Writes (StateT i m) = Writes m put x = lift (put x) instance (WriterM m) => WriterM (ExceptionT i m) where type Writes (ExceptionT i m) = Writes m put x = lift (put x) instance (WriterM m) => WriterM (ChoiceT m) where type Writes (ChoiceT m) = Writes m put x = lift (put x) instance (WriterM m) => WriterM (ContT i m) where type Writes (ContT i m) = Writes m put x = lift (put x) -- | Classifies monads that propagate a state component. class (Monad m) => StateM m where -- | The type of the state. type State m -- | Get the state. get :: m (State m) -- | Set the state. set :: State m -> m () instance (Monad m) => StateM (StateT i m) where type State (StateT i m) = i get = S (\s -> return (s,s)) set s = S (\_ -> return ((),s)) instance (StateM m) => StateM (IdT m) where type State (IdT m) = State m get = lift get set s = lift (set s) instance (StateM m) => StateM (ReaderT i m) where type State (ReaderT i m) = State m get = lift get set s = lift (set s) instance (StateM m,Monoid i) => StateM (WriterT i m) where type State (WriterT i m) = State m get = lift get set s = lift (set s) instance (StateM m) => StateM (ExceptionT i m) where type State (ExceptionT i m) = State m get = lift get set s = lift (set s) instance (StateM m) => StateM (ChoiceT m) where type State (ChoiceT m) = State m get = lift get set s = lift (set s) instance (StateM m) => StateM (ContT i m) where type State (ContT i m) = State m get = lift get set s = lift (set s) -- | Classifies monads that support raising exceptions. class (Monad m) => ExceptionM m where -- | The type of the exceptions. type Exception m -- | Raise an exception. raise :: Exception m -> m a instance (Monad m) => ExceptionM (ExceptionT i m) where type Exception (ExceptionT i m) = i raise x = X (return (Left x)) instance (ExceptionM m) => ExceptionM (IdT m) where type Exception (IdT m) = Exception m raise x = lift (raise x) instance (ExceptionM m) => ExceptionM (ReaderT i m) where type Exception (ReaderT i m) = Exception m raise x = lift (raise x) instance (ExceptionM m,Monoid i) => ExceptionM (WriterT i m) where type Exception (WriterT i m) = Exception m raise x = lift (raise x) instance (ExceptionM m) => ExceptionM (StateT i m) where type Exception (StateT i m) = Exception m raise x = lift (raise x) instance (ExceptionM m) => ExceptionM (ChoiceT m) where type Exception (ChoiceT m) = Exception m raise x = lift (raise x) instance (ExceptionM m) => ExceptionM (ContT i m) where type Exception (ContT i m) = Exception m raise x = lift (raise x) -- The following instances differ from the others because the -- liftings are not as uniform (although they certainly follow a pattern). -- | Classifies monads that provide access to a computation's continuation. class Monad m => ContM m where -- | Capture the current continuation. callCC :: ((a -> m b) -> m a) -> m a instance (ContM m) => ContM (IdT m) where callCC f = IT $ callCC $ \k -> runIdT $ f $ \a -> lift $ k a instance (ContM m) => ContM (ReaderT i m) where callCC f = R $ \r -> callCC $ \k -> runReaderT r $ f $ \a -> lift $ k a instance (ContM m) => ContM (StateT i m) where callCC f = S $ \s -> callCC $ \k -> runStateT s $ f $ \a -> lift $ k (a,s) instance (ContM m,Monoid i) => ContM (WriterT i m) where callCC f = W $ callCC $ \k -> runWriterT $ f $ \a -> lift $ k (a,mempty) instance (ContM m) => ContM (ExceptionT i m) where callCC f = X $ callCC $ \k -> runExceptionT $ f $ \a -> lift $ k $ Right a instance (ContM m) => ContM (ChoiceT m) where callCC f = ChoiceEff $ callCC $ \k -> return $ f $ \a -> lift $ k $ Answer a -- ??? What does this do ??? instance (Monad m) => ContM (ContT i m) where callCC f = C $ \k -> runContT k $ f $ \a -> C $ \_ -> k a -- $Nested_Exec -- -- The following classes define operations that are overloaded -- versions of the @run@ operations. Unlike the @run@ operations, -- these functions do not change the type of the computation (i.e, they -- do not remove a layer). Instead, they perform the effects in -- a ``separate effect thread''. -- | Classifies monads that support changing the context for a -- sub-computation. class ReaderM m => RunReaderM m where -- | Change the context for the duration of a computation. local :: Reads m -> m a -> m a -- prop(?): local i (m1 >> m2) = local i m1 >> local i m2 instance (Monad m) => RunReaderM (ReaderT i m) where local i m = lift (runReaderT i m) instance (RunReaderM m) => RunReaderM (IdT m) where local i (IT m) = IT (local i m) instance (RunReaderM m,Monoid i) => RunReaderM (WriterT i m) where local i (W m) = W (local i m) instance (RunReaderM m) => RunReaderM (StateT i m)where local i (S m) = S (local i . m) instance (RunReaderM m) => RunReaderM (ExceptionT i m) where local i (X m) = X (local i m) -- | Classifies monads that support collecting the output of -- a sub-computation. class WriterM m => RunWriterM m where -- | Collect the output from a computation. collect :: m a -> m (a,Writes m) instance (Monad m, Monoid i) => RunWriterM (WriterT i m) where collect m = lift (runWriterT m) instance (RunWriterM m) => RunWriterM (IdT m) where collect (IT m) = IT (collect m) instance (RunWriterM m) => RunWriterM (ReaderT i m) where collect (R m) = R (collect . m) instance (RunWriterM m) => RunWriterM (StateT i m) where collect (S m) = S (liftM swap . collect . m) where swap (~(a,s),w) = ((a,w),s) instance (RunWriterM m) => RunWriterM (ExceptionT i m) where collect (X m) = X (liftM swap (collect m)) where swap (Right a,w) = Right (a,w) swap (Left x,_) = Left x -- NOTE: if an exception is risen while we are collecting, -- then we ignore the output. If the output is important, -- then use 'try' to ensure that no exception may occur. -- Example: do (r,w) <- collect (try m) -- case r of -- Left err -> ... do something ... -- Right a -> ... do something ... -- | Classifies monads that support handling of exceptions. class ExceptionM m => RunExceptionM m where -- | Exceptions are explicit in the result. try :: m a -> m (Either (Exception m) a) instance (Monad m) => RunExceptionM (ExceptionT i m) where try m = lift (runExceptionT m) instance (RunExceptionM m) => RunExceptionM (IdT m) where try (IT m) = IT (try m) instance (RunExceptionM m) => RunExceptionM (ReaderT j m) where try (R m) = R (try . m) instance (RunExceptionM m,Monoid j) => RunExceptionM (WriterT j m) where try (W m) = W (liftM swap (try m)) where swap (Right ~(a,w)) = (Right a,w) swap (Left e) = (Left e, mempty) instance (RunExceptionM m) => RunExceptionM (StateT j m) where try (S m) = S (\s -> liftM (swap s) (try (m s))) where swap _ (Right ~(a,s)) = (Right a,s) swap s (Left e) = (Left e, s) -------------------------------------------------------------------------------- -- Some convenient functions for working with continuations. -- | An explicit representation for continuations that store a value. newtype Label m a = Lab ((a, Label m a) -> m ()) -- | Capture the current continuation -- This function is like 'return', except that it also captures -- the current continuation. Later we can use 'jump' to go back to -- the continuation with a possibly different value. labelCC :: (ContM m) => a -> m (a, Label m a) labelCC x = callCC (\k -> return (x, Lab k)) -- | Change the value passed to a previously captured continuation. jump :: (ContM m) => a -> Label m a -> m b jump x (Lab k) = k (x, Lab k) >> return unreachable where unreachable = error "(bug) jump: unreachable" -------------------------------------------------------------------------------- -- | A isomorphism between (usually) monads. -- Typically the constructor and selector of a newtype delcaration. data Iso m n = Iso { close :: forall a. m a -> n a, open :: forall a. n a -> m a } -- | Derive the implementation of 'fmap' from 'Functor'. derive_fmap :: (Functor m) => Iso m n -> (a -> b) -> n a -> n b derive_fmap iso f m = close iso (fmap f (open iso m)) -- | Derive the implementation of 'return' from 'Monad'. derive_return :: (Monad m) => Iso m n -> (a -> n a) derive_return iso a = close iso (return a) -- | Derive the implementation of '>>=' from 'Monad'. derive_bind :: (Monad m) => Iso m n -> n a -> (a -> n b) -> n b derive_bind iso m k = close iso ((open iso m) >>= \x -> open iso (k x)) derive_fail :: (Monad m) => Iso m n -> String -> n a derive_fail iso a = close iso (fail a) -- | Derive the implementation of 'mfix' from 'MonadFix'. derive_mfix :: (MonadFix m) => Iso m n -> (a -> n a) -> n a derive_mfix iso f = close iso (mfix (open iso . f)) -- | Derive the implementation of 'ask' from 'ReaderM'. derive_ask :: (ReaderM m) => Iso m n -> n (Reads m) derive_ask iso = close iso ask -- | Derive the implementation of 'put' from 'WriterM'. derive_put :: (WriterM m) => Iso m n -> Writes m -> n () derive_put iso x = close iso (put x) -- | Derive the implementation of 'get' from 'StateM'. derive_get :: (StateM m) => Iso m n -> n (State m) derive_get iso = close iso get -- | Derive the implementation of 'set' from 'StateM'. derive_set :: (StateM m) => Iso m n -> State m -> n () derive_set iso x = close iso (set x) -- | Derive the implementation of 'raise' from 'ExceptionM'. derive_raise :: (ExceptionM m) => Iso m n -> Exception m -> n a derive_raise iso x = close iso (raise x) -- | Derive the implementation of 'callCC' from 'ContM'. derive_callCC :: (ContM m) => Iso m n -> ((a -> n b) -> n a) -> n a derive_callCC iso f = close iso (callCC (open iso . f . (close iso .))) -- | Derive the implementation of 'local' from 'RunReaderM'. derive_local :: (RunReaderM m) => Iso m n -> Reads m -> n a -> n a derive_local iso i = close iso . local i . open iso -- | Derive the implementation of 'collect' from 'RunWriterM'. derive_collect :: (RunWriterM m) => Iso m n -> n a -> n (a,Writes m) derive_collect iso = close iso . collect . open iso -- | Derive the implementation of 'try' from 'RunExceptionM'. derive_try :: (RunExceptionM m) => Iso m n -> n a -> n (Either (Exception m) a) derive_try iso = close iso . try . open iso derive_mzero :: (MonadPlus m) => Iso m n -> n a derive_mzero iso = close iso mzero derive_mplus :: (MonadPlus m) => Iso m n -> n a -> n a -> n a derive_mplus iso n1 n2 = close iso (mplus (open iso n1) (open iso n2)) derive_lift :: (MonadT t, Monad m) => Iso (t m) n -> m a -> n a derive_lift iso m = close iso (lift m) derive_inBase :: (HasBase m) => Iso m n -> BaseM m a -> n a derive_inBase iso m = close iso (inBase m)
yav/monadlib
experimental/MonadLibTF.hs
Haskell
mit
24,318
module Main ( main ) where {- Automatic solver for Android game "tents & trees" -} {- Design: for now I think the most difficult part will be, given an image, to recognize board position and extract board configuration from it. good old matchTemplate should work, but here I want to see if there are better ways that is not sensitive to scaling so that a method works for 10x10 board will also work for 20x20 board. Questions: - how to extract and recognize trees and empty spaces? For simplicity, let's only work on a clean board (that is, no empty or tent marked). This is currently done based on the fact that all empty cells use the exact same color, so the region can be extracted with OpenCV's inRange function, after which we can floodFill to find boundaries of empty cells can use that to derive row and col coordinates of the board. Board's position (or we should say each cell's position) is straightforward to figure out after we derive bounding low/high for each cell's row and col. a reasonable (but not safe) assumption that we use here is that: + there will always be some empty spaces on board for each row and col. + every boundary will have at least one empty cell. - how to extract and recognize digits on board sides? This is now done by guessing: given first two cells of a row or column, we extend cell boundary in the other direction - as it turns out that all digits happen to be placed in that region. (TODO) Quick notes: - there are two different colors for digits: + one color is consistently used for unsatisfied digits + another color is consistently used for satisfied digits, and satistifed digits are trickier to recognoze as there's an extra check mark character that we want to exclude. - for unsatisfied digits, the plan is simple: run through inRange by filtering on just that unsatisfied color, the we can find boundary of it and extract those as samples - for satisfied digits, well since that row / col is already satisfied, we can derive what that number is from the board itself. The board parsing function might need some modification, but I believe we can entirely ignore the problem of recognizing digits from picture. -} main :: IO () main = pure ()
Javran/misc
auto-tents/src/Main.hs
Haskell
mit
2,344
module Part2 where import Control.Monad data Item = Item { name :: String, description :: String, weight :: Int, value :: Int } | Weapon { name :: String, description :: String, weight :: Int, value :: Int, damage :: Int } | Armor { name :: String, description :: String, weight :: Int, value :: Int, defense :: Int } | Potion { name :: String, description :: String, weight :: Int, value :: Int, potionType :: PotionType, capacity :: Int } deriving ( Show ) data PotionType = HP | MP instance Show PotionType where show HP = "Health" show MP = "Mana" data Shop = Shop { shopName :: String, shopItems :: Items } type Items = [Item] main :: IO () main = do printMenu input <- getLine play $ read input Control.Monad.unless (read input == 3) main printMenu :: IO () printMenu = do putStrLn "- Shop Select -" putStrLn " 1. Weapon/Armor Shop" putStrLn " 2. Potion Shop" putStrLn " 3. Exit\n" putStr "Select : " return () play :: Int -> IO () play n | n == 1 = showItemList weaponAndArmorShop | n == 2 = showItemList potionShop | n == 3 = return () | otherwise = putStrLn "\nInvalid number! Try again.\n" testCase1 = describe items describe :: Items -> IO () describe = mapM_ (putStrLn . toString) toString :: Item -> String toString (Item name description weight value) = baseInfo (Item name description weight value) toString (Weapon name description weight value damage) = baseInfo (Item name description weight value) ++ "Damage = " ++ show damage ++ "\n" toString (Armor name description weight value defense) = baseInfo (Item name description weight value) ++ "Defense = " ++ show defense ++ "\n" toString (Potion name description weight value potionType capacity) = baseInfo (Item name description weight value) ++ "Type = " ++ show potionType ++ "\n" ++ "Capacity = " ++ show capacity ++ "\n" baseInfo :: Item -> String baseInfo item = "Name = " ++ name item ++ "\n" ++ "Description = " ++ description item ++ "\n" ++ "Weight = " ++ w'' ++ "\n" ++ "value = " ++ v'' ++ "\n" where w = weight item v = value item w' = show w v' = show v w'' | w > 1 = w' ++ " lbs" | otherwise = w' ++ " lb" v'' | v > 1 = v' ++ " gold coins" | otherwise = v' ++ " gold coin" showItemList :: Shop -> IO () showItemList shop = do putStrLn $ "Welcom to " ++ shopName shop ++ "!\n" describe $ shopItems shop putStrLn "\n" items = [ Weapon { name = "Excalibur", description = "The legendary sword of King Arthur", weight = 12, value = 1024, damage = 24 }, Armor { name = "Steel Armor", description = "Protective covering made by steel", weight = 15, value = 805, defense = 18} ] weaponAndArmorShop = Shop { shopName = "Weapon/Armor", shopItems = [ Weapon { name = "Sword", description = "Medium DMG", weight = 3, value = 10, damage = 10 }, Armor { name = "Cap", description = "Light Armor", weight = 1, value = 5, defense = 5 }, Armor { name = "Gloves", description = "Light Armor", weight = 1, value = 5, defense = 5 }, Weapon { name = "Axe", description = "High Dmg", weight = 5, value = 15, damage = 15 }, Armor { name = "Boots", description = "Light Armor", weight = 1, value = 5, defense = 5 } ] } potionShop = Shop { shopName = "Potion", shopItems = [ Potion { name = "Small Health Potion", description = "Recovery 100 HP", weight = 2, value = 5, potionType = HP, capacity = 100 }, Potion { name = "Small Mana Potion", description = "Recovery 50 MP", weight = 1, value = 30, potionType = MP, capacity = 50 }, Potion { name = "Medium Health Potion", description = "Recovery 200 HP", weight = 4, value = 120, potionType = HP, capacity = 200 }, Potion { name = "Medium Mana Potion", description = "Recovery 100 MP", weight = 2, value = 75, potionType = MP, capacity = 100 }, Potion { name = "Large Health Potion", description = "Recovery 300 HP", weight = 6, value = 200, potionType = HP, capacity = 300 } ] }
utilForever/ProgrammingPractice
Solutions/MoNaDDu/Game Shop/3/Part3.hs
Haskell
mit
4,510
module NeatInterpolation.String where import NeatInterpolation.Prelude unindent :: [Char] -> [Char] unindent s = case lines s of head : tail -> let unindentedHead = dropWhile (== ' ') head minimumTailIndent = minimumIndent . unlines $ tail unindentedTail = case minimumTailIndent of Just indent -> map (drop indent) tail Nothing -> tail in unlines $ unindentedHead : unindentedTail [] -> [] trim :: [Char] -> [Char] trim = dropWhileRev isSpace . dropWhile isSpace dropWhileRev :: (a -> Bool) -> [a] -> [a] dropWhileRev p = foldr (\x xs -> if p x && null xs then [] else x:xs) [] tabsToSpaces :: [Char] -> [Char] tabsToSpaces ('\t' : tail) = " " ++ tabsToSpaces tail tabsToSpaces (head : tail) = head : tabsToSpaces tail tabsToSpaces [] = [] minimumIndent :: [Char] -> Maybe Int minimumIndent = listToMaybe . sort . map lineIndent . filter (not . null . dropWhile isSpace) . lines -- | Amount of preceding spaces on first line lineIndent :: [Char] -> Int lineIndent = length . takeWhile (== ' ')
nikita-volkov/neat-interpolation
library/NeatInterpolation/String.hs
Haskell
mit
1,083
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.NavigatorUserMediaError (js_getConstraintName, getConstraintName, NavigatorUserMediaError, castToNavigatorUserMediaError, gTypeNavigatorUserMediaError) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"constraintName\"]" js_getConstraintName :: NavigatorUserMediaError -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUserMediaError.constraintName Mozilla NavigatorUserMediaError.constraintName documentation> getConstraintName :: (MonadIO m, FromJSString result) => NavigatorUserMediaError -> m result getConstraintName self = liftIO (fromJSString <$> (js_getConstraintName (self)))
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/NavigatorUserMediaError.hs
Haskell
mit
1,537
{-# LANGUAGE OverloadedStrings, FlexibleContexts, ScopedTypeVariables #-} module ProcessStatus ( processStatuses , RetryAPI(..) ) where import Data.Conduit import Data.Conduit.Binary import qualified Data.Conduit.Attoparsec as CA import Network.HTTP.Conduit import qualified Web.Authenticate.OAuth as OA import Data.Aeson import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString as B import Data.List import qualified Data.Vector as V import Control.Monad.IO.Class import Control.Monad.State.Strict import Control.Monad.Trans.Resource import Control.Concurrent.STM import Control.Exception import Control.Concurrent hiding (yield) import Text.Printf import Text.Read (readMaybe) import System.IO import TwitterJSON import Trace -- Pick up Twitter status updates and related messages from a file or an HTTP connection -- and return the results as data structures from TwitterJSON -- Put status messages in a TBQueue (TODO: Maybe use stm-conduit package?) smQueueSink :: (MonadIO m, MonadResource m) => TBQueue StreamMessage -> Sink StreamMessage m () smQueueSink smQueue = awaitForever $ liftIO . atomically . writeTBQueue smQueue -- Count bytes passing through using the state (need to be careful that we don't -- retain a reference to the ByteString in case we're not looking at the state -- for a while) -- -- TODO: We take the byte count after gzip decompression, so not really what goes -- over the socket countBytesState :: (MonadIO m, MonadState Int m) => Conduit B.ByteString m B.ByteString countBytesState = awaitForever $ \mi -> do modify' (\x -> B.length mi `seq` x + fromIntegral (B.length mi)) yield mi parseStatus :: (MonadIO m, MonadState Int m, MonadResource m) => Conduit B.ByteString m StreamMessage parseStatus = do -- Bandwidth message for statistics yield <$> SMBytesReceived =<< get put 0 -- Use conduit adapter for attoparsec to read the next JSON -- object with the Aeson parser from the stream connection -- -- TODO: The performance we get is quite far away from the figures listed on -- Aeson's cabal site, do some benchmarking and profiling -- j <- CA.sinkParser json' -- The stream connections send individual objects we can decode into SMs, -- but the home timeline sends an array of such objects let msg = case j of Array v -> V.toList v x -> [x] forM_ msg $ \m -> do -- We expect something that can be parsed into a StreamMessage let sm = fromJSON m :: Result StreamMessage yield $ case sm of Success r -> r Error s -> SMParseError $ B8.pack s parseStatus -- Like conduitFile from Conduit.Binary, but with extra options to control the write -- mode and flushing conduitFileWithOptions :: MonadResource m => FilePath -> IOMode -> Bool -> Conduit B.ByteString m B.ByteString conduitFileWithOptions fp mode flush = bracketP (openBinaryFile fp mode) hClose go where go h = awaitForever $ \bs -> liftIO (B.hPut h bs >> when flush (hFlush h)) >> yield bs data RetryAPI = RetryNever | RetryNTimes Int | RetryForever -- This even retries in case of success deriving (Eq) -- Process status updates as returned from the REST or Stream API, write results into a queue processStatuses :: String -> OA.OAuth -> OA.Credential -> Manager -> Maybe FilePath -> Bool -> TBQueue StreamMessage -> RetryAPI -> IO () processStatuses uri oaClient oaCredential manager logFn appendLog smQueue retryAPI = do let uriIsHTTP = isPrefixOf "http://" uri || isPrefixOf "https://" uri -- File or HTTP? success <- catches ( -- We use State to keep track of how many bytes we received runResourceT . flip evalStateT (0 :: Int) $ let sink' = countBytesState =$ parseStatus =$ smQueueSink smQueue sink = case logFn of Just fn -> conduitFileWithOptions fn (if appendLog then AppendMode else WriteMode) True =$ sink' Nothing -> sink' in if uriIsHTTP then do -- Authenticate, connect and start receiving stream req' <- liftIO $ parseUrl uri let req = req' { requestHeaders = ("Accept-Encoding", "deflate, gzip") -- Need a User-Agent field as well to get a -- gzip'ed stream from Twitter : ("User-Agent", "jacky/http-conduit") : requestHeaders req' } reqSigned <- OA.signOAuth oaClient oaCredential req liftIO . traceS TLInfo $ "Twitter API request:\n" ++ show reqSigned res <- http reqSigned manager liftIO . traceS TLInfo $ "Twitter API response from '" ++ uri ++ "'\n" ++ case logFn of Just fn -> "Saving full log in '" ++ fn ++ "'\n" Nothing -> "" ++ "Status: " ++ show (responseStatus res) ++ "\n" ++ "Header: " ++ show (responseHeaders res) -- Are we approaching the rate limit? case find ((== "x-rate-limit-remaining") . fst) (responseHeaders res) >>= readMaybe . B8.unpack . snd :: Maybe Int of Just n -> when (n < 5) . liftIO . traceS TLWarn $ printf "Rate limit remaining for API '%s' at %i" uri n Nothing -> return () -- Finish parsing conduit responseBody res $$+- sink return True else do liftIO . traceS TLInfo $ "Streaming Twitter API response from file: " ++ uri sourceFile uri $$ sink return True ) [ Handler $ \(ex :: AsyncException) -> case ex of ThreadKilled -> do traceS TLInfo $ "Recv. ThreadKilled while processing statuses from '" ++ uri ++ "', exiting\n" ++ show ex void $ throwIO ex -- Clean exit, but re-throw so we're not trapped -- inside RetryForever return True _ -> do traceS TLError $ "Async exception while processing statuses from '" ++ uri ++ "\n" ++ show ex return False , Handler $ \(ex :: HttpException) -> do traceS TLError $ "HTTP / connection error while processing statuses from '" ++ uri ++ "'\n" ++ show ex return False , Handler $ \(ex :: CA.ParseError) -> if "demandInput" `elem` CA.errorContexts ex then do traceS TLInfo $ "End-of-Data for '" ++ uri ++ "'\n" ++ show ex return True -- This error is a clean exit else do traceS TLError $ "JSON parser error while processing statuses from '" ++ uri ++ "'\n" ++ show ex return False , Handler $ \(ex :: IOException) -> do traceS TLError $ "IO error while processing statuses from '" ++ uri ++ "'\n" ++ show ex return False -- TODO: This exception is likely caused by a failure to read -- a network dump from disk, we might not want to bother -- trying again if it can't be opened ] -- Do we need to retry? case retryAPI of RetryForever -> when uriIsHTTP $ do -- Don't retry forever if our source is a static file traceS TLWarn $ retryMsg ++ " (forever)\nURI: " ++ uri threadDelay retryDelay retryThis RetryForever RetryNTimes n -> when (not success && n > 0) $ do traceS TLWarn $ retryMsg ++ "\n" ++ "Remaining retries: " ++ show n ++ "\n" ++ "URI: " ++ uri threadDelay retryDelay retryThis (RetryNTimes $ n - 1) RetryNever -> return () where retryThis = processStatuses uri oaClient oaCredential manager logFn True -- Don't overwrite log data we've got so far smQueue retryDelay = 5 * 1000 * 1000 -- 5 seconds (TODO: Make this configurable) retryMsg = printf "Retrying API request in %isec" (retryDelay `div` 1000 `div` 1000)
blitzcode/jacky
src/ProcessStatus.hs
Haskell
mit
10,047
{-# htermination concat :: [[a]] -> [a] #-}
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Prelude_concat_1.hs
Haskell
mit
44
{-# LANGUAGE OverloadedStrings #-} module Ledger ( accountMap , findParents , transactionLine ) where import Data.Maybe import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Builder as TLB -- Lazy debugging import Debug.Trace import Types -- -- Helper functions -- inspectId :: Account -> T.Text inspectId a = if (idType $ aGuid a) /= (T.pack "guid") then trace ("Account IdType not guid! - " ++ (T.unpack $ aName a)) (idValue $ aGuid a) else (idValue $ aGuid a) inspectParentId :: Account -> Maybe T.Text inspectParentId a = case (aParent a) of Nothing -> Nothing Just p -> Just $ if (idType p) /= (T.pack "guid") then trace ("Account IdType not guid! - " ++ (T.unpack $ aName a)) (idValue p) else (idValue p) inspectAccountId :: Split -> T.Text inspectAccountId s = if (idType $ spAccountId s) /= (T.pack "guid") then trace ("Account IdType not guid! - " ++ (show $ sMemo s)) (idValue $ spAccountId s) else (idValue $ spAccountId s) -- -- * Map of Account Id -> Account (parent/account lookup) -- -- Text is idValue out of TypedId accountMap :: [Account] -> Map T.Text Account accountMap accounts = foldl foldAccount Map.empty accounts where foldAccount :: Map T.Text Account -> Account -> Map T.Text Account foldAccount m a = Map.insert (inspectId a) a m -- List is ordered from parent to child, does it include the given Account? -- * Code to find all parent of an account -- * For now it does not findParents :: Account -> Map T.Text Account -> [Account] findParents account am = case (inspectParentId account) of Nothing -> [] Just pid -> case (Map.lookup pid am) of Nothing -> trace ("Account parent not found in map! - " ++ (T.unpack $ aName account)) [] Just pa -> pa : findParents pa am -- -- Transaction process -- transactionLine :: Transaction -> Map T.Text Account -> IO () transactionLine t am = do putStr "Description: " print $ tDescription t putStr "\tCurrency: " print $ tCurrency t putStr "\tPosted: " print $ tPosted t putStr "\tEntered: " print $ tEntered t putStrLn "\tAccount Splits:" mapM_ (\s -> do putStr "\t\tMemo: " print $ sMemo s putStr "\t\tAction: " print $ sAction s putStr "\t\tspReconciledState: " print $ spReconciledState s putStr "\t\tValue: " print $ spValue s putStr "\t\tQuanity: " print $ spQuantity s let accountId = inspectAccountId s let account = Map.lookup accountId am let account' = fromJust account let parents = findParents account' am putStr "\t\tAccounts:" putStrLn $ show $ reverse $ map (T.unpack . aName) (account' : parents) ) (tSplits t) --data Transaction = Transaction -- { tVersion :: Text -- TODO: ADT this -- , tGuid :: TypedId PTTransaction -- , tCurrency :: (TypedId PTSpace) -- , tNum :: Maybe (Maybe Integer) -- No idea what this is -- , tPosted :: Date -- , tEntered :: Date -- , tDescription :: Text -- , tSlots :: Maybe (TypedSlots STransaction) -- , tSplits :: [Split] -- } deriving (Show, Eq) -- --data Split = Split -- { spId :: TypedId PTSplit -- , sAction :: Maybe Text -- , sMemo :: Maybe Text -- , spReconciledState :: Text -- , spReconciledDate :: Maybe Date -- , spValue :: Text -- TODO: convert to rational -- , spQuantity :: Text -- TODO: convert to rational -- , spAccountId :: TypedId PTSplitAccount -- , spSlots :: Maybe (TypedSlots SSplit) -- } deriving (Show, Eq) -- ---- Core Type (Cannot access constructors for this) --data TypedId t = TypedId -- { idType :: Text -- , idValue :: Text -- TODO: ADT this value/type -- } deriving (Show, Eq) -- -- --data Commodity = Commodity -- { cVersion :: Text -- TODO: ADT this -- , cSId :: TypedId PTSpace -- , cName :: Maybe Text -- , cXCode :: Maybe Text -- , cFraction :: Maybe Integer -- , cQuote :: Maybe () -- , cSource :: Maybe Text -- , cTz :: Maybe () -- } deriving (Show, Eq) -- --data PriceDb = PriceDb -- { pVersion :: Text -- TODO: ADT this -- , prices :: [Price] -- } deriving (Show, Eq) -- --data Price = Price -- { pGuid :: TypedId PTPrice -- , commoditySId :: TypedId PTSpace -- , currencySId :: TypedId PTSpace -- , pTime :: Date -- , pSource :: Text -- , pType :: Maybe Text -- , pValue :: Text -- TODO: convert to rational -- } deriving (Show, Eq) -- ---- TODO: make this handle <gdata> as well --data Date = Date -- { date :: Text -- TODO: proper type/parsing -- , ns :: Maybe Text -- TODO: proper type/parsing (no idea what a ns is) -- } deriving (Show, Eq)
pharaun/hGnucash
src/Ledger.hs
Haskell
apache-2.0
4,991
module GTKMain (main) where import Debug import BattleContext import GTKInitialization (initUI, buildUI, setupUI, startUI) import Data.IORef import Control.Monad.Trans.Reader (runReaderT) dataDir = "/usr/home/nbrk/projects/haskell/ld/executable" main :: IO () main = do putInfo "Starting GTK application" putInfo $ "Data dir: " ++ dataDir bc <- newFromScenario testScenario initUI gtkctx <- buildUI bc dataDir runReaderT setupUI gtkctx runReaderT startUI gtkctx putInfo "Exiting GTK application"
nbrk/ld
executable/GTKMain.hs
Haskell
bsd-2-clause
522
{-# LANGUAGE Haskell2010 #-} -- | Math (display) for 'normalDensity' -- -- \[ -- \int_{-\infty}^{\infty} e^{-x^2/2} = \sqrt{2\pi} -- \] -- -- \(\int_{-\infty}^{\infty} e^{-x^2/2} = \sqrt{2\pi}\) module Math where -- | Math (inline) for 'normalDensity' -- \(\int_{-\infty}^{\infty} e^{-x^2/2} = \sqrt{2\pi}\) -- \[\int_{-\infty}^{\infty} e^{-x^2/2} = \sqrt{2\pi}\] f = 5
haskell/haddock
html-test/src/Math.hs
Haskell
bsd-2-clause
372
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE CPP #-} #if __GLASGOW_HASKELL__ >= 800 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif {-# OPTIONS_GHC -fno-warn-dodgy-exports #-} module Text.RE.PCRE ( -- * Tutorial -- $tutorial -- * The Overloaded Match Operators (*=~) , (?=~) , (=~) , (=~~) -- * The Toolkit -- $toolkit , module Text.RE -- * The 'RE' Type -- $re , module Text.RE.PCRE.RE -- * The Operator Instances -- $instances , module Text.RE.PCRE.ByteString , module Text.RE.PCRE.ByteString.Lazy , module Text.RE.PCRE.Sequence , module Text.RE.PCRE.String ) where import qualified Text.Regex.Base as B import Text.RE import Text.RE.Internal.AddCaptureNames import Text.RE.PCRE.RE import qualified Text.Regex.PCRE as PCRE import Text.RE.PCRE.ByteString() import Text.RE.PCRE.ByteString.Lazy() import Text.RE.PCRE.Sequence() import Text.RE.PCRE.String() -- | find all matches in text (*=~) :: IsRegex RE s => s -> RE -> Matches s (*=~) bs rex = addCaptureNamesToMatches (reCaptureNames rex) $ matchMany rex bs -- | find first match in text (?=~) :: IsRegex RE s => s -> RE -> Match s (?=~) bs rex = addCaptureNamesToMatch (reCaptureNames rex) $ matchOnce rex bs -- | the regex-base polymorphic match operator (=~) :: ( B.RegexContext PCRE.Regex s a , B.RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption s ) => s -> RE -> a (=~) bs rex = B.match (reRegex rex) bs -- | the regex-base monadic, polymorphic match operator (=~~) :: ( Monad m , B.RegexContext PCRE.Regex s a , B.RegexMaker PCRE.Regex PCRE.CompOption PCRE.ExecOption s ) => s -> RE -> m a (=~~) bs rex = B.matchM (reRegex rex) bs -- $tutorial -- We have a regex tutorial at <http://tutorial.regex.uk>. These API -- docs are mainly for reference. -- $toolkit -- -- Beyond the above match operators and the regular expression type -- below, "Text.RE" contains the toolkit for replacing captures, -- specifying options, etc. -- $re -- -- "Text.RE.TDFA.RE" contains the toolkit specific to the 'RE' type, -- the type generated by the gegex compiler. -- $instances -- -- These modules merely provide the instances for the above regex -- match operators at the various text types.
cdornan/idiot
Text/RE/PCRE.hs
Haskell
bsd-3-clause
2,481
{-| Module : Idris.IdeMode Description : Idris' IDE Mode Copyright : License : BSD3 Maintainer : The Idris Community. -} {-# OPTIONS_GHC -fwarn-incomplete-patterns #-} {-# LANGUAGE FlexibleInstances, IncoherentInstances, PatternGuards #-} module Idris.IdeMode(parseMessage, convSExp, WhatDocs(..), IdeModeCommand(..), sexpToCommand, toSExp, SExp(..), SExpable, Opt(..), ideModeEpoch, getLen, getNChar, sExpToString) where import Idris.Core.Binary () import Idris.Core.TT import Control.Applicative hiding (Const) import qualified Data.Binary as Binary import qualified Data.ByteString.Base64 as Base64 import qualified Data.ByteString.Lazy as Lazy import qualified Data.ByteString.UTF8 as UTF8 import Data.List import Data.Maybe (isJust) import qualified Data.Text as T import Numeric import System.IO import Text.Printf import Text.Trifecta hiding (Err) import Text.Trifecta.Delta getNChar :: Handle -> Int -> String -> IO (String) getNChar _ 0 s = return (reverse s) getNChar h n s = do c <- hGetChar h getNChar h (n - 1) (c : s) getLen :: Handle -> IO (Either Err Int) getLen h = do s <- getNChar h 6 "" case readHex s of ((num, ""):_) -> return $ Right num _ -> return $ Left . Msg $ "Couldn't read length " ++ s data SExp = SexpList [SExp] | StringAtom String | BoolAtom Bool | IntegerAtom Integer | SymbolAtom String deriving ( Eq, Show ) sExpToString :: SExp -> String sExpToString (StringAtom s) = "\"" ++ escape s ++ "\"" sExpToString (BoolAtom True) = ":True" sExpToString (BoolAtom False) = ":False" sExpToString (IntegerAtom i) = printf "%d" i sExpToString (SymbolAtom s) = ":" ++ s sExpToString (SexpList l) = "(" ++ intercalate " " (map sExpToString l) ++ ")" class SExpable a where toSExp :: a -> SExp instance SExpable SExp where toSExp a = a instance SExpable Bool where toSExp True = BoolAtom True toSExp False = BoolAtom False instance SExpable String where toSExp s = StringAtom s instance SExpable Integer where toSExp n = IntegerAtom n instance SExpable Int where toSExp n = IntegerAtom (toInteger n) instance SExpable Name where toSExp s = StringAtom (show s) instance (SExpable a) => SExpable (Maybe a) where toSExp Nothing = SexpList [SymbolAtom "Nothing"] toSExp (Just a) = SexpList [SymbolAtom "Just", toSExp a] instance (SExpable a) => SExpable [a] where toSExp l = SexpList (map toSExp l) instance (SExpable a, SExpable b) => SExpable (a, b) where toSExp (l, r) = SexpList [toSExp l, toSExp r] instance (SExpable a, SExpable b, SExpable c) => SExpable (a, b, c) where toSExp (l, m, n) = SexpList [toSExp l, toSExp m, toSExp n] instance (SExpable a, SExpable b, SExpable c, SExpable d) => SExpable (a, b, c, d) where toSExp (l, m, n, o) = SexpList [toSExp l, toSExp m, toSExp n, toSExp o] instance (SExpable a, SExpable b, SExpable c, SExpable d, SExpable e) => SExpable (a, b, c, d, e) where toSExp (l, m, n, o, p) = SexpList [toSExp l, toSExp m, toSExp n, toSExp o, toSExp p] instance SExpable NameOutput where toSExp TypeOutput = SymbolAtom "type" toSExp FunOutput = SymbolAtom "function" toSExp DataOutput = SymbolAtom "data" toSExp MetavarOutput = SymbolAtom "metavar" toSExp PostulateOutput = SymbolAtom "postulate" maybeProps :: SExpable a => [(String, Maybe a)] -> [(SExp, SExp)] maybeProps [] = [] maybeProps ((n, Just p):ps) = (SymbolAtom n, toSExp p) : maybeProps ps maybeProps ((n, Nothing):ps) = maybeProps ps constTy :: Const -> String constTy (I _) = "Int" constTy (BI _) = "Integer" constTy (Fl _) = "Double" constTy (Ch _) = "Char" constTy (Str _) = "String" constTy (B8 _) = "Bits8" constTy (B16 _) = "Bits16" constTy (B32 _) = "Bits32" constTy (B64 _) = "Bits64" constTy _ = "Type" namespaceOf :: Name -> Maybe String namespaceOf (NS _ ns) = Just (intercalate "." $ reverse (map T.unpack ns)) namespaceOf _ = Nothing instance SExpable OutputAnnotation where toSExp (AnnName n ty d t) = toSExp $ [(SymbolAtom "name", StringAtom (show n)), (SymbolAtom "implicit", BoolAtom False), (SymbolAtom "key", StringAtom (encodeName n))] ++ maybeProps [("decor", ty)] ++ maybeProps [("doc-overview", d), ("type", t)] ++ maybeProps [("namespace", namespaceOf n)] toSExp (AnnBoundName n imp) = toSExp [(SymbolAtom "name", StringAtom (show n)), (SymbolAtom "decor", SymbolAtom "bound"), (SymbolAtom "implicit", BoolAtom imp)] toSExp (AnnConst c) = toSExp [(SymbolAtom "decor", SymbolAtom (if constIsType c then "type" else "data")), (SymbolAtom "type", StringAtom (constTy c)), (SymbolAtom "doc-overview", StringAtom (constDocs c)), (SymbolAtom "name", StringAtom (show c))] toSExp (AnnData ty doc) = toSExp [(SymbolAtom "decor", SymbolAtom "data"), (SymbolAtom "type", StringAtom ty), (SymbolAtom "doc-overview", StringAtom doc)] toSExp (AnnType name doc) = toSExp $ [(SymbolAtom "decor", SymbolAtom "type"), (SymbolAtom "type", StringAtom "Type"), (SymbolAtom "doc-overview", StringAtom doc)] ++ if not (null name) then [(SymbolAtom "name", StringAtom name)] else [] toSExp AnnKeyword = toSExp [(SymbolAtom "decor", SymbolAtom "keyword")] toSExp (AnnFC fc) = toSExp [(SymbolAtom "source-loc", toSExp fc)] toSExp (AnnTextFmt fmt) = toSExp [(SymbolAtom "text-formatting", SymbolAtom format)] where format = case fmt of BoldText -> "bold" ItalicText -> "italic" UnderlineText -> "underline" toSExp (AnnLink url) = toSExp [(SymbolAtom "link-href", StringAtom url)] toSExp (AnnTerm bnd tm) | termSmallerThan 1000 tm = toSExp [(SymbolAtom "tt-term", StringAtom (encodeTerm bnd tm))] | otherwise = SexpList [] toSExp (AnnSearchResult ordr) = toSExp [(SymbolAtom "doc-overview", StringAtom ("Result type is " ++ descr))] where descr = case ordr of EQ -> "isomorphic" LT -> "more general than searched type" GT -> "more specific than searched type" toSExp (AnnErr e) = toSExp [(SymbolAtom "error", StringAtom (encodeErr e))] toSExp (AnnNamespace ns file) = toSExp $ [(SymbolAtom "namespace", StringAtom (intercalate "." (map T.unpack ns)))] ++ [(SymbolAtom "decor", SymbolAtom $ if isJust file then "module" else "namespace")] ++ maybeProps [("source-file", file)] toSExp AnnQuasiquote = toSExp [(SymbolAtom "quasiquotation", True)] toSExp AnnAntiquote = toSExp [(SymbolAtom "antiquotation", True)] encodeName :: Name -> String encodeName n = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ n encodeTerm :: [(Name, Bool)] -> Term -> String encodeTerm bnd tm = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ (bnd, tm) decodeTerm :: String -> ([(Name, Bool)], Term) decodeTerm = Binary.decode . Lazy.fromStrict . Base64.decodeLenient . UTF8.fromString encodeErr :: Err -> String encodeErr e = UTF8.toString . Base64.encode . Lazy.toStrict . Binary.encode $ e decodeErr :: String -> Err decodeErr = Binary.decode . Lazy.fromStrict . Base64.decodeLenient . UTF8.fromString instance SExpable FC where toSExp (FC f (sl, sc) (el, ec)) = toSExp ((SymbolAtom "filename", StringAtom f), (SymbolAtom "start", IntegerAtom (toInteger sl), IntegerAtom (toInteger sc)), (SymbolAtom "end", IntegerAtom (toInteger el), IntegerAtom (toInteger ec))) toSExp NoFC = toSExp ([] :: [String]) toSExp (FileFC f) = toSExp [(SymbolAtom "filename", StringAtom f)] escape :: String -> String escape = concatMap escapeChar where escapeChar '\\' = "\\\\" escapeChar '"' = "\\\"" escapeChar c = [c] pSExp = do xs <- between (char '(') (char ')') (pSExp `sepBy` (char ' ')) return (SexpList xs) <|> atom atom = do string "nil"; return (SexpList []) <|> do char ':'; x <- atomC; return x <|> do char '"'; xs <- many quotedChar; char '"'; return (StringAtom xs) <|> do ints <- some digit case readDec ints of ((num, ""):_) -> return (IntegerAtom (toInteger num)) _ -> return (StringAtom ints) atomC = do string "True"; return (BoolAtom True) <|> do string "False"; return (BoolAtom False) <|> do xs <- many (noneOf " \n\t\r\"()"); return (SymbolAtom xs) quotedChar = try (string "\\\\" >> return '\\') <|> try (string "\\\"" >> return '"') <|> noneOf "\"" parseSExp :: String -> Result SExp parseSExp = parseString pSExp (Directed (UTF8.fromString "(unknown)") 0 0 0 0) data Opt = ShowImpl | ErrContext deriving Show data WhatDocs = Overview | Full data IdeModeCommand = REPLCompletions String | Interpret String | TypeOf String | CaseSplit Int String | AddClause Int String | AddProofClause Int String | AddMissing Int String | MakeWithBlock Int String | MakeCaseBlock Int String | ProofSearch Bool Int String [String] (Maybe Int) -- ^^ Recursive?, line, name, hints, depth | MakeLemma Int String | LoadFile String (Maybe Int) | DocsFor String WhatDocs | Apropos String | GetOpts | SetOpt Opt Bool | Metavariables Int -- ^^ the Int is the column count for pretty-printing | WhoCalls String | CallsWho String | BrowseNS String | TermNormalise [(Name, Bool)] Term | TermShowImplicits [(Name, Bool)] Term | TermNoImplicits [(Name, Bool)] Term | TermElab [(Name, Bool)] Term | PrintDef String | ErrString Err | ErrPPrint Err | GetIdrisVersion sexpToCommand :: SExp -> Maybe IdeModeCommand sexpToCommand (SexpList ([x])) = sexpToCommand x sexpToCommand (SexpList [SymbolAtom "interpret", StringAtom cmd]) = Just (Interpret cmd) sexpToCommand (SexpList [SymbolAtom "repl-completions", StringAtom prefix]) = Just (REPLCompletions prefix) sexpToCommand (SexpList [SymbolAtom "load-file", StringAtom filename, IntegerAtom line]) = Just (LoadFile filename (Just (fromInteger line))) sexpToCommand (SexpList [SymbolAtom "load-file", StringAtom filename]) = Just (LoadFile filename Nothing) sexpToCommand (SexpList [SymbolAtom "type-of", StringAtom name]) = Just (TypeOf name) sexpToCommand (SexpList [SymbolAtom "case-split", IntegerAtom line, StringAtom name]) = Just (CaseSplit (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "add-clause", IntegerAtom line, StringAtom name]) = Just (AddClause (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "add-proof-clause", IntegerAtom line, StringAtom name]) = Just (AddProofClause (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "add-missing", IntegerAtom line, StringAtom name]) = Just (AddMissing (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "make-with", IntegerAtom line, StringAtom name]) = Just (MakeWithBlock (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "make-case", IntegerAtom line, StringAtom name]) = Just (MakeCaseBlock (fromInteger line) name) -- The Boolean in ProofSearch means "search recursively" -- If it's False, that means "refine", i.e. apply the name and fill in any -- arguments which can be done by unification. sexpToCommand (SexpList (SymbolAtom "proof-search" : IntegerAtom line : StringAtom name : rest)) | [] <- rest = Just (ProofSearch True (fromInteger line) name [] Nothing) | [SexpList hintexp] <- rest , Just hints <- getHints hintexp = Just (ProofSearch True (fromInteger line) name hints Nothing) | [SexpList hintexp, IntegerAtom depth] <- rest , Just hints <- getHints hintexp = Just (ProofSearch True (fromInteger line) name hints (Just (fromInteger depth))) where getHints = mapM (\h -> case h of StringAtom s -> Just s _ -> Nothing) sexpToCommand (SexpList [SymbolAtom "make-lemma", IntegerAtom line, StringAtom name]) = Just (MakeLemma (fromInteger line) name) sexpToCommand (SexpList [SymbolAtom "refine", IntegerAtom line, StringAtom name, StringAtom hint]) = Just (ProofSearch False (fromInteger line) name [hint] Nothing) sexpToCommand (SexpList [SymbolAtom "docs-for", StringAtom name]) = Just (DocsFor name Full) sexpToCommand (SexpList [SymbolAtom "docs-for", StringAtom name, SymbolAtom s]) | Just w <- lookup s opts = Just (DocsFor name w) where opts = [("overview", Overview), ("full", Full)] sexpToCommand (SexpList [SymbolAtom "apropos", StringAtom search]) = Just (Apropos search) sexpToCommand (SymbolAtom "get-options") = Just GetOpts sexpToCommand (SexpList [SymbolAtom "set-option", SymbolAtom s, BoolAtom b]) | Just opt <- lookup s opts = Just (SetOpt opt b) where opts = [("show-implicits", ShowImpl), ("error-context", ErrContext)] --TODO support more options. Issue #1611 in the Issue tracker. https://github.com/idris-lang/Idris-dev/issues/1611 sexpToCommand (SexpList [SymbolAtom "metavariables", IntegerAtom cols]) = Just (Metavariables (fromIntegral cols)) sexpToCommand (SexpList [SymbolAtom "who-calls", StringAtom name]) = Just (WhoCalls name) sexpToCommand (SexpList [SymbolAtom "calls-who", StringAtom name]) = Just (CallsWho name) sexpToCommand (SexpList [SymbolAtom "browse-namespace", StringAtom ns]) = Just (BrowseNS ns) sexpToCommand (SexpList [SymbolAtom "normalise-term", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in Just (TermNormalise bnd tm) sexpToCommand (SexpList [SymbolAtom "show-term-implicits", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in Just (TermShowImplicits bnd tm) sexpToCommand (SexpList [SymbolAtom "hide-term-implicits", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in Just (TermNoImplicits bnd tm) sexpToCommand (SexpList [SymbolAtom "elaborate-term", StringAtom encoded]) = let (bnd, tm) = decodeTerm encoded in Just (TermElab bnd tm) sexpToCommand (SexpList [SymbolAtom "print-definition", StringAtom name]) = Just (PrintDef name) sexpToCommand (SexpList [SymbolAtom "error-string", StringAtom encoded]) = Just . ErrString . decodeErr $ encoded sexpToCommand (SexpList [SymbolAtom "error-pprint", StringAtom encoded]) = Just . ErrPPrint . decodeErr $ encoded sexpToCommand (SymbolAtom "version") = Just GetIdrisVersion sexpToCommand _ = Nothing parseMessage :: String -> Either Err (SExp, Integer) parseMessage x = case receiveString x of Right (SexpList [cmd, (IntegerAtom id)]) -> Right (cmd, id) Right x -> Left . Msg $ "Invalid message " ++ show x Left err -> Left err receiveString :: String -> Either Err SExp receiveString x = case parseSExp x of Failure _ -> Left . Msg $ "parse failure" Success r -> Right r convSExp :: SExpable a => String -> a -> Integer -> String convSExp pre s id = let sex = SexpList [SymbolAtom pre, toSExp s, IntegerAtom id] in let str = sExpToString sex in (getHexLength str) ++ str getHexLength :: String -> String getHexLength s = printf "%06x" (1 + (length s)) -- | The version of the IDE mode command set. Increment this when you -- change it so clients can adapt. ideModeEpoch :: Int ideModeEpoch = 1
uuhan/Idris-dev
src/Idris/IdeMode.hs
Haskell
bsd-3-clause
17,331