code stringlengths 5 1.03M | repo_name stringlengths 5 90 | path stringlengths 4 158 | license stringclasses 15 values | size int64 5 1.03M | n_ast_errors int64 0 53.9k | ast_max_depth int64 2 4.17k | n_whitespaces int64 0 365k | n_ast_nodes int64 3 317k | n_ast_terminals int64 1 171k | n_ast_nonterminals int64 1 146k | loc int64 -1 37.3k | cycloplexity int64 -1 1.31k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
import Test.HUnit
import Q01
assertEqualMaybeInt::String -> Maybe Int -> Maybe Int -> Assertion
assertEqualMaybeInt = assertEqual
test1 = TestCase (assertEqualMaybeInt "myLastTest [] should be Nothing." Nothing (myLastTest [] ))
test2 = TestCase (assertEqual "myLastTest [0] should be Just 0. " (Just 0) (myLastTest [0] ))
test3 = TestCase (assertEqual "myLastTest [0, 1] should be Just 1. " (Just 1) (myLastTest [0, 1]))
main = runTestTT $ TestList [test1, test2, test3] | cshung/MiscLab | Haskell99/q01.test.hs | mit | 504 | 0 | 10 | 102 | 153 | 80 | 73 | 8 | 1 |
import Math.NumberTheory.Primes.Sieve(primes)
import Data.List(sort)
import Debug.Trace(trace)
-- Generate the polygonal number
polygonalNumber :: Int -> Int -> Int
polygonalNumber b n = n*((b-2)*n+(4-b)) `div` 2
-- Returns the number of decimal digits of a number
nbrDigits :: Integral a => a -> Int
nbrDigits = (+1) . floor . logBase 10 . fromIntegral
-- Returns the number obtained by concating two numbers one after the other
(#) :: Integral a => a -> a -> a
n1 # n2 = n1 * 10^nbrDigits n2 + n2
-- tools
isEmpty [] = True
isEmpty _ = False
isSingleton [_] = True
isSingleton _ = False
isPerfectSquare :: Int -> Bool
isPerfectSquare n2 = (n*n == n2) where n = round $ sqrt $ fromIntegral n2
-- Return the greatest numerator a such that a² is not greater than the given
-- number n.
isqrt n =
iter n (n+1)
where
iter a a'
| a < a' = iter (div (a*a + n) (2*a)) a
| otherwise = fineStep a
fineStep a
| n < a*a = fineStep (a-1)
| n < (a+1)*(a+1) = a
| otherwise = fineStep (a+1)
-- Given the denominator b, return the greatest numerator a such that (a/b)² is
-- not greater than the given number n.
ratSqrt b n = iter (n*b) ((n*b)+1)
where
nb² = n*b*b
iter a a'
| a < a' = iter (div (a*a + nb²) (2*a)) a
| otherwise = fineStep a
fineStep a
| nb² < a*a = fineStep (a-1)
| nb² < (a+1)*(a+1) = a
| otherwise = fineStep (a+1)
{-# LANGUAGE BangPatterns #-}
import System.CPUTime
timeIt :: (a -> String) -> a -> IO ()
timeIt toString exp = do
t1 <- getCPUTime
let !exp' = exp
t2 <- getCPUTime
putStrLn $ (show $ round $ fromIntegral (t2-t1) / 10^9) ++ " \t| " ++ toString exp'
--------------------------------------------------------------------------------
-- Simple continued fractions (i.e. expressed in cannonical form)
--------------------------------------------------------------------------------
-- Compute successive approximations of a continued fraction given its
-- successive coefficients. If the coefficients are [a, b, c...], then the
-- approximations are: a, a+(1/b), a+(1/b+(1/c)), ...
approximations :: Integral a => [a] -> [Ratio a]
approximations (a:b:cs) = res
where
res = (a % 1) : ((a*b+1)%b) : zipWith3 combine res (tail res) cs
combine a b c =
(c * numerator b + numerator a) % (c * denominator b + denominator a)
approximations [a] = repeat (a%1)
approximations [] = repeat (0%1)
-- Return the coefficients of the continued fraction equals to the square root
-- of the parameters. For perfect square, only the first parameter is returned.
sqrtCoeffs :: Integral a => a -> [a]
sqrtCoeffs n = if (isqrtn^2 == n) then [isqrtn] else (isqrtn : iter isqrtn 1)
where
isqrtn = isqrt n
iter a b = d : iter a' b'
where
b' = (n-a^2) `div` b
d = (isqrtn + a) `div` b'
a' = d * b' - a
-- The coefficients of the continued fraction of e
e_ContinuedFractionCoeffs :: Integral a => [a]
e_coeffs = 2 : gen 1 2
where
gen 1 n = 1 : gen 2 n
gen 2 n = n : gen 3 (2+n)
gen 3 n = 1 : gen 1 n
-- Occurence frequency
import Data.Map (fromListWith, toList)
frequency :: (Ord a) => [a] -> [(a, Int)]
frequency xs = toList (fromListWith (+) [(x, 1) | x <- xs])
| dpieroux/euler | euler.hs | mit | 3,324 | 8 | 16 | 833 | 1,273 | 663 | 610 | -1 | -1 |
module SpecHelper where
import Network.Wai
import Test.Hspec
import Data.String.Conversions (cs)
import Data.Time.Clock.POSIX (getPOSIXTime)
import Control.Monad (void)
import Network.HTTP.Types.Header (Header, ByteRange, renderByteRange,
hRange, hAuthorization, hAccept)
import Codec.Binary.Base64.String (encode)
import Data.CaseInsensitive (CI(..))
import Text.Regex.TDFA ((=~))
import qualified Data.ByteString.Char8 as BS
import System.Process (readProcess)
import Web.JWT (secret)
import qualified Hasql.Connection as H
import qualified Hasql.Session as H
import PostgREST.App (app)
import PostgREST.Config (AppConfig(..))
import PostgREST.Middleware
import PostgREST.Error(pgErrResponse)
import PostgREST.Types
import PostgREST.QueryBuilder (inTransaction, Isolation(..))
dbString :: String
dbString = "postgres://postgrest_test_authenticator@localhost:5432/postgrest_test"
cfg :: String -> Maybe Integer -> AppConfig
cfg conStr = AppConfig conStr "postgrest_test_anonymous" "test" 3000 (secret "safe") 10
cfgDefault :: AppConfig
cfgDefault = cfg dbString Nothing
cfgLimitRows :: Integer -> AppConfig
cfgLimitRows = cfg dbString . Just
withApp :: AppConfig -> DbStructure -> H.Connection
-> ActionWith Application -> IO ()
withApp config dbStructure c perform =
perform $ defaultMiddle $ \req resp -> do
time <- getPOSIXTime
body <- strictRequestBody req
let handleReq = H.run $ inTransaction ReadCommitted
(runWithClaims config time (app dbStructure config body) req)
handleReq c >>= \case
Left err -> do
void $ H.run (H.sql "rollback;") c
resp $ pgErrResponse err
Right res -> resp res
setupDb :: IO ()
setupDb = do
void $ readProcess "psql" ["-d", "postgres", "-a", "-f", "test/fixtures/database.sql"] []
loadFixture "roles"
loadFixture "schema"
loadFixture "privileges"
resetDb
resetDb :: IO ()
resetDb = loadFixture "data"
loadFixture :: FilePath -> IO()
loadFixture name =
void $ readProcess "psql" ["-U", "postgrest_test", "-d", "postgrest_test", "-a", "-f", "test/fixtures/" ++ name ++ ".sql"] []
rangeHdrs :: ByteRange -> [Header]
rangeHdrs r = [rangeUnit, (hRange, renderByteRange r)]
acceptHdrs :: BS.ByteString -> [Header]
acceptHdrs mime = [(hAccept, mime)]
rangeUnit :: Header
rangeUnit = ("Range-Unit" :: CI BS.ByteString, "items")
matchHeader :: CI BS.ByteString -> String -> [Header] -> Bool
matchHeader name valRegex headers =
maybe False (=~ valRegex) $ lookup name headers
authHeaderBasic :: String -> String -> Header
authHeaderBasic u p =
(hAuthorization, cs $ "Basic " ++ encode (u ++ ":" ++ p))
authHeaderJWT :: String -> Header
authHeaderJWT token =
(hAuthorization, cs $ "Bearer " ++ token)
| motiz88/postgrest | test/SpecHelper.hs | mit | 2,765 | 0 | 19 | 476 | 868 | 474 | 394 | -1 | -1 |
module BranchExample where
import Numeric.Limp.Rep.Rep as R
import Numeric.Limp.Rep.Arbitrary as R
import Numeric.Limp.Program as P
import Numeric.Limp.Canon as C
import Numeric.Limp.Solve.Simplex.Maps as SM
import Numeric.Limp.Solve.Simplex.StandardForm as ST
import Numeric.Limp.Solve.Branch.Simple as B
import Numeric.Limp.Canon.Pretty
import Debug.Trace
import Control.Applicative
-- Dead simple ones -------------------------
-- x = 2
prog1 :: P.Program String String R.Arbitrary
prog1
= P.maximise
-- objective
(z "x" 1)
-- subject to
( z "x" 2 :<= con 5
:&& z "x" 4 :>= con 7)
[]
-- x = 1, y = 2
prog2 :: P.Program String String R.Arbitrary
prog2
= P.minimise
-- objective
(z "x" 1 .+. z "y" 1)
-- subject to
( z "x" 2 :<= con 5 -- z "y" 1 .+. con 1
:&& z "x" 1 :>= con 1
:&& z "y" 1 :<= con 4
:&& z "y" 1 :>= con 1)
[ lowerZ 0 "x"
, lowerZ 0 "y" ]
xkcd :: Direction -> P.Program String String R.Arbitrary
xkcd dir = P.program dir
( z1 mf .+.
z1 ff .+.
z1 ss .+.
z1 hw .+.
z1 ms .+.
z1 sp )
( z mf mfp .+.
z ff ffp .+.
z ss ssp .+.
z hw hwp .+.
z ms msp .+.
z sp spp :== con 1505 )
[ lowerZ 0 mf
, lowerZ 0 ff
, lowerZ 0 ss
, lowerZ 0 hw
, lowerZ 0 ms
, lowerZ 0 sp
]
where
(mf, mfp) = ("mixed-fruit", 215)
(ff, ffp) = ("french-fries", 275)
(ss, ssp) = ("side-salad", 335)
(hw, hwp) = ("hot-wings", 355)
(ms, msp) = ("mozzarella-sticks", 420)
(sp, spp) = ("sampler-plate", 580)
test :: (Show z, Show r, Ord z, Ord r)
=> P.Program z r R.Arbitrary -> IO ()
test prog
= let prog' = C.program prog
simpl p = SM.simplex $ ST.standard p
solver p
| st <- ST.standard p
-- , trace (ppr show show p) True
, Just s' <- SM.simplex st
-- , trace ("SAT") True
, ass <- SM.assignment s'
= Just ass
| otherwise
-- , trace ("unsat") True
= Nothing
bb = B.branch solver
in do
-- putStrLn (show (simpl prog'))
-- putStrLn (show (solver prog'))
putStrLn (show (bb prog'))
| amosr/limp | tests/BranchExample.hs | mit | 2,413 | 0 | 14 | 915 | 780 | 412 | 368 | 69 | 1 |
module Main where
import System.Environment (getArgs)
import System.IO
main = do {
args <- getArgs;
ih <- openFile (head args)
ReadMode;
input <- hGetContents ih;
putStrLn $show $ length $ words input;
hClose(ih);
}
| dicander/progp_haskell | word_count_with_environment.hs | mit | 229 | 0 | 10 | 47 | 93 | 48 | 45 | 10 | 1 |
-- Copyright (c) 2016-present, SoundCloud Ltd.
-- All rights reserved.
--
-- This source code is distributed under the terms of a MIT license,
-- found in the LICENSE file.
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
module Kubernetes.Model.V1.ComponentCondition
( ComponentCondition (..)
, type_
, status
, message
, error
, mkComponentCondition
) where
import Control.Lens.TH (makeLenses)
import Data.Aeson.TH (defaultOptions, deriveJSON,
fieldLabelModifier)
import Data.Text (Text)
import GHC.Generics (Generic)
import Prelude hiding (drop, error, max, min)
import qualified Prelude as P
import Test.QuickCheck (Arbitrary, arbitrary)
import Test.QuickCheck.Instances ()
-- | Information about the condition of a component.
data ComponentCondition = ComponentCondition
{ _type_ :: !(Text)
, _status :: !(Text)
, _message :: !(Maybe Text)
, _error :: !(Maybe Text)
} deriving (Show, Eq, Generic)
makeLenses ''ComponentCondition
$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''ComponentCondition)
instance Arbitrary ComponentCondition where
arbitrary = ComponentCondition <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
-- | Use this method to build a ComponentCondition
mkComponentCondition :: Text -> Text -> ComponentCondition
mkComponentCondition xtype_x xstatusx = ComponentCondition xtype_x xstatusx Nothing Nothing
| soundcloud/haskell-kubernetes | lib/Kubernetes/Model/V1/ComponentCondition.hs | mit | 1,751 | 0 | 14 | 486 | 324 | 192 | 132 | 39 | 1 |
module Nunavut.Layer.Weights where
import Control.Lens (to, (%=), (^.), _1, _2)
import Control.Monad.Identity (Identity, runIdentity)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.RWS (ask, get, mapRWST, tell)
import Data.Monoid (mappend, mempty)
import Numeric.LinearAlgebra (Matrix, RandDist (..), cols,
randomVector, reshape, rows, scale)
import System.Random (randomIO)
import Nunavut.Newtypes (HasMtx (..), mtxElementwise, trans,
(<>))
import Nunavut.Propogation (Backpropogation, PropData (..),
Propogation, learningRate, preWeights,
(><))
import Nunavut.Util (Error, SizedOperator (..), checkDims,
checkDims')
newtype Weights = Weights { unWeights :: Matrix Double }
deriving (Show, Eq)
{--------------------------------------------------------------------------
- Constructors -
--------------------------------------------------------------------------}
mkWeights :: Matrix Double -> Weights
mkWeights = Weights
initWeights :: Int -> Int -> IO Weights
initWeights rs cs = do
seed <- randomIO
let cs' = succ cs
stdev = fromIntegral cs' ** (-0.5)
return . fromMtx . reshape cs' . scale stdev . randomVector seed Gaussian $ (rs * cs')
{--------------------------------------------------------------------------
- Instances -
--------------------------------------------------------------------------}
instance SizedOperator Weights where
outSize = to $ rows . unWeights
inSize = to $ cols . unWeights
instance HasMtx Weights where
toMtx = unWeights
fromMtx = mkWeights
{--------------------------------------------------------------------------
- Propogation -
--------------------------------------------------------------------------}
unsafePropW :: Propogation Weights Identity
unsafePropW w sig = do
tell $ PData [sig] mempty
return $ w <> sig
propW :: Propogation Weights (Either Error)
propW w sig = do
checkedSig <- lift $ checkDims "propW" sig w
mapRWST (return . runIdentity) . unsafePropW w $ checkedSig
unsafeBackpropW :: Backpropogation Weights Identity
unsafeBackpropW w err = do
conf <- ask
(_, pData) <- get
let mulRate = mtxElementwise (* conf ^. learningRate)
_1 %= (`mappend` [mulRate . trans $ head (pData ^. preWeights) >< err])
_2 . preWeights %= tail
return $ trans w <> err
backpropW :: Backpropogation Weights (Either Error)
backpropW w err = do
checkedErr <- lift $ checkDims' "backpropW" w err
mapRWST (return . runIdentity) . unsafeBackpropW w $ checkedErr
shape :: Weights -> (Int, Int)
shape (Weights w) = (rows w, cols w)
| markcwhitfield/nunavut | src/Nunavut/Layer/Weights.hs | mit | 3,203 | 0 | 14 | 1,041 | 761 | 416 | 345 | -1 | -1 |
module SMCDEL.Examples.WhatSum where
import SMCDEL.Examples.SumAndProduct (nmbr)
import SMCDEL.Language
import SMCDEL.Internal.Help
import SMCDEL.Symbolic.S5
wsBound :: Int
wsBound = 50
wsTriples :: [ (Int,Int,Int) ]
wsTriples = filter
( \(x,y,z) -> x+y==z || x+z==y || y+z==x )
[ (x,y,z) | x <- [1..wsBound], y <- [1..wsBound], z <- [1..wsBound] ]
aProps,bProps,cProps :: [Prp]
(aProps,bProps,cProps) = ([(P 1)..(P k)],[(P $ k+1)..(P l)],[(P $ l+1)..(P m)]) where
[k,l,m] = map (wsAmount*) [1,2,3]
wsAmount = ceiling (logBase 2 (fromIntegral wsBound) :: Double)
aIs, bIs, cIs :: Int -> Form
aIs n = booloutofForm (powerset aProps !! n) aProps
bIs n = booloutofForm (powerset bProps !! n) bProps
cIs n = booloutofForm (powerset cProps !! n) cProps
wsKnStruct :: KnowStruct
wsKnStruct = KnS wsAllProps law obs where
wsAllProps = aProps++bProps++cProps
law = boolBddOf $ Disj [ Conj [ aIs x, bIs y, cIs z ] | (x,y,z) <- wsTriples ]
obs = [ (alice, bProps++cProps), (bob, aProps++cProps), (carol, aProps++bProps) ]
wsKnowSelfA,wsKnowSelfB,wsKnowSelfC :: Form
wsKnowSelfA = Disj [ K alice $ aIs x | x <- [1..wsBound] ]
wsKnowSelfB = Disj [ K bob $ bIs x | x <- [1..wsBound] ]
wsKnowSelfC = Disj [ K carol $ cIs x | x <- [1..wsBound] ]
wsResult :: KnowStruct
wsResult = foldl update wsKnStruct [ Neg wsKnowSelfA, Neg wsKnowSelfB, Neg wsKnowSelfC ]
wsSolutions :: [State]
wsSolutions = statesOf wsResult
wsExplainState :: [Prp] -> [(Char,Int)]
wsExplainState truths =
[ ('a', explain aProps), ('b', explain bProps), ('c', explain cProps) ] where
explain = nmbr truths
| jrclogic/SMCDEL | src/SMCDEL/Examples/WhatSum.hs | gpl-2.0 | 1,594 | 0 | 15 | 278 | 777 | 434 | 343 | 36 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Keymap.Vim.NormalOperatorPendingMap
-- License : GPL-2
-- Maintainer : yi-devel@googlegroups.com
-- Stability : experimental
-- Portability : portable
module Yi.Keymap.Vim.NormalOperatorPendingMap
(defNormalOperatorPendingMap) where
import Control.Applicative
import Control.Monad
import Data.Char (isDigit)
import Data.List (isPrefixOf)
import Data.Maybe (fromMaybe, fromJust)
import Data.Monoid
import qualified Data.Text as T
import Yi.Buffer.Adjusted hiding (Insert)
import Yi.Editor
import Yi.Keymap.Keys
import Yi.Keymap.Vim.Common
import Yi.Keymap.Vim.Motion
import Yi.Keymap.Vim.Operator
import Yi.Keymap.Vim.StateUtils
import Yi.Keymap.Vim.StyledRegion
import Yi.Keymap.Vim.TextObject
import Yi.Keymap.Vim.Utils
defNormalOperatorPendingMap :: [VimOperator] -> [VimBinding]
defNormalOperatorPendingMap operators = [textObject operators, escBinding]
textObject :: [VimOperator] -> VimBinding
textObject operators = VimBindingE f
where
f evs vs = case vsMode vs of
NormalOperatorPending _ -> WholeMatch $ action evs
_ -> NoMatch
action (Ev evs) = do
currentState <- getEditorDyn
let partial = vsTextObjectAccumulator currentState
opChar = Ev . T.pack $ lastCharForOperator op
op = fromJust $ stringToOperator operators opname
(NormalOperatorPending opname) = vsMode currentState
-- vim treats cw as ce
let evs' = if opname == Op "c" && T.last evs == 'w' &&
(case parseOperand opChar (evr evs) of
JustMove _ -> True
_ -> False)
then T.init evs `T.snoc` 'e'
else evs
-- TODO: fix parseOperand to take EventString as second arg
evr x = T.unpack . _unEv $ partial <> Ev x
operand = parseOperand opChar (evr evs')
case operand of
NoOperand -> do
dropTextObjectAccumulatorE
resetCountE
switchModeE Normal
return Drop
PartialOperand -> do
accumulateTextObjectEventE (Ev evs)
return Continue
_ -> do
count <- getCountE
dropTextObjectAccumulatorE
token <- case operand of
JustTextObject cto@(CountedTextObject n _) -> do
normalizeCountE (Just n)
operatorApplyToTextObjectE op 1 $
changeTextObjectCount (count * n) cto
JustMove (CountedMove n m) -> do
mcount <- getMaybeCountE
normalizeCountE n
region <- withCurrentBuffer $ regionOfMoveB $ CountedMove (maybeMult mcount n) m
operatorApplyToRegionE op 1 region
JustOperator n style -> do
normalizeCountE (Just n)
normalizedCount <- getCountE
region <- withCurrentBuffer $ regionForOperatorLineB normalizedCount style
curPoint <- withCurrentBuffer pointB
token <- operatorApplyToRegionE op 1 region
when (opname == Op "y") $
withCurrentBuffer $ moveTo curPoint
return token
_ -> error "can't happen"
resetCountE
return token
regionForOperatorLineB :: Int -> RegionStyle -> BufferM StyledRegion
regionForOperatorLineB n style = normalizeRegion =<< StyledRegion style <$> savingPointB (do
current <- pointB
if n == 1
then do
firstNonSpaceB
p0 <- pointB
return $! mkRegion p0 current
else do
void $ lineMoveRel (n-2)
moveToEol
rightB
firstNonSpaceB
p1 <- pointB
return $! mkRegion current p1)
escBinding :: VimBinding
escBinding = mkBindingE ReplaceSingleChar Drop (spec KEsc, return (), resetCount . switchMode Normal)
data OperandParseResult
= JustTextObject !CountedTextObject
| JustMove !CountedMove
| JustOperator !Int !RegionStyle -- ^ like dd and d2vd
| PartialOperand
| NoOperand
parseOperand :: EventString -> String -> OperandParseResult
parseOperand opChar s = parseCommand mcount styleMod opChar commandString
where (mcount, styleModString, commandString) = splitCountModifierCommand s
styleMod = case styleModString of
"" -> id
"V" -> const LineWise
"<C-v>" -> const Block
"v" -> \style -> case style of
Exclusive -> Inclusive
_ -> Exclusive
_ -> error "Can't happen"
-- | TODO: should this String be EventString?
parseCommand :: Maybe Int -> (RegionStyle -> RegionStyle)
-> EventString -> String -> OperandParseResult
parseCommand _ _ _ "" = PartialOperand
parseCommand _ _ _ "i" = PartialOperand
parseCommand _ _ _ "a" = PartialOperand
parseCommand _ _ _ "g" = PartialOperand
parseCommand n sm o s | o' == s = JustOperator (fromMaybe 1 n) (sm LineWise)
where o' = T.unpack . _unEv $ o
parseCommand n sm _ "0" =
let m = Move Exclusive False (const moveToSol)
in JustMove (CountedMove n (changeMoveStyle sm m))
parseCommand n sm _ s = case stringToMove . Ev $ T.pack s of
WholeMatch m -> JustMove $ CountedMove n $ changeMoveStyle sm m
PartialMatch -> PartialOperand
NoMatch -> case stringToTextObject s of
Just to -> JustTextObject $ CountedTextObject (fromMaybe 1 n)
$ changeTextObjectStyle sm to
Nothing -> NoOperand
-- TODO: setup doctests
-- Parse event string that can go after operator
-- w -> (Nothing, "", "w")
-- 2w -> (Just 2, "", "w")
-- V2w -> (Just 2, "V", "w")
-- v2V3<C-v>w -> (Just 6, "<C-v>", "w")
-- vvvvvvvvvvvvvw -> (Nothing, "v", "w")
-- 0 -> (Nothing, "", "0")
-- V0 -> (Nothing, "V", "0")
splitCountModifierCommand :: String -> (Maybe Int, String, String)
splitCountModifierCommand = go "" Nothing [""]
where go "" Nothing mods "0" = (Nothing, head mods, "0")
go ds count mods (h:t) | isDigit h = go (ds <> [h]) count mods t
go ds@(_:_) count mods s@(h:_) | not (isDigit h) = go [] (maybeMult count (Just (read ds))) mods s
go [] count mods (h:t) | h `elem` "vV" = go [] count ([h]:mods) t
go [] count mods s | "<C-v>" `isPrefixOf` s = go [] count ("<C-v>":mods) (drop 5 s)
go [] count mods s = (count, head mods, s)
go ds count mods [] = (maybeMult count (Just (read ds)), head mods, [])
go (_:_) _ _ (_:_) = error "Can't happen because isDigit and not isDigit cover every case"
| atsukotakahashi/wi | src/library/Yi/Keymap/Vim/NormalOperatorPendingMap.hs | gpl-2.0 | 7,030 | 129 | 11 | 2,302 | 1,751 | 932 | 819 | 146 | 9 |
module Poll
( watch ) where
import System.Directory
import Data.Time.Clock
import Data.Time.Calendar
import Control.Monad (forever)
import qualified Control.Concurrent as C
import System.IO.Error
watch :: (String -> IO ()) -> [String] -> IO ()
watch fun fs =
let
wait = C.threadDelay 1000000
in do
putStrLn "starting.."
mapM_ fun fs
forever $ (wait >> mapM_ (onChange fun) fs)
onChange :: (String -> IO ()) -> String -> IO ()
onChange fun file = do
modified <- retryAtMost 10 (getModificationTime file)
curTime <- getCurrentTime
let diff = (diffUTCTime curTime modified)
if diff < 2 then fun file else return ()
retryAtMost 1 action = catchIOError action (\e -> ioError e)
retryAtMost times action =
let
handle e = if isDoesNotExistError e
then C.threadDelay 50000 >> retryAtMost (times - 1) action
else ioError e
in
catchIOError action handle
| beni55/lit | src/Poll.hs | gpl-2.0 | 946 | 0 | 15 | 237 | 344 | 172 | 172 | 29 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Grammatik.Type
( module Grammatik.Type
, module Autolib.Set
)
where
import Autolib.Set
import Autolib.Size
import Autolib.Hash
import Autolib.ToDoc
import Autolib.Reader
import Data.Typeable
import GHC.Generics
data Grammatik = Grammatik
{ terminale :: Set Char
, variablen :: Set Char
, start :: Char
, regeln :: Set (String, String)
}
deriving ( Eq, Typeable, Generic )
-- | L(mirror (G)) = map reverse (L(G))
-- achieved by reversing both sides of each rule
mirror :: Grammatik -> Grammatik
mirror g = g { regeln =
smap ( \(l,r) -> (reverse l, reverse r))
$ regeln g }
example :: Grammatik
example = Grammatik
{ terminale = mkSet "ab"
, variablen = mkSet "S"
, start = 'S'
, regeln = mkSet [ ("S", ""), ("S", "aSbS") ]
}
example3 :: Grammatik
example3 = Grammatik
{ terminale = mkSet "ab"
, variablen = mkSet "ST"
, start = 'S'
, regeln = mkSet [ ("S", ""), ("S", "aT"), ("T", "bS") ]
}
$(derives [makeReader, makeToDoc] [''Grammatik])
instance Hashable Grammatik
terms = setToList . terminale
vars = setToList . variablen
rules = setToList . regeln
instance Size Grammatik where size = cardinality . regeln
-- | for compatibility:
nichtterminale = variablen
startsymbol = start
| marcellussiegburg/autotool | collection/src/Grammatik/Type.hs | gpl-2.0 | 1,480 | 15 | 13 | 404 | 410 | 240 | 170 | 43 | 1 |
module AccessLogger
(startAccessLogger, stopAccessLogger, logAccess) where
{ import ErrorLogger;
import Request;
import Response;
import Config;
import Global;
import Util;
import IO;
import Char (toLower);
import System.IO.Unsafe;
import System.Time;
import Network.Socket;
import Network.BSD;
import Control.Exception as Exception;
import Control.Concurrent;
data LogRequest = LogReq{log_ipaddr :: HostAddress,
log_logname :: String, log_request :: Request,
log_response :: Response, log_time :: ClockTime,
log_delay :: TimeDiff, log_user :: String,
log_server :: HostEntry};
logAccess ::
Request -> Response -> HostAddress -> TimeDiff -> IO ();
logAccess req resp haddr delay
= do { time <- getClockTime;
server <- readMVar local_hostent;
writeChan access_log_chan
LogReq{log_ipaddr = haddr, log_logname = "<nobody>",
log_request = req, log_response = resp, log_time = time,
log_delay = delay, log_user = "<nouser>", log_server = server}}
where {
access_log_chan :: Chan LogRequest};
access_log_chan = unsafePerformIO (newChan);
access_log_pid :: MVar ThreadId;
access_log_pid = unsafePerformIO (newEmptyMVar);
startAccessLogger :: Config -> IO ();
startAccessLogger conf
= do { logError
("access logger started on '" ++ accessLogFile conf ++ "'");
t <- forkIO
(Exception.catch (run_access_logger conf) (error_handler conf));
putMVar access_log_pid t};
stopAccessLogger :: IO ();
stopAccessLogger
= do { t <- takeMVar access_log_pid;
throwTo t (ErrorCall "**stop**")};
error_handler conf (ErrorCall "**stop**")
= logError ("access logger stopped");
error_handler conf exception
= do { logError ("access logger died: " ++ show exception);
Exception.catch (run_access_logger conf) (error_handler conf)};
run_access_logger conf
= Exception.bracket (openFile (accessLogFile conf) AppendMode)
(\ hdl -> hClose hdl)
(\ hdl -> doLogRequests conf hdl);
doLogRequests conf hdl
= do { req <- readChan access_log_chan;
ip_addr <- inet_ntoa (log_ipaddr req);
host <- if hostnameLookups conf then
do { catchJust ioErrors
(do { ent <- getHostByAddr AF_INET (log_ipaddr req);
return (Just ent)})
(\ _ -> return Nothing)}
else return Nothing;
let { line = mkLogLine req ip_addr host (accessLogFormat conf)};
hPutStrLn hdl line;
hFlush hdl;
doLogRequests conf hdl};
mkLogLine ::
LogRequest -> String -> Maybe HostEntry -> String -> String;
mkLogLine _info _ip_addr _host "" = "";
mkLogLine info ip_addr host ('%' : '{' : rest)
= expand info ip_addr host (Just str) c ++
mkLogLine info ip_addr host rest1
where { (str, '}' : c : rest1) = span (/= '}') rest};
mkLogLine info ip_addr host ('%' : c : rest)
= expand info ip_addr host Nothing c ++
mkLogLine info ip_addr host rest;
mkLogLine info ip_addr host (c : rest)
= c : mkLogLine info ip_addr host rest;
expand info ip_addr host arg c
= case c of
{ 'b' -> show (contentLength resp_body);
'f' -> getFileName resp_body;
'h'
-> case host of
{ Just ent -> hostName ent;
Nothing -> ip_addr};
'a' -> ip_addr;
'l' -> log_logname info;
'r' -> show (log_request info);
's' -> show resp_code;
't' -> formatTimeSensibly (toUTCTime (log_time info));
'T' -> timeDiffToString (log_delay info);
'v' -> hostName (log_server info);
'u' -> log_user info;
'i' -> getReqHeader arg (reqHeaders (log_request info));
_ -> ['%', c]}
where { Response{respCode = resp_code, respHeaders = resp_headers,
respCoding = resp_coding, respBody = resp_body,
respSendBody = resp_send_body}
= log_response info};
getReqHeader (Nothing) _hdrs = "";
getReqHeader (Just hdr) hdrs
= concat
(case map toLower hdr of
{ "accept" -> [s | Accept s <- hdrs];
"accept-charset" -> [s | AcceptCharset s <- hdrs];
"accept-encoding" -> [s | AcceptEncoding s <- hdrs];
"accept-language" -> [s | AcceptLanguage s <- hdrs];
"authorization" -> [s | Authorization s <- hdrs];
"cachecontrol" -> [s | CacheControl s <- hdrs];
"from" -> [s | From s <- hdrs];
"if-match" -> [s | IfMatch s <- hdrs];
"if-modified-since" -> [s | IfModifiedSince s <- hdrs];
"if-none-match" -> [s | IfNoneMatch s <- hdrs];
"if-range" -> [s | IfRange s <- hdrs];
"if-unmodified-since" -> [s | IfUnmodifiedSince s <- hdrs];
"max-forwards" -> [s | MaxForwards s <- hdrs];
"proxy-authorization" -> [s | ProxyAuthorization s <- hdrs];
"range" -> [s | Range s <- hdrs];
"referer" -> [s | Referer s <- hdrs];
"te" -> [s | TE s <- hdrs];
"user-agent" -> [s | UserAgent s <- hdrs];
_ -> []})}
| ckaestne/CIDE | CIDE_Language_Haskell/test/WSP/Webserver/AccessLogger.hs | gpl-3.0 | 5,592 | 0 | 18 | 1,901 | 1,670 | 901 | 769 | 125 | 19 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Texture.SH.RotationSO4 where
import qualified Data.List as L
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import qualified Data.HashMap.Strict as HM
import qualified Data.Packed as M
import Data.Complex
import Foreign.Storable (Storable)
import Data.Vector (Vector)
import Data.HashMap.Strict (HashMap)
import Data.Packed.Matrix ((><), (@@>), cols, buildMatrix)
import Numeric.LinearAlgebra ((<>))
import Numeric.Container (Product, add, ident, ctrans, multiply, cmap)
import Texture.HyperSphere
import Texture.Orientation
import Texture.SH.Harmonics
import Texture.SH.Pyramid
import Texture.SH.SupportFunctions
import Texture.SH.RotationSO3
--import Debug.Trace
--dbg s x = trace (show s L.++ show x) x
-- =========================== Hyper Spherical Harmonics Rotation ========================
-- | Rotation matrix series for hyper spherical harmonics from 2l = 0 until 2l = 2n. More
-- info on PhD Thesis J.K. Mason eq (52).
vecRotMatrixHSH :: Int -> SO3 -> SO3 -> Vector (M.Matrix (Complex Double))
vecRotMatrixHSH n r p = let
lmax = n `quot` 2
-- For some reason p and r had to swap positions, it mans that the active rotation is
-- given by vecPassiveRotMatrixSH and the passive rotation is given by vecActiveRotMatrixSH
us = vecActiveRotMatrixSH lmax p
us' = vecPassiveRotMatrixSH lmax r
in V.izipWith (\l u u' -> calcRotMatrixHSH u u' (2*l)) us us'
vecIDRotMatrixHSH :: Int -> Vector (M.Matrix (Complex Double))
vecIDRotMatrixHSH n = let
lmax = n `quot` 2
func l = let
s = (2*l+1) * (2*l+1)
in ident s
in V.generate lmax func
-- | Rotation matrix for hyper spherical harmonics at 2l. More info on PhD Thesis J.K.
-- Mason eq (52).
rotMatrixHSH :: Int -> SO3 -> SO3 -> M.Matrix (Complex Double)
rotMatrixHSH n r p = (vecRotMatrixHSH n r p) V.! (n `quot` 2)
-- | Rotation matrix series for Real hyper spherical harmonics from 2l = 0 until 2l = 2n.
vecRotMatrixRealHSH :: Int -> SO3 -> SO3 -> Vector (M.Matrix Double)
vecRotMatrixRealHSH n r p = let
l = n `quot` 2
vu = vecRotMatrixHSH (2*l) r p
vt = V.generate (2*l+1) realPartMatrixHSH
func i u = let
t = M.diagBlock $ V.toList $ V.take (2*i+1) vt
in M.mapMatrix realPart $ (ctrans t) <> u <> t
in V.imap func vu
-- | Calculate the rotation matrix for Hyper Spherical Harmonics (SO4) based on two SO3
-- rotation matrix, one active and one passive. More info, see PhD Thesis J.K. Mason eq (52)
calcRotMatrixHSH :: M.Matrix (Complex Double) -> M.Matrix (Complex Double) -> Int -> M.Matrix (Complex Double)
calcRotMatrixHSH u u' n = let
l = n `quot` 2
calcAtM (row, col) = let
p' = ps V.! row
p = ps V.! col
us = [l, l-1 .. (-l)]
in sum [ func p' p (m', m) (m''', m'')
| m <- us, m' <- us, m'' <- us, m''' <- us
]
func (lb', mu') (lb, mu) (m', m) (m''', m'') = let
-- calcClebshGordan j1 m1 j2 m2 j m
--c1 = getClebsh (l, m'' ) (l, m') (lb', mu')
--c2 = getClebsh (l, m''') (l, m ) (lb , mu )
c1 = calcClebshGordan (l, m'' ) (l, m') (lb', mu')
c2 = calcClebshGordan (l, m''') (l, m ) (lb , mu )
z = u @@> (l - m' , l - m )
z' = u' @@> (l - m''', l - m'')
in ((c1 * c2) :+ 0) * z * z'
ps = V.fromList [ (lb, mu) | lb <- [0 .. 2*l], mu <- [lb, lb-1 .. (-lb)] ]
ms = [ (row, col) | col <- [0 .. s-1], row <- [0 .. s-1] ]
s = (2*l+1) * (2*l+1)
in (s >< s) $ map calcAtM ms
-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
isNonZeroClebsh :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Bool
isNonZeroClebsh (j1, m1) (j2, m2) (j, m) =
m == m1 + m2 &&
j >= abs (j1 - j2) &&
j <= abs (j1 + j2) &&
j >= abs m &&
j1 >= abs m1 &&
j2 >= abs m2
getClebsh :: (Int, Int) -> (Int, Int) -> (Int, Int) -> Double
getClebsh (l1, m1) (l2, m2) (lb, mu)
| isNonZeroClebsh (l1, m1) (l2, m2) (lb, mu) = maybe slow id fast
| otherwise = 0
where
slow = calcClebshGordan (l1, m1) (l2, m2) (lb, mu)
fast = HM.lookup (l1, m1, l2, m2, lb, mu) memoClebsh
memoClebsh :: HashMap (Int, Int, Int, Int, Int, Int) Double
memoClebsh = HM.fromList useful
where
l = 6
useful =
[ ((l1, m1, l2, m2, lb, mu)
, calcClebshGordan (l1, m1) (l2, m2) (lb, mu))
| l1 <- [0 .. l ]
, m1 <- [(-l) .. l ]
, l2 <- [0 .. l ]
, m2 <- [(-l) .. l ]
, lb <- [0 .. 2*l]
, mu <- [(-lb) .. lb ]
, isNonZeroClebsh (l1, m1) (l2, m2) (lb, mu)
]
-- ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-- ======================== Matrix multiplication on N Stack Level =======================
-- | Applies matrix multiplication for each L x MF column along the N stack of the 'Pyramid'.
multNStack :: (U.Unbox a, Storable a, Product a)=> (Int -> M.Matrix a) ->
Pyramid (N, L, MF) a -> Pyramid (N, L, MF) a
multNStack getMs pyC = let
n = getMaxStack pyC
ls = [0 .. (n `quot` 2)]
toVec = U.fromList . M.toList
func li = (getMs li) <> (getNSlice pyC (N $ 2*li))
pyra = U.concat $ map (toVec . func) ls
in pyC { pyramid = pyra }
getNSlice :: (U.Unbox a, Storable a)=> Pyramid (N, L, MF) a -> N -> M.Vector a
getNSlice pyC n = toVec $ slicer $ pyramid pyC
where
l = (unN n) `quot` 2
toVec = M.fromList . U.toList
slicer = U.slice (getKeyPos (N (2*l), L 0, MF 0)) ((2*l+1)*(2*l+1))
-- =================== Matrix multiplication on N over L Stack Level =====================
-- | Applies matrix multiplication for each MF column along the N and L stacks of the 'Pyramid'.
multNLStack :: (U.Unbox a, Storable a, Product a)=> (Int -> M.Matrix a) ->
Pyramid (N, L, MF) a -> Pyramid (N, L, MF) a
multNLStack getMs pyC = let
n = getMaxStack pyC
ns = [0, 2 .. n]
func ni = multLStack getMs (getNLSlice pyC (N ni))
pyra = U.concat $ map (pyramid . func) ns
in pyC { pyramid = pyra }
getNLSlice :: (U.Unbox a, Storable a)=> Pyramid (N, L, MF) a -> N -> Pyramid (L, MF) a
getNLSlice pyC nt = generatePyramid func ni
where
vec = slicer $ pyramid pyC
n@(N ni) = if even (unN nt) then nt else nt-1
func lmf = vec U.! getKeyPos (lmf :: (L, MF))
slicer = U.slice (getKeyPos (n, L 0, MF 0)) ((ni + 1)^(2 :: Int))
-- =================== Conversion to real numbers transformation matrix ==================
realPartMatrixHSH :: Int -> M.Matrix (Complex Double)
realPartMatrixHSH l = let
calcAtM (i, j)
| mi == 0 && mj == 0 = (ip l)
| abs mi /= abs mj = 0 :+ 0
| mj > 0 && mi > 0 = (ip l) * k * s
| mj > 0 && mi < 0 = (ip l) * k
| mj < 0 && mi > 0 = (ip $ l-1) * k * s
| otherwise = (ip $ l-1) * (-k)
where
-- mi and mj range [l .. -l]
mi = -i + l
mj = -j + l
s = if even mi then 1 else (-1)
ip = negativeImaginaryPower
k = 1 / (sqrt 2)
ms = 2 * l + 1
in buildMatrix ms ms calcAtM
toRealMatrix :: M.Matrix (Complex Double) -> M.Matrix Double
toRealMatrix m = let
nsqrt = round $ sqrt $ (fromIntegral $ cols m :: Double)
l = nsqrt - 1
u = M.diagBlock $ map realPartMatrixHSH [0 .. l]
in cmap realPart $ (ctrans u) `multiply` m `multiply` u
-- ================================ Conversion to real Pyramid ===========================
-- | Transforms a complex Pyramid (L, MF) to its real equivalent.
fromComplexHSH :: Pyramid (N, L, MF) (Complex Double) -> Pyramid (N, L, MF) Double
fromComplexHSH pyC = generatePyramid (realPart . func) lmax
where
lmax = getMaxStack pyC
kr = (1 / sqrt 2) :+ 0
i = imaginaryPower . unL
func (n, l, mf)
| mf > 0 = i l * kr * (s * pyC %! (n, l, mf) + pyC %! (n, l, -mf))
| mf < 0 = i (l - 1) * kr * (s * pyC %! (n, l, -mf) - pyC %! (n, l, mf))
| otherwise = i l * pyC %! (n, l, mf)
where s = if even (unMF mf) then 1 else -1
-- ================================ Useful HSH functions =================================
-- | Applies both active and passive rotations on a Hyper Spherical Harmonics. The active
-- one is a rotation on the crystal reference frame and the passive is on the sample frame.
rotRHSH :: (SO3, SO3) -> Pyramid (N, L, MF) Double -> Pyramid (N, L, MF) Double
rotRHSH (ac, pa) = \hsh -> let
n = getMaxStack hsh
vecmat = V.map toRealMatrix $ vecRotMatrixHSH n ac pa
in applyRotMatrixHSH vecmat hsh
-- | Applies both active and passive rotations on a Hyper Spherical Harmonics. The active
-- one is a rotation on the crystal reference frame and the passive is on the sample frame.
rotHSH :: (SO3, SO3) -> Pyramid (N, L, MF) (Complex Double) -> Pyramid (N, L, MF) (Complex Double)
rotHSH (ac, pa) = \hsh -> let n = getMaxStack hsh in applyRotMatrixHSH (vecRotMatrixHSH n ac pa) hsh
-- | Calculates the matrix that enforces symmetry on Hyper Spherical Harmonics.
symmRotMatrixHSH :: [(SO3, SO3)] -> Int -> Vector (M.Matrix (Complex Double))
symmRotMatrixHSH [] l = vecIDRotMatrixHSH l
symmRotMatrixHSH symm l = let
rot0:rots = map (\(ac, pa) -> vecRotMatrixHSH l ac pa) symm
in L.foldl' (V.zipWith add) rot0 rots
-- | Calculates the matrix that enforces symmetry on Hyper Spherical Harmonics.
symmRotMatrixRHSH :: [(SO3, SO3)] -> Int -> Vector (M.Matrix Double)
symmRotMatrixRHSH symm = V.map toRealMatrix . symmRotMatrixHSH symm
-- | Applies a given rotation matrix to Hyper Spherical Harmonics.
applyRotMatrixHSH :: (Product a, U.Unbox a)=> Vector (M.Matrix a) -> Pyramid (N, L, MF) a -> Pyramid (N, L, MF) a
applyRotMatrixHSH rotvec = multNStack (rotvec V.!)
-- ======================================== Test ========================================
testRotHSH :: IO ()
testRotHSH = let
g1 = SO3 (pi/2) (pi/2) (pi/2)
g2 = SO3 (pi/4) (pi/4) 0
rot = SO3 (-pi/2) (pi/2) 0
in do
plotHSHPoints [g1, g2] [rot] [rot]
saveTest "HSH-C-initial" $ plotHSH_C 6 [g1, g2] fromComplexHSH
saveTest "HSH-initial" $ plotHSH 6 [g1, g2] id
saveTest "HSH-C-active" $ plotHSH_C 6 [g1, g2] (fromComplexHSH . rotHSH (rot, SO3 0 0 0))
saveTest "HSH-active" $ plotHSH 6 [g1, g2] (rotRHSH (rot, SO3 0 0 0))
saveTest "HSH-C-passive" $ plotHSH_C 6 [g1, g2] (fromComplexHSH . rotHSH (SO3 0 0 0, rot))
saveTest "HSH-passive" $ plotHSH 6 [g1, g2] (rotRHSH (SO3 0 0 0, rot))
testSymmHSH :: IO ()
testSymmHSH = let
g = SO3 (0.77*pi) (0.3*pi) (0.4*pi)
r1 = (SO3 0 0 0, SO3 (-pi/2) (pi/2) 0)
r2 = (SO3 (-pi/2) (pi/2) 0, SO3 0 0 0)
r3 = (SO3 0 0 0, SO3 0 0 0)
symm = [r1, r2, r3]
rot = symmRotMatrixHSH symm 6
(as, ps) = unzip symm
in do
plotHSHPoints [g] as ps
saveTest "HSH-symmetry" $ plotHSH_C 10 [g] (fromComplexHSH . applyRotMatrixHSH rot)
-- ======================================== Trash ========================================
testRowCol0 :: N -> SO3 -> SO3 -> Double
testRowCol0 n r p = let
rp = quaternionToSO3 ((so3ToQuaternion r) #<= (so3ToQuaternion p))
pr = quaternionToSO3 ((so3ToQuaternion p) #<= (so3ToQuaternion r))
vC1 = rotHSHCol0 n pr
vC2 = head $ M.toColumns $ rotMatrixHSH (unN n) r p
vR1 = rotHSHRow0 n rp
vR2 = head $ M.toRows $ rotMatrixHSH (unN n) r p
tc = V.imap (\i x -> abs $ magnitude $ x - (vC2 M.@> i) ) vC1
tr = V.imap (\i x -> abs $ magnitude $ x - (vR2 M.@> i) ) vR1
in max (V.maximum tc) (V.maximum tr)
rotHSHRow0 :: N -> SO3 -> Vector (Complex Double)
rotHSHRow0 n r = let
l = (unN n) `quot` 2
z = genSHFunc (2*l) r
func (lb, mu) = let
k1 = sqrt 2 * pi / (fromIntegral $ 2*l+1)
z1 = conjugate $ z %! (N (2*l), L lb, MF mu)
in (k1 :+ 0) * z1
ps = V.fromList [ (lb, mu) | lb <- [0 .. 2*l], mu <- [lb, lb-1 .. (-lb)] ]
in V.map func ps
rotHSHCol0 :: N -> SO3 -> Vector (Complex Double)
rotHSHCol0 n r = let
l = (unN n) `quot` 2
z = genSHFunc (2*l) r
func (lb, mu) = let
k1 = (-1)^lb * sqrt 2 * pi / (fromIntegral $ 2*l+1)
z1 = z %! (N (2*l), L lb, MF mu)
in (k1 :+ 0) * z1
ps = V.fromList [ (lb, mu) | lb <- [0 .. 2*l], mu <- [lb, lb-1 .. (-lb)] ]
in V.map func ps
| lostbean/sphermonics | src/Texture/SH/RotationSO4.hs | gpl-3.0 | 12,547 | 0 | 18 | 3,219 | 5,098 | 2,746 | 2,352 | 227 | 2 |
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
{-# LANGUAGE ForeignFunctionInterface #-}
module MEnv.Foreign.IOS
(
foreignBeginForeign,
foreignHandleForeignEnd,
) where
import MyPrelude
import MEnv
import Foreign.C
-- | start Foreign
foreignBeginForeign :: MEnv res ()
foreignBeginForeign =
io $ ios_foreignBeginForeign
foreign import ccall unsafe "ios_foreignBeginForeign" ios_foreignBeginForeign
:: IO ()
-- | handle end of Foreign
foreignHandleForeignEnd :: a -> a -> MEnv res a
foreignHandleForeignEnd a a' =
io $ ios_foreignHandleForeignEnd >>= \value -> case value of
0 -> return a
_ -> return a'
foreign import ccall unsafe "ios_foreignHandleForeignEnd" ios_foreignHandleForeignEnd
:: IO CUInt
| karamellpelle/grid | source/MEnv/Foreign/IOS.hs | gpl-3.0 | 1,464 | 0 | 10 | 282 | 168 | 100 | 68 | 20 | 2 |
{-# LANGUAGE OverloadedStrings, DeriveGeneric, TupleSections #-}
module StandOff.External.StandoffModeDump
( StandoffModeRange(..)
, StandoffModeAnnotations(..)
, runJsonParser
, elDump
, runELispDumpParser
)
where
-- | This module provides functions for parsing external annotations
-- that where generated in Emacs' standoff-mode.
import GHC.Generics
import Data.Time
import Data.UUID.Types hiding (nil)
import qualified Data.Aeson as A
import Data.Aeson ((.:))
import qualified Data.Aeson.Types as A
import Control.Applicative ((<|>))
import Text.Read (readMaybe)
import Text.Parsec hiding ((<|>))
import qualified Data.ByteString.Lazy as BS
import System.IO
import qualified Data.Map as Map
import Data.Maybe
import StandOff.TextRange
import StandOff.External
-- * Data type
-- | A record for markup ranges from Emacs' standoff-mode.
data StandoffModeRange
= StandoffModeRange -- ^ range of characters in source file
{ somr_id :: Maybe UUID -- ^ the UUID of the range
, somr_elementId :: UUID -- ^ the UUID of the element to which the range belongs
, somr_type :: String -- ^ the annotation type
, somr_start :: Int -- ^ the start character offset
, somr_end :: Int -- ^ the end character offset
, somr_createdAt :: Maybe UTCTime -- ^ a unix timestamp
, somr_createdBy :: Maybe String -- ^ the annotator's user name
-- | For internal use:
, somr_splitNum :: Maybe Int -- ^ number of the split
}
deriving (Show)
instance TextRange (StandoffModeRange) where
start = somr_start
end = somr_end
split _ range (e1, s2) = (range {somr_end = e1}, range {somr_start = s2})
instance ToAttributes StandoffModeRange where
attributes r = Map.fromList $ catMaybes
[ Just ("id", (show $ somr_elementId r)) -- "id" is used by 'GenericMarkup'
, Just ("tagger", "standoff-mode")
, (fmap (("rangeId",) . show ) $ somr_id r)
, Just ("elementId", (show $ somr_elementId r))
, Just ("type", somr_type r)
, (fmap (("createdAt",) . show) $ somr_createdAt r)
, (fmap ("createdBy",) $ somr_createdBy r)
]
instance IdentifiableSplit StandoffModeRange where
markupId = Just . show . somr_elementId
splitNum = somr_splitNum
updSplitNum r i = r { somr_splitNum = Just i }
-- | A record for representing the contents of standoff-mode's
-- external markup. Note: This is incomplete, since we parse
-- interesting stuff only.
data StandoffModeAnnotations
= StandoffModeAnnotations
{ som_md5sum :: String
, som_ranges :: [StandoffModeRange]
}
deriving (Show, Generic)
-- * Parsing JSON files
instance A.FromJSON StandoffModeRange where
parseJSON (A.Object v) = StandoffModeRange
<$> v .: "markupRangeId"
<*> v .: "markupElementId"
<*> v .: "qualifiedName"
<*> (fmap (\x -> x - 1) $ ((v .: "sourceStart") <|> (fmap (assertInt . readMaybe) $ v .: "sourceStart")))
<*> (fmap (\x -> x - 2) $ ((v .: "sourceEnd") <|> (fmap (assertInt . readMaybe) $ v .: "sourceEnd")))
<*> (fmap readFormattedTime $ v .: "createdAt")
<*> v .: "createdBy"
<*> pure Nothing
where
assertInt Nothing = 0
assertInt (Just i) = i
parseJSON invalid = A.typeMismatch "Object" invalid
-- | Parse the formatted time in "createdAt"
readFormattedTime :: String -> Maybe UTCTime
readFormattedTime s = parseTimeM True defaultTimeLocale "%Y-%m-%dT%H:%M:%S%Z" s
instance A.FromJSON StandoffModeAnnotations where
parseJSON = A.genericParseJSON A.defaultOptions { A.fieldLabelModifier = somJsonFields }
where
somJsonFields :: String -> String
somJsonFields "som_md5sum" = "md5sum"
somJsonFields "som_ranges" = "MarkupRanges"
somJsonFields s = s
-- | Parse all 'StandoffModeRange' objects found in IO 'Handle'.
runJsonParser :: Handle -> IO [StandoffModeRange]
runJsonParser h = do
c <- BS.hGetContents h
let ann = A.decode c :: Maybe StandoffModeAnnotations
-- TODO: Wrap the result in GADT.
return $ maybe [] id $ fmap som_ranges ann
-- * Parsing elisp dump files
uuid :: Parsec String () UUID
uuid = do
char '"'
hyphened <- count 36 $ oneOf $ '-':['a'..'h']++['0'..'9']
char '"'
case fromString(hyphened) of
Just valid -> return valid
Nothing -> error $ "Not a valid UUID: " ++ hyphened
timeStamp :: Parsec String () String
timeStamp = do
char '('
t <- manyTill (digit <|> space) $ char ')'
return t
escape :: Parsec String () String
escape = do
d <- char '\\'
c <- oneOf "\\\"\0\n\r\v\t\b\f"
return [d, c]
nonEscape :: Parsec String () Char
nonEscape = noneOf "\\\"\0\n\r\v\t\b\f"
quoteChar :: Parsec String () String
quoteChar = fmap return nonEscape <|> escape <|> (many1 space)
quoteString :: Parsec String () String
quoteString = do
char '"'
s <- many $ try quoteChar
char '"'
return $ concat s
nil :: Parsec String () [StandoffModeRange]
nil = do
spaces
string "nil"
spaces
return []
markupRange :: Parsec String () StandoffModeRange
markupRange = do
char '('
spaces
elemId <- uuid
spaces
rangeId <- optionMaybe $ try uuid
spaces
typ <- quoteString
spaces
start <- manyTill digit space
end <- manyTill digit space
txt <- quoteString
spaces
optional $ try timeStamp
spaces
optional $ try quoteString
spaces
char ')'
spaces
return $ StandoffModeRange
{ somr_id = rangeId
, somr_elementId = elemId
, somr_type = typ
-- Emacs starts with col 1, so -1 for start offset.
, somr_start = ((read start)::Int) - 1
-- Emacs starts with col 1 and standoff-mode
-- defines the ranges end at the following
-- char, so -2 for end offset.
, somr_end = ((read end)::Int) - 2
, somr_createdBy = Nothing -- FIXME
, somr_createdAt = Nothing -- FIXME
, somr_splitNum = Nothing
}
markupRanges :: Parsec String () [StandoffModeRange]
markupRanges = do
spaces
char '('
spaces
rs <- many markupRange
spaces
char ')'
return rs
relation :: Parsec String () ()
relation = do
char '('
spaces
firstUuid <- uuid
spaces
secondUuid <- optionMaybe $ try uuid
spaces
predicat <- quoteString
spaces
obj <- uuid
spaces
optional $ try timeStamp
spaces
optional $ try quoteString
spaces
char ')'
spaces
return ()
relations :: Parsec String () [StandoffModeRange]
relations = do
spaces
char '('
rels <- many relation
char ')'
spaces
return []
elDump :: Parsec String () [StandoffModeRange]
elDump = do
spaces
string "(setq standoff-markup-read-function-dumped (quote"
ranges <- try markupRanges <|> try nil
string "))"
spaces
string "(setq standoff-relations-read-function-dumped (quote"
rels <- try relations <|> try nil
string "))"
-- FIXME: parse literal predicates etc., too.
skipMany anyChar
return $ ranges++rels
-- | Run the dump parser in the IO monad.
runELispDumpParser :: Handle -> IO [StandoffModeRange]
runELispDumpParser h = do
contents <- hGetContents h
return $ either (fail . (err++) . show) id $ parse elDump (show h) contents
where
err = "Error parsing ELisp dump (" ++ (show h) ++ "): "
-- | Parse annotations.
--
-- Usage:
-- > runhaskell DumpFile.hs < INFILE
main :: IO ()
main = do
rc <- runELispDumpParser stdin
-- c <- BS.getContents
-- let rc = A.decode c :: Maybe StandoffModeAnnotations
print rc
| lueck/standoff-tools | src/StandOff/External/StandoffModeDump.hs | gpl-3.0 | 7,350 | 0 | 21 | 1,603 | 2,061 | 1,059 | 1,002 | 201 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Example where
import Data.Data
import Data.Typeable
import Control.Applicative
import GHC.Generics
data Foo = Foo deriving (Data, Typeable, Show, Generic)
data Bar = Bar deriving (Data, Typeable, Show, Generic)
data Baz = Baz [Foo] (Bar, Bar) deriving (Data, Typeable, Show, Generic)
data Input = Input Int deriving (Data, Typeable, Show, Generic)
data Output = Output Double deriving (Data, Typeable, Show, Generic)
data Tx = Tx [Input] [Output] deriving (Data, Typeable, Show, Generic)
newtype Size a = Size { unSize :: Int }
plus :: Size a -> Size b -> Size c
plus (Size s0) (Size s1) = Size (s0 + s1)
sumFields :: Data a => a -> Size a
sumFields baz = gfoldl step fcstr baz
where
step :: forall d b. Data d => Size (d -> b) -> d -> Size b
step tot d = tot `plus` sumFields d
fcstr :: forall g. g -> Size g
fcstr _ = Size 0
newtype TypeReps a = TypeReps { getTypes :: [TypeRep] } deriving (Show)
(<++>) :: TypeReps a -> TypeReps b -> TypeReps c
(TypeReps xs) <++> (TypeReps ys) = TypeReps (xs ++ ys) -- TODO: we could use a more efficient structure.
typeReps :: (Data a, Typeable a) => a -> TypeReps a
typeReps a = gfoldl step fcstr a
where
step :: forall d b. Data d => TypeReps (d -> b) -> d -> TypeReps b
step tot d = tot <++> typeReps d
fcstr :: forall g . g -> TypeReps g
fcstr g = TypeReps [typeOf a]
-- This won't work either!
typeReps2 :: forall a. (Typeable a, Data a) => a -> [TypeRep]
typeReps2 = getConst . gfoldl app constr where
-- app :: [TypeRep] -> d -> [TypeRep] -- informal type
-- app :: Data d => Const [TypeRep] _ -> d -> Const [TypeRep] _ -- actual type
--
-- Collect the types from the field d and append them to the result.
app (Const tys) d = Const (tys ++ typeReps2 d)
-- constr :: _ -> Const [TypeRep] _
--
-- Starting state: we have to at least collect the current type.
-- The argument of constr is the constructor of the value we are traversing,
-- it is useless here because we don't want to construct anything.
constr _ = Const [typeOf (undefined :: a)]
--------------------------------------------------------------------------------
-- Attempt using generics
--------------------------------------------------------------------------------
class Typeable a => HasTypeReps a where
typeReps3 :: a -> [TypeRep]
default typeReps3 :: (Generic a, GHasTypeReps (Rep a)) => a -> [TypeRep]
typeReps3 a = typeOf a: gTypeReps (from a)
class GHasTypeReps f where
gTypeReps :: f a -> [TypeRep]
instance GHasTypeReps U1 where
gTypeReps U1 = []
instance (GHasTypeReps a, GHasTypeReps b) => GHasTypeReps (a :*: b) where
gTypeReps (a :*: b) = gTypeReps a ++ gTypeReps b
instance (GHasTypeReps a, GHasTypeReps b) => GHasTypeReps (a :+: b) where
gTypeReps (L1 a) = gTypeReps a
gTypeReps (R1 b) = gTypeReps b
-- | We do need to do anything for the metadata.
instance (GHasTypeReps a) => GHasTypeReps (M1 i c a) where
gTypeReps (M1 x) = gTypeReps x
-- | And the only interesting case, get the type of a type constructor
instance (HasTypeReps a) => GHasTypeReps (K1 i a) where
gTypeReps (K1 x) = typeReps3 x
instance HasTypeReps a => HasTypeReps [a] where
typeReps3 xs = typeOf xs: concatMap typeReps3 xs
instance (HasTypeReps a, HasTypeReps b) => HasTypeReps (a, b) where
typeReps3 t@(a, b) = [typeOf t, typeOf a, typeOf b]
instance HasTypeReps Char where
typeReps3 x = [typeOf x]
instance HasTypeReps Int where
typeReps3 x = [typeOf x]
instance HasTypeReps Double where
typeReps3 x = [typeOf x]
instance HasTypeReps Input
instance HasTypeReps Output
instance HasTypeReps Tx
--------------------------------------------------------------------------------
-- https://stackoverflow.com/questions/54444559/get-all-the-typereps-in-a-value-using-generic-programming/54446912#54446912
--------------------------------------------------------------------------------
-- | Returns 'Just' only for lists
--
-- This can surely be done more efficiently, but it does the job.
listTypeReps :: Data a => a -> Maybe [TypeRep]
listTypeReps x
| typeRepTyCon (typeOf x) == listTyCon
, toConstr x == toConstr ([] :: [()]) -- empty list
= Just []
| typeRepTyCon (typeOf x) == listTyCon
, toConstr x == toConstr [()] -- cons
, [headTs, _] <- gmapQ typeReps4 x
, [_, Just tailTs] <- gmapQ listTypeReps x
= Just (headTs ++ tailTs)
| otherwise
= Nothing
listTyCon :: TyCon
listTyCon = typeRepTyCon (typeOf ([] :: [()]))
-- | Get the types of subterms
typeReps4 :: Data a => a -> [TypeRep]
typeReps4 x = typeOf x : case listTypeReps x of
Just ts -> ts
Nothing -> concat (gmapQ typeReps4 x)
| capitanbatata/sandbox | computing-abstract-sizes/src/Example.hs | gpl-3.0 | 5,095 | 0 | 12 | 1,093 | 1,550 | 810 | 740 | 90 | 2 |
module Dragonfly.Authorization.Authorities where
-- | Name of administrator group
administratorAuthority :: String
administratorAuthority = "admin"
-- | Capabilities known to always exist
knownCapabilities :: [String]
knownCapabilities = [readGalleryCapabilityName, uploadImageCapabilityName, administerGalleryCapabilityName]
-- | Authority to read galleries with no additional priviledges
readGalleryCapabilityName :: String
readGalleryCapabilityName = "readGalleryCapability"
-- | Authority to upload images to galleries with no additional priviledges
uploadImageCapabilityName :: String
uploadImageCapabilityName = "uploadImageCapability"
-- | Authority to adminster galleries with no additional priviledges
administerGalleryCapabilityName :: String
administerGalleryCapabilityName = "administerGalleryCapability"
| colin-adams/dragonfly-website | Dragonfly/Authorization/Authorities.hs | gpl-3.0 | 822 | 0 | 5 | 85 | 74 | 48 | 26 | 11 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.ContainerAnalysis.Projects.Notes.Occurrences.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists occurrences referencing the specified note. Provider projects can
-- use this method to get all occurrences across consumer projects
-- referencing the specified note.
--
-- /See:/ <https://cloud.google.com/container-analysis/api/reference/rest/ Container Analysis API Reference> for @containeranalysis.projects.notes.occurrences.list@.
module Network.Google.Resource.ContainerAnalysis.Projects.Notes.Occurrences.List
(
-- * REST Resource
ProjectsNotesOccurrencesListResource
-- * Creating a Request
, projectsNotesOccurrencesList
, ProjectsNotesOccurrencesList
-- * Request Lenses
, pnolXgafv
, pnolUploadProtocol
, pnolAccessToken
, pnolUploadType
, pnolName
, pnolFilter
, pnolPageToken
, pnolPageSize
, pnolCallback
) where
import Network.Google.ContainerAnalysis.Types
import Network.Google.Prelude
-- | A resource alias for @containeranalysis.projects.notes.occurrences.list@ method which the
-- 'ProjectsNotesOccurrencesList' request conforms to.
type ProjectsNotesOccurrencesListResource =
"v1beta1" :>
Capture "name" Text :>
"occurrences" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListNoteOccurrencesResponse
-- | Lists occurrences referencing the specified note. Provider projects can
-- use this method to get all occurrences across consumer projects
-- referencing the specified note.
--
-- /See:/ 'projectsNotesOccurrencesList' smart constructor.
data ProjectsNotesOccurrencesList =
ProjectsNotesOccurrencesList'
{ _pnolXgafv :: !(Maybe Xgafv)
, _pnolUploadProtocol :: !(Maybe Text)
, _pnolAccessToken :: !(Maybe Text)
, _pnolUploadType :: !(Maybe Text)
, _pnolName :: !Text
, _pnolFilter :: !(Maybe Text)
, _pnolPageToken :: !(Maybe Text)
, _pnolPageSize :: !(Maybe (Textual Int32))
, _pnolCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsNotesOccurrencesList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pnolXgafv'
--
-- * 'pnolUploadProtocol'
--
-- * 'pnolAccessToken'
--
-- * 'pnolUploadType'
--
-- * 'pnolName'
--
-- * 'pnolFilter'
--
-- * 'pnolPageToken'
--
-- * 'pnolPageSize'
--
-- * 'pnolCallback'
projectsNotesOccurrencesList
:: Text -- ^ 'pnolName'
-> ProjectsNotesOccurrencesList
projectsNotesOccurrencesList pPnolName_ =
ProjectsNotesOccurrencesList'
{ _pnolXgafv = Nothing
, _pnolUploadProtocol = Nothing
, _pnolAccessToken = Nothing
, _pnolUploadType = Nothing
, _pnolName = pPnolName_
, _pnolFilter = Nothing
, _pnolPageToken = Nothing
, _pnolPageSize = Nothing
, _pnolCallback = Nothing
}
-- | V1 error format.
pnolXgafv :: Lens' ProjectsNotesOccurrencesList (Maybe Xgafv)
pnolXgafv
= lens _pnolXgafv (\ s a -> s{_pnolXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
pnolUploadProtocol :: Lens' ProjectsNotesOccurrencesList (Maybe Text)
pnolUploadProtocol
= lens _pnolUploadProtocol
(\ s a -> s{_pnolUploadProtocol = a})
-- | OAuth access token.
pnolAccessToken :: Lens' ProjectsNotesOccurrencesList (Maybe Text)
pnolAccessToken
= lens _pnolAccessToken
(\ s a -> s{_pnolAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
pnolUploadType :: Lens' ProjectsNotesOccurrencesList (Maybe Text)
pnolUploadType
= lens _pnolUploadType
(\ s a -> s{_pnolUploadType = a})
-- | Required. The name of the note to list occurrences for in the form of
-- \`projects\/[PROVIDER_ID]\/notes\/[NOTE_ID]\`.
pnolName :: Lens' ProjectsNotesOccurrencesList Text
pnolName = lens _pnolName (\ s a -> s{_pnolName = a})
-- | The filter expression.
pnolFilter :: Lens' ProjectsNotesOccurrencesList (Maybe Text)
pnolFilter
= lens _pnolFilter (\ s a -> s{_pnolFilter = a})
-- | Token to provide to skip to a particular spot in the list.
pnolPageToken :: Lens' ProjectsNotesOccurrencesList (Maybe Text)
pnolPageToken
= lens _pnolPageToken
(\ s a -> s{_pnolPageToken = a})
-- | Number of occurrences to return in the list.
pnolPageSize :: Lens' ProjectsNotesOccurrencesList (Maybe Int32)
pnolPageSize
= lens _pnolPageSize (\ s a -> s{_pnolPageSize = a})
. mapping _Coerce
-- | JSONP
pnolCallback :: Lens' ProjectsNotesOccurrencesList (Maybe Text)
pnolCallback
= lens _pnolCallback (\ s a -> s{_pnolCallback = a})
instance GoogleRequest ProjectsNotesOccurrencesList
where
type Rs ProjectsNotesOccurrencesList =
ListNoteOccurrencesResponse
type Scopes ProjectsNotesOccurrencesList =
'["https://www.googleapis.com/auth/cloud-platform"]
requestClient ProjectsNotesOccurrencesList'{..}
= go _pnolName _pnolXgafv _pnolUploadProtocol
_pnolAccessToken
_pnolUploadType
_pnolFilter
_pnolPageToken
_pnolPageSize
_pnolCallback
(Just AltJSON)
containerAnalysisService
where go
= buildClient
(Proxy :: Proxy ProjectsNotesOccurrencesListResource)
mempty
| brendanhay/gogol | gogol-containeranalysis/gen/Network/Google/Resource/ContainerAnalysis/Projects/Notes/Occurrences/List.hs | mpl-2.0 | 6,514 | 0 | 19 | 1,467 | 964 | 558 | 406 | 136 | 1 |
----------------------------------------------------------------------
-- |
-- Module : Graphics.UI.Awesomium
-- Copyright : (c) 2012 Maksymilian Owsianny
-- License : LGPL-3 (see the file LICENSE)
--
-- Maintainer : Maksymilian.Owsianny+Awesomium@gmail.com
-- Stability : Experimental
-- Portability : Portable? (needs FFI)
--
----------------------------------------------------------------------
module Graphics.UI.Awesomium
( module Graphics.UI.Awesomium.WebCore
, module Graphics.UI.Awesomium.WebView
, module Graphics.UI.Awesomium.RenderBuffer
, module Graphics.UI.Awesomium.Resource
, module Graphics.UI.Awesomium.UploadElement
, module Graphics.UI.Awesomium.History
) where
import Graphics.UI.Awesomium.WebCore
import Graphics.UI.Awesomium.WebView
import Graphics.UI.Awesomium.RenderBuffer
import Graphics.UI.Awesomium.Resource
import Graphics.UI.Awesomium.UploadElement
import Graphics.UI.Awesomium.History
| MaxOw/awesomium | src/Graphics/UI/Awesomium.hs | lgpl-3.0 | 965 | 0 | 5 | 122 | 110 | 83 | 27 | 13 | 0 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE TemplateHaskell #-}
module ASTExpr where
import Generics.MultiRec.Base
import Generics.MultiRec.TH
-- * The AST type from the 'Generic Selections of Subexpressions' paper
-- -------------------------------
data Expr = EAdd Expr Expr
| EMul Expr Expr
| ETup Expr Expr
| EIntLit Int
| ETyped Expr Type
deriving (Eq, Show)
data Type = TyInt
| TyTup Type Type
deriving (Eq, Show)
-- ** Index type
data Tuples :: * -> * where
Expr :: Tuples Expr
Type :: Tuples Type
$(deriveAll ''Tuples)
{-
src/ASTExpr.hs:1:1: Splicing declarations
deriveAll ''Tuples
======>
src/ASTExpr.hs:37:3-20
data EAdd
data EMul
data ETup
data EIntLit
data ETyped
instance Constructor EAdd where
conName _ = "EAdd"
instance Constructor EMul where
conName _ = "EMul"
instance Constructor ETup where
conName _ = "ETup"
instance Constructor EIntLit where
conName _ = "EIntLit"
instance Constructor ETyped where
conName _ = "ETyped"
data TyInt
data TyTup
instance Constructor TyInt where
conName _ = "TyInt"
instance Constructor TyTup where
conName _ = "TyTup"
type instance PF Tuples =
:+: (:>: (:+: (C EAdd (:*: (I Expr) (I Expr))) (
:+: (C EMul (:*: (I Expr) (I Expr))) (
:+: (C ETup (:*: (I Expr) (I Expr))) (
:+: (C EIntLit (K Int))
(C ETyped ( :*: (I Expr) (I Type)))))))
Expr)
(:>:
(:+: (C TyInt U)
(C TyTup (:*: (I Type) (I Type))))
Type)
instance El Tuples Expr where
proof = Expr
instance El Tuples Type where
proof = Type
instance Fam Tuples where
from Expr (EAdd f0 f1)
= L (Tag (L (C ((:*:) ((I . I0) f0) ((I . I0) f1)))))
from Expr (EMul f0 f1)
= L (Tag (R (L (C ((:*:) ((I . I0) f0) ((I . I0) f1))))))
from Expr (ETup f0 f1)
= L (Tag (R (R (L (C ((:*:) ((I . I0) f0) ((I . I0) f1)))))))
from Expr (EIntLit f0) = L (Tag (R (R (R (L (C (K f0)))))))
from Expr (ETyped f0 f1)
= L (Tag (R (R (R (R (C ((:*:) ((I . I0) f0) ((I . I0) f1))))))))
from Type TyInt = R (Tag (L (C U)))
from Type (TyTup f0 f1)
= R (Tag (R (C ((:*:) ((I . I0) f0) ((I . I0) f1)))))
to Expr (L (Tag (L (C (:*: f0 f1)))))
= EAdd ((unI0 . unI) f0) ((unI0 . unI) f1)
to Expr (L (Tag (R (L (C (:*: f0 f1))))))
= EMul ((unI0 . unI) f0) ((unI0 . unI) f1)
to Expr (L (Tag (R (R (L (C (:*: f0 f1)))))))
= ETup ((unI0 . unI) f0) ((unI0 . unI) f1)
to Expr (L (Tag (R (R (R (L (C f0))))))) = EIntLit (unK f0)
to Expr (L (Tag (R (R (R (R (C (:*: f0 f1))))))))
= ETyped ((unI0 . unI) f0) ((unI0 . unI) f1)
to Type (R (Tag (L (C U)))) = TyInt
to Type (R (Tag (R (C (:*: f0 f1)))))
= TyTup ((unI0 . unI) f0) ((unI0 . unI) f1)
instance EqS Tuples where
eqS Expr Expr = Just Refl
eqS Type Type = Just Refl
eqS _ _ = Nothing
Ok, modules loaded: ASTExpr.
-}
| alanz/annotations-play | src/ASTExpr.hs | unlicense | 3,391 | 0 | 8 | 1,107 | 140 | 84 | 56 | 24 | 0 |
data Context = Home | Mobile | Business deriving (Eq, Show)
type Phone = String
rahul = [(Home, "123-123-1234"), (Mobile, "833-202-3233")]
milind = [(Mobile, "+91 8554036966"), (Business, "+91 20 1234 1234"), (Home, "+91 20 4565 3453"), (Business, "+91 20 2323 3434")]
anna = [(Business, "+260-23-1212")]
-- lookup :: Eq a => a -> [(a, b)] -> Maybe b
onePersonalPhone :: [(Context, Phone)] -> Maybe Phone
onePersonalPhone addressBook = case lookup Home addressBook of
Nothing -> lookup Mobile addressBook
Just n -> Just n
allBusinessPhones :: [(Context, Phone)] -> [Phone]
allBusinessPhones addressBook = map snd numbers
where numbers = case filter (isContext Business) addressBook of
[] -> filter(isContext Mobile) addressBook
bPhone -> bPhone
isContext phoneTypeToFind (phoneType, phone) = phoneTypeToFind == phoneType
| dongarerahul/lyah | chapter11-functorApplicativeMonad/AddressBook1.hs | apache-2.0 | 918 | 0 | 10 | 217 | 273 | 153 | 120 | 15 | 2 |
--import Prelude.Maybe hiding (Just, Nothing)
data Maybe' a = Just' a | Nothing'
instance Monad Maybe' where
--return :: a -> Maybe a
return x = Just' x
--(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing' >>= _ = Nothing'
Just' x >>= f = f x
newtype Parser a = P (String -> [(a, String)])
parse :: Parser a -> String -> [(a, String)]
parse (P p) inp = p inp
instance Monad Parser where
return v = P (\ inp -> [(v, inp)])
p >>= f = P (\ inp -> case parse p inp of
[] -> []
[(v, out)] -> parse (f v) out)
| dongarerahul/edx-haskell | maybe-state-monad.hs | apache-2.0 | 578 | 0 | 13 | 183 | 236 | 125 | 111 | 13 | 1 |
{-|
Module: Crypto.Spake2.Util
Description: Miscellany. Mostly to do with serialization.
-}
module Crypto.Spake2.Util
( expandData
, expandArbitraryElementSeed
, bytesToNumber
, numberToBytes
, unsafeNumberToBytes
) where
import Protolude
import Crypto.Hash.Algorithms (SHA256)
import Crypto.Number.Serialize (os2ip, i2ospOf, i2ospOf_)
import qualified Crypto.KDF.HKDF as HKDF
import Data.ByteArray (ByteArray, ByteArrayAccess(..))
-- | Take an arbitrary sequence of bytes and expand it to be the given number
-- of bytes. Do this by extracting a pseudo-random key and expanding it using
-- HKDF.
expandData :: (ByteArrayAccess input, ByteArray output) => ByteString -> input -> Int -> output
expandData info input size =
HKDF.expand prk info size
where
prk :: HKDF.PRK SHA256
prk = HKDF.extract salt input
-- XXX: I'm no crypto expert, but hard-coding an empty string as a salt
-- seems kind of weird.
salt :: ByteString
salt = ""
-- | Given a seed value for an arbitrary element (see 'arbitraryElement'),
-- expand it to be of the given length.
expandArbitraryElementSeed :: (ByteArrayAccess ikm, ByteArray out) => ikm -> Int -> out
expandArbitraryElementSeed =
-- NOTE: This must be exactly this string in order to interoperate with python-spake2
expandData "SPAKE2 arbitrary element"
-- | Serialize a number according to the SPAKE2 protocol.
--
-- Just kidding, there isn't a SPAKE2 protocol.
-- This just matches the Python implementation.
--
-- Inverse of 'bytesToNumber'.
numberToBytes :: ByteArray bytes => Int -> Integer -> Maybe bytes
numberToBytes = i2ospOf
-- | Serialize a number according to the SPAKE2 protocol.
--
-- Panics if the number is too big to fit into the given number of bytes.
unsafeNumberToBytes :: ByteArray bytes => Int -> Integer -> bytes
unsafeNumberToBytes = i2ospOf_
-- | Deserialize a number according to the SPAKE2 protocol.
--
-- Just kidding, there isn't a SPAKE2 protocol.
-- This just matches the Python implementation.
--
-- Inverse of 'numberToBytes'.
bytesToNumber :: ByteArrayAccess bytes => bytes -> Integer
bytesToNumber = os2ip
| jml/haskell-spake2 | src/Crypto/Spake2/Util.hs | apache-2.0 | 2,129 | 0 | 10 | 368 | 303 | 180 | 123 | 27 | 1 |
module Util where
import Control.Monad
import qualified Graphics.UI.GLFW as GLFW
import System.Exit
import System.IO
import Control.Concurrent (threadDelay)
-- Resize window
import qualified Graphics.Rendering.OpenGL as GL
import Graphics.Rendering.OpenGL (($=))
import Debug.Trace
-- type ErrorCallback = Error -> String -> IO ()
errorCallback :: GLFW.ErrorCallback
errorCallback _ = hPutStrLn stderr
keyCallback :: GLFW.KeyCallback
keyCallback window key _ action _ = when (key == GLFW.Key'Escape && action == GLFW.KeyState'Pressed) $
GLFW.setWindowShouldClose window True
-- | Resize the viewport and set the projection matrix
resize _ w h = do
-- These are all analogous to the standard OpenGL functions
GL.viewport $= (GL.Position 0 0, GL.Size (fromIntegral w) (fromIntegral h))
GL.matrixMode $= GL.Projection
GL.loadIdentity
GL.perspective 45 (fromIntegral w / fromIntegral h) 1 100
GL.matrixMode $= GL.Modelview 0
initialize :: String -> IO GLFW.Window
initialize title = do
GLFW.setErrorCallback (Just errorCallback)
successfulInit <- GLFW.init
-- if init failed, we exit the program
if not successfulInit then exitFailure else do
GLFW.windowHint $ GLFW.WindowHint'OpenGLDebugContext True
GLFW.windowHint $ GLFW.WindowHint'RedBits 8
GLFW.windowHint $ GLFW.WindowHint'GreenBits 8
GLFW.windowHint $ GLFW.WindowHint'BlueBits 8
GLFW.windowHint $ GLFW.WindowHint'DepthBits 1
mw <- GLFW.createWindow 640 480 title Nothing Nothing
case mw of
Nothing -> GLFW.terminate >> exitFailure
Just window -> do
GLFW.makeContextCurrent mw
GLFW.setKeyCallback window (Just keyCallback)
GLFW.setWindowSizeCallback window (Just resize)
return window
cleanup :: GLFW.Window -> IO ()
cleanup win = do
GLFW.destroyWindow win
GLFW.terminate
exitSuccess
mainLoop :: (Double -> IO ()) -> GLFW.Window -> Double -> IO ()
mainLoop draw w prev = do
close <- GLFW.windowShouldClose w
unless close $ do
Just now <- GLFW.getTime
draw now
GLFW.swapBuffers w
-- Sleep for the rest of the frame
frameLeft <- fmap (spf + prev -) $ return now
when (frameLeft > 0) $
trace (show frameLeft) (threadDelay (truncate $ 1000000 * frameLeft))
GLFW.pollEvents
mainLoop draw w now
where
-- maximum frame rate
fps = 60
spf = recip fps
| pharaun/hCraft | src/Util.hs | apache-2.0 | 2,633 | 0 | 17 | 740 | 715 | 347 | 368 | 57 | 3 |
-- Simple Interpreter
-- from The essence of functional programming by Philip Wadler
type Name = String
data Term = Var Name
| Con Int
| Add Term Term
| Lam Name Term
| App Term Term
data Value = Wrong
| Num Int
| Fun (Value -> M Value)
type Environment = [(Name, Value)]
showval :: Value -> String
showval Wrong = "Wrong"
showval (Num i) = show i
showval (Fun f) = "<function>"
interp :: Term -> Environment -> M Value
interp (Var x) e = envLookup x e
interp (Con i) e = unitM (Num i)
interp (Add u v) e = interp u e `bindM` (\a ->
interp v e `bindM` (\b ->
add a b))
interp (Lam x v) e = unitM (Fun (\a -> interp v ((x,a):e)))
interp (App t u) e = interp t e `bindM` (\f ->
interp u e `bindM` (\a ->
apply f a))
envLookup :: Name -> Environment -> M Value
envLookup x [] = unitM Wrong
envLookup x ((y,b):e) = if x==y then unitM b else envLookup x e
add :: Value -> Value -> M Value
add (Num i) (Num j) = unitM (Num (i+j))
add a b = unitM Wrong
apply :: Value -> Value -> M Value
apply (Fun k) a = k a
apply f a = unitM Wrong
test :: Term -> String
test t = showM (interp t [])
-- identity monad
type M a = a
unitM a = a
a `bindM` k = k a
showM a = showval a
term0 = (App (Lam "x" (Add (Var "x") (Var "x")))
(Add (Con 10) (Con 11)))
term1 = (App (Lam "x" (Add (Var "x") (Var "notfound")))
(Add (Con 10) (Con 11)))
main = do
putStrLn "Basic interpretter"
putStrLn $ test term0
putStrLn $ test term1
| cbare/Etudes | haskell/interpretter_00.hs | apache-2.0 | 1,678 | 0 | 13 | 583 | 786 | 406 | 380 | 47 | 2 |
-- Copyright 2016 TensorFlow authors.
--
-- 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.
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
-- | Tests for EmbeddingOps.
module Main where
import Control.Monad.IO.Class (liftIO)
import Data.Int (Int32, Int64)
import Data.List (genericLength)
import TensorFlow.EmbeddingOps (embeddingLookup)
import Test.Framework (defaultMain, Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit ((@=?))
import Test.Framework.Providers.HUnit (testCase)
import Test.QuickCheck (Arbitrary(..), Property, choose, vectorOf)
import Test.QuickCheck.Monadic (monadicIO, run)
import TensorFlow.Test (assertAllClose)
import qualified Data.Vector as V
import qualified TensorFlow.GenOps.Core as CoreOps
import qualified TensorFlow.Ops as TF
import qualified TensorFlow.Session as TF
import qualified TensorFlow.Tensor as TF
import qualified TensorFlow.Types as TF
import qualified TensorFlow.Gradient as TF
import qualified TensorFlow.Build as TF
-- | Tries to perform a simple embedding lookup, with two partitions.
testEmbeddingLookupHasRightShapeWithPartition :: Test
testEmbeddingLookupHasRightShapeWithPartition =
testCase "testEmbeddingLookupHasRightShapeWithPartition" $ do
let embShape = TF.Shape [1, 3] -- Consider a 3-dim embedding of two items.
let embedding1 = [1, 1, 1 :: Int32]
let embedding2 = [0, 0, 0 :: Int32]
let idValues = [0, 1 :: Int32]
(values, shape) <- TF.runSession $ do
embedding <- mapM TF.render [ TF.constant embShape embedding1
, TF.constant embShape embedding2
]
let ids = TF.constant (TF.Shape [1, 2]) idValues
vs <- embeddingLookup embedding ids
TF.run (vs, TF.shape vs)
-- This is the shape that is returned in the equiv. Python.
shape @=? V.fromList [1, 2, 3]
-- "[0, 1]" should pull out the resulting vector.
values @=? V.fromList [1, 1, 1, 0, 0, 0]
-- | Tries to perform a simple embedding lookup, with only a single partition.
testEmbeddingLookupHasRightShape :: Test
testEmbeddingLookupHasRightShape =
testCase "testEmbeddingLookupHasRightShape" $ do
-- Consider a 3-dim embedding of two items
let embShape = TF.Shape [2, 3]
let embeddingInit = [ 1, 1, 1
, 0, 0, 0 :: Int32
]
let idValues = [0, 1 :: Int32]
(values, shape) <- TF.runSession $ do
embedding <- TF.render $ TF.constant embShape embeddingInit
let ids = TF.constant (TF.Shape [1, 2]) idValues
vs <- embeddingLookup [embedding] ids
TF.run (vs, TF.shape vs)
-- This is the shape that is returned in the equiv. Python.
shape @=? V.fromList [1, 2, 3]
-- "[0, 1]" should pull out the resulting vector.
values @=? V.fromList [1, 1, 1, 0, 0, 0]
-- | Check that we can calculate gradients w.r.t embeddings.
testEmbeddingLookupGradients :: Test
testEmbeddingLookupGradients = testCase "testEmbeddingLookupGradients" $ do
-- Agrees with "embedding", so gradient should be zero.
let xVals = V.fromList ([20, 20 :: Float])
let shape = TF.Shape [2]
gs <- TF.runSession $ do
let embShape = TF.Shape [2, 1]
let embeddingInit = [1, 20 ::Float]
let idValues = [1, 1 :: Int32]
let ids = TF.constant (TF.Shape [1, 2]) idValues
x <- TF.placeholder (TF.Shape [2])
embedding <- TF.initializedVariable
(TF.constant embShape embeddingInit)
op <- embeddingLookup [embedding] ids
let twoNorm = CoreOps.square $ TF.abs (op `TF.sub` x)
loss = TF.mean twoNorm (TF.scalar (0 :: Int32))
grad <- fmap head (TF.gradients loss [embedding])
TF.runWithFeeds
[TF.feed x $ TF.encodeTensorData shape xVals]
grad
-- Gradients should be zero (or close)
assertAllClose gs (V.fromList ([0, 0 :: Float]))
-- Verifies that direct gather is the same as dynamic split into
-- partitions, followed by embedding lookup.
testEmbeddingLookupUndoesSplit ::
forall a. (TF.TensorDataType V.Vector a, Show a, Eq a)
=> LookupExample a -> Property
testEmbeddingLookupUndoesSplit
(LookupExample numParts
shape@(TF.Shape (firstDim : restDims))
values
indices) = monadicIO $ run $ TF.runSession $ do
let shapedValues = TF.constant shape values
indicesVector <- TF.render $ TF.vector indices
let directs = CoreOps.gather shapedValues indicesVector
let cyclicCounter :: TF.Tensor TF.Build Int32 =
TF.vector [0..fromIntegral firstDim-1]
`CoreOps.mod` fromIntegral numParts
modShardedValues :: [TF.Tensor TF.Value a] <-
mapM TF.render $ CoreOps.dynamicPartition numParts shapedValues cyclicCounter
embeddings <- embeddingLookup modShardedValues indicesVector
(shapeOut, got, want :: V.Vector a) <-
TF.run (TF.cast (TF.shape embeddings), embeddings, directs)
-- Checks the explicitly documented invariant of embeddingLookup.
liftIO $ shapeOut @=? V.fromList (genericLength indices : restDims)
liftIO $ got @=? want
testEmbeddingLookupUndoesSplit _ = error "Bug in Arbitrary (LookupExample)"
-- | Consistent set of parameters for EmbeddingLookupUndoesSplit.
data LookupExample a = LookupExample
Int64 -- ^ number of ways to split.
TF.Shape -- ^ shape of the generated tensor
[a] -- ^ data for the tensor
[Int32] -- ^ indices to split the tensor by
deriving Show
instance Arbitrary a => Arbitrary (LookupExample a) where
arbitrary = do
rank <- choose (1, 4)
-- Takes rank-th root of 100 to cap the tensor size.
let maxDim = fromIntegral (ceiling doubleMaxDim :: Int64)
doubleMaxDim :: Double
doubleMaxDim = 100 ** (1 / fromIntegral rank)
shape <- vectorOf rank (choose (1, maxDim))
let firstDim = head shape
values <- vectorOf (fromIntegral $ product shape) arbitrary
numParts <- choose (2, 15)
indSize <- choose (0, fromIntegral $ firstDim - 1)
indices <- vectorOf indSize (choose (0, fromIntegral firstDim - 1))
return $ LookupExample numParts (TF.Shape shape) values indices
main :: IO ()
main = defaultMain
[ testProperty "EmbeddingLookupUndoesSplit"
(testEmbeddingLookupUndoesSplit :: LookupExample Double -> Property)
, testEmbeddingLookupHasRightShape
, testEmbeddingLookupHasRightShapeWithPartition
, testEmbeddingLookupGradients
]
| tensorflow/haskell | tensorflow-ops/tests/EmbeddingOpsTest.hs | apache-2.0 | 7,343 | 77 | 12 | 1,860 | 1,601 | 917 | 684 | 120 | 1 |
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
module WaTor.Simulation
( step
) where
import Control.Applicative
import Control.Monad hiding (mapM)
import Data.Monoid
import Data.Traversable
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as MV
import Graphics.Gloss.Interface.IO.Simulate
import Prelude hiding (mapM)
import System.Random.MWC
import WaTor.Metrics
import WaTor.Movement
import WaTor.Random
import WaTor.Types
import WaTor.Utils
import WaTor.Vector
step :: GenIO -> Params -> ViewPort -> Float -> Simulation -> IO Simulation
step g p _ _ s@(Simulation ps _ _ wator@(WaTor t (V2D extent w))) = do
let counts@((fc, _), (sc, _), _) = getCounts wator
maybe (return ()) (logCounts wator counts) $ countLog ps
w' <- if fc == 0 && sc == 0
then mapM (const $ randomEntity g p) w
else return w
v' <- V2D extent <$> V.thaw w'
((`shuffle` g) $ V.zip indexes' w)
>>= V.mapM (uncurry (stepCell g ps extent v'))
>>= unless (quiet p) .
print . V.foldl' mappend mempty
v'' <- V.freeze $ v2dData v'
return $ s { wator = WaTor { time = t + 1
, world = V2D extent v''
}
}
where
indexes' = V.fromList $ indexes extent
stepCell :: GenIO
-> Params
-> Coord
-> Vector2D MV.IOVector Entity
-> Coord
-> Entity
-> IO StepSummary
stepCell g Params{..} extent v from f@Fish{} = do
current <- v !!? from
case current of
Just Fish{} -> do
ns <- neighborhoodEntities extent from v
moveEmpty g v from f' fishReproduce ns fishAge $ Fish 0
_ -> return mempty
where
f' = f { fishAge = fishAge f + 1 }
stepCell g Params{..} extent v from (Shark _ 0) = do
MV.write (v2dData v) (idx v from) Empty
return (mempty { sharksStarved = 1 })
stepCell g Params{..} extent v from s@Shark{} = do
ns <- neighborhoodEntities extent from v
mfish <- randomElem (filter (isFish . snd) ns) g
case mfish of
Just (to, Fish{}) ->
move v from to s'' sharkAge sharkReproduce child
_ -> moveEmpty g v from s' sharkReproduce ns sharkAge child
where
s' = Shark (sharkAge s + 1) (sharkEnergy s - 1)
s'' = s' { sharkEnergy = sharkEnergy s + fishBoost }
child = Shark 0 initEnergy
stepCell _ _ _ _ _ Empty = return mempty
move :: Vector2D MV.IOVector Entity
-> Coord
-> Coord
-> Entity
-> (Entity -> Chronon)
-> Chronon
-> Entity
-> IO StepSummary
move v2@(V2D _ v) from to entity getAge reproduceAge child = do
let child' = if (getAge entity `mod` reproduceAge) == 0
then child
else Empty
to' = idx v2 to
from' = idx v2 from
was <- MV.read v to'
MV.write v to' entity
MV.write v from' child'
return $ StepSum (if isFish child' && isFish entity then 1 else 0)
(if isFish was then 1 else 0)
(if isShark child' && isShark entity then 1 else 0)
0
update :: Vector2D MV.IOVector Entity -> Coord -> Entity -> IO StepSummary
update v2@(V2D _ v) coord entity =
MV.write v (idx v2 coord) entity >> return mempty
moveEmpty :: GenIO
-> Vector2D MV.IOVector Entity
-> Coord
-> Entity
-> Chronon
-> [(Coord, Entity)]
-> (Entity -> Chronon)
-> Entity
-> IO StepSummary
moveEmpty g v from curr repro ns getAge child =
randomElem (filter (isEmpty . snd) ns) g
>>= \case
Just (to, Empty) ->
move v from to curr getAge repro child
Just (_, Fish{}) -> update v from curr
Just (_, Shark{}) -> update v from curr
Nothing -> update v from curr
| erochest/wa-tor | src/WaTor/Simulation.hs | apache-2.0 | 4,174 | 5 | 17 | 1,545 | 1,447 | 738 | 709 | 105 | 5 |
module SqrtMultiples.A327953 (a327953, a327953_list) where
import Data.List (genericLength)
a327953 :: Integer -> Integer
a327953 n = genericLength $ recurse 2 ((n+1)^2 `div` 4) where
recurse m k
| k < 1 = []
| m^2 * k <= n^2 = recurse (m + 1) k
| m^2 * k >= upper = recurse m ((upper-1) `div` m^2)
| otherwise = (m, k) : recurse m (k - 1) where
upper = (n+1)^2
a327953_list :: [Integer]
a327953_list = map a327953 [1..]
| peterokagey/haskellOEIS | src/SqrtMultiples/A327953.hs | apache-2.0 | 467 | 0 | 13 | 126 | 247 | 131 | 116 | 12 | 1 |
-- Copyright 2020 Google LLC
--
-- 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.
{-# LANGUAGE CPP #-}
module Main(main) where
import HeadersLib (bar)
import Control.Monad (guard)
#include "header_provider.h"
foo = FOO
main = do
guard (foo == 42)
guard (bar == 17)
| google/cabal2bazel | bzl/tests/ffi/HeadersTest.hs | apache-2.0 | 783 | 0 | 9 | 141 | 78 | 50 | 28 | 8 | 1 |
module LogAnalysis where
import Data.Char
import Log
parseMessage :: String -> LogMessage
parseMessage str@(prefix:_:rhs@(timestamp:_:rest))
| prefix == 'I' = LogMessage Info (digitToInt timestamp) rest
| prefix == 'E' = parseError rhs
| prefix == 'W' = LogMessage Warning (digitToInt timestamp) rest
| otherwise = Unknown str
-- Just parse the errors.
-- Example: E 70 3 Way too many pickles
parseError :: String -> LogMessage
parseError (severity:_:timestamp:rest) = LogMessage (Error (digitToInt severity)) (digitToInt timestamp) rest | markmandel/cis194 | src/week3/homework/LogAnalysis.hs | apache-2.0 | 568 | 0 | 13 | 105 | 193 | 98 | 95 | 11 | 1 |
-- http://www.codewars.com/kata/54492291ec342c4a440008c5
module Combinations where
import Data.List
combinations :: Int -> [a] -> [[a]]
combinations n = filter ((==n) . length) . subsequences | Bodigrim/katas | src/haskell/B-Combinations.hs | bsd-2-clause | 193 | 0 | 9 | 24 | 58 | 34 | 24 | 4 | 1 |
-- Euler project with haskell solutions
module Euler where
import Data.List
import Data.Char
import Data.Array
import Data.Scientific (fromRationalRepetend, formatScientific, FPFormat(..))
import Data.Ratio ((%))
import Data.Function (on)
import Numeric (showIntAtBase)
-- $setup
-- >>> import Control.Applicative
-- >>> import Test.QuickCheck
-- >>> newtype Small = Small Int deriving Show
-- >>> instance Arbitrary Small where arbitrary = Small . (`mod` 100) <$> arbitrary
-- problem 18
inputp18 :: [[Integer]]
inputp18 =
[ [75]
, [95, 64]
, [17, 47, 82]
, [18, 35, 87, 10]
, [20, 04, 82, 47, 65]
, [19, 01, 23, 75, 03, 34]
, [88, 02, 77, 73, 07, 63, 67]
, [99, 65, 04, 28, 06, 16, 70, 92]
, [41, 41, 26, 56, 83, 40, 80, 70, 33]
, [41, 48, 72, 33, 47, 32, 37, 16, 94, 29]
, [53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14]
, [70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57]
, [91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48]
, [63, 66, 04, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31]
, [04, 62, 98, 27, 23, 09, 70, 98, 73, 93, 38, 53, 60, 04, 23]]
p18 :: [[Integer]] -> Integer
p18 = maximum . foldl1' cojoin
where
cojoin acc new =
let
fstnum = zipWith (+) acc (init new)
sndnum = zipWith (+) acc (tail new)
part = (zipWith max (tail fstnum) (init sndnum))
in head fstnum : part ++ [last sndnum]
-- problem 67
p67 :: IO ()
p67 = do
out <- readFile "src/assets/p67.txt"
let out' = (map . map) read . map words . lines $ out
print $ p18 out'
-- problem 19
data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec deriving (Eq, Show, Bounded, Ord, Enum)
type Day = Int
type Year = Int
type Date = (Year, Month, Day)
makeDate :: Year -> Month -> Day -> Maybe Date
makeDate year mon day =
let days =
if mon `elem` [Jan, Mar, May, Jul, Aug, Oct, Dec]
then 31
else if mon `elem` [Apr, Jun, Sep, Nov]
then 30
else if (mod year 4 == 0 && mod year 100 /= 0) ||
(mod year 400 == 0 && mod year 100 == 0)
then 29
else 28
in if (0 < year) && (0 < day) && (day <= days)
then Just (year, mon, day)
else Nothing
p19 :: IO ()
p19 = do
let join acc Nothing = acc
join acc (Just x) = x:acc
dates = foldl' join []
(makeDate <$> [1900..2000] <*> [Jan .. Dec] <*> [1..31])
week = cycle [1..7]
output = filter (\((year, _, da), we) ->
year >= 1901 && da == 1 && we == 7)
(zip (sort dates) week)
print (length output)
-- p20
p20 :: Integer -> Integer
p20 upper =
sum . map (\x -> read [x]) . show . product $ [1..upper]
-- p21
-- it's slow, maybe should remove lookup part
p21 :: Integer -> [Integer]
p21 n =
let
dvalue n' = sum . filter (\x -> mod n' x == 0) $ [1..n'-1]
dvalues = map dvalue [1..n]
pairAmi = filter (not . uncurry (==)) . zip [1..n] $ dvalues
check (x, xpair) acc = case lookup xpair pairAmi of
Nothing -> acc
Just y -> if y == x then x : acc else acc
numAmi = foldr check [] pairAmi
in numAmi
-- problem 22
nameBase :: String -> Integer
nameBase = toInteger . sum . map ord'
where ord' c = ord c - ord 'A' + 1
p22 :: IO ()
p22 = do
text <- readFile "src/assets/p22.txt"
let input = map nameBase . sort . read $ text
print . sum $ (zipWith (*) input [1..])
-- problem 23
-- Too much time spent here
-- should avoid `elem` for large lists
-- try use Data.array (learn form google)
divisorsum :: Integer -> Integer
divisorsum num = if num == 1 then 1 else sum . init . divs $ num
where divs n =
let r = floor . sqrt . fromIntegral $ n
(a, b) = unzip $ [(q, d) | q<-[1..r], let (d, r') = quotRem n q, r' == 0]
in if r*r == n then a ++ (tail (reverse b))
else a ++ reverse b
p23' :: IO ()
p23'= do
let upper = 28123
aboundNumbers = filter (\x -> x < divisorsum x) [1..upper]
-- aboundSums = makesum <$> aboundNumbers <*> aboundNumbers
out = filter (\x -> any (`elem` aboundNumbers) (map (\y -> y-x) aboundNumbers)) [1..upper]
print (sum [1..upper] - (sum out))
p23 :: IO ()
p23 = do
let
upper = 28123
aboundNumbers = listArray (1, upper) (map (\x -> x < divisorsum x) [1..upper])
abounds = filter (aboundNumbers !) [1..upper]
remainders x = map (x-) $ takeWhile (\y -> y <= x `quot` 2) abounds
aboundSum = filter (any (aboundNumbers !) . remainders) [1..upper]
out = (sum [1..upper]) - (sum aboundSum)
print out
-- problem 24
p24 :: String
p24 = last . take 1000000 . sort . permutations $ ['0'..'9']
-- problem 25
fibs :: [Integer]
fibs = 0:1:(zipWith (+) fibs (tail fibs))
p25 :: IO ()
p25 = do
let digitstest = (==1000) . length . show
(_, a:_) = break (digitstest . snd) (zip [0..] fibs)
print a
-- problem 26
fractions :: Integer -> String
fractions n =
let go (x:xs) acc = if x `elem` acc then acc else go xs (x:acc)
go [] acc = acc
in case fromRationalRepetend Nothing (1 % n) of
Right (sci, _) -> formatScientific Fixed Nothing sci
Left (sci, _) -> formatScientific Fixed Nothing sci
p26 :: IO ()
p26 =
-- putStrLn . show . maximumBy (compare `on` (length . fractions)) $ [1..1000]
-- putStrLn . show . maximum . zip (map (length . fractions) [1..1000]) $ [1..]
print . maximumBy (compare `on` (length . fractions)) $ [1..1000]
-- copy from github, this works too
-- but i can't figure out why
cycleLength :: Integer -> Integer
cycleLength n | even n = 0
| n `rem` 5 == 0 = 0
| otherwise = head [p | p <- [1..], (10^p - 1) `rem` n == 0]
p26' :: IO ()
p26' = print $ maximumBy (compare `on` cycleLength) [1,3..1000]
-- problem 27
isPrimes :: Array Integer Bool
isPrimes =
let ar = listArray (0, 1000000) (False:False:True:(map helper [3..1000000]))
helper n = all (\x -> mod n x /= 0) [p | p <- [2..(floor . sqrt . fromIntegral $ n)], ar ! p]
in ar
quadraticsForm :: Integer -> Integer -> Integer
quadraticsForm a b =
let f x = x^2 + a * x + b
in toInteger . length $ takeWhile (isPrimes !) (map (abs . f) [0..])
p27 :: IO ()
p27 = do
let limit = 1000
cojoin x y = ((x, y), quadraticsForm x y)
out = cojoin <$> [(-limit) .. limit] <*> [(-limit) .. limit]
print $ maximumBy (compare `on` snd) out
-- problem 28
p28 :: Int -> Int
p28 n =
let split' :: [Int] -> [Int] -> [[Int]]
split' (a:as) bs =
let (acc,left) = splitAt a bs
in acc : split' as left
split' _ _ = []
cycleGet :: Int -> [Int] -> [Int]
cycleGet n xs =
let (a, left) = splitAt n xs
in if n > length xs then []
else (last a) : cycleGet n left
ind = [1..n]
lens = map (8*) ind
oneSize = map (2*) ind
in (+1) . sum . concat . zipWith cycleGet oneSize . split' lens $ [2..(2*n+1)^2]
-- prblem 29
p29 :: [Integer] -> [Integer] -> Int
p29 xs ys = length . nub $ (^) <$> xs <*> ys
-- p29 [2..100] [2..100]
-- problem 30
-- the fifth power of 9 * 6 = 354294 < 10^6, so the maximum bound is 10^6
p30 :: [Integer]
p30 = filter go [2..10^6]
where go n = (==n) . sum . map (\x -> (read [x])^5) . show $ n
-- sum p30
-- problem 31
-- 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).
-- should walk through all possiable combinations for n
p31 :: Int -> Maybe Int
p31 n =
let coins = [1,2,5,10,20,50,100,200]
maxbound = map (\x -> [0 .. (div n x)]) coins
cojoin = map helper . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
where helper xs = case (unzip xs) of
(a:_, b) -> (a, sum b)
_ -> error "conflicts with condition"
f (co, li) acc = cojoin $ g <$> li <*> acc
where g li' (acc', fre) = (co*li'+acc', fre)
in lookup n (foldr f [(0,1)] (zip coins maxbound))
-- problem 32 TODO
-- inspired by source code for permutations
-- selections :: [a] -> [(a, [a])]
-- selections [] = []
-- selections (x:xs) = (x, xs):[(y, x:ys) | (y, ys) <- selections xs]
-- group3 :: [a] -> [([a],[a],[a])]
-- group3 [] = [([],[],[])]
-- group3 [x] = [([],[],[x])]
-- group3 [x, y] = [([],[],[x,y]), ([],[],[y,x]), ([],[x],[y]), ([],[y],[x])]
-- group3 xs = concat [[(a:a', b:b', c'), (a', b', a:b:c'), (a', b:b', a:c'), (a:a',b',b:c')] |
-- (a, as) <- selections xs,
-- (b, bs) <- selections as,
-- (a', b', c') <- group3 bs]
-- toInt xs = sum $ zipWith (*) xs [10^i | i<- [0..]]
-- p32 = filter test . group3 $ [1..9]
-- where
-- notnull = not . null
-- test (as, bs, cs) = (notnull as) && (notnull bs) && (notnull cs) &&
-- length as <= length cs && length bs <= length cs &&
-- (toInt as) * (toInt bs) == (toInt cs)
-- test xs = [(x, y, zs) |
-- (x, ys) <- selections xs,
-- (y, zs) <- selections ys]
-- problem 34
-- since 9! = 362880*6 < 10^6, so the upper bound must be 10^6
p34 :: [Integer]
p34 = filter checkp34 [10 .. (10^6)]
where factorial :: Integer -> Integer
factorial n = product [1..n]
checkp34 :: Integer -> Bool
checkp34 n =
(==n) . sum . map (factorial . read . (:[])) . show $ n
-- problem 35
-- circular isPrimes, note the isPrimes has just bounds [0,1000000]
p35 :: [Integer]
p35 = filter checkCicular (filter (isPrimes !) [2..1000000])
where checkCicular :: Integer -> Bool
checkCicular n = all (isPrimes !) (rotations n)
rotations n =
let ns = map (read . (:[])) . show $ n
len = length ns
toInt xs = sum $ zipWith (*) [10^i | i<-[0..]] (reverse xs)
new ind =
let (a, b) = splitAt ind ns
in toInt (b ++ a)
in map new [1..len-1]
-- problem 36
p36 :: Integer
p36 = sum . filter palindNum $ [1..1000000]
where palindromic xs = xs == (reverse xs)
palindNum n = all palindromic [showIntAtBase 10 intToDigit n "",
showIntAtBase 2 intToDigit n ""]
-- problem 37
p37 :: [Integer]
p37 = take 11 . filter truncatablePrime . filter (isPrimes !) $ [11..]
where truncatablePrime = all (isPrimes !) . deletes
deletes n =
let ns = map (read . (:[])) . show $ n
goleft [] = []
goleft al@(_:xs) = al : goleft xs
goright = map reverse . goleft . reverse
toInt xs = sum $ zipWith (*) [10^i | i<-[0..]] (reverse xs)
in map toInt (goleft (tail ns) ++ goright (init ns))
-- problem 38
-- the maximum bound is 987654321
p38 :: [(Bool, Maybe String)]
p38 = sortBy (compare `on` snd) . filter fst . map pandigital $ [1..9876]
where
pandigital :: Int -> (Bool, Maybe String)
pandigital n =
let ns = map (show . (n*)) [1..9]
out = dropWhile ((/="123456789") . sort) . map (concat . flip take ns) $ [2..length ns]
in if null out then (False, Nothing) else (True, Just (head out))
-- problem 39
-- m must be bigger than 3
p39 :: Int -> (Int, Int)
p39 m =
let tris n = [(a,b,c) | c <- [(div n 3) .. (div n 2)]
, b <- [(div n 4)..c]
, let a = n-c-b
, a < b
, 0 < a
, a^2+b^2==c^2]
in maximumBy (compare `on` snd) . map (\x -> (x, length . tris $ x)) $ [1..m]
-- problem 40
-- simple, just concate the number
p40 :: Int
p40 =
let ns = concatMap show [1..]
ind = [1, 10, 100, 1000, 10000, 100000, 1000000]
in product (map (digitToInt . (ns !!) . (\x -> x-1)) ind)
-- problem 41
-- time consume too much, so i just chek from take 1 numbers, take 2 numbers, and then stop at 7
p41 :: [Integer]
p41 = filter (\n -> n `elem` (takeWhile (<=n) isPrimes')) .
map toInt . permutations . reverse . take 7 $ [1..9]
-- note that permutations itself generate number in ordering if input are ordering
where toInt xs = sum $ zipWith (*) [10^i | i<-[0..]] (reverse xs)
isPrimes' = 2:3:(filter check [5,7..])
where check n = all (\x -> mod n x /= 0) (takeWhile (< cir) isPrimes')
where cir = floor . sqrt . fromIntegral $ n
-- problem 42
p42 :: IO ()
p42 = do
out <- readFile "src/assets/p42.txt"
let ns = [(n+1)*n `div` 2 | n <- [1..]]
inns n = (==n) . head . dropWhile (<n) $ ns
wordValue = sum . map (\c -> ord c - ord 'A' + 1)
content = filter inns . map wordValue . read $ out
print $ length content
-- preblem 43
p43 :: Int
p43 = sum . map toInt . filter subdiv . permutations $ [0..9]
where toInt xs = sum $ zipWith (*) [10^i | i<-[0..]] (reverse xs)
subdiv xs = go (tail xs) [2,3,5,7,11,13,17]
where go _ [] = True
go (x:y:z:zs) (a:as) = rem (toInt (x:y:z:[])) a == 0 &&
go (y:z:zs) as
go _ _ = False
-- problem 44 TODO
-- pentagon = map (\n -> div (n*(3*n-1)) 2) [1..]
-- checkpentagon n = (n `elem`) . takeWhile (<=n) $ pentagon
-- -- test (i, j) = (checkpentagon (i+j) || checkpentagon (i-j))
-- popTwo :: [(Int, Int)]
-- popTwo = [(i, j) | i <- pentagon
-- , j <- takeWhile (<= (limit i)) pentagon
-- , i < j]
-- where limit n = div (n+1) 3 -1
-- | Use doctest to test results
-- | this is just for init
--
-- prop> \(Small n) -> fib n == fib (n+2) - fib (n+1)
fib :: Int -> Int
fib n =
let fibs = 0:1:(zipWith (+) fibs (tail fibs))
in fibs !! n
| niexshao/Exercises | src/Euler.hs | bsd-3-clause | 13,466 | 0 | 18 | 3,944 | 5,446 | 2,995 | 2,451 | 266 | 5 |
-- Copyright : (C) 2009 Corey O'Connor
-- License : BSD-style (see the file LICENSE)
module Bind.Marshal.StaticProperties where
import Bind.Marshal.Prelude
import Bind.Marshal.Action.Base
import Bind.Marshal.Action.Static
import Bind.Marshal.DataModel
import Bind.Marshal.DesAction.Base
import Bind.Marshal.SerAction.Base
marshalled_byte_count :: forall buffer_iter_tag size out_type
. ( Nat size )
=> StaticMemAction buffer_iter_tag size out_type -> Size
marshalled_byte_count _action = toInt (undefined :: size)
| coreyoconnor/bind-marshal | src/Bind/Marshal/StaticProperties.hs | bsd-3-clause | 579 | 0 | 8 | 120 | 98 | 62 | 36 | -1 | -1 |
module CloudWatchTests.Util
( testCloudWatch
)
where
import Control.Monad.Trans.Resource(ResourceT, runResourceT)
import Data.Text (Text)
import Cloud.AWS.CloudWatch
testCloudWatch
:: Text
-> CloudWatch (ResourceT IO) a
-> IO a
testCloudWatch region request = do
runResourceT $ runCloudWatch $ do
setRegion region
request
| worksap-ate/aws-sdk | test/CloudWatchTests/Util.hs | bsd-3-clause | 369 | 0 | 10 | 85 | 99 | 53 | 46 | 13 | 1 |
{-# LANGUAGE TupleSections, PatternGuards, ExistentialQuantification #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Utilities (
module IdSupply,
module Utilities,
module Control.Arrow,
module Control.DeepSeq,
module Control.Monad,
module Data.Maybe,
module Data.List,
module Debug.Trace,
module Text.PrettyPrint.HughesPJClass
) where
import IdSupply
import StaticFlags
import Control.Arrow (first, second, (***), (&&&))
import Control.DeepSeq (NFData(..), rnf)
import Control.Monad
import Data.Maybe
import Data.List
import qualified Data.Map as M
import qualified Data.Set as S
import Data.Time.Clock.POSIX (getPOSIXTime)
import Debug.Trace
import Text.PrettyPrint.HughesPJClass hiding (render, int, char)
import qualified Text.PrettyPrint.HughesPJClass as Pretty
import System.IO
import System.IO.Unsafe (unsafePerformIO)
instance NFData Id where
rnf i = rnf (hashedId i)
type Tag = Int
injectTag :: Int -> Tag -> Tag
injectTag cls tg = cls * tg
data Tagged a = Tagged { tag :: Tag, tagee :: a }
deriving (Eq, Show)
instance NFData a => NFData (Tagged a) where
rnf (Tagged a b) = rnf a `seq` rnf b
instance Functor Tagged where
fmap f (Tagged tg x) = Tagged tg (f x)
instance Pretty a => Pretty (Tagged a) where
pPrintPrec level prec (Tagged tg x) = braces (pPrint tg) <+> pPrintPrec level prec x
instance Show IdSupply where
show = show . idFromSupply
instance Pretty Doc where
pPrint = id
instance Pretty Id where
pPrint = text . show
instance Pretty a => Pretty (S.Set a) where
pPrint xs = braces $ hsep (punctuate comma (map pPrint $ S.toList xs))
instance (Pretty k, Pretty v) => Pretty (M.Map k v) where
pPrint m = brackets $ fsep (punctuate comma [pPrint k <+> text "|->" <+> pPrint v | (k, v) <- M.toList m])
fmapSet :: (Ord a, Ord b) => (a -> b) -> S.Set a -> S.Set b
fmapSet f = S.fromList . map f . S.toList
fmapMap :: (Ord a, Ord b) => (a -> b) -> M.Map a v -> M.Map b v
fmapMap f = M.fromList . map (first f) . M.toList
restrict :: Ord k => M.Map k v -> S.Set k -> M.Map k v
restrict m s = M.filterWithKey (\k _ -> k `S.member` s) m
exclude :: Ord k => M.Map k v -> S.Set k -> M.Map k v
exclude m s = M.filterWithKey (\k _ -> k `S.notMember` s) m
{-# NOINLINE parseIdSupply #-}
parseIdSupply :: IdSupply
parseIdSupply = unsafePerformIO $ initIdSupply 'a'
{-# NOINLINE reduceIdSupply #-}
reduceIdSupply :: IdSupply
reduceIdSupply = unsafePerformIO $ initIdSupply 'u'
{-# NOINLINE tagIdSupply #-}
tagIdSupply :: IdSupply
tagIdSupply = unsafePerformIO $ initIdSupply 't'
{-# NOINLINE prettyIdSupply #-}
prettyIdSupply :: IdSupply
prettyIdSupply = unsafePerformIO $ initIdSupply 'p'
{-# NOINLINE matchIdSupply #-}
matchIdSupply :: IdSupply
matchIdSupply = unsafePerformIO $ initIdSupply 'm'
stepIdSupply :: IdSupply -> (IdSupply, Id)
stepIdSupply = second idFromSupply . splitIdSupply
data Train a b = Wagon a (Train a b)
| Caboose b
appPrec, opPrec, noPrec :: Rational
appPrec = 2 -- Argument of a function application
opPrec = 1 -- Argument of an infix operator
noPrec = 0 -- Others
normalLevel, haskellLevel :: PrettyLevel
normalLevel = PrettyLevel 0
haskellLevel = PrettyLevel 1
angles, coangles :: Doc -> Doc
angles d = Pretty.char '<' <> d <> Pretty.char '>'
coangles d = Pretty.char '>' <> d <> Pretty.char '<'
pPrintPrec' :: Pretty a => a -> PrettyLevel -> Rational -> Doc
pPrintPrec' x level prec = pPrintPrec level prec x
-- NB: this render function is exported instead of the one from the library
render :: Doc -> String
render = renderStyle (style { lineLength = 120 })
pPrintRender :: Pretty a => a -> String
pPrintRender = render . pPrint
panic :: String -> Doc -> a
panic s d = error $ s ++ ": " ++ render d
traceRender :: Pretty a => a -> b -> b
traceRender x | qUIET = id
| otherwise = trace (pPrintRender x)
assertRender :: Pretty a => a -> Bool -> b -> b
assertRender _ _ x | not aSSERTIONS = x
assertRender _ True x = x
assertRender a False _ = error (pPrintRender a)
removeOnes :: [a] -> [[a]]
removeOnes [] = []
removeOnes (x:xs) = xs : map (x:) (removeOnes xs)
accumL :: (acc -> (acc, a)) -> acc -> Int -> (acc, [a])
accumL f = go
where
go acc n | n <= 0 = (acc, [])
| (acc, x) <- f acc = second (x:) (go acc (n - 1))
instance (Pretty a, Pretty b, Pretty c, Pretty d,
Pretty e, Pretty f, Pretty g, Pretty h,
Pretty i) => Pretty (a, b, c, d, e, f, g, h, i) where
pPrint (a, b, c, d, e, f, g, h, i)
= pPrintTuple [pPrint a, pPrint b, pPrint c, pPrint d,
pPrint e, pPrint f, pPrint g, pPrint h,
pPrint i]
instance (Pretty a, Pretty b, Pretty c, Pretty d,
Pretty e, Pretty f, Pretty g, Pretty h,
Pretty i, Pretty j) => Pretty (a, b, c, d, e, f, g, h, i, j) where
pPrint (a, b, c, d, e, f, g, h, i, j)
= pPrintTuple [pPrint a, pPrint b, pPrint c, pPrint d,
pPrint e, pPrint f, pPrint g, pPrint h,
pPrint i, pPrint j]
instance (Pretty a, Pretty b, Pretty c, Pretty d,
Pretty e, Pretty f, Pretty g, Pretty h,
Pretty i, Pretty j, Pretty k) => Pretty (a, b, c, d, e, f, g, h, i, j, k) where
pPrint (a, b, c, d, e, f, g, h, i, j, k)
= pPrintTuple [pPrint a, pPrint b, pPrint c, pPrint d,
pPrint e, pPrint f, pPrint g, pPrint h,
pPrint i, pPrint j, pPrint k]
instance (Pretty a, Pretty b, Pretty c, Pretty d,
Pretty e, Pretty f, Pretty g, Pretty h,
Pretty i, Pretty j, Pretty k, Pretty l,
Pretty m, Pretty n, Pretty o) => Pretty (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) where
pPrint (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o)
= pPrintTuple [pPrint a, pPrint b, pPrint c, pPrint d,
pPrint e, pPrint f, pPrint g, pPrint h,
pPrint i, pPrint j, pPrint k, pPrint l,
pPrint m, pPrint n, pPrint o]
pPrintTuple :: [Doc] -> Doc
pPrintTuple ds = parens $ fsep $ punctuate comma ds
data SomePretty = forall a. Pretty a => SomePretty a
instance Pretty SomePretty where
pPrintPrec level prec (SomePretty x) = pPrintPrec level prec x
newtype PrettyFunction = PrettyFunction (PrettyLevel -> Rational -> Doc)
instance Pretty PrettyFunction where
pPrintPrec level prec (PrettyFunction f) = f level prec
asPrettyFunction :: Pretty a => a -> PrettyFunction
asPrettyFunction = PrettyFunction . pPrintPrec'
fst3 :: (a, b, c) -> a
fst3 (a, _, _) = a
snd3 :: (a, b, c) -> b
snd3 (_, b, _) = b
thd3 :: (a, b, c) -> c
thd3 (_, _, c) = c
first3 :: (a -> d) -> (a, b, c) -> (d, b, c)
first3 f (a, b, c) = (f a, b, c)
second3 :: (b -> d) -> (a, b, c) -> (a, d, c)
second3 f (a, b, c) = (a, f b, c)
third3 :: (c -> d) -> (a, b, c) -> (a, b, d)
third3 f (a, b, c) = (a, b, f c)
second4 :: (b -> e) -> (a, b, c, d) -> (a, e, c, d)
second4 f (a, b, c, d) = (a, f b, c, d)
third4 :: (c -> e) -> (a, b, c, d) -> (a, b, e, d)
third4 f (a, b, c, d) = (a, b, f c, d)
secondM :: Monad m => (b -> m c) -> (a, b) -> m (a, c)
secondM f (a, b) = liftM (a,) $ f b
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 f (a, b, c) = f a b c
splitBy :: [b] -> [a] -> ([a], [a])
splitBy [] xs = ([], xs)
splitBy (_:ys) (x:xs) = first (x:) $ splitBy ys xs
splitManyBy :: [[b]] -> [a] -> [[a]]
splitManyBy [] xs = [xs]
splitManyBy (ys:yss) xs = case splitBy ys xs of (xs1, xs2) -> xs1 : splitManyBy yss xs2
takeFirst :: (a -> Bool) -> [a] -> (Maybe a, [a])
takeFirst p = takeFirstJust (\x -> guard (p x) >> return x)
takeFirstJust :: (a -> Maybe b) -> [a] -> (Maybe b, [a])
takeFirstJust _ [] = (Nothing, [])
takeFirstJust p (x:xs)
| Just y <- p x = (Just y, xs)
| otherwise = second (x:) $ takeFirstJust p xs
expectJust :: String -> Maybe a -> a
expectJust _ (Just x) = x
expectJust s Nothing = error $ "expectJust: " ++ s
safeFromLeft :: Either a b -> Maybe a
safeFromLeft (Left x) = Just x
safeFromLeft _ = Nothing
safeHead :: [a] -> Maybe a
safeHead [] = Nothing
safeHead (x:_) = Just x
expectHead :: String -> [a] -> a
expectHead s = expectJust s . safeHead
uncons :: [a] -> Maybe (a, [a])
uncons [] = Nothing
uncons (x:xs) = Just (x, xs)
fixpoint :: Eq a => (a -> a) -> a -> a
fixpoint f x
| x' == x = x
| otherwise = fixpoint f x'
where x' = f x
zipWithEqualM :: Monad m => (a -> b -> m c) -> [a] -> [b] -> m [c]
zipWithEqualM _ [] [] = return []
zipWithEqualM f (x:xs) (y:ys) = liftM2 (:) (f x y) (zipWithEqualM f xs ys)
zipWithEqualM _ _ _ = fail "zipWithEqualM"
zipWithEqualM_ :: Monad m => (a -> b -> m ()) -> [a] -> [b] -> m ()
zipWithEqualM_ _ [] [] = return ()
zipWithEqualM_ f (x:xs) (y:ys) = f x y >> zipWithEqualM_ f xs ys
zipWithEqualM_ _ _ _ = fail "zipWithEqualM_"
zipWithEqual :: (a -> b -> c) -> [a] -> [b] -> Maybe [c]
zipWithEqual _ [] [] = Just []
zipWithEqual f (x:xs) (y:ys) = fmap (f x y :) $ zipWithEqual f xs ys
zipWithEqual _ _ _ = fail "zipWithEqual"
implies :: Bool -> Bool -> Bool
implies cond consq = not cond || consq
seperate :: Eq a => a -> [a] -> [[a]]
seperate c = go []
where
go sofar [] = [reverse sofar]
go sofar (x:xs)
| x == c = reverse sofar : go [] xs
| otherwise = go (x:sofar) xs
type Seconds = Double
time_ :: IO a -> IO Seconds
time_ = fmap fst . time
time :: IO a -> IO (Seconds, a)
time act = do { start <- getTime; res <- act; end <- getTime; return (end - start, res) }
getTime :: IO Seconds
getTime = (fromRational . toRational) `fmap` getPOSIXTime
type Bytes = Integer
fileSize :: FilePath -> IO Bytes
fileSize file = withFile file ReadMode hFileSize
| batterseapower/supercompilation-by-evaluation | Utilities.hs | bsd-3-clause | 9,807 | 0 | 14 | 2,519 | 4,692 | 2,524 | 2,168 | 231 | 2 |
{-# LANGUAGE BangPatterns, FlexibleContexts, NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings, Rank2Types, TemplateHaskell #-}
module Lens where
import ClassyPrelude.Yesod
import Control.Lens
import Language.Haskell.Exts (Module (..), ModuleName, SrcLoc)
import Language.Haskell.Exts (ExportSpec)
import Language.Haskell.TH
import Yesod.Default.Util (WidgetFileSettings, widgetFileNoReload,
widgetFileReload)
class HasSrcLoc a where
_SrcLoc :: Lens' a SrcLoc
instance HasSrcLoc Module where
_SrcLoc =
lens
(\(Module l _ _ps _wt _mex _imp _ds) -> l)
(\(Module _ n ps wt mex imp ds) l -> (Module l n ps wt mex imp ds))
_ExportSpecs :: Lens' Module (Maybe [ExportSpec])
_ExportSpecs = lens
(\(Module _ _l _ps _wt mex _imp _ds) -> mex)
(\(Module l n ps wt _ imp ds) mex ->
Module l n ps wt mex imp ds)
_ModuleName :: Lens' Module ModuleName
_ModuleName =
lens
(\(Module _ l _ps _wt _mex _imp _ds) -> l)
(\(Module n _ ps wt mex imp ds) l -> (Module n l ps wt mex imp ds))
-- | Rules for making lenses and traversals that precompose another 'Lens'. that won't interfere with Yesod Scaffold
persistClassyRules :: LensRules
persistClassyRules = classyRules_
& generateSignatures .~ False
& generateUpdateableOptics .~ True
persistMakeClassy :: Name -> Q [Dec]
persistMakeClassy = makeLensesWith persistClassyRules
| konn/leport | leport-web/Lens.hs | bsd-3-clause | 1,414 | 0 | 10 | 290 | 420 | 229 | 191 | 33 | 1 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.DE.Rules
( rules ) where
import Control.Monad (join)
import Data.HashMap.Strict (HashMap)
import qualified Data.HashMap.Strict as HashMap
import Data.Maybe
import Data.Text (Text)
import qualified Data.Text as Text
import Prelude
import Data.String
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers
import Duckling.Numeral.Types (NumeralData (..))
import qualified Duckling.Numeral.Types as TNumeral
import Duckling.Regex.Types
import Duckling.Types
ruleNumeralsPrefixWithNegativeOrMinus :: Rule
ruleNumeralsPrefixWithNegativeOrMinus = Rule
{ name = "numbers prefix with -, negative or minus"
, pattern =
[ regex "-|minus|negativ"
, dimension Numeral
]
, prod = \tokens -> case tokens of
(_:Token Numeral (NumeralData {TNumeral.value = v}):_) ->
double $ v * (- 1)
_ -> Nothing
}
ruleIntegerNumeric :: Rule
ruleIntegerNumeric = Rule
{ name = "integer (numeric)"
, pattern =
[ regex "(\\d{1,18})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> do
v <- parseInt match
integer $ toInteger v
_ -> Nothing
}
ruleFew :: Rule
ruleFew = Rule
{ name = "few"
, pattern =
[ regex "mehrere"
]
, prod = \_ -> integer 3
}
ruleTen :: Rule
ruleTen = Rule
{ name = "ten"
, pattern =
[ regex "zehn"
]
, prod = \_ -> integer 10 >>= withGrain 1
}
ruleDecimalWithThousandsSeparator :: Rule
ruleDecimalWithThousandsSeparator = Rule
{ name = "decimal with thousands separator"
, pattern =
[ regex "(\\d+(\\.\\d\\d\\d)+\\,\\d+)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
let dot = Text.singleton '.'
comma = Text.singleton ','
fmt = Text.replace comma dot $ Text.replace dot Text.empty match
in parseDouble fmt >>= double
_ -> Nothing
}
ruleDecimalNumeral :: Rule
ruleDecimalNumeral = Rule
{ name = "decimal number"
, pattern =
[ regex "(\\d*,\\d+)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
parseDecimal False match
_ -> Nothing
}
ruleInteger3 :: Rule
ruleInteger3 = Rule
{ name = "integer ([2-9][1-9])"
, pattern =
[ regex "(ein|zwei|drei|vier|f\x00fcnf|sechs|sieben|acht|neun)und(zwanzig|dreissig|vierzig|f\x00fcnfzig|sechzig|siebzig|achtzig|neunzig)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:m2:_)):_) -> do
v1 <- case Text.toLower m1 of
"ein" -> Just 1
"zwei" -> Just 2
"drei" -> Just 3
"vier" -> Just 4
"f\x00fcnf" -> Just 5
"sechs" -> Just 6
"sieben" -> Just 7
"acht" -> Just 8
"neun" -> Just 9
_ -> Nothing
v2 <- case Text.toLower m2 of
"zwanzig" -> Just 20
"dreissig" -> Just 30
"vierzig" -> Just 40
"f\x00fcnfzig" -> Just 50
"sechzig" -> Just 60
"siebzig" -> Just 70
"achtzig" -> Just 80
"neunzig" -> Just 90
_ -> Nothing
integer $ v1 + v2
_ -> Nothing
}
ruleNumeralsUnd :: Rule
ruleNumeralsUnd = Rule
{ name = "numbers und"
, pattern =
[ numberBetween 1 10
, regex "und"
, oneOf [20, 30 .. 90]
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = v1}):
_:
Token Numeral (NumeralData {TNumeral.value = v2}):
_) -> double $ v1 + v2
_ -> Nothing
}
ruleMultiply :: Rule
ruleMultiply = Rule
{ name = "compose by multiplication"
, pattern =
[ dimension Numeral
, numberWith TNumeral.multipliable id
]
, prod = \tokens -> case tokens of
(token1:token2:_) -> multiply token1 token2
_ -> Nothing
}
ruleIntersect :: Rule
ruleIntersect = Rule
{ name = "intersect"
, pattern =
[ numberWith (fromMaybe 0 . TNumeral.grain) (>1)
, dimension Numeral
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = val1, TNumeral.grain = Just g}):
Token Numeral (NumeralData {TNumeral.value = val2}):
_) | (10 ** fromIntegral g) > val2 -> double $ val1 + val2
_ -> Nothing
}
ruleNumeralsSuffixesKMG :: Rule
ruleNumeralsSuffixesKMG = Rule
{ name = "numbers suffixes (K, M, G)"
, pattern =
[ dimension Numeral
, regex "([kmg])(?=[\\W\\$\x20ac]|$)"
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = v}):
Token RegexMatch (GroupMatch (match:_)):
_) -> case Text.toLower match of
"k" -> double $ v * 1e3
"m" -> double $ v * 1e6
"g" -> double $ v * 1e9
_ -> Nothing
_ -> Nothing
}
ruleCouple :: Rule
ruleCouple = Rule
{ name = "couple"
, pattern =
[ regex "(ein )?paar"
]
, prod = \_ -> integer 2
}
ruleDozen :: Rule
ruleDozen = Rule
{ name = "dozen"
, pattern =
[ regex "dutzend"
]
, prod = \_ -> integer 12 >>= withGrain 1 >>= withMultipliable
}
rulePowersOfTen :: Rule
rulePowersOfTen = Rule
{ name = "powers of tens"
, pattern =
[ regex "(hunderte?|tausende?|million(en)?)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"hundert" -> double 1e2 >>= withGrain 2 >>= withMultipliable
"hunderte" -> double 1e2 >>= withGrain 2 >>= withMultipliable
"tausend" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"tausende" -> double 1e3 >>= withGrain 3 >>= withMultipliable
"million" -> double 1e6 >>= withGrain 6 >>= withMultipliable
"millionen" -> double 1e6 >>= withGrain 6 >>= withMultipliable
_ -> Nothing
_ -> Nothing
}
zeroNineteenMap :: HashMap Text Integer
zeroNineteenMap = HashMap.fromList
[ ("keine", 0)
, ("null", 0)
, ("nichts", 0)
, ("keiner", 0)
, ("kein", 0)
, ("keins", 0)
, ("keinen", 0)
, ("keines", 0)
, ("einer", 1)
, ("eins", 1)
, ("ein", 1)
, ("eine", 1)
, ("einser", 1)
, ("zwei", 2)
, ("drei", 3)
, ("vier", 4)
, ("f\x00fcnf", 5)
, ("sechs", 6)
, ("sieben", 7)
, ("acht", 8)
, ("neun", 9)
, ("zehn", 10)
, ("elf", 11)
, ("zw\x00f6lf", 12)
, ("dreizehn", 13)
, ("vierzehn", 14)
, ("f\x00fcnfzehn", 15)
, ("sechzehn", 16)
, ("siebzehn", 17)
, ("achtzehn", 18)
, ("neunzehn", 19)
]
ruleToNineteen :: Rule
ruleToNineteen = Rule
{ name = "integer (0..19)"
-- e.g. fourteen must be before four,
-- otherwise four will always shadow fourteen
, pattern = [regex "(keine?|keine?s|keiner|keinen|null|nichts|eins?(er)?|zwei|dreizehn|drei|vierzehn|vier|f\x00fcnf|sechzehn|sechs|siebzehn|sieben|achtzehn|acht|neunzehn|neun|elf|zw\x00f6lf|f\x00fcfzehn)"]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
HashMap.lookup (Text.toLower match) zeroNineteenMap >>= integer
_ -> Nothing
}
ruleInteger :: Rule
ruleInteger = Rule
{ name = "integer (0..19)"
, pattern =
[ regex "(keine?|keine?s|keiner|keinen|null|nichts|eins?(er)?|zwei|dreizehn|drei|vierzehn|vier|f\x00fcnf|sechzehn|sechs|siebzehn|sieben|achtzehn|acht|neunzehn|neun|elf|zw\x00f6lf|f\x00fcfzehn)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"nichts" -> integer 0
"keine" -> integer 0
"null" -> integer 0
"keiner" -> integer 0
"kein" -> integer 0
"keins" -> integer 0
"keinen" -> integer 0
"keines" -> integer 0
"einer" -> integer 1
"eins" -> integer 1
"ein" -> integer 1
"eine" -> integer 1
"zwei" -> integer 2
"drei" -> integer 3
"vier" -> integer 4
"f\x00fcnf" -> integer 5
"sechs" -> integer 6
"sieben" -> integer 7
"acht" -> integer 8
"neun" -> integer 9
"zehn" -> integer 10
"elf" -> integer 11
"zw\x00f6lf" -> integer 12
"dreizehn" -> integer 13
"vierzehn" -> integer 14
"f\x00fcnfzehn" -> integer 15
"sechzehn" -> integer 16
"siebzehn" -> integer 17
"achtzehn" -> integer 18
"neunzehn" -> integer 19
_ -> Nothing
_ -> Nothing
}
ruleInteger2 :: Rule
ruleInteger2 = Rule
{ name = "integer (20..90)"
, pattern =
[ regex "(zwanzig|dreissig|vierzig|f\x00fcnfzig|sechzig|siebzig|achtzig|neunzig)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> case Text.toLower match of
"zwanzig" -> integer 20
"dreissig" -> integer 30
"vierzig" -> integer 40
"f\x00fcnfzig" -> integer 50
"sechzig" -> integer 60
"siebzig" -> integer 70
"achtzig" -> integer 80
"neunzig" -> integer 90
_ -> Nothing
_ -> Nothing
}
ruleNumeralDotNumeral :: Rule
ruleNumeralDotNumeral = Rule
{ name = "number dot number"
, pattern =
[ dimension Numeral
, regex "komma"
, numberWith TNumeral.grain isNothing
]
, prod = \tokens -> case tokens of
(Token Numeral (NumeralData {TNumeral.value = v1}):
_:
Token Numeral (NumeralData {TNumeral.value = v2}):
_) -> double $ v1 + decimalsToDouble v2
_ -> Nothing
}
ruleIntegerWithThousandsSeparator :: Rule
ruleIntegerWithThousandsSeparator = Rule
{ name = "integer with thousands separator ."
, pattern =
[ regex "(\\d{1,3}(\\.\\d\\d\\d){1,5})"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
parseDouble (Text.replace (Text.singleton '.') Text.empty match) >>= double
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleCouple
, ruleDecimalNumeral
, ruleDecimalWithThousandsSeparator
, ruleDozen
, ruleFew
, ruleInteger
, ruleInteger2
, ruleInteger3
, ruleIntegerNumeric
, ruleIntegerWithThousandsSeparator
, ruleIntersect
, ruleMultiply
, ruleNumeralDotNumeral
, ruleNumeralsPrefixWithNegativeOrMinus
, ruleNumeralsSuffixesKMG
, ruleNumeralsUnd
, rulePowersOfTen
, ruleTen
, ruleToNineteen
]
| rfranek/duckling | Duckling/Numeral/DE/Rules.hs | bsd-3-clause | 10,638 | 0 | 19 | 2,864 | 3,088 | 1,679 | 1,409 | 316 | 32 |
{-|
Module : Ch01
Description : 第1章 関数プログラミングとは何か
Copyright : (c) Shinya Yamaguchi, 2017
Stability : experimental
Portability : POSIX
-}
module Ch01 (
-- * 1.3 例題: 頻出単語 (p.17-p.20)
-- ** 型
Text, Word
-- ** 関数
, commonWords, sortWords, countRuns, sortRuns, showRun
-- * 1.4 例題: 数を言葉に変換する (p.20-p.25)
-- ** 関数
, convert, convert1, digits2, convert2, combine2, convert2', convert3, convert6, link
-- * 1.6 練習問題
-- ** 練習問題A
, double
-- ** 練習問題B
, ansB
-- ** 練習問題C
, ansC
-- ** 練習問題D
, ansD
-- ** 練習問題E
, ansE
-- ** 練習問題F
-- *** 型
, Label
-- *** 関数
, anagrams, showEntry
-- ** 練習問題G
, song
) where
import Prelude hiding (Word)
import Data.Char (toLower)
import Data.Ord (comparing)
import Data.List (sort, sortBy, sortOn, intersperse)
import Data.Char (toUpper)
-- 1.3 例題: 頻出単語
-- | 文章を表す型
type Text = [Char]
-- | 単語を表す型
type Word = [Char]
-- |
--
-- 文章中の単語数を返す
--
-- >>> showRun (2, "be")
-- " be: 2\n"
--
commonWords :: Int -> Text -> String
commonWords n = concat . map showRun . take n
. sortRuns . countRuns . sortWords
. words . map toLower
-- |
--
-- 単語のリストをアルファベット順にソートする
--
-- >>> sortWords ["to", "be", "or", "not", "to", "be"]
-- ["be","be","not","or","to","to"]
--
sortWords :: [Word] -> [Word]
sortWords = sort
-- |
--
-- 単語が何回連続して出現するかを数える
--
-- >>> countRuns ["be", "be", "not", "or", "to", "to"]
-- [(2,"be"),(1,"not"),(1,"or"),(2,"to")]
--
countRuns :: [Word] -> [(Int, Word)]
countRuns = foldr go []
where
go w [] = [(1, w)]
go w1 (l@(n, w2):ls) = if w1 == w2 then (n+1, w2):ls else (1, w1):l:ls
-- |
--
-- 単語を頻度の降順でソートする
--
-- >>> sortRuns [(2, "be"), (1, "not"), (1, "or"), (2, "to")]
-- [(2,"be"),(2,"to"),(1,"not"),(1,"or")]
--
sortRuns :: [(Int, Word)] -> [(Int, Word)]
sortRuns = sortBy (flip $ comparing fst)
-- |
--
-- 結果を整形する
--
-- >>> showRun (2, "be")
-- " be: 2\n"
--
showRun :: (Int, Word) -> String
showRun (n, w) = mconcat [" ", w, ": " , show n, "\n"]
-- 1.4 例題:数を言葉に変換する
-- |
--
-- 数を言葉に変換する
--
-- >>> convert 308000
-- "three hundred and eight thousand"
--
convert :: Int -> String
convert = convert6
units, teens, tens :: [String]
units = [ "zero", "one", "two", "three", "four", "five"
, "six", "seven", "eight", "nine"
]
teens = [ "ten", "eleven", "twelve", "thirteen", "fourteen"
, "fifteen", "sixteen", "seventeen", "eighteen"
, "nineteen"
]
tens = [ "twenty", "thirty", "forty", "fifty", "sixty"
, "seventy", "eighty", "ninety"
]
-- |
--
-- 与えられる数値が1桁 (0 <= n < 10) の場合
--
convert1 :: Int -> String
convert1 n = units !! n
-- |
--
-- 2桁の数値のそれぞれの値を求める
--
-- __定義のみで利用しない__
--
digits2 :: Int -> (Int, Int)
digits2 n = (n `div` 10, n `mod` 10)
-- |
--
-- ver.1 与えられる数値が2桁 (10 <= n < 100) の場合
--
-- __定義のみで利用しない__
--
convert2 :: Int -> String
convert2 = combine2 . digits2
-- |
--
-- 2つの数値を繋げて言葉に変換する
--
-- __定義のみで利用しない__
--
combine2 :: (Int, Int) -> String
combine2 (t, u)
| t == 0 = units !! u
| t == 1 = teens !! u
| 2 <= t && u == 0 = tens !! (t - 2)
| otherwise = tens !! (t - 2) ++ "-" ++ units !! u
-- |
--
-- ver.2 与えられる数値が2桁 (10 <= n < 100) の場合
--
convert2' :: Int -> String
convert2' n
| t == 0 = units !! u
| t == 1 = teens !! u
| u == 0 = tens !! (t - 2)
| otherwise = tens !! (t - 2) ++ "-" ++ units !! u
where
(t, u) = (n `div` 10, n `mod` 10)
-- |
--
-- 3桁までの数を言葉に変換する
--
convert3 :: Int -> String
convert3 n
| h == 0 = convert2' t
| t == 0 = units !! h ++ " hundred"
| otherwise = units !! h ++ " hundred and " ++ convert2' t
where
(h, t) = (n `div` 100, n `mod` 100)
-- |
--
-- 6桁までの数を言葉に変換する
--
convert6 :: Int -> String
convert6 n
| m == 0 = convert3 h
| h == 0 = convert3 m ++ " thousand"
| otherwise = convert3 m ++ " thousand" ++ link h ++ convert3 h
where
(m, h) = (n `div` 1000, n `mod` 1000)
-- |
--
-- 0 < m かつ 0 < h < 100 の場合に and でつなぐ関数
--
-- > (m, h) = (n `div` 1000, n `mod` 1000)
--
link :: Int -> String
link h = if h < 100 then " and " else " "
-- 1.6 練習問題
-- |
--
-- 整数を2倍する関数
--
-- >>> map double [1,4,4,3]
-- [2,8,8,6]
-- >>> map (double . double) [1,4,4,3]
-- [4,16,16,12]
-- >>> map double []
-- []
--
-- > sum :: [Integer] -> Integer
-- > map :: (a -> b) -> [a] -> [b]
-- > concat :: [[a]] -> [a]
-- > sort :: Ord a => [a] -> [a]
--
-- 以下の性質が成り立つ
--
-- prop> (sum $ map double xs) == (double $ sum xs)
-- prop> (sum $ map sum xs) == (sum $ concat xs)
-- prop> (sum $ sort xs) == (sum xs)
--
double :: Integer -> Integer
double = (2*)
-- |
--
-- =正しい Haskell の式はどれか?
--
-- == 正しい
-- > sin theta^2
-- > (sin theta)^2
-- == 間違い
-- > sin^2 theta
--
-- == 問題の答え
-- > sin (theta*2) / (2*pi)
--
-- == 以下は結合性により、求める結果とならないことに注意
-- > sin (2 * theta) / 2 * pi
--
ansB :: String
ansB = undefined
-- |
--
-- = 問題の答え
-- > 'H' :: Char
-- > "H" :: String
--
-- 2001は数値であり、"2001"は文字列。
--
-- >>> [1,2,3] ++ [3,2,1]
-- [1,2,3,3,2,1]
--
-- >>> "Hello" ++ " World!"
-- "Hello World!"
--
-- >>> [1,2,3] ++ []
-- [1,2,3]
--
-- >>> "Hello" ++ "" ++ "World!"
-- "HelloWorld!"
ansC :: String
ansC = undefined
-- |
--
-- = 問題の答え
--
-- すべてのテキスト中の文字をすべて小文字に変換してから、テキストを単語に分ける方法
-- > words . map toLower
--
-- 単語に分けてから小文字に変換する方法
--
-- > map (map toLower) . words
-- > words :: String -> [String]
-- > toLower :: Char -> Char
--
-- prop> (words $ map toLower xs) == (map (map toLower) $ words xs)
ansD :: String
ansD = undefined
-- |
--
-- = 問題の答え
--
-- (+) : 結合性を持つ (単位元: 0)
--
-- (++) : 結合性を持つ (単位元: [])
--
-- (.) : 結合性を持つ (単位元: id)
--
-- (/) : 結合性を持たない
--
-- prop> (x + (y + z)) == ((x + y) + z)
-- prop> (xs ++ (ys ++ zs)) == ((xs ++ ys) ++ zs)
ansE :: String
ansE = undefined
-- |
--
-- anagrams s はアルファベット順の英単語のリストを取り、n文字の単語だけを取り出し、文字列を生成する
--
anagrams :: Int -> [Word] -> String
anagrams n = concat . map showEntry . groupByLabel
. sortLabels . map addLabel . getWords n
-- |
--
-- 長さ n の単語を取り出す
--
-- >>> getWords 2 ["abc", "d", "efg", "hi", "j", "", "kl"]
-- ["hi","kl"]
getWords :: Int -> [Word] -> [Word]
getWords n = filter ((==n) . length)
-- | アナグラムのラベル
type Label = [Char]
-- |
--
-- ラベルを付ける関数 (ラベルは最初と最後を入れ替えた形式)
--
-- >>> addLabel "word"
-- ("dorw","word")
--
addLabel :: Word -> (Label, Word)
addLabel w = (l, w)
where
hw = head w
lw = last w
mw = tail $ init w
l = [lw] ++ mw ++ [hw]
-- |
--
-- ラベル付きの単語のリストをラベルのアルファベット順にソートする
--
-- >>> sortLabels [("dorw", "word"), ("abcd", "dbca")]
-- [("abcd","dbca"),("dorw","word")]
--
sortLabels :: [(Label, Word)] -> [(Label, Word)]
sortLabels = sortOn fst
-- |
--
-- 同じラベルの単語をまとめる
--
-- >>> groupByLabel [("dorw", "zzzz"), ("dorw", "eeee")]
-- [("dorw",["eeee","zzzz"])]
--
groupByLabel :: [(Label, Word)] -> [(Label, [Word])]
groupByLabel = init . foldl go e
where
e = [("", [])]
go [] _ = []
go list@((l1, w1):xs) (l2, w2) = if l1 == l2 then (l1, sort $ w2:w1):xs else (l2, [w2]):list
-- |
--
-- 対応表を文字列に変換し、連結する
--
-- >>> showEntry ("eginor", ["ignore", "region"])
-- "eginor: ignore,region"
showEntry :: (Label, [Word]) -> String
showEntry (l, ws) = l ++ ": " ++ (concat $ intersperse "," ws)
-- |
--
-- song n は n 人の男が登場する歌
--
song :: Int -> String
song n = if n == 0 then ""
else song (n-1) ++ "\n" ++ verse n
-- |
--
-- n 人目の段落の歌詞
--
verse :: Int -> String
verse n = (toUpperOnlyHead $ line1 n) ++ line2 ++ (toUpperOnlyHead $ line3 n) ++ line4
where
line1 1 = (num!!0) ++ " man went to mow\n"
line1 m = (num!!(m-1)) ++ " men went to mow\n"
line2 = "Went to mow a meadow\n"
line3 1 = (num!!0) ++ " man and his dog\n"
line3 m = (num!!(m-1)) ++ " men, " ++ line3 (m-1)
line4 = "Went to mow a meadow\n"
-- |
--
-- 数を言葉に変換
--
num :: [String]
num = ["one","two","three","four","five","six","seven","eight","nine"]
-- |
--
-- 先頭の文字だけ大文字にする
--
-- >>> toUpperOnlyHead "abc"
-- "Abc"
toUpperOnlyHead :: String -> String
toUpperOnlyHead [] = []
toUpperOnlyHead (c:cs) = toUpper c : cs
| waddlaw/TFwH | src/Ch01.hs | bsd-3-clause | 9,317 | 0 | 12 | 1,894 | 2,184 | 1,332 | 852 | 123 | 3 |
import Test.Hspec
import Test.QuickCheck
import Euler202
import Data.List
main :: IO ()
main = hspec $ do
describe "bounces" $ do
it "satisfies sample" $ do
bounces 11 `shouldBe` 2
bounces 7 `shouldBe` 2
bounces 17 `shouldBe` 0 -- is leaky
bounces 1000001 `shouldBe` 80840
describe "factorizes correctly" $ do
it "works" $ do
factorize 201235 `shouldBe` [5,167,241,835,1205,40247]
describe "leaky points" $ do
it "if point (x1, y1) is leaky on factor y1, then at interval of x1, every point (xi, y1) mapped to (xi', y) on Y is leaky" $ do
let hits = 100001
y = (hits + 1) `div` 2 + 1
startX = if even y then 6 else 3
cCount = if even y then (y-1) `div` 6 else (y + 1) `div` 6
ptXs = takeWhile (< y) [ startX + x * 6 | x <- [0..]]
y1 = last $ factorize y
division = y `div` y1
(Just x1) = findFirstLeakyX y ptXs y1
sampling = 15 in
(take sampling $ leakyPoints 1000001) `shouldBe` (take sampling $ leakyPoints1 1000001)
-- it "can then result in total leaky points projected from all factor Y" $ do
-- let hits = 1000001
-- Analysis { xs = xs, y = y, pointsCount = cCount } = analyze hits in
-- 2 * (cCount - (leakCount y xs)) `shouldBe` 80840
-- it "collision - when points from different Y share the same ratio, should calculate from less Y" $ do
-- let hits = 1000001
-- Analysis { xs = xs, y = y, pointsCount = cCount } = analyze hits
-- y1:y2:_ = reverse $ factorize y
-- [div1,div2] = map (y `div`) [y1,y2]
-- (Just x1) = findFirstLeakyX y xs y1
-- (Just x2) = findFirstLeakyX y xs y2 in
-- (take 2 $ findCollisions (x1 `div` div1, y1) (x2 `div` div2, y2)) `shouldBe` [((1, 1), (2,2))]
-- it "can also be done just using least common multiples of Xs on Y" $ do
-- let hits = 1000001
-- analysis@(Analysis { xs = xs, y = y, pointsCount = cCount }) = analyze hits
-- y1:y2:_ = reverse $ factorize y
-- [div1,div2] = map (y `div`) [y1,y2]
-- (Just x1) = findFirstLeakyX y xs y1
-- (Just x2) = findFirstLeakyX y xs y2
-- interval1 = intervalX x1 y
-- interval2 = intervalX x2 y in
-- (take 5 $ collisions analysis y1 y2) `shouldBe` (take 5 $ findCollisions (x1 `div` div1, y1) (x2 `div` div2, y2))
it "can get total of leaks" $ do
let hits = 1000001
analysis@(Analysis { yFactors = yFactors, xs = xs, y = y, pointsCount = cCount }) = analyze hits in
(map (leakTotalOnY analysis) yFactors) `shouldBe` 0 : (map (toInteger.length.(leaksOnY y xs)) yFactors)
it "shows the differences in leaks, diff by 2586" $ do
let hits = 1000001
analysis@(Analysis { yFactors = yFactors, xs = xs, y = y, pointsCount = cCount }) = analyze hits in
sum (map (leakTotalOnY analysis) yFactors) `shouldBe` (cCount - 80840 `div` 2)
it "shows the collisions" $ do
let hits = 1000001
analysis@(Analysis { yFactors = yFactors, xs = xs, y = y, pointsCount = cCount }) = analyze hits
zips = zip yFactors $ drop 1 yFactors
colls = map (\(y1, y2) -> collisionCounts analysis y1 y2) zips in
-- colls `shouldBe` []
sum colls `shouldBe` 2586
| hackle/euler | test/Euler202Spec.hs | bsd-3-clause | 3,719 | 1 | 22 | 1,371 | 749 | 406 | 343 | 41 | 3 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
module Monad.RelMonad where
class (Functor r, Monad m) => RelMonad r m where
rPoint :: r a -> m a
instance Monad m => RelMonad m m where
rPoint = id
| shmookey/pure | src/Monad/RelMonad.hs | bsd-3-clause | 232 | 0 | 8 | 48 | 71 | 37 | 34 | 7 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Data.Json.Visualization where
import qualified Data.Aeson as A (Value (String))
import qualified Data.Graph.Inductive as G
import qualified Data.GraphViz as GV
import qualified Data.GraphViz.Attributes.Complete as GV
import Data.Json.Util
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import Prelude as P
pToG :: PathsPropertyNameValue -> G.Gr T.Text ()
pToG = fst . uncurry G.mkMapGraph . foldr go ([],[])
where
go (path, (_,A.String value)) (nodes,edges) =
-- only use first part of path
let n1 = T.intercalate "/" (map (T.pack . P.show) (P.take 2 path))
n2 = T.drop 2 value -- do not include "#/"
in ( n1:n2 :nodes
, (n1,n2,()):edges
)
go _ acc = acc -- this should not happen
gToD :: G.Gr T.Text () -> GV.DotGraph G.Node
gToD = GV.graphToDot params
where
params = GV.nonClusteredParams
{ GV.fmtNode = \(_, l) -> [GV.Label $ GV.StrLabel (TL.fromStrict l)]
}
toDot :: PathsPropertyNameValue -> GV.DotGraph G.Node
toDot = gToD . pToG
| haroldcarr/data-json-validation | src/Data/Json/Visualization.hs | bsd-3-clause | 1,359 | 0 | 16 | 512 | 383 | 221 | 162 | 24 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE ImpredicativeTypes #-}
-----------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.SVG
-- Copyright : (c) 2011 diagrams-svg team (see LICENSE)
-- License : BSD-style (see LICENSE)
-- Maintainer : diagrams-discuss@googlegroups.com
--
-- Generic tools for generating SVG files.
--
-- cf. https://github.com/diagrams/diagrams-svg/blob/v1.3.1.10/src/Graphics/Rendering/SVG.hs
-----------------------------------------------------------------------------
module Graphics.Rendering.SVG
(SVGFloat
,Element
,AttributeValue
,svgHeader
,renderPath
,renderText
,renderStyles
,renderMiterLimit
,renderFillTexture
,renderLineTexture
,getNumAttr)
where
-- from base
import Data.List (intercalate)
#if __GLASGOW_HASKELL__ < 710
import Data.Foldable (foldMap)
#endif
import Data.Maybe (fromMaybe)
import Data.Monoid
-- from diagrams-core
import Diagrams.Core.Transform (matrixHomRep)
-- from diagrams-lib
import Diagrams.Prelude hiding (Attribute, Render, with, (<>), stroke, transform, text, width, height)
import Diagrams.TwoD.Path (getFillRule)
import Diagrams.TwoD.Text hiding (text)
-- from text
import Data.Text (pack)
import qualified Data.Text as T
-- from virtual-hom
import VirtualHom.Element (Elem, children, content)
import VirtualHom.Svg hiding (opacity, id)
import qualified VirtualHom.Svg as S
import qualified VirtualHom.Svg.Path as P
-- | Constaint on number type that diagrams-svg can use to render an SVG. This
-- includes the common number types: Double, Float
type SVGFloat n = (Show n, TypeableFloat n)
getNumAttr :: AttributeClass (a n) => (a n -> t) -> Style v n -> Maybe t
getNumAttr f = (f <$>) . getAttr
-- | @svgHeader w h defs s@: @w@ width, @h@ height,
-- @defs@ global definitions for defs sections, @s@ actual SVG content.
svgHeader :: SVGFloat n => forall a. n -> n -> Maybe Element -> [Element -> Element] -> [Element] -> Element
svgHeader w h defines attributes s = svg11
& children .~ ds ++ s
& width (P.toText w)
& height (P.toText h)
& font_size "1"
& viewBox (pack . unwords $ map show ([0, 0, round w, round h] :: [Int]))
& stroke "rgb(0, 0, 0)"
& stroke_opacity "1"
& (appEndo $ foldMap id (fmap Endo attributes))
where
ds = maybe mempty return defines
renderPath :: SVGFloat n => Path V2 n -> [Element]
renderPath trs =
if makePath == T.empty
then mempty
else [path_ & d makePath]
where
makePath = foldMap renderTrail (op Path trs)
renderTrail :: SVGFloat n => Located (Trail V2 n) -> AttributeValue
renderTrail (viewLoc -> (P (V2 x y),t)) =
P.mA x y <> withTrail renderLine renderLoop t
where
renderLine = foldMap renderSeg . lineSegments
renderLoop lp =
case loopSegments lp of
-- let z handle the last segment if it is linear
(segs,Linear _) -> foldMap renderSeg segs
-- otherwise we have to emit it explicitly
_ -> foldMap renderSeg (lineSegments . cutLoop $ lp) <> P.z
renderSeg :: SVGFloat n => Segment Closed V2 n -> AttributeValue
renderSeg (Linear (OffsetClosed (V2 x 0))) = P.hR x
renderSeg (Linear (OffsetClosed (V2 0 y))) = P.vR y
renderSeg (Linear (OffsetClosed (V2 x y))) = P.lR x y
renderSeg (Cubic (V2 x0 y0) (V2 x1 y1) (OffsetClosed (V2 x2 y2))) =
P.cR x0 y0 x1 y1 x2 y2
-- Render the gradient using the id set up in renderFillTextureDefs.
renderFillTexture :: SVGFloat n => Int -> Style v n -> [Attribute]
renderFillTexture ident s =
case getNumAttr getFillTexture s of
Just (SC (SomeColor c)) ->
renderTextAttr fill fillColorRgb <>
renderAttr fill_opacity fillColorOpacity
where fillColorRgb = Just $ colorToRgbText c
fillColorOpacity = Just $ colorToOpacity c
_ -> []
renderLineTexture :: SVGFloat n => Int -> Style v n -> [Attribute]
renderLineTexture ident s =
case getNumAttr getLineTexture s of
Just (SC (SomeColor c)) ->
renderTextAttr stroke lineColorRgb <>
renderAttr stroke_opacity lineColorOpacity
where lineColorRgb = Just $ colorToRgbText c
lineColorOpacity = Just $ colorToOpacity c
_ -> []
renderText :: SVGFloat n => Text n -> Element
renderText (Text tt tAlign str) = text
& transform transformMatrix
& dominant_baseline vAlign
& text_anchor hAlign
& stroke "none"
& content .~ T.pack str
where
vAlign =
case tAlign of
BaselineText -> "alphabetic"
BoxAlignedText _ h ->
case h -- A mere approximation
of
h'
| h' <= 0.25 -> "text-after-edge"
h'
| h' >= 0.75 -> "text-before-edge"
_ -> "middle"
hAlign =
case tAlign of
BaselineText -> "start"
BoxAlignedText w _ ->
case w -- A mere approximation
of
w'
| w' <= 0.25 -> "start"
w'
| w' >= 0.75 -> "end"
_ -> "middle"
t = tt `mappend` reflectionY
[[a,b],[c,d],[e,f]] = matrixHomRep t
transformMatrix = P.matrix a b c d e f
renderStyles :: SVGFloat n => Int -> Int -> Style v n -> [Attribute]
renderStyles fillId lineId s =
concatMap ($ s) $
[ renderLineTexture lineId
, renderFillTexture fillId
, renderLineWidth
, renderLineCap
, renderLineJoin
, renderFillRule
, renderDashing
, renderOpacity
, renderFontSize
, renderFontSlant
, renderFontWeight
, renderFontFamily
, renderMiterLimit]
renderMiterLimit :: Style v n -> [Attribute]
renderMiterLimit s = renderAttr stroke_miterlimit miterLimit
where
miterLimit = getLineMiterLimit <$> getAttr s
renderOpacity :: Style v n -> [Attribute]
renderOpacity s = renderAttr S.opacity o
where
o = getOpacity <$> getAttr s
renderFillRule :: Style v n -> [Attribute]
renderFillRule s = renderTextAttr fill_rule fr
where
fr = (fillRuleToText . getFillRule) <$> getAttr s
fillRuleToText :: FillRule -> AttributeValue
fillRuleToText Winding = "nonzero"
fillRuleToText EvenOdd = "evenodd"
renderLineWidth :: SVGFloat n => Style v n -> [Attribute]
renderLineWidth s = renderAttr stroke_width lWidth
where
lWidth = getNumAttr getLineWidth s
renderLineCap :: Style v n -> [Attribute]
renderLineCap s = renderTextAttr stroke_linecap lCap
where
lCap = (lineCapToText . getLineCap) <$> getAttr s
lineCapToText :: LineCap -> AttributeValue
lineCapToText LineCapButt = "butt"
lineCapToText LineCapRound = "round"
lineCapToText LineCapSquare = "square"
renderLineJoin :: Style v n -> [Attribute]
renderLineJoin s = renderTextAttr stroke_linejoin lj
where
lj = (lineJoinToText . getLineJoin) <$> getAttr s
lineJoinToText :: LineJoin -> AttributeValue
lineJoinToText LineJoinMiter = "miter"
lineJoinToText LineJoinRound = "round"
lineJoinToText LineJoinBevel = "bevel"
renderDashing :: SVGFloat n => Style v n -> [Attribute]
renderDashing s =
renderTextAttr stroke_dasharray arr <>
renderAttr stroke_dashoffset dOffset
where
getDasharray (Dashing a _) = a
getDashoffset (Dashing _ o) = o
dashArrayToStr = intercalate "," . map show
-- Ignore dashing if dashing array is empty
checkEmpty (Just (Dashing [] _)) = Nothing
checkEmpty other = other
dashing' = checkEmpty $ getNumAttr getDashing s
arr = (pack . dashArrayToStr . getDasharray) <$> dashing'
dOffset = getDashoffset <$> dashing'
renderFontSize :: SVGFloat n => Style v n -> [Attribute]
renderFontSize s = renderTextAttr font_size fs
where
fs = pack <$> getNumAttr ((++ "px") . show . getFontSize) s
renderFontSlant :: Style v n -> [Attribute]
renderFontSlant s = renderTextAttr font_style fs
where
fs = (fontSlantAttr . getFontSlant) <$> getAttr s
fontSlantAttr :: FontSlant -> AttributeValue
fontSlantAttr FontSlantItalic = "italic"
fontSlantAttr FontSlantOblique = "oblique"
fontSlantAttr FontSlantNormal = "normal"
renderFontWeight :: Style v n -> [Attribute]
renderFontWeight s = renderTextAttr font_weight fw
where
fw = (fontWeightAttr . getFontWeight) <$> getAttr s
fontWeightAttr :: FontWeight -> AttributeValue
fontWeightAttr FontWeightNormal = "normal"
fontWeightAttr FontWeightBold = "bold"
renderFontFamily :: Style v n -> [Attribute]
renderFontFamily s = renderTextAttr font_family ff
where
ff = (pack . getFont) <$> getAttr s
-- | Render a style attribute if available, empty otherwise.
renderAttr :: Show s => AttrTag -> Maybe s -> [Attribute]
renderAttr attr valM = maybe [] (\v -> [(bindAttr attr) (pack . show $ v)]) valM
-- renderTextAttr :: (AttributeValue -> Attribute) -> Maybe AttributeValue -> [Attribute]
renderTextAttr :: AttrTag -> Maybe AttributeValue -> [Attribute]
renderTextAttr attr valM = maybe [] (\v -> [(bindAttr attr) v]) valM
colorToRgbText :: forall c. Color c => c -> AttributeValue
colorToRgbText c = T.concat ["rgb(", int r, ",", int g, ",", int b, ")"]
where
int d = pack . show $ (round (d * 255) :: Int)
(r,g,b,_) = colorToSRGBA c
colorToOpacity :: forall c. Color c => c -> Double
colorToOpacity c = a
where
(_,_,_,a) = colorToSRGBA c
| j-mueller/hldb | webapp/Graphics/Rendering/SVG.hs | bsd-3-clause | 9,919 | 0 | 16 | 2,537 | 2,717 | 1,426 | 1,291 | 204 | 7 |
-- |
-- Module: Data.Chimera.WheelMapping
-- Copyright: (c) 2017 Andrew Lelechenko
-- Licence: MIT
-- Maintainer: Andrew Lelechenko <andrew.lelechenko@gmail.com>
--
-- Helpers for mapping to <http://mathworld.wolfram.com/RoughNumber.html rough numbers>
-- and back. This has various applications in number theory.
--
-- __Example__
--
-- Let @isPrime@ be an expensive predicate,
-- which checks whether its argument is a prime number.
-- We can memoize it as usual:
--
-- > isPrimeCache1 :: UChimera Bool
-- > isPrimeCache1 = tabulate isPrime
-- >
-- > isPrime1 :: Word -> Bool
-- > isPrime1 = index isPrimeCache1
--
-- But one may argue that since the only even prime number is 2,
-- it is quite wasteful to cache @isPrime@ for even arguments.
-- So we can save half the space by memoizing it for odd
-- numbers only:
--
-- > isPrimeCache2 :: UChimera Bool
-- > isPrimeCache2 = tabulate (isPrime . (\n -> 2 * n + 1))
-- >
-- > isPrime2 :: Word -> Bool
-- > isPrime2 n
-- > | n == 2 = True
-- > | even n = False
-- > | otherwise = index isPrimeCache2 ((n - 1) `quot` 2)
--
-- Here @\\n -> 2 * n + 1@ maps n to the (n+1)-th odd number,
-- and @\\n -> (n - 1) \`quot\` 2@ takes it back. These functions
-- are available below as 'fromWheel2' and 'toWheel2'.
--
-- Odd numbers are the simplest example of numbers, lacking
-- small prime factors (so called
-- <http://mathworld.wolfram.com/RoughNumber.html rough numbers>).
-- Removing numbers, having small prime factors, is sometimes
-- called <https://en.wikipedia.org/wiki/Wheel_factorization wheel sieving>.
--
-- One can go further and exclude not only even numbers,
-- but also integers, divisible by 3.
-- To do this we need a function which maps n to the (n+1)-th number coprime with 2 and 3
-- (thus, with 6) and its inverse: namely, 'fromWheel6' and 'toWheel6'. Then write
--
-- > isPrimeCache6 :: UChimera Bool
-- > isPrimeCache6 = tabulate (isPrime . fromWheel6)
-- >
-- > isPrime6 :: Word -> Bool
-- > isPrime6 n
-- > | n `elem` [2, 3] = True
-- > | n `gcd` 6 /= 1 = False
-- > | otherwise = index isPrimeCache6 (toWheel6 n)
--
-- Thus, the wheel of 6 saves more space, improving memory locality.
--
-- (If you need to reduce memory consumption even further,
-- consider using 'Data.Bit.Bit' wrapper,
-- which provides an instance of unboxed vector,
-- packing one boolean per bit instead of one boolean per byte for 'Bool')
--
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE UnboxedTuples #-}
module Data.Chimera.WheelMapping
( fromWheel2
, toWheel2
, fromWheel6
, toWheel6
, fromWheel30
, toWheel30
, fromWheel210
, toWheel210
) where
import Data.Bits
import Data.Chimera.Compat
import GHC.Exts
bits :: Int
bits = fbs (0 :: Word)
-- | Left inverse for 'fromWheel2'. Monotonically non-decreasing function.
--
-- prop> toWheel2 . fromWheel2 == id
toWheel2 :: Word -> Word
toWheel2 i = i `shiftR` 1
{-# INLINE toWheel2 #-}
-- | 'fromWheel2' n is the (n+1)-th positive odd number.
-- Sequence <https://oeis.org/A005408 A005408>.
--
-- prop> map fromWheel2 [0..] == [ n | n <- [0..], n `gcd` 2 == 1 ]
--
-- >>> map fromWheel2 [0..9]
-- [1,3,5,7,9,11,13,15,17,19]
fromWheel2 :: Word -> Word
fromWheel2 i = i `shiftL` 1 + 1
{-# INLINE fromWheel2 #-}
-- | Left inverse for 'fromWheel6'. Monotonically non-decreasing function.
--
-- prop> toWheel6 . fromWheel6 == id
toWheel6 :: Word -> Word
toWheel6 i@(W# i#) = case bits of
64 -> W# z1# `shiftR` 1
_ -> i `quot` 3
where
m# = 12297829382473034411## -- (2^65+1) / 3
!(# z1#, _ #) = timesWord2# m# i#
{-# INLINE toWheel6 #-}
-- | 'fromWheel6' n is the (n+1)-th positive number, not divisible by 2 or 3.
-- Sequence <https://oeis.org/A007310 A007310>.
--
-- prop> map fromWheel6 [0..] == [ n | n <- [0..], n `gcd` 6 == 1 ]
--
-- >>> map fromWheel6 [0..9]
-- [1,5,7,11,13,17,19,23,25,29]
fromWheel6 :: Word -> Word
fromWheel6 i = i `shiftL` 1 + i + (i .&. 1) + 1
{-# INLINE fromWheel6 #-}
-- | Left inverse for 'fromWheel30'. Monotonically non-decreasing function.
--
-- prop> toWheel30 . fromWheel30 == id
toWheel30 :: Word -> Word
toWheel30 i@(W# i#) = q `shiftL` 3 + (r + r `shiftR` 4) `shiftR` 2
where
(q, r) = case bits of
64 -> (q64, r64)
_ -> i `quotRem` 30
m# = 9838263505978427529## -- (2^67+7) / 15
!(# z1#, _ #) = timesWord2# m# i#
q64 = W# z1# `shiftR` 4
r64 = i - q64 `shiftL` 5 + q64 `shiftL` 1
{-# INLINE toWheel30 #-}
-- | 'fromWheel30' n is the (n+1)-th positive number, not divisible by 2, 3 or 5.
-- Sequence <https://oeis.org/A007775 A007775>.
--
-- prop> map fromWheel30 [0..] == [ n | n <- [0..], n `gcd` 30 == 1 ]
--
-- >>> map fromWheel30 [0..9]
-- [1,7,11,13,17,19,23,29,31,37]
fromWheel30 :: Word -> Word
fromWheel30 i = ((i `shiftL` 2 - i `shiftR` 2) .|. 1)
+ ((i `shiftL` 1 - i `shiftR` 1) .&. 2)
{-# INLINE fromWheel30 #-}
-- | Left inverse for 'fromWheel210'. Monotonically non-decreasing function.
--
-- prop> toWheel210 . fromWheel210 == id
toWheel210 :: Word -> Word
toWheel210 i@(W# i#) = q `shiftL` 5 + q `shiftL` 4 + W# (indexWord8OffAddr# table# (word2Int# r#))
where
!(q, W# r#) = case bits of
64 -> (q64, r64)
_ -> i `quotRem` 210
m# = 5621864860559101445## -- (2^69+13) / 105
!(# z1#, _ #) = timesWord2# m# i#
q64 = W# z1# `shiftR` 6
r64 = i - q64 * 210
table# :: Addr#
table# = "\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\SOH\SOH\STX\STX\STX\STX\ETX\ETX\EOT\EOT\EOT\EOT\ENQ\ENQ\ENQ\ENQ\ENQ\ENQ\ACK\ACK\a\a\a\a\a\a\b\b\b\b\t\t\n\n\n\n\v\v\v\v\v\v\f\f\f\f\f\f\r\r\SO\SO\SO\SO\SO\SO\SI\SI\SI\SI\DLE\DLE\DC1\DC1\DC1\DC1\DC1\DC1\DC2\DC2\DC2\DC2\DC3\DC3\DC3\DC3\DC3\DC3\DC4\DC4\DC4\DC4\DC4\DC4\DC4\DC4\NAK\NAK\NAK\NAK\SYN\SYN\ETB\ETB\ETB\ETB\CAN\CAN\EM\EM\EM\EM\SUB\SUB\SUB\SUB\SUB\SUB\SUB\SUB\ESC\ESC\ESC\ESC\ESC\ESC\FS\FS\FS\FS\GS\GS\GS\GS\GS\GS\RS\RS\US\US\US\US !!\"\"\"\"\"\"######$$$$%%&&&&''''''(())))))****++,,,,--........../"#
-- map Data.Char.chr [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 23, 23, 23, 23, 24, 24, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 30, 30, 31, 31, 31, 31, 32, 32, 32, 32, 32, 32, 33, 33, 34, 34, 34, 34, 34, 34, 35, 35, 35, 35, 35, 35, 36, 36, 36, 36, 37, 37, 38, 38, 38, 38, 39, 39, 39, 39, 39, 39, 40, 40, 41, 41, 41, 41, 41, 41, 42, 42, 42, 42, 43, 43, 44, 44, 44, 44, 45, 45, 46, 46, 46, 46, 46, 46, 46, 46, 46, 46, 47]
{-# INLINE toWheel210 #-}
-- | 'fromWheel210' n is the (n+1)-th positive number, not divisible by 2, 3, 5 or 7.
-- Sequence <https://oeis.org/A008364 A008364>.
--
-- prop> map fromWheel210 [0..] == [ n | n <- [0..], n `gcd` 210 == 1 ]
--
-- >>> map fromWheel210 [0..9]
-- [1,11,13,17,19,23,29,31,37,41]
fromWheel210 :: Word -> Word
fromWheel210 i@(W# i#) = q * 210 + W# (indexWord8OffAddr# table# (word2Int# r#))
where
!(q, W# r#) = case bits of
64 -> (q64, r64)
_ -> i `quotRem` 48
m# = 12297829382473034411## -- (2^65+1) / 3
!(# z1#, _ #) = timesWord2# m# i#
q64 = W# z1# `shiftR` 5
r64 = i - q64 `shiftL` 5 - q64 `shiftL` 4
table# :: Addr#
table# = "\SOH\v\r\DC1\DC3\ETB\GS\US%)+/5;=CGIOSYaegkmqy\DEL\131\137\139\143\149\151\157\163\167\169\173\179\181\187\191\193\197\199\209"#
-- map Data.Char.chr [1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 121, 127, 131, 137, 139, 143, 149, 151, 157, 163, 167, 169, 173, 179, 181, 187, 191, 193, 197, 199, 209]
{-# INLINE fromWheel210 #-}
| Bodigrim/bit-stream | Data/Chimera/WheelMapping.hs | bsd-3-clause | 7,907 | 0 | 11 | 1,592 | 931 | 575 | 356 | 71 | 2 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Drive.Trello.Types
( TrelloF (..)
, TrelloAuth (..)
, User (..)
, Organization (..)
, Board (..)
) where
import Data.Aeson ((.:))
import qualified Data.Aeson as A
import Data.Text (Text)
import GHC.Generics
newtype User = User Text
newtype Organization = Organization Text
newtype Board = Board
{ boardName :: Text
} deriving (Show, Eq)
instance A.FromJSON Board where
parseJSON = A.withObject "board" $
\v -> Board <$> v .: "name"
data TrelloF a
= GetBoards User ([Board] -> a)
deriving (Functor)
data TrelloAuth = TrelloAuth
{ user :: Text
, token :: Text
, key :: Text
} deriving (Show, Eq, Generic)
instance A.FromJSON TrelloAuth
| palf/free-driver | packages/drive-trello/lib/Drive/Trello/Types.hs | bsd-3-clause | 831 | 0 | 9 | 210 | 239 | 147 | 92 | 30 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
module Text.HTML.TagSoup.Options where
import Data.Typeable
import Text.HTML.TagSoup.Type
import Text.HTML.TagSoup.Entity
import Text.StringLike
-- | These options control how 'parseTags' works. The 'ParseOptions' type is usually generated by one of
-- 'parseOptions', 'parseOptionsFast' or 'parseOptionsEntities', then selected fields may be overriden.
--
-- The options 'optTagPosition' and 'optTagWarning' specify whether to generate
-- 'TagPosition' or 'TagWarning' elements respectively. Usually these options should be set to @False@
-- to simplify future stages, unless you rely on position information or want to give malformed HTML
-- messages to the end user.
--
-- The options 'optEntityData' and 'optEntityAttrib' control how entities, for example @ @ are handled.
-- Both take a string, and a boolean, where @True@ indicates that the entity ended with a semi-colon @;@.
-- Inside normal text 'optEntityData' will be called, and the results will be inserted in the tag stream.
-- Inside a tag attribute 'optEntityAttrib' will be called, and the first component of the result will be used
-- in the attribute, and the second component will be appended after the 'TagOpen' value (usually the second
-- component is @[]@). As an example, to not decode any entities, pass:
--
-- > parseOptions
-- > {optEntityData = \(str,b) -> [TagText $ "&" ++ str ++ [';' | b]]
-- > ,optEntityAttrib = \(str,b) -> ("&" ++ str ++ [';' | b], [])
-- > }
--
-- (But this is just an example. If you really want to not decode any entities then see 'parseOptionsEntities'.)
-- The 'optTagTextMerge' value specifies if you always want adjacent 'TagText' values to be merged.
-- Merging adjacent pieces of text has a small performance penalty, but will usually make subsequent analysis
-- simpler. Contiguous runs of characters without entities or tags will also be generated as single 'TagText'
-- values.
data ParseOptions str = ParseOptions
{optTagPosition :: Bool -- ^ Should 'TagPosition' values be given before some items (default=False,fast=False).
,optTagWarning :: Bool -- ^ Should 'TagWarning' values be given (default=False,fast=False)
,optEntityData :: (str,Bool) -> [Tag str] -- ^ How to lookup an entity (Bool = has ending @';'@)
,optEntityAttrib :: (str,Bool) -> (str,[Tag str]) -- ^ How to lookup an entity in an attribute (Bool = has ending @';'@?)
,optTagTextMerge :: Bool -- ^ Require no adjacent 'TagText' values (default=True,fast=False)
}
deriving Typeable
-- | A 'ParseOptions' structure using a custom function to lookup attributes. Any attribute
-- that is not found will be left intact, and a 'TagWarning' given (if 'optTagWarning' is set).
--
-- If you do not want to resolve any entities, simpliy pass @const Nothing@ for the lookup function.
parseOptionsEntities :: StringLike str => (str -> Maybe str) -> ParseOptions str
parseOptionsEntities lookupEntity = ParseOptions False False entityData entityAttrib True
where
entityData x = TagText a : b
where (a,b) = entityAttrib x
entityAttrib ~(x,b) =
let x' = x `append` fromString [';'|b]
in case lookupEntity x' of
Just y -> (y, [])
Nothing -> (fromChar '&' `append` x'
,[TagWarning $ fromString "Unknown entity: " `append` x])
-- | The default parse options value, described in 'ParseOptions'. Equivalent to
-- @'parseOptionsEntities' 'lookupEntity'@.
parseOptions :: StringLike str => ParseOptions str
parseOptions = parseOptionsEntities $ fmap fromString . lookupEntity . toString
-- | A 'ParseOptions' structure optimised for speed, following the fast options.
parseOptionsFast :: StringLike str => ParseOptions str
parseOptionsFast = parseOptions{optTagTextMerge=False}
-- | Change the underlying string type of a 'ParseOptions' value.
fmapParseOptions :: (StringLike from, StringLike to) => ParseOptions from -> ParseOptions to
fmapParseOptions (ParseOptions a b c d e) = ParseOptions a b c2 d2 e
where
c2 ~(x,y) = map (fmap castString) $ c (castString x, y)
d2 ~(x,y) = (castString r, map (fmap castString) s)
where (r,s) = d (castString x, y)
| ndmitchell/tagsoup | src/Text/HTML/TagSoup/Options.hs | bsd-3-clause | 4,297 | 0 | 16 | 861 | 566 | 322 | 244 | 32 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# 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 Compiler (0.7.0-dev) --
-- --
-- DO NOT EDIT UNLESS YOU ARE SURE YOU KNOW WHAT YOU ARE DOING --
-----------------------------------------------------------------
module Thrift.ContentConsumer where
import Prelude ( Bool(..), Enum, Double, String, Maybe(..),
Eq, Show, Ord,
return, length, IO, fromIntegral, fromEnum, toEnum,
(&&), (||), (==), (++), ($), (-) )
import Control.Exception
import Data.ByteString.Lazy
import Data.Int
import Data.Typeable ( Typeable )
import qualified Data.Map as Map
import qualified Data.Set as Set
import Thrift
import Thrift.Content_Types
import qualified Thrift.ContentConsumer_Iface as Iface
-- HELPER FUNCTIONS AND STRUCTURES --
data MeshChanged_args = MeshChanged_args{f_MeshChanged_args_name :: Maybe String} deriving (Show,Eq,Ord,Typeable)
write_MeshChanged_args oprot record = do
writeStructBegin oprot "MeshChanged_args"
case f_MeshChanged_args_name record of {Nothing -> return (); Just _v -> do
writeFieldBegin oprot ("name",T_STRING,1)
writeString oprot _v
writeFieldEnd oprot}
writeFieldStop oprot
writeStructEnd oprot
read_MeshChanged_args_fields iprot record = do
(_,_t31,_id32) <- readFieldBegin iprot
if _t31 == T_STOP then return record else
case _id32 of
1 -> if _t31 == T_STRING then do
s <- readString iprot
read_MeshChanged_args_fields iprot record{f_MeshChanged_args_name=Just s}
else do
skip iprot _t31
read_MeshChanged_args_fields iprot record
_ -> do
skip iprot _t31
readFieldEnd iprot
read_MeshChanged_args_fields iprot record
read_MeshChanged_args iprot = do
_ <- readStructBegin iprot
record <- read_MeshChanged_args_fields iprot (MeshChanged_args{f_MeshChanged_args_name=Nothing})
readStructEnd iprot
return record
data MeshChanged_result = MeshChanged_result deriving (Show,Eq,Ord,Typeable)
write_MeshChanged_result oprot record = do
writeStructBegin oprot "MeshChanged_result"
writeFieldStop oprot
writeStructEnd oprot
read_MeshChanged_result_fields iprot record = do
(_,_t36,_id37) <- readFieldBegin iprot
if _t36 == T_STOP then return record else
case _id37 of
_ -> do
skip iprot _t36
readFieldEnd iprot
read_MeshChanged_result_fields iprot record
read_MeshChanged_result iprot = do
_ <- readStructBegin iprot
record <- read_MeshChanged_result_fields iprot (MeshChanged_result{})
readStructEnd iprot
return record
process_meshChanged (seqid, iprot, oprot, handler) = do
args <- read_MeshChanged_args iprot
readMessageEnd iprot
rs <- return (MeshChanged_result)
res <- (do
Iface.meshChanged handler (f_MeshChanged_args_name args)
return rs)
writeMessageBegin oprot ("meshChanged", M_REPLY, seqid);
write_MeshChanged_result oprot res
writeMessageEnd oprot
tFlush (getTransport oprot)
proc_ handler (iprot,oprot) (name,typ,seqid) = case name of
"meshChanged" -> process_meshChanged (seqid,iprot,oprot,handler)
_ -> do
skip iprot T_STRUCT
readMessageEnd iprot
writeMessageBegin oprot (name,M_EXCEPTION,seqid)
writeAppExn oprot (AppExn AE_UNKNOWN_METHOD ("Unknown function " ++ name))
writeMessageEnd oprot
tFlush (getTransport oprot)
process handler (iprot, oprot) = do
(name, typ, seqid) <- readMessageBegin iprot
proc_ handler (iprot,oprot) (name,typ,seqid)
return True
| csabahruska/GFXDemo | Thrift/ContentConsumer.hs | bsd-3-clause | 3,858 | 15 | 14 | 753 | 852 | 476 | 376 | 90 | 4 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Ordinal.HE.Tests
( tests ) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Ordinal.HE.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "HE Tests"
[ makeCorpusTest [Seal Ordinal] corpus
]
| facebookincubator/duckling | tests/Duckling/Ordinal/HE/Tests.hs | bsd-3-clause | 503 | 0 | 9 | 77 | 79 | 50 | 29 | 11 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{- |
Module : $Header$
Description : Morphisms in Propositional logic extended with QBFs
Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010
License : GPLv2 or higher, see LICENSE.txt
Maintainer : <jonathan.von_schroeder@dfki.de>
Stability : experimental
Portability : portable
Definition of morphisms for propositional logic
copied to "Temporal.Morphism"
Ref.
Till Mossakowski, Joseph Goguen, Razvan Diaconescu, Andrzej Tarlecki.
What is a Logic?.
In Jean-Yves Beziau (Ed.), Logica Universalis, pp. 113-133. Birkhaeuser.
2005.
-}
module QBF.Morphism
( Morphism (..) -- datatype for Morphisms
, pretty -- pretty printing
, idMor -- identity morphism
, isLegalMorphism -- check if morhpism is ok
, composeMor -- composition
, inclusionMap -- inclusion map
, mapSentence -- map of sentences
, mapSentenceH -- map of sentences, without Result type
, applyMap -- application function for maps
, applyMorphism -- application function for morphism
, morphismUnion
) where
import Data.Data
import qualified Data.Map as Map
import qualified Data.Set as Set
import Propositional.Sign as Sign
import qualified QBF.AS_BASIC_QBF as AS_BASIC
import Common.Id as Id
import Common.Result
import Common.Doc
import Common.DocUtils
import qualified Common.Result as Result
import Control.Monad (unless)
{- | The datatype for morphisms in propositional logic as
maps of sets -}
data Morphism = Morphism
{ source :: Sign
, target :: Sign
, propMap :: Map.Map Id Id
} deriving (Show, Eq, Ord, Typeable, Data)
instance Pretty Morphism where
pretty = printMorphism
-- | Constructs an id-morphism
idMor :: Sign -> Morphism
idMor a = inclusionMap a a
-- | Determines whether a morphism is valid
isLegalMorphism :: Morphism -> Result ()
isLegalMorphism pmor =
let psource = items $ source pmor
ptarget = items $ target pmor
pdom = Map.keysSet $ propMap pmor
pcodom = Set.map (applyMorphism pmor) psource
in unless (Set.isSubsetOf pcodom ptarget && Set.isSubsetOf pdom psource)
$ fail "illegal QBF morphism"
-- | Application funtion for morphisms
applyMorphism :: Morphism -> Id -> Id
applyMorphism mor idt = Map.findWithDefault idt idt $ propMap mor
-- | Application function for propMaps
applyMap :: Map.Map Id Id -> Id -> Id
applyMap pmap idt = Map.findWithDefault idt idt pmap
-- | Composition of morphisms in propositional Logic
composeMor :: Morphism -> Morphism -> Result Morphism
composeMor f g =
let fSource = source f
gTarget = target g
fMap = propMap f
gMap = propMap g
in return Morphism
{ source = fSource
, target = gTarget
, propMap = if Map.null gMap then fMap else
Set.fold ( \ i -> let j = applyMap gMap (applyMap fMap i) in
if i == j then id else Map.insert i j)
Map.empty $ items fSource }
-- | Pretty printing for Morphisms
printMorphism :: Morphism -> Doc
printMorphism m = pretty (source m) <> text "-->" <> pretty (target m)
<> vcat (map ( \ (x, y) -> lparen <> pretty x <> text ","
<> pretty y <> rparen) $ Map.assocs $ propMap m)
-- | Inclusion map of a subsig into a supersig
inclusionMap :: Sign.Sign -> Sign.Sign -> Morphism
inclusionMap s1 s2 = Morphism
{ source = s1
, target = s2
, propMap = Map.empty }
{- | sentence translation along signature morphism
here just the renaming of formulae -}
mapSentence :: Morphism -> AS_BASIC.FORMULA -> Result.Result AS_BASIC.FORMULA
mapSentence mor = return . mapSentenceH mor
mapSentenceH :: Morphism -> AS_BASIC.FORMULA -> AS_BASIC.FORMULA
mapSentenceH mor frm = case frm of
AS_BASIC.Negation form rn -> AS_BASIC.Negation (mapSentenceH mor form) rn
AS_BASIC.Conjunction form rn ->
AS_BASIC.Conjunction (map (mapSentenceH mor) form) rn
AS_BASIC.Disjunction form rn ->
AS_BASIC.Disjunction (map (mapSentenceH mor) form) rn
AS_BASIC.Implication form1 form2 rn -> AS_BASIC.Implication
(mapSentenceH mor form1) (mapSentenceH mor form2) rn
AS_BASIC.Equivalence form1 form2 rn -> AS_BASIC.Equivalence
(mapSentenceH mor form1) (mapSentenceH mor form2) rn
AS_BASIC.TrueAtom rn -> AS_BASIC.TrueAtom rn
AS_BASIC.FalseAtom rn -> AS_BASIC.FalseAtom rn
AS_BASIC.Predication predH -> AS_BASIC.Predication
$ id2SimpleId $ applyMorphism mor $ Id.simpleIdToId predH
AS_BASIC.ForAll xs form rn -> AS_BASIC.ForAll (map
(id2SimpleId . applyMorphism mor . Id.simpleIdToId) xs)
(mapSentenceH mor form) rn
AS_BASIC.Exists xs form rn -> AS_BASIC.Exists
(map (id2SimpleId . applyMorphism mor . Id.simpleIdToId) xs)
(mapSentenceH mor form) rn
morphismUnion :: Morphism -> Morphism -> Result.Result Morphism
morphismUnion mor1 mor2 =
let pmap1 = propMap mor1
pmap2 = propMap mor2
p1 = source mor1
p2 = source mor2
up1 = Set.difference (items p1) $ Map.keysSet pmap1
up2 = Set.difference (items p2) $ Map.keysSet pmap2
(pds, pmap) = foldr ( \ (i, j) (ds, m) -> case Map.lookup i m of
Nothing -> (ds, Map.insert i j m)
Just k -> if j == k then (ds, m) else
(Diag Error
("incompatible mapping of prop " ++ showId i " to "
++ showId j " and " ++ showId k "")
nullRange : ds, m)) ([], pmap1)
(Map.toList pmap2 ++ map (\ a -> (a, a))
(Set.toList $ Set.union up1 up2))
in if null pds then return Morphism
{ source = unite p1 p2
, target = unite (target mor1) $ target mor2
, propMap = pmap } else Result pds Nothing
| keithodulaigh/Hets | QBF/Morphism.hs | gpl-2.0 | 5,797 | 0 | 24 | 1,459 | 1,551 | 807 | 744 | 111 | 10 |
(a, b) = (3, 4)
| roberth/uu-helium | test/simple/correct/PatternBindBug1.hs | gpl-3.0 | 16 | 0 | 5 | 5 | 19 | 11 | 8 | 1 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.SSM.DeleteDocument
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes the specified configuration document.
--
-- You must use 'DeleteAssociation' to disassociate all instances that are
-- associated with the configuration document before you can delete it.
--
-- <http://docs.aws.amazon.com/ssm/latest/APIReference/API_DeleteDocument.html>
module Network.AWS.SSM.DeleteDocument
(
-- * Request
DeleteDocument
-- ** Request constructor
, deleteDocument
-- ** Request lenses
, dd2Name
-- * Response
, DeleteDocumentResponse
-- ** Response constructor
, deleteDocumentResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.SSM.Types
import qualified GHC.Exts
newtype DeleteDocument = DeleteDocument
{ _dd2Name :: Text
} deriving (Eq, Ord, Read, Show, Monoid, IsString)
-- | 'DeleteDocument' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dd2Name' @::@ 'Text'
--
deleteDocument :: Text -- ^ 'dd2Name'
-> DeleteDocument
deleteDocument p1 = DeleteDocument
{ _dd2Name = p1
}
-- | The name of the configuration document.
dd2Name :: Lens' DeleteDocument Text
dd2Name = lens _dd2Name (\s a -> s { _dd2Name = a })
data DeleteDocumentResponse = DeleteDocumentResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteDocumentResponse' constructor.
deleteDocumentResponse :: DeleteDocumentResponse
deleteDocumentResponse = DeleteDocumentResponse
instance ToPath DeleteDocument where
toPath = const "/"
instance ToQuery DeleteDocument where
toQuery = const mempty
instance ToHeaders DeleteDocument
instance ToJSON DeleteDocument where
toJSON DeleteDocument{..} = object
[ "Name" .= _dd2Name
]
instance AWSRequest DeleteDocument where
type Sv DeleteDocument = SSM
type Rs DeleteDocument = DeleteDocumentResponse
request = post "DeleteDocument"
response = nullResponse DeleteDocumentResponse
| kim/amazonka | amazonka-ssm/gen/Network/AWS/SSM/DeleteDocument.hs | mpl-2.0 | 3,006 | 0 | 9 | 659 | 359 | 220 | 139 | 48 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- Module : Gen.Types.Waiter
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : This Source Code Form is subject to the terms of
-- the Mozilla xtPublic License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : provisional
-- Portability : non-portable (GHC extensions)
module Gen.Types.Waiter where
import Control.Lens
import Data.Aeson
import Data.Text (Text)
import Gen.TH
import Gen.Types.Id
import Gen.Types.Notation
import GHC.Generics
data Match
= Path
| PathAll
| PathAny
| Status
| Error
deriving (Eq, Show, Generic)
instance FromJSON Match where
parseJSON = gParseJSON' camel
data Criteria
= Retry
| Success
| Failure
deriving (Eq, Show, Generic)
instance FromJSON Criteria where
parseJSON = gParseJSON' lower
data Expect
= Status' !Integer
| Textual !Text
| Boolean !Bool
deriving (Eq, Show)
instance FromJSON Expect where
parseJSON = \case
String s -> pure (Textual s)
Bool b -> pure (Boolean b)
o -> Status' <$> parseJSON o
data Accept a = Accept
{ _acceptExpect :: Expect
, _acceptMatch :: Match
, _acceptCriteria :: Criteria
, _acceptArgument :: Maybe (Notation a)
} deriving (Eq, Show)
makeLenses ''Accept
instance FromJSON (Accept Id) where
parseJSON = withObject "acceptor" $ \o -> Accept
<$> o .: "expected"
<*> o .: "matcher"
<*> o .: "state"
<*> o .:? "argument"
data Waiter a = Waiter
{ _waitDelay :: !Integer
, _waitAttempts :: !Integer
, _waitOperation :: Id
, _waitAcceptors :: [Accept a]
} deriving (Show, Eq)
makeLenses ''Waiter
instance FromJSON (Waiter Id) where
parseJSON = withObject "waiter" $ \o -> Waiter
<$> o .: "delay"
<*> o .: "maxAttempts"
<*> o .: "operation"
<*> o .: "acceptors"
| fmapfmapfmap/amazonka | gen/src/Gen/Types/Waiter.hs | mpl-2.0 | 2,319 | 0 | 15 | 699 | 503 | 277 | 226 | 75 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Network.Haskoin.Network.Units (tests) where
import Data.ByteString (ByteString)
import Data.Maybe (fromJust)
import Data.Serialize (encode)
import Data.Word (Word32)
import Network.Haskoin.Crypto
import Network.Haskoin.Network
import Network.Haskoin.Util
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, assertBool)
tests :: [Test]
tests =
[ -- Test cases come from bitcoind /src/test/bloom_tests.cpp
testGroup "Bloom Filters"
[ testCase "Bloom Filter Vector 1" bloomFilter1
, testCase "Bloom Filter Vector 2" bloomFilter2
, testCase "Bloom Filter Vector 3" bloomFilter3
]
]
bloomFilter :: Word32 -> ByteString -> Assertion
bloomFilter n x = do
assertBool "Bloom filter doesn't contain vector 1" $ bloomContains f1 v1
assertBool "Bloom filter contains something it should not" $
not $ bloomContains f1 v2
assertBool "Bloom filter doesn't contain vector 3" $ bloomContains f3 v3
assertBool "Bloom filter doesn't contain vector 4" $ bloomContains f4 v4
assertBool "Bloom filter serialization is incorrect" $
encode f4 == bs
where
f0 = bloomCreate 3 0.01 n BloomUpdateAll
f1 = bloomInsert f0 v1
f3 = bloomInsert f1 v3
f4 = bloomInsert f3 v4
v1 = fromJust $ decodeHex "99108ad8ed9bb6274d3980bab5a85c048f0950c8"
v2 = fromJust $ decodeHex "19108ad8ed9bb6274d3980bab5a85c048f0950c8"
v3 = fromJust $ decodeHex "b5a2c786d9ef4658287ced5914b37a1b4aa32eee"
v4 = fromJust $ decodeHex "b9300670b4c5366e95b2699e8b18bc75e5f729c5"
bs = fromJust $ decodeHex x
bloomFilter1 :: Assertion
bloomFilter1 = bloomFilter 0 "03614e9b050000000000000001"
bloomFilter2 :: Assertion
bloomFilter2 = bloomFilter 2147483649 "03ce4299050000000100008001"
bloomFilter3 :: Assertion
bloomFilter3 =
assertBool "Bloom filter serialization is incorrect" $
encode f2 == bs
where
f0 = bloomCreate 2 0.001 0 BloomUpdateAll
f1 = bloomInsert f0 $ encode p
f2 = bloomInsert f1 $ encode $ getAddrHash $ pubKeyAddr p
k = fromJust $ fromWif "5Kg1gnAjaLfKiwhhPpGS3QfRg2m6awQvaj98JCZBZQ5SuS2F15C"
p = derivePubKey k
bs = fromJust $ decodeHex "038fc16b080000000000000001"
| xenog/haskoin | test/bitcoin/Network/Haskoin/Network/Units.hs | unlicense | 2,503 | 0 | 10 | 645 | 506 | 263 | 243 | 51 | 1 |
-- Copyright (c) 2015 Eric McCorkle. All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions
-- are met:
--
-- 1. Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
--
-- 2. Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
--
-- 3. Neither the name of the author nor the names of any contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE AUTHORS 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 AUTHORS
-- OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
-- USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
-- OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-- SUCH DAMAGE.
{-# OPTIONS_GHC -funbox-strict-fields -Wall -Werror #-}
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses,
FunctionalDependencies #-}
-- | Defines datatype for information about source element positions.
module Data.Position.Class(
PositionInfo(..),
Position(..)
) where
import Control.Monad.Positions.Class
import Data.ByteString(ByteString)
import Data.Position.Filename
import Data.Position.Point
-- | A typeclass representing information available about 'Position'
-- instances. This is used to traverse whatever striucture the
-- 'Position' instance may have.
class PositionInfo info where
-- | Get the filename and offsets, if they exist.
location :: MonadPositions m =>
info -> m (Maybe (Filename, Maybe (Point, Point)))
-- | Children of this @PositionInfo@ All titles lines will be indented.
children :: info -> Maybe (ByteString, [info])
-- | Whether or not to show source context as well. Note that
-- source context is omitted for some message rendering modes.
showContext :: info -> Bool
description :: info -> ByteString
-- | A typeclass representing a position.
class Position info pos | pos -> info where
-- | Get a 'PositionInfo' instance to traverse this 'Position'.
positionInfo :: pos -> [info]
| saltlang/compiler-toolbox | src/Data/Position/Class.hs | bsd-3-clause | 2,849 | 0 | 14 | 512 | 210 | 139 | 71 | 18 | 0 |
{-# LANGUAGE ExistentialQuantification, TemplateHaskell, DeriveDataTypeable, Rank2Types, OverloadedStrings #-}
module SecondTransfer.Http2.TransferTypes (
SessionOutputPacket
, SessionOutputCommand (..)
, GlobalStreamId
, SessionToFramerBlock (..)
, OutputFrame
, OutputDataFeed
, InputFrame
, SessionInputCommand (..)
) where
--import Control.Lens
--import qualified Network.HPACK as HP
import qualified Data.ByteString as B
import qualified Network.HTTP2 as NH2
import Control.Concurrent (MVar)
import System.Clock ( --getTime
--, Clock(..)
--, toNanoSecs
--, diffTimeSpec
TimeSpec
)
import SecondTransfer.MainLoop.CoherentWorker (
Effect(..)
)
type OutputFrame = (NH2.EncodeInfo, NH2.FramePayload, Effect)
type GlobalStreamId = Int
-- | Commands that the sessions sends to the framer which concern the whole
-- session
data SessionOutputCommand =
-- Command sent to the framer to close the session as harshly as possible. The framer
-- will pick its own last valid stream.
CancelSession_SOC !NH2.ErrorCodeId
-- Command sent to the framer to close the session specifying a specific last-stream.
| SpecificTerminate_SOC !GlobalStreamId !NH2.ErrorCodeId
deriving Show
type OutputDataFeed = B.ByteString
-- | Signals that the Session sends to the Framer concerning normal operation, including
-- high-priority data to send (in priority trains, already formatted), and a command to
-- start the output machinery for a new stream
data SessionToFramerBlock =
Command_StFB !SessionOutputCommand
| PriorityTrain_StFB [OutputFrame]
| HeadersTrain_StFB (GlobalStreamId, [OutputFrame], Effect, MVar OutputDataFeed)
-- stream id, the headers of the response,
-- the effect provided by the worker, the mvar where data is put.
-- | StartDataOutput_StFB (GlobalStreamId, MVar DataAndEffect ) -- ^ An empty string shall signal end of data
type SessionOutputPacket = SessionToFramerBlock
-- |Have to figure out which are these...but I would expect to have things
-- like unexpected aborts here in this type.
data SessionInputCommand =
FirstFrame_SIC InputFrame -- | This frame is special
|MiddleFrame_SIC InputFrame -- | Ordinary frame
|InternalAbort_SIC -- | Internal abort from the session itself
|InternalAbortStream_SIC GlobalStreamId -- | Internal abort, but only for a frame
|CancelSession_SIC -- |Cancel request from the framer
|PingFrameEmitted_SIC (Int, TimeSpec) -- |The Framer decided to emit a ping request, this is the sequence number (of the packet it was sent on) and the time
|PingFrameReceived_SIC (InputFrame, TimeSpec) -- |The Framer detected a Ping frame with an ACK flag, and a time-measurement was made
deriving Show
type InputFrame = NH2.Frame
| shimmercat/second-transfer | hs-src/SecondTransfer/Http2/TransferTypes.hs | bsd-3-clause | 3,600 | 0 | 8 | 1,307 | 287 | 190 | 97 | 47 | 0 |
{-# LANGUAGE DeriveDataTypeable #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.GL.Tensor
-- Copyright : (c) Sven Panne 2013
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- This package contains tensor data types and their instances for some basic
-- type classes.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.GL.Tensor (
Vertex1(..), Vertex2(..), Vertex3(..), Vertex4(..),
Vector1(..), Vector2(..), Vector3(..), Vector4(..)
) where
import Control.Applicative
import Control.Monad
import Data.Foldable
import Data.Ix
import Data.Traversable
import Data.Typeable
import Foreign.Marshal.Array
import Foreign.Ptr
import Foreign.Storable
--------------------------------------------------------------------------------
-- | A vertex with /y/=0, /z/=0 and /w/=1.
newtype Vertex1 a = Vertex1 a
deriving (Eq, Ord, Ix, Bounded, Show, Read, Typeable)
instance Functor Vertex1 where
fmap f (Vertex1 x) = Vertex1 (f x)
instance Applicative Vertex1 where
pure a = Vertex1 a
Vertex1 f <*> Vertex1 x = Vertex1 (f x)
instance Foldable Vertex1 where
foldr f a (Vertex1 x) = x `f ` a
foldl f a (Vertex1 x) = a `f` x
foldr1 _ (Vertex1 x) = x
foldl1 _ (Vertex1 x) = x
instance Traversable Vertex1 where
traverse f (Vertex1 x) = pure Vertex1 <*> f x
sequenceA (Vertex1 x) = pure Vertex1 <*> x
mapM f (Vertex1 x) = return Vertex1 `ap` f x
sequence (Vertex1 x) = return Vertex1 `ap` x
instance Storable a => Storable (Vertex1 a) where
sizeOf ~(Vertex1 s) = sizeOf s
alignment ~(Vertex1 s) = alignment s
peek = peekApplicativeTraversable
poke = pokeFoldable
--------------------------------------------------------------------------------
-- | A vertex with /z/=0 and /w/=1.
data Vertex2 a = Vertex2 !a !a
deriving (Eq, Ord, Ix, Bounded, Show, Read, Typeable)
instance Functor Vertex2 where
fmap f (Vertex2 x y) = Vertex2 (f x) (f y)
instance Applicative Vertex2 where
pure a = Vertex2 a a
Vertex2 f g <*> Vertex2 x y = Vertex2 (f x) (g y)
instance Foldable Vertex2 where
foldr f a (Vertex2 x y) = x `f ` (y `f` a)
foldl f a (Vertex2 x y) = (a `f` x) `f` y
foldr1 f (Vertex2 x y) = x `f` y
foldl1 f (Vertex2 x y) = x `f` y
instance Traversable Vertex2 where
traverse f (Vertex2 x y) = pure Vertex2 <*> f x <*> f y
sequenceA (Vertex2 x y) = pure Vertex2 <*> x <*> y
mapM f (Vertex2 x y) = return Vertex2 `ap` f x `ap` f y
sequence (Vertex2 x y) = return Vertex2 `ap` x `ap` y
instance Storable a => Storable (Vertex2 a) where
sizeOf ~(Vertex2 x _) = 2 * sizeOf x
alignment ~(Vertex2 x _) = alignment x
peek = peekApplicativeTraversable
poke = pokeFoldable
--------------------------------------------------------------------------------
-- | A vertex with /w/=1.
data Vertex3 a = Vertex3 !a !a !a
deriving (Eq, Ord, Ix, Bounded, Show, Read, Typeable)
instance Functor Vertex3 where
fmap f (Vertex3 x y z) = Vertex3 (f x) (f y) (f z)
instance Applicative Vertex3 where
pure a = Vertex3 a a a
Vertex3 f g h <*> Vertex3 x y z = Vertex3 (f x) (g y) (h z)
instance Foldable Vertex3 where
foldr f a (Vertex3 x y z) = x `f ` (y `f` (z `f` a))
foldl f a (Vertex3 x y z) = ((a `f` x) `f` y) `f` z
foldr1 f (Vertex3 x y z) = x `f` (y `f` z)
foldl1 f (Vertex3 x y z) = (x `f` y) `f` z
instance Traversable Vertex3 where
traverse f (Vertex3 x y z) = pure Vertex3 <*> f x <*> f y <*> f z
sequenceA (Vertex3 x y z) = pure Vertex3 <*> x <*> y <*> z
mapM f (Vertex3 x y z) = return Vertex3 `ap` f x `ap` f y `ap` f z
sequence (Vertex3 x y z) = return Vertex3 `ap` x `ap` y `ap` z
instance Storable a => Storable (Vertex3 a) where
sizeOf ~(Vertex3 x _ _) = 3 * sizeOf x
alignment ~(Vertex3 x _ _) = alignment x
peek = peekApplicativeTraversable
poke = pokeFoldable
--------------------------------------------------------------------------------
-- | A fully-fledged four-dimensional vertex.
data Vertex4 a = Vertex4 !a !a !a !a
deriving (Eq, Ord, Ix, Bounded, Show, Read, Typeable)
instance Functor Vertex4 where
fmap f (Vertex4 x y z w) = Vertex4 (f x) (f y) (f z) (f w)
instance Applicative Vertex4 where
pure a = Vertex4 a a a a
Vertex4 f g h i <*> Vertex4 x y z w = Vertex4 (f x) (g y) (h z) (i w)
instance Foldable Vertex4 where
foldr f a (Vertex4 x y z w) = x `f ` (y `f` (z `f` (w `f` a)))
foldl f a (Vertex4 x y z w) = (((a `f` x) `f` y) `f` z) `f` w
foldr1 f (Vertex4 x y z w) = x `f` (y `f` (z `f` w))
foldl1 f (Vertex4 x y z w) = ((x `f` y) `f` z) `f` w
instance Traversable Vertex4 where
traverse f (Vertex4 x y z w) = pure Vertex4 <*> f x <*> f y <*> f z <*> f w
sequenceA (Vertex4 x y z w) = pure Vertex4 <*> x <*> y <*> z <*> w
mapM f (Vertex4 x y z w) = return Vertex4 `ap` f x `ap` f y `ap` f z `ap` f w
sequence (Vertex4 x y z w) = return Vertex4 `ap` x `ap` y `ap` z `ap` w
instance Storable a => Storable (Vertex4 a) where
sizeOf ~(Vertex4 x _ _ _) = 4 * sizeOf x
alignment ~(Vertex4 x _ _ _) = alignment x
peek = peekApplicativeTraversable
poke = pokeFoldable
--------------------------------------------------------------------------------
-- | A one-dimensional vector.
newtype Vector1 a = Vector1 a
deriving (Eq, Ord, Ix, Bounded, Show, Read, Typeable)
instance Functor Vector1 where
fmap f (Vector1 x) = Vector1 (f x)
instance Applicative Vector1 where
pure a = Vector1 a
Vector1 f <*> Vector1 x = Vector1 (f x)
instance Foldable Vector1 where
foldr f a (Vector1 x) = x `f ` a
foldl f a (Vector1 x) = a `f` x
foldr1 _ (Vector1 x) = x
foldl1 _ (Vector1 x) = x
instance Traversable Vector1 where
traverse f (Vector1 x) = pure Vector1 <*> f x
sequenceA (Vector1 x) = pure Vector1 <*> x
mapM f (Vector1 x) = return Vector1 `ap` f x
sequence (Vector1 x) = return Vector1 `ap` x
instance Storable a => Storable (Vector1 a) where
sizeOf ~(Vector1 s) = sizeOf s
alignment ~(Vector1 s) = alignment s
peek = peekApplicativeTraversable
poke = pokeFoldable
--------------------------------------------------------------------------------
-- | A two-dimensional vector.
data Vector2 a = Vector2 !a !a
deriving (Eq, Ord, Ix, Bounded, Show, Read, Typeable)
instance Functor Vector2 where
fmap f (Vector2 x y) = Vector2 (f x) (f y)
instance Applicative Vector2 where
pure a = Vector2 a a
Vector2 f g <*> Vector2 x y = Vector2 (f x) (g y)
instance Foldable Vector2 where
foldr f a (Vector2 x y) = x `f ` (y `f` a)
foldl f a (Vector2 x y) = (a `f` x) `f` y
foldr1 f (Vector2 x y) = x `f` y
foldl1 f (Vector2 x y) = x `f` y
instance Traversable Vector2 where
traverse f (Vector2 x y) = pure Vector2 <*> f x <*> f y
sequenceA (Vector2 x y) = pure Vector2 <*> x <*> y
mapM f (Vector2 x y) = return Vector2 `ap` f x `ap` f y
sequence (Vector2 x y) = return Vector2 `ap` x `ap` y
instance Storable a => Storable (Vector2 a) where
sizeOf ~(Vector2 x _) = 2 * sizeOf x
alignment ~(Vector2 x _) = alignment x
peek = peekApplicativeTraversable
poke = pokeFoldable
--------------------------------------------------------------------------------
-- | A three-dimensional vector.
data Vector3 a = Vector3 !a !a !a
deriving (Eq, Ord, Ix, Bounded, Show, Read, Typeable)
instance Functor Vector3 where
fmap f (Vector3 x y z) = Vector3 (f x) (f y) (f z)
instance Applicative Vector3 where
pure a = Vector3 a a a
Vector3 f g h <*> Vector3 x y z = Vector3 (f x) (g y) (h z)
instance Foldable Vector3 where
foldr f a (Vector3 x y z) = x `f ` (y `f` (z `f` a))
foldl f a (Vector3 x y z) = ((a `f` x) `f` y) `f` z
foldr1 f (Vector3 x y z) = x `f` (y `f` z)
foldl1 f (Vector3 x y z) = (x `f` y) `f` z
instance Traversable Vector3 where
traverse f (Vector3 x y z) = pure Vector3 <*> f x <*> f y <*> f z
sequenceA (Vector3 x y z) = pure Vector3 <*> x <*> y <*> z
mapM f (Vector3 x y z) = return Vector3 `ap` f x `ap` f y `ap` f z
sequence (Vector3 x y z) = return Vector3 `ap` x `ap` y `ap` z
instance Storable a => Storable (Vector3 a) where
sizeOf ~(Vector3 x _ _) = 3 * sizeOf x
alignment ~(Vector3 x _ _) = alignment x
peek = peekApplicativeTraversable
poke = pokeFoldable
--------------------------------------------------------------------------------
-- | A four-dimensional vector.
data Vector4 a = Vector4 !a !a !a !a
deriving (Eq, Ord, Ix, Bounded, Show, Read, Typeable)
instance Functor Vector4 where
fmap f (Vector4 x y z w) = Vector4 (f x) (f y) (f z) (f w)
instance Applicative Vector4 where
pure a = Vector4 a a a a
Vector4 f g h i <*> Vector4 x y z w = Vector4 (f x) (g y) (h z) (i w)
instance Foldable Vector4 where
foldr f a (Vector4 x y z w) = x `f ` (y `f` (z `f` (w `f` a)))
foldl f a (Vector4 x y z w) = (((a `f` x) `f` y) `f` z) `f` w
foldr1 f (Vector4 x y z w) = x `f` (y `f` (z `f` w))
foldl1 f (Vector4 x y z w) = ((x `f` y) `f` z) `f` w
instance Traversable Vector4 where
traverse f (Vector4 x y z w) = pure Vector4 <*> f x <*> f y <*> f z <*> f w
sequenceA (Vector4 x y z w) = pure Vector4 <*> x <*> y <*> z <*> w
mapM f (Vector4 x y z w) = return Vector4 `ap` f x `ap` f y `ap` f z `ap` f w
sequence (Vector4 x y z w) = return Vector4 `ap` x `ap` y `ap` z `ap` w
instance Storable a => Storable (Vector4 a) where
sizeOf ~(Vector4 x _ _ _) = 4 * sizeOf x
alignment ~(Vector4 x _ _ _) = alignment x
peek = peekApplicativeTraversable
poke = pokeFoldable
--------------------------------------------------------------------------------
peekApplicativeTraversable :: (Applicative t, Traversable t, Storable a) => Ptr (t a) -> IO (t a)
peekApplicativeTraversable = Data.Traversable.mapM peek . addresses
addresses :: (Applicative t, Traversable t, Storable a) => Ptr (t a) -> t (Ptr a)
addresses = snd . mapAccumL nextPtr 0 . pure . castPtr
nextPtr :: Storable a => Int -> Ptr a -> (Int, Ptr a)
nextPtr offset ptr = (offset + 1, advancePtr ptr offset)
--------------------------------------------------------------------------------
pokeFoldable :: (Foldable t, Storable a) => Ptr (t a) -> t a -> IO ()
pokeFoldable ptr xs = foldlM pokeAndAdvance (castPtr ptr) xs >> return ()
pokeAndAdvance :: Storable a => Ptr a -> a -> IO (Ptr a)
pokeAndAdvance ptr value = do
poke ptr value
return $ ptr `plusPtr` sizeOf value
| IreneKnapp/direct-opengl | Graphics/Rendering/OpenGL/GL/Tensor.hs | bsd-3-clause | 10,606 | 0 | 12 | 2,385 | 4,819 | 2,497 | 2,322 | 237 | 1 |
{-# LANGUAGE RecordWildCards #-}
-- |
-- This is the main entry point into our logic, with everything already nicely
-- in the world of Haskell, i.e. no JS dependencies.
module Entry where
import qualified Data.Map as M
import qualified Data.Set as S
import Types
import Lint
import Rules
import Analysis
import ShapeChecks
incredibleLogic :: Context -> Task -> Proof -> Either String Analysis
incredibleLogic ctxt task proof = do
lintsToEither (lint ctxt task proof)
return $ Analysis {..}
where
usedConnections = findUsedConnections ctxt task proof
scopedProof = prepare ctxt task proof
portLabels = spProps scopedProof'
(scopedProof', connectionStatus) = unifyScopedProof proof scopedProof
unconnectedGoals = findUnconnectedGoals ctxt task proof
cycles = findCycles ctxt task proof
escapedHypotheses = findEscapedHypotheses ctxt task proof
badConnections = S.unions
[ S.fromList (concat cycles)
, S.fromList (concat escapedHypotheses)
, S.fromList [ c | (c, r) <- M.toList connectionStatus, badResult r ]
]
emptyTask (Task [] []) = True
emptyTask (Task _ _) = False
rule = if emptyTask task && null unconnectedGoals && S.null badConnections
then deriveRule ctxt task proof scopedProof'
else Nothing
qed = null unconnectedGoals && S.null (usedConnections `S.intersection` badConnections)
| eccstartup/incredible | logic/Entry.hs | mit | 1,404 | 0 | 14 | 299 | 368 | 194 | 174 | 30 | 3 |
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP, DeriveDataTypeable #-}
-- | Module for (a) type kinds and (b) type coercions,
-- as used in System FC. See 'CoreSyn.Expr' for
-- more on System FC and how coercions fit into it.
--
module Coercion (
-- * Main data type
Coercion(..), Var, CoVar,
LeftOrRight(..), pickLR,
Role(..), ltRole,
-- ** Functions over coercions
coVarKind, coVarRole,
coercionType, coercionKind, coercionKinds, isReflCo,
isReflCo_maybe, coercionRole, coercionKindRole,
mkCoercionType,
-- ** Constructing coercions
mkReflCo, mkCoVarCo,
mkAxInstCo, mkUnbranchedAxInstCo, mkAxInstLHS, mkAxInstRHS,
mkUnbranchedAxInstRHS,
mkPiCo, mkPiCos, mkCoCast,
mkSymCo, mkTransCo, mkNthCo, mkNthCoRole, mkLRCo,
mkInstCo, mkAppCo, mkAppCoFlexible, mkTyConAppCo, mkFunCo,
mkForAllCo, mkUnsafeCo, mkUnivCo, mkSubCo, mkPhantomCo,
mkNewTypeCo, downgradeRole,
mkAxiomRuleCo,
-- ** Decomposition
instNewTyCon_maybe,
NormaliseStepper, NormaliseStepResult(..), composeSteppers,
modifyStepResultCo, unwrapNewTypeStepper,
topNormaliseNewType_maybe, topNormaliseTypeX_maybe,
decomposeCo, getCoVar_maybe,
splitAppCo_maybe,
splitForAllCo_maybe,
nthRole, tyConRolesX,
setNominalRole_maybe,
-- ** Coercion variables
mkCoVar, isCoVar, isCoVarType, coVarName, setCoVarName, setCoVarUnique,
-- ** Free variables
tyCoVarsOfCo, tyCoVarsOfCos, coVarsOfCo, coercionSize,
-- ** Substitution
CvSubstEnv, emptyCvSubstEnv,
CvSubst(..), emptyCvSubst, Coercion.lookupTyVar, lookupCoVar,
isEmptyCvSubst, zapCvSubstEnv, getCvInScope,
substCo, substCos, substCoVar, substCoVars,
substCoWithTy, substCoWithTys,
cvTvSubst, tvCvSubst, mkCvSubst, zipOpenCvSubst,
substTy, extendTvSubst,
extendCvSubstAndInScope, extendTvSubstAndInScope,
substTyVarBndr, substCoVarBndr,
-- ** Lifting
liftCoMatch, liftCoSubstTyVar, liftCoSubstWith,
-- ** Comparison
coreEqCoercion, coreEqCoercion2,
-- ** Forcing evaluation of coercions
seqCo,
-- * Pretty-printing
pprCo, pprParendCo,
pprCoAxiom, pprCoAxBranch, pprCoAxBranchHdr,
-- * Tidying
tidyCo, tidyCos,
-- * Other
applyCo,
) where
#include "HsVersions.h"
import Unify ( MatchEnv(..), matchList )
import TypeRep
import qualified Type
import Type hiding( substTy, substTyVarBndr, extendTvSubst )
import TyCon
import CoAxiom
import Var
import VarEnv
import VarSet
import Binary
import Maybes ( orElse )
import Name ( Name, NamedThing(..), nameUnique, nameModule, getSrcSpan )
import OccName ( parenSymOcc )
import Util
import BasicTypes
import Outputable
import Unique
import Pair
import SrcLoc
import PrelNames ( funTyConKey, eqPrimTyConKey, eqReprPrimTyConKey )
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative hiding ( empty )
import Data.Traversable (traverse, sequenceA)
#endif
import FastString
import ListSetOps
import qualified Data.Data as Data hiding ( TyCon )
import Control.Arrow ( first )
{-
************************************************************************
* *
Coercions
* *
************************************************************************
-}
-- | A 'Coercion' is concrete evidence of the equality/convertibility
-- of two types.
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.lhs
data Coercion
-- Each constructor has a "role signature", indicating the way roles are
-- propagated through coercions. P, N, and R stand for coercions of the
-- given role. e stands for a coercion of a specific unknown role (think
-- "role polymorphism"). "e" stands for an explicit role parameter
-- indicating role e. _ stands for a parameter that is not a Role or
-- Coercion.
-- These ones mirror the shape of types
= -- Refl :: "e" -> _ -> e
Refl Role Type -- See Note [Refl invariant]
-- Invariant: applications of (Refl T) to a bunch of identity coercions
-- always show up as Refl.
-- For example (Refl T) (Refl a) (Refl b) shows up as (Refl (T a b)).
-- Applications of (Refl T) to some coercions, at least one of
-- which is NOT the identity, show up as TyConAppCo.
-- (They may not be fully saturated however.)
-- ConAppCo coercions (like all coercions other than Refl)
-- are NEVER the identity.
-- Use (Refl Representational _), not (SubCo (Refl Nominal _))
-- These ones simply lift the correspondingly-named
-- Type constructors into Coercions
-- TyConAppCo :: "e" -> _ -> ?? -> e
-- See Note [TyConAppCo roles]
| TyConAppCo Role TyCon [Coercion] -- lift TyConApp
-- The TyCon is never a synonym;
-- we expand synonyms eagerly
-- But it can be a type function
| AppCo Coercion Coercion -- lift AppTy
-- AppCo :: e -> N -> e
-- See Note [Forall coercions]
| ForAllCo TyVar Coercion -- forall a. g
-- :: _ -> e -> e
-- These are special
| CoVarCo CoVar -- :: _ -> (N or R)
-- result role depends on the tycon of the variable's type
-- AxiomInstCo :: e -> _ -> [N] -> e
| AxiomInstCo (CoAxiom Branched) BranchIndex [Coercion]
-- See also [CoAxiom index]
-- The coercion arguments always *precisely* saturate
-- arity of (that branch of) the CoAxiom. If there are
-- any left over, we use AppCo. See
-- See [Coercion axioms applied to coercions]
-- see Note [UnivCo]
| UnivCo FastString Role Type Type -- :: "e" -> _ -> _ -> e
-- the FastString is just a note for provenance
| SymCo Coercion -- :: e -> e
| TransCo Coercion Coercion -- :: e -> e -> e
-- The number of types and coercions should match exactly the expectations
-- of the CoAxiomRule (i.e., the rule is fully saturated).
| AxiomRuleCo CoAxiomRule [Type] [Coercion]
-- These are destructors
| NthCo Int Coercion -- Zero-indexed; decomposes (T t0 ... tn)
-- :: _ -> e -> ?? (inverse of TyConAppCo, see Note [TyConAppCo roles])
| LRCo LeftOrRight Coercion -- Decomposes (t_left t_right)
-- :: _ -> N -> N
| InstCo Coercion Type
-- :: e -> _ -> e
| SubCo Coercion -- Turns a ~N into a ~R
-- :: N -> R
deriving (Data.Data, Data.Typeable)
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.lhs
data LeftOrRight = CLeft | CRight
deriving( Eq, Data.Data, Data.Typeable )
instance Binary LeftOrRight where
put_ bh CLeft = putByte bh 0
put_ bh CRight = putByte bh 1
get bh = do { h <- getByte bh
; case h of
0 -> return CLeft
_ -> return CRight }
pickLR :: LeftOrRight -> (a,a) -> a
pickLR CLeft (l,_) = l
pickLR CRight (_,r) = r
{-
Note [Refl invariant]
~~~~~~~~~~~~~~~~~~~~~
Coercions have the following invariant
Refl is always lifted as far as possible.
You might think that a consequencs is:
Every identity coercions has Refl at the root
But that's not quite true because of coercion variables. Consider
g where g :: Int~Int
Left h where h :: Maybe Int ~ Maybe Int
etc. So the consequence is only true of coercions that
have no coercion variables.
Note [Coercion axioms applied to coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The reason coercion axioms can be applied to coercions and not just
types is to allow for better optimization. There are some cases where
we need to be able to "push transitivity inside" an axiom in order to
expose further opportunities for optimization.
For example, suppose we have
C a : t[a] ~ F a
g : b ~ c
and we want to optimize
sym (C b) ; t[g] ; C c
which has the kind
F b ~ F c
(stopping through t[b] and t[c] along the way).
We'd like to optimize this to just F g -- but how? The key is
that we need to allow axioms to be instantiated by *coercions*,
not just by types. Then we can (in certain cases) push
transitivity inside the axiom instantiations, and then react
opposite-polarity instantiations of the same axiom. In this
case, e.g., we match t[g] against the LHS of (C c)'s kind, to
obtain the substitution a |-> g (note this operation is sort
of the dual of lifting!) and hence end up with
C g : t[b] ~ F c
which indeed has the same kind as t[g] ; C c.
Now we have
sym (C b) ; C g
which can be optimized to F g.
Note [CoAxiom index]
~~~~~~~~~~~~~~~~~~~~
A CoAxiom has 1 or more branches. Each branch has contains a list
of the free type variables in that branch, the LHS type patterns,
and the RHS type for that branch. When we apply an axiom to a list
of coercions, we must choose which branch of the axiom we wish to
use, as the different branches may have different numbers of free
type variables. (The number of type patterns is always the same
among branches, but that doesn't quite concern us here.)
The Int in the AxiomInstCo constructor is the 0-indexed number
of the chosen branch.
Note [Forall coercions]
~~~~~~~~~~~~~~~~~~~~~~~
Constructing coercions between forall-types can be a bit tricky.
Currently, the situation is as follows:
ForAllCo TyVar Coercion
represents a coercion between polymorphic types, with the rule
v : k g : t1 ~ t2
----------------------------------------------
ForAllCo v g : (all v:k . t1) ~ (all v:k . t2)
Note that it's only necessary to coerce between polymorphic types
where the type variables have identical kinds, because equality on
kinds is trivial.
Note [Predicate coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
g :: a~b
How can we coerce between types
([c]~a) => [a] -> c
and
([c]~b) => [b] -> c
where the equality predicate *itself* differs?
Answer: we simply treat (~) as an ordinary type constructor, so these
types really look like
((~) [c] a) -> [a] -> c
((~) [c] b) -> [b] -> c
So the coercion between the two is obviously
((~) [c] g) -> [g] -> c
Another way to see this to say that we simply collapse predicates to
their representation type (see Type.coreView and Type.predTypeRep).
This collapse is done by mkPredCo; there is no PredCo constructor
in Coercion. This is important because we need Nth to work on
predicates too:
Nth 1 ((~) [c] g) = g
See Simplify.simplCoercionF, which generates such selections.
Note [Kind coercions]
~~~~~~~~~~~~~~~~~~~~~
Suppose T :: * -> *, and g :: A ~ B
Then the coercion
TyConAppCo T [g] T g : T A ~ T B
Now suppose S :: forall k. k -> *, and g :: A ~ B
Then the coercion
TyConAppCo S [Refl *, g] T <*> g : T * A ~ T * B
Notice that the arguments to TyConAppCo are coercions, but the first
represents a *kind* coercion. Now, we don't allow any non-trivial kind
coercions, so it's an invariant that any such kind coercions are Refl.
Lint checks this.
However it's inconvenient to insist that these kind coercions are always
*structurally* (Refl k), because the key function exprIsConApp_maybe
pushes coercions into constructor arguments, so
C k ty e |> g
may turn into
C (Nth 0 g) ....
Now (Nth 0 g) will optimise to Refl, but perhaps not instantly.
Note [Roles]
~~~~~~~~~~~~
Roles are a solution to the GeneralizedNewtypeDeriving problem, articulated
in Trac #1496. The full story is in docs/core-spec/core-spec.pdf. Also, see
http://ghc.haskell.org/trac/ghc/wiki/RolesImplementation
Here is one way to phrase the problem:
Given:
newtype Age = MkAge Int
type family F x
type instance F Age = Bool
type instance F Int = Char
This compiles down to:
axAge :: Age ~ Int
axF1 :: F Age ~ Bool
axF2 :: F Int ~ Char
Then, we can make:
(sym (axF1) ; F axAge ; axF2) :: Bool ~ Char
Yikes!
The solution is _roles_, as articulated in "Generative Type Abstraction and
Type-level Computation" (POPL 2010), available at
http://www.seas.upenn.edu/~sweirich/papers/popl163af-weirich.pdf
The specification for roles has evolved somewhat since that paper. For the
current full details, see the documentation in docs/core-spec. Here are some
highlights.
We label every equality with a notion of type equivalence, of which there are
three options: Nominal, Representational, and Phantom. A ground type is
nominally equivalent only with itself. A newtype (which is considered a ground
type in Haskell) is representationally equivalent to its representation.
Anything is "phantomly" equivalent to anything else. We use "N", "R", and "P"
to denote the equivalences.
The axioms above would be:
axAge :: Age ~R Int
axF1 :: F Age ~N Bool
axF2 :: F Age ~N Char
Then, because transitivity applies only to coercions proving the same notion
of equivalence, the above construction is impossible.
However, there is still an escape hatch: we know that any two types that are
nominally equivalent are representationally equivalent as well. This is what
the form SubCo proves -- it "demotes" a nominal equivalence into a
representational equivalence. So, it would seem the following is possible:
sub (sym axF1) ; F axAge ; sub axF2 :: Bool ~R Char -- WRONG
What saves us here is that the arguments to a type function F, lifted into a
coercion, *must* prove nominal equivalence. So, (F axAge) is ill-formed, and
we are safe.
Roles are attached to parameters to TyCons. When lifting a TyCon into a
coercion (through TyConAppCo), we need to ensure that the arguments to the
TyCon respect their roles. For example:
data T a b = MkT a (F b)
If we know that a1 ~R a2, then we know (T a1 b) ~R (T a2 b). But, if we know
that b1 ~R b2, we know nothing about (T a b1) and (T a b2)! This is because
the type function F branches on b's *name*, not representation. So, we say
that 'a' has role Representational and 'b' has role Nominal. The third role,
Phantom, is for parameters not used in the type's definition. Given the
following definition
data Q a = MkQ Int
the Phantom role allows us to say that (Q Bool) ~R (Q Char), because we
can construct the coercion Bool ~P Char (using UnivCo).
See the paper cited above for more examples and information.
Note [UnivCo]
~~~~~~~~~~~~~
The UnivCo ("universal coercion") serves two rather separate functions:
- the implementation for unsafeCoerce#
- placeholder for phantom parameters in a TyConAppCo
At Representational, it asserts that two (possibly unrelated)
types have the same representation and can be casted to one another.
This form is necessary for unsafeCoerce#.
For optimisation purposes, it is convenient to allow UnivCo to appear
at Nominal role. If we have
data Foo a = MkFoo (F a) -- F is a type family
and we want an unsafe coercion from Foo Int to Foo Bool, then it would
be nice to have (TyConAppCo Foo (UnivCo Nominal Int Bool)). So, we allow
Nominal UnivCo's.
At Phantom role, it is used as an argument to TyConAppCo in the place
of a phantom parameter (a type parameter unused in the type definition).
For example:
data Q a = MkQ Int
We want a coercion for (Q Bool) ~R (Q Char).
(TyConAppCo Representational Q [UnivCo Phantom Bool Char]) does the trick.
Note [TyConAppCo roles]
~~~~~~~~~~~~~~~~~~~~~~~
The TyConAppCo constructor has a role parameter, indicating the role at
which the coercion proves equality. The choice of this parameter affects
the required roles of the arguments of the TyConAppCo. To help explain
it, assume the following definition:
newtype Age = MkAge Int
Nominal: All arguments must have role Nominal. Why? So that Foo Age ~N Foo Int
does *not* hold.
Representational: All arguments must have the roles corresponding to the
result of tyConRoles on the TyCon. This is the whole point of having
roles on the TyCon to begin with. So, we can have Foo Age ~R Foo Int,
if Foo's parameter has role R.
If a Representational TyConAppCo is over-saturated (which is otherwise fine),
the spill-over arguments must all be at Nominal. This corresponds to the
behavior for AppCo.
Phantom: All arguments must have role Phantom. This one isn't strictly
necessary for soundness, but this choice removes ambiguity.
The rules here also dictate what the parameters to mkTyConAppCo.
************************************************************************
* *
\subsection{Coercion variables}
* *
************************************************************************
-}
coVarName :: CoVar -> Name
coVarName = varName
setCoVarUnique :: CoVar -> Unique -> CoVar
setCoVarUnique = setVarUnique
setCoVarName :: CoVar -> Name -> CoVar
setCoVarName = setVarName
isCoVar :: Var -> Bool
isCoVar v = isCoVarType (varType v)
isCoVarType :: Type -> Bool
isCoVarType ty -- Tests for t1 ~# t2, the unboxed equality
= case splitTyConApp_maybe ty of
Just (tc,tys) -> (tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey)
&& tys `lengthAtLeast` 2
Nothing -> False
tyCoVarsOfCo :: Coercion -> VarSet
-- Extracts type and coercion variables from a coercion
tyCoVarsOfCo (Refl _ ty) = tyVarsOfType ty
tyCoVarsOfCo (TyConAppCo _ _ cos) = tyCoVarsOfCos cos
tyCoVarsOfCo (AppCo co1 co2) = tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2
tyCoVarsOfCo (ForAllCo tv co) = tyCoVarsOfCo co `delVarSet` tv
tyCoVarsOfCo (CoVarCo v) = unitVarSet v
tyCoVarsOfCo (AxiomInstCo _ _ cos) = tyCoVarsOfCos cos
tyCoVarsOfCo (UnivCo _ _ ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
tyCoVarsOfCo (SymCo co) = tyCoVarsOfCo co
tyCoVarsOfCo (TransCo co1 co2) = tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2
tyCoVarsOfCo (NthCo _ co) = tyCoVarsOfCo co
tyCoVarsOfCo (LRCo _ co) = tyCoVarsOfCo co
tyCoVarsOfCo (InstCo co ty) = tyCoVarsOfCo co `unionVarSet` tyVarsOfType ty
tyCoVarsOfCo (SubCo co) = tyCoVarsOfCo co
tyCoVarsOfCo (AxiomRuleCo _ ts cs) = tyVarsOfTypes ts `unionVarSet` tyCoVarsOfCos cs
tyCoVarsOfCos :: [Coercion] -> VarSet
tyCoVarsOfCos = mapUnionVarSet tyCoVarsOfCo
coVarsOfCo :: Coercion -> VarSet
-- Extract *coerction* variables only. Tiresome to repeat the code, but easy.
coVarsOfCo (Refl _ _) = emptyVarSet
coVarsOfCo (TyConAppCo _ _ cos) = coVarsOfCos cos
coVarsOfCo (AppCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2
coVarsOfCo (ForAllCo _ co) = coVarsOfCo co
coVarsOfCo (CoVarCo v) = unitVarSet v
coVarsOfCo (AxiomInstCo _ _ cos) = coVarsOfCos cos
coVarsOfCo (UnivCo _ _ _ _) = emptyVarSet
coVarsOfCo (SymCo co) = coVarsOfCo co
coVarsOfCo (TransCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2
coVarsOfCo (NthCo _ co) = coVarsOfCo co
coVarsOfCo (LRCo _ co) = coVarsOfCo co
coVarsOfCo (InstCo co _) = coVarsOfCo co
coVarsOfCo (SubCo co) = coVarsOfCo co
coVarsOfCo (AxiomRuleCo _ _ cos) = coVarsOfCos cos
coVarsOfCos :: [Coercion] -> VarSet
coVarsOfCos = mapUnionVarSet coVarsOfCo
coercionSize :: Coercion -> Int
coercionSize (Refl _ ty) = typeSize ty
coercionSize (TyConAppCo _ _ cos) = 1 + sum (map coercionSize cos)
coercionSize (AppCo co1 co2) = coercionSize co1 + coercionSize co2
coercionSize (ForAllCo _ co) = 1 + coercionSize co
coercionSize (CoVarCo _) = 1
coercionSize (AxiomInstCo _ _ cos) = 1 + sum (map coercionSize cos)
coercionSize (UnivCo _ _ ty1 ty2) = typeSize ty1 + typeSize ty2
coercionSize (SymCo co) = 1 + coercionSize co
coercionSize (TransCo co1 co2) = 1 + coercionSize co1 + coercionSize co2
coercionSize (NthCo _ co) = 1 + coercionSize co
coercionSize (LRCo _ co) = 1 + coercionSize co
coercionSize (InstCo co ty) = 1 + coercionSize co + typeSize ty
coercionSize (SubCo co) = 1 + coercionSize co
coercionSize (AxiomRuleCo _ tys cos) = 1 + sum (map typeSize tys)
+ sum (map coercionSize cos)
{-
************************************************************************
* *
Tidying coercions
* *
************************************************************************
-}
tidyCo :: TidyEnv -> Coercion -> Coercion
tidyCo env@(_, subst) co
= go co
where
go (Refl r ty) = Refl r (tidyType env ty)
go (TyConAppCo r tc cos) = let args = map go cos
in args `seqList` TyConAppCo r tc args
go (AppCo co1 co2) = (AppCo $! go co1) $! go co2
go (ForAllCo tv co) = ForAllCo tvp $! (tidyCo envp co)
where
(envp, tvp) = tidyTyVarBndr env tv
go (CoVarCo cv) = case lookupVarEnv subst cv of
Nothing -> CoVarCo cv
Just cv' -> CoVarCo cv'
go (AxiomInstCo con ind cos) = let args = tidyCos env cos
in args `seqList` AxiomInstCo con ind args
go (UnivCo s r ty1 ty2) = (UnivCo s r $! tidyType env ty1) $! tidyType env ty2
go (SymCo co) = SymCo $! go co
go (TransCo co1 co2) = (TransCo $! go co1) $! go co2
go (NthCo d co) = NthCo d $! go co
go (LRCo lr co) = LRCo lr $! go co
go (InstCo co ty) = (InstCo $! go co) $! tidyType env ty
go (SubCo co) = SubCo $! go co
go (AxiomRuleCo ax tys cos) = let tys1 = map (tidyType env) tys
cos1 = tidyCos env cos
in tys1 `seqList` cos1 `seqList`
AxiomRuleCo ax tys1 cos1
tidyCos :: TidyEnv -> [Coercion] -> [Coercion]
tidyCos env = map (tidyCo env)
{-
************************************************************************
* *
Pretty-printing coercions
* *
************************************************************************
@pprCo@ is the standard @Coercion@ printer; the overloaded @ppr@
function is defined to use this. @pprParendCo@ is the same, except it
puts parens around the type, except for the atomic cases.
@pprParendCo@ works just by setting the initial context precedence
very high.
-}
instance Outputable Coercion where
ppr = pprCo
pprCo, pprParendCo :: Coercion -> SDoc
pprCo co = ppr_co TopPrec co
pprParendCo co = ppr_co TyConPrec co
ppr_co :: TyPrec -> Coercion -> SDoc
ppr_co _ (Refl r ty) = angleBrackets (ppr ty) <> ppr_role r
ppr_co p co@(TyConAppCo _ tc [_,_])
| tc `hasKey` funTyConKey = ppr_fun_co p co
ppr_co _ (TyConAppCo r tc cos) = pprTcApp TyConPrec ppr_co tc cos <> ppr_role r
ppr_co p (AppCo co1 co2) = maybeParen p TyConPrec $
pprCo co1 <+> ppr_co TyConPrec co2
ppr_co p co@(ForAllCo {}) = ppr_forall_co p co
ppr_co _ (CoVarCo cv) = parenSymOcc (getOccName cv) (ppr cv)
ppr_co p (AxiomInstCo con index cos)
= pprPrefixApp p (ppr (getName con) <> brackets (ppr index))
(map (ppr_co TyConPrec) cos)
ppr_co p co@(TransCo {}) = maybeParen p FunPrec $
case trans_co_list co [] of
[] -> panic "ppr_co"
(co:cos) -> sep ( ppr_co FunPrec co
: [ char ';' <+> ppr_co FunPrec co | co <- cos])
ppr_co p (InstCo co ty) = maybeParen p TyConPrec $
pprParendCo co <> ptext (sLit "@") <> pprType ty
ppr_co p (UnivCo s r ty1 ty2) = pprPrefixApp p (ptext (sLit "UnivCo") <+> ftext s <+> ppr r)
[pprParendType ty1, pprParendType ty2]
ppr_co p (SymCo co) = pprPrefixApp p (ptext (sLit "Sym")) [pprParendCo co]
ppr_co p (NthCo n co) = pprPrefixApp p (ptext (sLit "Nth:") <> int n) [pprParendCo co]
ppr_co p (LRCo sel co) = pprPrefixApp p (ppr sel) [pprParendCo co]
ppr_co p (SubCo co) = pprPrefixApp p (ptext (sLit "Sub")) [pprParendCo co]
ppr_co p (AxiomRuleCo co ts cs) = maybeParen p TopPrec $
ppr_axiom_rule_co co ts cs
ppr_axiom_rule_co :: CoAxiomRule -> [Type] -> [Coercion] -> SDoc
ppr_axiom_rule_co co ts ps = ppr (coaxrName co) <> ppTs ts $$ nest 2 (ppPs ps)
where
ppTs [] = Outputable.empty
ppTs [t] = ptext (sLit "@") <> ppr_type TopPrec t
ppTs ts = ptext (sLit "@") <>
parens (hsep $ punctuate comma $ map pprType ts)
ppPs [] = Outputable.empty
ppPs [p] = pprParendCo p
ppPs (p : ps) = ptext (sLit "(") <+> pprCo p $$
vcat [ ptext (sLit ",") <+> pprCo q | q <- ps ] $$
ptext (sLit ")")
ppr_role :: Role -> SDoc
ppr_role r = underscore <> pp_role
where pp_role = case r of
Nominal -> char 'N'
Representational -> char 'R'
Phantom -> char 'P'
trans_co_list :: Coercion -> [Coercion] -> [Coercion]
trans_co_list (TransCo co1 co2) cos = trans_co_list co1 (trans_co_list co2 cos)
trans_co_list co cos = co : cos
instance Outputable LeftOrRight where
ppr CLeft = ptext (sLit "Left")
ppr CRight = ptext (sLit "Right")
ppr_fun_co :: TyPrec -> Coercion -> SDoc
ppr_fun_co p co = pprArrowChain p (split co)
where
split :: Coercion -> [SDoc]
split (TyConAppCo _ f [arg,res])
| f `hasKey` funTyConKey
= ppr_co FunPrec arg : split res
split co = [ppr_co TopPrec co]
ppr_forall_co :: TyPrec -> Coercion -> SDoc
ppr_forall_co p ty
= maybeParen p FunPrec $
sep [pprForAll tvs, ppr_co TopPrec rho]
where
(tvs, rho) = split1 [] ty
split1 tvs (ForAllCo tv ty) = split1 (tv:tvs) ty
split1 tvs ty = (reverse tvs, ty)
pprCoAxiom :: CoAxiom br -> SDoc
pprCoAxiom ax@(CoAxiom { co_ax_tc = tc, co_ax_branches = branches })
= hang (ptext (sLit "axiom") <+> ppr ax <+> dcolon)
2 (vcat (map (pprCoAxBranch tc) $ fromBranchList branches))
pprCoAxBranch :: TyCon -> CoAxBranch -> SDoc
pprCoAxBranch fam_tc (CoAxBranch { cab_tvs = tvs
, cab_lhs = lhs
, cab_rhs = rhs })
= hang (pprUserForAll tvs)
2 (hang (pprTypeApp fam_tc lhs) 2 (equals <+> (ppr rhs)))
pprCoAxBranchHdr :: CoAxiom br -> BranchIndex -> SDoc
pprCoAxBranchHdr ax@(CoAxiom { co_ax_tc = fam_tc, co_ax_name = name }) index
| CoAxBranch { cab_lhs = tys, cab_loc = loc } <- coAxiomNthBranch ax index
= hang (pprTypeApp fam_tc tys)
2 (ptext (sLit "-- Defined") <+> ppr_loc loc)
where
ppr_loc loc
| isGoodSrcSpan loc
= ptext (sLit "at") <+> ppr (srcSpanStart loc)
| otherwise
= ptext (sLit "in") <+>
quotes (ppr (nameModule name))
{-
************************************************************************
* *
Functions over Kinds
* *
************************************************************************
-}
-- | This breaks a 'Coercion' with type @T A B C ~ T D E F@ into
-- a list of 'Coercion's of kinds @A ~ D@, @B ~ E@ and @E ~ F@. Hence:
--
-- > decomposeCo 3 c = [nth 0 c, nth 1 c, nth 2 c]
decomposeCo :: Arity -> Coercion -> [Coercion]
decomposeCo arity co
= [mkNthCo n co | n <- [0..(arity-1)] ]
-- Remember, Nth is zero-indexed
-- | Attempts to obtain the type variable underlying a 'Coercion'
getCoVar_maybe :: Coercion -> Maybe CoVar
getCoVar_maybe (CoVarCo cv) = Just cv
getCoVar_maybe _ = Nothing
-- first result has role equal to input; second result is Nominal
splitAppCo_maybe :: Coercion -> Maybe (Coercion, Coercion)
-- ^ Attempt to take a coercion application apart.
splitAppCo_maybe (AppCo co1 co2) = Just (co1, co2)
splitAppCo_maybe (TyConAppCo r tc cos)
| isDecomposableTyCon tc || cos `lengthExceeds` tyConArity tc
, Just (cos', co') <- snocView cos
, Just co'' <- setNominalRole_maybe co'
= Just (mkTyConAppCo r tc cos', co'') -- Never create unsaturated type family apps!
-- Use mkTyConAppCo to preserve the invariant
-- that identity coercions are always represented by Refl
splitAppCo_maybe (Refl r ty)
| Just (ty1, ty2) <- splitAppTy_maybe ty
= Just (Refl r ty1, Refl Nominal ty2)
splitAppCo_maybe _ = Nothing
splitForAllCo_maybe :: Coercion -> Maybe (TyVar, Coercion)
splitForAllCo_maybe (ForAllCo tv co) = Just (tv, co)
splitForAllCo_maybe _ = Nothing
-------------------------------------------------------
-- and some coercion kind stuff
coVarKind :: CoVar -> (Type,Type)
coVarKind cv
| Just (tc, [_kind,ty1,ty2]) <- splitTyConApp_maybe (varType cv)
= ASSERT(tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey)
(ty1,ty2)
| otherwise = panic "coVarKind, non coercion variable"
coVarRole :: CoVar -> Role
coVarRole cv
| tc `hasKey` eqPrimTyConKey
= Nominal
| tc `hasKey` eqReprPrimTyConKey
= Representational
| otherwise
= pprPanic "coVarRole: unknown tycon" (ppr cv)
where
tc = case tyConAppTyCon_maybe (varType cv) of
Just tc0 -> tc0
Nothing -> pprPanic "coVarRole: not tyconapp" (ppr cv)
-- | Makes a coercion type from two types: the types whose equality
-- is proven by the relevant 'Coercion'
mkCoercionType :: Role -> Type -> Type -> Type
mkCoercionType Nominal = mkPrimEqPred
mkCoercionType Representational = mkReprPrimEqPred
mkCoercionType Phantom = panic "mkCoercionType"
isReflCo :: Coercion -> Bool
isReflCo (Refl {}) = True
isReflCo _ = False
isReflCo_maybe :: Coercion -> Maybe Type
isReflCo_maybe (Refl _ ty) = Just ty
isReflCo_maybe _ = Nothing
{-
************************************************************************
* *
Building coercions
* *
************************************************************************
Note [Role twiddling functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are a plethora of functions for twiddling roles:
mkSubCo: Requires a nominal input coercion and always produces a
representational output. This is used when you (the programmer) are sure you
know exactly that role you have and what you want.
downgradeRole_maybe: This function takes both the input role and the output role
as parameters. (The *output* role comes first!) It can only *downgrade* a
role -- that is, change it from N to R or P, or from R to P. This one-way
behavior is why there is the "_maybe". If an upgrade is requested, this
function produces Nothing. This is used when you need to change the role of a
coercion, but you're not sure (as you're writing the code) of which roles are
involved.
This function could have been written using coercionRole to ascertain the role
of the input. But, that function is recursive, and the caller of downgradeRole_maybe
often knows the input role. So, this is more efficient.
downgradeRole: This is just like downgradeRole_maybe, but it panics if the conversion
isn't a downgrade.
setNominalRole_maybe: This is the only function that can *upgrade* a coercion. The result
(if it exists) is always Nominal. The input can be at any role. It works on a
"best effort" basis, as it should never be strictly necessary to upgrade a coercion
during compilation. It is currently only used within GHC in splitAppCo_maybe. In order
to be a proper inverse of mkAppCo, the second coercion that splitAppCo_maybe returns
must be nominal. But, it's conceivable that splitAppCo_maybe is operating over a
TyConAppCo that uses a representational coercion. Hence the need for setNominalRole_maybe.
splitAppCo_maybe, in turn, is used only within coercion optimization -- thus, it is
not absolutely critical that setNominalRole_maybe be complete.
Note that setNominalRole_maybe will never upgrade a phantom UnivCo. Phantom
UnivCos are perfectly type-safe, whereas representational and nominal ones are
not. Indeed, `unsafeCoerce` is implemented via a representational UnivCo.
(Nominal ones are no worse than representational ones, so this function *will*
change a UnivCo Representational to a UnivCo Nominal.)
Conal Elliott also came across a need for this function while working with the GHC
API, as he was decomposing Core casts. The Core casts use representational coercions,
as they must, but his use case required nominal coercions (he was building a GADT).
So, that's why this function is exported from this module.
One might ask: shouldn't downgradeRole_maybe just use setNominalRole_maybe as appropriate?
I (Richard E.) have decided not to do this, because upgrading a role is bizarre and
a caller should have to ask for this behavior explicitly.
-}
mkCoVarCo :: CoVar -> Coercion
-- cv :: s ~# t
mkCoVarCo cv
| ty1 `eqType` ty2 = Refl (coVarRole cv) ty1
| otherwise = CoVarCo cv
where
(ty1, ty2) = ASSERT( isCoVar cv ) coVarKind cv
mkReflCo :: Role -> Type -> Coercion
mkReflCo = Refl
mkAxInstCo :: Role -> CoAxiom br -> BranchIndex -> [Type] -> Coercion
-- mkAxInstCo can legitimately be called over-staturated;
-- i.e. with more type arguments than the coercion requires
mkAxInstCo role ax index tys
| arity == n_tys = downgradeRole role ax_role $ AxiomInstCo ax_br index rtys
| otherwise = ASSERT( arity < n_tys )
downgradeRole role ax_role $
foldl AppCo (AxiomInstCo ax_br index (take arity rtys))
(drop arity rtys)
where
n_tys = length tys
ax_br = toBranchedAxiom ax
branch = coAxiomNthBranch ax_br index
arity = length $ coAxBranchTyVars branch
arg_roles = coAxBranchRoles branch
rtys = zipWith mkReflCo (arg_roles ++ repeat Nominal) tys
ax_role = coAxiomRole ax
-- to be used only with unbranched axioms
mkUnbranchedAxInstCo :: Role -> CoAxiom Unbranched -> [Type] -> Coercion
mkUnbranchedAxInstCo role ax tys
= mkAxInstCo role ax 0 tys
mkAxInstLHS, mkAxInstRHS :: CoAxiom br -> BranchIndex -> [Type] -> Type
-- Instantiate the axiom with specified types,
-- returning the instantiated RHS
-- A companion to mkAxInstCo:
-- mkAxInstRhs ax index tys = snd (coercionKind (mkAxInstCo ax index tys))
mkAxInstLHS ax index tys
| CoAxBranch { cab_tvs = tvs, cab_lhs = lhs } <- coAxiomNthBranch ax index
, (tys1, tys2) <- splitAtList tvs tys
= ASSERT( tvs `equalLength` tys1 )
mkTyConApp (coAxiomTyCon ax) (substTysWith tvs tys1 lhs ++ tys2)
mkAxInstRHS ax index tys
| CoAxBranch { cab_tvs = tvs, cab_rhs = rhs } <- coAxiomNthBranch ax index
, (tys1, tys2) <- splitAtList tvs tys
= ASSERT( tvs `equalLength` tys1 )
mkAppTys (substTyWith tvs tys1 rhs) tys2
mkUnbranchedAxInstRHS :: CoAxiom Unbranched -> [Type] -> Type
mkUnbranchedAxInstRHS ax = mkAxInstRHS ax 0
-- | Apply a 'Coercion' to another 'Coercion'.
-- The second coercion must be Nominal, unless the first is Phantom.
-- If the first is Phantom, then the second can be either Phantom or Nominal.
mkAppCo :: Coercion -> Coercion -> Coercion
mkAppCo co1 co2 = mkAppCoFlexible co1 Nominal co2
-- Note, mkAppCo is careful to maintain invariants regarding
-- where Refl constructors appear; see the comments in the definition
-- of Coercion and the Note [Refl invariant] in types/TypeRep.lhs.
-- | Apply a 'Coercion' to another 'Coercion'.
-- The second 'Coercion's role is given, making this more flexible than
-- 'mkAppCo'.
mkAppCoFlexible :: Coercion -> Role -> Coercion -> Coercion
mkAppCoFlexible (Refl r ty1) _ (Refl _ ty2)
= Refl r (mkAppTy ty1 ty2)
mkAppCoFlexible (Refl r ty1) r2 co2
| Just (tc, tys) <- splitTyConApp_maybe ty1
-- Expand type synonyms; a TyConAppCo can't have a type synonym (Trac #9102)
= TyConAppCo r tc (zip_roles (tyConRolesX r tc) tys)
where
zip_roles (r1:_) [] = [downgradeRole r1 r2 co2]
zip_roles (r1:rs) (ty1:tys) = mkReflCo r1 ty1 : zip_roles rs tys
zip_roles _ _ = panic "zip_roles" -- but the roles are infinite...
mkAppCoFlexible (TyConAppCo r tc cos) r2 co
= case r of
Nominal -> ASSERT( r2 == Nominal )
TyConAppCo Nominal tc (cos ++ [co])
Representational -> TyConAppCo Representational tc (cos ++ [co'])
where new_role = (tyConRolesX Representational tc) !! (length cos)
co' = downgradeRole new_role r2 co
Phantom -> TyConAppCo Phantom tc (cos ++ [mkPhantomCo co])
mkAppCoFlexible co1 _r2 co2 = ASSERT( _r2 == Nominal )
AppCo co1 co2
-- | Applies multiple 'Coercion's to another 'Coercion', from left to right.
-- See also 'mkAppCo'.
mkAppCos :: Coercion -> [Coercion] -> Coercion
mkAppCos co1 cos = foldl mkAppCo co1 cos
-- | Apply a type constructor to a list of coercions. It is the
-- caller's responsibility to get the roles correct on argument coercions.
mkTyConAppCo :: Role -> TyCon -> [Coercion] -> Coercion
mkTyConAppCo r tc cos
-- Expand type synonyms
| Just (tv_co_prs, rhs_ty, leftover_cos) <- tcExpandTyCon_maybe tc cos
= mkAppCos (liftCoSubst r tv_co_prs rhs_ty) leftover_cos
| Just tys <- traverse isReflCo_maybe cos
= Refl r (mkTyConApp tc tys) -- See Note [Refl invariant]
| otherwise = TyConAppCo r tc cos
-- | Make a function 'Coercion' between two other 'Coercion's
mkFunCo :: Role -> Coercion -> Coercion -> Coercion
mkFunCo r co1 co2 = mkTyConAppCo r funTyCon [co1, co2]
-- | Make a 'Coercion' which binds a variable within an inner 'Coercion'
mkForAllCo :: Var -> Coercion -> Coercion
-- note that a TyVar should be used here, not a CoVar (nor a TcTyVar)
mkForAllCo tv (Refl r ty) = ASSERT( isTyVar tv ) Refl r (mkForAllTy tv ty)
mkForAllCo tv co = ASSERT( isTyVar tv ) ForAllCo tv co
-------------------------------
-- | Create a symmetric version of the given 'Coercion' that asserts
-- equality between the same types but in the other "direction", so
-- a kind of @t1 ~ t2@ becomes the kind @t2 ~ t1@.
mkSymCo :: Coercion -> Coercion
-- Do a few simple optimizations, but don't bother pushing occurrences
-- of symmetry to the leaves; the optimizer will take care of that.
mkSymCo co@(Refl {}) = co
mkSymCo (UnivCo s r ty1 ty2) = UnivCo s r ty2 ty1
mkSymCo (SymCo co) = co
mkSymCo co = SymCo co
-- | Create a new 'Coercion' by composing the two given 'Coercion's transitively.
mkTransCo :: Coercion -> Coercion -> Coercion
mkTransCo (Refl {}) co = co
mkTransCo co (Refl {}) = co
mkTransCo co1 co2 = TransCo co1 co2
-- the Role is the desired one. It is the caller's responsibility to make
-- sure this request is reasonable
mkNthCoRole :: Role -> Int -> Coercion -> Coercion
mkNthCoRole role n co
= downgradeRole role nth_role $ nth_co
where
nth_co = mkNthCo n co
nth_role = coercionRole nth_co
mkNthCo :: Int -> Coercion -> Coercion
mkNthCo n (Refl r ty) = ASSERT( ok_tc_app ty n )
Refl r' (tyConAppArgN n ty)
where tc = tyConAppTyCon ty
r' = nthRole r tc n
mkNthCo n co = ASSERT( ok_tc_app _ty1 n && ok_tc_app _ty2 n )
NthCo n co
where
Pair _ty1 _ty2 = coercionKind co
mkLRCo :: LeftOrRight -> Coercion -> Coercion
mkLRCo lr (Refl eq ty) = Refl eq (pickLR lr (splitAppTy ty))
mkLRCo lr co = LRCo lr co
ok_tc_app :: Type -> Int -> Bool
ok_tc_app ty n = case splitTyConApp_maybe ty of
Just (_, tys) -> tys `lengthExceeds` n
Nothing -> False
-- | Instantiates a 'Coercion' with a 'Type' argument.
mkInstCo :: Coercion -> Type -> Coercion
mkInstCo co ty = InstCo co ty
-- | Manufacture an unsafe coercion from thin air.
-- Currently (May 14) this is used only to implement the
-- @unsafeCoerce#@ primitive. Optimise by pushing
-- down through type constructors.
mkUnsafeCo :: Type -> Type -> Coercion
mkUnsafeCo = mkUnivCo (fsLit "mkUnsafeCo") Representational
mkUnivCo :: FastString -> Role -> Type -> Type -> Coercion
mkUnivCo prov role ty1 ty2
| ty1 `eqType` ty2 = Refl role ty1
| otherwise = UnivCo prov role ty1 ty2
mkAxiomRuleCo :: CoAxiomRule -> [Type] -> [Coercion] -> Coercion
mkAxiomRuleCo = AxiomRuleCo
-- input coercion is Nominal; see also Note [Role twiddling functions]
mkSubCo :: Coercion -> Coercion
mkSubCo (Refl Nominal ty) = Refl Representational ty
mkSubCo (TyConAppCo Nominal tc cos)
= TyConAppCo Representational tc (applyRoles tc cos)
mkSubCo (UnivCo s Nominal ty1 ty2) = UnivCo s Representational ty1 ty2
mkSubCo co = ASSERT2( coercionRole co == Nominal, ppr co <+> ppr (coercionRole co) )
SubCo co
-- only *downgrades* a role. See Note [Role twiddling functions]
downgradeRole_maybe :: Role -- desired role
-> Role -- current role
-> Coercion -> Maybe Coercion
downgradeRole_maybe Representational Nominal co = Just (mkSubCo co)
downgradeRole_maybe Nominal Representational _ = Nothing
downgradeRole_maybe Phantom Phantom co = Just co
downgradeRole_maybe Phantom _ co = Just (mkPhantomCo co)
downgradeRole_maybe _ Phantom _ = Nothing
downgradeRole_maybe _ _ co = Just co
-- panics if the requested conversion is not a downgrade.
-- See also Note [Role twiddling functions]
downgradeRole :: Role -- desired role
-> Role -- current role
-> Coercion -> Coercion
downgradeRole r1 r2 co
= case downgradeRole_maybe r1 r2 co of
Just co' -> co'
Nothing -> pprPanic "downgradeRole" (ppr co)
-- Converts a coercion to be nominal, if possible.
-- See also Note [Role twiddling functions]
setNominalRole_maybe :: Coercion -> Maybe Coercion
setNominalRole_maybe co
| Nominal <- coercionRole co = Just co
setNominalRole_maybe (SubCo co) = Just co
setNominalRole_maybe (Refl _ ty) = Just $ Refl Nominal ty
setNominalRole_maybe (TyConAppCo Representational tc coes)
= do { cos' <- mapM setNominalRole_maybe coes
; return $ TyConAppCo Nominal tc cos' }
setNominalRole_maybe (UnivCo s Representational ty1 ty2) = Just $ UnivCo s Nominal ty1 ty2
-- We do *not* promote UnivCo Phantom, as that's unsafe.
-- UnivCo Nominal is no more unsafe than UnivCo Representational
setNominalRole_maybe (TransCo co1 co2)
= TransCo <$> setNominalRole_maybe co1 <*> setNominalRole_maybe co2
setNominalRole_maybe (AppCo co1 co2)
= AppCo <$> setNominalRole_maybe co1 <*> pure co2
setNominalRole_maybe (ForAllCo tv co)
= ForAllCo tv <$> setNominalRole_maybe co
setNominalRole_maybe (NthCo n co)
= NthCo n <$> setNominalRole_maybe co
setNominalRole_maybe (InstCo co ty)
= InstCo <$> setNominalRole_maybe co <*> pure ty
setNominalRole_maybe _ = Nothing
-- takes any coercion and turns it into a Phantom coercion
mkPhantomCo :: Coercion -> Coercion
mkPhantomCo co
| Just ty <- isReflCo_maybe co = Refl Phantom ty
| Pair ty1 ty2 <- coercionKind co = UnivCo (fsLit "mkPhantomCo") Phantom ty1 ty2
-- don't optimise here... wait for OptCoercion
-- All input coercions are assumed to be Nominal,
-- or, if Role is Phantom, the Coercion can be Phantom, too.
applyRole :: Role -> Coercion -> Coercion
applyRole Nominal = id
applyRole Representational = mkSubCo
applyRole Phantom = mkPhantomCo
-- Convert args to a TyConAppCo Nominal to the same TyConAppCo Representational
applyRoles :: TyCon -> [Coercion] -> [Coercion]
applyRoles tc cos
= zipWith applyRole (tyConRolesX Representational tc) cos
-- the Role parameter is the Role of the TyConAppCo
-- defined here because this is intimiately concerned with the implementation
-- of TyConAppCo
tyConRolesX :: Role -> TyCon -> [Role]
tyConRolesX Representational tc = tyConRoles tc ++ repeat Nominal
tyConRolesX role _ = repeat role
nthRole :: Role -> TyCon -> Int -> Role
nthRole Nominal _ _ = Nominal
nthRole Phantom _ _ = Phantom
nthRole Representational tc n
= (tyConRolesX Representational tc) !! n
ltRole :: Role -> Role -> Bool
-- Is one role "less" than another?
-- Nominal < Representational < Phantom
ltRole Phantom _ = False
ltRole Representational Phantom = True
ltRole Representational _ = False
ltRole Nominal Nominal = False
ltRole Nominal _ = True
-- See note [Newtype coercions] in TyCon
-- | Create a coercion constructor (axiom) suitable for the given
-- newtype 'TyCon'. The 'Name' should be that of a new coercion
-- 'CoAxiom', the 'TyVar's the arguments expected by the @newtype@ and
-- the type the appropriate right hand side of the @newtype@, with
-- the free variables a subset of those 'TyVar's.
mkNewTypeCo :: Name -> TyCon -> [TyVar] -> [Role] -> Type -> CoAxiom Unbranched
mkNewTypeCo name tycon tvs roles rhs_ty
= CoAxiom { co_ax_unique = nameUnique name
, co_ax_name = name
, co_ax_implicit = True -- See Note [Implicit axioms] in TyCon
, co_ax_role = Representational
, co_ax_tc = tycon
, co_ax_branches = FirstBranch branch }
where branch = CoAxBranch { cab_loc = getSrcSpan name
, cab_tvs = tvs
, cab_lhs = mkTyVarTys tvs
, cab_roles = roles
, cab_rhs = rhs_ty
, cab_incomps = [] }
mkPiCos :: Role -> [Var] -> Coercion -> Coercion
mkPiCos r vs co = foldr (mkPiCo r) co vs
mkPiCo :: Role -> Var -> Coercion -> Coercion
mkPiCo r v co | isTyVar v = mkForAllCo v co
| otherwise = mkFunCo r (mkReflCo r (varType v)) co
-- The first coercion *must* be Nominal.
mkCoCast :: Coercion -> Coercion -> Coercion
-- (mkCoCast (c :: s1 ~# t1) (g :: (s1 ~# t1) ~# (s2 ~# t2)
mkCoCast c g
= mkSymCo g1 `mkTransCo` c `mkTransCo` g2
where
-- g :: (s1 ~# s2) ~# (t1 ~# t2)
-- g1 :: s1 ~# t1
-- g2 :: s2 ~# t2
[_reflk, g1, g2] = decomposeCo 3 g
-- Remember, (~#) :: forall k. k -> k -> *
-- so it takes *three* arguments, not two
{-
************************************************************************
* *
Newtypes
* *
************************************************************************
-}
-- | If @co :: T ts ~ rep_ty@ then:
--
-- > instNewTyCon_maybe T ts = Just (rep_ty, co)
--
-- Checks for a newtype, and for being saturated
instNewTyCon_maybe :: TyCon -> [Type] -> Maybe (Type, Coercion)
instNewTyCon_maybe tc tys
| Just (tvs, ty, co_tc) <- unwrapNewTyConEtad_maybe tc -- Check for newtype
, tvs `leLength` tys -- Check saturated enough
= Just ( applyTysX tvs ty tys
, mkUnbranchedAxInstCo Representational co_tc tys)
| otherwise
= Nothing
{-
************************************************************************
* *
Type normalisation
* *
************************************************************************
-}
-- | A function to check if we can reduce a type by one step. Used
-- with 'topNormaliseTypeX_maybe'.
type NormaliseStepper = RecTcChecker
-> TyCon -- tc
-> [Type] -- tys
-> NormaliseStepResult
-- | The result of stepping in a normalisation function.
-- See 'topNormaliseTypeX_maybe'.
data NormaliseStepResult
= NS_Done -- ^ nothing more to do
| NS_Abort -- ^ utter failure. The outer function should fail too.
| NS_Step RecTcChecker Type Coercion -- ^ we stepped, yielding new bits;
-- ^ co :: old type ~ new type
modifyStepResultCo :: (Coercion -> Coercion)
-> NormaliseStepResult -> NormaliseStepResult
modifyStepResultCo f (NS_Step rec_nts ty co) = NS_Step rec_nts ty (f co)
modifyStepResultCo _ result = result
-- | Try one stepper and then try the next, if the first doesn't make
-- progress.
composeSteppers :: NormaliseStepper -> NormaliseStepper
-> NormaliseStepper
composeSteppers step1 step2 rec_nts tc tys
= case step1 rec_nts tc tys of
success@(NS_Step {}) -> success
NS_Done -> step2 rec_nts tc tys
NS_Abort -> NS_Abort
-- | A 'NormaliseStepper' that unwraps newtypes, careful not to fall into
-- a loop. If it would fall into a loop, it produces 'NS_Abort'.
unwrapNewTypeStepper :: NormaliseStepper
unwrapNewTypeStepper rec_nts tc tys
| Just (ty', co) <- instNewTyCon_maybe tc tys
= case checkRecTc rec_nts tc of
Just rec_nts' -> NS_Step rec_nts' ty' co
Nothing -> NS_Abort
| otherwise
= NS_Done
-- | A general function for normalising the top-level of a type. It continues
-- to use the provided 'NormaliseStepper' until that function fails, and then
-- this function returns. The roles of the coercions produced by the
-- 'NormaliseStepper' must all be the same, which is the role returned from
-- the call to 'topNormaliseTypeX_maybe'.
topNormaliseTypeX_maybe :: NormaliseStepper -> Type -> Maybe (Coercion, Type)
topNormaliseTypeX_maybe stepper
= go initRecTc Nothing
where
go rec_nts mb_co1 ty
| Just (tc, tys) <- splitTyConApp_maybe ty
= case stepper rec_nts tc tys of
NS_Step rec_nts' ty' co2
-> go rec_nts' (mb_co1 `trans` co2) ty'
NS_Done -> all_done
NS_Abort -> Nothing
| otherwise
= all_done
where
all_done | Just co <- mb_co1 = Just (co, ty)
| otherwise = Nothing
Nothing `trans` co2 = Just co2
(Just co1) `trans` co2 = Just (co1 `mkTransCo` co2)
topNormaliseNewType_maybe :: Type -> Maybe (Coercion, Type)
-- ^ Sometimes we want to look through a @newtype@ and get its associated coercion.
-- This function strips off @newtype@ layers enough to reveal something that isn't
-- a @newtype@, or responds False to ok_tc. Specifically, here's the invariant:
--
-- > topNormaliseNewType_maybe ty = Just (co, ty')
--
-- then (a) @co : ty0 ~ ty'@.
-- (b) ty' is not a newtype.
--
-- The function returns @Nothing@ for non-@newtypes@,
-- or unsaturated applications
--
-- This function does *not* look through type families, because it has no access to
-- the type family environment. If you do have that at hand, consider to use
-- topNormaliseType_maybe, which should be a drop-in replacement for
-- topNormaliseNewType_maybe
--
topNormaliseNewType_maybe ty
= topNormaliseTypeX_maybe unwrapNewTypeStepper ty
{-
************************************************************************
* *
Equality of coercions
* *
************************************************************************
-}
-- | Determines syntactic equality of coercions
coreEqCoercion :: Coercion -> Coercion -> Bool
coreEqCoercion co1 co2 = coreEqCoercion2 rn_env co1 co2
where rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2))
coreEqCoercion2 :: RnEnv2 -> Coercion -> Coercion -> Bool
coreEqCoercion2 env (Refl eq1 ty1) (Refl eq2 ty2) = eq1 == eq2 && eqTypeX env ty1 ty2
coreEqCoercion2 env (TyConAppCo eq1 tc1 cos1) (TyConAppCo eq2 tc2 cos2)
= eq1 == eq2 && tc1 == tc2 && all2 (coreEqCoercion2 env) cos1 cos2
coreEqCoercion2 env (AppCo co11 co12) (AppCo co21 co22)
= coreEqCoercion2 env co11 co21 && coreEqCoercion2 env co12 co22
coreEqCoercion2 env (ForAllCo v1 co1) (ForAllCo v2 co2)
= coreEqCoercion2 (rnBndr2 env v1 v2) co1 co2
coreEqCoercion2 env (CoVarCo cv1) (CoVarCo cv2)
= rnOccL env cv1 == rnOccR env cv2
coreEqCoercion2 env (AxiomInstCo con1 ind1 cos1) (AxiomInstCo con2 ind2 cos2)
= con1 == con2
&& ind1 == ind2
&& all2 (coreEqCoercion2 env) cos1 cos2
-- the provenance string is just a note, so don't use in comparisons
coreEqCoercion2 env (UnivCo _ r1 ty11 ty12) (UnivCo _ r2 ty21 ty22)
= r1 == r2 && eqTypeX env ty11 ty21 && eqTypeX env ty12 ty22
coreEqCoercion2 env (SymCo co1) (SymCo co2)
= coreEqCoercion2 env co1 co2
coreEqCoercion2 env (TransCo co11 co12) (TransCo co21 co22)
= coreEqCoercion2 env co11 co21 && coreEqCoercion2 env co12 co22
coreEqCoercion2 env (NthCo d1 co1) (NthCo d2 co2)
= d1 == d2 && coreEqCoercion2 env co1 co2
coreEqCoercion2 env (LRCo d1 co1) (LRCo d2 co2)
= d1 == d2 && coreEqCoercion2 env co1 co2
coreEqCoercion2 env (InstCo co1 ty1) (InstCo co2 ty2)
= coreEqCoercion2 env co1 co2 && eqTypeX env ty1 ty2
coreEqCoercion2 env (SubCo co1) (SubCo co2)
= coreEqCoercion2 env co1 co2
coreEqCoercion2 env (AxiomRuleCo a1 ts1 cs1) (AxiomRuleCo a2 ts2 cs2)
= a1 == a2 && all2 (eqTypeX env) ts1 ts2 && all2 (coreEqCoercion2 env) cs1 cs2
coreEqCoercion2 _ _ _ = False
{-
************************************************************************
* *
Substitution of coercions
* *
************************************************************************
-}
-- | A substitution of 'Coercion's for 'CoVar's (OR 'TyVar's, when
-- doing a \"lifting\" substitution)
type CvSubstEnv = VarEnv Coercion
emptyCvSubstEnv :: CvSubstEnv
emptyCvSubstEnv = emptyVarEnv
data CvSubst
= CvSubst InScopeSet -- The in-scope type variables
TvSubstEnv -- Substitution of types
CvSubstEnv -- Substitution of coercions
instance Outputable CvSubst where
ppr (CvSubst ins tenv cenv)
= brackets $ sep[ ptext (sLit "CvSubst"),
nest 2 (ptext (sLit "In scope:") <+> ppr ins),
nest 2 (ptext (sLit "Type env:") <+> ppr tenv),
nest 2 (ptext (sLit "Coercion env:") <+> ppr cenv) ]
emptyCvSubst :: CvSubst
emptyCvSubst = CvSubst emptyInScopeSet emptyVarEnv emptyVarEnv
isEmptyCvSubst :: CvSubst -> Bool
isEmptyCvSubst (CvSubst _ tenv cenv) = isEmptyVarEnv tenv && isEmptyVarEnv cenv
getCvInScope :: CvSubst -> InScopeSet
getCvInScope (CvSubst in_scope _ _) = in_scope
zapCvSubstEnv :: CvSubst -> CvSubst
zapCvSubstEnv (CvSubst in_scope _ _) = CvSubst in_scope emptyVarEnv emptyVarEnv
cvTvSubst :: CvSubst -> TvSubst
cvTvSubst (CvSubst in_scope tvs _) = TvSubst in_scope tvs
tvCvSubst :: TvSubst -> CvSubst
tvCvSubst (TvSubst in_scope tenv) = CvSubst in_scope tenv emptyCvSubstEnv
extendTvSubst :: CvSubst -> TyVar -> Type -> CvSubst
extendTvSubst (CvSubst in_scope tenv cenv) tv ty
= CvSubst in_scope (extendVarEnv tenv tv ty) cenv
extendTvSubstAndInScope :: CvSubst -> TyVar -> Type -> CvSubst
extendTvSubstAndInScope (CvSubst in_scope tenv cenv) tv ty
= CvSubst (in_scope `extendInScopeSetSet` tyVarsOfType ty)
(extendVarEnv tenv tv ty)
cenv
extendCvSubstAndInScope :: CvSubst -> CoVar -> Coercion -> CvSubst
-- Also extends the in-scope set
extendCvSubstAndInScope (CvSubst in_scope tenv cenv) cv co
= CvSubst (in_scope `extendInScopeSetSet` tyCoVarsOfCo co)
tenv
(extendVarEnv cenv cv co)
substCoVarBndr :: CvSubst -> CoVar -> (CvSubst, CoVar)
substCoVarBndr subst@(CvSubst in_scope tenv cenv) old_var
= ASSERT( isCoVar old_var )
(CvSubst (in_scope `extendInScopeSet` new_var) tenv new_cenv, new_var)
where
-- When we substitute (co :: t1 ~ t2) we may get the identity (co :: t ~ t)
-- In that case, mkCoVarCo will return a ReflCoercion, and
-- we want to substitute that (not new_var) for old_var
new_co = mkCoVarCo new_var
no_change = new_var == old_var && not (isReflCo new_co)
new_cenv | no_change = delVarEnv cenv old_var
| otherwise = extendVarEnv cenv old_var new_co
new_var = uniqAway in_scope subst_old_var
subst_old_var = mkCoVar (varName old_var) (substTy subst (varType old_var))
-- It's important to do the substitution for coercions,
-- because they can have free type variables
substTyVarBndr :: CvSubst -> TyVar -> (CvSubst, TyVar)
substTyVarBndr (CvSubst in_scope tenv cenv) old_var
= case Type.substTyVarBndr (TvSubst in_scope tenv) old_var of
(TvSubst in_scope' tenv', new_var) -> (CvSubst in_scope' tenv' cenv, new_var)
mkCvSubst :: InScopeSet -> [(Var,Coercion)] -> CvSubst
mkCvSubst in_scope prs = CvSubst in_scope Type.emptyTvSubstEnv (mkVarEnv prs)
zipOpenCvSubst :: [Var] -> [Coercion] -> CvSubst
zipOpenCvSubst vs cos
| debugIsOn && (length vs /= length cos)
= pprTrace "zipOpenCvSubst" (ppr vs $$ ppr cos) emptyCvSubst
| otherwise
= CvSubst (mkInScopeSet (tyCoVarsOfCos cos)) emptyTvSubstEnv (zipVarEnv vs cos)
substCoWithTy :: InScopeSet -> TyVar -> Type -> Coercion -> Coercion
substCoWithTy in_scope tv ty = substCoWithTys in_scope [tv] [ty]
substCoWithTys :: InScopeSet -> [TyVar] -> [Type] -> Coercion -> Coercion
substCoWithTys in_scope tvs tys co
| debugIsOn && (length tvs /= length tys)
= pprTrace "substCoWithTys" (ppr tvs $$ ppr tys) co
| otherwise
= ASSERT( length tvs == length tys )
substCo (CvSubst in_scope (zipVarEnv tvs tys) emptyVarEnv) co
-- | Substitute within a 'Coercion'
substCo :: CvSubst -> Coercion -> Coercion
substCo subst co | isEmptyCvSubst subst = co
| otherwise = subst_co subst co
-- | Substitute within several 'Coercion's
substCos :: CvSubst -> [Coercion] -> [Coercion]
substCos subst cos | isEmptyCvSubst subst = cos
| otherwise = map (substCo subst) cos
substTy :: CvSubst -> Type -> Type
substTy subst = Type.substTy (cvTvSubst subst)
subst_co :: CvSubst -> Coercion -> Coercion
subst_co subst co
= go co
where
go_ty :: Type -> Type
go_ty = Coercion.substTy subst
go :: Coercion -> Coercion
go (Refl eq ty) = Refl eq $! go_ty ty
go (TyConAppCo eq tc cos) = let args = map go cos
in args `seqList` TyConAppCo eq tc args
go (AppCo co1 co2) = mkAppCo (go co1) $! go co2
go (ForAllCo tv co) = case substTyVarBndr subst tv of
(subst', tv') ->
ForAllCo tv' $! subst_co subst' co
go (CoVarCo cv) = substCoVar subst cv
go (AxiomInstCo con ind cos) = AxiomInstCo con ind $! map go cos
go (UnivCo s r ty1 ty2) = (UnivCo s r $! go_ty ty1) $! go_ty ty2
go (SymCo co) = mkSymCo (go co)
go (TransCo co1 co2) = mkTransCo (go co1) (go co2)
go (NthCo d co) = mkNthCo d (go co)
go (LRCo lr co) = mkLRCo lr (go co)
go (InstCo co ty) = mkInstCo (go co) $! go_ty ty
go (SubCo co) = mkSubCo (go co)
go (AxiomRuleCo co ts cs) = let ts1 = map go_ty ts
cs1 = map go cs
in ts1 `seqList` cs1 `seqList`
AxiomRuleCo co ts1 cs1
substCoVar :: CvSubst -> CoVar -> Coercion
substCoVar (CvSubst in_scope _ cenv) cv
| Just co <- lookupVarEnv cenv cv = co
| Just cv1 <- lookupInScope in_scope cv = ASSERT( isCoVar cv1 ) CoVarCo cv1
| otherwise = WARN( True, ptext (sLit "substCoVar not in scope") <+> ppr cv $$ ppr in_scope)
ASSERT( isCoVar cv ) CoVarCo cv
substCoVars :: CvSubst -> [CoVar] -> [Coercion]
substCoVars subst cvs = map (substCoVar subst) cvs
lookupTyVar :: CvSubst -> TyVar -> Maybe Type
lookupTyVar (CvSubst _ tenv _) tv = lookupVarEnv tenv tv
lookupCoVar :: CvSubst -> Var -> Maybe Coercion
lookupCoVar (CvSubst _ _ cenv) v = lookupVarEnv cenv v
{-
************************************************************************
* *
"Lifting" substitution
[(TyVar,Coercion)] -> Type -> Coercion
* *
************************************************************************
Note [Lifting coercions over types: liftCoSubst]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The KPUSH rule deals with this situation
data T a = MkK (a -> Maybe a)
g :: T t1 ~ K t2
x :: t1 -> Maybe t1
case (K @t1 x) |> g of
K (y:t2 -> Maybe t2) -> rhs
We want to push the coercion inside the constructor application.
So we do this
g' :: t1~t2 = Nth 0 g
case K @t2 (x |> g' -> Maybe g') of
K (y:t2 -> Maybe t2) -> rhs
The crucial operation is that we
* take the type of K's argument: a -> Maybe a
* and substitute g' for a
thus giving *coercion*. This is what liftCoSubst does.
Note [Substituting kinds in liftCoSubst]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to take care with kind polymorphism. Suppose
K :: forall k (a:k). (forall b:k. a -> b) -> T k a
Now given (K @kk1 @ty1 v) |> g) where
g :: T kk1 ty1 ~ T kk2 ty2
we want to compute
(forall b:k a->b) [ Nth 0 g/k, Nth 1 g/a ]
Notice that we MUST substitute for 'k'; this happens in
liftCoSubstTyVarBndr. But what should we substitute?
We need to take b's kind 'k' and return a Kind, not a Coercion!
Happily we can do this because we know that all kind coercions
((Nth 0 g) in this case) are Refl. So we need a special purpose
subst_kind: LiftCoSubst -> Kind -> Kind
that expects a Refl coercion (or something equivalent to Refl)
when it looks up a kind variable.
-}
-- ----------------------------------------------------
-- See Note [Lifting coercions over types: liftCoSubst]
-- ----------------------------------------------------
data LiftCoSubst = LCS InScopeSet LiftCoEnv
type LiftCoEnv = VarEnv Coercion
-- Maps *type variables* to *coercions*
-- That's the whole point of this function!
liftCoSubstWith :: Role -> [TyVar] -> [Coercion] -> Type -> Coercion
liftCoSubstWith r tvs cos ty
= liftCoSubst r (zipEqual "liftCoSubstWith" tvs cos) ty
liftCoSubst :: Role -> [(TyVar,Coercion)] -> Type -> Coercion
liftCoSubst r prs ty
| null prs = Refl r ty
| otherwise = ty_co_subst (LCS (mkInScopeSet (tyCoVarsOfCos (map snd prs)))
(mkVarEnv prs)) r ty
-- | The \"lifting\" operation which substitutes coercions for type
-- variables in a type to produce a coercion.
--
-- For the inverse operation, see 'liftCoMatch'
-- The Role parameter is the _desired_ role
ty_co_subst :: LiftCoSubst -> Role -> Type -> Coercion
ty_co_subst subst role ty
= go role ty
where
go Phantom ty = lift_phantom ty
go role (TyVarTy tv) = liftCoSubstTyVar subst role tv
`orElse` Refl role (TyVarTy tv)
-- A type variable from a non-cloned forall
-- won't be in the substitution
go role (AppTy ty1 ty2) = mkAppCo (go role ty1) (go Nominal ty2)
go role (TyConApp tc tys) = mkTyConAppCo role tc
(zipWith go (tyConRolesX role tc) tys)
-- IA0_NOTE: Do we need to do anything
-- about kind instantiations? I don't think
-- so. see Note [Kind coercions]
go role (FunTy ty1 ty2) = mkFunCo role (go role ty1) (go role ty2)
go role (ForAllTy v ty) = mkForAllCo v' $! (ty_co_subst subst' role ty)
where
(subst', v') = liftCoSubstTyVarBndr subst v
go role ty@(LitTy {}) = ASSERT( role == Nominal )
mkReflCo role ty
lift_phantom ty = mkUnivCo (fsLit "lift_phantom")
Phantom (liftCoSubstLeft subst ty)
(liftCoSubstRight subst ty)
{-
Note [liftCoSubstTyVar]
~~~~~~~~~~~~~~~~~~~~~~~
This function can fail (i.e., return Nothing) for two separate reasons:
1) The variable is not in the substutition
2) The coercion found is of too low a role
liftCoSubstTyVar is called from two places: in liftCoSubst (naturally), and
also in matchAxiom in OptCoercion. From liftCoSubst, the so-called lifting
lemma guarantees that the roles work out. If we fail for reason 2) in this
case, we really should panic -- something is deeply wrong. But, in matchAxiom,
failing for reason 2) is fine. matchAxiom is trying to find a set of coercions
that match, but it may fail, and this is healthy behavior. Bottom line: if
you find that liftCoSubst is doing weird things (like leaving out-of-scope
variables lying around), disable coercion optimization (bypassing matchAxiom)
and use downgradeRole instead of downgradeRole_maybe. The panic will then happen,
and you may learn something useful.
-}
liftCoSubstTyVar :: LiftCoSubst -> Role -> TyVar -> Maybe Coercion
liftCoSubstTyVar (LCS _ cenv) r tv
= do { co <- lookupVarEnv cenv tv
; let co_role = coercionRole co -- could theoretically take this as
-- a parameter, but painful
; downgradeRole_maybe r co_role co } -- see Note [liftCoSubstTyVar]
liftCoSubstTyVarBndr :: LiftCoSubst -> TyVar -> (LiftCoSubst, TyVar)
liftCoSubstTyVarBndr subst@(LCS in_scope cenv) old_var
= (LCS (in_scope `extendInScopeSet` new_var) new_cenv, new_var)
where
new_cenv | no_change = delVarEnv cenv old_var
| otherwise = extendVarEnv cenv old_var (Refl Nominal (TyVarTy new_var))
no_change = no_kind_change && (new_var == old_var)
new_var1 = uniqAway in_scope old_var
old_ki = tyVarKind old_var
no_kind_change = isEmptyVarSet (tyVarsOfType old_ki)
new_var | no_kind_change = new_var1
| otherwise = setTyVarKind new_var1 (subst_kind subst old_ki)
-- map every variable to the type on the *left* of its mapped coercion
liftCoSubstLeft :: LiftCoSubst -> Type -> Type
liftCoSubstLeft (LCS in_scope cenv) ty
= Type.substTy (mkTvSubst in_scope (mapVarEnv (pFst . coercionKind) cenv)) ty
-- same, but to the type on the right
liftCoSubstRight :: LiftCoSubst -> Type -> Type
liftCoSubstRight (LCS in_scope cenv) ty
= Type.substTy (mkTvSubst in_scope (mapVarEnv (pSnd . coercionKind) cenv)) ty
subst_kind :: LiftCoSubst -> Kind -> Kind
-- See Note [Substituting kinds in liftCoSubst]
subst_kind subst@(LCS _ cenv) kind
= go kind
where
go (LitTy n) = n `seq` LitTy n
go (TyVarTy kv) = subst_kv kv
go (TyConApp tc tys) = let args = map go tys
in args `seqList` TyConApp tc args
go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
go (ForAllTy tv ty) = case liftCoSubstTyVarBndr subst tv of
(subst', tv') ->
ForAllTy tv' $! (subst_kind subst' ty)
subst_kv kv
| Just co <- lookupVarEnv cenv kv
, let co_kind = coercionKind co
= ASSERT2( pFst co_kind `eqKind` pSnd co_kind, ppr kv $$ ppr co )
pFst co_kind
| otherwise
= TyVarTy kv
-- | 'liftCoMatch' is sort of inverse to 'liftCoSubst'. In particular, if
-- @liftCoMatch vars ty co == Just s@, then @tyCoSubst s ty == co@.
-- That is, it matches a type against a coercion of the same
-- "shape", and returns a lifting substitution which could have been
-- used to produce the given coercion from the given type.
liftCoMatch :: TyVarSet -> Type -> Coercion -> Maybe LiftCoSubst
liftCoMatch tmpls ty co
= case ty_co_match menv emptyVarEnv ty co of
Just cenv -> Just (LCS in_scope cenv)
Nothing -> Nothing
where
menv = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope }
in_scope = mkInScopeSet (tmpls `unionVarSet` tyCoVarsOfCo co)
-- Like tcMatchTy, assume all the interesting variables
-- in ty are in tmpls
-- | 'ty_co_match' does all the actual work for 'liftCoMatch'.
ty_co_match :: MatchEnv -> LiftCoEnv -> Type -> Coercion -> Maybe LiftCoEnv
ty_co_match menv subst ty co
| Just ty' <- coreView ty = ty_co_match menv subst ty' co
-- Match a type variable against a non-refl coercion
ty_co_match menv cenv (TyVarTy tv1) co
| Just co1' <- lookupVarEnv cenv tv1' -- tv1' is already bound to co1
= if coreEqCoercion2 (nukeRnEnvL rn_env) co1' co
then Just cenv
else Nothing -- no match since tv1 matches two different coercions
| tv1' `elemVarSet` me_tmpls menv -- tv1' is a template var
= if any (inRnEnvR rn_env) (varSetElems (tyCoVarsOfCo co))
then Nothing -- occurs check failed
else return (extendVarEnv cenv tv1' co)
-- BAY: I don't think we need to do any kind matching here yet
-- (compare 'match'), but we probably will when moving to SHE.
| otherwise -- tv1 is not a template ty var, so the only thing it
-- can match is a reflexivity coercion for itself.
-- But that case is dealt with already
= Nothing
where
rn_env = me_env menv
tv1' = rnOccL rn_env tv1
ty_co_match menv subst (AppTy ty1 ty2) co
| Just (co1, co2) <- splitAppCo_maybe co -- c.f. Unify.match on AppTy
= do { subst' <- ty_co_match menv subst ty1 co1
; ty_co_match menv subst' ty2 co2 }
ty_co_match menv subst (TyConApp tc1 tys) (TyConAppCo _ tc2 cos)
| tc1 == tc2 = ty_co_matches menv subst tys cos
ty_co_match menv subst (FunTy ty1 ty2) (TyConAppCo _ tc cos)
| tc == funTyCon = ty_co_matches menv subst [ty1,ty2] cos
ty_co_match menv subst (ForAllTy tv1 ty) (ForAllCo tv2 co)
= ty_co_match menv' subst ty co
where
menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
ty_co_match menv subst ty co
| Just co' <- pushRefl co = ty_co_match menv subst ty co'
| otherwise = Nothing
ty_co_matches :: MatchEnv -> LiftCoEnv -> [Type] -> [Coercion] -> Maybe LiftCoEnv
ty_co_matches menv = matchList (ty_co_match menv)
pushRefl :: Coercion -> Maybe Coercion
pushRefl (Refl Nominal (AppTy ty1 ty2))
= Just (AppCo (Refl Nominal ty1) (Refl Nominal ty2))
pushRefl (Refl r (FunTy ty1 ty2))
= Just (TyConAppCo r funTyCon [Refl r ty1, Refl r ty2])
pushRefl (Refl r (TyConApp tc tys))
= Just (TyConAppCo r tc (zipWith mkReflCo (tyConRolesX r tc) tys))
pushRefl (Refl r (ForAllTy tv ty)) = Just (ForAllCo tv (Refl r ty))
pushRefl _ = Nothing
{-
************************************************************************
* *
Sequencing on coercions
* *
************************************************************************
-}
seqCo :: Coercion -> ()
seqCo (Refl eq ty) = eq `seq` seqType ty
seqCo (TyConAppCo eq tc cos) = eq `seq` tc `seq` seqCos cos
seqCo (AppCo co1 co2) = seqCo co1 `seq` seqCo co2
seqCo (ForAllCo tv co) = tv `seq` seqCo co
seqCo (CoVarCo cv) = cv `seq` ()
seqCo (AxiomInstCo con ind cos) = con `seq` ind `seq` seqCos cos
seqCo (UnivCo s r ty1 ty2) = s `seq` r `seq` seqType ty1 `seq` seqType ty2
seqCo (SymCo co) = seqCo co
seqCo (TransCo co1 co2) = seqCo co1 `seq` seqCo co2
seqCo (NthCo _ co) = seqCo co
seqCo (LRCo _ co) = seqCo co
seqCo (InstCo co ty) = seqCo co `seq` seqType ty
seqCo (SubCo co) = seqCo co
seqCo (AxiomRuleCo _ ts cs) = seqTypes ts `seq` seqCos cs
seqCos :: [Coercion] -> ()
seqCos [] = ()
seqCos (co:cos) = seqCo co `seq` seqCos cos
{-
************************************************************************
* *
The kind of a type, and of a coercion
* *
************************************************************************
Note [Computing a coercion kind and role]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To compute a coercion's kind is straightforward: see coercionKind.
But to compute a coercion's role, in the case for NthCo we need
its kind as well. So if we have two separate functions (one for kinds
and one for roles) we can get exponentially bad behaviour, since each
NthCo node makes a separate call to coercionKind, which traverses the
sub-tree again. This was part of the problem in Trac #9233.
Solution: compute both together; hence coercionKindRole. We keep a
separate coercionKind function because it's a bit more efficient if
the kind is all you want.
-}
coercionType :: Coercion -> Type
coercionType co = case coercionKindRole co of
(Pair ty1 ty2, r) -> mkCoercionType r ty1 ty2
------------------
-- | If it is the case that
--
-- > c :: (t1 ~ t2)
--
-- i.e. the kind of @c@ relates @t1@ and @t2@, then @coercionKind c = Pair t1 t2@.
coercionKind :: Coercion -> Pair Type
coercionKind co = go co
where
go (Refl _ ty) = Pair ty ty
go (TyConAppCo _ tc cos) = mkTyConApp tc <$> (sequenceA $ map go cos)
go (AppCo co1 co2) = mkAppTy <$> go co1 <*> go co2
go (ForAllCo tv co) = mkForAllTy tv <$> go co
go (CoVarCo cv) = toPair $ coVarKind cv
go (AxiomInstCo ax ind cos)
| CoAxBranch { cab_tvs = tvs, cab_lhs = lhs, cab_rhs = rhs } <- coAxiomNthBranch ax ind
, Pair tys1 tys2 <- sequenceA (map go cos)
= ASSERT( cos `equalLength` tvs ) -- Invariant of AxiomInstCo: cos should
-- exactly saturate the axiom branch
Pair (substTyWith tvs tys1 (mkTyConApp (coAxiomTyCon ax) lhs))
(substTyWith tvs tys2 rhs)
go (UnivCo _ _ ty1 ty2) = Pair ty1 ty2
go (SymCo co) = swap $ go co
go (TransCo co1 co2) = Pair (pFst $ go co1) (pSnd $ go co2)
go (NthCo d co) = tyConAppArgN d <$> go co
go (LRCo lr co) = (pickLR lr . splitAppTy) <$> go co
go (InstCo aco ty) = go_app aco [ty]
go (SubCo co) = go co
go (AxiomRuleCo ax tys cos) =
case coaxrProves ax tys (map go cos) of
Just res -> res
Nothing -> panic "coercionKind: Malformed coercion"
go_app :: Coercion -> [Type] -> Pair Type
-- Collect up all the arguments and apply all at once
-- See Note [Nested InstCos]
go_app (InstCo co ty) tys = go_app co (ty:tys)
go_app co tys = (`applyTys` tys) <$> go co
-- | Apply 'coercionKind' to multiple 'Coercion's
coercionKinds :: [Coercion] -> Pair [Type]
coercionKinds tys = sequenceA $ map coercionKind tys
-- | Get a coercion's kind and role.
-- Why both at once? See Note [Computing a coercion kind and role]
coercionKindRole :: Coercion -> (Pair Type, Role)
coercionKindRole = go
where
go (Refl r ty) = (Pair ty ty, r)
go (TyConAppCo r tc cos)
= (mkTyConApp tc <$> (sequenceA $ map coercionKind cos), r)
go (AppCo co1 co2)
= let (tys1, r1) = go co1 in
(mkAppTy <$> tys1 <*> coercionKind co2, r1)
go (ForAllCo tv co)
= let (tys, r) = go co in
(mkForAllTy tv <$> tys, r)
go (CoVarCo cv) = (toPair $ coVarKind cv, coVarRole cv)
go co@(AxiomInstCo ax _ _) = (coercionKind co, coAxiomRole ax)
go (UnivCo _ r ty1 ty2) = (Pair ty1 ty2, r)
go (SymCo co) = first swap $ go co
go (TransCo co1 co2)
= let (tys1, r) = go co1 in
(Pair (pFst tys1) (pSnd $ coercionKind co2), r)
go (NthCo d co)
= let (Pair t1 t2, r) = go co
(tc1, args1) = splitTyConApp t1
(_tc2, args2) = splitTyConApp t2
in
ASSERT( tc1 == _tc2 )
((`getNth` d) <$> Pair args1 args2, nthRole r tc1 d)
go co@(LRCo {}) = (coercionKind co, Nominal)
go (InstCo co ty) = go_app co [ty]
go (SubCo co) = (coercionKind co, Representational)
go co@(AxiomRuleCo ax _ _) = (coercionKind co, coaxrRole ax)
go_app :: Coercion -> [Type] -> (Pair Type, Role)
-- Collect up all the arguments and apply all at once
-- See Note [Nested InstCos]
go_app (InstCo co ty) tys = go_app co (ty:tys)
go_app co tys
= let (pair, r) = go co in
((`applyTys` tys) <$> pair, r)
-- | Retrieve the role from a coercion.
coercionRole :: Coercion -> Role
coercionRole = snd . coercionKindRole
-- There's not a better way to do this, because NthCo needs the *kind*
-- and role of its argument. Luckily, laziness should generally avoid
-- the need for computing kinds in other cases.
{-
Note [Nested InstCos]
~~~~~~~~~~~~~~~~~~~~~
In Trac #5631 we found that 70% of the entire compilation time was
being spent in coercionKind! The reason was that we had
(g @ ty1 @ ty2 .. @ ty100) -- The "@s" are InstCos
where
g :: forall a1 a2 .. a100. phi
If we deal with the InstCos one at a time, we'll do this:
1. Find the kind of (g @ ty1 .. @ ty99) : forall a100. phi'
2. Substitute phi'[ ty100/a100 ], a single tyvar->type subst
But this is a *quadratic* algorithm, and the blew up Trac #5631.
So it's very important to do the substitution simultaneously.
cf Type.applyTys (which in fact we call here)
-}
applyCo :: Type -> Coercion -> Type
-- Gives the type of (e co) where e :: (a~b) => ty
applyCo ty co | Just ty' <- coreView ty = applyCo ty' co
applyCo (FunTy _ ty) _ = ty
applyCo _ _ = panic "applyCo"
{-
Note [Kind coercions]
~~~~~~~~~~~~~~~~~~~~~
Kind coercions are only of the form: Refl kind. They are only used to
instantiate kind polymorphic type constructors in TyConAppCo. Remember
that kind instantiation only happens with TyConApp, not AppTy.
-}
| nathyong/microghc-ghc | compiler/types/Coercion.hs | bsd-3-clause | 78,821 | 1,008 | 12 | 20,814 | 11,656 | 7,214 | 4,442 | 937 | 16 |
{-
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
\section[StgLint]{A ``lint'' pass to check for Stg correctness}
-}
{-# LANGUAGE CPP #-}
module StgLint ( lintStgTopBindings ) where
import GhcPrelude
import StgSyn
import Bag ( Bag, emptyBag, isEmptyBag, snocBag, bagToList )
import Id ( Id, idType, isLocalId, isJoinId )
import VarSet
import DataCon
import CoreSyn ( AltCon(..) )
import PrimOp ( primOpType )
import Literal ( literalType )
import Maybes
import Name ( getSrcLoc )
import ErrUtils ( MsgDoc, Severity(..), mkLocMessage )
import Type
import RepType
import TyCon
import Util
import SrcLoc
import Outputable
import Control.Monad
#include "HsVersions.h"
{-
Checks for
(a) *some* type errors
(b) locally-defined variables used but not defined
Note: unless -dverbose-stg is on, display of lint errors will result
in "panic: bOGUS_LVs".
WARNING:
~~~~~~~~
This module has suffered bit-rot; it is likely to yield lint errors
for Stg code that is currently perfectly acceptable for code
generation. Solution: don't use it! (KSW 2000-05).
************************************************************************
* *
\subsection{``lint'' for various constructs}
* *
************************************************************************
@lintStgTopBindings@ is the top-level interface function.
-}
lintStgTopBindings :: Bool -- ^ have we run Unarise yet?
-> String -> [StgTopBinding] -> [StgTopBinding]
lintStgTopBindings unarised whodunnit binds
= {-# SCC "StgLint" #-}
case (initL unarised (lint_binds binds)) of
Nothing -> binds
Just msg -> pprPanic "" (vcat [
text "*** Stg Lint ErrMsgs: in" <+>
text whodunnit <+> text "***",
msg,
text "*** Offending Program ***",
pprStgTopBindings binds,
text "*** End of Offense ***"])
where
lint_binds :: [StgTopBinding] -> LintM ()
lint_binds [] = return ()
lint_binds (bind:binds) = do
binders <- lint_bind bind
addInScopeVars binders $
lint_binds binds
lint_bind (StgTopLifted bind) = lintStgBinds bind
lint_bind (StgTopStringLit v _) = return [v]
lintStgArg :: StgArg -> LintM (Maybe Type)
lintStgArg (StgLitArg lit) = return (Just (literalType lit))
lintStgArg (StgVarArg v) = lintStgVar v
lintStgVar :: Id -> LintM (Maybe Kind)
lintStgVar v = do checkInScope v
return (Just (idType v))
lintStgBinds :: StgBinding -> LintM [Id] -- Returns the binders
lintStgBinds (StgNonRec binder rhs) = do
lint_binds_help (binder,rhs)
return [binder]
lintStgBinds (StgRec pairs)
= addInScopeVars binders $ do
mapM_ lint_binds_help pairs
return binders
where
binders = [b | (b,_) <- pairs]
lint_binds_help :: (Id, StgRhs) -> LintM ()
lint_binds_help (binder, rhs)
= addLoc (RhsOf binder) $ do
-- Check the rhs
_maybe_rhs_ty <- lintStgRhs rhs
-- Check binder doesn't have unlifted type
checkL (isJoinId binder || not (isUnliftedType binder_ty))
(mkUnliftedTyMsg binder rhs)
-- Check match to RHS type
-- Actually we *can't* check the RHS type, because
-- unsafeCoerce means it really might not match at all
-- notably; eg x::Int = (error @Bool "urk") |> unsafeCoerce...
-- case maybe_rhs_ty of
-- Nothing -> return ()
-- Just rhs_ty -> checkTys binder_ty
-- rhs_ty
--- (mkRhsMsg binder rhs_ty)
return ()
where
binder_ty = idType binder
lintStgRhs :: StgRhs -> LintM (Maybe Type) -- Just ty => type is exact
lintStgRhs (StgRhsClosure _ _ _ _ [] expr)
= lintStgExpr expr
lintStgRhs (StgRhsClosure _ _ _ _ binders expr)
= addLoc (LambdaBodyOf binders) $
addInScopeVars binders $ runMaybeT $ do
body_ty <- MaybeT $ lintStgExpr expr
return (mkFunTys (map idType binders) body_ty)
lintStgRhs rhs@(StgRhsCon _ con args) = do
-- TODO: Check arg_tys
when (isUnboxedTupleCon con || isUnboxedSumCon con) $
addErrL (text "StgRhsCon is an unboxed tuple or sum application" $$
ppr rhs)
runMaybeT $ do
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp con_ty arg_tys (mkRhsConMsg con_ty arg_tys)
where
con_ty = dataConRepType con
lintStgExpr :: StgExpr -> LintM (Maybe Type) -- Just ty => type is exact
lintStgExpr (StgLit l) = return (Just (literalType l))
lintStgExpr e@(StgApp fun args) = runMaybeT $ do
fun_ty <- MaybeT $ lintStgVar fun
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp fun_ty arg_tys (mkFunAppMsg fun_ty arg_tys e)
lintStgExpr e@(StgConApp con args _arg_tys) = runMaybeT $ do
-- TODO: Check arg_tys
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp con_ty arg_tys (mkFunAppMsg con_ty arg_tys e)
where
con_ty = dataConRepType con
lintStgExpr e@(StgOpApp (StgPrimOp op) args _) = runMaybeT $ do
arg_tys <- mapM (MaybeT . lintStgArg) args
MaybeT $ checkFunApp op_ty arg_tys (mkFunAppMsg op_ty arg_tys e)
where
op_ty = primOpType op
lintStgExpr (StgOpApp _ args res_ty) = runMaybeT $ do
-- We don't have enough type information to check
-- the application for StgFCallOp and StgPrimCallOp; ToDo
_maybe_arg_tys <- mapM (MaybeT . lintStgArg) args
return res_ty
lintStgExpr (StgLam bndrs _) = do
addErrL (text "Unexpected StgLam" <+> ppr bndrs)
return Nothing
lintStgExpr (StgLet binds body) = do
binders <- lintStgBinds binds
addLoc (BodyOfLetRec binders) $
addInScopeVars binders $
lintStgExpr body
lintStgExpr (StgLetNoEscape binds body) = do
binders <- lintStgBinds binds
addLoc (BodyOfLetRec binders) $
addInScopeVars binders $
lintStgExpr body
lintStgExpr (StgTick _ expr) = lintStgExpr expr
lintStgExpr (StgCase scrut bndr alts_type alts) = runMaybeT $ do
_ <- MaybeT $ lintStgExpr scrut
lf <- liftMaybeT getLintFlags
in_scope <- MaybeT $ liftM Just $
case alts_type of
AlgAlt tc -> check_bndr (tyConPrimRep tc) >> return True
PrimAlt rep -> check_bndr [rep] >> return True
-- Case binders of unboxed tuple or unboxed sum type always dead
-- after the unariser has run. See Note [Post-unarisation invariants].
MultiValAlt _
| lf_unarised lf -> return False
| otherwise -> return True
PolyAlt -> return True
MaybeT $ addInScopeVars [bndr | in_scope] $
lintStgAlts alts scrut_ty
where
scrut_ty = idType bndr
scrut_reps = typePrimRep scrut_ty
check_bndr reps = checkL (scrut_reps == reps) bad_bndr
where
bad_bndr = mkDefltMsg bndr reps
lintStgAlts :: [StgAlt]
-> Type -- Type of scrutinee
-> LintM (Maybe Type) -- Just ty => type is accurage
lintStgAlts alts scrut_ty = do
maybe_result_tys <- mapM (lintAlt scrut_ty) alts
-- Check the result types
case catMaybes (maybe_result_tys) of
[] -> return Nothing
(first_ty:_tys) -> do -- mapM_ check tys
return (Just first_ty)
where
-- check ty = checkTys first_ty ty (mkCaseAltMsg alts)
-- We can't check that the alternatives have the
-- same type, because they don't, with unsafeCoerce#
lintAlt :: Type -> (AltCon, [Id], StgExpr) -> LintM (Maybe Type)
lintAlt _ (DEFAULT, _, rhs)
= lintStgExpr rhs
lintAlt scrut_ty (LitAlt lit, _, rhs) = do
checkTys (literalType lit) scrut_ty (mkAltMsg1 scrut_ty)
lintStgExpr rhs
lintAlt scrut_ty (DataAlt con, args, rhs) = do
case splitTyConApp_maybe scrut_ty of
Just (tycon, tys_applied) | isAlgTyCon tycon &&
not (isNewTyCon tycon) -> do
let
cons = tyConDataCons tycon
arg_tys = dataConInstArgTys con tys_applied
-- This does not work for existential constructors
checkL (con `elem` cons) (mkAlgAltMsg2 scrut_ty con)
checkL (args `lengthIs` dataConRepArity con) (mkAlgAltMsg3 con args)
when (isVanillaDataCon con) $
mapM_ check (zipEqual "lintAlgAlt:stg" arg_tys args)
return ()
_ ->
addErrL (mkAltMsg1 scrut_ty)
addInScopeVars args $
lintStgExpr rhs
where
check (ty, arg) = checkTys ty (idType arg) (mkAlgAltMsg4 ty arg)
-- elem: yes, the elem-list here can sometimes be long-ish,
-- but as it's use-once, probably not worth doing anything different
-- We give it its own copy, so it isn't overloaded.
elem _ [] = False
elem x (y:ys) = x==y || elem x ys
{-
************************************************************************
* *
\subsection[lint-monad]{The Lint monad}
* *
************************************************************************
-}
newtype LintM a = LintM
{ unLintM :: LintFlags
-> [LintLocInfo] -- Locations
-> IdSet -- Local vars in scope
-> Bag MsgDoc -- Error messages so far
-> (a, Bag MsgDoc) -- Result and error messages (if any)
}
data LintFlags = LintFlags { lf_unarised :: !Bool
-- ^ have we run the unariser yet?
}
data LintLocInfo
= RhsOf Id -- The variable bound
| LambdaBodyOf [Id] -- The lambda-binder
| BodyOfLetRec [Id] -- One of the binders
dumpLoc :: LintLocInfo -> (SrcSpan, SDoc)
dumpLoc (RhsOf v) =
(srcLocSpan (getSrcLoc v), text " [RHS of " <> pp_binders [v] <> char ']' )
dumpLoc (LambdaBodyOf bs) =
(srcLocSpan (getSrcLoc (head bs)), text " [in body of lambda with binders " <> pp_binders bs <> char ']' )
dumpLoc (BodyOfLetRec bs) =
(srcLocSpan (getSrcLoc (head bs)), text " [in body of letrec with binders " <> pp_binders bs <> char ']' )
pp_binders :: [Id] -> SDoc
pp_binders bs
= sep (punctuate comma (map pp_binder bs))
where
pp_binder b
= hsep [ppr b, dcolon, ppr (idType b)]
initL :: Bool -> LintM a -> Maybe MsgDoc
initL unarised (LintM m)
= case (m lf [] emptyVarSet emptyBag) of { (_, errs) ->
if isEmptyBag errs then
Nothing
else
Just (vcat (punctuate blankLine (bagToList errs)))
}
where
lf = LintFlags unarised
instance Functor LintM where
fmap = liftM
instance Applicative LintM where
pure a = LintM $ \_lf _loc _scope errs -> (a, errs)
(<*>) = ap
(*>) = thenL_
instance Monad LintM where
(>>=) = thenL
(>>) = (*>)
thenL :: LintM a -> (a -> LintM b) -> LintM b
thenL m k = LintM $ \lf loc scope errs
-> case unLintM m lf loc scope errs of
(r, errs') -> unLintM (k r) lf loc scope errs'
thenL_ :: LintM a -> LintM b -> LintM b
thenL_ m k = LintM $ \lf loc scope errs
-> case unLintM m lf loc scope errs of
(_, errs') -> unLintM k lf loc scope errs'
checkL :: Bool -> MsgDoc -> LintM ()
checkL True _ = return ()
checkL False msg = addErrL msg
addErrL :: MsgDoc -> LintM ()
addErrL msg = LintM $ \_lf loc _scope errs -> ((), addErr errs msg loc)
addErr :: Bag MsgDoc -> MsgDoc -> [LintLocInfo] -> Bag MsgDoc
addErr errs_so_far msg locs
= errs_so_far `snocBag` mk_msg locs
where
mk_msg (loc:_) = let (l,hdr) = dumpLoc loc
in mkLocMessage SevWarning l (hdr $$ msg)
mk_msg [] = msg
addLoc :: LintLocInfo -> LintM a -> LintM a
addLoc extra_loc m = LintM $ \lf loc scope errs
-> unLintM m lf (extra_loc:loc) scope errs
addInScopeVars :: [Id] -> LintM a -> LintM a
addInScopeVars ids m = LintM $ \lf loc scope errs
-> let
new_set = mkVarSet ids
in unLintM m lf loc (scope `unionVarSet` new_set) errs
getLintFlags :: LintM LintFlags
getLintFlags = LintM $ \lf _loc _scope errs -> (lf, errs)
{-
Checking function applications: we only check that the type has the
right *number* of arrows, we don't actually compare the types. This
is because we can't expect the types to be equal - the type
applications and type lambdas that we use to calculate accurate types
have long since disappeared.
-}
checkFunApp :: Type -- The function type
-> [Type] -- The arg type(s)
-> MsgDoc -- Error message
-> LintM (Maybe Type) -- Just ty => result type is accurate
checkFunApp fun_ty arg_tys msg
= do { case mb_msg of
Just msg -> addErrL msg
Nothing -> return ()
; return mb_ty }
where
(mb_ty, mb_msg) = cfa True fun_ty arg_tys
cfa :: Bool -> Type -> [Type] -> (Maybe Type -- Accurate result?
, Maybe MsgDoc) -- Errors?
cfa accurate fun_ty [] -- Args have run out; that's fine
= (if accurate then Just fun_ty else Nothing, Nothing)
cfa accurate fun_ty arg_tys@(arg_ty':arg_tys')
| Just (arg_ty, res_ty) <- splitFunTy_maybe fun_ty
= if accurate && not (arg_ty `stgEqType` arg_ty')
then (Nothing, Just msg) -- Arg type mismatch
else cfa accurate res_ty arg_tys'
| Just (_, fun_ty') <- splitForAllTy_maybe fun_ty
= cfa False fun_ty' arg_tys
| Just (tc,tc_args) <- splitTyConApp_maybe fun_ty
, isNewTyCon tc
= if tc_args `lengthLessThan` tyConArity tc
then WARN( True, text "cfa: unsaturated newtype" <+> ppr fun_ty $$ msg )
(Nothing, Nothing) -- This is odd, but I've seen it
else cfa False (newTyConInstRhs tc tc_args) arg_tys
| Just tc <- tyConAppTyCon_maybe fun_ty
, not (isTypeFamilyTyCon tc) -- Definite error
= (Nothing, Just msg) -- Too many args
| otherwise
= (Nothing, Nothing)
-- | "Compare" types. We used to try a crude comparison of the type themselves,
-- but this is essentially impossible in STG as we have discarded both casts
-- and type applications, so types might look different but be the same. Now we
-- simply compare their runtime representations. See #14120.
stgEqType :: Type -> Type -> Bool
stgEqType ty1 ty2
= reps1 == reps2
where
reps1 = typePrimRep ty1
reps2 = typePrimRep ty2
checkInScope :: Id -> LintM ()
checkInScope id = LintM $ \_lf loc scope errs
-> if isLocalId id && not (id `elemVarSet` scope) then
((), addErr errs (hsep [ppr id, dcolon, ppr (idType id),
text "is out of scope"]) loc)
else
((), errs)
checkTys :: Type -> Type -> MsgDoc -> LintM ()
checkTys ty1 ty2 msg = LintM $ \_lf loc _scope errs
-> if (ty1 `stgEqType` ty2)
then ((), errs)
else ((), addErr errs msg loc)
_mkCaseAltMsg :: [StgAlt] -> MsgDoc
_mkCaseAltMsg _alts
= ($$) (text "In some case alternatives, type of alternatives not all same:")
(Outputable.empty) -- LATER: ppr alts
mkDefltMsg :: Id -> [PrimRep] -> MsgDoc
mkDefltMsg bndr reps
= ($$) (text "Binder of a case expression doesn't match representation of scrutinee:")
(ppr bndr $$ ppr (idType bndr) $$ ppr reps)
mkFunAppMsg :: Type -> [Type] -> StgExpr -> MsgDoc
mkFunAppMsg fun_ty arg_tys expr
= vcat [text "In a function application, function type doesn't match arg types:",
hang (text "Function type:") 4 (ppr fun_ty),
hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys)),
hang (text "Expression:") 4 (ppr expr)]
mkRhsConMsg :: Type -> [Type] -> MsgDoc
mkRhsConMsg fun_ty arg_tys
= vcat [text "In a RHS constructor application, con type doesn't match arg types:",
hang (text "Constructor type:") 4 (ppr fun_ty),
hang (text "Arg types:") 4 (vcat (map (ppr) arg_tys))]
mkAltMsg1 :: Type -> MsgDoc
mkAltMsg1 ty
= ($$) (text "In a case expression, type of scrutinee does not match patterns")
(ppr ty)
mkAlgAltMsg2 :: Type -> DataCon -> MsgDoc
mkAlgAltMsg2 ty con
= vcat [
text "In some algebraic case alternative, constructor is not a constructor of scrutinee type:",
ppr ty,
ppr con
]
mkAlgAltMsg3 :: DataCon -> [Id] -> MsgDoc
mkAlgAltMsg3 con alts
= vcat [
text "In some algebraic case alternative, number of arguments doesn't match constructor:",
ppr con <+> parens (text "arity" <+> ppr (dataConRepArity con)),
ppr alts
]
mkAlgAltMsg4 :: Type -> Id -> MsgDoc
mkAlgAltMsg4 ty arg
= vcat [
text "In some algebraic case alternative, type of argument doesn't match data constructor:",
ppr ty,
ppr arg
]
_mkRhsMsg :: Id -> Type -> MsgDoc
_mkRhsMsg binder ty
= vcat [hsep [text "The type of this binder doesn't match the type of its RHS:",
ppr binder],
hsep [text "Binder's type:", ppr (idType binder)],
hsep [text "Rhs type:", ppr ty]
]
mkUnliftedTyMsg :: Id -> StgRhs -> SDoc
mkUnliftedTyMsg binder rhs
= (text "Let(rec) binder" <+> quotes (ppr binder) <+>
text "has unlifted type" <+> quotes (ppr (idType binder)))
$$
(text "RHS:" <+> ppr rhs)
| ezyang/ghc | compiler/stgSyn/StgLint.hs | bsd-3-clause | 17,628 | 1 | 19 | 5,130 | 4,709 | 2,393 | 2,316 | -1 | -1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 2000
FunDeps - functional dependencies
It's better to read it as: "if we know these, then we're going to know these"
-}
{-# LANGUAGE CPP #-}
module FunDeps (
FunDepEqn(..), pprEquation,
improveFromInstEnv, improveFromAnother,
checkInstCoverage, checkFunDeps,
pprFundeps
) where
#include "HsVersions.h"
import Name
import Var
import Class
import Type
import TcType( transSuperClasses )
import CoAxiom( TypeEqn )
import Unify
import FamInst( injTyVarsOfTypes )
import InstEnv
import VarSet
import VarEnv
import Outputable
import ErrUtils( Validity(..), allValid )
import SrcLoc
import Util
import Pair ( Pair(..) )
import Data.List ( nubBy )
import Data.Maybe
import Data.Foldable ( fold )
{-
************************************************************************
* *
\subsection{Generate equations from functional dependencies}
* *
************************************************************************
Each functional dependency with one variable in the RHS is responsible
for generating a single equality. For instance:
class C a b | a -> b
The constraints ([Wanted] C Int Bool) and [Wanted] C Int alpha
will generate the folloing FunDepEqn
FDEqn { fd_qtvs = []
, fd_eqs = [Pair Bool alpha]
, fd_pred1 = C Int Bool
, fd_pred2 = C Int alpha
, fd_loc = ... }
However notice that a functional dependency may have more than one variable
in the RHS which will create more than one pair of types in fd_eqs. Example:
class C a b c | a -> b c
[Wanted] C Int alpha alpha
[Wanted] C Int Bool beta
Will generate:
FDEqn { fd_qtvs = []
, fd_eqs = [Pair Bool alpha, Pair alpha beta]
, fd_pred1 = C Int Bool
, fd_pred2 = C Int alpha
, fd_loc = ... }
INVARIANT: Corresponding types aren't already equal
That is, there exists at least one non-identity equality in FDEqs.
Assume:
class C a b c | a -> b c
instance C Int x x
And: [Wanted] C Int Bool alpha
We will /match/ the LHS of fundep equations, producing a matching substitution
and create equations for the RHS sides. In our last example we'd have generated:
({x}, [fd1,fd2])
where
fd1 = FDEq 1 Bool x
fd2 = FDEq 2 alpha x
To ``execute'' the equation, make fresh type variable for each tyvar in the set,
instantiate the two types with these fresh variables, and then unify or generate
a new constraint. In the above example we would generate a new unification
variable 'beta' for x and produce the following constraints:
[Wanted] (Bool ~ beta)
[Wanted] (alpha ~ beta)
Notice the subtle difference between the above class declaration and:
class C a b c | a -> b, a -> c
where we would generate:
({x},[fd1]),({x},[fd2])
This means that the template variable would be instantiated to different
unification variables when producing the FD constraints.
Finally, the position parameters will help us rewrite the wanted constraint ``on the spot''
-}
data FunDepEqn loc
= FDEqn { fd_qtvs :: [TyVar] -- Instantiate these type and kind vars
-- to fresh unification vars,
-- Non-empty only for FunDepEqns arising from instance decls
, fd_eqs :: [TypeEqn] -- Make these pairs of types equal
, fd_pred1 :: PredType -- The FunDepEqn arose from
, fd_pred2 :: PredType -- combining these two constraints
, fd_loc :: loc }
{-
Given a bunch of predicates that must hold, such as
C Int t1, C Int t2, C Bool t3, ?x::t4, ?x::t5
improve figures out what extra equations must hold.
For example, if we have
class C a b | a->b where ...
then improve will return
[(t1,t2), (t4,t5)]
NOTA BENE:
* improve does not iterate. It's possible that when we make
t1=t2, for example, that will in turn trigger a new equation.
This would happen if we also had
C t1 t7, C t2 t8
If t1=t2, we also get t7=t8.
improve does *not* do this extra step. It relies on the caller
doing so.
* The equations unify types that are not already equal. So there
is no effect iff the result of improve is empty
-}
instFD :: FunDep TyVar -> [TyVar] -> [Type] -> FunDep Type
-- (instFD fd tvs tys) returns fd instantiated with (tvs -> tys)
instFD (ls,rs) tvs tys
= (map lookup ls, map lookup rs)
where
env = zipVarEnv tvs tys
lookup tv = lookupVarEnv_NF env tv
zipAndComputeFDEqs :: (Type -> Type -> Bool) -- Discard this FDEq if true
-> [Type] -> [Type]
-> [TypeEqn]
-- Create a list of (Type,Type) pairs from two lists of types,
-- making sure that the types are not already equal
zipAndComputeFDEqs discard (ty1:tys1) (ty2:tys2)
| discard ty1 ty2 = zipAndComputeFDEqs discard tys1 tys2
| otherwise = Pair ty1 ty2 : zipAndComputeFDEqs discard tys1 tys2
zipAndComputeFDEqs _ _ _ = []
-- Improve a class constraint from another class constraint
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
improveFromAnother :: loc
-> PredType -- Template item (usually given, or inert)
-> PredType -- Workitem [that can be improved]
-> [FunDepEqn loc]
-- Post: FDEqs always oriented from the other to the workitem
-- Equations have empty quantified variables
improveFromAnother loc pred1 pred2
| Just (cls1, tys1) <- getClassPredTys_maybe pred1
, Just (cls2, tys2) <- getClassPredTys_maybe pred2
, cls1 == cls2
= [ FDEqn { fd_qtvs = [], fd_eqs = eqs, fd_pred1 = pred1, fd_pred2 = pred2, fd_loc = loc }
| let (cls_tvs, cls_fds) = classTvsFds cls1
, fd <- cls_fds
, let (ltys1, rs1) = instFD fd cls_tvs tys1
(ltys2, rs2) = instFD fd cls_tvs tys2
, eqTypes ltys1 ltys2 -- The LHSs match
, let eqs = zipAndComputeFDEqs eqType rs1 rs2
, not (null eqs) ]
improveFromAnother _ _ _ = []
-- Improve a class constraint from instance declarations
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
instance Outputable (FunDepEqn a) where
ppr = pprEquation
pprEquation :: FunDepEqn a -> SDoc
pprEquation (FDEqn { fd_qtvs = qtvs, fd_eqs = pairs })
= vcat [text "forall" <+> braces (pprWithCommas ppr qtvs),
nest 2 (vcat [ ppr t1 <+> text "~" <+> ppr t2
| Pair t1 t2 <- pairs])]
improveFromInstEnv :: InstEnvs
-> (PredType -> SrcSpan -> loc)
-> PredType
-> [FunDepEqn loc] -- Needs to be a FunDepEqn because
-- of quantified variables
-- Post: Equations oriented from the template (matching instance) to the workitem!
improveFromInstEnv inst_env mk_loc pred
| Just (cls, tys) <- ASSERT2( isClassPred pred, ppr pred )
getClassPredTys_maybe pred
, let (cls_tvs, cls_fds) = classTvsFds cls
instances = classInstances inst_env cls
rough_tcs = roughMatchTcs tys
= [ FDEqn { fd_qtvs = meta_tvs, fd_eqs = eqs
, fd_pred1 = p_inst, fd_pred2 = pred
, fd_loc = mk_loc p_inst (getSrcSpan (is_dfun ispec)) }
| fd <- cls_fds -- Iterate through the fundeps first,
-- because there often are none!
, let trimmed_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs
-- Trim the rough_tcs based on the head of the fundep.
-- Remember that instanceCantMatch treats both argumnents
-- symmetrically, so it's ok to trim the rough_tcs,
-- rather than trimming each inst_tcs in turn
, ispec <- instances
, (meta_tvs, eqs) <- improveClsFD cls_tvs fd ispec
tys trimmed_tcs -- NB: orientation
, let p_inst = mkClassPred cls (is_tys ispec)
]
improveFromInstEnv _ _ _ = []
improveClsFD :: [TyVar] -> FunDep TyVar -- One functional dependency from the class
-> ClsInst -- An instance template
-> [Type] -> [Maybe Name] -- Arguments of this (C tys) predicate
-> [([TyCoVar], [TypeEqn])] -- Empty or singleton
improveClsFD clas_tvs fd
(ClsInst { is_tvs = qtvs, is_tys = tys_inst, is_tcs = rough_tcs_inst })
tys_actual rough_tcs_actual
-- Compare instance {a,b} C sx sp sy sq
-- with wanted [W] C tx tp ty tq
-- for fundep (x,y -> p,q) from class (C x p y q)
-- If (sx,sy) unifies with (tx,ty), take the subst S
-- 'qtvs' are the quantified type variables, the ones which an be instantiated
-- to make the types match. For example, given
-- class C a b | a->b where ...
-- instance C (Maybe x) (Tree x) where ..
--
-- and a wanted constraint of form (C (Maybe t1) t2),
-- then we will call checkClsFD with
--
-- is_qtvs = {x}, is_tys = [Maybe x, Tree x]
-- tys_actual = [Maybe t1, t2]
--
-- We can instantiate x to t1, and then we want to force
-- (Tree x) [t1/x] ~ t2
| instanceCantMatch rough_tcs_inst rough_tcs_actual
= [] -- Filter out ones that can't possibly match,
| otherwise
= ASSERT2( length tys_inst == length tys_actual &&
length tys_inst == length clas_tvs
, ppr tys_inst <+> ppr tys_actual )
case tcMatchTyKis ltys1 ltys2 of
Nothing -> []
Just subst | isJust (tcMatchTyKisX subst rtys1 rtys2)
-- Don't include any equations that already hold.
-- Reason: then we know if any actual improvement has happened,
-- in which case we need to iterate the solver
-- In making this check we must taking account of the fact that any
-- qtvs that aren't already instantiated can be instantiated to anything
-- at all
-- NB: We can't do this 'is-useful-equation' check element-wise
-- because of:
-- class C a b c | a -> b c
-- instance C Int x x
-- [Wanted] C Int alpha Int
-- We would get that x -> alpha (isJust) and x -> Int (isJust)
-- so we would produce no FDs, which is clearly wrong.
-> []
| null fdeqs
-> []
| otherwise
-> [(meta_tvs, fdeqs)]
-- We could avoid this substTy stuff by producing the eqn
-- (qtvs, ls1++rs1, ls2++rs2)
-- which will re-do the ls1/ls2 unification when the equation is
-- executed. What we're doing instead is recording the partial
-- work of the ls1/ls2 unification leaving a smaller unification problem
where
rtys1' = map (substTyUnchecked subst) rtys1
fdeqs = zipAndComputeFDEqs (\_ _ -> False) rtys1' rtys2
-- Don't discard anything!
-- We could discard equal types but it's an overkill to call
-- eqType again, since we know for sure that /at least one/
-- equation in there is useful)
meta_tvs = [ setVarType tv (substTyUnchecked subst (varType tv))
| tv <- qtvs, tv `notElemTCvSubst` subst ]
-- meta_tvs are the quantified type variables
-- that have not been substituted out
--
-- Eg. class C a b | a -> b
-- instance C Int [y]
-- Given constraint C Int z
-- we generate the equation
-- ({y}, [y], z)
--
-- But note (a) we get them from the dfun_id, so they are *in order*
-- because the kind variables may be mentioned in the
-- type variabes' kinds
-- (b) we must apply 'subst' to the kinds, in case we have
-- matched out a kind variable, but not a type variable
-- whose kind mentions that kind variable!
-- Trac #6015, #6068
where
(ltys1, rtys1) = instFD fd clas_tvs tys_inst
(ltys2, rtys2) = instFD fd clas_tvs tys_actual
{-
%************************************************************************
%* *
The Coverage condition for instance declarations
* *
************************************************************************
Note [Coverage condition]
~~~~~~~~~~~~~~~~~~~~~~~~~
Example
class C a b | a -> b
instance theta => C t1 t2
For the coverage condition, we check
(normal) fv(t2) `subset` fv(t1)
(liberal) fv(t2) `subset` oclose(fv(t1), theta)
The liberal version ensures the self-consistency of the instance, but
it does not guarantee termination. Example:
class Mul a b c | a b -> c where
(.*.) :: a -> b -> c
instance Mul Int Int Int where (.*.) = (*)
instance Mul Int Float Float where x .*. y = fromIntegral x * y
instance Mul a b c => Mul a [b] [c] where x .*. v = map (x.*.) v
In the third instance, it's not the case that fv([c]) `subset` fv(a,[b]).
But it is the case that fv([c]) `subset` oclose( theta, fv(a,[b]) )
But it is a mistake to accept the instance because then this defn:
f = \ b x y -> if b then x .*. [y] else y
makes instance inference go into a loop, because it requires the constraint
Mul a [b] b
-}
checkInstCoverage :: Bool -- Be liberal
-> Class -> [PredType] -> [Type]
-> Validity
-- "be_liberal" flag says whether to use "liberal" coverage of
-- See Note [Coverage Condition] below
--
-- Return values
-- Nothing => no problems
-- Just msg => coverage problem described by msg
checkInstCoverage be_liberal clas theta inst_taus
= allValid (map fundep_ok fds)
where
(tyvars, fds) = classTvsFds clas
fundep_ok fd
| and (isEmptyVarSet <$> undetermined_tvs) = IsValid
| otherwise = NotValid msg
where
(ls,rs) = instFD fd tyvars inst_taus
ls_tvs = tyCoVarsOfTypes ls
rs_tvs = splitVisVarsOfTypes rs
undetermined_tvs | be_liberal = liberal_undet_tvs
| otherwise = conserv_undet_tvs
closed_ls_tvs = oclose theta ls_tvs
liberal_undet_tvs = (`minusVarSet` closed_ls_tvs) <$> rs_tvs
conserv_undet_tvs = (`minusVarSet` ls_tvs) <$> rs_tvs
undet_set = fold undetermined_tvs
msg = vcat [ -- text "ls_tvs" <+> ppr ls_tvs
-- , text "closed ls_tvs" <+> ppr (closeOverKinds ls_tvs)
-- , text "theta" <+> ppr theta
-- , text "oclose" <+> ppr (oclose theta (closeOverKinds ls_tvs))
-- , text "rs_tvs" <+> ppr rs_tvs
sep [ text "The"
<+> ppWhen be_liberal (text "liberal")
<+> text "coverage condition fails in class"
<+> quotes (ppr clas)
, nest 2 $ text "for functional dependency:"
<+> quotes (pprFunDep fd) ]
, sep [ text "Reason: lhs type"<>plural ls <+> pprQuotedList ls
, nest 2 $
(if isSingleton ls
then text "does not"
else text "do not jointly")
<+> text "determine rhs type"<>plural rs
<+> pprQuotedList rs ]
, text "Un-determined variable" <> pluralVarSet undet_set <> colon
<+> pprVarSet undet_set (pprWithCommas ppr)
, ppWhen (isEmptyVarSet $ pSnd undetermined_tvs) $
ppSuggestExplicitKinds
, ppWhen (not be_liberal &&
and (isEmptyVarSet <$> liberal_undet_tvs)) $
text "Using UndecidableInstances might help" ]
{- Note [Closing over kinds in coverage]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have a fundep (a::k) -> b
Then if 'a' is instantiated to (x y), where x:k2->*, y:k2,
then fixing x really fixes k2 as well, and so k2 should be added to
the lhs tyvars in the fundep check.
Example (Trac #8391), using liberal coverage
data Foo a = ... -- Foo :: forall k. k -> *
class Bar a b | a -> b
instance Bar a (Foo a)
In the instance decl, (a:k) does fix (Foo k a), but only if we notice
that (a:k) fixes k. Trac #10109 is another example.
Here is a more subtle example, from HList-0.4.0.0 (Trac #10564)
class HasFieldM (l :: k) r (v :: Maybe *)
| l r -> v where ...
class HasFieldM1 (b :: Maybe [*]) (l :: k) r v
| b l r -> v where ...
class HMemberM (e1 :: k) (l :: [k]) (r :: Maybe [k])
| e1 l -> r
data Label :: k -> *
type family LabelsOf (a :: [*]) :: *
instance (HMemberM (Label {k} (l::k)) (LabelsOf xs) b,
HasFieldM1 b l (r xs) v)
=> HasFieldM l (r xs) v where
Is the instance OK? Does {l,r,xs} determine v? Well:
* From the instance constraint HMemberM (Label k l) (LabelsOf xs) b,
plus the fundep "| el l -> r" in class HMameberM,
we get {l,k,xs} -> b
* Note the 'k'!! We must call closeOverKinds on the seed set
ls_tvs = {l,r,xs}, BEFORE doing oclose, else the {l,k,xs}->b
fundep won't fire. This was the reason for #10564.
* So starting from seeds {l,r,xs,k} we do oclose to get
first {l,r,xs,k,b}, via the HMemberM constraint, and then
{l,r,xs,k,b,v}, via the HasFieldM1 constraint.
* And that fixes v.
However, we must closeOverKinds whenever augmenting the seed set
in oclose! Consider Trac #10109:
data Succ a -- Succ :: forall k. k -> *
class Add (a :: k1) (b :: k2) (ab :: k3) | a b -> ab
instance (Add a b ab) => Add (Succ {k1} (a :: k1))
b
(Succ {k3} (ab :: k3})
We start with seed set {a:k1,b:k2} and closeOverKinds to {a,k1,b,k2}.
Now use the fundep to extend to {a,k1,b,k2,ab}. But we need to
closeOverKinds *again* now to {a,k1,b,k2,ab,k3}, so that we fix all
the variables free in (Succ {k3} ab).
Bottom line:
* closeOverKinds on initial seeds (done automatically
by tyCoVarsOfTypes in checkInstCoverage)
* and closeOverKinds whenever extending those seeds (in oclose)
Note [The liberal coverage condition]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
(oclose preds tvs) closes the set of type variables tvs,
wrt functional dependencies in preds. The result is a superset
of the argument set. For example, if we have
class C a b | a->b where ...
then
oclose [C (x,y) z, C (x,p) q] {x,y} = {x,y,z}
because if we know x and y then that fixes z.
We also use equality predicates in the predicates; if we have an
assumption `t1 ~ t2`, then we use the fact that if we know `t1` we
also know `t2` and the other way.
eg oclose [C (x,y) z, a ~ x] {a,y} = {a,y,z,x}
oclose is used (only) when checking the coverage condition for
an instance declaration
Note [Equality superclasses]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
class (a ~ [b]) => C a b
Remember from Note [The equality types story] in TysPrim, that
* (a ~~ b) is a superclass of (a ~ b)
* (a ~# b) is a superclass of (a ~~ b)
So when oclose expands superclasses we'll get a (a ~# [b]) superclass.
But that's an EqPred not a ClassPred, and we jolly well do want to
account for the mutual functional dependencies implied by (t1 ~# t2).
Hence the EqPred handling in oclose. See Trac #10778.
Note [Care with type functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider (Trac #12803)
class C x y | x -> y
type family F a b
type family G c d = r | r -> d
Now consider
oclose (C (F a b) (G c d)) {a,b}
Knowing {a,b} fixes (F a b) regardless of the injectivity of F.
But knowing (G c d) fixes only {d}, because G is only injective
in its second parameter.
Hence the tyCoVarsOfTypes/injTyVarsOfTypes dance in tv_fds.
-}
oclose :: [PredType] -> TyCoVarSet -> TyCoVarSet
-- See Note [The liberal coverage condition]
oclose preds fixed_tvs
| null tv_fds = fixed_tvs -- Fast escape hatch for common case.
| otherwise = fixVarSet extend fixed_tvs
where
extend fixed_tvs = foldl add fixed_tvs tv_fds
where
add fixed_tvs (ls,rs)
| ls `subVarSet` fixed_tvs = fixed_tvs `unionVarSet` closeOverKinds rs
| otherwise = fixed_tvs
-- closeOverKinds: see Note [Closing over kinds in coverage]
tv_fds :: [(TyCoVarSet,TyCoVarSet)]
tv_fds = [ (tyCoVarsOfTypes ls, injTyVarsOfTypes rs)
-- See Note [Care with type functions]
| pred <- preds
, pred' <- pred : transSuperClasses pred
-- Look for fundeps in superclasses too
, (ls, rs) <- determined pred' ]
determined :: PredType -> [([Type],[Type])]
determined pred
= case classifyPredType pred of
EqPred NomEq t1 t2 -> [([t1],[t2]), ([t2],[t1])]
-- See Note [Equality superclasses]
ClassPred cls tys -> [ instFD fd cls_tvs tys
| let (cls_tvs, cls_fds) = classTvsFds cls
, fd <- cls_fds ]
_ -> []
{- *********************************************************************
* *
Check that a new instance decl is OK wrt fundeps
* *
************************************************************************
Here is the bad case:
class C a b | a->b where ...
instance C Int Bool where ...
instance C Int Char where ...
The point is that a->b, so Int in the first parameter must uniquely
determine the second. In general, given the same class decl, and given
instance C s1 s2 where ...
instance C t1 t2 where ...
Then the criterion is: if U=unify(s1,t1) then U(s2) = U(t2).
Matters are a little more complicated if there are free variables in
the s2/t2.
class D a b c | a -> b
instance D a b => D [(a,a)] [b] Int
instance D a b => D [a] [b] Bool
The instance decls don't overlap, because the third parameter keeps
them separate. But we want to make sure that given any constraint
D s1 s2 s3
if s1 matches
Note [Bogus consistency check]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In checkFunDeps we check that a new ClsInst is consistent with all the
ClsInsts in the environment.
The bogus aspect is discussed in Trac #10675. Currenty it if the two
types are *contradicatory*, using (isNothing . tcUnifyTys). But all
the papers say we should check if the two types are *equal* thus
not (substTys subst rtys1 `eqTypes` substTys subst rtys2)
For now I'm leaving the bogus form because that's the way it has
been for years.
-}
checkFunDeps :: InstEnvs -> ClsInst -> [ClsInst]
-- The Consistency Check.
-- Check whether adding DFunId would break functional-dependency constraints
-- Used only for instance decls defined in the module being compiled
-- Returns a list of the ClsInst in InstEnvs that are inconsistent
-- with the proposed new ClsInst
checkFunDeps inst_envs (ClsInst { is_tvs = qtvs1, is_cls = cls
, is_tys = tys1, is_tcs = rough_tcs1 })
| null fds
= []
| otherwise
= nubBy eq_inst $
[ ispec | ispec <- cls_insts
, fd <- fds
, is_inconsistent fd ispec ]
where
cls_insts = classInstances inst_envs cls
(cls_tvs, fds) = classTvsFds cls
qtv_set1 = mkVarSet qtvs1
is_inconsistent fd (ClsInst { is_tvs = qtvs2, is_tys = tys2, is_tcs = rough_tcs2 })
| instanceCantMatch trimmed_tcs rough_tcs2
= False
| otherwise
= case tcUnifyTyKis bind_fn ltys1 ltys2 of
Nothing -> False
Just subst
-> isNothing $ -- Bogus legacy test (Trac #10675)
-- See Note [Bogus consistency check]
tcUnifyTyKis bind_fn (substTysUnchecked subst rtys1) (substTysUnchecked subst rtys2)
where
trimmed_tcs = trimRoughMatchTcs cls_tvs fd rough_tcs1
(ltys1, rtys1) = instFD fd cls_tvs tys1
(ltys2, rtys2) = instFD fd cls_tvs tys2
qtv_set2 = mkVarSet qtvs2
bind_fn tv | tv `elemVarSet` qtv_set1 = BindMe
| tv `elemVarSet` qtv_set2 = BindMe
| otherwise = Skolem
eq_inst i1 i2 = instanceDFunId i1 == instanceDFunId i2
-- An single instance may appear twice in the un-nubbed conflict list
-- because it may conflict with more than one fundep. E.g.
-- class C a b c | a -> b, a -> c
-- instance C Int Bool Bool
-- instance C Int Char Char
-- The second instance conflicts with the first by *both* fundeps
trimRoughMatchTcs :: [TyVar] -> FunDep TyVar -> [Maybe Name] -> [Maybe Name]
-- Computing rough_tcs for a particular fundep
-- class C a b c | a -> b where ...
-- For each instance .... => C ta tb tc
-- we want to match only on the type ta; so our
-- rough-match thing must similarly be filtered.
-- Hence, we Nothing-ise the tb and tc types right here
--
-- Result list is same length as input list, just with more Nothings
trimRoughMatchTcs clas_tvs (ltvs, _) mb_tcs
= zipWith select clas_tvs mb_tcs
where
select clas_tv mb_tc | clas_tv `elem` ltvs = mb_tc
| otherwise = Nothing
| olsner/ghc | compiler/typecheck/FunDeps.hs | bsd-3-clause | 26,607 | 0 | 19 | 8,718 | 2,787 | 1,511 | 1,276 | -1 | -1 |
module A3 where
import C3
main xs
= case xs of
[] -> 0
[(x : xs)]
-> (x ^ pow) +
(case xs of
(x : xs) -> (sq x) + (sumSquares1 xs)
[] -> 0)
| kmate/HaRe | old/testing/unfoldDef/A3AST.hs | bsd-3-clause | 270 | 0 | 15 | 167 | 98 | 53 | 45 | 10 | 3 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Traversable
-- Copyright : Conor McBride and Ross Paterson 2005
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Class of data structures that can be traversed from left to right,
-- performing an action on each element.
--
-- See also
--
-- * \"Applicative Programming with Effects\",
-- by Conor McBride and Ross Paterson,
-- /Journal of Functional Programming/ 18:1 (2008) 1-13, online at
-- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>.
--
-- * \"The Essence of the Iterator Pattern\",
-- by Jeremy Gibbons and Bruno Oliveira,
-- in /Mathematically-Structured Functional Programming/, 2006, online at
-- <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>.
--
-- * \"An Investigation of the Laws of Traversals\",
-- by Mauro Jaskelioff and Ondrej Rypacek,
-- in /Mathematically-Structured Functional Programming/, 2012, online at
-- <http://arxiv.org/pdf/1202.2919>.
--
-----------------------------------------------------------------------------
module Data.Traversable (
-- * The 'Traversable' class
Traversable(..),
-- * Utility functions
for,
forM,
mapAccumL,
mapAccumR,
-- * General definitions for superclass methods
fmapDefault,
foldMapDefault,
) where
-- It is convenient to use 'Const' here but this means we must
-- define a few instances here which really belong in Control.Applicative
import Control.Applicative ( Const(..), ZipList(..) )
import Data.Either ( Either(..) )
import Data.Foldable ( Foldable )
import Data.Functor
import Data.Monoid ( Dual(..), Sum(..), Product(..), First(..), Last(..) )
import Data.Proxy ( Proxy(..) )
import GHC.Arr
import GHC.Base ( Applicative(..), Monad(..), Monoid, Maybe(..),
($), (.), id, flip )
import qualified GHC.List as List ( foldr )
-- | Functors representing data structures that can be traversed from
-- left to right.
--
-- A definition of 'traverse' must satisfy the following laws:
--
-- [/naturality/]
-- @t . 'traverse' f = 'traverse' (t . f)@
-- for every applicative transformation @t@
--
-- [/identity/]
-- @'traverse' Identity = Identity@
--
-- [/composition/]
-- @'traverse' (Compose . 'fmap' g . f) = Compose . 'fmap' ('traverse' g) . 'traverse' f@
--
-- A definition of 'sequenceA' must satisfy the following laws:
--
-- [/naturality/]
-- @t . 'sequenceA' = 'sequenceA' . 'fmap' t@
-- for every applicative transformation @t@
--
-- [/identity/]
-- @'sequenceA' . 'fmap' Identity = Identity@
--
-- [/composition/]
-- @'sequenceA' . 'fmap' Compose = Compose . 'fmap' 'sequenceA' . 'sequenceA'@
--
-- where an /applicative transformation/ is a function
--
-- @t :: (Applicative f, Applicative g) => f a -> g a@
--
-- preserving the 'Applicative' operations, i.e.
--
-- * @t ('pure' x) = 'pure' x@
--
-- * @t (x '<*>' y) = t x '<*>' t y@
--
-- and the identity functor @Identity@ and composition of functors @Compose@
-- are defined as
--
-- > newtype Identity a = Identity a
-- >
-- > instance Functor Identity where
-- > fmap f (Identity x) = Identity (f x)
-- >
-- > instance Applicative Identity where
-- > pure x = Identity x
-- > Identity f <*> Identity x = Identity (f x)
-- >
-- > newtype Compose f g a = Compose (f (g a))
-- >
-- > instance (Functor f, Functor g) => Functor (Compose f g) where
-- > fmap f (Compose x) = Compose (fmap (fmap f) x)
-- >
-- > instance (Applicative f, Applicative g) => Applicative (Compose f g) where
-- > pure x = Compose (pure (pure x))
-- > Compose f <*> Compose x = Compose ((<*>) <$> f <*> x)
--
-- (The naturality law is implied by parametricity.)
--
-- Instances are similar to 'Functor', e.g. given a data type
--
-- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)
--
-- a suitable instance would be
--
-- > instance Traversable Tree where
-- > traverse f Empty = pure Empty
-- > traverse f (Leaf x) = Leaf <$> f x
-- > traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r
--
-- This is suitable even for abstract types, as the laws for '<*>'
-- imply a form of associativity.
--
-- The superclass instances should satisfy the following:
--
-- * In the 'Functor' instance, 'fmap' should be equivalent to traversal
-- with the identity applicative functor ('fmapDefault').
--
-- * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be
-- equivalent to traversal with a constant applicative functor
-- ('foldMapDefault').
--
class (Functor t, Foldable t) => Traversable t where
{-# MINIMAL traverse | sequenceA #-}
-- | Map each element of a structure to an action, evaluate these actions
-- from left to right, and collect the results. For a version that ignores
-- the results see 'Data.Foldable.traverse_'.
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
traverse f = sequenceA . fmap f
-- | Evaluate each action in the structure from left to right, and
-- and collect the results. For a version that ignores the results
-- see 'Data.Foldable.sequenceA_'.
sequenceA :: Applicative f => t (f a) -> f (t a)
sequenceA = traverse id
-- | Map each element of a structure to a monadic action, evaluate
-- these actions from left to right, and collect the results. For
-- a version that ignores the results see 'Data.Foldable.mapM_'.
mapM :: Monad m => (a -> m b) -> t a -> m (t b)
mapM = traverse
-- | Evaluate each monadic action in the structure from left to
-- right, and collect the results. For a version that ignores the
-- results see 'Data.Foldable.sequence_'.
sequence :: Monad m => t (m a) -> m (t a)
sequence = sequenceA
-- instances for Prelude types
instance Traversable Maybe where
traverse _ Nothing = pure Nothing
traverse f (Just x) = Just <$> f x
instance Traversable [] where
{-# INLINE traverse #-} -- so that traverse can fuse
traverse f = List.foldr cons_f (pure [])
where cons_f x ys = (:) <$> f x <*> ys
instance Traversable (Either a) where
traverse _ (Left x) = pure (Left x)
traverse f (Right y) = Right <$> f y
instance Traversable ((,) a) where
traverse f (x, y) = (,) x <$> f y
instance Ix i => Traversable (Array i) where
traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr)
instance Traversable Proxy where
traverse _ _ = pure Proxy
{-# INLINE traverse #-}
sequenceA _ = pure Proxy
{-# INLINE sequenceA #-}
mapM _ _ = return Proxy
{-# INLINE mapM #-}
sequence _ = return Proxy
{-# INLINE sequence #-}
instance Traversable (Const m) where
traverse _ (Const m) = pure $ Const m
instance Traversable Dual where
traverse f (Dual x) = Dual <$> f x
instance Traversable Sum where
traverse f (Sum x) = Sum <$> f x
instance Traversable Product where
traverse f (Product x) = Product <$> f x
instance Traversable First where
traverse f (First x) = First <$> traverse f x
instance Traversable Last where
traverse f (Last x) = Last <$> traverse f x
instance Traversable ZipList where
traverse f (ZipList x) = ZipList <$> traverse f x
-- general functions
-- | 'for' is 'traverse' with its arguments flipped. For a version
-- that ignores the results see 'Data.Foldable.for_'.
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
{-# INLINE for #-}
for = flip traverse
-- | 'forM' is 'mapM' with its arguments flipped. For a version that
-- ignores the results see 'Data.Foldable.forM_'.
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
{-# INLINE forM #-}
forM = flip mapM
-- left-to-right state transformer
newtype StateL s a = StateL { runStateL :: s -> (s, a) }
instance Functor (StateL s) where
fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v)
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)
-- |The 'mapAccumL' function behaves like a combination of 'fmap'
-- and 'foldl'; it applies a function to each element of a structure,
-- passing an accumulating parameter from left to right, and returning
-- a final value of this accumulator together with the new structure.
mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s
-- right-to-left state transformer
newtype StateR s a = StateR { runStateR :: s -> (s, a) }
instance Functor (StateR s) where
fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v)
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)
-- |The 'mapAccumR' function behaves like a combination of 'fmap'
-- and 'foldr'; it applies a function to each element of a structure,
-- passing an accumulating parameter from right to left, and returning
-- a final value of this accumulator together with the new structure.
mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c)
mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s
-- | This function may be used as a value for `fmap` in a `Functor`
-- instance, provided that 'traverse' is defined. (Using
-- `fmapDefault` with a `Traversable` instance defined only by
-- 'sequenceA' will result in infinite recursion.)
fmapDefault :: Traversable t => (a -> b) -> t a -> t b
{-# INLINE fmapDefault #-}
fmapDefault f = getId . traverse (Id . f)
-- | This function may be used as a value for `Data.Foldable.foldMap`
-- in a `Foldable` instance.
foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m
foldMapDefault f = getConst . traverse (Const . f)
-- local instances
newtype Id a = Id { getId :: a }
instance Functor Id where
fmap f (Id x) = Id (f x)
instance Applicative Id where
pure = Id
Id f <*> Id x = Id (f x)
| acowley/ghc | libraries/base/Data/Traversable.hs | bsd-3-clause | 10,316 | 0 | 12 | 2,284 | 2,033 | 1,140 | 893 | 106 | 1 |
module Pair () where
import Language.Haskell.Liquid.Prelude
{-@ data Pair a b <p :: x0:a -> x1:b -> Prop> = P (x :: a) (y :: b<p x>) @-}
data Pair a b = P a b
incr x = let p = P x ((x+1)) in p
chk (P x (y)) = liquidAssertB (x<y)
prop = chk $ incr n
where n = choose 0
incr2 x =
let p1 = (P True (x+1)) in
let p2 = P x p1 in
p2
chk2 (P x w) =
case w of (P z y) -> liquidAssertB (x<y)
prop2 = chk2 $ incr2 n
where n = choose 0
incr3 x = P x (P True (P 0 (x+1)))
chk3 (P x (P _(P _ y))) = liquidAssertB (x<y)
prop3 = chk3 $ incr3 n
where n = choose 0
| ssaavedra/liquidhaskell | tests/pos/pair.hs | bsd-3-clause | 582 | 0 | 12 | 173 | 329 | 169 | 160 | 19 | 1 |
import System.IO
main = do
hSetBuffering stdout NoBuffering
putStr "Enter an integer: "
x1 <- readLine
putStr "Enter another integer: "
x2 <- readLine
putStr ("Their sum is " ++ show (read x1 + read x2 :: Int) ++ "\n")
where readLine = do
eof <- isEOF
if eof then return [] else do
c <- getChar
if c `elem` ['\n','\r']
then return []
else do cs <- readLine
return (c:cs)
| urbanslug/ghc | libraries/base/tests/IO/hGetChar001.hs | bsd-3-clause | 468 | 6 | 14 | 168 | 163 | 78 | 85 | -1 | -1 |
module M where
| ezyang/ghc | testsuite/tests/backpack/cabal/bkpcabal07/M.hs | bsd-3-clause | 15 | 0 | 2 | 3 | 4 | 3 | 1 | 1 | 0 |
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE GADTs #-}
-- https://www.cs.ox.ac.uk/jeremy.gibbons/publications/iterator.pdf
module Iterator where
import Data.Bifunctor
import Data.Monoid
import Data.Foldable
import Control.Applicative hiding (Const)
import Control.Comonad
import Control.Monad
import Data.Char
data Fix s a = In { out :: s a (Fix s a) }
bmap :: Bifunctor s => (a -> b) -> Fix s a -> Fix s b
bmap f = In . bimap f (bmap f) . out
bfold :: Bifunctor s => (s a b -> b) -> Fix s a -> b
bfold f = f . bimap id (bfold f) . out
bunfold :: Bifunctor s => (b -> s a b) -> b -> Fix s a
bunfold f = In . bimap id (bunfold f) . f
data Stream a = SCons a (Stream a)
instance Functor Stream where
fmap f (SCons x xs) = SCons (f x) (fmap f xs)
instance Applicative Stream where
pure a = SCons a (pure a)
SCons f fs <*> SCons x xs = SCons (f x) (fs <*> xs)
instance Comonad Stream where
extract (SCons a _) = a
duplicate (SCons a tl) = SCons (SCons a tl) (cojoin tl)
-- instance Monad Stream where
-- return a = SCons a (return a)
-- (SCons a tl) >>= f = SCons (f a) (tl >>= f)
counit :: Stream a -> a
counit (SCons a _) = a
cojoin :: Stream a -> Stream (Stream a)
cojoin (SCons a tl) = SCons (SCons a tl) (cojoin tl)
srepeat :: a -> Stream a
srepeat a = SCons a (srepeat a)
newtype Reader r a = Reader { unReader :: r -> a }
ask :: Reader r r
ask = Reader id
instance Functor (Reader r) where
fmap f ra = Reader (\r -> f ((unReader ra) r))
instance Applicative (Reader r) where
-- pure :: a -> Reader r a
pure = Reader . const
(Reader f) <*> (Reader a) = Reader $ \r -> (f r) (a r)
instance Monad (Reader r) where
return a = Reader $ \r -> a
(Reader fra) >>= f = Reader $ \r ->
let a = fra r in
let (Reader frb) = f a in
frb r
newtype Const b a = Const { unConst :: b }
instance Monoid m => Functor (Const m) where
fmap :: (a -> b) -> (Const m a) -> (Const m b)
fmap f = Const . unConst
instance Monoid b => Applicative (Const b) where
pure _ = Const mempty
(Const x) <*> (Const y) = Const (x `mappend` y)
-- instance Applicative [] where
-- pure x = xs where xs = x:xs
-- (f:fs) <*> (x:xs) = f x:(fs <*> xs)
-- _ <*> _ = []
-- type Prod<'F, 'G, 'a> = { fst : App<'F, 'a> ; snd : App<'G, 'a> }
data (m • n) a = Prod { pfst :: m a, psnd :: n a }
instance (Functor m, Functor n) => Functor (m • n) where
fmap f mn = Prod (fmap f (pfst mn)) (fmap f (psnd mn))
instance (Applicative m, Applicative n) => Applicative (m • n) where
pure x = Prod (pure x) (pure x)
mf <*> mx = Prod (pfst mf <*> pfst mx) (psnd mf <*> psnd mx)
-- (°) :: (Functor m, Functor n) => (a -> m b) -> (a -> n b) -> (a -> (m • n) b)
-- (f ° g) x = Prod (f x) (g x)
(•) :: (Functor m, Functor n) => (a -> m b) -> (a -> n b) -> (a -> (m • n) b)
(f • g) x = Prod (f x) (g x)
data (m ° n) a = Comp { unComp :: m (n a) }
instance (Functor m, Functor n) => Functor (m ° n) where
fmap :: (a -> b) -> (m ° n) a -> (m ° n) b
fmap f mn = Comp $ fmap (fmap f) (unComp mn)
instance (Applicative m, Applicative n) => Applicative (m ° n) where
pure x = Comp $ pure (pure x)
-- (<*>) :: (m ° n) (a -> b) -> (m ° n) a -> (m ° n) b
-- pure (<*>) :: m (n (a -> b) -> n a -> n b)
-- pure (<*>) <*> fs :: m (n a -> n b)
-- pure (<*>) <*> fs <*> xs :: m (n b)
(Comp fs) <*> (Comp xs) = Comp $ pure (<*>) <*> fs <*> xs
(°) :: (Functor m, Functor n) => (b -> n c) -> (a -> m b) -> (a -> (m ° n) c)
f ° g = Comp . fmap f . g
traverseList :: (Applicative m) => (a -> m b) -> [a] -> m [b]
traverseList f [] = pure []
traverseList f (x:xs) = pure (:) <*> f x <*> traverseList f xs
distList :: (Applicative m) => [m a] -> m [a]
distList = traverseList id
class Functor t => Traversable t where
traverse :: Applicative m => (a -> m b) -> t a -> m (t b)
traverse f = dist . fmap f
dist :: Applicative m => t (m a) -> m (t a)
dist = traverse id
data Tree a = Leaf a | Bin (Tree a) (Tree a) deriving (Show)
instance Functor Tree where
fmap f (Leaf a) = Leaf (f a)
fmap f (Bin l r) = Bin (fmap f l) (fmap f r)
instance Foldable Tree where
foldMap f (Leaf a) = mappend (f a) mempty
foldMap f (Bin l r) = mappend (foldMap f l) (foldMap f r)
instance Traversable Tree where
traverse f (Leaf a) = pure Leaf <*> (f a)
traverse f (Bin l r) = pure Bin <*> traverse f l <*> traverse f r
class Bifunctor s => Bitraversable s where
bidist :: Applicative m => s (m a) (m b) -> m (s a b)
instance Bitraversable s => Functor (Fix s) where
fmap f = bmap f
instance Bitraversable s => Traversable (Fix s) where
traverse :: Applicative m => (a -> m b) -> Fix s a -> m (Fix s b)
traverse f = bfold (fmap In . bidist . bimap f id)
newtype Id a = Id { unId :: a }
instance Functor Id where
fmap f = Id . f . unId
instance Applicative Id where
pure a = Id a
(Id f) <*> (Id a) = Id (f a)
reduce :: (Traversable t, Monoid m) => (a -> m) -> t a -> m
reduce f = unConst . traverse (Const . f)
crush :: (Traversable t, Monoid m) => t m -> m
crush = reduce id
-- tsum :: (Traversable t) => t Integer -> Integer
-- tsum = crush
class Coerce a b | a -> b where
cdown :: a -> b
cup :: b -> a
instance Coerce (Id a) a where
cdown = unId
cup = Id
instance Coerce (Const a b) a where
cdown = unConst
cup = Const
instance (Coerce (m a) b, Coerce (n a) c) => Coerce ((m • n) a) (b,c) where
cdown mnx = (cdown (pfst mnx),cdown (psnd mnx))
cup (x,y) = Prod (cup x) (cup y)
instance (Functor m, Functor n, Coerce (m b) c, Coerce (n a) b) => Coerce ((m ° n) a) c where
cdown = cdown . fmap cdown . unComp
cup = Comp . fmap cup . cup
contentsBody :: a -> Const [a] b
contentsBody a = cup [a]
contents :: Traversable t => t a -> Const [a] (t b)
contents = traverse contentsBody
run :: (Coerce b c, Traversable t) => (t a -> b) -> t a -> c
run program = cdown . program
runContents :: Traversable t => t a -> [a]
runContents = run contents
shapeBody :: a -> Id ()
shapeBody _ = cup ()
shape :: Traversable t => t a -> Id (t ())
shape = traverse shapeBody
decompose :: Traversable t => t a -> (Id • Const [a]) (t ())
-- decompose = shape ° contents
decompose = traverse (shapeBody • contentsBody)
instance Coerce (Maybe a) (Maybe a) where
cdown = id
cup = id
newtype State s a = State { runState :: s -> (a,s) }
get :: State s s
get = State $ \s -> (s,s)
put :: s -> State s ()
put a = State $ \s -> ((),a)
modify :: (s -> s) -> State s ()
modify f = State $ \s -> ((), f s)
instance Functor (State s) where
fmap f (State st) = State $ \s -> let (a,s') = st s in (f a, s')
instance Applicative (State s) where
pure a = State $ \s -> (a,s)
(State sab) <*> (State sa) = State $ \s ->
let (ab,s') = sab s in
let (a,s'') = sa s' in
(ab a,s'')
instance Monad (State s) where
return a = State $ \s -> (a,s)
(State sa) >>= f = State $ \s ->
let (a,s') = sa s in
let (b,s'') = (runState (f a)) s' in
(b,s'')
instance Coerce (State s a) (s -> (a,s)) where
cdown = runState
cup = State
reassembleBody :: () -> (State [a] ° Maybe) a
reassembleBody = cup . weakHead where
weakHead _ [] = (Nothing, [])
weakHead _ (y:ys) = (Just y, ys)
reassemble :: Traversable t => t () -> (State [a] ° Maybe) (t a)
reassemble = traverse reassembleBody
runReassemble :: Traversable t => (t (), [a]) -> Maybe (t a)
runReassemble = fst . uncurry (run reassemble)
-- runDecompose xs = (ys,zs) =
-- fmap (curry runReassemble ys) (traverseList fs zs) = fmap (Just) (traverse f xs)
collect :: (Traversable t, Applicative m) => (a -> m ()) -> (a -> b) -> t a -> m (t b)
collect f g = traverse (\a -> pure (\() -> g a) <*> f a)
loop :: (Traversable t) => (a -> b) -> t a -> State Integer (t b)
loop touch = collect (\a -> do { n <- get ; put (n + 1) }) touch
disperse :: (Traversable t, Applicative m) => m b -> (a -> b -> c) -> t a -> m (t c)
disperse mb g = traverse (\a -> pure (g a) <*> mb)
label :: Traversable t => t a -> State Integer (t Integer)
label = disperse step (curry snd)
step :: State Integer Integer
step = do
n <- get
put (n + 1)
return n
newtype Backwards m a = Backwards { runBackwards :: m a }
instance Functor m => Functor (Backwards m) where
fmap f = Backwards . fmap f . runBackwards
instance Applicative m => Applicative (Backwards m) where
pure = Backwards . pure
(Backwards f) <*> (Backwards a) = Backwards $ pure (flip ($)) <*> a <*> f
data AppAdapter m where
AppAdapter :: Applicative (g m) =>
(forall a. m a -> g m a) -> (forall a. g m a -> m a) -> AppAdapter m
backwards :: Applicative m => AppAdapter m
backwards = AppAdapter Backwards runBackwards
ptraverse :: (Applicative m, Traversable t) => AppAdapter m -> (a -> m b) -> t a -> m (t b)
ptraverse (AppAdapter insert retrieve) f = retrieve . traverse (insert . f)
lebal :: Traversable t => t a -> State Integer (t Integer)
lebal = ptraverse backwards (\a -> step)
-- distLaw :: (Traversable t, Applicative m) => (a -> b) -> t (m a) -> Bool
-- distLaw f tma = dist . fmap (fmap f) == fmap (fmap f) . dist
-- dist . fmap Id = Id
-- dist . fmap Comp = Comp . fmap dist . dist
(<<*>>) :: Monad m => (b -> m c) -> (a -> m b) -> (a -> m c)
g <<*>> f = \a -> f a >>= g
-- (mx >>= \x -> my >>= \y -> (x,y)) = (my >>= \y -> mx >>= \x -> (x,y))
update1 :: a -> State Integer a
update1 x = do { var <- get ; put (var * 2) ; return x }
update2 :: a -> State Integer a
update2 x = do { var <- get ; put (var + 1); return x }
-- monadic1 = traverse update1 <<*>> traverse update2
-- monadic2 = traverse (update1 <<*>> update2)
instance Traversable [] where
traverse f [] = pure []
--traverse f (x:xs) = pure (const (:)) <*> f x <*> traverse f xs
traverse f (x:xs) = pure (:) <*> f x <*> traverse f xs
type Count = Const Integer
instance Monoid Integer where
mempty = 0
mappend = (+)
count :: a -> Count b
count _ = Const 1
cciBody :: Char -> Count a
cciBody = count
cci :: String -> Count [a]
cci = traverse cciBody
test :: Bool -> Integer
test b = if b then 1 else 0
lciBody::Char -> Count a
lciBody c = cup (test (c == '\n'))
lci :: String -> Count [a]
lci = traverse lciBody
wciBody :: Char -> ((State Bool) ° Count) a
wciBody c = cup (updateState c) where
updateState :: Char -> Bool -> (Integer,Bool)
updateState c w = let s = not (isSpace c) in (test (not w && s),s)
wci :: String -> ((State Bool) ° Count) [a]
wci = traverse wciBody
clci :: String -> (Count • Count) [a]
-- clci = cci ° lci
clci = traverse (cciBody • lciBody)
-- (m ° n) a :: m (n a)
clwci :: String -> ((Count • Count) • ((State Bool) ° Count)) [a]
clwci = traverse (cciBody • lciBody • wciBody)
newtype Pair a = P (a,a)
instance Functor Pair where
fmap f (P (a,b)) = P (f a, f b)
instance Applicative Pair where
pure a = P (a,a)
P (f,g) <*> P (x,y) = P (f x, g y)
quiBody :: Char -> Pair Bool
quiBody c = P (c == 'q', c == 'u')
qui :: String -> Pair [Bool]
qui = traverse quiBody
-- ⊠ = Prod = •
-- = Comp = °
-- ⊗ = ° = (a -> m b) ° (a -> n b) = (a -> (m ° n) b)
-- ⊙ = = (a -> m b) (a -> n b) = (a -> (m ))
ccqui :: String -> (Count • Pair) [Bool]
ccqui = traverse (cciBody • quiBody)
wcqui :: String -> (Pair • (State Bool ° Count)) [Bool]
wcqui = qui • wci
wcqui' :: String -> ((Id • (State Bool ° Count)) ° Pair) [Bool]
wcqui' = traverse (quiBody ° (Id • wciBody))
newtype Writer w a = Writer { unWriter :: (a,w) }
instance Monoid w => Functor (Writer w) where
fmap f (Writer (a,w)) = Writer (f a, w)
instance Monoid w => Applicative (Writer w) where
pure a = Writer (a, mempty)
(Writer (f,w)) <*> (Writer (a,w')) = Writer (f a, mappend w w')
instance Monoid w => Monad (Writer w) where
return a = Writer (a,mempty)
(Writer (a,w)) >>= f = let Writer (b,w') = f a in Writer (b, mappend w w')
tell :: Monoid w => w -> Writer w ()
tell w = Writer ((), w)
listen :: Monoid w => a -> Writer w a
listen a = Writer (a, mempty)
--pass :: Monoid w => Writer (w -> w) a -> a
ccmBody :: Char -> Writer Integer Char
ccmBody c = do { tell 1 ; return c }
ccm :: String -> Writer Integer String
ccm = mapM ccmBody
lcmBody :: Char -> Writer Integer Char
lcmBody c = do { tell (test (c == '\n')) ; return c }
lcm :: String -> Writer Integer String
lcm = mapM lcmBody
wcmBody :: Char -> State (Integer,Bool) Char
wcmBody c = let s = not (isSpace c) in do
(n,w) <- get
put (n + test (not w && s),s)
return c
wcm :: String -> State (Integer,Bool) String
wcm = mapM wcmBody
-- clwcm = ccm • lcm • wcm
-- clwcm = mapM (ccmBody • lcmBody • wcmBody)
qumBody :: Char -> Reader Bool Bool
qumBody c = do { b <- ask ; return (if b then (c == 'q') else (c == 'u')) }
qum :: String -> Reader Bool [Bool]
qum = mapM qumBody
class MonadTrans t where
lift :: Monad m => m a -> t m a
newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }
instance Monad m => Monad (StateT s m) where
return a = StateT $ \s -> return (a,s)
(StateT st) >>= f = StateT $ \s -> do
(a,s) <- st s
let (StateT st') = f a
(a,s') <- st' s
return (a,s')
instance Monad m => Functor (StateT s m) where
fmap f (StateT st) = StateT $ \s -> do
(a,s') <- st s
return (f a,s')
instance Monad m => Applicative (StateT s m) where
pure a = StateT $ \s -> return (a,s)
(StateT f) <*> (StateT a) = StateT $ \s -> do
(f,s') <- f s
(a,s'') <- a s'
return (f a,s'')
instance MonadTrans (StateT s) where
lift :: Monad m => m a -> StateT s m a
lift ma = StateT $ \s -> do
a <- ma
return (a,s)
class Monad m => MonadState s m | m -> s where
getT :: m s
putT :: s -> m ()
instance MonadState s (State s) where
getT = State $ \s -> (s,s)
putT s = State $ \_ -> ((),s)
instance Monad m => MonadState s (StateT s m) where
getT = StateT $ \s -> return (s,s)
putT s = StateT $ \_ -> return ((),s)
(‡) :: (Monad m, MonadTrans t, Monad (t m)) => (b -> t m c) -> (a -> m b) -> (a -> t m c)
p1 ‡ p2 = p1 <<*>> (lift . p2)
(€) :: (Monad m, MonadTrans t, Monad (t m)) => (b -> m c) -> (a -> t m b) -> (a -> t m c)
p1 € p2 = (lift . p1) <<*>> p2
-- wcmBody' :: MonadState (Integer, Bool) m => Char -> m Char
-- wcmBody' c = let s = not (isSpace c) in do
-- (n,w) <- get
-- put (n + test (not w && s),s)
-- return c
-- quwcm :: String -> StateT (Integer,Bool) (Reader Bool) [Bool]
-- quwcm = mapM qumBody € mapM wcmBody'
main :: IO ()
main = do
let t = Bin (Leaf 1) (Leaf 2)
let x = loop (\a -> a + 2) t
let (t,s) = (runState x) 1
putStrLn (show t)
putStrLn (show s)
return ()
| eulerfx/learnfp | essence_iterator.hs | mit | 14,745 | 40 | 19 | 3,636 | 7,154 | 3,697 | 3,457 | -1 | -1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module TwitterMarkov.Tests.MarkovModel
(tests) where
import Test.Tasty
import Test.Tasty.QuickCheck as QC
import TwitterMarkov.MarkovModel
import qualified Data.Map as Map
import Data.Monoid (Sum(..))
import qualified Data.List.NonEmpty as NE
import Control.Monad.State
import System.Random
tests = testGroup "MarkovModel" [monoidProps, randomProps, modelProps]
monoidProps = testGroup "Markov model forms a monoid"
[ QC.testProperty "empty model is neutral left" $
\(model :: MarkovModel String) -> emptyModel `mappend` model == model
, QC.testProperty "empty model is neutral right" $
\(model :: MarkovModel String) -> model `mappend` emptyModel == model
, QC.testProperty "mappend is associative" $
\(model1 :: MarkovModel String) model2 model3 ->
(model1 `mappend` model2) `mappend` model3 == model1 `mappend` (model2 `mappend` model3)
]
modelProps = testGroup "Markov model properties"
[ QC.testProperty "Markov transition weights sum" $
\(startState :: String) (endState :: String) ->
let transition = singletonModel startState endState
sumModel = transition `mappend` transition
lookedUp = lookupTransitions startState sumModel in
length lookedUp == 1 &&
fst (head lookedUp) == (Sum 2) &&
snd (head lookedUp) == endState
, QC.testProperty "Singleton model always takes single transition" $
\(start :: String) (end :: String) (seed :: Int) ->
let model = singletonModel start end
r = generateRandom model
result = evalState r (mkStdGen seed) in
(take 2 result) == [start, end]
]
toWeights :: NonEmptyList (Positive Int, String) -> NE.NonEmpty (Sum Int, String)
toWeights (NonEmpty l) = NE.fromList $ fmap toWeightTup l
where toWeightTup (Positive i, s) = (Sum i, s)
randomProps = testGroup "Randomness properties"
[ QC.testProperty "Weight zero is never chosen" $
\(randWeights :: NonEmptyList (Positive Int, String)) (seed :: Int) ->
let weights = (Sum 0, "never chosen") NE.<| (toWeights randWeights)
r = weightedRandom weights
result = evalState r (mkStdGen seed) in
result /= "never chosen"
, QC.testProperty "Weight one is always chosen if other weights are 0." $
\(randStrings :: [String]) (seed :: Int) ->
let weights = NE.fromList $ (Sum 1, "always chosen") : fmap ((,) (Sum 0)) randStrings
r = weightedRandom weights
result = evalState r (mkStdGen seed) in
result == "always chosen"
, QC.testProperty "Single option with positive weight is always chosen" $
\(weight :: Positive Int) (randString :: String) (seed :: Int) ->
let weights = NE.fromList [(Sum (getPositive weight), randString)]
r = weightedRandom weights
result = evalState r (mkStdGen seed) in
result == randString
]
instance (Ord k, Arbitrary k, Arbitrary v) => Arbitrary (MonoidalValueMap k v) where
arbitrary = do
pairs <- listOf arbitrary
return $ MonoidalValueMap (Map.fromList pairs)
instance (Arbitrary a) => Arbitrary (NE.NonEmpty a) where
arbitrary = do
xs <- listOf1 arbitrary
return $ NE.fromList xs
instance (Arbitrary i) => Arbitrary (Sum i) where
arbitrary = Sum <$> arbitrary
| beala/twitter-markov | tests/TwitterMarkov/Tests/MarkovModel.hs | mit | 3,348 | 1 | 18 | 742 | 1,048 | 555 | 493 | 68 | 1 |
-- | The problem described by Bertsekas p. 210.
module Algorithms.MDP.Examples.Ex_3_2 where
import Algorithms.MDP.Examples.Ex_3_1 hiding (mdp)
import Algorithms.MDP
-- | The MDP representing the problem.
mdp :: MDP State Control Double
mdp = mkUndiscountedMDP states controls transition costs (\_ -> controls)
| prsteele/mdp | src/Algorithms/MDP/Examples/Ex_3_2.hs | mit | 313 | 0 | 7 | 44 | 64 | 39 | 25 | 5 | 1 |
--------------------------------------------------------------------
-- |
-- Copyright : (c) 2015 Smelkov Ilya
-- License : MIT
-- Maintainer: Smelkov Ilya <triplepointfive@gmail.com>
-- Stability : experimental
-- Portability: non-portable
--
-- This step adjusts the output face winding order to be CW.
-- The default face winding order is counter clockwise (CCW).
--
--------------------------------------------------------------------
module Codec.Soten.PostProcess.FlipWindingOrder (
apply
) where
import Control.Lens ((%~))
import qualified Data.Vector as V
import Codec.Soten.Scene
import Codec.Soten.Scene.Mesh
-- | Applies the post processing step on the given imported data.
apply :: Scene -> Scene
apply = sceneMeshes %~ V.map flipMesh
-- | Converts a single mesh.
flipMesh :: Mesh -> Mesh
flipMesh = meshFaces %~ V.map (faceIndices %~ V.reverse)
| triplepointfive/soten | src/Codec/Soten/PostProcess/FlipWindingOrder.hs | mit | 902 | 0 | 9 | 155 | 115 | 75 | 40 | 10 | 1 |
module Main where
import Data.Char (toLower)
import Data.Maybe (catMaybes, isNothing)
import Parser
data Register
= RegA
| RegB
| RegC
| RegD
deriving Show
data Target
= ToRegister Register
| ToValue Int
deriving Show
data Command
= Cpy Target Register
| Inc Register
| Dec Register
| Jnz Target Int
deriving Show
type Programm = [Command]
data CmdPointer =
CmdPointer { prev :: [Command]
, current :: Command
, next :: [Command]
} deriving Show
data CPU =
CPU { regA :: Int
, regB :: Int
, regC :: Int
, regD :: Int
, pointer :: Maybe CmdPointer
} deriving Show
initialize :: Programm -> CPU
initialize (l:ls) = CPU 0 0 0 0 (Just pt)
where pt = CmdPointer [] l ls
run :: CPU -> CPU
run cpu
| halting cpu = cpu
| otherwise =
run (step cpu)
step :: CPU -> CPU
step cpu =
case curCommand cpu of
Just (Cpy t r) -> copy t r cpu
Just (Inc r) -> increase r cpu
Just (Dec r) -> decrease r cpu
Just (Jnz t i) -> jumpNotZero t i cpu
_ -> cpu
halting :: CPU -> Bool
halting cpu = isNothing (pointer cpu)
curCommand :: CPU -> Maybe Command
curCommand cpu =
case pointer cpu of
Just (CmdPointer _ current _) ->
Just current
_ -> Nothing
copy :: Target -> Register -> CPU -> CPU
copy (ToValue v) RegA cpu =
moveNext $ cpu { regA = v }
copy (ToValue v) RegB cpu =
moveNext $ cpu { regB = v }
copy (ToValue v) RegC cpu =
moveNext $ cpu { regC = v }
copy (ToValue v) RegD cpu =
moveNext $ cpu { regD = v }
copy (ToRegister r) RegA cpu =
moveNext $ cpu { regA = getRegister r cpu }
copy (ToRegister r) RegB cpu =
moveNext $ cpu { regB = getRegister r cpu }
copy (ToRegister r) RegC cpu =
moveNext $ cpu { regC = getRegister r cpu }
copy (ToRegister r) RegD cpu =
moveNext $ cpu { regD = getRegister r cpu }
increase :: Register -> CPU -> CPU
increase reg cpu =
let v = getRegister reg cpu
in copy (ToValue $ v+1) reg cpu
decrease :: Register -> CPU -> CPU
decrease reg cpu =
let v = getRegister reg cpu
in copy (ToValue $ v-1) reg cpu
jumpNotZero :: Target -> Int -> CPU -> CPU
jumpNotZero (ToRegister reg) delta cpu =
let v = getRegister reg cpu
in jumpNotZero (ToValue v) delta cpu
jumpNotZero (ToValue v) delta cpu =
if v /= 0
then cpu { pointer = movePointer delta (pointer cpu) }
else moveNext cpu
moveNext :: CPU -> CPU
moveNext cpu =
cpu { pointer = movePointer 1 (pointer cpu) }
movePointer :: Int -> Maybe CmdPointer -> Maybe CmdPointer
movePointer _ Nothing = Nothing
movePointer 0 (Just pt) = Just pt
movePointer n (Just pt)
| n > 0 =
case pt of
CmdPointer prs c (nx:nxs) ->
let pt' = CmdPointer (c:prs) nx nxs
in movePointer (n-1) (Just pt')
_ -> Nothing
| n < 0 =
case pt of
CmdPointer (pr:prs) c nxs ->
let pt' = CmdPointer prs pr (c:nxs)
in movePointer (n+1) (Just pt')
_ -> Nothing
getRegister :: Register -> CPU -> Int
getRegister RegA = regA
getRegister RegB = regB
getRegister RegC = regC
getRegister RegD = regD
parseCmd :: Parser Command
parseCmd =
parseEither
(parseEither parseCpy parseJnz)
(parseEither parseInc parseDec)
where
parseCpy = do
parseString "cpy"
f <- parseTarget
t <- parseRegister
return $ Cpy f t
parseJnz = do
parseString "jnz"
f <- parseTarget
i <- parseInt
return $ Jnz f i
parseInc = do
parseString "inc"
f <- parseRegister
return $ Inc f
parseDec = do
parseString "dec"
f <- parseRegister
return $ Dec f
parseTarget :: Parser Target
parseTarget =
parseEither
(ToRegister <$> parseRegister)
(ToValue <$> parseInt)
parseRegister :: Parser Register
parseRegister = do
ignoreWhiteSpace
c <- parseAlpha
case toLower c of
'a' -> pure RegA
'b' -> pure RegB
'c' -> pure RegC
'd' -> pure RegD
_ -> failParse
input :: IO String
input = readFile "input.txt"
inputLines :: IO [String]
inputLines = lines <$> input
programm :: IO Programm
programm =
catMaybes . fmap (eval parseCmd) <$> inputLines
inputCPU :: IO CPU
inputCPU = initialize <$> programm
programm2 :: IO Programm
programm2 =
(Cpy (ToValue 1) RegC :) .
catMaybes . fmap (eval parseCmd) <$> inputLines
inputCPU2 :: IO CPU
inputCPU2 = initialize <$> programm2
main :: IO ()
main = do
p1 <- inputCPU
p2 <- inputCPU2
putStrLn $ "part 1: " ++ show (eval p1)
putStrLn $ "part 2: " ++ show (eval p2)
putStrLn "all done"
where
eval p = regA $ run p
testProgramm :: Programm
testProgramm =
[ Cpy (ToValue 41) RegA
, Inc RegA
, Inc RegA
, Dec RegA
, Jnz (ToRegister RegA) 2
, Dec RegA
]
| CarstenKoenig/AdventOfCode2016 | Day12/Main.hs | mit | 4,749 | 0 | 15 | 1,321 | 1,884 | 949 | 935 | 183 | 5 |
{-|
Module : Day7
Description : <http://adventofcode.com/2016/day/7 Day 7: Internet Protocol Version 7>
-}
{-# OPTIONS_HADDOCK ignore-exports #-}
module Day7 (main) where
import Common (readDataFile)
import Control.Monad (guard, replicateM)
import Data.Char (isAlphaNum)
import Data.Set (empty, insert, member)
import System.IO.Unsafe (unsafePerformIO)
import Text.ParserCombinators.ReadP (ReadP, (<++), between, char, eof, look, many, munch, readP_to_S, satisfy)
input :: [String]
input = lines $ unsafePerformIO $ readDataFile "day7.txt"
abba :: ReadP Bool
abba = (<* munch isAlphaNum) $ (<++ return False) $ True <$ do
many $ satisfy isAlphaNum
a:b:c:d:_ <- replicateM 4 $ satisfy isAlphaNum
guard $ a /= b && b == c && a == d
tls :: ReadP Bool
tls = tls' False where
tls' k = do
super <- abba
let k' = k || super
(<++ (k' <$ eof)) $ do
hyper <- char '[' `between` char ']' $ abba
if hyper then return False else tls' k'
ssl :: ReadP Bool
ssl = ssl' empty empty where
ssl' j k = (<++ (char '[' <++ char ']' >> ssl' k j) <++ (False <$ eof)) $ do
a <- satisfy isAlphaNum
(<++ ssl' j k) $ do
b:c:_ <- look
guard $ isAlphaNum b && a /= b && a == c
if member (b, a) j then return True else ssl' j $ insert (a, b) k
matches :: ReadP Bool -> String -> Bool
matches p = any fst . readP_to_S p
main :: IO ()
main = do
print $ length $ filter (matches tls) input
print $ length $ filter (matches ssl) input
| ephemient/aoc2016 | src/Day7.hs | mit | 1,540 | 0 | 18 | 399 | 620 | 321 | 299 | 37 | 2 |
{-# LANGUAGE RecordWildCards #-}
import Data.Foldable (for_)
import Test.Hspec (Spec, describe, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)
import Data.String (fromString)
import TwelveDays (recite)
main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs
specs :: Spec
specs = describe "responseFor" $ for_ cases test
where
test Case{..} = it description assertion
where
assertion = recite start stop `shouldBe` fromString <$> expected
data Case = Case { description :: String
, start :: Int
, stop :: Int
, expected :: [String]
}
cases :: [Case]
cases = [ Case { description = "first day a partridge in a pear tree"
, start = 1
, stop = 1
, expected = [
"On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree."
]
}
, Case { description = "second day two turtle doves"
, start = 2
, stop = 2
, expected = [
"On the second day of Christmas my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "third day three french hens"
, start = 3
, stop = 3
, expected = [
"On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "fourth day four calling birds"
, start = 4
, stop = 4
, expected = [
"On the fourth day of Christmas my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "fifth day five gold rings"
, start = 5
, stop = 5
, expected = [
"On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "sixth day six geese-a-laying"
, start = 6
, stop = 6
, expected = [
"On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "seventh day seven swans-a-swimming"
, start = 7
, stop = 7
, expected = [
"On the seventh day of Christmas my true love gave to me: seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "eighth day eight maids-a-milking"
, start = 8
, stop = 8
, expected = [
"On the eighth day of Christmas my true love gave to me: eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "ninth day nine ladies dancing"
, start = 9
, stop = 9
, expected = [
"On the ninth day of Christmas my true love gave to me: nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "tenth day ten lords-a-leaping"
, start = 10
, stop = 10
, expected = [
"On the tenth day of Christmas my true love gave to me: ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "eleventh day eleven pipers piping"
, start = 11
, stop = 11
, expected = [
"On the eleventh day of Christmas my true love gave to me: eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "twelfth day twelve drummers drumming"
, start = 12
, stop = 12
, expected = [
"On the twelfth day of Christmas my true love gave to me: twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "recites first three verses of the song"
, start = 1
, stop = 3
, expected = [
"On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree."
, "On the second day of Christmas my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree."
, "On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "recites three verses from the middle of the song"
, start = 4
, stop = 6
, expected = [
"On the fourth day of Christmas my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
, Case { description = "recites the whole song"
, start = 1
, stop = 12
, expected = [
"On the first day of Christmas my true love gave to me: a Partridge in a Pear Tree."
, "On the second day of Christmas my true love gave to me: two Turtle Doves, and a Partridge in a Pear Tree."
, "On the third day of Christmas my true love gave to me: three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the fourth day of Christmas my true love gave to me: four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the fifth day of Christmas my true love gave to me: five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the sixth day of Christmas my true love gave to me: six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the seventh day of Christmas my true love gave to me: seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the eighth day of Christmas my true love gave to me: eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the ninth day of Christmas my true love gave to me: nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the tenth day of Christmas my true love gave to me: ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the eleventh day of Christmas my true love gave to me: eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
, "On the twelfth day of Christmas my true love gave to me: twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree."
]
}
]
-- 24d0ebe44cfefb718a504734862ebd2f1b4df7bb
| exercism/xhaskell | exercises/practice/twelve-days/test/Tests.hs | mit | 9,737 | 1 | 9 | 3,386 | 750 | 468 | 282 | 107 | 1 |
{-# LANGUAGE BangPatterns #-}
module Statistics.SGT.Observations
( fromFile
)
where
import qualified Data.ByteString.Lazy.Char8 as L
import qualified Data.Vector as V
import Statistics.SGT.Types
-- Fill new vector from file containing [(Int,Int)].
fromFile :: FilePath -> IO (V.Vector Row)
fromFile fn = do
s <- L.readFile fn
return $ parse s
parse :: L.ByteString -> V.Vector Row
parse = V.unfoldr nextRow
-- Bang patterns: ensure strict accumulation of state in parsing.
nextRow :: L.ByteString -> Maybe (Row, L.ByteString)
nextRow (!s) = do
(!r, !t) <- nextInt s
(!n, !t') <- nextInt t
Just (Row r n, t')
nextInt :: L.ByteString -> Maybe (Int, L.ByteString)
nextInt (!s) = do
(!i, !t) <- L.readInt $ L.dropWhile isWhite s
Just (i, t)
where isWhite c = c `elem` " \t\n"
| marklar/Statistics.SGT | Statistics/SGT/Observations.hs | mit | 824 | 0 | 10 | 177 | 292 | 153 | 139 | 22 | 1 |
module Y2016.M12.D12.Solution where
import Control.Monad (guard)
{--
Today's Haskell exercise is from the Mensa Genuis Quiz-a-Day book. And I quote:
"Aha," said the math professor to her husband, "it's a very simple problem, but
I see that our two sons have now reached interesting ages. The product of their
ages is six times the amount you get if you add their ages. On the other hand,
if you add the square of each age, the total of the two will be 325." How old
were their boys?
Okay, solve that. ... How?
Question: do you have conversations like this around the dinner table, ...
like I do?
Solution:
One way to look at this problem is that it is a 'spreadsheet problem.'
1. What are all the integral values of y given 325-x*x?
(first of all, we know, therefore, that x*x is less than 325, so what is the
range of x?)
--}
rangex :: [Int]
rangex = takeWhile (\x -> x * x <= 325) [1..]
{-- we also assume x is born, so that's good.
*Y2016.M12.D12.Solution> rangex ~> [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
Okay, so now we have x nailed, we also assume, weirdly enough, that x and y
are integral ... this presupposes that x and y are born on the same day of the
year, but we will accept that and leave aside the inconsistency of the problem
statement, because the problem was written in this imprecise language, English,
and not in 'Math', so we must forgive it this laxity.
So, then, what are the possible integral values of x and y, given that
x*x + y*y = 325
Well, we know the range of x. Let's use that as the starting point.
--}
possibleIntegralAges :: [(Int, Int)]
possibleIntegralAges = map fromIntegral rangex >>= \x ->
let y = sqrt (325 - x*x) in
guard (floor (y * 1000) == floor y * 1000) >> -- imprecise, but close enough
return (floor x, floor y)
-- *Y2016.M12.D12.Solution> possibleIntegralAges ~> [(1,18),(6,17),(10,15),(15,10),(17,6),(18,1)]
-- These are the values we work with the first part of the equation.
productSum :: [(Int, Int)] -> [(Int, Int)]
productSum = filter (\(x,y) -> x*y == 6 * (x + y))
twoBirthdayBoyz :: [(Int, Int)]
twoBirthdayBoyz = productSum possibleIntegralAges
-- *Y2016.M12.D12.Solution> twoBirthdayBoyz ~> [(10,15),(15,10)]
-- Their boys are 15 and 10 years old.
| geophf/1HaskellADay | exercises/HAD/Y2016/M12/D12/Solution.hs | mit | 2,250 | 0 | 16 | 419 | 256 | 146 | 110 | 13 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Test.HUnit
import qualified Data.Text as ST
import qualified Data.Text.Lazy as LT
import Data.Binary
import Data.Tree -- TODO: rm when debugged
import TestFileUtils
import NewickParser
import FastA
import Alignment
import Classifier
import MlgscTypes
import Output
fastaInput1 = unlines [
">ID0 Aeromonas",
"ACGTACGT",
">ID1 Aeromonas",
"ACGTACGT",
">ID3 Aeromonas",
"ACGTACGT",
">ID4 Aeromonas",
"ACGTACGT",
">ID5 Aeromonas",
"ACGTACGT",
">ID6 Bacillus",
"BCGTACGT",
">ID7 Bacillus",
"BCGTACGT",
">ID8 Bacillus",
"BCGTACGT",
">ID9 Clostridium",
"CCGTACGT",
">ID10 Clostridium",
"CCGTACGT",
">ID11 Clostridium",
"CCGTACGT",
">ID12 Clostridium",
"CCGTACGT",
">ID13 Geobacillus",
"GCGTACGT",
">ID14 Geobacillus",
"GCGTACGT",
">ID15 Geobacillus",
"GCGTACGT"
]
smallprob = 0.0001
scale = 1000
newick1 = "(Aeromonas,((Geobacillus,Bacillus)Bacillaceae,Clostridium)Firmicutes);"
(Right tree1) = parseNewickTree newick1
fastaRecs1 = fastATextToRecords $ LT.pack fastaInput1
aln1 = fastARecordsToAln fastaRecs1
map1 = alnToAlnMap aln1
q1 = ST.pack "ACGTACGT"
clssfr1 = buildClassifier DNA smallprob scale map1 tree1
-- TODO: should use extended crumbs, and not call these functions directly.
-- Now score sequences according to the classifier, e.g.
trail1 = classifySequence clssfr1 1 "ACGTACGT"
trail2 = classifySequence clssfr1 1 "CCGTACGT"
trail3 = classifySequence clssfr1 1 "CCGTACGG"
score1 = bestScore $ last trail1
score2 = bestScore $ last trail2
score3 = bestScore $ last trail3
taxon1 = otuName $ last trail1
taxon2 = otuName $ last trail2
taxon3 = otuName $ last trail3
test01 = "clssfr1 ACGTACGT score" ~: score1 ~?= 0
test02 = "clssfr1 CCGTACGT score" ~: score2 ~?= 0
test03 = "clssfr1 CCGTACGG score" ~: score3 ~?= (-4000)
test11 = "clssfr1 ACGTACGT OTU" ~: taxon1 ~?= "Aeromonas"
test12 = "clssfr1 CCGTACGT OTU" ~: taxon2 ~?= "Clostridium"
test13 = "clssfr1 CCGTACGG OTU" ~: taxon3 ~?= "Clostridium"
-- Check that we can save and load a classifier in binary form
test21 = TestCase (do
removeIfExists "clssfr1.bcls"
encodeFile "clssfr1.bcls" clssfr1
clssfr2 <- decodeFile "clssfr1.bcls"
assertEqual "store-read" clssfr1 clssfr2
let trail1 = classifySequence clssfr2 1 "ACGTACGT"
let trail2 = classifySequence clssfr2 1 "CCGTACGT"
let trail3 = classifySequence clssfr2 1 "CCGTACGG"
(bestScore $ last trail1) @?= 0
(bestScore $ last trail2) @?= 0
(bestScore $ last trail3) @?= (-4000)
(otuName $ last trail1) @?= "Aeromonas"
(otuName $ last trail2) @?= "Clostridium"
(otuName $ last trail3) @?= "Clostridium"
)
-- TODO: test multiple-branch (=recovering) classifying function, first steps go
-- like this (GHCi):
-- let pred = classifySequenceMulti clssfr1 2 "ACGTACGT"
-- map (ST.intercalate "; " . tail) pred
tests = TestList [
TestLabel "nuc score" test01
, TestLabel "nuc score" test02
, TestLabel "nuc score" test03
, TestLabel "nuc score" test11
, TestLabel "nuc score" test12
, TestLabel "nuc score" test13
, TestLabel "nuc score" test21
]
main = do
runTestTT tests
| tjunier/mlgsc | test/TestClassifier.hs | mit | 3,373 | 18 | 12 | 774 | 764 | 380 | 384 | 92 | 1 |
module Ch21.HttpStuff where
import Data.ByteString.Lazy hiding (map)
import Network.Wreq
urls :: [String]
urls =
[ "http://httpbin.org/ip"
, "http://httpbin.org/bytes/5"
, "https://parkinsons-and-me.herokuapp.com/api/quotes-services-weightings"
]
mappingGet :: [IO (Response ByteString)]
mappingGet = map get urls
traversedUrls :: IO [Response ByteString]
traversedUrls = traverse get urls
| andrewMacmurray/haskell-book-solutions | src/ch21/HttpStuff.hs | mit | 402 | 0 | 8 | 53 | 96 | 55 | 41 | 12 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{- |
"Aabb" is "Axis-aligned bounding box".
The "broadphase" of collision detection is a conservative estimate of which bodies may be in contact.
-}
module Physics.Broadphase.Aabb where
import GHC.Generics (Generic)
import GHC.Prim (Double#, (+##), (-##), (<##),
(>##))
import GHC.Types (Double (D#), isTrue#)
import Control.Monad.ST
import Control.DeepSeq
import Control.Lens (itoListOf, (^.))
import Data.Array (elems)
import Data.Maybe
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Unboxed.Mutable as MV
import Data.Vector.Unboxed.Deriving
import qualified Physics.Constraint as C
import Physics.Contact
import Physics.Contact.Circle
import Physics.Contact.ConvexHull
import Physics.Linear
import Physics.World
import qualified Utils.EmptiesVector as E
import Utils.Descending
-- TODO: explore rewrite rules or other alternatives to manually using primops
-- | An interval, bounded above and below
data Bounds = Bounds { _bmin :: Double# -- ^ lower bound
, _bmax :: Double# -- ^ upper bound
} deriving (Eq, Generic)
instance NFData Bounds where
rnf (Bounds _ _) = ()
derivingUnbox "Bounds"
[t| Bounds -> (Double, Double) |]
[| \Bounds{..} -> (D# _bmin, D# _bmax) |]
[| \(D# bmin', D# bmax') -> Bounds bmin' bmax' |]
-- | An axis-aligned bounding box (AABB)
data Aabb = Aabb { _aabbx :: {-# UNPACK #-} !Bounds -- ^ bounds on x axis
, _aabby :: {-# UNPACK #-} !Bounds -- ^ bounds on y axis
} deriving (Eq, Generic, NFData)
derivingUnbox "Aabb"
[t| Aabb -> (Bounds, Bounds) |]
[| \Aabb{..} -> (_aabbx, _aabby) |]
[| uncurry Aabb |]
instance Show Aabb where
show (Aabb (Bounds x0 x1) (Bounds y0 y1)) =
"Aabb " ++ show (D# x0, D# x1) ++ " " ++ show (D# y0, D# y1)
-- | Do a pair of intervals overlap?
boundsOverlap :: Bounds -> Bounds -> Bool
boundsOverlap (Bounds a b) (Bounds c d) =
not $ isTrue# (c >## b) || isTrue# (d <## a)
{-# INLINE boundsOverlap #-}
-- | Do a pair of AABBs overlap?
aabbCheck :: Aabb -> Aabb -> Bool
aabbCheck (Aabb xBounds yBounds) (Aabb xBounds' yBounds') =
boundsOverlap xBounds xBounds' && boundsOverlap yBounds yBounds'
{-# INLINE aabbCheck #-}
-- | Find the AABB for a convex polygon.
hullToAabb :: ConvexHull -> Aabb
hullToAabb hull = foldl1 mergeAabb aabbs
where aabbs = fmap toAabb_ . elems . _hullVertices $ hull
{-# INLINE hullToAabb #-}
circleToAabb :: Circle -> Aabb
circleToAabb (Circle (P2 (V2 x y)) (D# r)) =
Aabb (Bounds (x -## r) (x +## r)) (Bounds (y -## r) (y +## r))
toAabb :: Shape -> Aabb
toAabb (HullShape hull) = hullToAabb hull
toAabb (CircleShape circle) = circleToAabb circle
-- | Get the (degenerate) AABB for a single point.
toAabb_ :: P2 -> Aabb
toAabb_ (P2 (V2 a b))= Aabb (Bounds a a) (Bounds b b)
{-# INLINE toAabb_ #-}
-- | Find the AABB of a pair of AABBs.
mergeAabb :: Aabb -> Aabb -> Aabb
mergeAabb (Aabb ax ay) (Aabb bx by) =
Aabb (mergeRange ax bx) (mergeRange ay by)
{-# INLINE mergeAabb #-}
-- | Find the interval that contains a pair of intervals.
mergeRange :: Bounds -> Bounds -> Bounds
mergeRange (Bounds a b) (Bounds c d) = Bounds minx maxx
where minx = if isTrue# (a <## c) then a else c
maxx = if isTrue# (b >## d) then b else d
{-# INLINE mergeRange #-}
{- |
Find the AABB for each object in a world.
Build a vector of these AABBs, each identified by its key in the world.
Objects are ordered using the world's traversal order
-}
toAabbs :: World s label -> ST s (V.Vector (Int, Aabb))
toAabbs world@World {..} = V.unsafeFreeze =<< E.mapM f _wEmpties
where
f i = do
shape <- readShape world i
return (i, toAabb shape)
{-# INLINE toAabbs #-}
{- |
Given a world:
*Find the AABB for each object.
*Extract a tag from each object.
*Build a vector of these tagged AABBs, each identified by its key in the world.
Objects are ordered using the world's traversal order
-}
toTaggedAabbs :: (V.Unbox tag)
=> (Int -> ST s tag)
-> World s label
-> ST s (V.Vector (Int, Aabb, tag))
toTaggedAabbs toTag world@World {..} = V.unsafeFreeze =<< E.mapM f _wEmpties
where
f i = do
tag <- toTag i
shape <- readShape world i
return (i, toAabb shape, tag)
{-# INLINE toTaggedAabbs #-}
{- |
Called \"unordered\" because (x, y) is equivalent to (y, x)
Given an 'Int' n, find all choices of two different 'Int's [0, n - 1]
These pairs (x, y) are in decreasing order, where x is the most significant value and y is the least significant value.
-}
unorderedPairs :: Int -> [(Int, Int)]
unorderedPairs n
| n < 2 = []
| otherwise = f (n - 1) (n - 2)
where f 1 0 = [(1, 0)]
f x 0 = (x, 0) : f (x - 1) (x - 2)
f x y = (x, y) : f x (y - 1)
{-# INLINE f #-}
{-# INLINE unorderedPairs #-}
-- | Find pairs of objects with overlapping AABBs.
-- Note: Pairs of static objects are excluded.
-- These pairs are in descending order according to 'unorderedPairs', where \"ascending\" is the world's traversal order.
culledKeys :: World s label -> ST s (Descending (Int, Int))
culledKeys world = do
taggedAabbs <- toTaggedAabbs isStatic world
let ijs = unorderedPairs $ V.length taggedAabbs
-- NOTE: don't aabbCheck static objects, otherwise the sim explodes
f (i, j) =
if not (isStaticA && isStaticB) && aabbCheck a b
then Just (i', j')
else Nothing
where
(i', a, isStaticA) = taggedAabbs V.! i
(j', b, isStaticB) = taggedAabbs V.! j
return $ Descending . catMaybes $ fmap f ijs
where
isStatic i = (C.isStatic . C._physObjInvMass) <$> readPhysObj world i
{-# INLINE culledKeys #-}
| ublubu/shapes | shapes/src/Physics/Broadphase/Aabb.hs | mit | 6,304 | 0 | 14 | 1,659 | 1,565 | 859 | 706 | 117 | 3 |
{-
- Whidgle.CompositeMap
-
- Describes operations on the type representing the pathfinding knowledge of all heroes.
-}
module Whidgle.CompositeMap
( generateMaps
) where
import Control.Parallel.Strategies
import qualified Data.Map as M
import Whidgle.Pathfinding
import Whidgle.Types
-- Generates a RouteMap for every hero, caching its contents.
generateMaps :: Activity -> [Hero] -> CompositeMap
generateMaps act heroes = M.fromList $ parMap rpar makeRoute heroes
where
makeRoute h@(Hero {_heroId = hId, _heroPos = hPos}) =
(hId, mapFrom act h hPos)
| Zekka/whidgle | src/Whidgle/CompositeMap.hs | mit | 568 | 0 | 12 | 93 | 120 | 70 | 50 | 10 | 1 |
-- | This module provides some higher-level types and infrastructure to make it easier to use.
{-# LANGUAGE PatternGuards, ScopedTypeVariables, NoMonomorphismRestriction,FlexibleInstances, FlexibleContexts, RankNTypes, ScopedTypeVariables #-}
-- {-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleContexts #-}
module Text.ParserCombinators.UU.Utils (
-- * Single-char parsers
pCR,
pLF,
pLower,
pUpper,
pLetter,
pAscii,
pDigit,
pDigitAsNum,
pAnySym,
-- * Whitespace and comments (comments - not yet supported)
pSpaces, -- This should not be used very often. In general
-- you may want to use it to skip initial whitespace
-- at the start of all input, but after that you
-- should rely on Lexeme parsers to skip whitespace
-- as needed. (This is the same as the strategy used
-- by Parsec).
-- * Lexeme parsers (as opposed to 'Raw' parsers)
lexeme,
pDot,
pComma,
pDQuote,
pLParen,
pRParen,
pLBracket,
pRBracket,
pLBrace,
pRBrace,
pSymbol,
-- * Raw parsers for numbers
pNaturalRaw,
pIntegerRaw,
pDoubleRaw,
pDoubleStr,
-- * Lexeme parsers for numbers
pNatural,
pInteger,
pDouble,
pPercent,
-- * Parsers for Enums
pEnumRaw,
pEnum,
pEnumStrs,
-- * Parenthesized parsers
pParens,
pBraces,
pBrackets,
listParser,
tupleParser,
pTuple,
-- * Lexeme parsers for `Date`-s
pDay,
pDayMonthYear,
-- * Lexeme parser for quoted `String`-s
pParentheticalString,
pQuotedString,
-- * Read-compatability
parserReadsPrec,
-- * Basic facility for runninga parser, getting at most a single error message
execParser,
runParser
)
where
import Data.Char
import Data.List
import Data.Time
import Text.ParserCombinators.UU.Core
import Text.ParserCombinators.UU.BasicInstances
import Text.ParserCombinators.UU.Derived
import Text.Printf
import qualified Data.ListLike as LL
------------------------------------------------------------------------
-- Single Char parsers
pCR :: Parser Char
pCR = pSym '\r'
pLF :: Parser Char
pLF = pSym '\n'
pLower :: Parser Char
pLower = pRange ('a','z')
pUpper :: Parser Char
pUpper = pRange ('A','Z')
pLetter:: Parser Char
pLetter = pUpper <|> pLower
pAscii :: Parser Char
pAscii = pRange ('\000', '\254')
pDigit :: Parser Char
pDigit = pRange ('0','9')
pDigitAsNum :: Num a => Parser a
pDigitAsNum =
digit2Int <$> pDigit
where
digit2Int a = fromInteger $ toInteger $ ord a - ord '0'
pAnySym :: (IsLocationUpdatedBy loc Char, LL.ListLike state Char) => String -> P (Str Char state loc) Char
pAnySym = pAny pSym
-- * Dealing with Whitespace
pSpaces :: Parser String
pSpaces = pMunch (`elem` " \r\n\t") <?> "Whitespace"
-- | Lexeme Parsers skip trailing whitespace (this terminology comes from Parsec)
lexeme :: ParserTrafo a a
lexeme p = p <* pSpaces
pDot, pComma, pDQuote, pLParen, pRParen, pLBracket, pRBracket, pLBrace, pRBrace :: Parser Char
pDot = lexeme $ pSym '.'
pComma = lexeme $ pSym ','
pDQuote = lexeme $ pSym '"'
pLParen = lexeme $ pSym '('
pRParen = lexeme $ pSym ')'
pLBracket = lexeme $ pSym '['
pRBracket = lexeme $ pSym ']'
pLBrace = lexeme $ pSym '{'
pRBrace = lexeme $ pSym '}'
pSymbol :: (IsLocationUpdatedBy loc Char, LL.ListLike state Char) => String -> P (Str Char state loc) String
pSymbol = lexeme . pToken
-- * Parsers for Numbers
-- ** Raw (non lexeme) parsers
pNaturalRaw :: (Num a) => Parser a
pNaturalRaw = foldl (\a b -> a * 10 + b) 0 <$> pList1 pDigitAsNum <?> "Natural"
pIntegerRaw :: (Num a) => Parser a
pIntegerRaw = pSign <*> pNaturalRaw <?> "Integer"
pDoubleRaw :: (Read a) => Parser a
pDoubleRaw = read <$> pDoubleStr
pDoubleStr :: Parser [Char]
pDoubleStr = pOptSign <*> (pToken "Infinity" <|> pPlainDouble)
<?> "Double (eg -3.4e-5)"
where
pPlainDouble = (++) <$> ((++) <$> pList1 pDigit <*> (pFraction `opt` [])) <*> pExponent
pFraction = (:) <$> pSym '.' <*> pList1 pDigit
pExponent = ((:) <$> pAnySym "eE" <*> (pOptSign <*> pList1 pDigit)) `opt` []
pOptSign = ((('+':) <$ (pSym '+')) <|> (('-':) <$ (pSym '-'))) `opt` id
-- | NB - At present this is /not/ a lexeme parser, hence we don't
-- support @- 7.0@, @- 7@, @+ 7.0@ etc.
-- It's also currently private - ie local to this module.
pSign :: (Num a) => Parser (a -> a)
pSign = (id <$ (pSym '+')) <|> (negate <$ (pSym '-')) `opt` id
pPercentRaw ::Parser Double
pPercentRaw = (/ 100.0) . read <$> pDoubleStr <* pSym '%' <?> "Double%"
pPctOrDbl = pPercentRaw <|> pDoubleRaw
-- ** Lexeme Parsers for Numbers
pNatural :: Num a => Parser a
pNatural = lexeme pNaturalRaw
pInteger :: Num a => Parser a
pInteger = lexeme pIntegerRaw
pDouble :: Parser Double
pDouble = lexeme pDoubleRaw
pPercent :: Parser Double
pPercent = lexeme pPctOrDbl
-- * Parsers for Enums
pEnumRaw :: forall a . ((Enum a, Show a)=> Parser a)
pEnumRaw = foldr (\ c r -> c <$ pToken (show c) <|> r) pFail enumerated
<?> (printf "Enum (eg %s or ... %s)" (show (head enumerated)) (show (last enumerated)))
-- unless it is an empty data decl we will always have a head/last (even if the same)
-- if it is empty, you cannot use it anyhow...
where
enumerated :: [a]
enumerated = [toEnum 0..]
-- pToken :: Provides st s s => [s] -> P st [s]
-- pToken [] = pure []
-- pToken (a:as) = (:) <$> pSym a <*> pToken as
pEnum :: (Enum a, Show a) => Parser a
pEnum = lexeme pEnumRaw
pEnumStrs :: [String]-> Parser String
pEnumStrs xs = pAny (\t -> pSpaces *> pToken t <* pSpaces) xs <?> "enumerated value in " ++ show xs
-- * Parenthesized structures
pParens :: ParserTrafo a a
pParens p = pLParen *> p <* pRParen
pBraces :: ParserTrafo a a
pBraces p = pLBrace *> p <* pRBrace
pBrackets :: ParserTrafo a a
pBrackets p = pLBracket *> p <* pRBracket
-- * Lists and tuples
-- | eg [1,2,3]
listParser :: ParserTrafo a [a]
listParser = pBrackets . pListSep pComma
-- | eg (1,2,3)
tupleParser :: ParserTrafo a [a]
tupleParser = pParens . pListSep pComma
pTuple :: (IsLocationUpdatedBy loc Char, LL.ListLike state Char) => [P (Str Char state loc) a] -> P (Str Char state loc) [a]
pTuple [] = [] <$ pParens pSpaces
pTuple (p:ps) = pParens $ (:) <$> lexeme p <*> mapM ((pComma *>) . lexeme) ps
-- * Lexeme parsers for Dates
data Month = Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
deriving (Enum, Bounded, Eq, Show, Ord)
pDayMonthYear :: (Num d, Num y) => Parser (d, Int, y)
pDayMonthYear = lexeme $ (,,) <$> pDayNum <*> (pSym '-' *> pMonthNum) <*> (pSym '-' *> pYearNum)
where
pMonthNum = ((+1) . (fromEnum :: Month -> Int)) <$> pEnumRaw <?> "Month (eg Jan)"
pDayNum = pNaturalRaw <?> "Day (1-31)"
pYearNum = pNaturalRaw <?> "Year (eg 2019)"
pDay :: Parser Day
pDay = (\(d,m,y) -> fromGregorian y m d) <$> pDayMonthYear
-- * Quoted Strings
pParentheticalString :: Char -> Parser String
pParentheticalString d = lexeme $ pSym d *> pList pNonQuoteVChar <* pSym d
where
pNonQuoteVChar = pSatisfy (\c -> visibleChar c && c /= d)
(Insertion "Character in a string set off from main text by delimiter, e.g. double-quotes or comment token" 'y' 5)
-- visibleChar :: Char -> Bool
visibleChar c = '\032' <= c && c <= '\126'
pQuotedString :: Parser String
pQuotedString = pParentheticalString '"'
-- * Read-compatability
-- | Converts a UU Parser into a read-style one.
--
-- This is intended to facilitate migration from read-style
-- parsers to UU-based ones.
parserReadsPrec :: Parser a -> Int -> ReadS a
parserReadsPrec p _ s = [parse ((,) <$> p <*> pMunch (const True)) . createStr (0::Int) $ s]
-- * Running parsers straightforwardly
-- | The lower-level interface. Returns all errors.
execParser :: Parser a -> String -> (a, [Error LineColPos])
execParser p = parse_h ((,) <$> p <*> pEnd) . createStr (LineColPos 0 0 0)
-- | The higher-level interface. (Calls 'error' with a simplified error).
-- Runs the parser; if the complete input is accepted without problems return the
-- result else fail with reporting unconsumed tokens
runParser :: String -> Parser a -> String -> a
runParser inputName p s | (a,b) <- execParser p s =
if null b
then a
else error (printf "Failed parsing '%s' :\n%s\n" inputName (pruneError s b))
-- We do 'pruneError' above because otherwise you can end
-- up reporting huge correction streams, and that's
-- generally not helpful... but the pruning does discard info...
where -- | Produce a single simple, user-friendly error message
pruneError :: String -> [Error LineColPos] -> String
pruneError _ [] = ""
pruneError _ (DeletedAtEnd x : _) = printf "Unexpected '%s' at end." x
pruneError s (Inserted _ pos exp : _) = prettyError s exp pos
pruneError s (Deleted _ pos exp : _) = prettyError s exp pos
prettyError :: String -> [String] -> LineColPos -> String
prettyError s exp p@(LineColPos line c abs) = printf "Expected %s at %s :\n%s\n%s\n%s\n"
(show_expecting p exp)
(show p)
aboveString
inputFrag
belowString
where
s' = map (\c -> if c=='\n' || c=='\r' || c=='\t' then ' ' else c) s
aboveString = replicate 30 ' ' ++ "v"
belowString = replicate 30 ' ' ++ "^"
inputFrag = replicate (30 - c) ' ' ++ (take 71 $ drop (c - 30) s')
| sol/uu-parsinglib | src/Text/ParserCombinators/UU/Utils.hs | mit | 9,883 | 0 | 17 | 2,557 | 2,592 | 1,419 | 1,173 | 180 | 6 |
somme n = sum[1..n]
| Debaerdm/L3-MIAGE | Programmation Fonctionnel/TP/TP1/test.hs | mit | 20 | 0 | 6 | 4 | 17 | 8 | 9 | 1 | 1 |
-- Does loop_eachE work?
module T where
import Prelude ()
import Tests.KesterelBasis
-- c = unitA *** id >>> runE (bool2sig $ \r -> loopEachE r nothingE)
-- c = unitA *** id >>> runE (bool2sig $ \r -> loopE (abortE r haltE))
-- c = unitA >>> runE (signalE $ \r -> abortE r haltE)
c = unitA >>> runE (signalE $ \r -> loopE pauseE `abortE` r)
ok_netlist = runNL c
prop_correct = property (\xs -> simulate c xs == replicate (length xs) (false, ()))
test_constructive = isJust (isConstructive c)
| peteg/ADHOC | Tests/08_Kesterel/112_loopEach.hs | gpl-2.0 | 495 | 0 | 11 | 95 | 118 | 66 | 52 | 7 | 1 |
module Types.JSON where
import Web.Vorple
import Types.Entry
import Types.Request
import Types.Response
import Types.Session
import Types.Tag
import Types.User
deriveJSON (drop 2) ''Entry
deriveJSON (drop 2) ''EntryFilter
deriveJSON (drop 3) ''Request
deriveJSON id ''Error
deriveJSON (drop 4) ''Response
deriveJSON (drop 8) ''Session
deriveJSON (drop 2) ''Tag
deriveJSON (drop 3) ''UserProfile
| ktvoelker/todo | src/Types/JSON.hs | gpl-3.0 | 407 | 0 | 7 | 60 | 163 | 78 | 85 | -1 | -1 |
{-
The Delve Programming Language
Copyright 2009 John Morrice
Distributed under the terms of the GNU General Public License v3, or ( at your option ) any later version.
This file is part of Delve.
Delve is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Delve is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Delve. If not, see <http://www.gnu.org/licenses/>.
-}
module VarCore where
import Core
-- A simplified version of core where only simple expressions can be applied to functions
type VCore =
[ VStmt ]
type VExecCore =
[ VExecStmt ]
data VStmt =
VSetHere Symbol VExecStmt
| VSetLocal [ Symbol ] VExecStmt
| VSetObject [ Symbol ] VExecStmt
| VStandalone VCoreExpr
| VBegin VExecCore
| VCoreSpecial Symbol String
deriving Show
data VExecStmt =
VStmt VStmt
| VExecExpr VExecExpr
deriving Show
data VCoreExpr =
VApp VVar [ VVar ]
| VCoreMatch VVar VAlternatives
| VSimple VSimpleExpr
deriving Show
data VVar =
VLocalVar [ Symbol ]
| VObjVar [ Symbol ]
deriving Show
type VAlternatives =
[ VCoreAlternative ]
type VCoreAlternative =
( Symbol , VExecCore )
data VSimpleExpr =
VLit Lit
| VReserved Reserved
| VVar VVar
deriving Show
data VExecExpr =
VFunction [ Symbol ] VExecCore
| VMethod [ Symbol ] VExecCore
deriving Show
| elginer/Delve | src/VarCore.hs | gpl-3.0 | 1,833 | 0 | 7 | 461 | 217 | 133 | 84 | 40 | 0 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE UnicodeSyntax #-}
module Main where
import Brick.AttrMap
import Brick.Main
import Brick.Types
import Brick.Widgets.Border
import Brick.Widgets.Border.Style
import Brick.Widgets.Center
import Brick.Widgets.Core
import Brick.Widgets.GameBoard
import Control.Concurrent
import Control.Monad.Unicode
import Control.Monad.Writer
import Data.Default
import FRP.Sodium hiding (Event)
import Graphics.Vty
import qualified Graphics.Vty as Vty
import Prelude.Unicode
import Prelude.Unicode.SR
import Safe
import System.Random
------------
-- Types. --
------------
type Position = (Int, Int)
data AppEvent = VtyEvent Vty.Event
| BoardEvent BoardEvent
deriving (Show, Eq)
data AppState = AppState {
appWidget ∷ Widget,
appGameboard ∷ Behavior LoggedWidget,
appSendBoard ∷ BoardEvent → Reactive (),
appTicks ∷ Int,
appLog ∷ String
}
-----------------------------
-- Main loop and handlers. --
-----------------------------
main ∷ IO ()
main = do
(boardEvent, sendBoard) ← sync newEvent -- An event stream for
-- events sent to the
-- gameboard, and a means
-- to trigger such events.
eventChan ← newChan -- We are using customMain to be able to pump
-- our own events from a separate thread.
-- Events are pumped into eventChan either by
-- us or by Vty.
forkIO $ danceThread eventChan -- Pump «Dance» events into the
-- gameboard at regular intervals.
-- Assemble an initial gameboard state.
initialDancers ← replicateM 60 (randomCoord 1 80)
boardBehavior ← sync (gameBoard pos₀ initialDancers boardEvent)
let beginState = AppState (initialBoard initialDancers) boardBehavior
sendBoard 0 mempty
-- Dispatch.
customMain (mkVty def) eventChan demoApp beginState
return ()
where
initialBoard = fst ∘ runWriter ∘ boardWidget pos₀
randomCoord lo hi = do
x ← randomRIO (lo,hi)
y ← randomRIO (lo,hi)
return (x,y)
pos₀ = (0,0)
danceThread ∷ Chan AppEvent → IO ()
danceThread chan = forever $ do
δdance ← randomCoord (-1) 1
let event = BoardEvent (Dance δdance)
writeChan chan event
threadDelay (10↑5)
demoApp ∷ App AppState AppEvent
demoApp = App drawApp chooseCursor handleAppEvent initialEvent
mapAttrs liftVtyEvent
drawApp ∷ AppState → [Widget]
drawApp AppState{..} =
let debugString = show appTicks ⧺ " " ⧺
(unlines ∘ reverse ∘ lines) appLog
in [
vBox [
ui appWidget,
(debugFrame ∘ str) debugString
]
]
chooseCursor ∷ AppState → [CursorLocation] → Maybe CursorLocation
chooseCursor _ = headMay
handleAppEvent ∷ AppState → AppEvent → EventM (Next AppState)
handleAppEvent state@AppState{..} event
| event ∈ quitEvents = halt state
| otherwise = do
-- This only gets event related to player movements,
-- if any.
let boardMovement = convertEv event
traverse (lift ∘ lift ∘ sync ∘ appSendBoard) boardMovement
(koalaWidget, messages) ← fmap runWriter ∘ lift ∘ lift ∘
sync $ sample appGameboard
let nextDebug = show event ⧺ "\n" ⧺ messages
nextState = AppState koalaWidget appGameboard appSendBoard
(succ appTicks) nextDebug
continue nextState
where
convertEv (Key KUp) = Just $ Move ( 0, -1)
convertEv (Key KDown) = Just $ Move ( 0, 1)
convertEv (Key KLeft) = Just $ Move (-1, 0)
convertEv (Key KRight) = Just $ Move ( 1, 0)
convertEv (BoardEvent x) = Just x
convertEv _ = Nothing
quitEvents = [Key KEsc, Key (KChar 'q')]
initialEvent ∷ AppState → EventM AppState
initialEvent = return
mapAttrs ∷ AppState → AttrMap
mapAttrs _ = def
liftVtyEvent ∷ Vty.Event → AppEvent
liftVtyEvent = VtyEvent
----------------
-- UI frames. --
----------------
ui ∷ Widget → Widget
ui board = hBox [ helloFrame, boardFrame board ]
helloFrame ∷ Widget
helloFrame = bordered (borderWithLabel label contents)
where
label = txt "Your government informs you"
contents = center (txt "A bagel a day keeps the darkness at bay")
boardFrame ∷ Widget → Widget
boardFrame board = bordered (borderWithLabel label contents)
where
label = txt "Work 8h, Play 8h, Sleep 8h"
contents = center board
debugFrame ∷ Widget → Widget
debugFrame info = bordered (borderWithLabel label contents)
where
label = txt "Debug info"
contents = center info
bordered ∷ Widget → Widget
bordered = withBorderStyle unicodeRounded
------------------------
-- Keyboard patterns. --
------------------------
pattern Key k = VtyEvent (EvKey k [])
| eigengrau/haskell-sodium-vty | src/Main.hs | gpl-3.0 | 5,967 | 6 | 15 | 2,198 | 1,291 | 678 | 613 | 112 | 6 |
module Hadolint.Rule.DL3030 (rule) where
import Hadolint.Rule
import qualified Hadolint.Shell as Shell
import Language.Docker.Syntax
rule :: Rule Shell.ParsedShell
rule = simpleRule code severity message check
where
code = "DL3030"
severity = DLWarningC
message = "Use the -y switch to avoid manual input `yum install -y <package`"
check (Run (RunArgs args _)) = foldArguments (Shell.noCommands forgotYumYesOption) args
check _ = True
forgotYumYesOption cmd = isYumInstall cmd && not (hasYesOption cmd)
isYumInstall = Shell.cmdHasArgs "yum" ["install", "groupinstall", "localinstall"]
hasYesOption = Shell.hasAnyFlag ["y", "assumeyes"]
{-# INLINEABLE rule #-}
| lukasmartinelli/hadolint | src/Hadolint/Rule/DL3030.hs | gpl-3.0 | 698 | 0 | 11 | 122 | 177 | 97 | 80 | 14 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.SubAccounts.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Inserts a new subaccount.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.subaccounts.insert@.
module Network.Google.Resource.DFAReporting.SubAccounts.Insert
(
-- * REST Resource
SubAccountsInsertResource
-- * Creating a Request
, subAccountsInsert
, SubAccountsInsert
-- * Request Lenses
, saiProFileId
, saiPayload
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.subaccounts.insert@ method which the
-- 'SubAccountsInsert' request conforms to.
type SubAccountsInsertResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"subaccounts" :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] SubAccount :> Post '[JSON] SubAccount
-- | Inserts a new subaccount.
--
-- /See:/ 'subAccountsInsert' smart constructor.
data SubAccountsInsert = SubAccountsInsert'
{ _saiProFileId :: !(Textual Int64)
, _saiPayload :: !SubAccount
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'SubAccountsInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'saiProFileId'
--
-- * 'saiPayload'
subAccountsInsert
:: Int64 -- ^ 'saiProFileId'
-> SubAccount -- ^ 'saiPayload'
-> SubAccountsInsert
subAccountsInsert pSaiProFileId_ pSaiPayload_ =
SubAccountsInsert'
{ _saiProFileId = _Coerce # pSaiProFileId_
, _saiPayload = pSaiPayload_
}
-- | User profile ID associated with this request.
saiProFileId :: Lens' SubAccountsInsert Int64
saiProFileId
= lens _saiProFileId (\ s a -> s{_saiProFileId = a})
. _Coerce
-- | Multipart request metadata.
saiPayload :: Lens' SubAccountsInsert SubAccount
saiPayload
= lens _saiPayload (\ s a -> s{_saiPayload = a})
instance GoogleRequest SubAccountsInsert where
type Rs SubAccountsInsert = SubAccount
type Scopes SubAccountsInsert =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient SubAccountsInsert'{..}
= go _saiProFileId (Just AltJSON) _saiPayload
dFAReportingService
where go
= buildClient
(Proxy :: Proxy SubAccountsInsertResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/SubAccounts/Insert.hs | mpl-2.0 | 3,285 | 0 | 14 | 739 | 406 | 242 | 164 | 63 | 1 |
--
-- Minio Haskell SDK, (C) 2017 Minio, Inc.
--
-- 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 Network.Minio.Data.Crypto
(
hashSHA256
, hashSHA256FromSource
, hashMD5
, hashMD5FromSource
, hmacSHA256
, hmacSHA256RawBS
, digestToBS
, digestToBase16
) where
import Crypto.Hash (SHA256(..), MD5(..), hashWith, Digest)
import Crypto.Hash.Conduit (sinkHash)
import Crypto.MAC.HMAC (hmac, HMAC)
import Data.ByteArray (ByteArrayAccess, convert)
import Data.ByteArray.Encoding (convertToBase, Base(Base16))
import qualified Data.Conduit as C
import Lib.Prelude
hashSHA256 :: ByteString -> ByteString
hashSHA256 = digestToBase16 . hashWith SHA256
hashSHA256FromSource :: Monad m => C.Producer m ByteString -> m ByteString
hashSHA256FromSource src = do
digest <- src C.$$ sinkSHA256Hash
return $ digestToBase16 digest
where
-- To help with type inference
sinkSHA256Hash :: Monad m => C.Consumer ByteString m (Digest SHA256)
sinkSHA256Hash = sinkHash
hashMD5 :: ByteString -> ByteString
hashMD5 = digestToBase16 . hashWith MD5
hashMD5FromSource :: Monad m => C.Producer m ByteString -> m ByteString
hashMD5FromSource src = do
digest <- src C.$$ sinkMD5Hash
return $ digestToBase16 digest
where
-- To help with type inference
sinkMD5Hash :: Monad m => C.Consumer ByteString m (Digest MD5)
sinkMD5Hash = sinkHash
hmacSHA256 :: ByteString -> ByteString -> HMAC SHA256
hmacSHA256 message key = hmac key message
hmacSHA256RawBS :: ByteString -> ByteString -> ByteString
hmacSHA256RawBS message key = convert $ hmacSHA256 message key
digestToBS :: ByteArrayAccess a => a -> ByteString
digestToBS = convert
digestToBase16 :: ByteArrayAccess a => a -> ByteString
digestToBase16 = convertToBase Base16
| donatello/minio-hs | src/Network/Minio/Data/Crypto.hs | apache-2.0 | 2,332 | 0 | 10 | 447 | 479 | 265 | 214 | 41 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.Aeson as DA
import qualified Data.Text as DT
import qualified Network.HTTP.Types as NHT
import qualified Network.Wai as NW
import qualified Network.Wai.Application.Static as NWAS
import qualified Network.Wai.Handler.Warp as NWHW
data User = User { name :: DT.Text, email :: DT.Text }
deriving (Show, Read, Eq)
instance DA.ToJSON User where
toJSON x = DA.object [ "name" DA..= (name x), "email" DA..= (email x) ]
resource :: NHT.StdMethod -> DT.Text -> NW.Application
resource NHT.GET _uuid _req =
-- we are ignoring the uuid but you can see how you would use it
return $ NW.responseLBS NHT.statusOK headers json
where user = User { name = "Tim Dysinger", email = "tim@dysinger.net" }
json = DA.encode user
headers = [("Content-Type", "application/json")]
resource _ _ _ =
-- we only accept GET requests right now
return $ NW.responseLBS NHT.statusNotAllowed [("Accept", "GET")] ""
dispatch :: NW.Middleware
dispatch app req =
case path req of
-- handle the route /api/v1/resource/:uuid
("api":"v1":"resource":uuid:_) -> resource (method req) uuid req
-- otherwise pass the request to the next app
_ -> app req
where path :: NW.Request -> [DT.Text]
path req' = filter (\p -> p /= "") $ map DT.toLower $ NW.pathInfo req'
method :: NW.Request -> NHT.StdMethod
method req' = case NHT.parseMethod $ NW.requestMethod req' of
Right m -> m
Left _ -> NHT.GET
main :: IO ()
main = NWHW.run 8080 $
-- pass the request to dispatch
dispatch $
-- but fall through to serving static content if nothing else
NWAS.staticApp NWAS.defaultFileServerSettings
| dysinger/aeson-wai-example | Main.hs | apache-2.0 | 1,871 | 0 | 12 | 512 | 507 | 280 | 227 | 35 | 3 |
newtype Trace a = Trace ([String], a)
instance Functor Trace where
fmap k (Trace (msgs, x)) = Trace (msgs, (k x))
instance Applicative Trace where
(<*>) (Trace (msgs', k)) (Trace (msgs'', x)) = Trace (msgs' ++ msgs'', (k x))
pure x = Trace ([], x)
instance Monad Trace where
(>>=) (Trace (msgs, x)) k =
let Trace (new_msgs, y) = k x
in Trace (msgs ++ new_msgs, y)
return x = Trace ([], x)
put :: Show a => String -> a -> Trace ()
put msg v = Trace ([msg ++ " " ++ show v], ())
fact :: Integer -> Trace Integer
fact n = do
put "fact" n
if n == 0
then return 1
else do
m <- fact (n - 1)
return (n * m)
main = let Trace (lst, m) = fact 3
in do
print lst
print m | cbare/Etudes | haskell/trace.hs | apache-2.0 | 768 | 0 | 13 | 254 | 411 | 211 | 200 | 25 | 2 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
--------------------------------------------------------------------
---- |
---- Copyright : (c) Edward Kmett and Dan Doel 2013-2014
---- License : BSD2
---- Maintainer: Edward Kmett <ekmett@gmail.com>
---- Stability : experimental
---- Portability: non-portable (DeriveDataTypeable)
----
----------------------------------------------------------------------
module Ermine.Syntax.Class
( Class(Class)
, HasClass(..)
) where
import Bound
import Bound.Scope
import Control.Applicative
import Control.Lens
import Data.Bifoldable
import Data.Bitraversable
import Data.Map (Map)
import Data.Foldable
import Data.Traversable
import Data.Void
import Ermine.Syntax ((~>))
import Ermine.Syntax.Global
import Ermine.Syntax.Hint
import Ermine.Syntax.Kind as Kind
import Ermine.Syntax.Type as Type
import Ermine.Syntax.Term as Term
import GHC.Generics
data Class k t = Class
{ _kindArgs :: [Hint]
, _typeArgs :: [(Hint, Scope Int Kind k)]
, _context :: [Scope Int (TK k) t]
, _signatures :: Map Global (Type (Var Int k) (Var Int t))
, _defaults :: Map Global (Bodies (Annot Void t) Void)
}
deriving (Eq, Show, Generic)
makeClassy ''Class
instance Functor (Class k) where
fmap f (Class kh th cxt sigs defs) =
Class kh th (fmap f <$> cxt) (fmap (fmap f) <$> sigs) (bimap (fmap f) id <$> defs)
instance Foldable (Class k) where
foldMap = foldMapDefault
instance Traversable (Class k) where
traverse f (Class kh th cxt sigs defs) =
Class kh th <$> (traverse.traverse) f cxt
<*> (traverse.traverse.traverse) f sigs
<*> (traverse.flip bitraverse pure.traverse) f defs
instance Bifunctor Class where
bimap = bimapDefault
instance Bifoldable Class where
bifoldMap = bifoldMapDefault
instance Bitraversable Class where
bitraverse f g (Class kh th cxt sigs defs) =
Class kh <$> (traverse.traverse.traverse) f th
<*> traverse (bitraverseScope (traverse f) g) cxt
<*> traverse (bitraverse (traverse f) (traverse g)) sigs
<*> traverse (bitraverse (traverse g) pure) defs
instance Schematic (Class k t) k where
schema clazz =
Schema (clazz^.kindArgs)
(Scope . Prelude.foldr (~>) constraint $ unscope . snd <$> clazz^.typeArgs)
instance HasKindVars (Class k t) (Class k' t) k k' where
kindVars f = bitraverse f pure
| PipocaQuemada/ermine | src/Ermine/Syntax/Class.hs | bsd-2-clause | 2,608 | 0 | 14 | 564 | 765 | 415 | 350 | 62 | 0 |
{-
EEL -- Extensible Experimental Language
by Lukáš Kuklínek, 2013
-}
module Parser.Parser(runEel, runEelExt, initState, initStack, emitModule, semaCheck) where
import Sema.Term
import Sema.Error
import Sema.Infer
import Parser.State
import Parser.Core
import Parser.Dump
import Builtins.Eval
import Builtins.Types
import Backend.Emit
import qualified Data.Map as M
import qualified Text.Parsec as P
import qualified System.FilePath as Path
-- | initial symbol table filled w/ built-ins
initSymTab = builtInsTable
-- | Initial stack is empty
initStack = Stack []
-- | EEL parser initial state bootstrap
initState = case P.runParser addRuleP initState' "" "" of
Left _ -> error "Parser bootstrap failed"
Right ste -> ste
where
-- add rule ".eel" to parsec state and return the new state
addRuleP = addRule (Symbol ".eel") 1 eelRule >> getState
-- ".eel" rule definition --> skip whitespace, eel core call
eelRule = TComp mEps (biCall BIppcoreskip) (biCall BIppcoreterm)
-- builtin call helper
biCall = TFunc mEps (Symbol "") . FDBuiltIn
-- initial state without the ".eel" bootstrap
initState' = PState {
pSymTable = initSymTab,
pRules = M.empty,
pStack = initStack,
pPrimRules = (coreSkipParser, coreParser)
}
-- | Run parser with supplied initial state, extract semantic errors
runEel name ste nt = P.runParser eelp ste name
where eelp = invoke nt >> P.eof >> getState
-- | Run EEL parser guessing the starting nonterminal from the file extension
runEelExt name ste = runEel name ste (Symbol $ getNT name)
-- | Get non-terminal name from the file extension
getNT name = case Path.takeExtensions name of "" -> ".eel"; ext -> ext
-- | Check the final state for semantic errors, main presence etc.
-- and return either errors or a list of functions to compile
semaCheck mainNme ste = case checkTypes ste ++ checkMain ste mainNme of
[] -> Right (pSymTable ste)
xs -> Left $ ErrorSet xs
-- | check the main function for presence and type
checkMain _ste Nothing = []
checkMain ste (Just nme) = case M.lookup (Symbol nme) (pSymTable ste) of
Nothing -> mkErr SEMainMissing
Just (FDUser term) -> case termType term of
Left _er -> []
Right ty -> either (mkErr . SEMain) (const []) (inferUnify ty mainType)
_ -> error "checkMain: fatal error"
where mkErr = return . TracedError (Symbol nme) []
-- | Check type metadata annotations
checkTypes ste = concatMap fproc funcs
where
funcs = [ (sym, term) | (sym, FDUser term) <- M.toList (pSymTable ste) ]
fproc (sym, term) = [ TracedError sym tr err | (tr, err) <- withTrace [] tracer term ]
tracer tr term = case termType term of
Left err | nonTrivialError err -> [(tr, err)]
_ -> []
| iljakuklic/eel-proto | src/Parser/Parser.hs | bsd-3-clause | 2,831 | 0 | 14 | 642 | 748 | 396 | 352 | 47 | 4 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.OES.ByteCoordinates
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/OES/byte_coordinates.txt OES_byte_coordinates> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.OES.ByteCoordinates (
-- * Types
GLbyte,
-- * Enums
gl_BYTE,
-- * Functions
glMultiTexCoord1bOES,
glMultiTexCoord1bvOES,
glMultiTexCoord2bOES,
glMultiTexCoord2bvOES,
glMultiTexCoord3bOES,
glMultiTexCoord3bvOES,
glMultiTexCoord4bOES,
glMultiTexCoord4bvOES,
glTexCoord1bOES,
glTexCoord1bvOES,
glTexCoord2bOES,
glTexCoord2bvOES,
glTexCoord3bOES,
glTexCoord3bvOES,
glTexCoord4bOES,
glTexCoord4bvOES,
glVertex2bOES,
glVertex2bvOES,
glVertex3bOES,
glVertex3bvOES,
glVertex4bOES,
glVertex4bvOES
) where
import Graphics.Rendering.OpenGL.Raw.Types
import Graphics.Rendering.OpenGL.Raw.Tokens
import Graphics.Rendering.OpenGL.Raw.Functions
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/OES/ByteCoordinates.hs | bsd-3-clause | 1,235 | 0 | 4 | 161 | 124 | 91 | 33 | 28 | 0 |
module Experiment.AtomicOps where
import qualified Data.IORef as Ref
import qualified Data.Atomics as Atm
import qualified Data.Primitive.Array as Arr
atomicModifyIORef :: IO ()
atomicModifyIORef = do
ref <- Ref.newIORef (0 :: Int)
v1 <- Ref.atomicModifyIORef' ref (\ v -> (1, v))
v2 <- Ref.readIORef ref
print (v1, v2)
atomicModifyIORefCAS :: IO ()
atomicModifyIORefCAS = do
ref <- Ref.newIORef (0 :: Int)
v1 <- Atm.atomicModifyIORefCAS ref (\ v -> (1, v))
v2 <- Ref.readIORef ref
print (v1, v2)
casIORef :: IO ()
casIORef = do
ref <- Ref.newIORef (0 :: Int)
ticket <- Atm.readForCAS ref
(suc, next) <- Atm.casIORef ref ticket 1
let v1 = Atm.peekTicket ticket
v2 = Atm.peekTicket next
print (v1, v2, suc)
casArrayElem :: IO ()
casArrayElem = do
arr <- Arr.newArray 100 (0 :: Int)
ticket <- Atm.readArrayElem arr 0
(suc, next) <- Atm.casArrayElem arr 0 ticket 1
let v1 = Atm.peekTicket ticket
v2 = Atm.peekTicket next
print (v1, v2, suc)
| asakamirai/experiment-atomic-primops-with-fhpc | src/Experiment/AtomicOps.hs | bsd-3-clause | 1,049 | 0 | 11 | 264 | 419 | 216 | 203 | 32 | 1 |
{-# LANGUAGE DeriveGeneric, FlexibleContexts, TypeFamilies #-}
module Tutorial.Chapter7.Plant (Plant(..), FlowerColour(..),
buildPlant, run) where
import ALife.Creatur (Agent, agentId, isAlive)
import ALife.Creatur.Database (Record, key)
import ALife.Creatur.Genetics.BRGCBool (Genetic, Reader, Sequence,
getWithDefault, runReader, copy)
import ALife.Creatur.Genetics.Recombination (mutatePairedLists,
randomCrossover, randomCutAndSplice, randomOneOfPair, withProbability)
import ALife.Creatur.Genetics.Reproduction.SimplifiedSexual
(Reproductive, Strand, recombine, build, makeOffspring)
import ALife.Creatur.Universe (SimpleUniverse, genName, writeToLog)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Random (evalRandIO)
import Control.Monad.State (StateT)
import Data.Serialize (Serialize)
import GHC.Generics (Generic)
data Plant = Plant
{
plantName :: String,
plantFlowerColour :: FlowerColour,
plantEnergy :: Int,
plantGenome :: Sequence
} deriving (Show, Generic)
instance Serialize Plant
instance Agent Plant where
agentId = plantName
isAlive plant = plantEnergy plant > 0
instance Record Plant where key = agentId
data FlowerColour = Red | Orange | Yellow | Violet | Blue
deriving (Show, Eq, Generic, Enum, Bounded)
instance Serialize FlowerColour
instance Genetic FlowerColour
buildPlant :: String -> Reader (Either [String] Plant)
buildPlant name = do
g <- copy
colour <- getWithDefault Red
return . Right $ Plant name colour 10 g
instance Reproductive Plant where
type Strand Plant = Sequence
recombine a b =
withProbability 0.1 randomCrossover (plantGenome a, plantGenome b) >>=
withProbability 0.01 randomCutAndSplice >>=
withProbability 0.001 mutatePairedLists >>=
randomOneOfPair
build name = runReader (buildPlant name)
run :: [Plant] -> StateT (SimpleUniverse Plant) IO [Plant]
run (me:other:_) = do
name <- genName
(Right baby) <- liftIO $ evalRandIO (makeOffspring me other name)
writeToLog $
plantName me ++ " and " ++ plantName other ++
" gave birth to " ++ name ++ ", with " ++
show (plantFlowerColour baby) ++ " flowers"
writeToLog $ "Me: " ++ show me
writeToLog $ "Mate: " ++ show other
writeToLog $ "Baby: " ++ show baby
return [deductMatingEnergy me, deductMatingEnergy other, baby]
run _ = return [] -- need two agents to mate
deductMatingEnergy :: Plant -> Plant
deductMatingEnergy p = p {plantEnergy=plantEnergy p - 1}
| mhwombat/creatur-examples | src/Tutorial/Chapter7/Plant.hs | bsd-3-clause | 2,475 | 0 | 15 | 416 | 751 | 407 | 344 | 60 | 1 |
module Paths_phong where
import Data.Version
version :: Version
version = Version {versionBranch = [0,1,0,0], versionTags = []}
| CodosaurusRex/Phong | Paths_phong.hs | bsd-3-clause | 130 | 0 | 7 | 19 | 47 | 30 | 17 | 4 | 1 |
safeSqrt x = sqrtBool (x >= 0) x
sqrtBool True x = Just (sqrt x)
sqrtBool False _ = Nothing
| YoshikuniJujo/funpaala | samples/05_function/guards0.hs | bsd-3-clause | 93 | 0 | 7 | 21 | 50 | 24 | 26 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module GenC2
-- Uncomment the below line to expose all top level symbols for
-- repl testing
{-
(gen)
-- -}
where
import Ast (Block(..))
import TypeCheck
-- import Control.Monad.State.Lazy
-- import Control.Monad.Reader
-- import Control.Monad
import Control.Monad.RWS.Lazy
-- import qualified Data.Text as T
import Text.PrettyPrint hiding ((<>))
import qualified CPretty
import SyntaxImp
--
-- The generator function that we expose from this module
--
gen :: Env Block -> [Block] -> String
gen gamma bs =
let env = GenEnv { gamma = gamma }
(_, _, out) = runRWS (genCM bs) env initGenSt
in printOutput out
genCM :: [Block] -> GenM ()
genCM bs = mapM genHandle bs >>= \_ -> return ()
--
-- Define our state monad and initial state
--
data GenEnv = GenEnv {
gamma :: Env Block
}
deriving( Show )
data GenSt = GenSt {
counter :: Int
}
deriving( Show )
data Output = Output {
decls :: [IDecl]
}
deriving( Show )
printOutput :: Output -> String
printOutput out = show doc
where doc = vcat $ (map CPretty.cpretty (decls out))
instance Monoid Output where
mempty = Output {
decls = mempty
}
mappend x y = Output {
decls = decls x `mappend` decls y
}
type GenM = RWS GenEnv Output GenSt
-- data GenM a = Reader CodeGenEnv a
-- it is useful to leave this lying around for repl testing
bogusGenEnv :: GenEnv
bogusGenEnv = GenEnv {
gamma = gammaInit
}
initGenSt :: GenSt
initGenSt = GenSt {
counter = 0
}
uniqueId :: [String] -> GenM IId
uniqueId base = do
st <- get
put $ st { counter = (counter st) + 1 }
return $ IId base (Just (counter st))
-- makes a nekked id. beware of name capture
mkId :: [String] -> GenM IId
mkId base = return $ IId base Nothing
genHandle :: Block -> GenM ()
genHandle (Block name _) = do
n <- mkId [name]
isValid <- mkId ["is", "valid"]
d <- mkId ["data"]
tell $ Output [ IStructure n [
IAnnId isValid (IMut IBool)
, IAnnId d (IMut (IPtr (IMut IByte)))
]]
-- mkStructPtr :: IId -> IAnnTy
{-
genRead :: Block -> GenM ()
genRead (Block name entries) = do
funName <- mkId [name, "read", "new"]
handle <- mkId [name]
tell $ IFun funName -- [IAnnId handle (IMut (IStruct
-}
| ethanpailes/bbc | src/GenC2.hs | bsd-3-clause | 2,406 | 0 | 18 | 681 | 648 | 355 | 293 | 54 | 1 |
module Check (checkSyntax) where
import Cabal
import Control.Applicative
import CoreMonad
import ErrMsg
import Exception
import GHC
import GHCApi
import Prelude hiding (catch)
import Types
----------------------------------------------------------------
checkSyntax :: Options -> String -> IO String
checkSyntax opt file = unlines <$> check opt file
----------------------------------------------------------------
check :: Options -> String -> IO [String]
check opt fileName = withGHC $ checkIt `gcatch` handleErrMsg
where
checkIt = do
(file,readLog) <- initializeGHC opt fileName options True
setTargetFile file
_ <- load LoadAllTargets
liftIO readLog
options
| expandSplice opt = ["-w:"] ++ ghcOpts opt
| otherwise = ["-Wall"] ++ ghcOpts opt
| johntyree/ghc-mod | Check.hs | bsd-3-clause | 811 | 0 | 10 | 161 | 214 | 112 | 102 | 22 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE QuasiQuotes #-}
module Entities (
FieldType(..)
, Field(..)
, EntityReference(..)
, EntityMetadata(..)
, Entity(..)
, AllEntityInfo
, FromRow(..)
, ToRow(..)
, ToField(..)
, RowParser
, MonadReader(..)
, field
, queryReader
, makeEntities
, makeEntitiesLenses
, makeEntitiesFromRow
, makeEntitiesToRow
, makeEntitiesPostgresClasses
, makeEntityMethods
) where
import Data.Text hiding (toUpper, toLower, intersperse, foldl', length, concat, filter)
import qualified Data.Text as T
import Data.List (intersperse, foldl')
import Language.Haskell.TH
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Wiring
import Control.Lens.TH
import Control.Lens
import Control.Lens.Traversal
import Data.Char
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.ToRow
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToField
import Database.PostgreSQL.Simple.FromField hiding (Field)
import Control.Monad.Reader.Class
import Control.Monad.Reader.Class.Wiring
import qualified Data.HashSet as S
data FieldType = TextFieldType
| IntFieldType
| MaybeFieldType { _maybeInnerType :: FieldType }
makeLenses ''FieldType
data Field = Field
{ _fieldName :: Text
, _fieldType :: FieldType
}
makeLenses ''Field
data EntityReference = EntityReference
{ _originEntity :: Text
, _originFields :: [Text]
, _referencedEntity :: Text
, _referencedFields :: [Text]
}
makeLenses ''EntityReference
data EntityMetadata = IndexEntityMetadata { _indexFieldNames :: [Text] }
| PrimaryKeyEntityMetadata { _primaryKeyFieldNames :: [Text] }
makeLenses ''EntityMetadata
data Entity = Entity
{ _entityName :: Text
, _entityFields :: [Field]
, _entityMetadata :: [EntityMetadata]
}
makeLenses ''Entity
type AllEntityInfo = ([Entity], [EntityReference])
-- Build database entities that reference the elements rather than containing them.
-- Build "normal" entities that contain the full structure?
mkTextName :: Text -> Name
mkTextName = mkName . unpack
mkEntityName :: Entity -> Name
mkEntityName = mkTextName . _entityName
mkEntityType :: Entity -> TypeQ
mkEntityType = conT . mkEntityName
fieldTypeToType :: FieldType -> TypeQ
fieldTypeToType TextFieldType = conT $ mkName "Text"
fieldTypeToType IntFieldType = conT $ mkName "Int"
fieldTypeToType (MaybeFieldType innerFieldType) = do
case innerFieldType of
(MaybeFieldType _) -> reportError "Nested Maybes makes no sense."
_ -> return ()
let inner = fieldTypeToType innerFieldType
let maybeName = conT $ mkName "Maybe"
appT maybeName inner
fieldToType :: Field -> TypeQ
fieldToType (Field _ fieldType) = fieldTypeToType fieldType
fieldToStrictType :: Field -> VarStrictTypeQ
fieldToStrictType (Field name fieldType) = do
fieldType <- fieldTypeToType fieldType
return (mkTextName name, IsStrict, fieldType)
defaultDeriving :: [Name]
defaultDeriving = [mkName "Eq", mkName "Ord", mkName "Show"]
upperFirstLetter :: String -> String
upperFirstLetter [] = []
upperFirstLetter (x : xs) = toUpper x : xs
lowerFirstLetter :: String -> String
lowerFirstLetter [] = []
lowerFirstLetter (x : xs) = toLower x : xs
makeEntities :: AllEntityInfo -> Q [Dec]
makeEntities (entities, references) = (flip traverse) entities $ \entity -> do
let declName = mkTextName $ _entityName entity
let fields = fmap fieldToStrictType (_entityFields entity)
dataD (return []) declName [] [recC declName fields] defaultDeriving
makeEntitiesLenses :: AllEntityInfo -> Q [Dec]
makeEntitiesLenses (entities, references) = fmap join $ (flip traverse) entities $ \entity -> do
let nameOfEntity = _entityName entity
let declName = mkTextName nameOfEntity
let makeLensPair (Field name _) = (unpack name, (lowerFirstLetter $ unpack nameOfEntity) ++ (upperFirstLetter $ unpack name))
let lensDetails = fmap makeLensPair $ _entityFields entity
makeLensesFor lensDetails declName
fieldFnExp :: ExpQ
fieldFnExp = varE $ mkName "field"
makeFromRow :: Text -> [Field] -> ExpQ
makeFromRow entityName [] = conE $ mkTextName entityName
makeFromRow entityName (_ : fs) =
let apFn = varE $ mkName "<*>"
fmapFn = varE $ mkName "<$>"
initial = infixE (Just $ conE $ mkTextName entityName) fmapFn (Just $ fieldFnExp)
in foldl' (\w -> \e -> infixE (Just w) apFn (Just fieldFnExp)) initial fs
makeEntitiesFromRow :: AllEntityInfo -> Q [Dec]
makeEntitiesFromRow (entities, references) = (flip traverse) entities $ \entity -> do
let instanceType = appT (conT $ mkName "FromRow") (mkEntityType entity)
let fromRowClause = clause [] (normalB $ makeFromRow (_entityName entity) (_entityFields entity)) []
let fromRowDecl = funD (mkName "fromRow") [fromRowClause]
instanceD (return []) instanceType [fromRowDecl]
makeToRow :: Text -> [Field] -> ClauseQ
makeToRow entityName fields =
let fieldNames = fmap (\n -> mkName ("field" ++ show n)) [1..(length fields)]
pattern = conP (mkTextName entityName) $ fmap varP fieldNames
body = normalB $ listE $ fmap (\f -> appE (varE $ mkName "toField") (varE f)) fieldNames
in clause [pattern] body []
makeEntitiesToRow :: AllEntityInfo -> Q [Dec]
makeEntitiesToRow (entities, references) = (flip traverse) entities $ \entity -> do
let instanceType = appT (conT $ mkName "ToRow") (mkEntityType entity)
let toRowDecl = funD (mkName "toRow") [makeToRow (_entityName entity) (_entityFields entity)]
instanceD (return []) instanceType [toRowDecl]
makeEntitiesPostgresClasses :: AllEntityInfo -> Q [Dec]
makeEntitiesPostgresClasses allInfo = (++) <$> makeEntitiesToRow allInfo <*> makeEntitiesFromRow allInfo
queryReader :: (ToRow q, FromRow a, Functor m, MonadReader r m, MonadIO m, Wirable r Connection) => Query -> q -> m [a]
queryReader dbQuery queryParams = do
connection <- wiredAsk
liftIO $ query connection dbQuery queryParams
makePrimaryKeyedEntityMethods :: Entity -> Q [Dec]
makePrimaryKeyedEntityMethods entity = case (toListOf (entityMetadata . each . primaryKeyFieldNames) entity) of
[] -> return []
[_ : _ : _] -> reportError "Too many primary keys." >> return []
[fieldNames] -> do
let pkFieldNames = S.fromList fieldNames
let remainingFieldNames = S.difference pkFieldNames (S.fromList $ toListOf (entityFields . each . fieldName) entity)
if S.null remainingFieldNames then return () else reportError ("Fields listed in primary key not present in entity: " ++ show remainingFieldNames)
let keyClauses = concat $ intersperse ", " $ fmap (\f -> (unpack $ T.toLower f) ++ " = ?") fieldNames
let query = litE $ stringL ("select * from " ++ (unpack $ T.toLower $ _entityName entity) ++ "s where " ++ keyClauses)
patternNames <- traverse (\f -> newName $ unpack f) fieldNames
let callParams = [query, (tupE (fmap varE patternNames))]
let lookupClause = clause (fmap varP patternNames) (normalB $ foldl' appE (varE $ mkName "queryReader") callParams) []
do
let functionName = mkName ("get" ++ (unpack $ _entityName entity) ++ "ByPK")
let idParameters = foldl' appT (tupleT $ S.size pkFieldNames) $ fmap fieldToType $ filter (\f -> S.member (_fieldName f) pkFieldNames) $ _entityFields entity
let entityType = mkEntityType entity
signatureDef <- sigD functionName $ [t|forall m . forall r . (ToRow $idParameters, FromRow $entityType, MonadIO m, MonadReader r m, Wirable r Connection) => $idParameters -> m [$entityType]|]
functionDef <- funD functionName [lookupClause]
return [signatureDef, functionDef]
makeInsertEntityMethods :: Entity -> Q [Dec]
makeInsertEntityMethods entity = do
let functionName = mkName ("insert" ++ (unpack $ _entityName entity))
let fields = _entityFields entity
let fieldParameterTypes = foldl' appT (tupleT $ length fields) $ fmap fieldToType $ fields
let validFieldNames = fmap (mkName . unpack . _fieldName) $ fields
let columnNames = join $ intersperse "," $ fmap (unpack . T.toLower . _fieldName) fields
let columnWildcards = join $ intersperse "," $ fmap (\_ -> "?") fields
let fieldParameters = tupP $ fmap varP validFieldNames
let fieldsTuple = tupE $ fmap varE validFieldNames
let query = litE $ stringL ("insert into " ++ (unpack $ T.toLower $ _entityName entity) ++ "(" ++ columnNames ++ ") VALUES (" ++ columnWildcards ++ ")")
signatureDef <- sigD functionName $ [t|forall m . forall r . (ToRow $fieldParameterTypes, MonadIO m, MonadReader r m, Wirable r Connection) => $fieldParameterTypes -> m ()|]
let lookupClause = clause [[p|$fieldParameters|]] (normalB $ [|wiredAsk >>= (\c -> liftIO $ execute c $query $fieldsTuple) >> return ()|]) []
functionDef <- funD functionName [lookupClause]
return [signatureDef, functionDef]
makeEntityMethods :: AllEntityInfo -> Q [Dec]
makeEntityMethods (entities, _) = do
primaryKeyMethods <- (flip traverse) entities makePrimaryKeyedEntityMethods
insertEntityMethods <- (flip traverse) entities makeInsertEntityMethods
return $ join $ primaryKeyMethods ++ insertEntityMethods
| seanparsons/app-base | src/Entities.hs | bsd-3-clause | 9,916 | 10 | 30 | 2,124 | 2,862 | 1,493 | 1,369 | -1 | -1 |
module Tak.AI.Random where
import Control.Lens
import System.Random
import Tak.AI.Types
import Tak.Types
ai :: AIGameState -> IO Move
ai gs = do
let validMoves = moves (gs^.aiGameState)
m <- randomRIO (0,length validMoves - 1)
return $ validMoves !! m
| z0isch/htak | src/Tak/AI/Random.hs | bsd-3-clause | 306 | 0 | 12 | 92 | 101 | 53 | 48 | 10 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS -funbox-strict-fields #-}
module Data.TrieMap.UnionMap.Base (
module Data.TrieMap.UnionMap.Base,
module Data.TrieMap.TrieKey)
where
import Data.TrieMap.TrieKey
data instance TrieMap (Either k1 k2) a =
Empty
| MapL (TrieMap k1 a)
| MapR (TrieMap k2 a)
| Union !Int (TrieMap k1 a) (TrieMap k2 a)
data instance Zipper (TrieMap (Either k1 k2)) a =
HoleX0 (Hole k1 a)
| HoleXR (Hole k1 a) (TrieMap k2 a)
| Hole0X (Hole k2 a)
| HoleLX (TrieMap k1 a) (Hole k2 a)
{-# INLINE (^) #-}
(^) :: (TrieKey k1, TrieKey k2, Sized a) => Maybe (TrieMap k1 a) -> Maybe (TrieMap k2 a) -> TrieMap (Either k1 k2) a
Nothing ^ Nothing = Empty
Just m1 ^ Nothing = MapL m1
Nothing ^ Just m2 = MapR m2
Just m1 ^ Just m2 = Union (sizeM m1 + sizeM m2) m1 m2
mapLR :: (TrieKey k1, TrieKey k2, Sized a) => TrieMap k1 a -> TrieMap k2 a -> TrieMap (Either k1 k2) a
mapLR m1 m2 = Union (sizeM m1 + getSize m2) m1 m2
singletonL :: (TrieKey k1, TrieKey k2, Sized a) => k1 -> a -> TrieMap (Either k1 k2) a
singletonL k a = MapL (singleton k a)
singletonR :: (TrieKey k1, TrieKey k2, Sized a) => k2 -> a -> TrieMap (Either k1 k2) a
singletonR k a = MapR (singleton k a)
data UView k1 k2 a = UView (Maybe (TrieMap k1 a)) (Maybe (TrieMap k2 a))
data HView k1 k2 a = Hole1 (Hole k1 a) (Maybe (TrieMap k2 a))
| Hole2 (Maybe (TrieMap k1 a)) (Hole k2 a)
{-# INLINE uView #-}
uView :: TrieMap (Either k1 k2) a -> UView k1 k2 a
uView Empty = UView Nothing Nothing
uView (MapL m1) = UView (Just m1) Nothing
uView (MapR m2) = UView Nothing (Just m2)
uView (Union _ m1 m2) = UView (Just m1) (Just m2)
hView :: Hole (Either k1 k2) a -> HView k1 k2 a
hView (HoleX0 hole1) = Hole1 hole1 Nothing
hView (HoleXR hole1 m2) = Hole1 hole1 (Just m2)
hView (Hole0X hole2) = Hole2 Nothing hole2
hView (HoleLX m1 hole2) = Hole2 (Just m1) hole2
hole1 :: Hole k1 a -> Maybe (TrieMap k2 a) -> Hole (Either k1 k2) a
hole1 hole1 Nothing = HoleX0 hole1
hole1 hole1 (Just m2) = HoleXR hole1 m2
hole2 :: Maybe (TrieMap k1 a) -> Hole k2 a -> Hole (Either k1 k2) a
hole2 Nothing hole2 = Hole0X hole2
hole2 (Just m1) hole2 = HoleLX m1 hole2
| lowasser/TrieMap | Data/TrieMap/UnionMap/Base.hs | bsd-3-clause | 2,155 | 10 | 10 | 464 | 1,099 | 549 | 550 | 50 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.