code
stringlengths 2
1.05M
| repo_name
stringlengths 5
101
| path
stringlengths 4
991
| language
stringclasses 3
values | license
stringclasses 5
values | size
int64 2
1.05M
|
|---|---|---|---|---|---|
module Lava.Smv
( smv
)
where
import Lava.Signal
import Lava.Netlist
import Lava.Generic
import Lava.Sequent
import Lava.Property
import Lava.Error
import Lava.LavaDir
import Lava.Verification
import Data.List
( intersperse
, nub
)
import System.IO
( openFile
, IOMode(..)
, hPutStr
, hClose
)
import Lava.IOBuffering
( noBuffering
)
import Data.IORef
import System.Cmd (system)
import System.Exit (ExitCode(..))
----------------------------------------------------------------
-- smv
smv :: Checkable a => a -> IO ProofResult
smv a =
do checkVerifyDir
noBuffering
(props,_) <- properties a
proveFile defsFile (writeDefinitions defsFile props)
where
defsFile = verifyDir ++ "/circuit.smv"
----------------------------------------------------------------
-- definitions
writeDefinitions :: FilePath -> [Signal Bool] -> IO ()
writeDefinitions file props =
do firstHandle <- openFile firstFile WriteMode
secondHandle <- openFile secondFile WriteMode
var <- newIORef 0
hPutStr firstHandle $ unlines $
[ "-- Generated by Lava"
, ""
, "MODULE main"
]
let new =
do n <- readIORef var
let n' = n+1; v = "w" ++ show n'
n' `seq` writeIORef var n'
return v
define v s =
case s of
Bool True -> op0 "1"
Bool False -> op0 "0"
Inv x -> op1 "!" x
And [] -> define v (Bool True)
And [x] -> op0 x
And xs -> opl "&" xs
Or [] -> define v (Bool False)
Or [x] -> op0 x
Or xs -> opl "|" xs
Xor [] -> define v (Bool False)
Xor xs -> op0 (xor xs)
VarBool s -> do op0 s
hPutStr firstHandle ("VAR " ++ s ++ " : boolean;\n")
DelayBool x y -> delay x y
_ -> wrong Lava.Error.NoArithmetic
where
w i = v ++ "_" ++ show i
op0 s =
hPutStr secondHandle $
"DEFINE " ++ v ++ " := " ++ s ++ ";\n"
op1 op s =
op0 (op ++ "(" ++ s ++ ")")
opl op xs =
op0 (concat (intersperse (" " ++ op ++ " ") xs))
xor [x] = x
xor [x,y] = "!(" ++ x ++ " <-> " ++ y ++ ")"
xor (x:xs) = "(" ++ x ++ " & !("
++ concat (intersperse " | " xs)
++ ") | (!" ++ x ++ " & (" ++ xor xs ++ ")))"
delay x y =
do hPutStr firstHandle ("VAR " ++ v ++ " : boolean;\n")
hPutStr secondHandle $
"ASSIGN init(" ++ v ++ ") := " ++ x ++ ";\n"
++ "ASSIGN next(" ++ v ++ ") := " ++ y ++ ";\n"
outvs <- netlistIO new define (struct props)
hPutStr secondHandle $ unlines $
[ "SPEC AG " ++ outv
| outv <- flatten outvs
]
hClose firstHandle
hClose secondHandle
system ("cat " ++ firstFile ++ " " ++ secondFile ++ " > " ++ file)
system ("rm " ++ firstFile ++ " " ++ secondFile)
return ()
where
firstFile = file ++ "-1"
secondFile = file ++ "-2"
----------------------------------------------------------------
-- primitive proving
proveFile :: FilePath -> IO () -> IO ProofResult
proveFile file before =
do putStr "Smv: "
before
putStr "... "
lavadir <- getLavaDir
x <- system ( lavadir
++ "/Scripts/smv.wrapper "
++ file
++ " -showTime"
)
let res = case x of
ExitSuccess -> Valid
ExitFailure 1 -> Indeterminate
ExitFailure _ -> Falsifiable
putStrLn (show res ++ ".")
return res
----------------------------------------------------------------
-- the end.
|
dfordivam/lava
|
Lava/Smv.hs
|
Haskell
|
bsd-3-clause
| 3,975
|
module Database.TokyoCabinet.Sequence where
import Foreign.Ptr
import Foreign.Storable (peek)
import Foreign.Marshal (alloca, mallocBytes, copyBytes)
import Foreign.ForeignPtr
import Database.TokyoCabinet.List.C
import Database.TokyoCabinet.Storable
class Sequence a where
withList :: (Storable s) => a s -> (Ptr LIST -> IO b) -> IO b
peekList' :: (Storable s) => Ptr LIST -> IO (a s)
empty :: (Storable s) => IO (a s)
smap :: (Storable s1, Storable s2) => (s1 -> s2) -> a s1 -> IO (a s2)
instance Sequence List where
withList xs action = withForeignPtr (unTCList xs) action
peekList' tcls = List `fmap` newForeignPtr tclistFinalizer tcls
empty = List `fmap` (c_tclistnew >>= newForeignPtr tclistFinalizer)
smap f tcls =
withForeignPtr (unTCList tcls) $ \tcls' ->
alloca $ \sizbuf ->
do num <- c_tclistnum tcls'
vals <- c_tclistnew
loop tcls' 0 num sizbuf vals
where
loop tcls' n num sizbuf acc
| n < num = do vbuf <- c_tclistval tcls' n sizbuf
vsiz <- peek sizbuf
buf <- mallocBytes (fromIntegral vsiz)
copyBytes buf vbuf (fromIntegral vsiz)
val <- f `fmap` peekPtrLen (buf, vsiz)
withPtrLen val $ uncurry (c_tclistpush acc)
loop tcls' (n+1) num sizbuf acc
| otherwise = List `fmap` newForeignPtr tclistFinalizer acc
instance Sequence [] where
withList xs action =
do list <- c_tclistnew
mapM_ (push list) xs
result <- action list
c_tclistdel list
return result
where
push list val = withPtrLen val $ uncurry (c_tclistpush list)
peekList' tcls = do
vals <- peekList'' tcls []
c_tclistdel tcls
return vals
where
peekList'' lis acc =
alloca $ \sizbuf ->
do val <- c_tclistpop lis sizbuf
siz <- peek sizbuf
if val == nullPtr
then return acc
else do elm <- peekPtrLen (val, siz)
peekList'' lis (elm:acc)
empty = return []
smap f = return . (map f)
|
tom-lpsd/tokyocabinet-haskell
|
Database/TokyoCabinet/Sequence.hs
|
Haskell
|
bsd-3-clause
| 2,356
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-} --these two for Isomorphic class
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-} -- necessary for Shapely Generics instances
{-# LANGUAGE TypeOperators #-} -- for our cons synonym
{-# LANGUAGE StandaloneDeriving #-} -- these two for deriving AlsoNormal instances
module Data.Shapely.Classes
where
-- internal module to avoid circular dependencies
import Data.Shapely.Normal.Exponentiation
-- | Instances of the 'Shapely' class have a 'Normal' form representation,
-- made up of @(,)@, @()@ and @Either@, and functions to convert 'from' @a@ and
-- back 'to' @a@ again.
class (Exponent (Normal a))=> Shapely a where
-- | A @Shapely@ instances \"normal form\" representation, consisting of
-- nested product, sum and unit types. Types with a single constructor will
-- be given a 'Product' Normal representation, where types with more than
-- one constructor will be 'Sum's.
--
-- See the documentation for 'Data.Shapely.TH.deriveShapely', and the
-- instances defined here for details.
type Normal a
-- NOTE: the naming here seems backwards but is what's in GHC.Generics
from :: a -> Normal a
to :: Normal a -> a
to na = let a = fanin (constructorsOf a) na in a
-- | Return a structure capable of rebuilding a type @a@ from its 'Normal'
-- representation (via 'fanin').
--
-- This structure is simply the data constructor (or a 'Product' of
-- constructors for 'Sum's), e.g. for @Either@:
--
-- > constructorsOf _ = (Left,(Right,()))
--
-- Satisfies:
--
-- > fanin (constructorsOf a) (from a) == a
constructorsOf :: a -> Normal a :=>-> a
-- Here I walk-through the ways we define 'Shapely' instances; you can also see
-- the documentation for mkShapely for a description.
--
-- Syntactically we can think of the type constructor (in this case (), but
-- usually, e.g. "Foo") becoming (), and getting pushed to the bottom of the
-- stack of its terms (in this case there aren't any).
instance Shapely () where
type Normal () = ()
from = id
--to = id
constructorsOf _ = ()
-- And data constructor arguments appear on the 'fst' positions of nested
-- tuples, finally terminated by a () in the 'snd' place.
-- | Note, the normal form for a tuple is not itself
instance Shapely (x,y) where
type Normal (x,y) = (x,(y,()))
from (x,y) = (x,(y,()))
--to (x,(y,())) = (x,y)
constructorsOf _ = (,)
-- Here, again syntactically, both constructors Left and Right become `()`, and
-- we replace `|` with `Either` creating a sum of products.
instance Shapely (Either x y) where
type Normal (Either x y) = Either (x,()) (y,())
from = let f = flip (,) () in either (Left . f) (Right . f)
--to = either (Left . fst) (Right . fst)
constructorsOf _ = (Left,(Right,()))
-- The Normal form of a type is just a simple unpacking of the constructor
-- terms, and doesn't do anything to express recursive structure. But this
-- simple type function gives us what we need to make use of recursive
-- structure, e.g. in Isomorphic, or by converting to a pattern functor that
-- can be turned into a fixed point with with FunctorOn.
instance Shapely [a] where
-- NOTE: data [] a = [] | a : [a] -- Defined in `GHC.Types'
type Normal [a] = Either () (a,([a],()))
from [] = Left ()
from ((:) a as) = Right (a, (as, ()))
constructorsOf _ = ([],((:),()))
---- Additional instances are derived automatically in Data.Shapely
{-
-- | A wrapper for recursive child occurences of a 'Normal'-ized type
newtype AlsoNormal a = Also { normal :: Normal a }
deriving instance (Show (Normal a))=> Show (AlsoNormal a)
deriving instance (Eq (Normal a))=> Eq (AlsoNormal a)
deriving instance (Ord (Normal a))=> Ord (AlsoNormal a)
deriving instance (Read (Normal a))=> Read (AlsoNormal a)
-}
|
jberryman/shapely-data
|
src/Data/Shapely/Classes.hs
|
Haskell
|
bsd-3-clause
| 3,973
|
{-# LANGUAGE OverloadedStrings #-}
module Database.MetaStorage.Spec (metaStorageSpec) where
import Test.Hspec
import Test.QuickCheck
import Filesystem.Path.CurrentOS
import Crypto.Hash
import Filesystem
import Database.MetaStorage
import Database.MetaStorage.Types
metaStorageSpec :: Spec
metaStorageSpec = do
describe "MetaStorage.mkMetaStorage" $ do
it "creates a new storage in FilePath" $ example $ do
(st, _) <- (mkMetaStorageDefault fp)
st `shouldBe` (MetaStorage fp)
it "throws an exception on invalid filepath" $ example $ do
let ms = (mkMetaStorageDefault invalidPath)
ms `shouldThrow` anyException
context "when given an non existing dir" $ do
it "the new directory will be created" $ example $ do
removeTree fp
(_, ds) <- (mkMetaStorageDefault fp)
isDir <- isDirectory fp
isDir `shouldBe` True
it "returns an empty list " $ example $ do
removeTree fp
(_, ds) <- (mkMetaStorageDefault fp)
ds `shouldBe` []
it "returns a list of the hashes of existing items" $ example $ do
pendingWith "no tests implemented yet"
describe "MetaStorage.ms_basedir" $ do
it "returns the basedir of the MetaStorage" $ do
(st, _) <- (mkMetaStorageDefault fp)
pending --ms_basedir st `shouldBe` fp
describe "MetaStorage.ms_getFilePath" $ do
it "returns an absolute FilePath for a given digest" $
pendingWith "unimplemented test"
where fpbase = "/tmp"
fp = fpbase </> fromText "mstesttmp"
invalidPath = empty
|
alios/metastorage
|
Database/MetaStorage/Spec.hs
|
Haskell
|
bsd-3-clause
| 1,588
|
module Network.Tangaroa.Byzantine.Server
( runRaftServer
) where
import Data.Binary
import Control.Concurrent.Chan.Unagi
import Control.Lens
import qualified Data.Set as Set
import Network.Tangaroa.Byzantine.Handler
import Network.Tangaroa.Byzantine.Types
import Network.Tangaroa.Byzantine.Util
import Network.Tangaroa.Byzantine.Timer
runRaftServer :: (Binary nt, Binary et, Binary rt, Ord nt) => Config nt -> RaftSpec nt et rt mt -> IO ()
runRaftServer rconf spec = do
let qsize = getQuorumSize $ 1 + (Set.size $ rconf ^. otherNodes)
(ein, eout) <- newChan
runRWS_
raft
(RaftEnv rconf qsize ein eout (liftRaftSpec spec))
initialRaftState
raft :: (Binary nt, Binary et, Binary rt, Ord nt) => Raft nt et rt mt ()
raft = do
fork_ messageReceiver
resetElectionTimer
handleEvents
|
chrisnc/tangaroa
|
src/Network/Tangaroa/Byzantine/Server.hs
|
Haskell
|
bsd-3-clause
| 808
|
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module TensorOps.Backend.BTensor
( BTensor
, BTensorL, BTensorV
, HMat
, HMatD
) where
import Control.Applicative
import Control.DeepSeq
import Data.Distributive
import Data.Kind
import Data.List.Util
import Data.Monoid
import Data.Nested hiding (unScalar, unVector, gmul')
import Data.Singletons
import Data.Singletons.Prelude hiding (Reverse, Head, sReverse, (:-))
import Data.Type.Combinator
import Data.Type.Combinator.Util
import Data.Type.Length as TCL
import Data.Type.Length.Util as TCL
import Data.Type.Nat
import Data.Type.Product as TCP
import Data.Type.Product.Util as TCP
import Data.Type.Sing
import Data.Type.Uniform
import Statistics.Distribution
import TensorOps.BLAS
import TensorOps.BLAS.HMat
import TensorOps.NatKind
import TensorOps.Types
import Type.Class.Higher
import Type.Class.Higher.Util
import Type.Class.Witness
import Type.Family.List
import Type.Family.List.Util
import Type.Family.Nat
import qualified Data.Type.Vector as TCV
import qualified Data.Type.Vector.Util as TCV
import qualified Data.Vector.Sized as VS
data BTensor :: (k -> Type -> Type) -> (BShape k -> Type) -> [k] -> Type where
BTS :: { unScalar :: !(ElemB b) } -> BTensor v b '[]
BTV :: { unVector :: !(b ('BV n)) } -> BTensor v b '[n]
BTM :: { unMatrix :: !(b ('BM n m)) } -> BTensor v b '[n,m]
BTN :: { unNested :: !(v n (BTensor v b (o ': m ': ns))) }
-> BTensor v b (n ': o ': m ': ns)
type BTensorL = BTensor (Flip2 TCV.VecT I)
type BTensorV = BTensor (Flip2 VS.VectorT I)
instance (Nesting Proxy Show v, Show1 b, Show (ElemB b)) => Show (BTensor v b s) where
showsPrec p = \case
BTS x -> showParen (p > 10) $ showString "BTS "
. showsPrec 11 x
BTV xs -> showParen (p > 10) $ showString "BTV "
. showsPrec1 11 xs
BTM xs -> showParen (p > 10) $ showString "BTM "
. showsPrec1 11 xs
BTN xs -> showParen (p > 10) $ showString "BTN "
. showsPrec' 11 xs
where
showsPrec' :: forall n s'. Int -> v n (BTensor v b s') -> ShowS
showsPrec' p' xs = showsPrec p' xs
\\ (nesting Proxy :: Show (BTensor v b s')
:- Show (v n (BTensor v b s'))
)
instance (Nesting Proxy Show v, Show1 b, Show (ElemB b)) => Show1 (BTensor v b)
instance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => Nesting1 Proxy NFData (BTensor v b) where
nesting1 _ = Wit
instance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => NFData (BTensor v b js) where
rnf = \case
BTS x -> rnf x
BTV xs -> rnf1 xs
BTM xs -> rnf1 xs
BTN (xs :: v n (BTensor v b (o ': m ': ns))) ->
rnf xs \\ (nesting Proxy :: NFData (BTensor v b (o ': m ': ns))
:- NFData (v n (BTensor v b (o ': m ': ns)))
)
instance (NFData (ElemB b), NFData1 b, Nesting Proxy NFData v) => NFData1 (BTensor v b)
instance ( BLAS b
, Vec v
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
, SingI ns
, Num (ElemB b)
)
=> Num (BTensor v b ns) where
(+) = zipBase sing
(+)
(\_ xs ys -> axpy 1 xs (Just ys))
(\(SBM _ sM) xs ys -> gemm 1 xs (eye sM) (Just (1, ys)))
{-# INLINE (+) #-}
(-) = zipBase sing
(-)
(\_ xs ys -> axpy (-1) ys (Just xs))
(\(SBM _ sM) xs ys -> gemm 1 xs (eye sM) (Just (-1, ys)))
{-# INLINE (-) #-}
(*) = zipBTensorElems sing (*)
{-# INLINE (*) #-}
negate = mapBase sing
negate
(\_ xs -> axpy (-1) xs Nothing)
(\(SBM _ sM) xs -> gemm 1 xs (eye sM) Nothing)
{-# INLINE negate #-}
abs = mapBTensorElems abs
{-# INLINE abs #-}
signum = mapBTensorElems signum
{-# INLINE signum #-}
fromInteger i = genBTensor sing $ \_ -> fromInteger i
{-# INLINE fromInteger #-}
-- | TODO: add RULES pragmas so that this can be done without checking
-- lengths at runtime in the common case that the lengths are known at
-- compile-time.
--
-- Also, totally forgot about matrix-scalar multiplication here, but there
-- isn't really any way of making it work without a lot of empty cases.
-- should probably handle one level up.
dispatchBLAS
:: forall b ms os ns v. (RealFloat (ElemB b), BLAS b)
=> MaxLength N1 ms
-> MaxLength N1 os
-> MaxLength N1 ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
dispatchBLAS lM lO lN v r = case (lM, lO, lN) of
(MLZ , MLZ , MLZ ) -> case (v, r) of
-- scalar-scalar
(BTS x, BTS y) -> BTS $ x * y
(MLZ , MLZ , MLS MLZ) -> case (v, r) of
-- scalar-vector
(BTS x, BTV y) -> BTV $ axpy x y Nothing
(MLZ , MLS MLZ, MLZ ) -> case (v, r) of
-- dot
(BTV x, BTV y) -> BTS $ x `dot` y
(MLZ , MLS MLZ, MLS MLZ) -> case (v, r) of
-- vector-matrix
-- TODO: transpose?
(BTV x, BTM y) -> BTV $ gemv 1 (transpB y) x Nothing
(MLS MLZ, MLZ , MLZ ) -> case (v, r) of
-- vector-scalar
(BTV x, BTS y) -> BTV $ axpy y x Nothing
(MLS MLZ, MLZ , MLS MLZ) -> case (v, r) of
-- vector-scalar
(BTV x, BTV y) -> BTM $ ger x y
(MLS MLZ, MLS MLZ, MLZ ) -> case (v, r) of
-- matrx-vector
(BTM x, BTV y) -> BTV $ gemv 1 x y Nothing
(MLS MLZ, MLS MLZ, MLS MLZ) -> case (v, r) of
-- matrix-matrix
(BTM x, BTM y) -> BTM $ gemm 1 x y Nothing
{-# INLINE dispatchBLAS #-}
mapRowsBTensor
:: forall k (v :: k -> Type -> Type) ns ms os b. (Vec v, BLAS b)
=> Sing ns
-> Length os
-> (BTensor v b ms -> BTensor v b os)
-> BTensor v b (ns ++ ms)
-> BTensor v b (ns ++ os)
mapRowsBTensor sN lO f = getI . bRows sN lO (I . f)
{-# INLINE mapRowsBTensor #-}
bRows
:: forall k (v :: k -> Type -> Type) ns ms os b f. (Applicative f, Vec v, BLAS b)
=> Sing ns
-> Length os
-> (BTensor v b ms -> f (BTensor v b os))
-> BTensor v b (ns ++ ms)
-> f (BTensor v b (ns ++ os))
bRows sN lO f = bIxRows sN lO (\_ -> f)
{-# INLINE bRows #-}
mapIxRows
:: forall k (v :: k -> Type -> Type) ns ms os b. (Vec v, BLAS b)
=> Sing ns
-> Length os
-> (Prod (IndexN k) ns -> BTensor v b ms -> BTensor v b os)
-> BTensor v b (ns ++ ms)
-> BTensor v b (ns ++ os)
mapIxRows sN lO f = getI . bIxRows sN lO (\i -> I . f i)
{-# INLINE mapIxRows #-}
foldMapIxRows
:: forall k (v :: k -> Type -> Type) ns ms m b. (Vec v, Monoid m, BLAS b)
=> Sing ns
-> (Prod (IndexN k) ns -> BTensor v b ms -> m)
-> BTensor v b (ns ++ ms)
-> m
foldMapIxRows s f = getConst . bIxRows s LZ (\i -> Const . f i)
{-# INLINE foldMapIxRows #-}
bIxRows
:: forall k (v :: k -> Type -> Type) ns ms os b f. (Applicative f, Vec v, BLAS b)
=> Sing ns
-> Length os
-> (Prod (IndexN k) ns -> BTensor v b ms -> f (BTensor v b os))
-> BTensor v b (ns ++ ms)
-> f (BTensor v b (ns ++ os))
bIxRows = \case
SNil -> \_ f -> f Ø
s `SCons` ss -> \lO f -> \case
BTV xs -> case ss of
-- ns ~ '[n]
-- ms ~ '[]
SNil -> case lO of
-- ns ++ os ~ '[n]
LZ -> BTV <$> iElemsB (\i -> fmap unScalar . f (pbvProd i) . BTS) xs
-- ns ++ os ~ '[n,m]
LS LZ -> BTM <$> bgenRowsA (\i -> unVector <$> f (i :< Ø) (BTS $ indexB (PBV i) xs))
\\ s
LS (LS _) -> BTN <$> vGenA s (\i -> f (i :< Ø) (BTS $ indexB (PBV i) xs))
BTM xs -> case ss of
-- ns ~ '[n]
-- ms ~ '[m]
SNil -> case lO of
-- ns ++ os ~ '[n]
LZ -> BTV <$> bgenA (SBV s) (\(PBV i) -> unScalar <$> f (i :< Ø) (BTV (indexRowB i xs)))
-- ns ++ os ~ '[n,o]
LS LZ -> BTM <$> iRowsB (\i -> fmap unVector . f (i :< Ø) . BTV) xs
LS (LS _) -> BTN <$> vGenA s (\i -> f (i :< Ø) (BTV (indexRowB i xs)))
-- ns ~ '[n,m]
-- ms ~ '[]
s' `SCons` ss' -> (\\ s') $ case ss' of
SNil -> case lO of
LZ -> BTM <$> iElemsB (\i -> fmap unScalar . f (pbmProd i) . BTS) xs
LS _ -> BTN <$>
vGenA s (\i ->
btn lO <$>
vGenA s' (\j ->
f (i :< j :< Ø) (BTS (indexB (PBM i j) xs))
)
)
BTN xs -> (\\ s) $
fmap (btn (singLength ss `TCL.append'` lO))
. vITraverse (\i -> bIxRows ss lO (\is -> f (i :< is)))
$ xs
indexRowBTensor
:: forall k (b :: BShape k -> Type) v ns ms.
( BLAS b
, Vec v
)
=> Prod (IndexN k) ns
-> BTensor v b (ns ++ ms)
-> BTensor v b ms
indexRowBTensor = \case
Ø -> id
i :< is -> \case
BTV xs -> case is of
Ø -> BTS $ indexB (PBV i) xs
BTM xs -> case is of
Ø -> BTV $ indexRowB i xs
j :< Ø -> BTS $ indexB (PBM i j) xs
BTN xs -> indexRowBTensor is (vIndex i xs)
{-# INLINE indexRowBTensor #-}
mapBTensorElems
:: (Vec v, BLAS b)
=> (ElemB b -> ElemB b)
-> BTensor v b ns
-> BTensor v b ns
mapBTensorElems f = getI . bTensorElems (I . f)
{-# INLINE mapBTensorElems #-}
bTensorElems
:: forall k (v :: k -> Type -> Type) ns b f. (Applicative f, Vec v, BLAS b)
=> (ElemB b -> f (ElemB b))
-> BTensor v b ns
-> f (BTensor v b ns)
bTensorElems f = \case
BTS x -> BTS <$> f x
BTV xs -> BTV <$> elemsB f xs
BTM xs -> BTM <$> elemsB f xs
BTN xs -> BTN <$> vITraverse (\_ x -> bTensorElems f x) xs
{-# INLINE bTensorElems #-}
ifoldMapBTensor
:: forall k (v :: k -> Type -> Type) ns m b. (Monoid m, Vec v, BLAS b)
=> (Prod (IndexN k) ns -> ElemB b -> m)
-> BTensor v b ns
-> m
ifoldMapBTensor f = getConst . bTensorIxElems (\i -> Const . f i)
{-# INLINE ifoldMapBTensor #-}
bTensorIxElems
:: forall k (v :: k -> Type -> Type) ns b f. (Applicative f, Vec v, BLAS b)
=> (Prod (IndexN k) ns -> ElemB b -> f (ElemB b))
-> BTensor v b ns
-> f (BTensor v b ns)
bTensorIxElems f = \case
BTS x -> BTS <$> f Ø x
BTV xs -> BTV <$> iElemsB (f . pbvProd) xs
BTM xs -> BTM <$> iElemsB (f . pbmProd) xs
BTN xs -> BTN <$> vITraverse (\i -> bTensorIxElems (\is -> f (i :< is))) xs
{-# INLINE bTensorIxElems #-}
zipBTensorElems
:: forall v b ns. (BLAS b, Nesting1 Sing Applicative v)
=> Sing ns
-> (ElemB b -> ElemB b -> ElemB b)
-> BTensor v b ns
-> BTensor v b ns
-> BTensor v b ns
zipBTensorElems = \case
SNil -> \f -> \case
BTS x -> \case
BTS y -> BTS (f x y)
sN `SCons` SNil -> \f -> \case
BTV xs -> \case
BTV ys -> BTV (zipB (SBV sN) f xs ys)
sN `SCons` (sM `SCons` SNil) -> \f -> \case
BTM xs -> \case
BTM ys -> BTM (zipB (SBM sN sM) f xs ys)
(s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f -> \case
BTN xs -> \case
BTN ys -> BTN (zipBTensorElems ss f <$> xs <*> ys)
\\ (nesting1 s :: Wit (Applicative (v k)))
{-# INLINE zipBTensorElems #-}
liftBTensor
:: forall v b ns n.
( BLAS b
, Nesting1 Proxy Functor v
, Nesting1 Sing Distributive v
)
=> Sing ns
-> (TCV.Vec n (ElemB b) -> ElemB b)
-> TCV.Vec n (BTensor v b ns)
-> BTensor v b ns
liftBTensor = \case
SNil -> \f xs ->
let xs' = unScalar <$> xs
in BTS $ f xs'
sN `SCons` SNil -> \f xs ->
let xs' = unVector <$> xs
in BTV $ liftB (SBV sN) f xs'
sN `SCons` (sM `SCons` SNil) -> \f xs ->
let xs' = unMatrix <$> xs
in BTM $ liftB (SBM sN sM) f xs'
(s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f xs ->
let xs' = unNested <$> xs
in BTN $ TCV.liftVecD (liftBTensor ss f) xs'
\\ (nesting1 s :: Wit (Distributive (v k)))
{-# INLINE liftBTensor #-}
mapBTM
:: forall k (v :: k -> Type -> Type) ns n m ms b. (Vec v, BLAS b)
=> Sing ns
-> Length ms
-> (b ('BM n m) -> BTensor v b ms)
-> BTensor v b (ns ++ [n,m])
-> BTensor v b (ns ++ ms)
mapBTM sN lM f = getI . traverseBTM sN lM (I . f)
{-# INLINE mapBTM #-}
foldMapBTM
:: (Monoid a, Vec v, BLAS b)
=> Length ns
-> (b ('BM n m) -> a)
-> BTensor v b (ns ++ [n,m])
-> a
foldMapBTM l f = ifoldMapBTM l (\_ -> f)
{-# INLINE foldMapBTM #-}
traverseBTM
:: forall k (v :: k -> Type -> Type) ns n m ms b f. (Applicative f, Vec v, BLAS b)
=> Sing ns
-> Length ms
-> (b ('BM n m) -> f (BTensor v b ms))
-> BTensor v b (ns ++ [n,m])
-> f (BTensor v b (ns ++ ms))
traverseBTM = \case
SNil -> \_ f -> \case
BTM x -> f x
s `SCons` ss -> \lM f -> \case
BTV _ -> case ss of
BTM _ -> case ss of
BTN xs -> (\\ s) $
fmap (btn (singLength ss `TCL.append'` lM))
. vITraverse (\_ -> traverseBTM ss lM f)
$ xs
{-# INLINE traverseBTM #-}
imapBTM
:: forall k (v :: k -> Type -> Type) ns n m ms b. (Vec v, BLAS b)
=> Sing ns
-> Length ms
-> (Prod (IndexN k) ns -> b ('BM n m) -> BTensor v b ms)
-> BTensor v b (ns ++ [n,m])
-> BTensor v b (ns ++ ms)
imapBTM sN lM f = getI . itraverseBTM sN lM (\i -> I . f i)
{-# INLINE imapBTM #-}
ifoldMapBTM
:: (Vec v, Monoid a, BLAS b)
=> Length ns
-> (Prod (IndexN k) ns -> b ('BM n m) -> a)
-> BTensor v b (ns ++ [n,m])
-> a
ifoldMapBTM = \case
LZ -> \f -> \case
BTM xs -> f Ø xs
LS l -> \f -> \case
BTV _ -> case l of
BTM _ -> case l of
BTN xs -> vIFoldMap (\i -> ifoldMapBTM l (\is -> f (i :< is))) xs
{-# INLINE ifoldMapBTM #-}
itraverseBTM
:: forall k (v :: k -> Type -> Type) ns n m ms b f. (Applicative f, Vec v, BLAS b)
=> Sing ns
-> Length ms
-> (Prod (IndexN k) ns -> b ('BM n m) -> f (BTensor v b ms))
-> BTensor v b (ns ++ [n,m])
-> f (BTensor v b (ns ++ ms))
itraverseBTM = \case
SNil -> \_ f -> \case
BTM x -> f Ø x
s `SCons` ss -> \lM f -> \case
BTV _ -> case ss of
BTM _ -> case ss of
BTN xs -> (\\ s) $
fmap (btn (singLength ss `TCL.append'` lM))
. vITraverse (\i -> itraverseBTM ss lM (\is ys -> f (i :< is) ys))
$ xs
{-# INLINE itraverseBTM #-}
mapBase
:: forall v b ns. (Nesting1 Proxy Functor v)
=> Sing ns
-> (ElemB b -> ElemB b)
-> (forall n. Sing n -> b ('BV n) -> b ('BV n))
-> (forall n m. Sing ('BM n m) -> b ('BM n m) -> b ('BM n m))
-> BTensor v b ns
-> BTensor v b ns
mapBase = \case
SNil -> \f _ _ -> \case
BTS x -> BTS (f x)
sN `SCons` SNil -> \_ g _ -> \case
BTV xs -> BTV (g sN xs)
sN `SCons` (sM `SCons` SNil) -> \_ _ h -> \case
BTM xs -> BTM (h (SBM sN sM) xs)
(_ :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f g h -> \case
BTN xs -> BTN (mapBase ss f g h <$> xs)
\\ (nesting1 Proxy :: Wit (Functor (v k)))
{-# INLINE mapBase #-}
zipBase
:: forall v b ns. (Nesting1 Sing Applicative v)
=> Sing ns
-> (ElemB b -> ElemB b -> ElemB b)
-> (forall n. Sing n -> b ('BV n) -> b ('BV n) -> b ('BV n))
-> (forall n m. Sing ('BM n m) -> b ('BM n m) -> b ('BM n m) -> b ('BM n m))
-> BTensor v b ns
-> BTensor v b ns
-> BTensor v b ns
zipBase = \case
SNil -> \f _ _ -> \case
BTS x -> \case
BTS y -> BTS (f x y)
sN `SCons` SNil -> \_ g _ -> \case
BTV xs -> \case
BTV ys -> BTV (g sN xs ys)
sN `SCons` (sM `SCons` SNil) -> \_ _ h -> \case
BTM xs -> \case
BTM ys -> BTM (h (SBM sN sM) xs ys)
(s :: Sing k) `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f g h -> \case
BTN xs -> \case
BTN ys -> BTN $ zipBase ss f g h <$> xs <*> ys
\\ (nesting1 s :: Wit (Applicative (v k)))
{-# INLINE zipBase #-}
genBTensorA
:: forall k (b :: BShape k -> Type) v (ns :: [k]) f. (Applicative f, BLAS b, Vec v)
=> Sing ns
-> (Prod (IndexN k) ns -> f (ElemB b))
-> f (BTensor v b ns)
genBTensorA = \case
SNil -> \f ->
BTS <$> f Ø
sN `SCons` SNil -> \f ->
BTV <$> bgenA (SBV sN) (f . pbvProd)
sN `SCons` (sM `SCons` SNil) -> \f ->
BTM <$> bgenA (SBM sN sM) (f . pbmProd)
s `SCons` ss@(_ `SCons` (_ `SCons` _)) -> \f ->
BTN <$> vGenA s (\i -> genBTensorA ss (\is -> f (i :< is)))
{-# INLINE genBTensorA #-}
genBTensor
:: forall k (b :: BShape k -> Type) v (ns :: [k]). (BLAS b, Vec v)
=> Sing ns
-> (Prod (IndexN k) ns -> ElemB b)
-> BTensor v b ns
genBTensor s f = getI $ genBTensorA s (I . f)
{-# INLINE genBTensor #-}
indexBTensor
:: forall k (b :: BShape k -> Type) v ns. (BLAS b, Vec v)
=> Prod (IndexN k) ns
-> BTensor v b ns
-> ElemB b
indexBTensor = \case
Ø -> \case
BTS x -> x
i :< Ø -> \case
BTV xs -> indexB (PBV i) xs
i :< j :< Ø -> \case
BTM xs -> indexB (PBM i j) xs
i :< js@(_ :< _ :< _) -> \case
BTN xs -> indexBTensor js (vIndex i xs)
{-# INLINE indexBTensor #-}
btn :: (BLAS b, Vec v, SingI n)
=> Length ns
-> v n (BTensor v b ns)
-> BTensor v b (n ': ns)
btn = \case
LZ -> \xs ->
BTV $ bgen sing (unScalar . (`vIndex` xs) . unPBV)
LS LZ -> \xs ->
BTM $ bgenRows (unVector . (`vIndex` xs))
LS (LS _) -> BTN
{-# INLINE btn #-}
gmul'
:: forall v b ms os ns.
( SingI (ms ++ ns)
, RealFloat (ElemB b)
, Vec v
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
, BLAS b
)
=> Length ms
-> Length os
-> Length ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
gmul' lM lO lN = gmulB sM lO lN \\ sN
where
sM :: Sing ms
sN :: Sing ns
(sM, sN) = splitSing lM sing
{-# INLINE[0] gmul' #-}
{-# RULES
"gmul'/SS" gmul' = dispatchSS
"gmul'/SV" gmul' = dispatchSV
"gmul'/dot" gmul' = dispatchDot
"gmul'/VM" gmul' = dispatchVM
"gmul'/VS" gmul' = dispatchVS
"gmul'/out" gmul' = dispatchOut
"gmul'/MV" gmul' = dispatchMV
"gmul'/MM" gmul' = dispatchMM
#-}
-- | General strategy:
--
-- * We can only outsource to BLAS (using 'dispatchBLAS') in the case
-- that @os@ and @ns@ have length 0 or 1. Anything else, fall back to
-- the basic reverse-indexing method in "Data.Nested".
-- * If @ms@ is length 2 or higher, "traverse down" to the length 0 or
-- 1 tail...and then sum them up.
gmulB
:: forall k (b :: BShape k -> Type) v ms os ns.
( RealFloat (ElemB b)
, SingI ns
, BLAS b
, Vec v
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
)
=> Sing ms
-> Length os
-> Length ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
gmulB sM lO lN v r = case splitting (S_ Z_) (lengthProd lN) of
Fewer mlN _ -> case splittingEnd (S_ (S_ Z_)) (lengthProd lO) of
FewerEnd MLZ _ -> gmulBLAS sM MLZ mlN v r
FewerEnd (MLS MLZ) _ -> gmulBLAS sM (MLS MLZ) mlN v r
FewerEnd (MLS (MLS MLZ)) _ -> case mlN of
MLZ -> case r of
BTM ys -> mapBTM sM LZ (\xs -> BTS $ traceB (gemm 1 xs ys Nothing)) v
MLS MLZ -> naiveGMul sM lO lN v r
SplitEnd _ _ _ -> naiveGMul sM lO lN v r
Split _ _ _ -> naiveGMul sM lO lN v r
{-# INLINE[0] gmulB #-}
-- | Naive implementation of 'gmul' (based on the implementation for
-- 'NTensor') that does not utilize any BLAS capabilities.
naiveGMul
:: forall k (b :: BShape k -> Type) v ms os ns.
( BLAS b
, Vec v
, Num (ElemB b)
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
, SingI ns
)
=> Sing ms
-> Length os
-> Length ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
naiveGMul sM _ lN v r =
mapRowsBTensor sM lN (getSum . ifoldMapBTensor (\i -> Sum . f i)) v
where
f :: Prod (IndexN k) os
-> ElemB b
-> BTensor v b ns
f is x = mapBase sing
(x *)
(\_ ys -> scaleB x ys)
(\_ ys -> scaleB x ys)
(indexRowBTensor (TCP.reverse' is) r)
-- | A 'gmul' that runs my dispatching BLAS commands when it can.
-- Contains the type-level constraint that @os@ and @ns@ have to have
-- either length 0 or 1.
--
-- TODO: no longer needs Sing ms
gmulBLAS
:: forall b ms os ns v.
( RealFloat (ElemB b)
, BLAS b
, Vec v
, SingI ns
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
)
=> Sing ms
-> MaxLength N1 os
-> MaxLength N1 ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
gmulBLAS sM mlO mlN v r = case mlO of
MLZ -> case splittingEnd (S_ (S_ Z_)) spM of
FewerEnd MLZ _ -> dispatchBLAS MLZ mlO mlN v r
FewerEnd (MLS MLZ) _ -> dispatchBLAS (MLS MLZ) mlO mlN v r
FewerEnd (MLS (MLS MLZ)) _ -> case v of
BTM xs -> case mlN of
MLZ -> case r of
BTS y -> BTM $ scaleB y xs
-- TODO: can this be made non-naive?
-- ms ~ '[m1,m2]
-- os ~ '[]
-- ns ~ '[n]
MLS MLZ -> naiveGMul sM LZ (fromMaxLength mlN) v r
SplitEnd (ELS (ELS ELZ)) spM0 spM1 -> case mlN of
MLZ -> case r of
BTS y -> mapBTM (prodSing spM0)
(prodLength spM1)
(\xs -> BTM $ scaleB y xs)
v
\\ appendNil lM
-- TODO: can this be made non-naive?
-- ms ~ (ms0 ++ '[m1,m2])
-- os ~ '[]
-- ns ~ '[n]
MLS MLZ -> naiveGMul sM LZ (fromMaxLength mlN) v r
MLS MLZ -> case splittingEnd (S_ Z_) spM of
FewerEnd mlM _ -> dispatchBLAS mlM mlO mlN v r
SplitEnd (ELS ELZ) spM0 spM1 ->
let sM0 = prodSing spM0
lM0 = prodLength spM0
lM1 = prodLength spM1
in (\\ appendAssoc (TCL.tail' lM0)
lM1
(LS LZ :: Length os)
) $ case mlN of
MLZ -> case r of
BTV ys -> mapBTM sM0 lM1 (\xs -> BTV $ gemv 1 xs ys Nothing) v
\\ appendNil lM
MLS MLZ -> case r of
BTM ys -> mapBTM sM0
(lM1 `TCL.append'` (LS LZ :: Length ns))
(\xs -> BTM $ gemm 1 xs ys Nothing)
v
\\ appendAssoc (TCL.tail' lM0)
lM1
(LS LZ :: Length ns)
where
spM = singProd sM
lM = singLength sM
diagBTensor
:: forall k (b :: BShape k -> Type) v n ns.
( SingI (n ': ns)
, BLAS b
, Vec v
, Num (ElemB b)
, Eq (IndexN k n)
)
=> Uniform n ns
-> BTensor v b '[n]
-> BTensor v b (n ': ns)
diagBTensor = \case
UØ -> id
US UØ -> \case
BTV xs -> BTM $ diagB xs
u@(US (US _)) -> \(BTV xs) ->
genBTensor sing (\i -> case TCV.uniformVec (prodToVec I (US u) i) of
Nothing -> 0
Just (I i') -> indexB (PBV i') xs
)
{-# INLINE diagBTensor #-}
transpBTensor
:: (BLAS b, Vec v)
=> Sing ns
-> BTensor v b ns
-> BTensor v b (Reverse ns)
transpBTensor s = \case
BTS x -> BTS x
BTV xs -> BTV xs
BTM xs -> BTM $ transpB xs
xs@(BTN _) -> (\\ reverseReverse (singLength s)) $
genBTensor (sReverse s) $ \i ->
indexBTensor (TCP.reverse' i) xs
{-# INLINE transpBTensor #-}
sumBTensor
:: forall v b n ns.
( BLAS b
, Vec v
, Num (ElemB b)
, Foldable (v n)
, SingI ns
, SingI n
, Nesting1 Proxy Functor v
, Nesting1 Sing Applicative v
)
=> BTensor v b (n ': ns)
-> BTensor v b ns
sumBTensor = \case
BTV xs -> BTS $ sumB xs
BTM (xs :: b ('BM n m))
-> BTV $ gemv 1 (transpB xs)
(bgen (SBV (sing :: Sing n)) (\_ -> 1))
Nothing
BTN xs -> sum xs
instance
( Vec (v :: k -> Type -> Type)
, BLAS b
, RealFloat (ElemB b)
, Nesting1 Proxy Functor v
, Nesting1 Proxy Foldable v
, Nesting1 Sing Applicative v
, Nesting1 Sing Distributive v
, Eq1 (IndexN k)
)
=> Tensor (BTensor v b) where
type ElemT (BTensor v b) = ElemB b
liftT
:: SingI ns
=> (TCV.Vec n (ElemB b) -> ElemB b)
-> TCV.Vec n (BTensor v b ns)
-> BTensor v b ns
liftT = liftBTensor sing
{-# INLINE liftT #-}
sumT = sum'
{-# INLINE sumT #-}
scaleT α = mapBase sing (α*) (\_ -> scaleB α) (\_ -> scaleB α)
{-# INLINE scaleT #-}
gmul
:: forall ms os ns. SingI (ms ++ ns)
=> Length ms
-> Length os
-> Length ns
-> BTensor v b (ms ++ os)
-> BTensor v b (Reverse os ++ ns)
-> BTensor v b (ms ++ ns)
gmul = gmul'
{-# INLINE gmul #-}
diag
:: forall n ns. SingI (n ': ns)
=> Uniform n ns
-> BTensor v b '[n]
-> BTensor v b (n ': ns)
diag = diagBTensor
\\ (produceEq1 :: Eq1 (IndexN k) :- Eq (IndexN k n))
{-# INLINE diag #-}
getDiag
:: SingI n
=> Uniform n ns
-> BTensor v b (n ': n ': ns)
-> BTensor v b '[n]
getDiag = \case
UØ -> \case
BTM xs -> BTV $ getDiagB xs
u@(US _) -> \xs ->
genBTensor sing $ \(i :< Ø) ->
indexBTensor (TCP.replicate i (US (US u))) xs
{-# INLINE getDiag #-}
transp = transpBTensor sing
{-# INLINE transp #-}
generateA = genBTensorA sing
{-# INLINE generateA #-}
genRand d g = generateA (\_ -> realToFrac <$> genContVar d g)
{-# INLINE genRand #-}
ixRows
:: forall f ms os ns. (Applicative f, SingI (ms ++ os))
=> Length ms
-> Length os
-> (Prod (IndexN k) ms -> BTensor v b ns -> f (BTensor v b os))
-> BTensor v b (ms ++ ns)
-> f (BTensor v b (ms ++ os))
ixRows lM lO = bIxRows sM lO
where
sM :: Sing ms
sM = takeSing lM lO (sing :: Sing (ms ++ os))
{-# INLINE ixRows #-}
(!) = flip indexBTensor
{-# INLINE (!) #-}
sumRows
:: forall n ns. (SingI (n ': ns), SingI ns)
=> BTensor v b (n ': ns)
-> BTensor v b ns
sumRows = sumBTensor
\\ (nesting1 Proxy :: Wit (Foldable (v n)))
\\ sHead (sing :: Sing (n ': ns))
{-# INLINE sumRows #-}
mapRows :: forall ns ms. SingI (ns ++ ms)
=> Length ns
-> (BTensor v b ms -> BTensor v b ms)
-> BTensor v b (ns ++ ms)
-> BTensor v b (ns ++ ms)
mapRows l f = mapRowsBTensor sN (singLength sM) f
where
sN :: Sing ns
sM :: Sing ms
(sN, sM) = splitSing l (sing :: Sing (ns ++ ms))
{-# INLINE mapRows #-}
-- * Boring dispatches
dispatchSS
:: Num (ElemB b)
=> Length '[]
-> Length '[]
-> Length '[]
-> BTensor v b '[]
-> BTensor v b '[]
-> BTensor v b '[]
dispatchSS _ _ _ (BTS x) (BTS y) = BTS (x * y)
{-# INLINE dispatchSS #-}
dispatchSV
:: BLAS b
=> Length '[]
-> Length '[]
-> Length '[n]
-> BTensor v b '[]
-> BTensor v b '[n]
-> BTensor v b '[n]
dispatchSV _ _ _ (BTS x) (BTV y) = BTV $ axpy x y Nothing
{-# INLINE dispatchSV #-}
dispatchDot
:: BLAS b
=> Length '[]
-> Length '[n]
-> Length '[]
-> BTensor v b '[n]
-> BTensor v b '[n]
-> BTensor v b '[]
dispatchDot _ _ _ (BTV x) (BTV y) = BTS $ x `dot` y
{-# INLINE dispatchDot #-}
dispatchVM
:: (Num (ElemB b), BLAS b)
=> Length '[]
-> Length '[n]
-> Length '[m]
-> BTensor v b '[n]
-> BTensor v b '[n,m]
-> BTensor v b '[m]
dispatchVM _ _ _ (BTV x) (BTM y) = BTV $ gemv 1 (transpB y) x Nothing
{-# INLINE dispatchVM #-}
dispatchVS
:: BLAS b
=> Length '[n]
-> Length '[]
-> Length '[]
-> BTensor v b '[n]
-> BTensor v b '[]
-> BTensor v b '[n]
dispatchVS _ _ _ (BTV x) (BTS y) = BTV $ axpy y x Nothing
{-# INLINE dispatchVS #-}
dispatchOut
:: BLAS b
=> Length '[n]
-> Length '[]
-> Length '[m]
-> BTensor v b '[n]
-> BTensor v b '[m]
-> BTensor v b '[n,m]
dispatchOut _ _ _ (BTV x) (BTV y) = BTM $ ger x y
{-# INLINE dispatchOut #-}
dispatchMV
:: (Num (ElemB b), BLAS b)
=> Length '[n]
-> Length '[m]
-> Length '[]
-> BTensor v b '[n,m]
-> BTensor v b '[m]
-> BTensor v b '[n]
dispatchMV _ _ _ (BTM x) (BTV y) = BTV $ gemv 1 x y Nothing
{-# INLINE dispatchMV #-}
dispatchMM
:: (Num (ElemB b), BLAS b)
=> Length '[m]
-> Length '[o]
-> Length '[n]
-> BTensor v b '[m,o]
-> BTensor v b '[o,n]
-> BTensor v b '[m,n]
dispatchMM _ _ _ (BTM x) (BTM y) = BTM $ gemm 1 x y Nothing
{-# INLINE dispatchMM #-}
|
mstksg/tensor-ops
|
src/TensorOps/Backend/BTensor.hs
|
Haskell
|
bsd-3-clause
| 30,700
|
-- | this module contains the defs of common data types and type classes
module Text.Regex.Deriv.Common
( Range(..), range, minRange, maxRange
, Letter
, PosEpsilon (..)
, IsEpsilon (..)
, IsPhi (..)
, Simplifiable (..)
, myHash
, myLookup
, GFlag (..)
, IsGreedy (..)
, nub2
, nub3
, preBinder
, preBinder_
, subBinder
, mainBinder
) where
import Data.Char (ord)
import qualified Data.IntMap as IM
-- | (sub)words represent by range
-- type Range = (Int,Int)
data Range = Range !Int !Int deriving (Show, Ord)
instance Eq Range where
(==) (Range x y) (Range w z) = (x == w) && (y == z)
range :: Int -> Int -> Range
range = Range
minRange :: (Int, Int) -> Int
minRange = fst
maxRange :: (Int, Int) -> Int
maxRange = snd
-- | a character and its index (position)
type Letter = (Char,Int)
-- | test for 'epsilon \in a' epsilon-possession
class PosEpsilon a where
posEpsilon :: a -> Bool
-- | test for epsilon == a
class IsEpsilon a where
isEpsilon :: a -> Bool
-- | test for \phi == a
class IsPhi a where
isPhi :: a -> Bool
class Simplifiable a where
simplify :: a -> a
myHash :: Int -> Char -> Int
myHash i x = ord x + 256 * i
-- the lookup function
myLookup :: Int -> Char -> IM.IntMap [Int] -> [Int]
myLookup i x dict = case IM.lookup (myHash i x) dict of
Just ys -> ys
Nothing -> []
-- | The greediness flag
data GFlag = Greedy -- ^ greedy
| NotGreedy -- ^ not greedy
deriving (Eq,Ord)
instance Show GFlag where
show Greedy = ""
show NotGreedy = "?"
class IsGreedy a where
isGreedy :: a -> Bool
-- remove duplications in a list of pairs, using the first components as key.
nub2 :: [(Int,a)] -> [(Int,a)]
nub2 [] = []
nub2 [x] = [x]
nub2 ls = nub2sub IM.empty ls
nub2sub :: IM.IntMap () -> [(IM.Key, t)] -> [(IM.Key, t)]
nub2sub _ [] = []
nub2sub im (x@(k,_):xs) =
case IM.lookup k im of
Just _ -> xs `seq` nub2sub im xs
Nothing -> let im' = IM.insert k () im
in im' `seq` xs `seq` x:nub2sub im' xs
nub3 :: [(Int,a,Int)] -> [(Int,a,Int)]
nub3 [] = []
nub3 [x] = [x]
nub3 ls = nub3subsimple IM.empty ls
nub3subsimple :: IM.IntMap () -> [(Int,a,Int)] -> [(Int,a,Int)]
nub3subsimple _ [] = []
nub3subsimple _ [ x ] = [ x ]
nub3subsimple im (x@(_,_,0):xs) = x:(nub3subsimple im xs)
nub3subsimple im (x@(k,_,1):xs) = let im' = IM.insert k () im
in im' `seq` x:(nub3subsimple im' xs)
nub3subsimple im (x@(k,_,_):xs) = case IM.lookup k im of
Just _ -> nub3subsimple im xs
Nothing -> let im' = IM.insert k () im
in im' `seq` xs `seq` x:(nub3subsimple im' xs)
-- The smallest binder index capturing the prefix of the unanchored regex
preBinder :: Int
preBinder = -1
preBinder_ :: Int
preBinder_ = -2
-- The largest binder index capturing for the suffix of the unanchored regex
subBinder :: Int
subBinder = 2147483647
-- The binder index capturing substring which matches by the unanchored regex
mainBinder :: Int
mainBinder = 0
|
awalterschulze/xhaskell-regex-deriv
|
Text/Regex/Deriv/Common.hs
|
Haskell
|
bsd-3-clause
| 3,221
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module State6502 where
import Data.Word
import Deque
import Data.Array
import Data.Time.Clock
import Control.Lens
import Control.Monad.State
import Data.Bits.Lens
import System.Console.Haskeline
import Data.Array.IO
import qualified Data.IntMap as M
import System.IO
import Data.ByteString as B
import FileSystems
data Registers = R {
_pc :: !Word16,
_p :: !Word8,
_a :: !Word8,
_x :: !Word8,
_y :: !Word8,
_s :: !Word8
}
makeLenses ''Registers
{-# INLINE flagC #-}
flagC :: Lens' Registers Bool
flagC = p . bitAt 0
{-# INLINE flagZ #-}
flagZ :: Lens' Registers Bool
flagZ = p . bitAt 1
{-# INLINE flagI #-}
flagI :: Lens' Registers Bool
flagI = p . bitAt 2
{-# INLINE flagD #-}
flagD :: Lens' Registers Bool
flagD = p . bitAt 3
{-# INLINE flagB #-}
flagB :: Lens' Registers Bool
flagB = p . bitAt 4
{-# INLINE flagV #-}
flagV :: Lens' Registers Bool
flagV = p . bitAt 6
{-# INLINE flagN #-}
flagN :: Lens' Registers Bool
flagN = p . bitAt 7
data KeyInput = KeyInput {
buffer :: Deque Word8,
keydefs :: Array Int [Word8]
}
data VDUOutput = VDUOutput {
vbuffer :: [Word8],
requiredChars :: Int
}
data State6502 = S {
_mem :: IOUArray Int Word8,
_clock :: !Int,
_regs :: !Registers,
_debug :: !Bool,
_currentDirectory :: Char,
_sysclock :: !UTCTime,
_handles :: M.IntMap VHandle,
_keyQueue :: KeyInput,
_vduQueue :: VDUOutput,
_logFile :: Maybe Handle
}
makeLenses ''State6502
|
dpiponi/Bine
|
src/State6502.hs
|
Haskell
|
bsd-3-clause
| 1,646
|
{-# 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.ContentProvider_Client(downloadMesh) where
import Data.IORef
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 Thrift.ContentProvider
seqid = newIORef 0
downloadMesh (ip,op) arg_name = do
send_downloadMesh op arg_name
recv_downloadMesh ip
send_downloadMesh op arg_name = do
seq <- seqid
seqn <- readIORef seq
writeMessageBegin op ("downloadMesh", M_CALL, seqn)
write_DownloadMesh_args op (DownloadMesh_args{f_DownloadMesh_args_name=Just arg_name})
writeMessageEnd op
tFlush (getTransport op)
recv_downloadMesh ip = do
(fname, mtype, rseqid) <- readMessageBegin ip
if mtype == M_EXCEPTION then do
x <- readAppExn ip
readMessageEnd ip
throw x
else return ()
res <- read_DownloadMesh_result ip
readMessageEnd ip
case f_DownloadMesh_result_success res of
Just v -> return v
Nothing -> do
throw (AppExn AE_MISSING_RESULT "downloadMesh failed: unknown result")
|
csabahruska/GFXDemo
|
Thrift/ContentProvider_Client.hs
|
Haskell
|
bsd-3-clause
| 1,913
|
{-# Language ScopedTypeVariables #-}
{-# Language DeriveGeneric #-}
{-# Language DeriveDataTypeable #-}
module StateManager where
import Control.Distributed.Process
import Control.Monad (filterM)
import Control.Monad.Trans.State.Strict
import Control.Monad.Trans.Class (lift)
import Data.Binary (Binary)
import Data.Map as Map
import Data.Maybe
import Data.Typeable
import GHC.Generics
import Task
type TaskState = Map.Map TaskId TaskResult
type StateProcess = StateT TaskState Process
data StateReq
= Finish (TaskId, TaskResult)
| CheckDeps (ProcessId, [TaskId])
deriving (Show, Generic, Typeable)
instance Binary StateReq
isFinished :: TaskId -> StateProcess Bool
isFinished tid = do
taskState <- get
return (isJust $ Map.lookup tid taskState)
updateState :: TaskId -> TaskResult -> StateProcess ()
updateState tid res = modify $ \s -> insert tid res s
stateManager :: Process ()
stateManager = do
say "starting state manager"
evalStateT stateProc Map.empty
where
stateProc :: StateProcess ()
stateProc = do
(req :: StateReq) <- lift expect
case req of
Finish (tid, res) -> updateState tid res
CheckDeps (pid, deps) -> do
numFinished <- filterM isFinished deps
lift $ send pid (length numFinished == length deps)
stateProc
|
sgeop/side-batch
|
src/StateManager.hs
|
Haskell
|
bsd-3-clause
| 1,333
|
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Cardano.Wallet.API.Indices (
module Cardano.Wallet.API.Indices
-- * Re-exports from IxSet for convenience
-- (these were previously /defined/ in this module)
, IndicesOf
, IxSet
, Indexable
, IsIndexOf
) where
import Universum
import Cardano.Wallet.API.V1.Types
import qualified Data.Text as T
import GHC.TypeLits
import qualified Pos.Chain.Txp as Txp
import qualified Pos.Core as Core
import Pos.Crypto (decodeHash)
import Cardano.Wallet.Kernel.DB.Util.IxSet (HasPrimKey (..),
Indexable, IndicesOf, IsIndexOf, IxSet, OrdByPrimKey,
ixFun, ixList)
import qualified Data.IxSet.Typed as IxSet
-- | 'ToIndex' represents the witness that we can build an index 'ix' for a resource 'a'
-- from an input 'Text'.
class ToIndex a ix where
-- | How to build this index from the input 'Text'.
toIndex :: Proxy a -> Text -> Maybe ix
-- | How to access this index from the input data.
accessIx :: (a -> ix)
instance ToIndex Wallet WalletId where
toIndex _ x = Just (WalletId x)
accessIx Wallet{..} = walId
instance ToIndex Wallet Core.Coin where
toIndex _ x = case readMaybe (T.unpack x) of
Nothing -> Nothing
Just c | c > Core.maxCoinVal -> Nothing
Just c -> Just (Core.mkCoin c)
accessIx Wallet{..} = let (V1 balance) = walBalance in balance
instance ToIndex Wallet (V1 Core.Timestamp) where
toIndex _ = fmap V1 . Core.parseTimestamp
accessIx = walCreatedAt
instance ToIndex Transaction (V1 Txp.TxId) where
toIndex _ = fmap V1 . rightToMaybe . decodeHash
accessIx Transaction{..} = txId
instance ToIndex Transaction (V1 Core.Timestamp) where
toIndex _ = fmap V1 . Core.parseTimestamp
accessIx Transaction{..} = txCreationTime
instance ToIndex WalletAddress (V1 Core.Address) where
toIndex _ = fmap V1 . either (const Nothing) Just . Core.decodeTextAddress
accessIx WalletAddress{..} = addrId
--
-- Primary and secondary indices for V1 types
--
instance HasPrimKey Wallet where
type PrimKey Wallet = WalletId
primKey = walId
instance HasPrimKey Account where
type PrimKey Account = AccountIndex
primKey = accIndex
instance HasPrimKey Transaction where
type PrimKey Transaction = V1 Txp.TxId
primKey = txId
instance HasPrimKey WalletAddress where
type PrimKey WalletAddress = V1 Core.Address
primKey = addrId
-- | The secondary indices for each major resource.
type SecondaryWalletIxs = '[Core.Coin, V1 Core.Timestamp]
type SecondaryTransactionIxs = '[V1 Core.Timestamp]
type SecondaryAccountIxs = '[]
type SecondaryWalletAddressIxs = '[]
type instance IndicesOf Wallet = SecondaryWalletIxs
type instance IndicesOf Account = SecondaryAccountIxs
type instance IndicesOf Transaction = SecondaryTransactionIxs
type instance IndicesOf WalletAddress = SecondaryWalletAddressIxs
--
-- Indexable instances for V1 types
--
-- TODO [CBR-356] These should not exist! We should not create 'IxSet's
-- (with their indices) on the fly. Fortunately, the only one for which this
-- is /really/ important is addresses, for which we already have special
-- cases. Nonetheless, the instances below should also go.
--
-- Instance for 'WalletAddress' is available only in
-- "Cardano.Wallet.API.V1.LegacyHandlers.Instances". The same should be done
-- for the other instances here.
--
instance IxSet.Indexable (WalletId ': SecondaryWalletIxs)
(OrdByPrimKey Wallet) where
indices = ixList (ixFun ((:[]) . unV1 . walBalance))
(ixFun ((:[]) . walCreatedAt))
instance IxSet.Indexable (V1 Txp.TxId ': SecondaryTransactionIxs)
(OrdByPrimKey Transaction) where
indices = ixList (ixFun (\Transaction{..} -> [txCreationTime]))
instance IxSet.Indexable (AccountIndex ': SecondaryAccountIxs)
(OrdByPrimKey Account) where
indices = ixList
-- | Extract the parameter names from a type leve list with the shape
type family ParamNames res xs where
ParamNames res '[] =
'[]
ParamNames res (ty ': xs) =
IndexToQueryParam res ty ': ParamNames res xs
-- | This type family allows you to recover the query parameter if you know
-- the resource and index into that resource.
type family IndexToQueryParam resource ix where
IndexToQueryParam Account AccountIndex = "id"
IndexToQueryParam Wallet Core.Coin = "balance"
IndexToQueryParam Wallet WalletId = "id"
IndexToQueryParam Wallet (V1 Core.Timestamp) = "created_at"
IndexToQueryParam WalletAddress (V1 Core.Address) = "address"
IndexToQueryParam Transaction (V1 Txp.TxId) = "id"
IndexToQueryParam Transaction (V1 Core.Timestamp) = "created_at"
-- This is the fallback case. It will trigger a type error if you use
-- 'IndexToQueryParam'' with a pairing that is invalid. We want this to
-- trigger early, so that we don't get Weird Errors later on with stuck
-- types.
IndexToQueryParam res ix = TypeError (
'Text "You used `IndexToQueryParam' with the following resource:"
':$$: 'Text " " ':<>: 'ShowType res
':$$: 'Text "and index type:"
':$$: 'Text " " ':<>: 'ShowType ix
':$$: 'Text "But no instance for that type was defined."
':$$: 'Text "Perhaps you mismatched a resource and an index?"
':$$: 'Text "Or, maybe you need to add a type instance to `IndexToQueryParam'."
)
-- | Type-level composition of 'KnownSymbol' and 'IndexToQueryParam'
--
-- TODO: Alternatively, it would be possible to get rid of 'IndexToQueryParam'
-- completely and just have the 'KnownQueryParam' class.
class KnownSymbol (IndexToQueryParam resource ix) => KnownQueryParam resource ix
instance KnownQueryParam Account AccountIndex
instance KnownQueryParam Wallet Core.Coin
instance KnownQueryParam Wallet WalletId
instance KnownQueryParam Wallet (V1 Core.Timestamp)
instance KnownQueryParam WalletAddress (V1 Core.Address)
instance KnownQueryParam Transaction (V1 Txp.TxId)
instance KnownQueryParam Transaction (V1 Core.Timestamp)
|
input-output-hk/pos-haskell-prototype
|
wallet/src/Cardano/Wallet/API/Indices.hs
|
Haskell
|
mit
| 6,558
|
-----------------------------------------------------------------------------
-- |
-- Module : Control.Monad.Indexed.Fix
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : portable
--
----------------------------------------------------------------------------
module Control.Monad.Indexed.Fix
( IxMonadFix(..)
) where
import Control.Monad.Indexed
class IxMonad m => IxMonadFix m where
imfix :: (a -> m i i a) -> m i i a
|
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
|
Control/Monad/Indexed/Fix.hs
|
Haskell
|
apache-2.0
| 575
|
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "src/Data/Foldable/Compat.hs" #-}
{-# LANGUAGE CPP, NoImplicitPrelude #-}
module Data.Foldable.Compat (
module Base
, maximumBy
, minimumBy
) where
import Data.Foldable as Base hiding (maximumBy, minimumBy)
import Prelude (Ordering(..))
-- | The largest element of a non-empty structure with respect to the
-- given comparison function.
maximumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
maximumBy cmp = foldl1 max'
where max' x y = case cmp x y of
GT -> x
_ -> y
-- | The least element of a non-empty structure with respect to the
-- given comparison function.
minimumBy :: Foldable t => (a -> a -> Ordering) -> t a -> a
minimumBy cmp = foldl1 min'
where min' x y = case cmp x y of
GT -> y
_ -> x
|
phischu/fragnix
|
tests/packages/scotty/Data.Foldable.Compat.hs
|
Haskell
|
bsd-3-clause
| 902
|
{-
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
\section[PrimOp]{Primitive operations (machine-level)}
-}
{-# LANGUAGE CPP #-}
module PrimOp (
PrimOp(..), PrimOpVecCat(..), allThePrimOps,
primOpType, primOpSig,
primOpTag, maxPrimOpTag, primOpOcc,
tagToEnumKey,
primOpOutOfLine, primOpCodeSize,
primOpOkForSpeculation, primOpOkForSideEffects,
primOpIsCheap, primOpFixity,
getPrimOpResultInfo, PrimOpResultInfo(..),
PrimCall(..)
) where
#include "HsVersions.h"
import TysPrim
import TysWiredIn
import CmmType
import Demand
import Var ( TyVar )
import OccName ( OccName, pprOccName, mkVarOccFS )
import TyCon ( TyCon, isPrimTyCon, tyConPrimRep, PrimRep(..) )
import Type ( Type, mkForAllTys, mkFunTy, mkFunTys, tyConAppTyCon,
typePrimRep )
import BasicTypes ( Arity, Fixity(..), FixityDirection(..), Boxity(..) )
import ForeignCall ( CLabelString )
import Unique ( Unique, mkPrimOpIdUnique )
import Outputable
import FastString
import Module ( UnitId )
{-
************************************************************************
* *
\subsection[PrimOp-datatype]{Datatype for @PrimOp@ (an enumeration)}
* *
************************************************************************
These are in \tr{state-interface.verb} order.
-}
-- supplies:
-- data PrimOp = ...
#include "primop-data-decl.hs-incl"
-- supplies
-- primOpTag :: PrimOp -> Int
#include "primop-tag.hs-incl"
primOpTag _ = error "primOpTag: unknown primop"
instance Eq PrimOp where
op1 == op2 = primOpTag op1 == primOpTag op2
instance Ord PrimOp where
op1 < op2 = primOpTag op1 < primOpTag op2
op1 <= op2 = primOpTag op1 <= primOpTag op2
op1 >= op2 = primOpTag op1 >= primOpTag op2
op1 > op2 = primOpTag op1 > primOpTag op2
op1 `compare` op2 | op1 < op2 = LT
| op1 == op2 = EQ
| otherwise = GT
instance Outputable PrimOp where
ppr op = pprPrimOp op
data PrimOpVecCat = IntVec
| WordVec
| FloatVec
-- An @Enum@-derived list would be better; meanwhile... (ToDo)
allThePrimOps :: [PrimOp]
allThePrimOps =
#include "primop-list.hs-incl"
tagToEnumKey :: Unique
tagToEnumKey = mkPrimOpIdUnique (primOpTag TagToEnumOp)
{-
************************************************************************
* *
\subsection[PrimOp-info]{The essential info about each @PrimOp@}
* *
************************************************************************
The @String@ in the @PrimOpInfos@ is the ``base name'' by which the user may
refer to the primitive operation. The conventional \tr{#}-for-
unboxed ops is added on later.
The reason for the funny characters in the names is so we do not
interfere with the programmer's Haskell name spaces.
We use @PrimKinds@ for the ``type'' information, because they're
(slightly) more convenient to use than @TyCons@.
-}
data PrimOpInfo
= Dyadic OccName -- string :: T -> T -> T
Type
| Monadic OccName -- string :: T -> T
Type
| Compare OccName -- string :: T -> T -> Int#
Type
| GenPrimOp OccName -- string :: \/a1..an . T1 -> .. -> Tk -> T
[TyVar]
[Type]
Type
mkDyadic, mkMonadic, mkCompare :: FastString -> Type -> PrimOpInfo
mkDyadic str ty = Dyadic (mkVarOccFS str) ty
mkMonadic str ty = Monadic (mkVarOccFS str) ty
mkCompare str ty = Compare (mkVarOccFS str) ty
mkGenPrimOp :: FastString -> [TyVar] -> [Type] -> Type -> PrimOpInfo
mkGenPrimOp str tvs tys ty = GenPrimOp (mkVarOccFS str) tvs tys ty
{-
************************************************************************
* *
\subsubsection{Strictness}
* *
************************************************************************
Not all primops are strict!
-}
primOpStrictness :: PrimOp -> Arity -> StrictSig
-- See Demand.StrictnessInfo for discussion of what the results
-- The arity should be the arity of the primop; that's why
-- this function isn't exported.
#include "primop-strictness.hs-incl"
{-
************************************************************************
* *
\subsubsection{Fixity}
* *
************************************************************************
-}
primOpFixity :: PrimOp -> Maybe Fixity
#include "primop-fixity.hs-incl"
{-
************************************************************************
* *
\subsubsection[PrimOp-comparison]{PrimOpInfo basic comparison ops}
* *
************************************************************************
@primOpInfo@ gives all essential information (from which everything
else, notably a type, can be constructed) for each @PrimOp@.
-}
primOpInfo :: PrimOp -> PrimOpInfo
#include "primop-primop-info.hs-incl"
primOpInfo _ = error "primOpInfo: unknown primop"
{-
Here are a load of comments from the old primOp info:
A @Word#@ is an unsigned @Int#@.
@decodeFloat#@ is given w/ Integer-stuff (it's similar).
@decodeDouble#@ is given w/ Integer-stuff (it's similar).
Decoding of floating-point numbers is sorta Integer-related. Encoding
is done with plain ccalls now (see PrelNumExtra.hs).
A @Weak@ Pointer is created by the @mkWeak#@ primitive:
mkWeak# :: k -> v -> f -> State# RealWorld
-> (# State# RealWorld, Weak# v #)
In practice, you'll use the higher-level
data Weak v = Weak# v
mkWeak :: k -> v -> IO () -> IO (Weak v)
The following operation dereferences a weak pointer. The weak pointer
may have been finalized, so the operation returns a result code which
must be inspected before looking at the dereferenced value.
deRefWeak# :: Weak# v -> State# RealWorld ->
(# State# RealWorld, v, Int# #)
Only look at v if the Int# returned is /= 0 !!
The higher-level op is
deRefWeak :: Weak v -> IO (Maybe v)
Weak pointers can be finalized early by using the finalize# operation:
finalizeWeak# :: Weak# v -> State# RealWorld ->
(# State# RealWorld, Int#, IO () #)
The Int# returned is either
0 if the weak pointer has already been finalized, or it has no
finalizer (the third component is then invalid).
1 if the weak pointer is still alive, with the finalizer returned
as the third component.
A {\em stable name/pointer} is an index into a table of stable name
entries. Since the garbage collector is told about stable pointers,
it is safe to pass a stable pointer to external systems such as C
routines.
\begin{verbatim}
makeStablePtr# :: a -> State# RealWorld -> (# State# RealWorld, StablePtr# a #)
freeStablePtr :: StablePtr# a -> State# RealWorld -> State# RealWorld
deRefStablePtr# :: StablePtr# a -> State# RealWorld -> (# State# RealWorld, a #)
eqStablePtr# :: StablePtr# a -> StablePtr# a -> Int#
\end{verbatim}
It may seem a bit surprising that @makeStablePtr#@ is a @IO@
operation since it doesn't (directly) involve IO operations. The
reason is that if some optimisation pass decided to duplicate calls to
@makeStablePtr#@ and we only pass one of the stable pointers over, a
massive space leak can result. Putting it into the IO monad
prevents this. (Another reason for putting them in a monad is to
ensure correct sequencing wrt the side-effecting @freeStablePtr@
operation.)
An important property of stable pointers is that if you call
makeStablePtr# twice on the same object you get the same stable
pointer back.
Note that we can implement @freeStablePtr#@ using @_ccall_@ (and,
besides, it's not likely to be used from Haskell) so it's not a
primop.
Question: Why @RealWorld@ - won't any instance of @_ST@ do the job? [ADR]
Stable Names
~~~~~~~~~~~~
A stable name is like a stable pointer, but with three important differences:
(a) You can't deRef one to get back to the original object.
(b) You can convert one to an Int.
(c) You don't need to 'freeStableName'
The existence of a stable name doesn't guarantee to keep the object it
points to alive (unlike a stable pointer), hence (a).
Invariants:
(a) makeStableName always returns the same value for a given
object (same as stable pointers).
(b) if two stable names are equal, it implies that the objects
from which they were created were the same.
(c) stableNameToInt always returns the same Int for a given
stable name.
These primops are pretty weird.
dataToTag# :: a -> Int (arg must be an evaluated data type)
tagToEnum# :: Int -> a (result type must be an enumerated type)
The constraints aren't currently checked by the front end, but the
code generator will fall over if they aren't satisfied.
************************************************************************
* *
Which PrimOps are out-of-line
* *
************************************************************************
Some PrimOps need to be called out-of-line because they either need to
perform a heap check or they block.
-}
primOpOutOfLine :: PrimOp -> Bool
#include "primop-out-of-line.hs-incl"
{-
************************************************************************
* *
Failure and side effects
* *
************************************************************************
Note [PrimOp can_fail and has_side_effects]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Both can_fail and has_side_effects mean that the primop has
some effect that is not captured entirely by its result value.
---------- has_side_effects ---------------------
A primop "has_side_effects" if it has some *write* effect, visible
elsewhere
- writing to the world (I/O)
- writing to a mutable data structure (writeIORef)
- throwing a synchronous Haskell exception
Often such primops have a type like
State -> input -> (State, output)
so the state token guarantees ordering. In general we rely *only* on
data dependencies of the state token to enforce write-effect ordering
* NB1: if you inline unsafePerformIO, you may end up with
side-effecting ops whose 'state' output is discarded.
And programmers may do that by hand; see Trac #9390.
That is why we (conservatively) do not discard write-effecting
primops even if both their state and result is discarded.
* NB2: We consider primops, such as raiseIO#, that can raise a
(Haskell) synchronous exception to "have_side_effects" but not
"can_fail". We must be careful about not discarding such things;
see the paper "A semantics for imprecise exceptions".
* NB3: *Read* effects (like reading an IORef) don't count here,
because it doesn't matter if we don't do them, or do them more than
once. *Sequencing* is maintained by the data dependency of the state
token.
---------- can_fail ----------------------------
A primop "can_fail" if it can fail with an *unchecked* exception on
some elements of its input domain. Main examples:
division (fails on zero demoninator)
array indexing (fails if the index is out of bounds)
An "unchecked exception" is one that is an outright error, (not
turned into a Haskell exception,) such as seg-fault or
divide-by-zero error. Such can_fail primops are ALWAYS surrounded
with a test that checks for the bad cases, but we need to be
very careful about code motion that might move it out of
the scope of the test.
Note [Transformations affected by can_fail and has_side_effects]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The can_fail and has_side_effects properties have the following effect
on program transformations. Summary table is followed by details.
can_fail has_side_effects
Discard NO NO
Float in YES YES
Float out NO NO
Duplicate YES NO
* Discarding. case (a `op` b) of _ -> rhs ===> rhs
You should not discard a has_side_effects primop; e.g.
case (writeIntArray# a i v s of (# _, _ #) -> True
Arguably you should be able to discard this, since the
returned stat token is not used, but that relies on NEVER
inlining unsafePerformIO, and programmers sometimes write
this kind of stuff by hand (Trac #9390). So we (conservatively)
never discard a has_side_effects primop.
However, it's fine to discard a can_fail primop. For example
case (indexIntArray# a i) of _ -> True
We can discard indexIntArray#; it has can_fail, but not
has_side_effects; see Trac #5658 which was all about this.
Notice that indexIntArray# is (in a more general handling of
effects) read effect, but we don't care about that here, and
treat read effects as *not* has_side_effects.
Similarly (a `/#` b) can be discarded. It can seg-fault or
cause a hardware exception, but not a synchronous Haskell
exception.
Synchronous Haskell exceptions, e.g. from raiseIO#, are treated
as has_side_effects and hence are not discarded.
* Float in. You can float a can_fail or has_side_effects primop
*inwards*, but not inside a lambda (see Duplication below).
* Float out. You must not float a can_fail primop *outwards* lest
you escape the dynamic scope of the test. Example:
case d ># 0# of
True -> case x /# d of r -> r +# 1
False -> 0
Here we must not float the case outwards to give
case x/# d of r ->
case d ># 0# of
True -> r +# 1
False -> 0
Nor can you float out a has_side_effects primop. For example:
if blah then case writeMutVar# v True s0 of (# s1 #) -> s1
else s0
Notice that s0 is mentioned in both branches of the 'if', but
only one of these two will actually be consumed. But if we
float out to
case writeMutVar# v True s0 of (# s1 #) ->
if blah then s1 else s0
the writeMutVar will be performed in both branches, which is
utterly wrong.
* Duplication. You cannot duplicate a has_side_effect primop. You
might wonder how this can occur given the state token threading, but
just look at Control.Monad.ST.Lazy.Imp.strictToLazy! We get
something like this
p = case readMutVar# s v of
(# s', r #) -> (S# s', r)
s' = case p of (s', r) -> s'
r = case p of (s', r) -> r
(All these bindings are boxed.) If we inline p at its two call
sites, we get a catastrophe: because the read is performed once when
s' is demanded, and once when 'r' is demanded, which may be much
later. Utterly wrong. Trac #3207 is real example of this happening.
However, it's fine to duplicate a can_fail primop. That is really
the only difference between can_fail and has_side_effects.
Note [Implementation: how can_fail/has_side_effects affect transformations]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
How do we ensure that that floating/duplication/discarding are done right
in the simplifier?
Two main predicates on primpops test these flags:
primOpOkForSideEffects <=> not has_side_effects
primOpOkForSpeculation <=> not (has_side_effects || can_fail)
* The "no-float-out" thing is achieved by ensuring that we never
let-bind a can_fail or has_side_effects primop. The RHS of a
let-binding (which can float in and out freely) satisfies
exprOkForSpeculation; this is the let/app invariant. And
exprOkForSpeculation is false of can_fail and has_side_effects.
* So can_fail and has_side_effects primops will appear only as the
scrutinees of cases, and that's why the FloatIn pass is capable
of floating case bindings inwards.
* The no-duplicate thing is done via primOpIsCheap, by making
has_side_effects things (very very very) not-cheap!
-}
primOpHasSideEffects :: PrimOp -> Bool
#include "primop-has-side-effects.hs-incl"
primOpCanFail :: PrimOp -> Bool
#include "primop-can-fail.hs-incl"
primOpOkForSpeculation :: PrimOp -> Bool
-- See Note [PrimOp can_fail and has_side_effects]
-- See comments with CoreUtils.exprOkForSpeculation
-- primOpOkForSpeculation => primOpOkForSideEffects
primOpOkForSpeculation op
= primOpOkForSideEffects op
&& not (primOpOutOfLine op || primOpCanFail op)
-- I think the "out of line" test is because out of line things can
-- be expensive (eg sine, cosine), and so we may not want to speculate them
primOpOkForSideEffects :: PrimOp -> Bool
primOpOkForSideEffects op
= not (primOpHasSideEffects op)
{-
Note [primOpIsCheap]
~~~~~~~~~~~~~~~~~~~~
@primOpIsCheap@, as used in \tr{SimplUtils.hs}. For now (HACK
WARNING), we just borrow some other predicates for a
what-should-be-good-enough test. "Cheap" means willing to call it more
than once, and/or push it inside a lambda. The latter could change the
behaviour of 'seq' for primops that can fail, so we don't treat them as cheap.
-}
primOpIsCheap :: PrimOp -> Bool
-- See Note [PrimOp can_fail and has_side_effects]
primOpIsCheap op = primOpOkForSpeculation op
-- In March 2001, we changed this to
-- primOpIsCheap op = False
-- thereby making *no* primops seem cheap. But this killed eta
-- expansion on case (x ==# y) of True -> \s -> ...
-- which is bad. In particular a loop like
-- doLoop n = loop 0
-- where
-- loop i | i == n = return ()
-- | otherwise = bar i >> loop (i+1)
-- allocated a closure every time round because it doesn't eta expand.
--
-- The problem that originally gave rise to the change was
-- let x = a +# b *# c in x +# x
-- were we don't want to inline x. But primopIsCheap doesn't control
-- that (it's exprIsDupable that does) so the problem doesn't occur
-- even if primOpIsCheap sometimes says 'True'.
{-
************************************************************************
* *
PrimOp code size
* *
************************************************************************
primOpCodeSize
~~~~~~~~~~~~~~
Gives an indication of the code size of a primop, for the purposes of
calculating unfolding sizes; see CoreUnfold.sizeExpr.
-}
primOpCodeSize :: PrimOp -> Int
#include "primop-code-size.hs-incl"
primOpCodeSizeDefault :: Int
primOpCodeSizeDefault = 1
-- CoreUnfold.primOpSize already takes into account primOpOutOfLine
-- and adds some further costs for the args in that case.
primOpCodeSizeForeignCall :: Int
primOpCodeSizeForeignCall = 4
{-
************************************************************************
* *
PrimOp types
* *
************************************************************************
-}
primOpType :: PrimOp -> Type -- you may want to use primOpSig instead
primOpType op
= case primOpInfo op of
Dyadic _occ ty -> dyadic_fun_ty ty
Monadic _occ ty -> monadic_fun_ty ty
Compare _occ ty -> compare_fun_ty ty
GenPrimOp _occ tyvars arg_tys res_ty ->
mkForAllTys tyvars (mkFunTys arg_tys res_ty)
primOpOcc :: PrimOp -> OccName
primOpOcc op = case primOpInfo op of
Dyadic occ _ -> occ
Monadic occ _ -> occ
Compare occ _ -> occ
GenPrimOp occ _ _ _ -> occ
-- primOpSig is like primOpType but gives the result split apart:
-- (type variables, argument types, result type)
-- It also gives arity, strictness info
primOpSig :: PrimOp -> ([TyVar], [Type], Type, Arity, StrictSig)
primOpSig op
= (tyvars, arg_tys, res_ty, arity, primOpStrictness op arity)
where
arity = length arg_tys
(tyvars, arg_tys, res_ty)
= case (primOpInfo op) of
Monadic _occ ty -> ([], [ty], ty )
Dyadic _occ ty -> ([], [ty,ty], ty )
Compare _occ ty -> ([], [ty,ty], intPrimTy)
GenPrimOp _occ tyvars arg_tys res_ty -> (tyvars, arg_tys, res_ty )
data PrimOpResultInfo
= ReturnsPrim PrimRep
| ReturnsAlg TyCon
-- Some PrimOps need not return a manifest primitive or algebraic value
-- (i.e. they might return a polymorphic value). These PrimOps *must*
-- be out of line, or the code generator won't work.
getPrimOpResultInfo :: PrimOp -> PrimOpResultInfo
getPrimOpResultInfo op
= case (primOpInfo op) of
Dyadic _ ty -> ReturnsPrim (typePrimRep ty)
Monadic _ ty -> ReturnsPrim (typePrimRep ty)
Compare _ _ -> ReturnsPrim (tyConPrimRep intPrimTyCon)
GenPrimOp _ _ _ ty | isPrimTyCon tc -> ReturnsPrim (tyConPrimRep tc)
| otherwise -> ReturnsAlg tc
where
tc = tyConAppTyCon ty
-- All primops return a tycon-app result
-- The tycon can be an unboxed tuple, though, which
-- gives rise to a ReturnAlg
{-
We do not currently make use of whether primops are commutable.
We used to try to move constants to the right hand side for strength
reduction.
-}
{-
commutableOp :: PrimOp -> Bool
#include "primop-commutable.hs-incl"
-}
-- Utils:
dyadic_fun_ty, monadic_fun_ty, compare_fun_ty :: Type -> Type
dyadic_fun_ty ty = mkFunTys [ty, ty] ty
monadic_fun_ty ty = mkFunTy ty ty
compare_fun_ty ty = mkFunTys [ty, ty] intPrimTy
-- Output stuff:
pprPrimOp :: PrimOp -> SDoc
pprPrimOp other_op = pprOccName (primOpOcc other_op)
{-
************************************************************************
* *
\subsubsection[PrimCall]{User-imported primitive calls}
* *
************************************************************************
-}
data PrimCall = PrimCall CLabelString UnitId
instance Outputable PrimCall where
ppr (PrimCall lbl pkgId)
= text "__primcall" <+> ppr pkgId <+> ppr lbl
|
siddhanathan/ghc
|
compiler/prelude/PrimOp.hs
|
Haskell
|
bsd-3-clause
| 23,245
|
module Test20 where
y c = c
f n y = n y
g = (f 1 1)
h = (+1) 1
|
kmate/HaRe
|
old/testing/refacFunDef/Test20.hs
|
Haskell
|
bsd-3-clause
| 67
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
@Uniques@ are used to distinguish entities in the compiler (@Ids@,
@Classes@, etc.) from each other. Thus, @Uniques@ are the basic
comparison key in the compiler.
If there is any single operation that needs to be fast, it is @Unique@
comparison. Unsurprisingly, there is quite a bit of huff-and-puff
directed to that end.
Some of the other hair in this code is to be able to use a
``splittable @UniqueSupply@'' if requested/possible (not standard
Haskell).
-}
{-# LANGUAGE CPP, BangPatterns, MagicHash #-}
module Unique (
-- * Main data types
Unique, Uniquable(..),
-- ** Constructors, desctructors and operations on 'Unique's
hasKey,
pprUnique,
mkUniqueGrimily, -- Used in UniqSupply only!
getKey, -- Used in Var, UniqFM, Name only!
mkUnique, unpkUnique, -- Used in BinIface only
incrUnique, -- Used for renumbering
deriveUnique, -- Ditto
newTagUnique, -- Used in CgCase
initTyVarUnique,
-- ** Making built-in uniques
-- now all the built-in Uniques (and functions to make them)
-- [the Oh-So-Wonderful Haskell module system wins again...]
mkAlphaTyVarUnique,
mkPrimOpIdUnique,
mkTupleTyConUnique, mkTupleDataConUnique,
mkCTupleTyConUnique,
mkPreludeMiscIdUnique, mkPreludeDataConUnique,
mkPreludeTyConUnique, mkPreludeClassUnique,
mkPArrDataConUnique,
mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique,
mkRegSingleUnique, mkRegPairUnique, mkRegClassUnique, mkRegSubUnique,
mkCostCentreUnique,
mkBuiltinUnique,
mkPseudoUniqueD,
mkPseudoUniqueE,
mkPseudoUniqueH
) where
#include "HsVersions.h"
import BasicTypes
import FastString
import Outputable
import Util
-- just for implementing a fast [0,61) -> Char function
import GHC.Exts (indexCharOffAddr#, Char(..), Int(..))
import Data.Char ( chr, ord )
import Data.Bits
{-
************************************************************************
* *
\subsection[Unique-type]{@Unique@ type and operations}
* *
************************************************************************
The @Chars@ are ``tag letters'' that identify the @UniqueSupply@.
Fast comparison is everything on @Uniques@:
-}
--why not newtype Int?
-- | The type of unique identifiers that are used in many places in GHC
-- for fast ordering and equality tests. You should generate these with
-- the functions from the 'UniqSupply' module
data Unique = MkUnique {-# UNPACK #-} !Int
{-
Now come the functions which construct uniques from their pieces, and vice versa.
The stuff about unique *supplies* is handled further down this module.
-}
unpkUnique :: Unique -> (Char, Int) -- The reverse
mkUniqueGrimily :: Int -> Unique -- A trap-door for UniqSupply
getKey :: Unique -> Int -- for Var
incrUnique :: Unique -> Unique
deriveUnique :: Unique -> Int -> Unique
newTagUnique :: Unique -> Char -> Unique
mkUniqueGrimily = MkUnique
{-# INLINE getKey #-}
getKey (MkUnique x) = x
incrUnique (MkUnique i) = MkUnique (i + 1)
-- deriveUnique uses an 'X' tag so that it won't clash with
-- any of the uniques produced any other way
deriveUnique (MkUnique i) delta = mkUnique 'X' (i + delta)
-- newTagUnique changes the "domain" of a unique to a different char
newTagUnique u c = mkUnique c i where (_,i) = unpkUnique u
-- pop the Char in the top 8 bits of the Unique(Supply)
-- No 64-bit bugs here, as long as we have at least 32 bits. --JSM
-- and as long as the Char fits in 8 bits, which we assume anyway!
mkUnique :: Char -> Int -> Unique -- Builds a unique from pieces
-- NOT EXPORTED, so that we can see all the Chars that
-- are used in this one module
mkUnique c i
= MkUnique (tag .|. bits)
where
tag = ord c `shiftL` 24
bits = i .&. 16777215 {-``0x00ffffff''-}
unpkUnique (MkUnique u)
= let
-- as long as the Char may have its eighth bit set, we
-- really do need the logical right-shift here!
tag = chr (u `shiftR` 24)
i = u .&. 16777215 {-``0x00ffffff''-}
in
(tag, i)
{-
************************************************************************
* *
\subsection[Uniquable-class]{The @Uniquable@ class}
* *
************************************************************************
-}
-- | Class of things that we can obtain a 'Unique' from
class Uniquable a where
getUnique :: a -> Unique
hasKey :: Uniquable a => a -> Unique -> Bool
x `hasKey` k = getUnique x == k
instance Uniquable FastString where
getUnique fs = mkUniqueGrimily (uniqueOfFS fs)
instance Uniquable Int where
getUnique i = mkUniqueGrimily i
{-
************************************************************************
* *
\subsection[Unique-instances]{Instance declarations for @Unique@}
* *
************************************************************************
And the whole point (besides uniqueness) is fast equality. We don't
use `deriving' because we want {\em precise} control of ordering
(equality on @Uniques@ is v common).
-}
eqUnique, ltUnique, leUnique :: Unique -> Unique -> Bool
eqUnique (MkUnique u1) (MkUnique u2) = u1 == u2
ltUnique (MkUnique u1) (MkUnique u2) = u1 < u2
leUnique (MkUnique u1) (MkUnique u2) = u1 <= u2
cmpUnique :: Unique -> Unique -> Ordering
cmpUnique (MkUnique u1) (MkUnique u2)
= if u1 == u2 then EQ else if u1 < u2 then LT else GT
instance Eq Unique where
a == b = eqUnique a b
a /= b = not (eqUnique a b)
instance Ord Unique where
a < b = ltUnique a b
a <= b = leUnique a b
a > b = not (leUnique a b)
a >= b = not (ltUnique a b)
compare a b = cmpUnique a b
-----------------
instance Uniquable Unique where
getUnique u = u
-- We do sometimes make strings with @Uniques@ in them:
showUnique :: Unique -> String
showUnique uniq
= case unpkUnique uniq of
(tag, u) -> finish_show tag u (iToBase62 u)
finish_show :: Char -> Int -> String -> String
finish_show 't' u _pp_u | u < 26
= -- Special case to make v common tyvars, t1, t2, ...
-- come out as a, b, ... (shorter, easier to read)
[chr (ord 'a' + u)]
finish_show tag _ pp_u = tag : pp_u
pprUnique :: Unique -> SDoc
pprUnique u = text (showUnique u)
instance Outputable Unique where
ppr = pprUnique
instance Show Unique where
show uniq = showUnique uniq
{-
************************************************************************
* *
\subsection[Utils-base62]{Base-62 numbers}
* *
************************************************************************
A character-stingy way to read/write numbers (notably Uniques).
The ``62-its'' are \tr{[0-9a-zA-Z]}. We don't handle negative Ints.
Code stolen from Lennart.
-}
iToBase62 :: Int -> String
iToBase62 n_
= ASSERT(n_ >= 0) go n_ ""
where
go n cs | n < 62
= let !c = chooseChar62 n in c : cs
| otherwise
= go q (c : cs) where (q, r) = quotRem n 62
!c = chooseChar62 r
chooseChar62 :: Int -> Char
{-# INLINE chooseChar62 #-}
chooseChar62 (I# n) = C# (indexCharOffAddr# chars62 n)
chars62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"#
{-
************************************************************************
* *
\subsection[Uniques-prelude]{@Uniques@ for wired-in Prelude things}
* *
************************************************************************
Allocation of unique supply characters:
v,t,u : for renumbering value-, type- and usage- vars.
B: builtin
C-E: pseudo uniques (used in native-code generator)
X: uniques derived by deriveUnique
_: unifiable tyvars (above)
0-9: prelude things below
(no numbers left any more..)
:: (prelude) parallel array data constructors
other a-z: lower case chars for unique supplies. Used so far:
d desugarer
f AbsC flattener
g SimplStg
n Native codegen
r Hsc name cache
s simplifier
-}
mkAlphaTyVarUnique :: Int -> Unique
mkPreludeClassUnique :: Int -> Unique
mkPreludeTyConUnique :: Int -> Unique
mkTupleTyConUnique :: Boxity -> Arity -> Unique
mkCTupleTyConUnique :: Arity -> Unique
mkPreludeDataConUnique :: Arity -> Unique
mkTupleDataConUnique :: Boxity -> Arity -> Unique
mkPrimOpIdUnique :: Int -> Unique
mkPreludeMiscIdUnique :: Int -> Unique
mkPArrDataConUnique :: Int -> Unique
mkAlphaTyVarUnique i = mkUnique '1' i
mkPreludeClassUnique i = mkUnique '2' i
-- Prelude type constructors occupy *three* slots.
-- The first is for the tycon itself; the latter two
-- are for the generic to/from Ids. See TysWiredIn.mk_tc_gen_info.
mkPreludeTyConUnique i = mkUnique '3' (3*i)
mkTupleTyConUnique Boxed a = mkUnique '4' (3*a)
mkTupleTyConUnique Unboxed a = mkUnique '5' (3*a)
mkCTupleTyConUnique a = mkUnique 'k' (3*a)
-- Data constructor keys occupy *two* slots. The first is used for the
-- data constructor itself and its wrapper function (the function that
-- evaluates arguments as necessary and calls the worker). The second is
-- used for the worker function (the function that builds the constructor
-- representation).
mkPreludeDataConUnique i = mkUnique '6' (2*i) -- Must be alphabetic
mkTupleDataConUnique Boxed a = mkUnique '7' (2*a) -- ditto (*may* be used in C labels)
mkTupleDataConUnique Unboxed a = mkUnique '8' (2*a)
mkPrimOpIdUnique op = mkUnique '9' op
mkPreludeMiscIdUnique i = mkUnique '0' i
-- No numbers left anymore, so I pick something different for the character tag
mkPArrDataConUnique a = mkUnique ':' (2*a)
-- The "tyvar uniques" print specially nicely: a, b, c, etc.
-- See pprUnique for details
initTyVarUnique :: Unique
initTyVarUnique = mkUnique 't' 0
mkPseudoUniqueD, mkPseudoUniqueE, mkPseudoUniqueH,
mkBuiltinUnique :: Int -> Unique
mkBuiltinUnique i = mkUnique 'B' i
mkPseudoUniqueD i = mkUnique 'D' i -- used in NCG for getUnique on RealRegs
mkPseudoUniqueE i = mkUnique 'E' i -- used in NCG spiller to create spill VirtualRegs
mkPseudoUniqueH i = mkUnique 'H' i -- used in NCG spiller to create spill VirtualRegs
mkRegSingleUnique, mkRegPairUnique, mkRegSubUnique, mkRegClassUnique :: Int -> Unique
mkRegSingleUnique = mkUnique 'R'
mkRegSubUnique = mkUnique 'S'
mkRegPairUnique = mkUnique 'P'
mkRegClassUnique = mkUnique 'L'
mkCostCentreUnique :: Int -> Unique
mkCostCentreUnique = mkUnique 'C'
mkVarOccUnique, mkDataOccUnique, mkTvOccUnique, mkTcOccUnique :: FastString -> Unique
-- See Note [The Unique of an OccName] in OccName
mkVarOccUnique fs = mkUnique 'i' (uniqueOfFS fs)
mkDataOccUnique fs = mkUnique 'd' (uniqueOfFS fs)
mkTvOccUnique fs = mkUnique 'v' (uniqueOfFS fs)
mkTcOccUnique fs = mkUnique 'c' (uniqueOfFS fs)
|
acowley/ghc
|
compiler/basicTypes/Unique.hs
|
Haskell
|
bsd-3-clause
| 11,873
|
{-# LANGUAGE OverloadedLabels, DataKinds, FlexibleContexts #-}
import GHC.OverloadedLabels
-- No instance for (OverloadedLabel "x" t0)
a = #x
-- No instance for (OverloadedLabel "x" (t0 -> t1), OverloadedLabel "y" t0)
b = #x #y
-- Could not deduce (OverloadedLabel "y" t) from (OverloadedLabel "x" t)
c :: IsLabel "x" t => t
c = #y
main = return ()
|
olsner/ghc
|
testsuite/tests/overloadedrecflds/should_fail/overloadedlabelsfail01.hs
|
Haskell
|
bsd-3-clause
| 354
|
{-# OPTIONS_HADDOCK hide #-}
module Ticket61_Hidden where
class C a where
-- | A comment about f
f :: a
|
DavidAlphaFox/ghc
|
utils/haddock/html-test/src/Ticket61_Hidden.hs
|
Haskell
|
bsd-3-clause
| 110
|
{-# LANGUAGE DuplicateRecordFields #-}
module OverloadedRecFldsRun02_A (U(..), V(MkV, x), Unused(..), u) where
data U = MkU { x :: Bool, y :: Bool }
data V = MkV { x :: Int }
data Unused = MkUnused { unused :: Bool }
u = MkU False True
|
shlevy/ghc
|
testsuite/tests/overloadedrecflds/should_run/OverloadedRecFldsRun02_A.hs
|
Haskell
|
bsd-3-clause
| 239
|
{-# htermination min :: Char -> Char -> Char #-}
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Prelude_min_3.hs
|
Haskell
|
mit
| 49
|
{-# LANGUAGE TupleSections #-}
-- | Parser for .prof files generated by GHC.
module ProfFile
( Time(..)
, Line(..)
, lIndividualTime
, lInheritedTime
, lIndividualAlloc
, lInheritedAlloc
, parse
, processLines
, findStart
) where
import Control.Arrow (second, left)
import Data.Char (isSpace)
import Data.List (isPrefixOf)
import Text.Read (readEither)
import Control.Monad (unless)
import Control.Applicative
import Prelude -- Quash AMP related warnings in GHC>=7.10
data Time = Time
{ tIndividual :: Double
, tInherited :: Double
} deriving (Show, Eq)
data Line = Line
{ lCostCentre :: String
, lModule :: String
, lNumber :: Int
, lEntries :: Int
, lTime :: Time
, lAlloc :: Time
, lTicks :: Int
, lBytes :: Int
, lChildren :: [Line]
} deriving (Show, Eq)
lIndividualTime :: Line -> Double
lIndividualTime = tIndividual . lTime
lInheritedTime :: Line -> Double
lInheritedTime = tInherited . lTime
lIndividualAlloc :: Line -> Double
lIndividualAlloc = tIndividual . lAlloc
lInheritedAlloc :: Line -> Double
lInheritedAlloc = tInherited . lAlloc
data ProfFormat = NoSources | IncludesSources
-- | Returns a function accepting the children and returning a fully
-- formed 'Line'.
parseLine :: ProfFormat -> String -> Either String ([Line] -> Line)
parseLine format s =
case format of
NoSources ->
case words s of
(costCentre:module_:no:entries:indTime:indAlloc:inhTime:inhAlloc:other) ->
parse' costCentre module_ no entries indTime indAlloc inhTime inhAlloc other
_ -> Left $ "Malformed .prof file line:\n" ++ s
IncludesSources ->
case words s of
(costCentre:module_:rest) | (no:entries:indTime:indAlloc:inhTime:inhAlloc:other) <- dropSRC rest ->
parse' costCentre module_ no entries indTime indAlloc inhTime inhAlloc other
_ -> Left $ "Malformed .prof file line:\n" ++ s
where
-- XXX: The SRC field can contain arbitrary characters (from the
-- subdirectory name)!
--
-- As a heuristic, assume SRC spans until the last word which:
--
-- * Ends with '>'
-- (for special values emitted by GHC like "<no location info>")
--
-- or
--
-- * Contains a colon eventually followed by another colon or a minus
-- (to identify the source span, e.g. ":69:55-64" or ":(36,1)-(38,30)",
-- or maybe for a single character ":30:3")
--
-- If there is no such word, assume SRC is just one word.
--
-- This heuristic will break if:
--
-- * In the future, columns to the right of SRC can match the above
-- condition (currently, they're all numeric)
--
-- or
--
-- * GHC doesn't add a source span formatted as assumed above, and the
-- SRC contains spaces
--
-- The implementation is not very efficient, but I suppose this is not
-- performance-critical.
dropSRC (_:rest) = reverse . takeWhile (not . isPossibleEndOfSRC) . reverse $ rest
dropSRC [] = []
isPossibleEndOfSRC w = last w == '>'
|| case break (==':') w of
(_, _:rest) -> any (`elem` ":-") rest
_ -> False
parse' costCentre module_ no entries indTime indAlloc inhTime inhAlloc other = do
pNo <- readEither' no
pEntries <- readEither' entries
pTime <- Time <$> readEither' indTime <*> readEither' inhTime
pAlloc <- Time <$> readEither' indAlloc <*> readEither' inhAlloc
(pTicks, pBytes) <-
case other of
(ticks:bytes:_) -> (,) <$> readEither' ticks <*> readEither' bytes
_ -> pure (0, 0)
return $ Line costCentre module_ pNo pEntries pTime pAlloc pTicks pBytes
readEither' str = left (("Could not parse value "++show str++": ")++)
(readEither str)
type LineNumber = Int
processLines :: ProfFormat -> [String] -> LineNumber -> Either String [Line]
processLines format lines0 lineNumber0 = do
((ss,_), lines') <- go 0 lines0 lineNumber0
unless (null ss) $
error "processLines: the impossible happened, not all strings were consumed."
return lines'
where
go :: Int -> [String] -> LineNumber -> Either String (([String], LineNumber), [Line])
go _depth [] lineNumber = do
return (([], lineNumber), [])
go depth0 (line : lines') lineNumber = do
let (spaces, rest) = break (not . isSpace) line
let depth = length spaces
if depth < depth0
then return ((line : lines', lineNumber), [])
else do
parsedLine <- left (("Parse error in line "++show lineNumber++": ")++) $
parseLine format rest
((lines'', lineNumber''), children) <- go (depth + 1) lines' (lineNumber + 1)
second (parsedLine children :) <$> go depth lines'' lineNumber''
firstLineNoSources :: [String]
firstLineNoSources = ["COST", "CENTRE", "MODULE", "no.", "entries", "%time", "%alloc", "%time", "%alloc"]
-- Since GHC 8.0.2 the cost centres include the src location
firstLineIncludesSources :: [String]
firstLineIncludesSources = ["COST", "CENTRE", "MODULE", "SRC", "no.", "entries", "%time", "%alloc", "%time", "%alloc"]
findStart :: [String] -> LineNumber -> Either String (ProfFormat, [String], [String], LineNumber)
findStart [] _ = Left "Malformed .prof file: couldn't find start line"
findStart (line : _empty : lines') lineNumber | (firstLineNoSources `isPrefixOf` words line) = return (NoSources, words line, lines', lineNumber + 2)
| (firstLineIncludesSources `isPrefixOf` words line) = return (IncludesSources, words line, lines', lineNumber + 2)
findStart (_line : lines') lineNumber = findStart lines' (lineNumber + 1)
parse :: String -> Either String ([String], [Line])
parse s = do
(format, names, ss, lineNumber) <- findStart (lines s) 1
return . (names,) =<< processLines format ss lineNumber
|
fpco/ghc-prof-flamegraph
|
ProfFile.hs
|
Haskell
|
mit
| 6,019
|
module Monoid8 where
import Data.Monoid
import Test.QuickCheck
import SemiGroupAssociativeLaw
import Test.HUnit
import MonoidLaws
import Text.Show.Functions
import ArbitrarySum
newtype Mem s a = Mem { runMem :: s -> (a,s) } deriving Show
mappendMem :: Monoid a => Mem s a -> Mem s a -> Mem s a
mappendMem f1 f2 =
Mem $ combiningFunc
where
combiningFunc s =
let
(a1, s1) = (runMem f1) s
(a2, s2) = (runMem f2) s1
in
(a1 `mappend` a2, s2)
instance Monoid a => Monoid (Mem s a) where
mempty = Mem $ \n -> (mempty, n)
mappend = mappendMem
{-
Iceland_jack: arbitrary :: (CoArbitrary s, Arbitrary s, Arbitrary a) => Gen (s -> (a, s))
Iceland_jack: You can already generate functions like that
Iceland_jack: So you can just do
Iceland_jack: Mem <$> arbitrary
Iceland_jack: :: (Arbitrary a, Arbitrary s, CoArbitrary s) => Gen (Mem s a)
Iceland_jack: Where 's' appears as an "input" (CoArbitrary, contravariant position) as well as an "output" (Arbitrary, covariant position)
Iceland_jack: that's why we get (Arbitrary s, CoArbitrary s)
-}
instance (CoArbitrary s, Arbitrary s, Arbitrary a) => Arbitrary (Mem s a) where
arbitrary = Mem <$> arbitrary
f' = Mem $ \s -> ("hi", s + 1)
test1 = TestCase (assertEqual "" (runMem (f' <> mempty) $ 0) ("hi", 1))
test2 = TestCase (assertEqual "" (runMem (mempty <> f') 0) ("hi", 1))
test3 = TestCase (assertEqual "" (runMem mempty 0 :: (String, Int)) ("", 0))
test4 = TestCase (assertEqual "" (runMem (f' <> mempty) 0) (runMem f' 0))
test5 = TestCase (assertEqual "" (runMem (mempty <> f') 0) (runMem f' 0))
-- can't use semigroupAssoc as Eq isn't defined for functions...
-- instead use QuickCheck to generate a random value which is applied
-- to both combined functions producing a result which can be tested
-- for equality
memAssoc :: (Eq s, Eq a, Monoid a) => s -> Mem s a -> Mem s a -> Mem s a -> Bool
memAssoc v a b c = (runMem (a <> (b <> c)) $ v) == (runMem ((a <> b) <> c) $ v)
type MemAssoc = Int -> Mem Int (Sum Int) -> Mem Int (Sum Int) -> Mem Int (Sum Int) -> Bool
memLeftIdentity :: (Eq s, Eq a, Monoid a) => s -> Mem s a -> Bool
memLeftIdentity x a = (runMem (mempty <> a) $ x) == (runMem a $ x)
memRightIdentity :: (Eq s, Eq a, Monoid a) => s -> Mem s a -> Bool
memRightIdentity x a = (runMem (a <> mempty) $ x) == (runMem a $ x)
main :: IO ()
main = do
quickCheck (memAssoc :: MemAssoc)
quickCheck (memLeftIdentity :: Int -> Mem Int (Sum Int) -> Bool)
quickCheck (memRightIdentity :: Int -> Mem Int (Sum Int) -> Bool)
counts <- runTestTT (TestList [test1, test2, test3, test4, test5])
print counts
|
NickAger/LearningHaskell
|
HaskellProgrammingFromFirstPrinciples/Chapter15.hsproj/Monoid8.hs
|
Haskell
|
mit
| 2,666
|
-- 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.Binding
( Binding (..)
, kind
, apiVersion
, metadata
, target
, mkBinding
) where
import Control.Lens.TH (makeLenses)
import Data.Aeson.TH (defaultOptions,
deriveJSON,
fieldLabelModifier)
import Data.Text (Text)
import GHC.Generics (Generic)
import Kubernetes.Model.V1.ObjectMeta (ObjectMeta)
import Kubernetes.Model.V1.ObjectReference (ObjectReference)
import Prelude hiding (drop, error, max,
min)
import qualified Prelude as P
import Test.QuickCheck (Arbitrary, arbitrary)
import Test.QuickCheck.Instances ()
-- | Binding ties one object to another. For example, a pod is bound to a node by a scheduler.
data Binding = Binding
{ _kind :: !(Maybe Text)
, _apiVersion :: !(Maybe Text)
, _metadata :: !(Maybe ObjectMeta)
, _target :: !(ObjectReference)
} deriving (Show, Eq, Generic)
makeLenses ''Binding
$(deriveJSON defaultOptions{fieldLabelModifier = (\n -> if n == "_type_" then "type" else P.drop 1 n)} ''Binding)
instance Arbitrary Binding where
arbitrary = Binding <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
-- | Use this method to build a Binding
mkBinding :: ObjectReference -> Binding
mkBinding xtargetx = Binding Nothing Nothing Nothing xtargetx
|
soundcloud/haskell-kubernetes
|
lib/Kubernetes/Model/V1/Binding.hs
|
Haskell
|
mit
| 2,009
|
--------------------------------------------------------------------
-- |
-- Copyright : © Oleg Grenrus 2014
-- License : MIT
-- Maintainer: Oleg Grenrus <oleg.grenrus@iki.fi>
-- Stability : experimental
-- Portability: non-portable
--
-- This module re-exports tree-based implementation.
--------------------------------------------------------------------
module Data.Algebra.Boolean.NNF (
module Data.Algebra.Boolean.NNF.Tree
) where
import Data.Algebra.Boolean.NNF.Tree
|
phadej/boolean-normal-forms
|
src/Data/Algebra/Boolean/NNF.hs
|
Haskell
|
mit
| 484
|
{-# language NoImplicitPrelude, DoAndIfThenElse, OverloadedStrings, ExtendedDefaultRules #-}
module IHaskell.Publish (publishResult) where
import IHaskellPrelude
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import IHaskell.Display
import IHaskell.Types
import IHaskell.CSS (ihaskellCSS)
-- | Publish evaluation results, ignore any CommMsgs. This function can be used to create a function
-- of type (EvaluationResult -> IO ()), which can be used to publish results to the frontend. The
-- resultant function shares some state between different calls by storing it inside the MVars
-- passed while creating it using this function. Pager output is accumulated in the MVar passed for
-- this purpose if a pager is being used (indicated by an argument), and sent to the frontend
-- otherwise.
publishResult :: (Message -> IO ()) -- ^ A function to send messages
-> MessageHeader -- ^ Message header to use for reply
-> MVar [Display] -- ^ A MVar to use for displays
-> MVar Bool -- ^ A mutable boolean to decide whether the output need to be cleared and
-- redrawn
-> MVar [DisplayData] -- ^ A MVar to use for storing pager output
-> Bool -- ^ Whether to use the pager
-> EvaluationResult -- ^ The evaluation result
-> IO ()
publishResult send replyHeader displayed updateNeeded pagerOutput usePager result = do
let final =
case result of
IntermediateResult{} -> False
FinalResult{} -> True
outs = outputs result
-- If necessary, clear all previous output and redraw.
clear <- readMVar updateNeeded
when clear $ do
clearOutput
disps <- readMVar displayed
mapM_ sendOutput $ reverse disps
-- Draw this message.
sendOutput outs
-- If this is the final message, add it to the list of completed messages. If it isn't, make sure we
-- clear it later by marking update needed as true.
modifyMVar_ updateNeeded (const $ return $ not final)
when final $ do
modifyMVar_ displayed (return . (outs :))
-- If this has some pager output, store it for later.
let pager = pagerOut result
unless (null pager) $
if usePager
then modifyMVar_ pagerOutput (return . (++ pager))
else sendOutput $ Display pager
where
clearOutput = do
header <- dupHeader replyHeader ClearOutputMessage
send $ ClearOutput header True
sendOutput (ManyDisplay manyOuts) = mapM_ sendOutput manyOuts
sendOutput (Display outs) = do
header <- dupHeader replyHeader DisplayDataMessage
send $ PublishDisplayData header "haskell" $ map (convertSvgToHtml . prependCss) outs
convertSvgToHtml (DisplayData MimeSvg svg) = html $ makeSvgImg $ base64 $ E.encodeUtf8 svg
convertSvgToHtml x = x
makeSvgImg :: Base64 -> String
makeSvgImg base64data = T.unpack $ "<img src=\"data:image/svg+xml;base64," <>
base64data <>
"\"/>"
prependCss (DisplayData MimeHtml html) =
DisplayData MimeHtml $ mconcat ["<style>", T.pack ihaskellCSS, "</style>", html]
prependCss x = x
|
sumitsahrawat/IHaskell
|
src/IHaskell/Publish.hs
|
Haskell
|
mit
| 3,310
|
module Interpreter where
-- union = union (|||), delete = remove (---)
import Parsing
import Data.List
-- Free variables of a term (variables that are not bound by a lambda)
freeVariables :: Term -> [Var]
freeVariables (Constant _) = []
freeVariables (Variable v) = [v]
freeVariables (Application (a, b)) = (freeVariables a) `union` (freeVariables b)
freeVariables (Lambda (x, b)) = filter (\z -> z == x) (freeVariables b)
-- Checks if a variable is free in a term
isFreeVariableOf :: Var -> Term -> Bool
isFreeVariableOf v t = v `elem` (freeVariables t)
-- Create a new variable name, that is not free in a term
newVar :: Term -> Var
newVar t = newVar' t "new-var"
newVar' :: Term -> Var -> Var
newVar' t nVar = if isFreeVariableOf nVar t
then newVar' t (nVar++"1")
else nVar
-- substitute a variable in a term with another term
substitution :: Term -> Var -> Term -> Term
substitution (Variable term1) var term2
| term1 == var = term2
substitution (Application (t1,t2)) var term2 =
Application (substitution t1 var term2, substitution t2 var term2)
substitution (Lambda (x,t)) var term2
| x /= var && not (isFreeVariableOf x term2) = Lambda (x, substitution t var term2)
| x /= var = substitution (substitution t x (Variable (newVar (Application (t, term2))))) var term2
substitution term1 _ _ = term1
-- apply parameters to a function
betaConversion :: Term -> Term
betaConversion (Application (Lambda (x, a), b)) = substitution a x b
betaConversion t = t
-- pattern matching here probably buggy
etaConversion :: Term -> Term
etaConversion (Lambda (x, Application (t, Variable x2)))
| x == x2 = etaConversion' x t (Lambda (x, Application (t, Variable x2)))
etaConversion te = te
etaConversion' :: Var -> Term -> Term -> Term
etaConversion' _ (Constant (Num t)) _ = Constant (Num t)
etaConversion' x t te = if (isFreeVariableOf x t) then te else t
-- give the constants some meaning
deltaConversion :: Term -> Term
deltaConversion (Application (Constant Succ, Constant (Num n))) = Constant (Num (n + 1))
deltaConversion (Application (Application (Constant Add, Constant (Num n)), Constant (Num m))) = Constant (Num (n + m))
deltaConversion t = t
|
JorisM/HLambdaCalculus
|
Interpreter.hs
|
Haskell
|
mit
| 2,187
|
-- ch4.hs
module Ch4 where
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome xs = (reverse xs) == xs
myAbs :: Integer -> Integer
myAbs x = if x >= 0 then x else (-x)
f :: (a, b) -> (c, d) -> ((b, d), (a, c))
f x y = ((snd x, snd y), (fst x, fst y))
|
candu/haskellbook
|
ch4/ch4.hs
|
Haskell
|
mit
| 252
|
module Language.Asol.Expression where
data Instruction = Push Integer
| Top Int
| Pop
| Print
| Read
| Emit
| Mul
| Sub
| Add
| Div
| Mod
| Pow
| Fact
| Swap
| Dup
| ShowStack
deriving (Eq,Show)
|
kmein/asol
|
Language/Asol/Expression.hs
|
Haskell
|
mit
| 468
|
-- Core stuff: Tic Tac Toe struct, win conditions
module Core where
data Place = X | O | E
deriving (Show, Eq)
-- X, O or Empty
data Player = PX | PO | N
deriving (Show, Eq)
-- N is to be used only for a full board where no one has won
getPlace :: Player -> Place
getPlace player = case player of
PX -> X
PO -> O
N -> E
switchPlayer :: Player -> Player
switchPlayer player = case player of
PX -> PO
PO -> PX
N -> N
data Row = Row {
left :: Place,
mid :: Place,
right :: Place
} deriving Eq
instance Show Row where
show (Row l m r) = (show l) ++ " " ++ (show m) ++ " " ++ (show r)
data Board = Board {
top :: Row,
middle :: Row,
bottom :: Row
} deriving Eq
instance Show Board where
show (Board t m b) = (show t) ++ "\n\n" ++ (show m) ++ "\n\n" ++ (show b) ++ "\n"
data Diagonal = LMR | RML deriving (Show, Eq) -- Left-middle-right or Right-middle-left, from the top down
emptyBoard :: Board
emptyBoard = Board (Row E E E) (Row E E E) (Row E E E)
getByPosition :: Board -> (Int, Int) -> Place
getByPosition (Board t m b) (x, y) = selector (case y of
1 -> t
2 -> m
_ -> b)
where
selector = case x of
1 -> left
2 -> mid
3 -> right
setByPosition :: Board -> (Int, Int) -> Place -> Board
setByPosition (Board t m b) (x, y) place = Board t' m' b'
where
substitute (Row l m r) x = Row
(if x == 1 then place else l)
(if x == 2 then place else m)
(if x == 3 then place else r)
t' = if y == 1 then substitute t x else t
m' = if y == 2 then substitute m x else m
b' = if y == 3 then substitute b x else b
placeIsFull :: Place -> Bool
placeIsFull E = False
placeIsFull _ = True
rowIsFull :: Row -> Bool
rowIsFull (Row l m r) = placeIsFull l && placeIsFull m && placeIsFull r
boardIsFull :: Board -> Bool
boardIsFull (Board t m b) = rowIsFull t && rowIsFull m && rowIsFull b
getDiag :: Board -> Diagonal -> Row
getDiag board LMR = Row (getByPosition board (1, 1)) (getByPosition board (2, 2)) (getByPosition board (3, 3))
getDiag board RML = Row (getByPosition board (3, 1)) (getByPosition board (2, 2)) (getByPosition board (1, 3))
checkPosInt :: Place -> Place -> Int
checkPosInt place1 place2 = if place1 == place2 then 1 else 0
countPos :: Row -> Player -> Int
countPos row player = sum [ checkPosInt p $ getPlace player | p <- [ left row, mid row, right row ] ]
findDiag :: Board -> Place -> Bool
findDiag (Board t m b) place =
(mid m == place) &&
(((left t == place) && (right b == place)) ||
((right t == place) && (left b == place)))
findRow :: Board -> Place -> Bool
findRow (Board t m b) place = checkRow t || checkRow m || checkRow b
where
checkRow (Row l m r) = (l == place) && (m == place) && (r == place)
findColumn :: Board -> Place -> Bool
findColumn (Board t m b) place =
((left t == place) && (left m == place) && (left b == place)) ||
((mid t == place) && (mid m == place) && (mid b == place)) ||
((right t == place) && (right m == place) && (right b == place))
findPath :: Board -> Player -> Bool
findPath board player = (findDiag board p) || (findRow board p) || (findColumn board p)
where
p = getPlace player
determineWin :: Board -> Maybe Player -- Just Player if won or full, Nothing if no one has won and there are free spots
determineWin board
| findPath board PX = Just PX
| findPath board PO = Just PO
| boardIsFull board = Just N
| otherwise = Nothing
|
quantum-dan/tictactoe-ai
|
Core.hs
|
Haskell
|
mit
| 3,579
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns #-}
module Commands.TH.Data where
import Commands.Grammar
import Data.List.NonEmpty (toList)
import Data.Functor
import Language.Haskell.TH
import Language.Haskell.TH.Syntax
-- |
-- given the input 'Production':
--
-- > Production ''Command [
-- > Variant ''ReplaceWith [Part "replace", Hole ''Phrase, Part "with", Hole ''Phrase],
-- > Variant ''Click [Hole ''Times, Hole ''Button, Part "click"],
-- > Variant ''Undo [Part "undo"]]
--
-- 'buildDataD' builds a @data@ declaration:
--
-- > data Command
-- > = ReplaceWith Phrase Phrase
-- > | Click Times Button
-- > | Undo
-- > deriving (Show,Eq)
--
-- i.e. ignore 'Terminal's, keep 'NonTerminal's
--
buildDataD :: Production -> Dec
buildDataD (Production lhs (toList -> rhs)) = DataD context typename parameters constructors derived
where
context = []
NonTerminal typename = lhs
parameters = []
constructors = buildConstructorC <$> rhs
derived = [''Show, ''Eq]
-- |
-- given the input 'Variant':
--
-- > Variant ''ReplaceWith [Part "replace", Hole ''Phrase, Part "with", Hole ''Phrase],
--
-- 'buildConstructorC' builds the constructor "declaration":
--
-- > ReplaceWith Phrase Phrase
--
buildConstructorC :: Variant -> Con
buildConstructorC (Variant constructor (toList -> symbols)) = NormalC constructor arguments
where
arguments = concatMap buildArgument symbols
buildArgument :: Symbol -> [StrictType]
buildArgument (Part {}) = []
buildArgument (Hole (NonTerminal name)) = [(NotStrict, ConT name)]
|
sboosali/Haskell-DragonNaturallySpeaking
|
sources/Commands/TH/Data.hs
|
Haskell
|
mit
| 1,628
|
{-------------------------------------------------------------------------------
Consider the consecutive primes p₁ = 19 and p₂ = 23. It can be verified that 1219 is the smallest number such that the last digits are formed by p₁ whilst also being divisible by p₂.
In fact, with the exception of p₁ = 3 and p₂ = 5, for every pair of consecutive primes, p₂ > p₁, there exist values of n for which the last digits are formed by p₁ and n is divisible by p₂. Let S be the smallest of these values of n.
Find ∑ S for every pair of consecutive primes with 5 ≤ p₁ ≤ 1000000.
-------------------------------------------------------------------------------}
import qualified Data.Numbers.Primes as Primes
import qualified Data.Digits as Digits
unDigits = Digits.unDigits 10
from0to9 = [0..9]
-- Given m and e, build the smallest number S such that m|S and S ends by e.
genS :: Int -> Int -> Int
genS m e = (m *) $ minimum $ recGenS e 0 [] []
where
recGenS :: Int -> Int -> [Int] -> [Int] -> [Int]
recGenS 0 _ digits acc = unDigits digits : acc
recGenS end rest digits acc =
concat $ map (\(d, r) -> recGenS end' r (d:digits) acc) ds
where
(end', end'') = quotRem end 10
ds = [(d, r') | d <- from0to9
, let (r', r0') = quotRem (m * d + rest) 10
, r0' == end'']
-- return ∑ S for every pair of consecutive primes with 5 ≤ p₁ ≤ bound
euler bound =
sum $ map (\(p1, p2) -> genS p2 p1)
$ takeWhile (\(p1, p2) -> p1 <= bound)
$ dropWhile (\(p1, p2) -> p1 < 5)
$ zip Primes.primes $ tail Primes.primes
main = do
putStr "Smallest number ending by 19 multiple of 23: "
putStrLn $ show $ genS 23 19
putStrLn $ "Euler 134: " ++ (show $ euler 1000000)
|
dpieroux/euler
|
0134.hs
|
Haskell
|
mit
| 1,797
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
module WS.App where
import Control.Applicative ((<$>), (<*>))
import Control.Exception (Exception)
import Control.Monad.Catch (MonadThrow, MonadCatch, throwM, catch)
import Control.Monad.Trans.Class (lift)
import qualified Control.Monad.Trans.Either as E
import qualified Data.ByteString.Char8 as BS
import Data.Text (Text, pack)
import Data.Time (getCurrentTimeZone, getCurrentTime, utcToLocalTime, LocalTime)
import Data.Typeable (Typeable)
import Database.Relational.Query
import Servant
import WS.Cache as Cache
import WS.DB as DB
import WS.Mail as Mail
import qualified WS.Types as User
import WS.Types (User, user, tableOfUser, InsertUser(..), piUser, RegForm(..), LoginForm(..))
type API = "register" :> ReqBody '[JSON] RegForm :> Post '[JSON] User
:<|> "login" :> ReqBody '[JSON] LoginForm :> Post '[] ()
:<|> "users" :> Capture "userId" Int :> Get '[JSON] User
api :: Proxy API
api = Proxy
server :: Server API
server = registerH
:<|> loginH
:<|> getUserH
where
registerH f = lift (register f) `catch` errorH
loginH f = lift (login f) `catch` errorH
getUserH i = lift (getUser i) `catch` errorH
-- errorH :: Monad m => AppException -> E.EitherT ServantErr m a
errorH NotFound = E.left err404
-- handlers
adminAddress :: Text
adminAddress = "admin@example.com"
data AppException = NotFound deriving (Show, Typeable)
instance Exception AppException
class (MonadCatch m, MonadMail m, MonadCache m, MonadDB m) => App m where
getCurrentLocalTime :: m LocalTime
instance App IO where
getCurrentLocalTime = utcToLocalTime <$> getCurrentTimeZone <*> getCurrentTime
register :: App m => RegForm -> m User
register form = do
lt <- getCurrentLocalTime
_ <- insertUser' (regName form) (regEmailAddress form) lt
user' <- getUserByName (regName form)
sendMail
adminAddress
(User.emailAddress user')
"register"
(pack $ "registered at " ++ show lt)
return user'
login :: App m => LoginForm -> m ()
login form = do
lt <- getCurrentLocalTime
let name' = loginName form
_ <- updateUser' name' lt
user' <- getUserByName name'
sendMail
adminAddress
(User.emailAddress user')
"login"
(pack $ "logged-in at " ++ show lt)
getUser :: App m => Int -> m User
getUser userId = do
u <- getUserCache userId
case u of
Just u' -> return u'
Nothing -> do
u' <- getUserById userId
setUserCache u'
return u'
-- operations
getUserCache :: MonadCache m => Int -> m (Maybe User)
getUserCache pk = Cache.get (BS.pack . show $ pk)
setUserCache :: MonadCache m => User -> m ()
setUserCache u = Cache.set (BS.pack . show $ User.id u) u
insertUser' :: MonadDB m => Text -> Text -> LocalTime -> m Integer
insertUser' name addr time = insert (typedInsert tableOfUser piUser) ins
where
ins = InsertUser { insName = name
, insEmailAddress = addr
, insCreatedAt = time
, insLastLoggedinAt = time
}
updateUser' :: MonadDB m => Text -> LocalTime -> m Integer
updateUser' name time = update (typedUpdate tableOfUser target) ()
where
target = updateTarget $ \proj -> do
User.lastLoggedinAt' <-# value time
wheres $ proj ! User.name' .=. value name
getUserById :: (MonadThrow m, MonadDB m) => Int -> m User
getUserById pk = do
res <- select (relationalQuery rel) (fromIntegral pk)
if null res
then throwM NotFound
else return $ head res
where
rel = relation' . placeholder $ \ph -> do
u <- query user
wheres $ u ! User.id' .=. ph
return u
getUserByName :: (MonadThrow m, MonadDB m) => Text -> m User
getUserByName name = do
res <- select (relationalQuery rel) name
if null res
then throwM NotFound
else return $ head res
where
rel = relation' . placeholder $ \ph -> do
u <- query user
wheres $ u ! User.name' .=. ph
return u
|
krdlab/haskell-webapp-testing-experimentation
|
src/WS/App.hs
|
Haskell
|
mit
| 4,212
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
class TooMany a where
tooMany :: a -> Bool
instance TooMany Int where
tooMany n = n > 42
{-
newtype Goats = Goats Int deriving Show
-}
-- with GeneralizedNewtypeDeriving, we can get this automatically:
newtype Goats = Goats Int deriving (Show, Num)
instance TooMany Goats where
tooMany (Goats n) = n > 43
{-
-- reuse the original TooMany Int instance we made above:
instance TooMany Goats where
tooMany (Goats n) = tooMany n
-}
-- exercises:
-- make a TooMany instance for (Int, String)
-- with newtype:
newtype Goats' = Goats' (Int, String) deriving Show
instance TooMany Goats' where
tooMany (Goats' (n, _)) = n > 43
-- with FlexibleInstances:
instance TooMany (Int, String) where
tooMany (n,_) = n > 43
-- Make a TooMany instance for (Int, Int), check sum
--instance TooMany (Int, Int) where
-- tooMany (x,y) = (x+y) > 43
-- make a TooMany instance for (Num a, TooMany a) => (a, a)
instance (Num a, TooMany a) => TooMany (a, a) where
tooMany (x, y) = tooMany (x+y)
|
JustinUnger/haskell-book
|
ch11/learn.hs
|
Haskell
|
mit
| 1,105
|
{-# LANGUAGE BangPatterns, CPP, FlexibleContexts #-}
-- |
-- Module : Statistics.Correlation.Kendall
--
-- Fast O(NlogN) implementation of
-- <http://en.wikipedia.org/wiki/Kendall_tau_rank_correlation_coefficient Kendall's tau>.
--
-- This module implementes Kendall's tau form b which allows ties in the data.
-- This is the same formula used by other statistical packages, e.g., R, matlab.
--
-- $$\tau = \frac{n_c - n_d}{\sqrt{(n_0 - n_1)(n_0 - n_2)}}$$
--
-- where $n_0 = n(n-1)/2$, $n_1 = number of pairs tied for the first quantify$,
-- $n_2 = number of pairs tied for the second quantify$,
-- $n_c = number of concordant pairs$, $n_d = number of discordant pairs$.
module Statistics.Correlation.Kendall
( kendall
, kendallMatrix
-- * References
-- $references
) where
import Control.Monad.ST (ST, runST)
import Data.Bits (shiftR)
import Data.Function (on)
import Data.STRef
import qualified Data.Vector.Algorithms.Intro as I
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Generic.Mutable as GM
import qualified Data.Vector.Unboxed as U
import qualified Data.Matrix.Generic as MG
import qualified Data.Matrix.Symmetric as MS
import Statistics.Correlation.Internal
-- | /O(nlogn)/ Compute the Kendall's tau from a vector of paired data.
-- Return NaN when number of pairs <= 1.
kendall :: (Ord a, Ord b, G.Vector v (a, b)) => v (a, b) -> Double
kendall xy'
| G.length xy' <= 1 = 0/0
| otherwise = runST $ do
xy <- G.thaw xy'
let n = GM.length xy
n_dRef <- newSTRef 0
I.sort xy
tieX <- numOfTiesBy ((==) `on` fst) xy
tieXY <- numOfTiesBy (==) xy
tmp <- GM.new n
mergeSort (compare `on` snd) xy tmp n_dRef
tieY <- numOfTiesBy ((==) `on` snd) xy
n_d <- readSTRef n_dRef
let n_0 = (fromIntegral n * (fromIntegral n-1)) `shiftR` 1 :: Integer
n_c = n_0 - n_d - tieX - tieY + tieXY
return $ fromIntegral (n_c - n_d) /
(sqrt.fromIntegral) ((n_0 - tieX) * (n_0 - tieY))
{-# INLINE kendall #-}
kendallMatrix :: (Ord a, MG.Matrix m v a, G.Vector v (a,a))
=> m v a -> MS.SymMatrix U.Vector Double
kendallMatrix = correlationMatrix kendall
{-# INLINE kendallMatrix #-}
-- calculate number of tied pairs in a sorted vector
numOfTiesBy :: GM.MVector v a
=> (a -> a -> Bool) -> v s a -> ST s Integer
numOfTiesBy f xs = do count <- newSTRef (0::Integer)
loop count (1::Int) (0::Int)
readSTRef count
where
n = GM.length xs
loop c !acc !i | i >= n - 1 = modifySTRef' c (+ g acc)
| otherwise = do
x1 <- GM.unsafeRead xs i
x2 <- GM.unsafeRead xs (i+1)
if f x1 x2
then loop c (acc+1) (i+1)
else modifySTRef' c (+ g acc) >> loop c 1 (i+1)
g x = fromIntegral ((x * (x - 1)) `shiftR` 1)
{-# INLINE numOfTiesBy #-}
-- Implementation of Knight's merge sort (adapted from vector-algorithm). This
-- function is used to count the number of discordant pairs.
mergeSort :: GM.MVector v e
=> (e -> e -> Ordering)
-> v s e
-> v s e
-> STRef s Integer
-> ST s ()
mergeSort cmp src buf count = loop 0 (GM.length src - 1)
where
loop l u
| u == l = return ()
| u - l == 1 = do
eL <- GM.unsafeRead src l
eU <- GM.unsafeRead src u
case cmp eL eU of
GT -> do GM.unsafeWrite src l eU
GM.unsafeWrite src u eL
modifySTRef' count (+1)
_ -> return ()
| otherwise = do
let mid = (u + l) `shiftR` 1
loop l mid
loop mid u
merge cmp (GM.unsafeSlice l (u-l+1) src) buf (mid - l) count
{-# INLINE mergeSort #-}
merge :: GM.MVector v e
=> (e -> e -> Ordering)
-> v s e
-> v s e
-> Int
-> STRef s Integer
-> ST s ()
merge cmp src buf mid count = do GM.unsafeCopy tmp lower
eTmp <- GM.unsafeRead tmp 0
eUpp <- GM.unsafeRead upper 0
loop tmp 0 eTmp upper 0 eUpp 0
where
lower = GM.unsafeSlice 0 mid src
upper = GM.unsafeSlice mid (GM.length src - mid) src
tmp = GM.unsafeSlice 0 mid buf
wroteHigh low iLow eLow high iHigh iIns
| iHigh >= GM.length high =
GM.unsafeCopy (GM.unsafeSlice iIns (GM.length low - iLow) src)
(GM.unsafeSlice iLow (GM.length low - iLow) low)
| otherwise = do eHigh <- GM.unsafeRead high iHigh
loop low iLow eLow high iHigh eHigh iIns
wroteLow low iLow high iHigh eHigh iIns
| iLow >= GM.length low = return ()
| otherwise = do eLow <- GM.unsafeRead low iLow
loop low iLow eLow high iHigh eHigh iIns
loop !low !iLow !eLow !high !iHigh !eHigh !iIns = case cmp eHigh eLow of
LT -> do GM.unsafeWrite src iIns eHigh
modifySTRef' count (+ fromIntegral (GM.length low - iLow))
wroteHigh low iLow eLow high (iHigh+1) (iIns+1)
_ -> do GM.unsafeWrite src iIns eLow
wroteLow low (iLow+1) high iHigh eHigh (iIns+1)
{-# INLINE merge #-}
-- $references
--
-- * William R. Knight. (1966) A computer method for calculating Kendall's Tau
-- with ungrouped data. /Journal of the American Statistical Association/,
-- Vol. 61, No. 314, Part 1, pp. 436-439. <http://www.jstor.org/pss/2282833>
--
|
kaizhang/statistics-correlation
|
Statistics/Correlation/Kendall.hs
|
Haskell
|
mit
| 5,569
|
module Hoton.Types
(
Number
) where
type Number = Double
|
woufrous/hoton
|
src/Hoton/Types.hs
|
Haskell
|
mit
| 63
|
-- |
-- Module: Math.NumberTheory.Zeta.Hurwitz
-- Copyright: (c) 2018 Alexandre Rodrigues Baldé
-- Licence: MIT
-- Maintainer: Alexandre Rodrigues Baldé <alexandrer_b@outlook.com>
--
-- Hurwitz zeta function.
{-# LANGUAGE ScopedTypeVariables #-}
module Math.NumberTheory.Zeta.Hurwitz
( zetaHurwitz
) where
import Math.NumberTheory.Recurrences (bernoulli, factorial)
import Math.NumberTheory.Zeta.Utils (skipEvens, skipOdds)
-- | Values of Hurwitz zeta function evaluated at @ζ(s, a)@ for @s ∈ [0, 1 ..]@.
--
-- The algorithm used was based on the Euler-Maclaurin formula and was derived
-- from <http://fredrikj.net/thesis/thesis.pdf Fast and Rigorous Computation of Special Functions to High Precision>
-- by F. Johansson, chapter 4.8, formula 4.8.5.
-- The error for each value in this recurrence is given in formula 4.8.9 as an
-- indefinite integral, and in formula 4.8.12 as a closed form formula.
--
-- It is the __user's responsibility__ to provide an appropriate precision for
-- the type chosen.
--
-- For instance, when using @Double@s, it does not make sense
-- to provide a number @ε < 1e-53@ as the desired precision. For @Float@s,
-- providing an @ε < 1e-24@ also does not make sense.
-- Example of how to call the function:
--
-- >>> zetaHurwitz 1e-15 0.25 !! 5
-- 1024.3489745265808
zetaHurwitz :: forall a . (Floating a, Ord a) => a -> a -> [a]
zetaHurwitz eps a = zipWith3 (\s i t -> s + i + t) ss is ts
where
-- When given @1e-14@ as the @eps@ argument, this'll be
-- @div (33 * (length . takeWhile (>= 1) . iterate (/ 10) . recip) 1e-14) 10 == div (33 * 14) 10@
-- @div (33 * 14) 10 == 46.
-- meaning @N,M@ in formula 4.8.5 will be @46@.
-- Multiplying by 33 and dividing by 10 is because asking for @14@ digits
-- of decimal precision equals asking for @(log 10 / log 2) * 14 ~ 3.3 * 14 ~ 46@
-- bits of precision.
digitsOfPrecision :: Integer
digitsOfPrecision =
let magnitude = toInteger . length . takeWhile (>= 1) . iterate (/ 10) . recip $ eps
in div (magnitude * 33) 10
-- @a + n@
aPlusN :: a
aPlusN = a + fromInteger digitsOfPrecision
-- @[(a + n)^s | s <- [0, 1, 2 ..]]@
powsOfAPlusN :: [a]
powsOfAPlusN = iterate (aPlusN *) 1
-- [ [ 1 ] | ]
-- | \sum_{k=0}^\(n-1) | ----------- | | s <- [0, 1, 2 ..] |
-- [ [ (a + k) ^ s ] | ]
-- @S@ value in 4.8.5 formula.
ss :: [a]
ss = let numbers = map ((a +) . fromInteger) [0..digitsOfPrecision-1]
denoms = replicate (fromInteger digitsOfPrecision) 1 :
iterate (zipWith (*) numbers) numbers
in map (sum . map recip) denoms
-- [ (a + n) ^ (1 - s) a + n | ]
-- | ----------------- = ---------------------- | s <- [0, 1, 2 ..] |
-- [ s - 1 (a + n) ^ s * (s - 1) | ]
-- @I@ value in 4.8.5 formula.
is :: [a]
is = let denoms = zipWith
(\powOfA int -> powOfA * fromInteger int)
powsOfAPlusN
[-1, 0..]
in map (aPlusN /) denoms
-- [ 1 | ]
-- [ ----------- | s <- [0 ..] ]
-- [ (a + n) ^ s | ]
constants2 :: [a]
constants2 = map recip powsOfAPlusN
-- [ [(s)_(2*k - 1) | k <- [1 ..]], s <- [0 ..]], i.e. odd indices of
-- infinite rising factorial sequences, each sequence starting at a
-- positive integer.
pochhammers :: [[Integer]]
pochhammers = let -- [ [(s)_k | k <- [1 ..]], s <- [1 ..]]
pochhs :: [[Integer]]
pochhs = iterate (\(x : xs) -> map (`div` x) xs) (tail factorial)
in -- When @s@ is @0@, the infinite sequence of rising
-- factorials starting at @s@ is @[0,0,0,0..]@.
repeat 0 : map skipOdds pochhs
-- [ B_2k | ]
-- | ------------------------- | k <- [1 ..] |
-- [ (2k)! (a + n) ^ (2*k - 1) | ]
second :: [a]
second =
take (fromInteger digitsOfPrecision) $
zipWith3
(\bern evenFac denom -> fromRational bern / (denom * fromInteger evenFac))
(tail $ skipOdds bernoulli)
(tail $ skipOdds factorial)
-- Recall that @powsOfAPlusN = [(a + n) ^ s | s <- [0 ..]]@, so this
-- is @[(a + n) ^ (2 * s - 1) | s <- [1 ..]]@
(skipEvens powsOfAPlusN)
fracs :: [a]
fracs = map
(sum . zipWith (\s p -> s * fromInteger p) second)
pochhammers
-- Infinite list of @T@ values in 4.8.5 formula, for every @s@ in
-- @[0, 1, 2 ..]@.
ts :: [a]
ts = zipWith
(\constant2 frac -> constant2 * (0.5 + frac))
constants2
fracs
|
Bodigrim/arithmoi
|
Math/NumberTheory/Zeta/Hurwitz.hs
|
Haskell
|
mit
| 4,891
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PartialTypeSignatures #-}
module Web.Views.Index where
import Model.CoreTypes
import Web.Utils
import Web.Routes as R
import Web.Views.DiamondButton
import Text.Blaze.Html5 ((!))
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
indexAction :: PortfolioAction ctx a
indexAction = blaze $ baseHeader "Index" indexBase
indexBase :: H.Html
indexBase =
H.div ! A.class_ "white black-text" $
H.main $
H.div ! A.class_ "full f f-col f-sa center" $ do
H.div ! A.class_ "f-g1 f f-center fi-center" $
H.h5 $ H.blockquote "I wanna make the world a better place /s"
H.div ! A.class_ "f-g5 f f-center f-col fi-center" $ do
H.h5 $ H.em "Linux enthusiast"
H.h1 "Tom Lebreux"
H.div ! A.class_ "f f-row f-center f-g1 fi-center" $
diamondBtn (A.href $ toHref R.aboutR) "Press here"
|
tomleb/portfolio
|
src/Web/Views/Index.hs
|
Haskell
|
mit
| 1,036
|
module Main where
import qualified Data.ByteString.Lazy.Char8 as BS
import Data.Maybe (fromJust)
import Data.Aeson (decode)
import LevelParser
import ParitySolver
main :: IO ()
main = do
fc <- BS.readFile "story.json"
let levels = map fromLevel . fromJust $ decode fc
let findPath gs = findChoosenPath $ findCompletionPath gs
-- print . findPath $ levels !! 50
print . mapM_ findPath $ take 50 levels
|
jcla1/parity-solver
|
Main.hs
|
Haskell
|
mit
| 498
|
isPrime::Integer->Bool
isPrime n = null [x | x <- [2..(floor(sqrt(fromInteger n)))], mod n x == 0]
factors::Integer->[Integer]
factors n = [x | x <- [1..n], mod n x == 0]
main::IO()
main = print $ last $ takeWhile isPrime $ factors 600851475143
|
neutronest/eulerproject-douby
|
e3/e3.hs
|
Haskell
|
mit
| 247
|
diffHam :: (Integral a) => a -> a -> a
diffHam a b
| a == 0 && b == 0 = 0
| otherwise = let rr = if (mod a 2) /= (mod b 2)
then 1
else 0
in rr + diffHam (div a 2) (div b 2)
totalHammingDistance :: (Integral a) => [a] -> a
totalHammingDistance [] = 0
totalHammingDistance (x:xs) = (sum $ map (diffHam x) xs) + totalHammingDistance xs
|
ccqpein/Arithmetic-Exercises
|
Total-Hamming-Distance/THD.hs
|
Haskell
|
apache-2.0
| 402
|
import Text.CSV
import Data.List as L
import Text.Nagato.NagatoIO as NagatoIO
import Text.Nagato.Models as Models
import Text.Nagato.MeCabTools as MeCabTools
import qualified Text.Nagato.Classify as NC
import qualified Text.Nagato.Train as Train
import qualified Text.Nagato.Train_complement as Train_compl
main = do
rawCsvData <- NagatoIO.loadCSVFileUtf8 "testData.csv"
let csvData = init rawCsvData
classes <- NagatoIO.readFromFile "classes.bin"
classesComplement <- NagatoIO.readFromFile "complementClasses.bin"
print $ fst $ unzip classes
print $ fst $ unzip classesComplement
classed <- mapM (\x->test (head x) classes classesComplement) csvData
let compared = unzip $ map (\a -> judge a) $ zip [a !! 1 | a <- csvData] classed
let accuracyNormal = (realToFrac (length (filter (==True) (fst compared)))) / (realToFrac (length csvData))
let accuracyComplement = (realToFrac (length (filter (==True) (snd compared)))) / (realToFrac (length csvData))
putStrLn "normal:"
print accuracyNormal
putStrLn "complement:"
print accuracyComplement
judge :: (String, (String, String)) -> (Bool, Bool)
judge item =
let trueAnswer = fst item
answers = snd item
in ((trueAnswer == (fst answers)),(trueAnswer == (snd answers )))
test :: String -> [(String, Props)] -> [(String, Props)] -> IO(String, String)
test text classNormal classComplement = do
wakati <- MeCabTools.parseWakati text
let wordList = words wakati
return ((NC.classify wordList classNormal), (NC.classifyComplement wordList classComplement))
trainAndSaveFromSetting :: String -> String -> IO()
trainAndSaveFromSetting settingFile saveFileName = do
trainResult <- trainFromSetting settingFile
NagatoIO.writeToFile saveFileName trainResult
trainFromSetting :: String -> IO [(String, Props)]
trainFromSetting settingFileName = do
classesList <- loadSettings settingFileName
let unzippedClasses = unzip classesList
classStrings <- loadClassStrings $ snd unzippedClasses
classesTrained <- mapM (\a -> Train.parseAndTrainClass a) classStrings
return $ zip (fst unzippedClasses) classesTrained
doTrainNormal :: String -> IO()
doTrainNormal settingName = trainAndSaveFromSetting settingName "classes.bin"
doTrainComplemnt :: String -> IO()
doTrainComplemnt settingName = doTrainCompl settingName "classes_complement.bin"
loadClassStrings :: [String] -> IO [String]
loadClassStrings settingFiles = do
if length settingFiles == 1
then do
str <- NagatoIO.loadPlainText $ head settingFiles
return [str]
else do
str <- NagatoIO.loadPlainText $ head settingFiles
deepStrs <- loadClassStrings $ drop 1 settingFiles
return $ str : deepStrs
doTrainCompl :: String -> String -> IO()
doTrainCompl settingFile saveFileName = do
counted <- countFromSetting settingFile
let complementCounts = L.map (\classItems -> ((fst classItems), (Train_compl.makeComplementClass (snd counted)))) counted
NagatoIO.writeToFile saveFileName complementCounts
countFromSetting :: String -> IO [(String, Freqs)]
countFromSetting settingFileName = do
classesList <- loadSettings settingFileName
let unzippedClasses = unzip classesList
classStrings <- loadClassStrings $ snd unzippedClasses
classesCounted <- mapM (\a -> Train.parseAndCountClass a) classStrings
return $ zip (fst unzippedClasses) classesCounted
loadSettings :: String -> IO [(String, String)]
loadSettings settingName = do
eitherCsv <- parseCSVFromFile settingName
case eitherCsv of
Right csv' -> return $ L.map (\x -> (x !! 0, x !! 1)) $ init csv'
Left e -> error $ show e
|
haru2036/nagato
|
samples/tester.hs
|
Haskell
|
apache-2.0
| 3,593
|
import Data.Set (Set)
import qualified Data.Set as Set
-- See TorusLatticeWalk.hs, this is mostly copied and pasted from there with
-- some changes to nextStatesRight and nextStatesUp
-- Notes: I can prove that the number of all cylinder walks is w^h where w is
-- the width, and h is the right. (At each height, take 0, 1, ..., w-1) steps,
-- at the final height, there's only one choice to make.
-- I believe that the maximum number of steps from (0,0) to (0, h) is w*h + (h % w).
-- The main diagonal and off-diagonals seem to have nice structure when counting
-- maximal walks.
-- n x n torus (A324603)
-- n x m torus (A324604)
-- n x m torus steps in maximal walk (A306779)
-- n x m torus number of maximal walks (A324605)
-- n x n torus maximal (A056188?)
-- n x n torus up >= right (A324606)
-- n x m torus up >= right (A324607)
-- n x n torus up > right (A324608)
-- n x n cylinder
-- n x m cylinder
-- n x n cylinder maximal
-- n x m cylinder maximal
-- n x n cylinder up > right
-- n x m cylinder up > right
data CurrentState = Intersected | Completed (Set Position) | Ongoing State deriving (Show, Eq)
type Position = (Int, Int)
type State = (Position, Set Position)
maximalCylinderWalks n m = recurse [] [Ongoing ((0, 0), Set.singleton (0,0))] where
recurse completedWalks [] = completedWalks
recurse completedWalks ongoingStates = recurse completedWalks' ongoingStates' where
nextStates = concatMap (\s -> [nextStatesRight n m s, nextStatesUp m s]) ongoingStates
ongoingStates' = filter isOngoing nextStates
completedWalks' = if null cW then completedWalks else cW where
cW = filter isCompleted nextStates
allCylinderWalks n m = recurse [] [Ongoing ((0, 0), Set.singleton (0,0))] where
recurse completedWalks [] = completedWalks
recurse completedWalks ongoingStates = recurse completedWalks' ongoingStates' where
nextStates = concatMap (\s -> [nextStatesRight n m s, nextStatesUp m s]) ongoingStates
ongoingStates' = filter isOngoing nextStates
completedWalks' = completedWalks ++ filter isCompleted nextStates
nextStatesRight :: Int -> Int -> CurrentState -> CurrentState
nextStatesRight width height (Ongoing ((x, y), pastPositions))
| newPosition == (0, height) = Completed pastPositions
| newPosition `elem` pastPositions = Intersected
| otherwise = Ongoing (newPosition, Set.insert newPosition pastPositions) where
newPosition = ((x + 1) `mod` width, y)
nextStatesUp :: Int -> CurrentState -> CurrentState
nextStatesUp height (Ongoing ((x, y), pastPositions))
| newPosition == (0, height) = Completed pastPositions
| y == height = Intersected
| newPosition `elem` pastPositions = Intersected
| otherwise = Ongoing (newPosition, Set.insert newPosition pastPositions) where
newPosition = (x, y + 1)
isCompleted :: CurrentState -> Bool
isCompleted (Completed _) = True
isCompleted _ = False
isOngoing :: CurrentState -> Bool
isOngoing (Ongoing _) = True
isOngoing _ = False
-- n x n torus
-- n x m torus
-- n x m torus size of maximal walk
-- n x m torus number of maximal walks
-- * n x n torus maximal
-- n x m torus maximal
-- n x n torus up > right
-- n x m torus up > right
-- n x n cylinder
-- n x m cylinder
-- n x n cylinder maximal
-- n x m cylinder maximal
-- n x n cylinder up > right
-- n x m cylinder up > right
stepCount :: CurrentState -> Int
stepCount Intersected = error "Intersected"
stepCount (Ongoing _) = error "Ongoing!"
stepCount (Completed steps) = length steps
|
peterokagey/haskellOEIS
|
src/Sandbox/CylinderLatticeWalk.hs
|
Haskell
|
apache-2.0
| 3,524
|
module Arbitrary.File where
import Test.QuickCheck
--import qualified Data.Test as T
import Filesystem.Path.CurrentOS
import Prelude hiding (FilePath, writeFile)
import qualified Data.Set as S
import Control.Applicative
import Data.ModulePath
import Control.Lens
import Arbitrary.TestModule (toGenerated, testModulePath)
import Arbitrary.FilePath
import Arbitrary.Properties
import Language.Haskell.Exts
import Language.Haskell.Exts.SrcLoc (noLoc)
import Data.Integrated.TestModule
import qualified Data.List as L
import qualified Data.Property as P
import Control.Monad.State
isTest :: Content -> Bool
isTest (Left _) = True
isTest _ = False
type Nonsense = String
type Content = Either TestModule Nonsense
data File = File { path :: FilePath, content :: Content }
instance Show File where
show (File p (Left t)) = show p ++ ": \n" ++ show t
show (File p (Right n)) = show p ++ ": \n" ++ show n
toStr :: TestModule -> String
toStr tm =
prettyPrint (toModule [] $ view modpath tm) ++ '\n' : append_properties_buf
where
append_properties_buf :: String
append_properties_buf =
L.intercalate "\n" . map (\f -> P.func f ++ " = undefined") $
view properties tm
-- Note, Nonsense can contain erroneously test data
-- or have a test like path with erroneous data
nonSenseGen :: Gen Char -> S.Set FilePath -> Gen File
nonSenseGen subpath avoided =
(\(p,b) -> File p (Right b)) <$>
frequency [ (1, testModule), (2, fakeModule), (2, nonModule) ]
where
testModule,fakeModule,nonModule :: Gen (FilePath, String)
testModule = do -- This case should fail gracefully.
mp <- testModulePath subpath S.empty
buf <- oneof [ garbageBuf, testBuf mp ]
return (relPath mp, buf)
fakeModule = do
mp <- suchThat arbitrary (not . flip S.member avoided . relPath)
buf <- oneof [ testBuf mp, moduleBuf mp ]
return (relPath mp, buf)
nonModule = liftM2 (,) (filepathGen subpath) garbageBuf
moduleBuf,testBuf :: ModulePath -> Gen String
testBuf mp = toStr . TestModule mp . list <$> (arbitrary :: Gen Properties)
moduleBuf mp =
return . prettyPrint $
Module noLoc (ModuleName $ show mp) [] Nothing Nothing [] []
garbageBuf :: Gen String
garbageBuf = return "Nonsense"
fileGen :: Gen Char -> StateT (S.Set FilePath, S.Set ModulePath) Gen File
fileGen subpath = do
test <- lift $ choose (True, False)
if test
then do
avoided <- snd <$> get
(fp, tm) <- lift $ toGenerated subpath avoided
modify
(\t -> (S.insert fp . fst $ t, S.insert (view modpath tm) . snd $ t))
return $ File fp (Left tm)
else do
avoided <- fst <$> get
f <- lift $ nonSenseGen subpath avoided
modify (over _1 (S.insert (path f)))
return f
|
jfeltz/tasty-integrate
|
tests/Arbitrary/File.hs
|
Haskell
|
bsd-2-clause
| 2,787
|
module Ovid.Prelude
( JsCFAState (..)
, CFAOpts (..)
, emptyCFAOpts
, message
, warnAt
, enableUnlimitedRecursion, enablePreciseArithmetic, enablePreciseConditionals
-- source positions
, SourcePos, sourceName
-- Monads
, module Control.Monad
, module Control.Monad.Trans
, module Control.Monad.Identity
, lift2, lift3
-- module Control.Monad.State.Strict
, MonadState (..), StateT, runStateT, evalStateT
-- lists, numbers, etc
,tryInt, L.intersperse, L.isInfixOf, L.isPrefixOf, L.partition
-- others
, isJust, fromJust
, module Scheme.Write
-- Data.Traversable
, forM -- Traversable.mapM with arguments flipped; avoid conflicts with Prelude.mapM
, module Framework
-- exceptions
, try, catch, IOException
) where
import Prelude hiding (catch)
import Scheme.Write
import Text.ParserCombinators.Parsec.Pos (SourcePos, sourceName)
import Control.Monad hiding (mapM,forM)
import Control.Monad.Trans
import Control.Monad.Identity (Identity, runIdentity)
import Control.Monad.State.Strict (StateT,runStateT,evalStateT,get,put,MonadState)
import qualified System.IO as IO
import Data.Maybe
import qualified Data.List as L
import Numeric
import Framework
import Data.Traversable (forM)
import Control.Exception
import CFA.Labels (Label)
import qualified Data.Map as M
message :: MonadIO m => String -> m ()
message s = liftIO (IO.hPutStrLn IO.stdout s)
warnAt str loc = do
let sLen = length str
let truncLoc = take (80 - sLen - 7) loc
warn $ str ++ " (at " ++ truncLoc ++ ")"
lift2 m = lift (lift m)
lift3 m = lift (lift2 m)
tryInt :: String -> Maybe Int
tryInt s = case readDec s of
[(n,"")] -> Just n
otherwise -> Nothing
-- ---------------------------------------------------------------------------------------------------------------------
data JsCFAState ct = JsCFAState {
xhrSend :: Maybe Label,
jscfasBuiltins :: M.Map String Label,
-- ^function sets passed to 'application'. Verify that they have at least one function and hopefully no more than
-- one function.
jscfaFns :: [(Label,ct)],
jscfaBranches :: [(Label,ct)],
jscfaOpts :: CFAOpts,
jscfaGlobals :: [Label] -- ^list of globals; this is augmented as JavaScript is dynamically loaded
}
--------------------------------------------------------------------------------
-- Options that affect the analysis
-- |Options that control the analysis
data CFAOpts = CFAOpts {
-- |A recursive function take time exponential (in the number of syntactic
-- recursive calls) to analyze. This behavior is also observable for
-- mutually recursive functions. By default, the analysis detects this
-- behavior and halts early. However, this can break certain libraries
-- such as Flapjax.
cfaOptUnlimitedRecursion :: [String],
-- |By default, we do not perform primitive arithmetic operations. Instead,
-- their results are approximated by 'AnyNum'. However, this approximation
-- can break common implementations of library functions, such as the
-- functions in the Flapjax library.
cfaOptsPreciseArithmetic :: [String],
-- |The analysis disregards the test expression in conditionals by default.
cfaOptsPreciseConditionals :: [String]
} deriving (Show)
-- |No options specified. These are effectively "defaults." By default,
-- "flapjax/flapjax.js" and "../flapjax/flapjax.js" are permitted to
-- recurse exponentially. However, in practice, this does not happen, but
-- just allows combinators from flapjax.js to weave through application-specific
-- code.
emptyCFAOpts :: CFAOpts
emptyCFAOpts =
CFAOpts ["flapjax/flapjax.js","../flapjax/flapjax.js","DOM.js"]
["flapjax/flapjax.js","../flapjax/flapjax.js","DOM.js"]
["flapjax/flapjax.js","../flapjax/flapjax.js","DOM.js"]
updateCFAOpts :: (CFAOpts -> CFAOpts) -> JsCFAState ct -> JsCFAState ct
updateCFAOpts f st@JsCFAState{jscfaOpts=opts} = st{jscfaOpts=f opts}
enableUnlimitedRecursion path =
updateCFAOpts $ \opts -> opts { cfaOptUnlimitedRecursion = path:(cfaOptUnlimitedRecursion opts) }
enablePreciseArithmetic path =
updateCFAOpts $ \opts -> opts { cfaOptsPreciseArithmetic = path:(cfaOptsPreciseArithmetic opts) }
enablePreciseConditionals path =
updateCFAOpts $ \opts -> opts { cfaOptsPreciseConditionals = path:(cfaOptsPreciseConditionals opts) }
|
brownplt/ovid
|
src/Ovid/Prelude.hs
|
Haskell
|
bsd-2-clause
| 4,321
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTreeWidget_h.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:27
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTreeWidget_h where
import Foreign.C.Types
import Qtc.Enums.Base
import Qtc.Enums.Gui.QItemSelectionModel
import Qtc.Enums.Gui.QAbstractItemView
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Enums.Gui.QAbstractItemDelegate
import Qtc.Classes.Base
import Qtc.Classes.Qccs_h
import Qtc.Classes.Core_h
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui_h
import Qtc.ClassTypes.Gui
import Foreign.Marshal.Array
instance QunSetUserMethod (QTreeWidget ()) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
foreign import ccall "qtc_QTreeWidget_unSetUserMethod" qtc_QTreeWidget_unSetUserMethod :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO (CBool)
instance QunSetUserMethod (QTreeWidgetSc a) where
unSetUserMethod qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid)
instance QunSetUserMethodVariant (QTreeWidget ()) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariant (QTreeWidgetSc a) where
unSetUserMethodVariant qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid)
instance QunSetUserMethodVariantList (QTreeWidget ()) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QunSetUserMethodVariantList (QTreeWidgetSc a) where
unSetUserMethodVariantList qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
qtc_QTreeWidget_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid)
instance QsetUserMethod (QTreeWidget ()) (QTreeWidget x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTreeWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTreeWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTreeWidget_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setUserMethod" qtc_QTreeWidget_setUserMethod :: Ptr (TQTreeWidget a) -> CInt -> Ptr (Ptr (TQTreeWidget x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethod_QTreeWidget :: (Ptr (TQTreeWidget x0) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO ()))
foreign import ccall "wrapper" wrapSetUserMethod_QTreeWidget_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTreeWidgetSc a) (QTreeWidget x0 -> IO ()) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethod_QTreeWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethod_QTreeWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTreeWidget_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO ()
setHandlerWrapper x0
= do
x0obj <- objectFromPtr_nf x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetUserMethod (QTreeWidget ()) (QTreeWidget x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTreeWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTreeWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTreeWidget_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setUserMethodVariant" qtc_QTreeWidget_setUserMethodVariant :: Ptr (TQTreeWidget a) -> CInt -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTreeWidget :: (Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))))
foreign import ccall "wrapper" wrapSetUserMethodVariant_QTreeWidget_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetUserMethod (QTreeWidgetSc a) (QTreeWidget x0 -> QVariant () -> IO (QVariant ())) where
setUserMethod _eobj _eid _handler
= do
funptr <- wrapSetUserMethodVariant_QTreeWidget setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetUserMethodVariant_QTreeWidget_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
qtc_QTreeWidget_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return ()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
setHandlerWrapper x0 x1
= do
x0obj <- objectFromPtr_nf x0
x1obj <- objectFromPtr_nf x1
rv <- if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
withObjectPtr rv $ \cobj_rv -> return cobj_rv
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QunSetHandler (QTreeWidget ()) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTreeWidget_unSetHandler cobj_qobj cstr_evid
foreign import ccall "qtc_QTreeWidget_unSetHandler" qtc_QTreeWidget_unSetHandler :: Ptr (TQTreeWidget a) -> CWString -> IO (CBool)
instance QunSetHandler (QTreeWidgetSc a) where
unSetHandler qobj evid
= withBoolResult $
withObjectPtr qobj $ \cobj_qobj ->
withCWString evid $ \cstr_evid ->
qtc_QTreeWidget_unSetHandler cobj_qobj cstr_evid
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler1" qtc_QTreeWidget_setHandler1 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget1 :: (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QEvent t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget1 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget1_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdropEvent_h (QTreeWidget ()) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dropEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dropEvent" qtc_QTreeWidget_dropEvent :: Ptr (TQTreeWidget a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent_h (QTreeWidgetSc a) ((QDropEvent t1)) where
dropEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dropEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QTreeWidgetItem t1 -> Int -> QObject t3 -> DropAction -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2 x3 x4
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
x3obj <- qObjectFromPtr x3
let x4enum = qEnum_fromInt $ fromCLong x4
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2int x3obj x4enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler2" qtc_QTreeWidget_setHandler2 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget2 :: (Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QTreeWidgetItem t1 -> Int -> QObject t3 -> DropAction -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget2 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget2_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQObject t3) -> CLong -> IO (CBool)
setHandlerWrapper x0 x1 x2 x3 x4
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
x3obj <- qObjectFromPtr x3
let x4enum = qEnum_fromInt $ fromCLong x4
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2int x3obj x4enum
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdropMimeData_h (QTreeWidget ()) ((QTreeWidgetItem t1, Int, QMimeData t3, DropAction)) where
dropMimeData_h x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_dropMimeData cobj_x0 cobj_x1 (toCInt x2) cobj_x3 (toCLong $ qEnum_toInt x4)
foreign import ccall "qtc_QTreeWidget_dropMimeData" qtc_QTreeWidget_dropMimeData :: Ptr (TQTreeWidget a) -> Ptr (TQTreeWidgetItem t1) -> CInt -> Ptr (TQMimeData t3) -> CLong -> IO CBool
instance QdropMimeData_h (QTreeWidgetSc a) ((QTreeWidgetItem t1, Int, QMimeData t3, DropAction)) where
dropMimeData_h x0 (x1, x2, x3, x4)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_dropMimeData cobj_x0 cobj_x1 (toCInt x2) cobj_x3 (toCLong $ qEnum_toInt x4)
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler3" qtc_QTreeWidget_setHandler3 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget3 :: (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QEvent t1 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget3 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget3_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQEvent t1) -> IO (CBool)
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance Qevent_h (QTreeWidget ()) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_event cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_event" qtc_QTreeWidget_event :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent_h (QTreeWidgetSc a) ((QEvent t1)) where
event_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_event cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO (DropActions)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (CLong)
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then withQFlagsResult $ return $ toCLong 0
else _handler x0obj
rvf <- rv
return (toCLong $ qFlags_toInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler4" qtc_QTreeWidget_setHandler4 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO (CLong)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget4 :: (Ptr (TQTreeWidget x0) -> IO (CLong)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO (CLong)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO (DropActions)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget4 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget4_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (CLong)
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then withQFlagsResult $ return $ toCLong 0
else _handler x0obj
rvf <- rv
return (toCLong $ qFlags_toInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsupportedDropActions_h (QTreeWidget ()) (()) where
supportedDropActions_h x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_supportedDropActions cobj_x0
foreign import ccall "qtc_QTreeWidget_supportedDropActions" qtc_QTreeWidget_supportedDropActions :: Ptr (TQTreeWidget a) -> IO CLong
instance QsupportedDropActions_h (QTreeWidgetSc a) (()) where
supportedDropActions_h x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_supportedDropActions cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> QModelIndex t2 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler5" qtc_QTreeWidget_setHandler5 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget5 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> QModelIndex t2 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget5 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget5_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdataChanged_h (QTreeWidget ()) ((QModelIndex t1, QModelIndex t2)) where
dataChanged_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_dataChanged cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_dataChanged" qtc_QTreeWidget_dataChanged :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> Ptr (TQModelIndex t2) -> IO ()
instance QdataChanged_h (QTreeWidgetSc a) ((QModelIndex t1, QModelIndex t2)) where
dataChanged_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_dataChanged cobj_x0 cobj_x1 cobj_x2
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler6" qtc_QTreeWidget_setHandler6 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget6 :: (Ptr (TQTreeWidget x0) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget6 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget6_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO ()
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
if (objectIsNull x0obj)
then return ()
else _handler x0obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdoItemsLayout_h (QTreeWidget ()) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_doItemsLayout cobj_x0
foreign import ccall "qtc_QTreeWidget_doItemsLayout" qtc_QTreeWidget_doItemsLayout :: Ptr (TQTreeWidget a) -> IO ()
instance QdoItemsLayout_h (QTreeWidgetSc a) (()) where
doItemsLayout_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_doItemsLayout cobj_x0
instance QdragMoveEvent_h (QTreeWidget ()) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragMoveEvent" qtc_QTreeWidget_dragMoveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent_h (QTreeWidgetSc a) ((QDragMoveEvent t1)) where
dragMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragMoveEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QPainter t1 -> QRect t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler7" qtc_QTreeWidget_setHandler7 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget7 :: (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QPainter t1 -> QRect t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget7 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget7_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqdrawBranches_h (QTreeWidget ()) ((QPainter t1, QRect t2, QModelIndex t3)) where
qdrawBranches_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QTreeWidget_drawBranches" qtc_QTreeWidget_drawBranches :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> Ptr (TQRect t2) -> Ptr (TQModelIndex t3) -> IO ()
instance QqdrawBranches_h (QTreeWidgetSc a) ((QPainter t1, QRect t2, QModelIndex t3)) where
qdrawBranches_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QdrawBranches_h (QTreeWidget ()) ((QPainter t1, Rect, QModelIndex t3)) where
drawBranches_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRect x2 $ \crect_x2_x crect_x2_y crect_x2_w crect_x2_h ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches_qth cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h cobj_x3
foreign import ccall "qtc_QTreeWidget_drawBranches_qth" qtc_QTreeWidget_drawBranches_qth :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> CInt -> CInt -> CInt -> CInt -> Ptr (TQModelIndex t3) -> IO ()
instance QdrawBranches_h (QTreeWidgetSc a) ((QPainter t1, Rect, QModelIndex t3)) where
drawBranches_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withCRect x2 $ \crect_x2_x crect_x2_y crect_x2_w crect_x2_h ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawBranches_qth cobj_x0 cobj_x1 crect_x2_x crect_x2_y crect_x2_w crect_x2_h cobj_x3
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QPainter t1 -> QStyleOption t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler8" qtc_QTreeWidget_setHandler8 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget8 :: (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QPainter t1 -> QStyleOption t2 -> QModelIndex t3 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget8 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget8_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPainter t1) -> Ptr (TQStyleOption t2) -> Ptr (TQModelIndex t3) -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
x2obj <- objectFromPtr_nf x2
x3obj <- objectFromPtr_nf x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2obj x3obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QdrawRow_h (QTreeWidget ()) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where
drawRow_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawRow cobj_x0 cobj_x1 cobj_x2 cobj_x3
foreign import ccall "qtc_QTreeWidget_drawRow" qtc_QTreeWidget_drawRow :: Ptr (TQTreeWidget a) -> Ptr (TQPainter t1) -> Ptr (TQStyleOptionViewItem t2) -> Ptr (TQModelIndex t3) -> IO ()
instance QdrawRow_h (QTreeWidgetSc a) ((QPainter t1, QStyleOptionViewItem t2, QModelIndex t3)) where
drawRow_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QTreeWidget_drawRow cobj_x0 cobj_x1 cobj_x2 cobj_x3
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler9" qtc_QTreeWidget_setHandler9 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget9 :: (Ptr (TQTreeWidget x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget9 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget9_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (CInt)
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QhorizontalOffset_h (QTreeWidget ()) (()) where
horizontalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalOffset cobj_x0
foreign import ccall "qtc_QTreeWidget_horizontalOffset" qtc_QTreeWidget_horizontalOffset :: Ptr (TQTreeWidget a) -> IO CInt
instance QhorizontalOffset_h (QTreeWidgetSc a) (()) where
horizontalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_horizontalOffset cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QPoint t1 -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler10" qtc_QTreeWidget_setHandler10 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget10 :: (Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QPoint t1 -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget10 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget10_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QindexAt_h (QTreeWidget ()) ((Point)) where
indexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QTreeWidget_indexAt_qth" qtc_QTreeWidget_indexAt_qth :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO (Ptr (TQModelIndex ()))
instance QindexAt_h (QTreeWidgetSc a) ((Point)) where
indexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QTreeWidget_indexAt_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance QqindexAt_h (QTreeWidget ()) ((QPoint t1)) where
qindexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexAt cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_indexAt" qtc_QTreeWidget_indexAt :: Ptr (TQTreeWidget a) -> Ptr (TQPoint t1) -> IO (Ptr (TQModelIndex ()))
instance QqindexAt_h (QTreeWidgetSc a) ((QPoint t1)) where
qindexAt_h x0 (x1)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_indexAt cobj_x0 cobj_x1
instance QkeyPressEvent_h (QTreeWidget ()) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyPressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_keyPressEvent" qtc_QTreeWidget_keyPressEvent :: Ptr (TQTreeWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent_h (QTreeWidgetSc a) ((QKeyEvent t1)) where
keyPressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyPressEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1str <- stringFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1str
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler11" qtc_QTreeWidget_setHandler11 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget11 :: (Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget11_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> String -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget11 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget11_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler11 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQString ()) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1str <- stringFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1str
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QkeyboardSearch_h (QTreeWidget ()) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_keyboardSearch cobj_x0 cstr_x1
foreign import ccall "qtc_QTreeWidget_keyboardSearch" qtc_QTreeWidget_keyboardSearch :: Ptr (TQTreeWidget a) -> CWString -> IO ()
instance QkeyboardSearch_h (QTreeWidgetSc a) ((String)) where
keyboardSearch_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QTreeWidget_keyboardSearch cobj_x0 cstr_x1
instance QmouseDoubleClickEvent_h (QTreeWidget ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseDoubleClickEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseDoubleClickEvent" qtc_QTreeWidget_mouseDoubleClickEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent_h (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseDoubleClickEvent cobj_x0 cobj_x1
instance QmouseMoveEvent_h (QTreeWidget ()) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseMoveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseMoveEvent" qtc_QTreeWidget_mouseMoveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent_h (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseMoveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseMoveEvent cobj_x0 cobj_x1
instance QmousePressEvent_h (QTreeWidget ()) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mousePressEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mousePressEvent" qtc_QTreeWidget_mousePressEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent_h (QTreeWidgetSc a) ((QMouseEvent t1)) where
mousePressEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mousePressEvent cobj_x0 cobj_x1
instance QmouseReleaseEvent_h (QTreeWidget ()) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_mouseReleaseEvent" qtc_QTreeWidget_mouseReleaseEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent_h (QTreeWidgetSc a) ((QMouseEvent t1)) where
mouseReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_mouseReleaseEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> CursorAction -> KeyboardModifiers -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let x2flags = qFlags_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2flags
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler12" qtc_QTreeWidget_setHandler12 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget12 :: (Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget12_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> CursorAction -> KeyboardModifiers -> IO (QModelIndex t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget12 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget12_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler12 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CLong -> CLong -> IO (Ptr (TQModelIndex t0))
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let x2flags = qFlags_fromInt $ fromCLong x2
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum x2flags
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QmoveCursor_h (QTreeWidget ()) ((CursorAction, KeyboardModifiers)) where
moveCursor_h x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_moveCursor" qtc_QTreeWidget_moveCursor :: Ptr (TQTreeWidget a) -> CLong -> CLong -> IO (Ptr (TQModelIndex ()))
instance QmoveCursor_h (QTreeWidgetSc a) ((CursorAction, KeyboardModifiers)) where
moveCursor_h x0 (x1, x2)
= withQModelIndexResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_moveCursor cobj_x0 (toCLong $ qEnum_toInt x1) (toCLong $ qFlags_toInt x2)
instance QpaintEvent_h (QTreeWidget ()) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_paintEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_paintEvent" qtc_QTreeWidget_paintEvent :: Ptr (TQTreeWidget a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent_h (QTreeWidgetSc a) ((QPaintEvent t1)) where
paintEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_paintEvent cobj_x0 cobj_x1
instance Qreset_h (QTreeWidget ()) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_reset cobj_x0
foreign import ccall "qtc_QTreeWidget_reset" qtc_QTreeWidget_reset :: Ptr (TQTreeWidget a) -> IO ()
instance Qreset_h (QTreeWidgetSc a) (()) (IO ()) where
reset_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_reset cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
let x3int = fromCInt x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2int x3int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler13" qtc_QTreeWidget_setHandler13 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget13 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget13_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget13 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget13_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler13 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2 x3
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2int = fromCInt x2
let x3int = fromCInt x3
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2int x3int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QrowsAboutToBeRemoved_h (QTreeWidget ()) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTreeWidget_rowsAboutToBeRemoved" qtc_QTreeWidget_rowsAboutToBeRemoved :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsAboutToBeRemoved_h (QTreeWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsAboutToBeRemoved_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsAboutToBeRemoved cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QrowsInserted_h (QTreeWidget ()) ((QModelIndex t1, Int, Int)) where
rowsInserted_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
foreign import ccall "qtc_QTreeWidget_rowsInserted" qtc_QTreeWidget_rowsInserted :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CInt -> CInt -> IO ()
instance QrowsInserted_h (QTreeWidgetSc a) ((QModelIndex t1, Int, Int)) where
rowsInserted_h x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_rowsInserted cobj_x0 cobj_x1 (toCInt x2) (toCInt x3)
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler14" qtc_QTreeWidget_setHandler14 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget14 :: (Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget14_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> Int -> Int -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget14 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget14_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler14 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CInt -> CInt -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
let x1int = fromCInt x1
let x2int = fromCInt x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1int x2int
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QscrollContentsBy_h (QTreeWidget ()) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QTreeWidget_scrollContentsBy" qtc_QTreeWidget_scrollContentsBy :: Ptr (TQTreeWidget a) -> CInt -> CInt -> IO ()
instance QscrollContentsBy_h (QTreeWidgetSc a) ((Int, Int)) where
scrollContentsBy_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_scrollContentsBy cobj_x0 (toCInt x1) (toCInt x2)
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler15" qtc_QTreeWidget_setHandler15 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget15 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget15_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget15 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget15_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler15 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> ScrollHint -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2enum
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler16" qtc_QTreeWidget_setHandler16 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget16 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget16_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> ScrollHint -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget16 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget16_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler16 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2enum = qEnum_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2enum
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QscrollTo_h (QTreeWidget ()) ((QModelIndex t1)) where
scrollTo_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_scrollTo" qtc_QTreeWidget_scrollTo :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO ()
instance QscrollTo_h (QTreeWidgetSc a) ((QModelIndex t1)) where
scrollTo_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo cobj_x0 cobj_x1
instance QscrollTo_h (QTreeWidget ()) ((QModelIndex t1, ScrollHint)) where
scrollTo_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
foreign import ccall "qtc_QTreeWidget_scrollTo1" qtc_QTreeWidget_scrollTo1 :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> CLong -> IO ()
instance QscrollTo_h (QTreeWidgetSc a) ((QModelIndex t1, ScrollHint)) where
scrollTo_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_scrollTo1 cobj_x0 cobj_x1 (toCLong $ qEnum_toInt x2)
instance QselectAll_h (QTreeWidget ()) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_selectAll cobj_x0
foreign import ccall "qtc_QTreeWidget_selectAll" qtc_QTreeWidget_selectAll :: Ptr (TQTreeWidget a) -> IO ()
instance QselectAll_h (QTreeWidgetSc a) (()) where
selectAll_h x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_selectAll cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler17" qtc_QTreeWidget_setHandler17 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget17 :: (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget17_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QObject t1 -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget17 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget17_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler17 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetModel_h (QTreeWidget ()) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setModel cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setModel" qtc_QTreeWidget_setModel :: Ptr (TQTreeWidget a) -> Ptr (TQAbstractItemModel t1) -> IO ()
instance QsetModel_h (QTreeWidgetSc a) ((QAbstractItemModel t1)) where
setModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setModel cobj_x0 cobj_x1
instance QsetRootIndex_h (QTreeWidget ()) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setRootIndex cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setRootIndex" qtc_QTreeWidget_setRootIndex :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO ()
instance QsetRootIndex_h (QTreeWidgetSc a) ((QModelIndex t1)) where
setRootIndex_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setRootIndex cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QRect t1 -> SelectionFlags -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2flags = qFlags_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2flags
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler18" qtc_QTreeWidget_setHandler18 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget18 :: (Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget18_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QRect t1 -> SelectionFlags -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget18 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget18_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler18 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQRect t1) -> CLong -> IO ()
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let x2flags = qFlags_fromInt $ fromCLong x2
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1obj x2flags
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqsetSelection_h (QTreeWidget ()) ((QRect t1, SelectionFlags)) where
qsetSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_setSelection" qtc_QTreeWidget_setSelection :: Ptr (TQTreeWidget a) -> Ptr (TQRect t1) -> CLong -> IO ()
instance QqsetSelection_h (QTreeWidgetSc a) ((QRect t1, SelectionFlags)) where
qsetSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelection cobj_x0 cobj_x1 (toCLong $ qFlags_toInt x2)
instance QsetSelection_h (QTreeWidget ()) ((Rect, SelectionFlags)) where
setSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QTreeWidget_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
foreign import ccall "qtc_QTreeWidget_setSelection_qth" qtc_QTreeWidget_setSelection_qth :: Ptr (TQTreeWidget a) -> CInt -> CInt -> CInt -> CInt -> CLong -> IO ()
instance QsetSelection_h (QTreeWidgetSc a) ((Rect, SelectionFlags)) where
setSelection_h x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QTreeWidget_setSelection_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h (toCLong $ qFlags_toInt x2)
instance QsetSelectionModel_h (QTreeWidget ()) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelectionModel cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_setSelectionModel" qtc_QTreeWidget_setSelectionModel :: Ptr (TQTreeWidget a) -> Ptr (TQItemSelectionModel t1) -> IO ()
instance QsetSelectionModel_h (QTreeWidgetSc a) ((QItemSelectionModel t1)) where
setSelectionModel_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_setSelectionModel cobj_x0 cobj_x1
instance QverticalOffset_h (QTreeWidget ()) (()) where
verticalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalOffset cobj_x0
foreign import ccall "qtc_QTreeWidget_verticalOffset" qtc_QTreeWidget_verticalOffset :: Ptr (TQTreeWidget a) -> IO CInt
instance QverticalOffset_h (QTreeWidgetSc a) (()) where
verticalOffset_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_verticalOffset cobj_x0
instance QviewportEvent_h (QTreeWidget ()) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_viewportEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_viewportEvent" qtc_QTreeWidget_viewportEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO CBool
instance QviewportEvent_h (QTreeWidgetSc a) ((QEvent t1)) where
viewportEvent_h x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_viewportEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QModelIndex t1 -> IO (QRect t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget19 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget19_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler19 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler19" qtc_QTreeWidget_setHandler19 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget19 :: (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget19_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QModelIndex t1 -> IO (QRect t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget19 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget19_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler19 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqvisualRect_h (QTreeWidget ()) ((QModelIndex t1)) where
qvisualRect_h x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_visualRect" qtc_QTreeWidget_visualRect :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> IO (Ptr (TQRect ()))
instance QqvisualRect_h (QTreeWidgetSc a) ((QModelIndex t1)) where
qvisualRect_h x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect cobj_x0 cobj_x1
instance QvisualRect_h (QTreeWidget ()) ((QModelIndex t1)) where
visualRect_h x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QTreeWidget_visualRect_qth" qtc_QTreeWidget_visualRect_qth :: Ptr (TQTreeWidget a) -> Ptr (TQModelIndex t1) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QvisualRect_h (QTreeWidgetSc a) ((QModelIndex t1)) where
visualRect_h x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRect_qth cobj_x0 cobj_x1 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QItemSelection t1 -> IO (QRegion t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget20 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget20_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler20 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler20" qtc_QTreeWidget_setHandler20 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget20 :: (Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget20_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QItemSelection t1 -> IO (QRegion t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget20 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget20_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler20 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- objectFromPtr_nf x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QvisualRegionForSelection_h (QTreeWidget ()) ((QItemSelection t1)) where
visualRegionForSelection_h x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRegionForSelection cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_visualRegionForSelection" qtc_QTreeWidget_visualRegionForSelection :: Ptr (TQTreeWidget a) -> Ptr (TQItemSelection t1) -> IO (Ptr (TQRegion ()))
instance QvisualRegionForSelection_h (QTreeWidgetSc a) ((QItemSelection t1)) where
visualRegionForSelection_h x0 (x1)
= withQRegionResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_visualRegionForSelection cobj_x0 cobj_x1
instance QdragEnterEvent_h (QTreeWidget ()) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragEnterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragEnterEvent" qtc_QTreeWidget_dragEnterEvent :: Ptr (TQTreeWidget a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent_h (QTreeWidgetSc a) ((QDragEnterEvent t1)) where
dragEnterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragEnterEvent cobj_x0 cobj_x1
instance QdragLeaveEvent_h (QTreeWidget ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragLeaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_dragLeaveEvent" qtc_QTreeWidget_dragLeaveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent_h (QTreeWidgetSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_dragLeaveEvent cobj_x0 cobj_x1
instance QfocusInEvent_h (QTreeWidget ()) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusInEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_focusInEvent" qtc_QTreeWidget_focusInEvent :: Ptr (TQTreeWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent_h (QTreeWidgetSc a) ((QFocusEvent t1)) where
focusInEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusInEvent cobj_x0 cobj_x1
instance QfocusOutEvent_h (QTreeWidget ()) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusOutEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_focusOutEvent" qtc_QTreeWidget_focusOutEvent :: Ptr (TQTreeWidget a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent_h (QTreeWidgetSc a) ((QFocusEvent t1)) where
focusOutEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_focusOutEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget21 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget21_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler21 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler21" qtc_QTreeWidget_setHandler21 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget21 :: (Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget21_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> InputMethodQuery -> IO (QVariant t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget21 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget21_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler21 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CLong -> IO (Ptr (TQVariant t0))
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1enum = qEnum_fromInt $ fromCLong x1
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj x1enum
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QinputMethodQuery_h (QTreeWidget ()) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QTreeWidget_inputMethodQuery" qtc_QTreeWidget_inputMethodQuery :: Ptr (TQTreeWidget a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery_h (QTreeWidgetSc a) ((InputMethodQuery)) where
inputMethodQuery_h x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1)
instance QresizeEvent_h (QTreeWidget ()) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_resizeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_resizeEvent" qtc_QTreeWidget_resizeEvent :: Ptr (TQTreeWidget a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent_h (QTreeWidgetSc a) ((QResizeEvent t1)) where
resizeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_resizeEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget22 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget22_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler22 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler22" qtc_QTreeWidget_setHandler22 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget22 :: (Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget22_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> Int -> IO (Int)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget22 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget22_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler22 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CInt -> IO (CInt)
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1int = fromCInt x1
let rv =
if (objectIsNull x0obj)
then return 0
else _handler x0obj x1int
rvf <- rv
return (toCInt rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsizeHintForRow_h (QTreeWidget ()) ((Int)) where
sizeHintForRow_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHintForRow cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_sizeHintForRow" qtc_QTreeWidget_sizeHintForRow :: Ptr (TQTreeWidget a) -> CInt -> IO CInt
instance QsizeHintForRow_h (QTreeWidgetSc a) ((Int)) where
sizeHintForRow_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHintForRow cobj_x0 (toCInt x1)
instance QcontextMenuEvent_h (QTreeWidget ()) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_contextMenuEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_contextMenuEvent" qtc_QTreeWidget_contextMenuEvent :: Ptr (TQTreeWidget a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent_h (QTreeWidgetSc a) ((QContextMenuEvent t1)) where
contextMenuEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_contextMenuEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget23 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget23_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler23 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler23" qtc_QTreeWidget_setHandler23 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget23 :: (Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget23_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO (QSize t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget23 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget23_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler23 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (Ptr (TQSize t0))
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QqminimumSizeHint_h (QTreeWidget ()) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint cobj_x0
foreign import ccall "qtc_QTreeWidget_minimumSizeHint" qtc_QTreeWidget_minimumSizeHint :: Ptr (TQTreeWidget a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint_h (QTreeWidgetSc a) (()) where
qminimumSizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint cobj_x0
instance QminimumSizeHint_h (QTreeWidget ()) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTreeWidget_minimumSizeHint_qth" qtc_QTreeWidget_minimumSizeHint_qth :: Ptr (TQTreeWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint_h (QTreeWidgetSc a) (()) where
minimumSizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QqsizeHint_h (QTreeWidget ()) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint cobj_x0
foreign import ccall "qtc_QTreeWidget_sizeHint" qtc_QTreeWidget_sizeHint :: Ptr (TQTreeWidget a) -> IO (Ptr (TQSize ()))
instance QqsizeHint_h (QTreeWidgetSc a) (()) where
qsizeHint_h x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint cobj_x0
instance QsizeHint_h (QTreeWidget ()) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QTreeWidget_sizeHint_qth" qtc_QTreeWidget_sizeHint_qth :: Ptr (TQTreeWidget a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint_h (QTreeWidgetSc a) (()) where
sizeHint_h x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h
instance QwheelEvent_h (QTreeWidget ()) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_wheelEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_wheelEvent" qtc_QTreeWidget_wheelEvent :: Ptr (TQTreeWidget a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent_h (QTreeWidgetSc a) ((QWheelEvent t1)) where
wheelEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_wheelEvent cobj_x0 cobj_x1
instance QchangeEvent_h (QTreeWidget ()) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_changeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_changeEvent" qtc_QTreeWidget_changeEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent_h (QTreeWidgetSc a) ((QEvent t1)) where
changeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_changeEvent cobj_x0 cobj_x1
instance QactionEvent_h (QTreeWidget ()) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_actionEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_actionEvent" qtc_QTreeWidget_actionEvent :: Ptr (TQTreeWidget a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent_h (QTreeWidgetSc a) ((QActionEvent t1)) where
actionEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_actionEvent cobj_x0 cobj_x1
instance QcloseEvent_h (QTreeWidget ()) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closeEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_closeEvent" qtc_QTreeWidget_closeEvent :: Ptr (TQTreeWidget a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent_h (QTreeWidgetSc a) ((QCloseEvent t1)) where
closeEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_closeEvent cobj_x0 cobj_x1
instance QdevType_h (QTreeWidget ()) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_devType cobj_x0
foreign import ccall "qtc_QTreeWidget_devType" qtc_QTreeWidget_devType :: Ptr (TQTreeWidget a) -> IO CInt
instance QdevType_h (QTreeWidgetSc a) (()) where
devType_h x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_devType cobj_x0
instance QenterEvent_h (QTreeWidget ()) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_enterEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_enterEvent" qtc_QTreeWidget_enterEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent_h (QTreeWidgetSc a) ((QEvent t1)) where
enterEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_enterEvent cobj_x0 cobj_x1
instance QheightForWidth_h (QTreeWidget ()) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_heightForWidth cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTreeWidget_heightForWidth" qtc_QTreeWidget_heightForWidth :: Ptr (TQTreeWidget a) -> CInt -> IO CInt
instance QheightForWidth_h (QTreeWidgetSc a) ((Int)) where
heightForWidth_h x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_heightForWidth cobj_x0 (toCInt x1)
instance QhideEvent_h (QTreeWidget ()) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_hideEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_hideEvent" qtc_QTreeWidget_hideEvent :: Ptr (TQTreeWidget a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent_h (QTreeWidgetSc a) ((QHideEvent t1)) where
hideEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_hideEvent cobj_x0 cobj_x1
instance QkeyReleaseEvent_h (QTreeWidget ()) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyReleaseEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_keyReleaseEvent" qtc_QTreeWidget_keyReleaseEvent :: Ptr (TQTreeWidget a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent_h (QTreeWidgetSc a) ((QKeyEvent t1)) where
keyReleaseEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_keyReleaseEvent cobj_x0 cobj_x1
instance QleaveEvent_h (QTreeWidget ()) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_leaveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_leaveEvent" qtc_QTreeWidget_leaveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent_h (QTreeWidgetSc a) ((QEvent t1)) where
leaveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_leaveEvent cobj_x0 cobj_x1
instance QmoveEvent_h (QTreeWidget ()) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_moveEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_moveEvent" qtc_QTreeWidget_moveEvent :: Ptr (TQTreeWidget a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent_h (QTreeWidgetSc a) ((QMoveEvent t1)) where
moveEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_moveEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget24 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget24_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler24 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler24" qtc_QTreeWidget_setHandler24 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget24 :: (Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget24_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> IO (QPaintEngine t0)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget24 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget24_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler24 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> IO (Ptr (TQPaintEngine t0))
setHandlerWrapper x0
= do x0obj <- qTreeWidgetFromPtr x0
let rv =
if (objectIsNull x0obj)
then return $ objectCast x0obj
else _handler x0obj
rvf <- rv
withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QpaintEngine_h (QTreeWidget ()) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_paintEngine cobj_x0
foreign import ccall "qtc_QTreeWidget_paintEngine" qtc_QTreeWidget_paintEngine :: Ptr (TQTreeWidget a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine_h (QTreeWidgetSc a) (()) where
paintEngine_h x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_paintEngine cobj_x0
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget25 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget25_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler25 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler25" qtc_QTreeWidget_setHandler25 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget25 :: (Ptr (TQTreeWidget x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> CBool -> IO ()))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget25_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> Bool -> IO ()) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget25 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget25_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler25 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> CBool -> IO ()
setHandlerWrapper x0 x1
= do x0obj <- qTreeWidgetFromPtr x0
let x1bool = fromCBool x1
if (objectIsNull x0obj)
then return ()
else _handler x0obj x1bool
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QsetVisible_h (QTreeWidget ()) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setVisible cobj_x0 (toCBool x1)
foreign import ccall "qtc_QTreeWidget_setVisible" qtc_QTreeWidget_setVisible :: Ptr (TQTreeWidget a) -> CBool -> IO ()
instance QsetVisible_h (QTreeWidgetSc a) ((Bool)) where
setVisible_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTreeWidget_setVisible cobj_x0 (toCBool x1)
instance QshowEvent_h (QTreeWidget ()) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_showEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_showEvent" qtc_QTreeWidget_showEvent :: Ptr (TQTreeWidget a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent_h (QTreeWidgetSc a) ((QShowEvent t1)) where
showEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_showEvent cobj_x0 cobj_x1
instance QtabletEvent_h (QTreeWidget ()) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_tabletEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QTreeWidget_tabletEvent" qtc_QTreeWidget_tabletEvent :: Ptr (TQTreeWidget a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent_h (QTreeWidgetSc a) ((QTabletEvent t1)) where
tabletEvent_h x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTreeWidget_tabletEvent cobj_x0 cobj_x1
instance QsetHandler (QTreeWidget ()) (QTreeWidget x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget26 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget26_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler26 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
foreign import ccall "qtc_QTreeWidget_setHandler26" qtc_QTreeWidget_setHandler26 :: Ptr (TQTreeWidget a) -> CWString -> Ptr (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO ()
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget26 :: (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)))
foreign import ccall "wrapper" wrapSetHandler_QTreeWidget26_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()))
instance QsetHandler (QTreeWidgetSc a) (QTreeWidget x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where
setHandler _eobj _eid _handler
= do
funptr <- wrapSetHandler_QTreeWidget26 setHandlerWrapper
stptr <- newStablePtr (Wrap _handler)
funptr_d <- wrapSetHandler_QTreeWidget26_d setHandlerWrapper_d
withObjectPtr _eobj $ \cobj_eobj ->
withCWString _eid $ \cstr_eid ->
qtc_QTreeWidget_setHandler26 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d)
return()
where
setHandlerWrapper :: Ptr (TQTreeWidget x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)
setHandlerWrapper x0 x1 x2
= do x0obj <- qTreeWidgetFromPtr x0
x1obj <- qObjectFromPtr x1
x2obj <- objectFromPtr_nf x2
let rv =
if (objectIsNull x0obj)
then return False
else _handler x0obj x1obj x2obj
rvf <- rv
return (toCBool rvf)
setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO ()
setHandlerWrapper_d funptr stptr funptr_d
= do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
when (funptr_d/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr_d))
return ()
instance QeventFilter_h (QTreeWidget ()) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_eventFilter cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QTreeWidget_eventFilter" qtc_QTreeWidget_eventFilter :: Ptr (TQTreeWidget a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter_h (QTreeWidgetSc a) ((QObject t1, QEvent t2)) where
eventFilter_h x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QTreeWidget_eventFilter cobj_x0 cobj_x1 cobj_x2
|
keera-studios/hsQt
|
Qtc/Gui/QTreeWidget_h.hs
|
Haskell
|
bsd-2-clause
| 132,988
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Lens
import Data.Bool (bool)
import Data.Maybe (fromMaybe)
import Data.Text (Text)
import Network.URI (URI)
import Hackerspace.Space
import qualified Network.Browser as Browser
import qualified Network.HTTP as HTTP
import qualified Network.URI as URI
import qualified Data.Aeson as Aeson
import qualified Data.Text as Text (intercalate)
import qualified Data.Text.IO as Text (putStrLn)
hackerspace :: URI
hackerspace =
let uri = "http://hackerspace-bielefeld.de/status.json" in
fromMaybe URI.nullURI $ URI.parseURI uri
spaceInfo :: Space -> Text
spaceInfo s =
Text.intercalate "\n"
[ view space s
, view (location . address) s
, "closed" `bool` "open" $ view (state . open) s
, fromMaybe "" $ view (contact . phone) s
]
main :: IO ()
main = do
(_, rsp) <- Browser.browse $ do
Browser.setOutHandler (const $ return ())
Browser.request $ HTTP.mkRequest HTTP.GET hackerspace
either
(putStrLn . ("<error>: " ++))
(Text.putStrLn . spaceInfo)
(Aeson.eitherDecode (HTTP.rspBody rsp))
|
HackerspaceBielefeld/hackerspaceapi-haskell
|
src/Main.hs
|
Haskell
|
bsd-2-clause
| 1,121
|
{- OPTIONS_GHC -fplugin Brisk.Plugin #-}
{- OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-}
{-# LANGUAGE TemplateHaskell #-}
module SpawnSym where
import Control.Monad (forM, foldM)
import Control.Distributed.Process
import Control.Distributed.BriskStatic
import Control.Distributed.Process.Closure
import Control.Distributed.Process.SymmetricProcess
import GHC.Base.Brisk
p :: ProcessId -> Process ()
p who = do self <- getSelfPid
c <- liftIO $ getChar
msg <- if c == 'x' then return (0 :: Int) else return 1
send who msg
expect :: Process ()
return ()
remotable ['p]
ack :: ProcessId -> Process ()
ack p = send p ()
req = expect :: Process Int
broadCast :: SymSet ProcessId -> Process ()
broadCast pids = do
forM pids $ \p -> req
forM pids $ \p -> ack p
return ()
main :: [NodeId] -> Process ()
main nodes = do me <- getSelfPid
symSet <- spawnSymmetric nodes $ $(mkBriskClosure 'p) me
broadCast symSet
return ()
|
abakst/brisk-prelude
|
tests/pos/SpawnSymForM.hs
|
Haskell
|
bsd-3-clause
| 1,036
|
{-# language CPP #-}
-- | = Name
--
-- VK_EXT_physical_device_drm - device extension
--
-- == VK_EXT_physical_device_drm
--
-- [__Name String__]
-- @VK_EXT_physical_device_drm@
--
-- [__Extension Type__]
-- Device extension
--
-- [__Registered Extension Number__]
-- 354
--
-- [__Revision__]
-- 1
--
-- [__Extension and Version Dependencies__]
--
-- - Requires Vulkan 1.0
--
-- - Requires @VK_KHR_get_physical_device_properties2@
--
-- [__Contact__]
--
-- - Simon Ser
-- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_physical_device_drm] @emersion%0A<<Here describe the issue or question you have about the VK_EXT_physical_device_drm extension>> >
--
-- == Other Extension Metadata
--
-- [__Last Modified Date__]
-- 2021-06-09
--
-- [__IP Status__]
-- No known IP claims.
--
-- [__Contributors__]
--
-- - Simon Ser
--
-- == Description
--
-- This extension provides new facilities to query DRM properties for
-- physical devices, enabling users to match Vulkan physical devices with
-- DRM nodes on Linux.
--
-- Its functionality closely overlaps with
-- @EGL_EXT_device_drm@<https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_physical_device_drm-fn1 1>^.
-- Unlike the EGL extension, this extension does not expose a string
-- containing the name of the device file and instead exposes device minor
-- numbers.
--
-- DRM defines multiple device node types. Each physical device may have
-- one primary node and one render node associated. Physical devices may
-- have no primary node (e.g. if the device does not have a display
-- subsystem), may have no render node (e.g. if it is a software rendering
-- engine), or may have neither (e.g. if it is a software rendering engine
-- without a display subsystem).
--
-- To query DRM properties for a physical device, chain
-- 'PhysicalDeviceDrmPropertiesEXT' to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2'.
--
-- == New Structures
--
-- - Extending
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2':
--
-- - 'PhysicalDeviceDrmPropertiesEXT'
--
-- == New Enum Constants
--
-- - 'EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME'
--
-- - 'EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION'
--
-- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType':
--
-- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT'
--
-- == References
--
-- 1. #VK_EXT_physical_device_drm-fn1#
-- <https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_device_drm.txt EGL_EXT_device_drm>
--
-- == Version History
--
-- - Revision 1, 2021-06-09
--
-- - First stable revision
--
-- == See Also
--
-- 'PhysicalDeviceDrmPropertiesEXT'
--
-- == Document Notes
--
-- For more information, see the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_physical_device_drm Vulkan Specification>
--
-- This page is a generated document. Fixes and changes should be made to
-- the generator scripts, not directly.
module Vulkan.Extensions.VK_EXT_physical_device_drm ( PhysicalDeviceDrmPropertiesEXT(..)
, EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION
, pattern EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION
, EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME
, pattern EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME
) where
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (nullPtr)
import Foreign.Ptr (plusPtr)
import Vulkan.CStruct (FromCStruct)
import Vulkan.CStruct (FromCStruct(..))
import Vulkan.CStruct (ToCStruct)
import Vulkan.CStruct (ToCStruct(..))
import Vulkan.Zero (Zero(..))
import Data.String (IsString)
import Data.Typeable (Typeable)
import Foreign.Storable (Storable)
import Foreign.Storable (Storable(peek))
import Foreign.Storable (Storable(poke))
import qualified Foreign.Storable (Storable(..))
import GHC.Generics (Generic)
import Data.Int (Int64)
import Foreign.Ptr (Ptr)
import Data.Kind (Type)
import Vulkan.Core10.FundamentalTypes (bool32ToBool)
import Vulkan.Core10.FundamentalTypes (boolToBool32)
import Vulkan.Core10.FundamentalTypes (Bool32)
import Vulkan.Core10.Enums.StructureType (StructureType)
import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT))
-- | VkPhysicalDeviceDrmPropertiesEXT - Structure containing DRM information
-- of a physical device
--
-- = Description
--
-- If the 'PhysicalDeviceDrmPropertiesEXT' structure is included in the
-- @pNext@ chain of the
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.PhysicalDeviceProperties2'
-- structure passed to
-- 'Vulkan.Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceProperties2',
-- it is filled in with each corresponding implementation-dependent
-- property.
--
-- These are properties of the DRM information of a physical device.
--
-- == Valid Usage (Implicit)
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_physical_device_drm VK_EXT_physical_device_drm>,
-- 'Vulkan.Core10.FundamentalTypes.Bool32',
-- 'Vulkan.Core10.Enums.StructureType.StructureType'
data PhysicalDeviceDrmPropertiesEXT = PhysicalDeviceDrmPropertiesEXT
{ -- | @hasPrimary@ is a boolean indicating whether the physical device has a
-- DRM primary node.
hasPrimary :: Bool
, -- | @hasRender@ is a boolean indicating whether the physical device has a
-- DRM render node.
hasRender :: Bool
, -- | @primaryMajor@ is the DRM primary node major number, if any.
primaryMajor :: Int64
, -- | @primaryMinor@ is the DRM primary node minor number, if any.
primaryMinor :: Int64
, -- | @renderMajor@ is the DRM render node major number, if any.
renderMajor :: Int64
, -- | @renderMinor@ is the DRM render node minor number, if any.
renderMinor :: Int64
}
deriving (Typeable, Eq)
#if defined(GENERIC_INSTANCES)
deriving instance Generic (PhysicalDeviceDrmPropertiesEXT)
#endif
deriving instance Show PhysicalDeviceDrmPropertiesEXT
instance ToCStruct PhysicalDeviceDrmPropertiesEXT where
withCStruct x f = allocaBytes 56 $ \p -> pokeCStruct p x (f p)
pokeCStruct p PhysicalDeviceDrmPropertiesEXT{..} f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (hasPrimary))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (hasRender))
poke ((p `plusPtr` 24 :: Ptr Int64)) (primaryMajor)
poke ((p `plusPtr` 32 :: Ptr Int64)) (primaryMinor)
poke ((p `plusPtr` 40 :: Ptr Int64)) (renderMajor)
poke ((p `plusPtr` 48 :: Ptr Int64)) (renderMinor)
f
cStructSize = 56
cStructAlignment = 8
pokeZeroCStruct p f = do
poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_PHYSICAL_DEVICE_DRM_PROPERTIES_EXT)
poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr)
poke ((p `plusPtr` 16 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 20 :: Ptr Bool32)) (boolToBool32 (zero))
poke ((p `plusPtr` 24 :: Ptr Int64)) (zero)
poke ((p `plusPtr` 32 :: Ptr Int64)) (zero)
poke ((p `plusPtr` 40 :: Ptr Int64)) (zero)
poke ((p `plusPtr` 48 :: Ptr Int64)) (zero)
f
instance FromCStruct PhysicalDeviceDrmPropertiesEXT where
peekCStruct p = do
hasPrimary <- peek @Bool32 ((p `plusPtr` 16 :: Ptr Bool32))
hasRender <- peek @Bool32 ((p `plusPtr` 20 :: Ptr Bool32))
primaryMajor <- peek @Int64 ((p `plusPtr` 24 :: Ptr Int64))
primaryMinor <- peek @Int64 ((p `plusPtr` 32 :: Ptr Int64))
renderMajor <- peek @Int64 ((p `plusPtr` 40 :: Ptr Int64))
renderMinor <- peek @Int64 ((p `plusPtr` 48 :: Ptr Int64))
pure $ PhysicalDeviceDrmPropertiesEXT
(bool32ToBool hasPrimary) (bool32ToBool hasRender) primaryMajor primaryMinor renderMajor renderMinor
instance Storable PhysicalDeviceDrmPropertiesEXT where
sizeOf ~_ = 56
alignment ~_ = 8
peek = peekCStruct
poke ptr poked = pokeCStruct ptr poked (pure ())
instance Zero PhysicalDeviceDrmPropertiesEXT where
zero = PhysicalDeviceDrmPropertiesEXT
zero
zero
zero
zero
zero
zero
type EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION = 1
-- No documentation found for TopLevel "VK_EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION"
pattern EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION :: forall a . Integral a => a
pattern EXT_PHYSICAL_DEVICE_DRM_SPEC_VERSION = 1
type EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME = "VK_EXT_physical_device_drm"
-- No documentation found for TopLevel "VK_EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME"
pattern EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a
pattern EXT_PHYSICAL_DEVICE_DRM_EXTENSION_NAME = "VK_EXT_physical_device_drm"
|
expipiplus1/vulkan
|
src/Vulkan/Extensions/VK_EXT_physical_device_drm.hs
|
Haskell
|
bsd-3-clause
| 9,168
|
module Sexy.Instances.Show.Double () where
import Sexy.Classes (Show(..))
import Sexy.Data (Double)
import qualified Prelude as P
instance Show Double where
show = P.show
|
DanBurton/sexy
|
src/Sexy/Instances/Show/Double.hs
|
Haskell
|
bsd-3-clause
| 176
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
module Singletons where
import GHC.TypeLits
import GHC.Types
import Data.Proxy
import Test.Hspec
-- | Demote should be injective
type family Demote (k :: Type) = r | r -> k
type family TypeOf (a :: k) where TypeOf (a :: k) = k
reify :: forall a. Reflect a => Demote (TypeOf a)
reify = reflect (Proxy @a)
class Reflect (a :: k) where
reflect :: Proxy a -> Demote k
type instance Demote () = ()
instance Reflect '() where
reflect _ = ()
type instance Demote Symbol = String
instance (KnownSymbol s) => Reflect (s :: Symbol) where
reflect p = symbolVal p
type instance Demote Nat = Integer
instance (KnownNat n) => Reflect (n :: Nat) where
reflect p = natVal p
type instance Demote (Maybe k) = Maybe (Demote k)
instance (Reflect x) => Reflect (Just x :: Maybe a) where
reflect _ = Just (reflect (Proxy @x))
instance Reflect (Nothing :: Maybe a) where
reflect _ = Nothing
type instance Demote (Either j k) = Either (Demote j) (Demote k)
instance (Reflect x) => Reflect (Left x :: Either a b) where
reflect _ = Left (reflect (Proxy @x))
instance (Reflect y) => Reflect (Right y :: Either a b) where
reflect _ = Right (reflect (Proxy @y))
type instance Demote (a, b) = ((Demote a), (Demote b))
instance (Reflect x, Reflect y) => Reflect ('(x, y) :: (a, b)) where
reflect _ = (reflect (Proxy @x), reflect (Proxy @y))
spec = do
describe "reify" $ do
it "works for Unit" $ do
reify @'() `shouldBe` ()
it "works for Symbol" $ do
reify @"hello" `shouldBe` "hello"
it "works for Maybe" $ do
reify @(Just "hello") `shouldBe` Just "hello"
reify @(Nothing :: Maybe Symbol) `shouldBe` Nothing
reify @(Nothing :: Maybe (Maybe Symbol)) `shouldBe` Nothing
it "works for Either" $ do
reify @(Left "hello" :: Either Symbol Nat) `shouldBe` Left "hello"
reify @(Right 123 :: Either Symbol Nat) `shouldBe` Right 123
it "works for Tuples" $ do
reify @'("hello", 123) `shouldBe` ("hello", 123)
reify @'( '(123, "hello"), '()) `shouldBe` ((123, "hello"), ())
|
sleexyz/haskell-fun
|
Singletons.hs
|
Haskell
|
bsd-3-clause
| 2,511
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
--
-- A Mandelbrot set generator.
-- Originally submitted by Simon Marlow as part of Issue #49.
--
module Mandel (
-- Types
View, Render, Bitmap,
-- Pretty pictures
mandelbrot, prettyRGBA,
) where
import Prelude as P
import Data.Array.Accelerate as A
import Data.Array.Accelerate.IO as A
import Data.Array.Accelerate.Data.Complex
-- Types -----------------------------------------------------------------------
-- Current view into the complex plane
type View a = (a, a, a, a)
-- Image data
type Bitmap = Array DIM2 RGBA32
-- Action to render a frame
type Render a = Scalar (View a) -> Bitmap
-- Mandelbrot Set --------------------------------------------------------------
-- Compute the mandelbrot as repeated application of the recurrence relation:
--
-- Z_{n+1} = c + Z_n^2
--
-- This returns the iteration depth 'i' at divergence.
--
mandelbrot
:: forall a. (Elt a, IsFloating a)
=> Int
-> Int
-> Int
-> a
-> Acc (Scalar (View a))
-> Acc (Array DIM2 Int32)
mandelbrot screenX screenY depth radius view =
generate (constant (Z:.screenY:.screenX))
(\ix -> let c = initial ix
in A.snd $ A.while (\zi -> A.snd zi A.<* cMAX &&* dot (A.fst zi) A.<* rMAX)
(\zi -> lift1 (next c) zi)
(lift (c, constant 0)))
where
-- The view plane
(xmin,ymin,xmax,ymax) = unlift (the view)
sizex = xmax - xmin
sizey = ymax - ymin
viewx = constant (P.fromIntegral screenX)
viewy = constant (P.fromIntegral screenY)
-- initial conditions for a given pixel in the window, translated to the
-- corresponding point in the complex plane
initial :: Exp DIM2 -> Exp (Complex a)
initial ix = lift ( (xmin + (x * sizex) / viewx) :+ (ymin + (y * sizey) / viewy) )
where
pr = unindex2 ix
x = A.fromIntegral (A.snd pr :: Exp Int)
y = A.fromIntegral (A.fst pr :: Exp Int)
-- take a single step of the iteration
next :: Exp (Complex a) -> (Exp (Complex a), Exp Int32) -> (Exp (Complex a), Exp Int32)
next c (z, i) = (c + (z * z), i+1)
dot c = let r :+ i = unlift c
in r*r + i*i
cMAX = P.fromIntegral depth
rMAX = constant (radius * radius)
-- Rendering -------------------------------------------------------------------
{--}
prettyRGBA :: Exp Int32 -> Exp Int32 -> Exp RGBA32
prettyRGBA cmax c = c ==* cmax ? ( 0xFF000000, escapeToColour (cmax - c) )
-- Directly convert the iteration count on escape to a colour. The base set
-- (x,y,z) yields a dark background with light highlights.
--
-- Note that OpenGL reads pixel data in AGBR format, rather than RGBA.
--
escapeToColour :: Exp Int32 -> Exp RGBA32
escapeToColour m = constant 0xFFFFFFFF - (packRGBA32 $ lift (r,g,b,a))
where
r = A.fromIntegral (3 * m)
g = A.fromIntegral (5 * m)
b = A.fromIntegral (7 * m)
a = constant 0
--}
{--
-- A simple colour scheme
--
prettyRGBA :: Elt a => Exp Int -> Exp (Complex a, Int) -> Exp RGBA32
prettyRGBA lIMIT s' = r + g + b + a
where
s = A.snd s'
t = A.fromIntegral $ ((lIMIT - s) * 255) `quot` lIMIT
r = (t `rem` 128 + 64) * 0x1000000
g = (t * 2 `rem` 128 + 64) * 0x10000
b = (t * 3 `rem` 256 ) * 0x100
a = 0xFF
--}
{--
prettyRGBA :: Exp Int32 -> Exp Int32 -> Exp RGBA32
prettyRGBA cmax' c' =
let cmax = A.fromIntegral cmax' :: Exp Float
c = A.fromIntegral c' / cmax
in
c A.>* 0.98 ? ( 0xFF000000, rampColourHotToCold 0 1 c )
-- Standard Hot-to-Cold hypsometric colour ramp. Colour sequence is
-- Red, Yellow, Green, Cyan, Blue
--
rampColourHotToCold
:: (Elt a, IsFloating a)
=> Exp a -- ^ minimum value of the range
-> Exp a -- ^ maximum value of the range
-> Exp a -- ^ data value
-> Exp RGBA32
rampColourHotToCold vmin vmax vNotNorm
= let v = vmin `max` vNotNorm `min` vmax
dv = vmax - vmin
--
result = v A.<* vmin + 0.28 * dv
? ( lift ( constant 0.0
, 4 * (v-vmin) / dv
, constant 1.0
, constant 1.0 )
, v A.<* vmin + 0.5 * dv
? ( lift ( constant 0.0
, constant 1.0
, 1 + 4 * (vmin + 0.25 * dv - v) / dv
, constant 1.0 )
, v A.<* vmin + 0.75 * dv
? ( lift ( 4 * (v - vmin - 0.5 * dv) / dv
, constant 1.0
, constant 0.0
, constant 1.0 )
, lift ( constant 1.0
, 1 + 4 * (vmin + 0.75 * dv - v) / dv
, constant 0.0
, constant 1.0 )
)))
in
rgba32OfFloat result
--}
|
vollmerm/shallow-fission
|
tests/mandelbrot/src-acc/Mandel.hs
|
Haskell
|
bsd-3-clause
| 5,237
|
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ViewPatterns #-}
module Physics.Bullet.PointToPointConstraint where
import qualified Language.C.Inline.Cpp as C
import Foreign.C
import Linear.Extra
import Control.Monad.Trans
import Data.Monoid
import Physics.Bullet.Types
-----------------
-- Springs
-- See http://bulletphysics.org/Bullet/BulletFull/classbtGeneric6DofSpring2Constraint.html
-----------------
C.context (C.cppCtx <> C.funCtx)
C.include "<btBulletDynamicsCommon.h>"
addWorldPointToPointConstraint :: (Real a, MonadIO m)
=> DynamicsWorld
-> RigidBody -> V3 a
-> m PointToPointConstraint
addWorldPointToPointConstraint (DynamicsWorld dynamicsWorld)
(toCollisionObjectPointer->rigidBodyA) (fmap realToFrac -> V3 aX aY aZ) = PointToPointConstraint <$> liftIO [C.block| void * {
btDiscreteDynamicsWorld *dynamicsWorld = (btDiscreteDynamicsWorld *)$(void *dynamicsWorld);
btRigidBody *rigidBodyA = (btRigidBody *)$(void *rigidBodyA);
btVector3 pivotInA = btVector3($(float aX), $(float aY), $(float aZ));
btPoint2PointConstraint *point2Point = new btPoint2PointConstraint(
*rigidBodyA, pivotInA
);
dynamicsWorld->addConstraint(point2Point);
return point2Point;
}|]
addPointToPointConstraint :: (Real a, MonadIO m)
=> DynamicsWorld
-> RigidBody -> V3 a
-> RigidBody -> V3 a
-> m PointToPointConstraint
addPointToPointConstraint (DynamicsWorld dynamicsWorld)
(toCollisionObjectPointer->rigidBodyA) (fmap realToFrac -> V3 aX aY aZ)
(toCollisionObjectPointer->rigidBodyB) (fmap realToFrac -> V3 bX bY bZ) = PointToPointConstraint <$> liftIO [C.block| void * {
btDiscreteDynamicsWorld *dynamicsWorld = (btDiscreteDynamicsWorld *)$(void *dynamicsWorld);
btRigidBody *rigidBodyA = (btRigidBody *)$(void *rigidBodyA);
btRigidBody *rigidBodyB = (btRigidBody *)$(void *rigidBodyB);
btVector3 pivotInA = btVector3($(float aX), $(float aY), $(float aZ));
btVector3 pivotInB = btVector3($(float bX), $(float bY), $(float bZ));
btPoint2PointConstraint *point2Point = new btPoint2PointConstraint(
*rigidBodyA, *rigidBodyB,
pivotInA, pivotInB
);
dynamicsWorld->addConstraint(point2Point);
return point2Point;
}|]
|
lukexi/bullet-mini
|
src/Physics/Bullet/PointToPointConstraint.hs
|
Haskell
|
bsd-3-clause
| 2,693
|
module CC.Language where
import Data.List (transpose)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
--
-- * Syntax
--
-- | Minimal, generic, binary choice calculus syntax.
data CC t e =
Obj (e (CC t e))
| Chc t (CC t e) (CC t e)
class Obj e where
mapCC :: (CC t e -> a) -> e (CC t e) -> e a
foldCC :: (CC t e -> a -> a) -> a -> e (CC t e) -> a
showObj :: Tag t => e (CC t e) -> String
class Tag t where
-- | The configuration options referenced in this tag.
tagOpts :: t -> Set Option
-- | Resolve or simplify a tag given a configuration.
resolve :: Config -> t -> Either t Bool
-- | Pretty print a tag.
showTag :: t -> String
showCC :: (Tag t, Obj e) => CC t e -> String
showCC (Obj e) = showObj e
showCC (Chc t l r) = showTag t ++ "<" ++ showCC l ++ "," ++ showCC r ++ ">"
instance (Tag t, Obj e) => Show (CC t e) where
show = showCC
--
-- * Semantics
--
-- | Configure option.
type Option = String
-- | Configuration option setting: on or off.
type Setting = (Option, Bool)
-- | (Potentially partial) configuration.
type Config = Map Option Bool
-- | Plain types correspond to the fixed-point of the object language
-- type constructor.
newtype Plain f = P { unP :: f (Plain f) }
-- | Denotational semantics.
type Semantics e = Map Config (Plain e)
-- | The set of all configuration options referred to in an expression.
options :: (Tag t, Obj e) => CC t e -> Set Option
options (Obj e) = foldCC (Set.union . options) Set.empty e
options (Chc t l r) = Set.unions [tagOpts t, options l, options r]
-- | All configurations of an expression.
configs :: (Tag t, Obj e) => CC t e -> [Config]
configs e = (map Map.fromList . transpose) [[(o,True),(o,False)] | o <- os]
where os = Set.toList (options e)
-- | Apply a (potentially partial) configuration to an expression.
configure :: (Tag t, Obj e) => Config -> CC t e -> CC t e
configure c (Obj e) = Obj (mapCC (configure c) e)
configure c (Chc t l r) =
case resolve c t of
Left t' -> Chc t' l' r'
Right b -> if b then l' else r'
where l' = configure c l
r' = configure c r
-- | Convert an expression without choices into a plain expression.
toPlain :: (Tag t, Obj e) => CC t e -> Plain e
toPlain (Obj e) = P (mapCC toPlain e)
toPlain e = error $ "toPlain: not plain: " ++ show e
-- | Compute the denotational semantics.
semantics :: (Tag t, Obj e) => CC t e -> Semantics e
semantics e = Map.fromList [(c, toPlain (configure c e)) | c <- configs e]
|
walkie/CC-Minimal
|
src/CC/Language.hs
|
Haskell
|
bsd-3-clause
| 2,559
|
module Language.Interpreter.StdLib.BlockHandling
( addBlockHandlingStdLib
)
where
import Language.Ast ( Value(Null) )
import Language.Interpreter.Types ( InterpreterProcess
, setBuiltIn
, withGfxCtx
)
import Gfx.Context ( pushScope
, popScope
)
addBlockHandlingStdLib :: InterpreterProcess ()
addBlockHandlingStdLib = do
setBuiltIn "pushScope" pushGfxScope
setBuiltIn "popScope" popGfxScope
pushGfxScope :: [Value] -> InterpreterProcess Value
pushGfxScope _ = withGfxCtx pushScope >> return Null
popGfxScope :: [Value] -> InterpreterProcess Value
popGfxScope _ = withGfxCtx popScope >> return Null
|
rumblesan/proviz
|
src/Language/Interpreter/StdLib/BlockHandling.hs
|
Haskell
|
bsd-3-clause
| 923
|
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE OverloadedStrings #-}
module Prosper.Commands
( invest
, account
, allListings
, notes
, listingFromNote
, listingCSV
, AccountException (..)
, UnauthorizedException (..)
) where
import Control.Exception (Exception, throwIO)
import Control.Monad (when)
import Data.ByteString.Char8 as C
import Data.Maybe (listToMaybe)
import Data.Monoid ((<>))
import Data.Typeable (Typeable)
import Data.Vector (Vector)
import Network.Http.Client
import System.IO.Streams (InputStream)
import Prosper.Account
import Prosper.Internal.JSON
import Prosper.Internal.CSV
import Prosper.Invest
import Prosper.Listing
import Prosper.Money
import Prosper.Note
import Prosper.User
-- | An investment request. This requires a 'User', an amount of 'Money', and a 'Listing'.
invest :: User -> Money -> Listing -> IO InvestResponse
invest user amt l = investRequest user (listingId l) amt
-- | Request 'Account' information from Prosper
account :: User -> IO Account
account user = jsonGetHandler user "Account" accountHandler
where
accountHandler resp is = do
let statusCode = getStatusCode resp
statusMsg = getStatusMessage resp
when (statusCode == 500) $
throwIO (AccountException statusMsg)
when (statusCode == 401) $
throwIO (UnauthorizedException statusMsg)
jsonHandler resp is
-- | Used as a hack around the 500 Critical Exception error
data AccountException = AccountException ByteString
deriving (Typeable, Show)
instance Exception AccountException
-- | If unauthorized response, send
data UnauthorizedException = UnauthorizedException ByteString
deriving (Typeable, Show)
instance Exception UnauthorizedException
-- | Request notes for a Prosper user
notes :: User -> IO (Vector Note)
notes user = jsonGet user "Notes"
-- | Given a 'Note', look up the associated 'Listing' by the ListingId
listingFromNote :: User -> Note -> IO (Maybe Listing)
listingFromNote user (Note { listingNumber = lid }) = do
ls <- jsonGet user command
return $ listToMaybe ls
where
command = "ListingsHistorical?$filter=ListingNumber eq " <> C.pack (show lid)
-- | Send a request to the Listings end-point at Prosper
allListings :: User -> IO (Vector Listing)
allListings user = jsonGet user "Listings"
-- | Request a particular 'Listing' via the CSV endpoint
listingCSV :: User -> Listing -> (InputStream ByteString -> IO a) -> IO a
listingCSV user l = csvGetStream user url
where
lid = listingId l
url = "Listings?$filter=ListingNumber%20eq%20" <> C.pack (show lid)
|
WraithM/prosper
|
src/Prosper/Commands.hs
|
Haskell
|
bsd-3-clause
| 2,860
|
module Lint where
import Control.Monad.Writer
import Data.List (intercalate)
import Statement
import Expression (Name, Expr(..))
-- Quick 'n dirty! Unused variables are any variable that's in an assignment
-- statement, but not in any expression. As a proof-of-concept, we do directly
-- this, and first make a pass over the program to get any defined variable names,
-- then do a second pass and get all of the variable names that appear in an
-- expression. The difference of these two lists is then all of the
-- declared, but unused variables.
usedVars :: Statement -> [Name]
usedVars (s1 :. s2 ) = usedVars s1 ++ usedVars s2
usedVars (Print e) = getVars e
usedVars (If e _ _) = getVars e
usedVars (While e _) = getVars e
usedVars _ = mempty
getVars :: Expr -> [Name]
getVars (Var name) = [name]
getVars (Add e1 e2) = getVars e1 ++ getVars e2
getVars (Sub e1 e2) = getVars e1 ++ getVars e2
getVars (Mul e1 e2) = getVars e1 ++ getVars e2
getVars (Div e1 e2) = getVars e1 ++ getVars e2
getVars (And e1 e2) = getVars e1 ++ getVars e2
getVars (Or e1 e2) = getVars e1 ++ getVars e2
getVars (Not e1 ) = getVars e1
getVars (Eq e1 e2) = getVars e1 ++ getVars e2
getVars (Gt e1 e2) = getVars e1 ++ getVars e2
getVars (Lt e1 e2) = getVars e1 ++ getVars e2
getVars (Const _) = mempty
declaredVars :: Statement -> [Name]
declaredVars (s1 :. s2) = declaredVars s1 ++ declaredVars s2
declaredVars (Assign name _) = [name]
declaredVars _ = []
unusedVarMessage :: Statement -> Maybe String
unusedVarMessage stmt = go $ declaredVars stmt `less` usedVars stmt
where xs `less` ys = [x | x <- xs, x `notElem` ys]
go [] = Nothing
go [x] = Just $! "Yikes, variable " ++ x ++ " is defined but never used!"
go xs = Just $! "Great Scott! The variables " ++ (intercalate ", " xs) ++ " are defined, but never used!"
|
shawa/delorean
|
src/Lint.hs
|
Haskell
|
bsd-3-clause
| 1,872
|
{-# LANGUAGE CPP #-}
module MacAddress where
import Data.Binary (decode)
import qualified Data.ByteString.Lazy as BSL
import Safe (headDef)
#ifdef ETA_VERSION
import Java
import Data.Maybe (catMaybes)
import Data.Traversable (for)
import Data.Word (Word64, Word8)
#else /* !defined ETA_VERSION */
import Data.Word (Word64)
import Network.Info (MAC (MAC), getNetworkInterfaces, mac)
#endif /* ETA_VERSION */
getMacAddress :: IO Word64
#ifdef ETA_VERSION
getMacAddress = java $ do
interfaces <- fromJava <$> getNetworkInterfaces
macs <- for interfaces (<.> getHardwareAddress)
let macBytes =
headDef (error "Can't get any non-zero MAC address of this machine")
$ catMaybes macs
let mac = foldBytes $ fromJava macBytes
pure mac
data NetworkInterface = NetworkInterface @java.net.NetworkInterface
deriving Class
foreign import java unsafe
"@static java.net.NetworkInterface.getNetworkInterfaces"
getNetworkInterfaces :: Java a (Enumeration NetworkInterface)
foreign import java unsafe
getHardwareAddress :: Java NetworkInterface (Maybe JByteArray)
foldBytes :: [Word8] -> Word64
foldBytes bytes = decode . BSL.pack $ replicate (8 - length bytes) 0 ++ bytes
#else /* !defined ETA_VERSION */
getMacAddress = decodeMac <$> getMac
getMac :: IO MAC
getMac =
headDef (error "Can't get any non-zero MAC address of this machine")
. filter (/= minBound)
. map mac
<$> getNetworkInterfaces
decodeMac :: MAC -> Word64
decodeMac (MAC b5 b4 b3 b2 b1 b0) =
decode $ BSL.pack [0, 0, b5, b4, b3, b2, b1, b0]
#endif /* ETA_VERSION */
|
cblp/crdt
|
crdt/lib/MacAddress.hs
|
Haskell
|
bsd-3-clause
| 1,697
|
import System.Environment (getArgs)
import Data.List (sort)
bat :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> [Int] -> Int
bat l d n c s t tx xs | s > l - 6 = c
| s > tx - d && t == n = bat l d n c (tx+d) t (l-6+d) xs
| s > tx - d = bat l d n c (tx+d) (t+1) (head xs) (tail xs)
| otherwise = bat l d n (c+1) (s+d) t tx xs
bats :: [Int] -> Int
bats (a:d:n:xs) = bat a d n 0 6 0 (6-d) (sort xs)
main :: IO ()
main = do
[inpFile] <- getArgs
input <- readFile inpFile
putStr . unlines . map (show . bats . map read . words) $ lines input
|
nikai3d/ce-challenges
|
moderate/bats.hs
|
Haskell
|
bsd-3-clause
| 680
|
{-
- Hacq (c) 2013 NEC Laboratories America, Inc. All rights reserved.
-
- This file is part of Hacq.
- Hacq is distributed under the 3-clause BSD license.
- See the LICENSE file for more details.
-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
module Data.MexSet (MexSet, empty, singleton, fromList, fromAscList, toList, null, member, notMember, insert, delete, mex) where
import Prelude hiding (null)
import Data.FingerTree (FingerTree, Measured, (<|), (><), ViewL((:<)))
import qualified Data.FingerTree as FingerTree
import qualified Data.Foldable as Foldable
import qualified Data.List as List
import Data.Monoid (Monoid)
import qualified Data.Monoid as Monoid
import Util (mergeAscLists)
data Mex a = Mex {
_getMin :: !a, -- ^minimum integer in the tree; 0 for empty tree
getMax :: !a, -- ^maximum integer in the tree; 0 for empty tree
_getNextHole :: !a -- ^minimum integer that is at least _getMin and does not appear in the tree; 0 for empty tree
}
instance Integral a => Monoid (Mex a) where
mempty = Mex 0 0 0
Mex _ _ 0 `mappend` mex2 = mex2
mex1 `mappend` Mex _ _ 0 = mex1
Mex mi1 _ ho1 `mappend` Mex mi2 ma2 ho2 =
Mex mi1 ma2 $ if ho1 == mi2 then ho2 else ho1
newtype Item a = Item {
getItem :: a
} deriving (Eq, Ord, Num, Real, Enum, Integral)
instance Show a => Show (Item a) where
showsPrec d (Item x) = showsPrec d x
instance Integral a => Measured (Mex a) (Item a) where
measure (Item x) =
Mex x x y
where
y = x + 1
newtype MexSet a = MexSet (FingerTree (Mex a) (Item a))
deriving (Eq, Ord, Show)
empty :: Integral a => MexSet a
empty = MexSet FingerTree.empty
singleton :: Integral a => a -> MexSet a
singleton x = MexSet $ FingerTree.singleton $ Item x
instance Integral a => Monoid (MexSet a) where
mempty = empty
MexSet t1 `mappend` MexSet t2 =
MexSet $ FingerTree.fromList $ mergeAscLists (Foldable.toList t1) (Foldable.toList t2)
fromList :: Integral a => [a] -> MexSet a
fromList =
fromAscList . List.sort
fromAscList :: Integral a => [a] -> MexSet a
fromAscList =
MexSet . FingerTree.fromList . map Item
toList :: Integral a => MexSet a -> [a]
toList (MexSet t) = map getItem $ Foldable.toList t
null :: Integral a => MexSet a -> Bool
null (MexSet t) = FingerTree.null t
member :: Integral a => a -> MexSet a -> Bool
member x (MexSet t) =
case FingerTree.viewl (FingerTree.dropUntil ((>= x) . getMax) t) of
Item x' :< _ | x == x' -> True
_ -> False
notMember :: Integral a => a -> MexSet a -> Bool
notMember a = not . member a
insert :: Integral a => a -> MexSet a -> MexSet a
insert x s@(MexSet t) =
case FingerTree.viewl r of
Item x' :< _ | x == x' -> s
_ -> MexSet $ l >< Item x <| r
where
(l, r) = FingerTree.split ((>= x) . getMax) t
delete :: Integral a => a -> MexSet a -> MexSet a
delete x s@(MexSet t) =
case FingerTree.viewl r of
Item x' :< r' | x == x' -> MexSet $ l >< r'
_ -> s
where
(l, r) = FingerTree.split ((>= x) . getMax) t
mex :: Integral a => MexSet a -> a
mex (MexSet t) =
if mi == 0 then
ho
else
0
where
Mex mi _ ho = FingerTree.measure t
|
ti1024/hacq
|
src/Data/MexSet.hs
|
Haskell
|
bsd-3-clause
| 3,215
|
{-|
Directory tree database.
Directory database of B+ tree: huge DBM with order.
* Persistence: /persistent/
* Algorithm: /B+ tree/
* Complexity: /O(log n)/
* Sequence: /custom order/
* Lock unit: /page (rwlock)/
-}
module Database.KyotoCabinet.DB.Forest
( Forest
, ForestOptions (..)
, defaultForestOptions
, Compressor (..)
, Options (..)
, Comparator (..)
, makeForest
, openForest
)
where
import Data.Int (Int64, Int8)
import Data.Maybe (maybeToList)
import Prelude hiding (log)
import Database.KyotoCabinet.Internal
import Database.KyotoCabinet.Operations
newtype Forest = Forest DB
instance WithDB Forest where
getDB (Forest db) = db
data ForestOptions = ForestOptions { alignmentPow :: Maybe Int8
, freePoolPow :: Maybe Int8
, options :: [Options]
, buckets :: Maybe Int64
, maxSize :: Maybe Int64
, defragInterval :: Maybe Int64
, compressor :: Maybe Compressor
, cipherKey :: Maybe String
, pageSize :: Maybe Int64
, comparator :: Maybe Comparator
, pageCacheSize :: Maybe Int64
}
deriving (Show, Read, Eq, Ord)
defaultForestOptions :: ForestOptions
defaultForestOptions = defaultForestOptions { alignmentPow = Nothing
, freePoolPow = Nothing
, options = []
, buckets = Nothing
, maxSize = Nothing
, defragInterval = Nothing
, compressor = Nothing
, cipherKey = Nothing
, pageSize = Nothing
, comparator = Nothing
, pageCacheSize = Nothing
}
toTuningOptions :: ForestOptions -> [TuningOption]
toTuningOptions ForestOptions { alignmentPow = ap
, freePoolPow = fp
, options = os
, buckets = bs
, maxSize = ms
, defragInterval = di
, compressor = cmp
, cipherKey = key
, pageSize = ps
, comparator = cmprtr
, pageCacheSize = pcs
} =
mtl AlignmentPow ap ++ mtl FreePoolPow fp ++ map Options os ++ mtl Buckets bs ++
mtl MaxSize ms ++ mtl DefragInterval di ++ mtl Compressor cmp ++ mtl CipherKey key ++
mtl PageSize ps ++ mtl Comparator cmprtr ++ mtl PageCacheSize pcs
where
mtl f = maybeToList . fmap f
className :: String
className = "kcf"
makeForest :: FilePath -> LoggingOptions -> ForestOptions -> Mode -> IO Forest
makeForest fp log opts mode = makePersistent Forest toTuningOptions className fp log opts mode
openForest :: FilePath -> LoggingOptions -> Mode -> IO Forest
openForest fp log mode = openPersistent Forest className fp log mode
|
bitonic/kyotocabinet
|
Database/KyotoCabinet/DB/Forest.hs
|
Haskell
|
bsd-3-clause
| 3,570
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module CANOpen.Tower.NMT where
import Ivory.Language
import Ivory.Stdlib
import Ivory.Tower
import Ivory.Tower.HAL.Bus.CAN
import Ivory.Tower.HAL.Bus.Interface
import Ivory.Tower.HAL.Bus.CAN.Fragment
import Ivory.Serialize.LittleEndian
import CANOpen.Tower.Attr
import CANOpen.Tower.Interface.Base.Dict
import CANOpen.Tower.NMT.Types
import CANOpen.Tower.Utils
data NMTCMD
= Start
| Stop
| PreOperation
| ResetNode
| ResetComm
| HeartBeat
nmtCmd :: NMTCMD -> Uint8
nmtCmd Start = 0x01
nmtCmd Stop = 0x02
nmtCmd PreOperation = 0x80
nmtCmd ResetNode = 0x81
nmtCmd ResetComm = 0x82
heartBeatOffset :: Uint16
heartBeatOffset = 0x700
-- receives NMT (Network Management) messages from canopenTower
--
-- takes (required) node_id
-- outputs NMTState iff state changes
--
-- NMT message format
-- ID0 byte 1 node ID
-- byte 0 command
--
-- example NMT messages:
--
-- # start node 01
-- cansend can0 000#0101
--
-- # reset node 01
-- cansend can0 000#8101
nmtTower :: ChanOutput ('Struct "can_message")
-> AbortableTransmit ('Struct "can_message") ('Stored IBool)
-> ChanOutput ('Stored Uint8)
-> BaseAttrs Attr
-> Tower e ( ChanInput ('Stored NMTState)
, ChanOutput ('Stored NMTState))
nmtTower res req nid_update attrs = do
(nmt_notify_in, nmt_notify_out) <- channel
(nmt_set_in, nmt_set_out) <- channel
p <- period (Milliseconds 1)
monitor "nmt_controller" $ do
received <- stateInit "nmt_received" (ival (0 :: Uint32))
lastmsg <- state "nmt_lastmsg"
lastcmd <- state "nmt_lastcmd"
nmtState <- stateInit "nmt_state" (ival nmtInitialising)
previous_nmtState <- stateInit "nmt_state_prev" (ival nmtInitialising)
nodeId <- stateInit "heartbeat_node_id" (ival (0 :: Uint8))
heartbeat_cnt <- stateInit "heartbeat_cnt" (ival (0 :: Uint16))
heartbeat_enabled <- state "heartbeat_enabled"
heartbeat_time <- state "heartbeat_time"
attrHandler (producerHeartbeatTime attrs) $ do
callbackV $ \time -> do
store heartbeat_time time
when (time >? 0) $ store heartbeat_enabled true
handler systemInit "nmtinit" $ do
nmtE <- emitter nmt_notify_in 1
callback $ const $ emit nmtE (constRef nmtState)
handler res "nmtcanmsg" $ do
nmtE <- emitter nmt_notify_in 1
reqE <- emitter (abortableTransmit req) 1
callback $ \msg -> do
received += 1
refCopy lastmsg msg
nid <- deref nodeId
assert $ nid /=? 0
mlen <- deref (msg ~> can_message_len)
assert $ mlen ==? 2
cmd <- deref (msg ~> can_message_buf ! 0)
targetId <- deref (msg ~> can_message_buf ! 1)
store lastcmd cmd
let isCmd x = (cmd ==? nmtCmd x)
when (targetId ==? 0 .|| targetId ==? nid) $ do
cond_
[ isCmd Start ==> do
store nmtState nmtOperational
, isCmd Stop ==> do
store nmtState nmtStopped
, isCmd PreOperation ==> do
store nmtState nmtPreOperational
-- emit bootmsg when entering pre-Operational
empty <- local $ ival 0
bootmsg <- canMsgUint8 (heartBeatOffset + safeCast nid) false $ constRef empty
emit reqE bootmsg
store heartbeat_enabled true
, isCmd ResetNode ==> do
store nmtState nmtResetting
store heartbeat_enabled false
, isCmd ResetComm ==> do
store nmtState nmtResettingComm
store heartbeat_enabled false
]
cstate <- deref nmtState
prevstate <- deref previous_nmtState
when (cstate /=? prevstate) $ do
store previous_nmtState cstate
emit nmtE $ constRef nmtState
handler nid_update "nmt_node_id" $ do
callback $ refCopy nodeId
handler nmt_set_out "nmt_set" $ do
nmtE <- emitter nmt_notify_in 1
callback $ \x -> refCopy nmtState x >> emit nmtE x
handler p "per_heartbeat" $ do
reqe <- emitter (abortableTransmit req) 1
callback $ const $ do
cnt <- deref heartbeat_cnt
ena <- deref heartbeat_enabled
tim <- deref heartbeat_time
heartbeat_cnt += 1
when (ena .&& tim /=? 0) $ do
when (cnt >=? tim) $ do
nid <- deref nodeId
state <- deref nmtState
heartbeat_state <- local $ ival (0 :: Uint8)
cond_
[ state ==? nmtStopped ==> store heartbeat_state 4
, state ==? nmtOperational ==> store heartbeat_state 5
, state ==? nmtPreOperational ==> store heartbeat_state 127
]
bootmsg <- canMsgUint8 (heartBeatOffset + safeCast nid) false $ constRef heartbeat_state
emit reqe bootmsg
store heartbeat_cnt 0
return (nmt_set_in, nmt_notify_out)
|
distrap/ivory-tower-canopen
|
src/CANOpen/Tower/NMT.hs
|
Haskell
|
bsd-3-clause
| 5,043
|
{-# LANGUAGE FlexibleContexts #-}
module Advent.Day6 where
import qualified Data.Text as T
import Text.Parsec as Parsec (many1
, char
, newline
, sepEndBy
, try
, string
, ParseError
, digit
, choice
, parse)
import qualified Data.Vector as V
import qualified Data.Vector.Mutable as VM
import Control.Monad.ST (ST, runST)
import Control.Monad.Reader (ReaderT, runReaderT, lift, ask)
import Control.Monad (forM)
data Action = TurnOn
| TurnOff
| Toggle
deriving (Eq, Show)
type Index = (Int, Int)
type Start = Index
type End = Index
type Bounds = (Start, End)
data Command = Command { _action :: Action, _bounds :: Bounds } deriving (Eq, Show)
type LightGridM s a = V.Vector (VM.MVector s a)
type LightGrid a = V.Vector (V.Vector a)
type MyMon s a = ReaderT (LightGridM s a) (ST s)
parse :: T.Text -> Either ParseError [Command]
parse =
Parsec.parse commandP ""
where
commandP = sepEndBy command newline
int = read <$> many1 digit
index = (,) <$> int <*> (char ',' *> int)
coords = (,) <$> index <*> (string " through " *> index)
on = try $ TurnOn <$ string "turn on "
off = try $ TurnOff <$ string "turn off "
tog = try $ Toggle <$ string "toggle "
command = Command <$> choice [on, tog, off] <*> coords
initialState :: a -> ST s (LightGridM s a)
initialState initialValue = sequence $ V.replicate 1000 inner
where
inner = VM.replicate 1000 initialValue
elvish :: Action -> Int -> Int
elvish TurnOn = (+ 1)
elvish TurnOff = max 0 . subtract 1
elvish Toggle = (+ 2)
english :: Action -> Bool -> Bool
english TurnOn = const True
english TurnOff = const False
english Toggle = not
reifyBounds :: Bounds -> [Index]
reifyBounds ((x1,y1), (x2,y2)) = [(x,y) | x <- [x1 .. x2], y <- [y1 .. y2]]
-- | I have no real idea how performant this is. I started going down the rabbit
-- hole of mutable vectors inside a monad stack and this is where I ended up.
step :: (Action -> a -> a) -> Command -> MyMon s a ()
step language c =
mapM_ update indices
where
update (x,y) = do
grid <- ask
let ys = (V.!) grid y
-- No idea why I can't reference modify, it's there on Hackage :S
-- so have to do it the verbose way
-- lift $ Data.Vector.Mutable.modify ys f x
v <- lift $ VM.read ys x
lift $ VM.write ys x (setter v)
setter = language $ _action c
indices = reifyBounds $ _bounds c
runSteps :: (Action -> a -> a) -> a -> [Command] -> LightGrid a
runSteps language initialValue t = runST $ do
s <- initialState initialValue
_ <- runReaderT (Control.Monad.forM t $ step language) s
freeze s
freeze :: LightGridM s a -> ST s (LightGrid a)
freeze = sequence . fmap V.freeze
numberLit :: LightGrid Bool -> Int
numberLit =
V.sum . fmap rows
where
rows :: V.Vector Bool -> Int
rows = length . V.filter id
totalBrightness :: LightGrid Int -> Int
totalBrightness = V.sum . fmap V.sum
|
screamish/adventofhaskellcode
|
src/Advent/Day6.hs
|
Haskell
|
bsd-3-clause
| 3,203
|
module LetLang.ParserSuite
( tests
) where
import LetLang.Data
import LetLang.Parser
import Test.HUnit.Base
import Text.Megaparsec
import Text.Megaparsec.String
tests :: Test
tests = TestList
[ TestLabel "Test const expression" testConstExpr
, TestLabel "Test binary-operator expression" testBinOpExpr
, TestLabel "Test unary-operator expression" testUnaryOpExpr
, TestLabel "Test condition expression" testCondExpr
, TestLabel "Test var expression" testVarExpr
, TestLabel "Test let expression" testLetExpr
, TestLabel "Test expression" testExpression
, TestLabel "Test parse program" testParseProgram
]
constNum = ConstExpr . ExprNum
constBool = ConstExpr . ExprBool
parserEqCase :: (Eq a, Show a) => Parser a -> String -> a -> String -> Test
parserEqCase parser msg expect input =
TestCase $ assertEqual msg (Right expect) runP
where runP = runParser parser "Test equal case" input
parserFailCase :: (Eq a, Show a) => Parser a -> String -> String -> Test
parserFailCase parser msg input =
TestCase $ assertBool msg (isLeft runP)
where
isLeft (Left _) = True
isLeft (Right _) = False
runP = runParser parser "Test fail case" input
testEq :: String -> Expression -> String -> Test
testEq = parserEqCase expression
testFail :: String -> String -> Test
testFail = parserFailCase expression
testConstExpr :: Test
testConstExpr = TestList
[ testEq "Parse single number" (constNum 5) "5"
, testEq "Parse multi-numbers" (constNum 123) "123"
, testFail "Parse negative numbers should fail" "-3"
]
testBinOpExpr :: Test
testBinOpExpr = TestList
[ testEq "Parse '-' expression (no space)"
(BinOpExpr Sub (constNum 3) (constNum 4))
"-(3,4)"
, testEq "Parse '*' expression (with spaces)"
(BinOpExpr Mul (constNum 10) (constNum 24))
"* ( 10 , 24 )"
, testEq "Parse binary num-to-bool expression"
(BinOpExpr Gt (constNum 1) (constNum 2))
"greater?(1, 2)"
, testEq "Parse cons expression"
(BinOpExpr Cons (constNum 3) EmptyListExpr)
"cons (3, emptyList)"
]
testUnaryOpExpr :: Test
testUnaryOpExpr = TestList
[ testEq "Parse isZero expression (no space)"
(UnaryOpExpr IsZero (constNum 1)) "zero?(1)"
, testEq "Parse isZero expression (with space)"
(UnaryOpExpr IsZero (constNum 3)) "zero? ( 3 )"
, testEq "Parse minus expression"
(UnaryOpExpr Minus (constNum 1)) "minus(1)"
, testEq "Parse car expression"
(UnaryOpExpr Car EmptyListExpr) "car (emptyList)"
]
testCondExpr :: Test
testCondExpr = TestList
[ testEq "Parse if expression"
(CondExpr
[ (UnaryOpExpr IsZero (constNum 3), constNum 4)
, (constBool True, constNum 5) ])
"if zero?(3) then 4 else 5"
, testEq "Parse cond expression"
(CondExpr
[ (UnaryOpExpr IsZero (constNum 3), constNum 4)
, (BinOpExpr Gt (constNum 3) (constNum 5), constNum 4)
, (UnaryOpExpr IsZero (constNum 0), constNum 4)
])
$ unlines
[ "cond zero?(3) ==> 4\n"
, " greater?(3, 5) ==> 4\n"
, " zero?(0) ==> 4\n"
, "end"
]
]
testVarExpr :: Test
testVarExpr = TestList
[ testEq "Parse var expression" (VarExpr "foo") "foo"
, testFail "Parse reserved word should fail" "then"
]
testLetExpr :: Test
testLetExpr = TestList
[ testEq "Parse let expression with 0 binding"
(LetExpr [] (VarExpr "bar"))
"let in bar"
, testEq "Parse let expression with 1 binding"
(LetExpr [("bar", constNum 1)] (VarExpr "bar"))
"let bar = 1 in bar"
, testEq "Parse let expression with multi bindings"
(LetExpr [("x", constNum 1), ("y", constNum 2), ("z", constNum 3)]
(VarExpr "bar"))
"let x = 1 y = 2 z = 3 in bar"
, testEq "Parse let* expression with 1 binding"
(LetStarExpr [("x", constNum 1)]
(VarExpr "bar"))
"let* x = 1 in bar"
, testEq "Parse nested let and let*"
(LetExpr
[("x", constNum 30)]
(LetStarExpr
[ ("x", BinOpExpr Sub (VarExpr "x") (constNum 1))
, ("y", BinOpExpr Sub (VarExpr "x") (constNum 2))
]
(BinOpExpr Sub (VarExpr "x") (VarExpr "y"))))
"let x = 30 in let* x = -(x,1) y = -(x,2) in -(x,y)"
]
testExpression :: Test
testExpression = TestList
[ testEq "Parse complex expression"
(LetExpr [("bar", constNum 1)]
(CondExpr
[ (UnaryOpExpr IsZero (VarExpr "bar"), constNum 3)
, (constBool True, VarExpr "zero") ]))
"let bar = 1 in if zero? (bar) then 3 else zero"
, testEq "Parse list expression"
(UnaryOpExpr
Car (LetExpr
[("foo", constNum 3)]
(BinOpExpr Cons (constNum 5) EmptyListExpr)))
"car(let foo = 3 in cons(5, emptyList))"
]
testParseProgram :: Test
testParseProgram = TestList
[ testEq "Parse program (with spaces)"
(Prog (LetExpr [("x", constNum 3)]
(VarExpr "x")))
"let x = 3 in x"
]
where
testEq msg expect prog = TestCase $
assertEqual msg (Right expect) (parseProgram prog)
|
li-zhirui/EoplLangs
|
test/LetLang/ParserSuite.hs
|
Haskell
|
bsd-3-clause
| 5,455
|
module Wikirick.JSONConnection where
import Control.Exception hiding (Handler)
import Data.Aeson
import Data.Typeable
import Snap
data JSONParseError = JSONParseError String deriving (Eq, Show, Typeable)
instance Exception JSONParseError
data JSONConnection = JSONConnection
{ _parseJSON :: (MonadSnap m, FromJSON a) => m a
, _responseJSON :: (MonadSnap m, ToJSON a) => a -> m ()
}
parseJSON :: (MonadState JSONConnection m, MonadSnap m, FromJSON a) => m a
parseJSON = get >>= _parseJSON
responseJSON :: (MonadState JSONConnection m, MonadSnap m, ToJSON a) => a -> m ()
responseJSON v = get >>= \self ->
_responseJSON self v
|
keitax/wikirick
|
src/Wikirick/JSONConnection.hs
|
Haskell
|
bsd-3-clause
| 638
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE RecordWildCards #-}
module Juno.Consensus.Handle.AppendEntriesResponse
(handle
,handleAlotOfAers
,updateCommitProofMap)
where
import Control.Lens hiding (Index)
import Control.Parallel.Strategies
import Control.Monad.Reader
import Control.Monad.State (get)
import Control.Monad.Writer.Strict
import Data.Maybe
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Juno.Consensus.Commit (doCommit)
import Juno.Consensus.Handle.Types
import Juno.Runtime.Timer (resetElectionTimerLeader)
import Juno.Util.Util (debug, updateLNextIndex)
import qualified Juno.Types as JT
data AEResponseEnv = AEResponseEnv {
-- Old Constructors
_nodeRole :: Role
, _term :: Term
, _commitProof :: Map NodeID AppendEntriesResponse
}
makeLenses ''AEResponseEnv
data AEResponseOut = AEResponseOut
{ _stateMergeCommitProof :: Map NodeID AppendEntriesResponse
, _leaderState :: LeaderState }
data LeaderState =
DoNothing |
NotLeader |
StatelessSendAE
{ _sendAENodeID :: NodeID } |
Unconvinced -- sends AE after
{ _sendAENodeID :: NodeID
, _deleteConvinced :: NodeID } |
ConvincedAndUnsuccessful -- sends AE after
{ _sendAENodeID :: NodeID
, _setLaggingLogIndex :: LogIndex } |
ConvincedAndSuccessful -- does not send AE after
{ _incrementNextIndexNode :: NodeID
, _incrementNextIndexLogIndex :: LogIndex
, _insertConvinced :: NodeID}
data Convinced = Convinced | NotConvinced
data AESuccess = Success | Failure
data RequestTermStatus = OldRequestTerm | CurrentRequestTerm | NewerRequestTerm
handleAEResponse :: (MonadWriter [String] m, MonadReader AEResponseEnv m) => AppendEntriesResponse -> m AEResponseOut
handleAEResponse aer@AppendEntriesResponse{..} = do
--tell ["got an appendEntriesResponse RPC"]
mcp <- updateCommitProofMap aer <$> view commitProof
role' <- view nodeRole
currentTerm' <- view term
if role' == Leader then
return $ case (isConvinced, isSuccessful, whereIsTheRequest currentTerm') of
(NotConvinced, _, OldRequestTerm) -> AEResponseOut mcp $ Unconvinced _aerNodeId _aerNodeId
(NotConvinced, _, CurrentRequestTerm) -> AEResponseOut mcp $ Unconvinced _aerNodeId _aerNodeId
(Convinced, Failure, CurrentRequestTerm) -> AEResponseOut mcp $ ConvincedAndUnsuccessful _aerNodeId _aerIndex
(Convinced, Success, CurrentRequestTerm) -> AEResponseOut mcp $ ConvincedAndSuccessful _aerNodeId _aerIndex _aerNodeId
-- The next two case are underspecified currently and they should not occur as
-- they imply that a follow is ahead of us but the current code sends an AER anyway
(NotConvinced, _, _) -> AEResponseOut mcp $ StatelessSendAE _aerNodeId
(_, Failure, _) -> AEResponseOut mcp $ StatelessSendAE _aerNodeId
-- This is just a fall through case in the current code
-- do nothing as the follower is convinced and successful but out of date? Shouldn't this trigger a replay AE?
(Convinced, Success, OldRequestTerm) -> AEResponseOut mcp DoNothing
-- We are a leader, in a term that hasn't happened yet?
(_, _, NewerRequestTerm) -> AEResponseOut mcp DoNothing
else
return $ AEResponseOut mcp NotLeader
where
isConvinced = if _aerConvinced then Convinced else NotConvinced
isSuccessful = if _aerSuccess then Success else Failure
whereIsTheRequest ct | _aerTerm == ct = CurrentRequestTerm
| _aerTerm < ct = OldRequestTerm
| otherwise = NewerRequestTerm
updateCommitProofMap :: AppendEntriesResponse -> Map NodeID AppendEntriesResponse -> Map NodeID AppendEntriesResponse
updateCommitProofMap aerNew m = Map.alter go nid m
where
nid :: NodeID
nid = _aerNodeId aerNew
go = \case
Nothing -> Just aerNew
Just aerOld -> if _aerIndex aerNew > _aerIndex aerOld
then Just aerNew
else Just aerOld
handle :: Monad m => AppendEntriesResponse -> JT.Raft m ()
handle ae = do
s <- get
let ape = AEResponseEnv
(JT._nodeRole s)
(JT._term s)
(JT._commitProof s)
(AEResponseOut{..}, l) <- runReaderT (runWriterT (handleAEResponse ae)) ape
mapM_ debug l
JT.commitProof .= _stateMergeCommitProof
doCommit
case _leaderState of
NotLeader -> return ()
DoNothing -> resetElectionTimerLeader
StatelessSendAE{..} ->
resetElectionTimerLeader
Unconvinced{..} -> do
JT.lConvinced %= Set.delete _deleteConvinced
resetElectionTimerLeader
ConvincedAndSuccessful{..} -> do
updateLNextIndex $ Map.insert _incrementNextIndexNode $ _incrementNextIndexLogIndex + 1
JT.lConvinced %= Set.insert _insertConvinced
resetElectionTimerLeader
ConvincedAndUnsuccessful{..} -> do
updateLNextIndex $ Map.insert _sendAENodeID _setLaggingLogIndex
resetElectionTimerLeader
handleAlotOfAers :: Monad m => AlotOfAERs -> JT.Raft m ()
handleAlotOfAers (AlotOfAERs m) = do
ks <- KeySet <$> view (JT.cfg . JT.publicKeys) <*> view (JT.cfg . JT.clientPublicKeys)
let res = (processSetAer ks <$> Map.elems m) `using` parList rseq
aers <- catMaybes <$> mapM (\(a,l) -> mapM_ debug l >> return a) res
mapM_ handle aers
processSetAer :: KeySet -> Set AppendEntriesResponse -> (Maybe AppendEntriesResponse, [String])
processSetAer ks s = go [] (Set.toDescList s)
where
go fails [] = (Nothing, fails)
go fails (aer:rest)
| _aerWasVerified aer = (Just aer, fails)
| otherwise = case aerReVerify ks aer of
Left f -> go (f:fails) rest
Right () -> (Just $ aer {_aerWasVerified = True}, fails)
-- | Verify if needed on `ReceivedMsg` provenance
aerReVerify :: KeySet -> AppendEntriesResponse -> Either String ()
aerReVerify _ AppendEntriesResponse{ _aerWasVerified = True } = Right ()
aerReVerify _ AppendEntriesResponse{ _aerProvenance = NewMsg } = Right ()
aerReVerify ks AppendEntriesResponse{
_aerWasVerified = False,
_aerProvenance = ReceivedMsg{..}
} = verifySignedRPC ks $ SignedRPC _pDig _pOrig
|
haroldcarr/juno
|
src/Juno/Consensus/Handle/AppendEntriesResponse.hs
|
Haskell
|
bsd-3-clause
| 6,373
|
-- | The Finite Module which exports Finite
----------------------------------------------------------------
module Finite (Finite(..), (*^), (*^-), sigfigs, orderOfMagnitude, showNatural, showFull, showScientific, roundToPrecision, fromIntegerWithPrecision, fromIntegerMatchingPrecision) where
----------------------------------------------------------------
import Extensions
import Data.Ratio
----------------------------------------------------------------
-- FINITE DATA TYPE
----------------------------------------------------------------
-- | Finite Data Type `(b*10^e)`
-- * ensure that the digits comprising b correspond to the significant
-- figures of the number
data Finite = Finite
{base :: Integer, -- ^ the `b` in `b*10^e`
expo :: Integer} -- ^ the `e` in `b*10^e`
-- CONVENIENCE CONSTRUCTORS
-- | Constructor for Finite Data Type
(*^) :: Integer -> Integer -> Finite
a*^m = Finite a m
-- | Convenience constructor for Finite where the exponent is negative
-- This is most commonly used for when writing literals
(*^-) :: Integer -> Integer -> Finite
a*^-m = a*^(-m)
-- INFORMATION
-- | Significant figures
sigfigs :: Finite -> Integer
sigfigs (Finite a _) = digits a
-- | Order of Magnitude
-- `n.nnnn*10^?`
orderOfMagnitude :: Finite -> Integer
orderOfMagnitude (Finite a m) = digits a - 1 + m
----------------------------------------------------------------
-- SHOWABILITY
----------------------------------------------------------------
instance Show Finite where
show = showNatural
-- | Show with component decomposition
showNatural :: Finite -> String
showNatural (Finite a m) = "[" ++ (show a) ++ "*10^" ++ (show m) ++ "]"
-- | Show in full written form
showFull :: Finite -> String
showFull (Finite a m)
| m < 0 = show intPart ++ "." ++ leadingZeroes ++ show floatPart -- has decimals
| otherwise = show (a*10^m) -- no decimals
where
intPart = a `div` 10^(abs m)
floatPart = a - a `div` 10^(abs m) * 10^(abs m) -- not including leading 0's
leadingZeroes = replicate (fromIntegral $ abs m - digits floatPart) '0'
-- | Show in Scientific form
showScientific :: Finite -> String
showScientific (Finite a m) = lead ++ decimals ++ "e" ++ show exponent
where
lead = [head (show a)]
decimals = if tail (show a) /= "" then "." ++ tail (show a) else ""
exponent = digits a + m - 1
----------------------------------------------------------------
-- NUMBERNESS
----------------------------------------------------------------
instance Num Finite where
am@(Finite a m) + bn@(Finite b n) = roundToPrecision (u *^ lowestExpo) (digits u - diff) -- FIXME: rounding error on associativity
where
lowestExpo = min m n
highestExpo = max m n
u = a*10^(m-lowestExpo) + b*10^(n-lowestExpo) -- the unrounded base of the added number
diff = highestExpo - lowestExpo -- the difference in exponents (always positive)
am - bn = am + (-bn)
am@(Finite a m) * bn@(Finite b n) = roundToPrecision ((a * b) *^ (m + n)) lowestPrecision -- FIXME: rounding error on associativity
where
lowestPrecision = min (sigfigs am) (sigfigs bn)
negate (Finite a m) = Finite (-a) m
abs (Finite a m) = abs a *^ m
signum (Finite a _) = Finite (signum a) 0
fromInteger a = (a*10^16)*^-16 -- ^ Assumes IEEE Double precision
-- | takes an integer and sets it to a certain sigfigs precision
-- (instead of the default IEEE Double precision)
fromIntegerWithPrecision :: Integer -> Integer -> Finite
fromIntegerWithPrecision a p
| digits a > p = (a `div` 10^(digits a - p))*^(digits a - p) -- cut off end of int and give it that exponent
| otherwise = (a*10^(p - digits a))*^-(p - digits a) -- append zeroes to end and give it that exponent
-- | takes an integer and another finite and turns the integer into
-- a finite of the same precision (sigfigs)
fromIntegerMatchingPrecision :: Integer -> Finite -> Finite
fromIntegerMatchingPrecision a n = fromIntegerWithPrecision a (sigfigs n)
----------------------------------------------------------------
-- EQUATABILITY & ORDERABILITY
----------------------------------------------------------------
-- | tests if two finites have the same value
instance Eq Finite where
(Finite a m) == (Finite b n)
| n < m = a*10^(m-n) == b
| otherwise = a == b*10^(n-m)
-- | tests if two finites are exactly the same
(Finite a m) === (Finite b n) = a == b && m == n
instance Ord Finite where
compare (Finite a m) (Finite b n) = compare (a*10^(m-lowestExpo)) (b*10^(n-lowestExpo))
where
lowestExpo = min m n
----------------------------------------------------------------
-- FRACTIONALNESS
----------------------------------------------------------------
instance Fractional Finite where
am@(Finite a m) / bn@(Finite b n) = roundToPrecision (((a*10^(db+1)) `div` b) *^ (m-n-db-1)) lowestPrecision
where
db = digits b
lowestPrecision = min (sigfigs am) (sigfigs bn)
fromRational r = (fromInteger (numerator r)) / (fromInteger (denominator r)) -- ^ Assumes IEEE Double precision
-- | The representation as a ratio
-- `a/10^-m`
instance Real Finite where
toRational (Finite a m)
| m > 0 = a % 1
| otherwise = a % (10^(-m))
-- | The representation as an integer part and float part
instance RealFrac Finite where
properFraction am@(Finite a m) = (intPart, floatPart)
where
intPart = fromIntegral $ if m < 0 then a `div` 10^(abs m) else a * 10^m
floatPart = am - fromIntegral intPart
----------------------------------------------------------------
-- EXTENDED ARITHMETIC
----------------------------------------------------------------
-- | Powers
-- power :: Finite -> Finite -> Finite
-- power (Finite a m) (Finite b n) =
-- | Roots
-- root :: Finite -> Finite -> Finite
-- root (Finite a m) (Finite b n) =
-- | Logarithms
-- log :: Finite -> Finite -> Finite
-- log (Finite a m) (Finite b n) =
----------------------------------------------------------------
-- OTHER FUNCTIONS
----------------------------------------------------------------
-- | Round to a certain precision
-- supply with a number and the number of significant figures you want to round to
roundToPrecision :: Finite -> Integer -> Finite
roundToPrecision am@(Finite a m) p
| d <= p = am -- if equal or worse precision than specified, return original
| otherwise = (a `div` 10^(d-p) + r) *^ (d-p+m) -- d-p is how many digits to take off the end of a
where
d = digits a
r = if a `div` 10^(d-p-1) `mod` 10 >= 5 then 1 else 0 -- add 1 to the number if the digit after the precision is >= 5
----------------------------------------------------------------
-- MATHEMATICAL CONSTANTS
----------------------------------------------------------------
-- piAtPrecision :: Integer -> Finite
-- eAtPrecision :: Integer -> Finite
|
Conflagrationator/HMath
|
src/Finite.hs
|
Haskell
|
bsd-3-clause
| 6,948
|
-- for TokParsing, MonadicParsing
{-# LANGUAGE ConstraintKinds #-}
-- for impOrExpVar
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
-- ghc opts / calm down ghc-mod
-- {-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- {-# OPTIONS_GHC -fno-warn-orphans #-}
-- {-# OPTIONS_GHC -fno-warn-missing-signatures #-}
-- {-# OPTIONS_GHC -fno-warn-unused-do-bind #-}
-- {-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
-- -- {-# OPTIONS_GHC -fno-warn-incomplete-uni-patterns #-}
--------------------------------------------------------------------
-- |
-- Copyright : (c) Andreas Reuleaux 2015
-- License : BSD2
-- Maintainer: Andreas Reuleaux <rx@a-rx.info>
-- Stability : experimental
-- Portability: non-portable
--
-- This module is part of Pire's parser.
--------------------------------------------------------------------
module Pire.Parser.Nat where
import Pire.Parser.Parser
import Pire.Parser.Basic
import Pire.Parser.Token
import Pire.Syntax.Ex
import Pire.Syntax.Ws
import Pire.Syntax.Expr
import qualified Data.Text as T (pack)
-- import Control.Monad.State
import Control.Monad.State.Strict
-- originally desugaring of nats in the parser...
-- commented out in PIRE!!!
{-
natenc :: TokParsing m => m Tm
natenc =
do n <- natural
return $ encode n
where encode 0 = DCon "Zero" [] natty
encode n = DCon "Succ" [Arg RuntimeP (encode (n-1))] natty
natty = Annot $ Just (TCon "Nat" [])
-}
-- commented out in PIRE!!!
-- think about where to put the ws:
-- as part of the DCName' or of the Annot' ?
-- for now on the (top most) DCName'
{-
natenc_ :: (TokParsing m
, DeltaParsing m
) => m Tm_
natenc_ = do
n <- runUnspaced natural
ws <- sliced whiteSpace
-- return $ (\(DCon_ n' args (Annot_ m _)) ->
-- DCon_ n' args (Annot_ m $ Ws $ txt ws )) $ encode n
return $ (\(DCon_ (DCName_ n' _) args annot) ->
DCon_ (DCName_ n' $ Ws $ txt ws) args annot) $ encode n
where
-- encode 0 = DCon_ "Zero" [] natty
encode 0 = DCon_ (DCName_ "Zero" $ Ws "") [] natty
-- encode n = DCon_ "Succ" [Arg_ Runtime (encode (n-1))] natty
encode n = DCon_ (DCName_ "Succ" $ Ws "")
[Arg_ RuntimeP (encode (n-1))] natty
natty = Annot_ (Just (TCon_ (TCName_ "Nat" $ Ws "") [])) $ Ws ""
-}
-- ... but don't want implicit desugaring while parsing
nat :: TokParsing m => m Ex
nat =
do n <- natural
return $ Nat n
nat_ :: (TokenParsing m
, Monad m
, DeltaParsing m
, MonadState PiState m
)
=> m Ex
nat_ = do
n <- runUnspaced natural
ws <- sliced whiteSpace
return $ Nat_ n (T.pack $ show n) (Ws $ txt ws)
|
reuleaux/pire
|
src/Pire/Parser/Nat.hs
|
Haskell
|
bsd-3-clause
| 2,865
|
module Main where
--gcd :: Int -> Int -> Int
--gcd x 0 = x
--gcd x y
-- | x < y = gcd y x
-- | otherwise = gcd y (mod x y)
--lcm :: Int -> Int -> Int
--lcm x y = let g = gcd (x y)
-- in (div x g) * (div y g) * g
splitBy delimiter = foldr f [[]]
where f c l@(x:xs) | c == delimiter = []:l
| otherwise = (c:x):xs
solve :: [Int] -> Int
solve = foldr lcm 1
main :: IO ()
main = do
getLine
nsStr <- getLine
let ns = map (read::String -> Int) $ splitBy ' ' nsStr
print $ solve ns
|
everyevery/programming_study
|
hackerrank/functional/jumping-bunnies/jumping-bunnies.hs
|
Haskell
|
mit
| 548
|
{-# LANGUAGE OverloadedStrings, ExistentialQuantification, ExtendedDefaultRules, FlexibleContexts, TemplateHaskell #-}
module Dashdo.Examples.GapminderScatterplot where
import Numeric.Datasets
import Numeric.Datasets.Gapminder
import Dashdo
import Dashdo.Types
import Dashdo.Serve
import Dashdo.Elements
import Lucid
import Lucid.Bootstrap
import Lucid.Bootstrap3
import Data.Monoid ((<>))
import qualified Data.Foldable as DF
import Data.Text (Text, unpack, pack)
import Data.List
import Data.Aeson.Types
import GHC.Float
import Lens.Micro.Platform
import Control.Monad
import Control.Monad.State.Strict
import Control.Applicative
import Graphics.Plotly
import qualified Graphics.Plotly.Base as B
import Graphics.Plotly.Lucid
data GmParams = GmParams
{
_selCountries :: [Text]
, _selContinents :: [Text]
, _selYear :: Text
}
makeLenses ''GmParams
gm0 = GmParams [] [] "2007"
data Continent = Africa | Americas | Asia | Europe | Oceania deriving (Eq, Show, Read, Enum)
continentRGB :: Continent -> RGB Int
continentRGB Africa = RGB 255 165 0
continentRGB Americas = RGB 178 34 34
continentRGB Asia = RGB 218 112 214
continentRGB Europe = RGB 0 128 0
continentRGB Oceania = RGB 0 0 255
continentRGB _ = undefined
-- TODO: 1 - doghunt 2- sum gdp for region
-- TODO: plotlySelectMultiple
countriesTable :: [Gapminder] -> SHtml IO GmParams ()
countriesTable gms =
table_ [class_ "table table-striped"] $ do
thead_ $ do
tr_ $ do
th_ "Country"
th_ "Population"
th_ "GDP per capita"
th_ "Life expectancy"
tbody_ $ do
DF.for_ gms $ \(c) -> do
tr_ $ do
td_ $ toHtml (country c)
td_ $ toHtml (show $ pop c)
td_ $ toHtml (show $ gdpPercap c)
td_ $ toHtml (show $ lifeExp c)
countriesScatterPlot :: [Gapminder] -> SHtml IO GmParams ()
countriesScatterPlot gms =
let
trace :: Trace
trace =
scatter
& B.x ?~ (toJSON . gdpPercap <$> gms)
& B.y ?~ (toJSON . lifeExp <$> gms)
& B.customdata ?~ (toJSON . country <$> gms)
& B.mode ?~ [B.Markers]
& B.text ?~ (country <$> gms)
& B.marker ?~
(defMarker
& B.markercolor ?~ (List $ toJSON . continentRGB . read . unpack . continent <$> gms)
& B.size ?~ (List $ (toJSON . float2Double . (* 200000) . log . fromInteger . pop) <$> gms)
& B.sizeref ?~ toJSON 2e5
& B.sizeMode ?~ Area)
xTicks = [
(1000, "$ 1,000")
, (10000, "$ 10,000")
, (50000, "$ 50,000")]
in plotlySelectMultiple
(plotly "countries-scatterplot" [trace]
& layout %~ xaxis ?~ (defAxis
& axistype ?~ Log
& axistitle ?~ "GDP Per Capita"
& tickvals ?~ (toJSON . fst <$> xTicks)
& ticktext ?~ (pack . snd <$> xTicks))
& layout %~ yaxis ?~ (defAxis & axistitle ?~ "Life Expectancy")
& layout %~ title ?~ "GDP Per Capita and Life Expectancy") selCountries
gdp :: Gapminder -> Double
gdp c = gdpPercap c * (fromIntegral $ pop c)
continentsGDPsPie :: [Gapminder] -> SHtml IO GmParams ()
continentsGDPsPie gms =
let
-- list of continent-GDP pairs [(Continent, Double)]
-- for each continent from Africa to Oceania
continentGdps =
[((,) currentCont) . sum $
gdp <$>
(filter ((== show currentCont) . unpack . continent) gms)
| currentCont <- [ Africa .. Oceania ]]
pieLabels = pack . show . fst <$> continentGdps
pieValues = toJSON . snd <$> continentGdps
pieColors = List $ (toJSON . continentRGB . fst) <$> continentGdps
trace :: Trace
trace = pie
& labels ?~ pieLabels
& values ?~ pieValues
& customdata ?~ (toJSON <$> pieLabels)
& hole ?~ (toJSON 0.4)
& marker ?~ (defMarker
& markercolors ?~ pieColors)
in plotlySelectMultiple
(plotly "continents-gdp" [trace]
& layout %~ title ?~ "World's GDP by Continents") selContinents
average :: (Real a) => [a] -> Double
average xs = realToFrac (sum xs) / genericLength xs
yearsBarPlot :: [Gapminder] -> SHtml IO GmParams ()
yearsBarPlot gms =
let
years = nub $ year <$> gms
trace = vbarChart [((pack . show) y,
average (lifeExp <$> (filter ((==y) . year) gms)))
| y <- years]
in plotlySelect
(plotly "years-lifeexp" [trace]
& layout %~ title ?~ "Average Life Expactancy by Years") selYear
gmRenderer :: [Gapminder] -> SHtml IO GmParams ()
gmRenderer gms =
wrap plotlyCDN $ do
gmParams <- getValue
let selectedYear = read (unpack $ gmParams ^. selYear) :: Int
yearFilter = filter ((==selectedYear) . year)
countriesFilter = case gmParams ^. selCountries of
[] -> id
cs -> filter ((`elem` cs) . country)
continentsFilter = case gmParams ^. selContinents of
[] -> id
cs -> filter ((`elem` cs) . continent)
yearFilteredGMs = yearFilter gms
h1_ "Gapminder Scatterplot Example"
row_ $ do
mkCol [(MD,4)] $ do
continentsGDPsPie yearFilteredGMs
mkCol [(MD,8)] $ do
countriesScatterPlot $ continentsFilter yearFilteredGMs
row_ $ do
mkCol [(MD,12)] $ do
yearsBarPlot $ (countriesFilter . continentsFilter) gms
row_ $ do
mkCol [(MD,12)] $ do
countriesTable $ (countriesFilter . continentsFilter) yearFilteredGMs
gapMinderScatterPlot = do
gms <- getDataset gapminder
runDashdoIO $ Dashdo gm0 (gmRenderer gms)
|
diffusionkinetics/open
|
dashdo-examples/lib/Dashdo/Examples/GapminderScatterplot.hs
|
Haskell
|
mit
| 5,579
|
{-# LANGUAGE PatternSynonyms #-}
module Foo(A(.., B)) where
data A = A | B
|
mpickering/ghc-exactprint
|
tests/examples/ghc8/export-syntax.hs
|
Haskell
|
bsd-3-clause
| 76
|
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Plots.CmdLine where
-- ( module Plots
-- , r2AxisMain
-- ) where
-- import Data.Typeable
-- import Options.Applicative
-- -- import Diagrams.Prelude hiding ((<>), option)
-- import Diagrams.Backend.CmdLine
-- import Diagrams.Prelude hiding (option, (<>))
-- import Diagrams.TwoD.Text (Text)
-- import Plots.Axis
-- import Plots
-- data PlotOptions = PlotOptions
-- { plotTitle :: Maybe String
-- }
-- instance Parseable PlotOptions where
-- parser = PlotOptions
-- <$> (optional . strOption)
-- (long "title" <> short 't' <> help "Plot title")
-- instance (Typeable b,
-- TypeableFloat n,
-- Renderable (Text n) b,
-- Renderable (Path V2 n) b,
-- Backend b V2 n,
-- Mainable (QDiagram b V2 n Any))
-- => Mainable (Axis b V2 n) where
-- type MainOpts (Axis b V2 n) = (MainOpts (QDiagram b V2 n Any), PlotOptions)
-- mainRender (opts, pOpts) a
-- = mainRender opts . renderAxis
-- $ a & axisTitle .~ plotTitle pOpts
-- --
-- r2AxisMain :: (Parseable (MainOpts (QDiagram b V2 Double Any)), Mainable (Axis b V2 Double)) => Axis b V2 Double -> IO ()
-- r2AxisMain = mainWith
|
bergey/plots
|
src/Plots/CmdLine.hs
|
Haskell
|
bsd-3-clause
| 1,379
|
f [] a = return a ; f (x:xs) a = a + x >>= \fax -> f xs fax
|
mpickering/hlint-refactor
|
tests/examples/ListRec4.hs
|
Haskell
|
bsd-3-clause
| 59
|
{-# LANGUAGE TypeFamilies, NoMonomorphismRestriction #-}
module T2767a where
import Data.Kind (Type)
main = return ()
-- eval' :: Solver solver => Tree solver a -> [(Label solver,Tree solver a)] -> solver [a]
eval' (NewVar f) wl = do v <- newvarSM
eval' (f v) wl
eval' Fail wl = continue wl
-- continue :: Solver solver => [(Label solver,Tree solver a)] -> solver [a]
continue ((past,t):wl) = do gotoSM past
eval' t wl
data Tree s a
= Fail
| NewVar (Term s -> Tree s a)
class Monad solver => Solver solver where
type Term solver :: Type
type Label solver :: Type
newvarSM :: solver (Term solver)
gotoSM :: Label solver -> solver ()
|
sdiehl/ghc
|
testsuite/tests/indexed-types/should_compile/T2767.hs
|
Haskell
|
bsd-3-clause
| 791
|
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="fil-PH">
<title>Getting started Guide</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset>
|
ccgreen13/zap-extensions
|
src/org/zaproxy/zap/extension/gettingStarted/resources/help_fil_PH/helpset_fil_PH.hs
|
Haskell
|
apache-2.0
| 968
|
{-# LANGUAGE TypeFamilies, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE ViewPatterns #-}
module YesodCoreTest.ErrorHandling
( errorHandlingTest
, Widget
) where
import Yesod.Core
import Test.Hspec
import Network.Wai
import Network.Wai.Test
import Text.Hamlet (hamlet)
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Char8 as S8
import Control.Exception (SomeException, try)
import Network.HTTP.Types (mkStatus)
import Blaze.ByteString.Builder (Builder, fromByteString, toLazyByteString)
import Data.Monoid (mconcat)
import Data.Text (Text, pack)
import Control.Monad (forM_)
import qualified Control.Exception.Lifted as E
data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
/not_found NotFoundR POST
/first_thing FirstThingR POST
/after_runRequestBody AfterRunRequestBodyR POST
/error-in-body ErrorInBodyR GET
/error-in-body-noeval ErrorInBodyNoEvalR GET
/override-status OverrideStatusR GET
/error/#Int ErrorR GET
-- https://github.com/yesodweb/yesod/issues/658
/builder BuilderR GET
/file-bad-len FileBadLenR GET
/file-bad-name FileBadNameR GET
/good-builder GoodBuilderR GET
|]
overrideStatus = mkStatus 15 "OVERRIDE"
instance Yesod App where
errorHandler (InvalidArgs ["OVERRIDE"]) = sendResponseStatus overrideStatus ("OH HAI" :: String)
errorHandler x = defaultErrorHandler x
getHomeR :: Handler Html
getHomeR = do
$logDebug "Testing logging"
defaultLayout $ toWidget [hamlet|
$doctype 5
<html>
<body>
<form method=post action=@{NotFoundR}>
<input type=submit value="Not found">
<form method=post action=@{FirstThingR}>
<input type=submit value="Error is thrown first thing in handler">
<form method=post action=@{AfterRunRequestBodyR}>
<input type=submit value="BUGGY: Error thrown after runRequestBody">
|]
postNotFoundR, postFirstThingR, postAfterRunRequestBodyR :: Handler Html
postNotFoundR = do
(_, _files) <- runRequestBody
_ <- notFound
getHomeR
postFirstThingR = do
_ <- error "There was an error 3.14159"
getHomeR
postAfterRunRequestBodyR = do
x <- runRequestBody
_ <- error $ show $ fst x
getHomeR
getErrorInBodyR :: Handler Html
getErrorInBodyR = do
let foo = error "error in body 19328" :: String
defaultLayout [whamlet|#{foo}|]
getErrorInBodyNoEvalR :: Handler (DontFullyEvaluate Html)
getErrorInBodyNoEvalR = fmap DontFullyEvaluate getErrorInBodyR
getOverrideStatusR :: Handler ()
getOverrideStatusR = invalidArgs ["OVERRIDE"]
getBuilderR :: Handler TypedContent
getBuilderR = return $ TypedContent "ignored" $ ContentBuilder (error "builder-3.14159") Nothing
getFileBadLenR :: Handler TypedContent
getFileBadLenR = return $ TypedContent "ignored" $ ContentFile "yesod-core.cabal" (error "filebadlen")
getFileBadNameR :: Handler TypedContent
getFileBadNameR = return $ TypedContent "ignored" $ ContentFile (error "filebadname") Nothing
goodBuilderContent :: Builder
goodBuilderContent = mconcat $ replicate 100 $ fromByteString "This is a test\n"
getGoodBuilderR :: Handler TypedContent
getGoodBuilderR = return $ TypedContent "text/plain" $ toContent goodBuilderContent
getErrorR :: Int -> Handler ()
getErrorR 1 = setSession undefined "foo"
getErrorR 2 = setSession "foo" undefined
getErrorR 3 = deleteSession undefined
getErrorR 4 = addHeader undefined "foo"
getErrorR 5 = addHeader "foo" undefined
getErrorR 6 = expiresAt undefined
getErrorR 7 = setLanguage undefined
getErrorR 8 = cacheSeconds undefined
getErrorR 9 = setUltDest (undefined :: Text)
getErrorR 10 = setMessage undefined
errorHandlingTest :: Spec
errorHandlingTest = describe "Test.ErrorHandling" $ do
it "says not found" caseNotFound
it "says 'There was an error' before runRequestBody" caseBefore
it "says 'There was an error' after runRequestBody" caseAfter
it "error in body == 500" caseErrorInBody
it "error in body, no eval == 200" caseErrorInBodyNoEval
it "can override status code" caseOverrideStatus
it "builder" caseBuilder
it "file with bad len" caseFileBadLen
it "file with bad name" caseFileBadName
it "builder includes content-length" caseGoodBuilder
forM_ [1..10] $ \i -> it ("error case " ++ show i) (caseError i)
runner :: Session a -> IO a
runner f = toWaiApp App >>= runSession f
caseNotFound :: IO ()
caseNotFound = runner $ do
res <- request defaultRequest
{ pathInfo = ["not_found"]
, requestMethod = "POST"
}
assertStatus 404 res
assertBodyContains "Not Found" res
caseBefore :: IO ()
caseBefore = runner $ do
res <- request defaultRequest
{ pathInfo = ["first_thing"]
, requestMethod = "POST"
}
assertStatus 500 res
assertBodyContains "There was an error 3.14159" res
caseAfter :: IO ()
caseAfter = runner $ do
let content = "foo=bar&baz=bin12345"
res <- srequest SRequest
{ simpleRequest = defaultRequest
{ pathInfo = ["after_runRequestBody"]
, requestMethod = "POST"
, requestHeaders =
[ ("content-type", "application/x-www-form-urlencoded")
, ("content-length", S8.pack $ show $ L.length content)
]
}
, simpleRequestBody = content
}
assertStatus 500 res
assertBodyContains "bin12345" res
caseErrorInBody :: IO ()
caseErrorInBody = runner $ do
res <- request defaultRequest { pathInfo = ["error-in-body"] }
assertStatus 500 res
assertBodyContains "error in body 19328" res
caseErrorInBodyNoEval :: IO ()
caseErrorInBodyNoEval = do
eres <- try $ runner $ do
request defaultRequest { pathInfo = ["error-in-body-noeval"] }
case eres of
Left (_ :: SomeException) -> return ()
Right x -> error $ "Expected an exception, got: " ++ show x
caseOverrideStatus :: IO ()
caseOverrideStatus = runner $ do
res <- request defaultRequest { pathInfo = ["override-status"] }
assertStatus 15 res
caseBuilder :: IO ()
caseBuilder = runner $ do
res <- request defaultRequest { pathInfo = ["builder"] }
assertStatus 500 res
assertBodyContains "builder-3.14159" res
caseFileBadLen :: IO ()
caseFileBadLen = runner $ do
res <- request defaultRequest { pathInfo = ["file-bad-len"] }
assertStatus 500 res
assertBodyContains "filebadlen" res
caseFileBadName :: IO ()
caseFileBadName = runner $ do
res <- request defaultRequest { pathInfo = ["file-bad-name"] }
assertStatus 500 res
assertBodyContains "filebadname" res
caseGoodBuilder :: IO ()
caseGoodBuilder = runner $ do
res <- request defaultRequest { pathInfo = ["good-builder"] }
assertStatus 200 res
let lbs = toLazyByteString goodBuilderContent
assertBody lbs res
assertHeader "content-length" (S8.pack $ show $ L.length lbs) res
caseError :: Int -> IO ()
caseError i = runner $ do
res <- request defaultRequest { pathInfo = ["error", pack $ show i] }
assertStatus 500 res `E.catch` \e -> do
liftIO $ print res
E.throwIO (e :: E.SomeException)
|
pikajude/yesod
|
yesod-core/test/YesodCoreTest/ErrorHandling.hs
|
Haskell
|
mit
| 7,179
|
{-# LANGUAGE MagicHash, UnliftedFFITypes #-}
-- !!! cc004 -- foreign declarations
module ShouldCompile where
import Foreign
import GHC.Exts
import Data.Int
import Data.Word
-- importing functions
-- We can't import the same function using both stdcall and ccall
-- calling conventions in the same file when compiling via C (this is a
-- restriction in the C backend caused by the need to emit a prototype
-- for stdcall functions).
foreign import stdcall "p" m_stdcall :: StablePtr a -> IO (StablePtr b)
foreign import ccall unsafe "q" m_ccall :: ByteArray# -> IO Int
-- We can't redefine the calling conventions of certain functions (those from
-- math.h).
foreign import stdcall "my_sin" my_sin :: Double -> IO Double
foreign import stdcall "my_cos" my_cos :: Double -> IO Double
foreign import stdcall "m1" m8 :: IO Int8
foreign import stdcall "m2" m16 :: IO Int16
foreign import stdcall "m3" m32 :: IO Int32
foreign import stdcall "m4" m64 :: IO Int64
foreign import stdcall "dynamic" d8 :: FunPtr (IO Int8) -> IO Int8
foreign import stdcall "dynamic" d16 :: FunPtr (IO Int16) -> IO Int16
foreign import stdcall "dynamic" d32 :: FunPtr (IO Int32) -> IO Int32
foreign import stdcall "dynamic" d64 :: FunPtr (IO Int64) -> IO Int64
foreign import ccall unsafe "kitchen"
sink :: Ptr a
-> ByteArray#
-> MutableByteArray# RealWorld
-> Int
-> Int8
-> Int16
-> Int32
-> Int64
-> Word8
-> Word16
-> Word32
-> Word64
-> Float
-> Double
-> IO ()
type Sink2 b = Ptr b
-> ByteArray#
-> MutableByteArray# RealWorld
-> Int
-> Int8
-> Int16
-> Int32
-> Word8
-> Word16
-> Word32
-> Float
-> Double
-> IO ()
foreign import ccall unsafe "dynamic"
sink2 :: Ptr (Sink2 b) -> Sink2 b
|
hferreiro/replay
|
testsuite/tests/ffi/should_compile/cc004.hs
|
Haskell
|
bsd-3-clause
| 1,861
|
{-# LANGUAGE RoleAnnotations #-}
{-# OPTIONS_GHC -fwarn-unused-imports #-}
import Data.Coerce
import Data.Proxy
import Data.Monoid (First(First)) -- check whether the implicit use of First is noted
-- see https://ghc.haskell.org/trac/ghc/wiki/Design/NewCoercibleSolver/V2
foo1 :: f a -> f a
foo1 = coerce
newtype X = MkX (Int -> X)
foo2 :: X -> X
foo2 = coerce
newtype X2 a = MkX2 Char
type role X2 nominal
foo3 :: X2 Int -> X2 Bool
foo3 = coerce
newtype Age = MkAge Int
newtype Y a = MkY a
type role Y nominal
foo4 :: Y Age -> Y Int
foo4 = coerce
newtype Z a = MkZ ()
type role Z representational
foo5 :: Z Int -> Z Bool
foo5 = coerce
newtype App f a = MkApp (f a)
foo6 :: f a -> App f a
foo6 = coerce
foo7 :: Coercible a b => b -> a
foo7 = coerce
foo8 :: (Coercible a b, Coercible b c) => Proxy b -> a -> c
foo8 _ = coerce
main = print (coerce $ Just (1::Int) :: First Int)
|
urbanslug/ghc
|
testsuite/tests/typecheck/should_compile/TcCoercibleCompile.hs
|
Haskell
|
bsd-3-clause
| 896
|
-- !!! Importing Tycon with bogus constructor
module M where
import Prelude(Either(Left,Right,Foo))
|
forked-upstream-packages-for-ghcjs/ghc
|
testsuite/tests/module/mod81.hs
|
Haskell
|
bsd-3-clause
| 101
|
main :: IO ()
main = do
putStrLn "Escriba un nombre: "
nombre <- getLine
case nombre of "Napoleon" -> putStrLn "Su apellido es Bonaparte!"
_ -> putStrLn "No se ha podido determinar su apellido"
|
clinoge/primer-semestre-udone
|
src/04-condicionales/nombre.hs
|
Haskell
|
mit
| 231
|
module Bio.Utils.Misc
( readInt
, readDouble
, bins
, binBySize
, binBySizeLeft
, binBySizeOverlap
) where
import Data.ByteString.Char8 (ByteString)
import Data.ByteString.Lex.Fractional (readExponential, readSigned)
import Data.ByteString.Lex.Integral (readDecimal)
import Data.Maybe (fromMaybe)
readInt :: ByteString -> Int
readInt x = fst . fromMaybe errMsg . readSigned readDecimal $ x
where
errMsg = error $ "readInt: Fail to cast ByteString to Int:" ++ show x
{-# INLINE readInt #-}
readDouble :: ByteString -> Double
readDouble x = fst . fromMaybe errMsg . readSigned readExponential $ x
where
errMsg = error $ "readDouble: Fail to cast ByteString to Double:" ++ show x
{-# INLINE readDouble #-}
-- | divide a given half-close-half-open region into fixed size
-- half-close-half-open intervals, discarding leftovers
binBySize :: Int -> (Int, Int) -> [(Int, Int)]
binBySize step (start, end) = let xs = [start, start + step .. end]
in zip xs . tail $ xs
{-# INLINE binBySize #-}
binBySizeOverlap :: Int -> Int -> (Int, Int) -> [(Int, Int)]
binBySizeOverlap step overlap (start, end)
| overlap >= step = error "binBySizeOverlap: overlap > step"
| otherwise = go start
where
go i | i + overlap < end = (i, i + step) : go (i + step - overlap)
| otherwise = []
{-# INLINE binBySizeOverlap #-}
-- | Including leftovers, the last bin will be extended to match desirable size
binBySizeLeft :: Int -> (Int, Int) -> [(Int, Int)]
binBySizeLeft step (start, end) = go start
where
go i | i < end = (i, i + step) : go (i + step)
| otherwise = []
{-# INLINE binBySizeLeft #-}
-- | divide a given region into k equal size sub-regions, discarding leftovers
bins :: Int -> (Int, Int) -> [(Int, Int)]
bins binNum (start, end) = let k = (end - start) `div` binNum
in take binNum . binBySize k $ (start, end)
{-# INLINE bins #-}
|
kaizhang/bioinformatics-toolkit
|
bioinformatics-toolkit/src/Bio/Utils/Misc.hs
|
Haskell
|
mit
| 2,028
|
module Bot
( Event (..)
, Response (..)
, handleEvent
) where
import Data.List
import Data.List.Split
import Data.Char (toLower)
import Network.HTTP.Base (urlEncode)
data Event = Msg { msg :: String
, sender :: String }
data Response = SendMsg { msgToSend :: String }
-- | GetChanUsers { chanName :: String}
| LeaveChan
| JoinChan { chanName :: String }
| Exit
handleEvent :: Event -> Maybe Response
handleEvent (Msg m s) = case m of
-- Commands start with '!'
('!' : command) -> handleCommand . buildCommand $ command
"Hello" -> Just $ SendMsg $ "Hello, " ++ s ++ "!"
s -> if isHey s
then Just $ SendMsg $ "H" ++ (replicate ((countEInHey s) + 1) 'o')
else Nothing
-----------------------------------
-- Commands
-----------------------------------
data Command = Command { cmd :: String
, arg :: Maybe String }
buildCommand :: String -> Command
buildCommand s =
Command makeCommand makeArg
where
makeCommand = takeWhile ((/=) ' ') s
makeArg = let argStr = drop 1 . dropWhile ((/=) ' ') $ s
in if argStr == [] then Nothing else Just argStr
handleCommand :: Command -> Maybe Response
handleCommand (Command command Nothing) =
case command of
"quit" -> Just $ Exit
"part" -> Just $ LeaveChan
handleCommand (Command command (Just arg)) =
case command of
"gs" -> Just $ SendMsg $ getSearchUrl "https://www.google.com/search?q=" arg
"hs" -> Just $ SendMsg $ getSearchUrl "https://www.haskell.org/hoogle/?hoogle=" arg
-----------------------------------
-- Used for Heeey-Hooo
-----------------------------------
isHey :: String -> Bool
isHey s =
if s == []
then False
else let s' = map toLower s
in (head s' == 'h') && ((dropWhile (== 'e') . drop 1 $ s) == "y")
countEInHey :: String -> Int
countEInHey s = (length s) - 2
-----------------------------------
-- Helper functions
-----------------------------------
getSearchUrl :: String -> String -> String
getSearchUrl basicUrl str = basicUrl ++ urlEncode str
|
TheCrafter/Scarybot
|
src/Bot.hs
|
Haskell
|
mit
| 2,215
|
{-# LANGUAGE TupleSections #-}
module System where
import System.Directory
import System.FilePath
import Aws
import Control.Monad
import Data.Text (Text)
-- | Loads the aws creds by keyname from the currenty directory or parent
-- directories.
loadAwsCreds :: Text -> IO (Maybe (FilePath, Credentials))
loadAwsCreds key = do
dirs <- getDirectories
mcreds <- mapM (flip loadCredentialsFromFile key . (</> ".aws-keys")) dirs
return $ msum $ zipWith (\d m -> (d,) <$> m) dirs mcreds
-- | Returns the current working directory and each parent directory.
getDirectories :: IO [FilePath]
getDirectories = getCurrentDirectory >>= return . subs
where subs "/" = ["/"]
subs fp = fp : (subs $ takeDirectory fp)
-- | Checks a file as an absolute path and relative path - if either path
-- is a valid file then returns a Just filepath.
checkFilePath :: FilePath -> IO (Maybe FilePath)
checkFilePath fp = do
isAbs <- doesFileExist fp
if isAbs
then return $ Just fp
else do
cwd <- getCurrentDirectory
let relfp = cwd </> fp
isRel <- doesFileExist relfp
if isRel
then return $ Just relfp
else return $ Nothing
|
schell/dropdox
|
src/System.hs
|
Haskell
|
mit
| 1,193
|
{-# LANGUAGE OverloadedStrings #-}
import Control.Applicative ((<$>))
import Data.List (intercalate,sortBy)
import Text.Blaze.Html (toHtml,toValue, (!))
import Text.Blaze.Html.Renderer.String (renderHtml)
import qualified Text.Blaze.Html5 as BlazeHtml
import qualified Text.Blaze.Html5.Attributes as BlazeAttr
import Data.Monoid (mappend, mconcat)
import Hakyll.Web.Tags (renderTags)
import Control.Monad (forM)
import Data.Maybe (fromMaybe)
import Hakyll
main :: IO ()
main = hakyll $ do
-- Static files
match ("images/*" .||. "js/*" .||. "favicon.ico" .||. "CNAME" .||. "files/*") $ do
route idRoute
compile copyFileCompiler
-- Compress CSS
match "css/*" $ do
route idRoute
compile compressCssCompiler
-- About
match "about.md" $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/about.html" defaultContext
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
-- Build Tags
tags <- buildTags "posts/*" (fromCapture "tags/*.html")
-- Individual Posts
match "posts/*" $ do
route $ setExtension "html"
compile $ pandocCompiler
>>= loadAndApplyTemplate "templates/post.html" (postContext tags)
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
-- Posts
create ["posts.html"] $ do
route idRoute
compile $ do
list <- postList tags "posts/*" recentFirst
let postsContext = constField "posts" list `mappend`
constField "title" "Posts" `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/posts.html" postsContext
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
-- Index
create ["index.html"] $ do
route idRoute
compile $ do
list <- postListNum tags "posts/*" recentFirst 3
let indexContext = constField "posts" list `mappend`
constField "title" "Home" `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/index.html" indexContext
>>= loadAndApplyTemplate "templates/default.html" indexContext
>>= relativizeUrls
-- 404
create ["404.html"] $ do
route idRoute
compile $ do
let notFoundContext = constField "title" "404 - Not Found" `mappend`
constField "body" "The page you were looking for was not found." `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/about.html" notFoundContext
>>= loadAndApplyTemplate "templates/default.html" notFoundContext
>>= relativizeUrls
-- Tag Pages
tagsRules tags $ \tag pattern -> do
let title = "Posts tagged with " ++ tag
route idRoute
compile $ do
list <- postList tags pattern recentFirst
let tagContext = constField "title" title `mappend`
constField "posts" list `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/posts.html" tagContext
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
-- Tags
create ["tags.html"] $ do
route idRoute
compile $ do
tagList <- renderTagElem tags
let tagsContext = constField "title" "Tags" `mappend`
constField "tags" tagList `mappend`
defaultContext
makeItem ""
>>= loadAndApplyTemplate "templates/tags.html" tagsContext
>>= loadAndApplyTemplate "templates/default.html" defaultContext
>>= relativizeUrls
-- RSS
create ["rss.xml"] $ do
route idRoute
compile $ do
posts <- loadAll "posts/*"
sorted <- take 10 <$> recentFirst posts
renderRss feedConfiguration feedContext sorted
match "templates/*" $ compile templateCompiler
------------------------------------------------------
postContext :: Tags -> Context String
postContext tags = mconcat
[ modificationTimeField "mtime" "%U"
, dateField "date" "%B %e, %Y"
, tagsField "tags" tags
, defaultContext
]
------------------------------------------------------
postList :: Tags -> Pattern -> ([Item String] -> Compiler [Item String]) -> Compiler String
postList tags pattern prep = do
posts <- loadAll pattern
itemTemplate <- loadBody "templates/postitem.html"
processed <- prep posts
applyTemplateList itemTemplate (postContext tags) processed
postListNum :: Tags -> Pattern -> ([Item String] -> Compiler [Item String]) -> Int -> Compiler String
postListNum tags pattern prep num = do
posts <- prep <$> loadAll pattern
itemTemplate <- loadBody "templates/postitem.html"
taken <- take num <$> posts
applyTemplateList itemTemplate (postContext tags) taken
-----------------------------------------------------
renderTagElem :: Tags -> Compiler String
renderTagElem = renderTags makeLink (intercalate "\n")
where
makeLink tag url count _ _ = renderHtml $
BlazeHtml.li $ BlazeHtml.a ! BlazeAttr.href (toValue url) $ toHtml (tag ++ " - " ++ show count ++(postName count))
postName :: Int -> String
postName 1 = " post"
postName _ = " posts"
------------------------------------------------------
feedConfiguration :: FeedConfiguration
feedConfiguration = FeedConfiguration
{ feedTitle = "warwickmasson.com - Posts"
, feedDescription = "Posts from warwickmasson.com"
, feedAuthorName = "Warwick Masson"
, feedAuthorEmail = "warwick.masson@gmail.com"
, feedRoot = "http://warwickmasson.com"
}
------------------------------------------------------
feedContext :: Context String
feedContext = constField "description" "" `mappend` defaultContext
|
WarwickMasson/wmasson-hakyll
|
site.hs
|
Haskell
|
mit
| 6,246
|
{-# LANGUAGE GADTs #-}
module Kafkaesque.Request.Offsets
( offsetsRequestV0
, respondToRequestV0
) where
import Data.Attoparsec.ByteString (Parser)
import Data.Int (Int32, Int64)
import Data.Maybe (catMaybes, fromMaybe)
import qualified Data.Pool as Pool
import qualified Database.PostgreSQL.Simple as PG
import Kafkaesque.KafkaError
(noError, unknownTopicOrPartition, unsupportedForMessageFormat)
import Kafkaesque.Parsers
(kafkaArray, kafkaString, signedInt32be, signedInt64be)
import Kafkaesque.Protocol.ApiKey (Offsets)
import Kafkaesque.Protocol.ApiVersion (V0)
import Kafkaesque.Queries
(getEarliestOffset, getNextOffset, getTopicPartition)
import Kafkaesque.Request.KafkaRequest
(OffsetListRequestPartition,
OffsetListRequestTimestamp(EarliestOffset, LatestOffset,
OffsetListTimestamp),
OffsetListRequestTopic, OffsetListResponsePartition,
OffsetListResponseTopic, Request(OffsetsRequestV0),
Response(OffsetsResponseV0))
makeTimestamp :: Int64 -> Maybe OffsetListRequestTimestamp
makeTimestamp (-1) = Just LatestOffset
makeTimestamp (-2) = Just EarliestOffset
makeTimestamp t
| t > 0 = Just $ OffsetListTimestamp t
| otherwise = Nothing
offsetsRequestTimestamp :: Parser OffsetListRequestTimestamp
offsetsRequestTimestamp =
makeTimestamp <$> signedInt64be >>=
maybe (fail "Unable to parse timestamp") return
offsetsRequestPartition :: Parser OffsetListRequestPartition
offsetsRequestPartition =
(\partitionId ts maxNumOffsets -> (partitionId, ts, maxNumOffsets)) <$>
signedInt32be <*>
offsetsRequestTimestamp <*>
signedInt32be
offsetsRequestTopic :: Parser OffsetListRequestTopic
offsetsRequestTopic =
(\t xs -> (t, xs)) <$> kafkaString <*>
(fromMaybe [] <$> kafkaArray offsetsRequestPartition)
offsetsRequestV0 :: Parser (Request Offsets V0)
offsetsRequestV0 =
OffsetsRequestV0 <$> signedInt32be <*>
(fromMaybe [] <$> kafkaArray offsetsRequestTopic)
fetchTopicPartitionOffsets ::
PG.Connection
-> Int32
-> Int32
-> OffsetListRequestTimestamp
-> Int32
-> IO (Maybe [Int64])
fetchTopicPartitionOffsets conn topicId partitionId timestamp maxOffsets = do
earliest <- getEarliestOffset conn topicId partitionId
latest <- getNextOffset conn topicId partitionId
-- TODO handle actual timestamp offsets
let sendOffsets = Just . take (fromIntegral maxOffsets) . catMaybes
return $
case timestamp of
LatestOffset -> sendOffsets [Just latest, earliest]
EarliestOffset -> sendOffsets [earliest]
OffsetListTimestamp _ -> Nothing
fetchPartitionOffsets ::
PG.Connection
-> String
-> OffsetListRequestPartition
-> IO OffsetListResponsePartition
fetchPartitionOffsets conn topicName (partitionId, timestamp, maxOffsets) = do
res <- getTopicPartition conn topicName partitionId
case res of
Nothing -> return (partitionId, unknownTopicOrPartition, Nothing)
Just (topicId, _) -> do
offsetRes <-
fetchTopicPartitionOffsets conn topicId partitionId timestamp maxOffsets
return $
case offsetRes of
Nothing -> (partitionId, unsupportedForMessageFormat, Nothing)
Just offsets -> (partitionId, noError, Just offsets)
fetchTopicOffsets ::
PG.Connection -> OffsetListRequestTopic -> IO OffsetListResponseTopic
fetchTopicOffsets conn (topicName, partitions) = do
partitionResponses <- mapM (fetchPartitionOffsets conn topicName) partitions
return (topicName, partitionResponses)
respondToRequestV0 ::
Pool.Pool PG.Connection -> Request Offsets V0 -> IO (Response Offsets V0)
respondToRequestV0 pool (OffsetsRequestV0 _ topics) = do
topicResponses <-
Pool.withResource pool (\conn -> mapM (fetchTopicOffsets conn) topics)
return $ OffsetsResponseV0 topicResponses
|
cjlarose/kafkaesque
|
src/Kafkaesque/Request/Offsets.hs
|
Haskell
|
mit
| 3,819
|
import System.Environment
import System.IO
import Data.List
import Data.Ord
import qualified Data.Map as M
import System.Process
splitOn :: (a -> Bool) -> [a] -> [[a]]
splitOn f [] = [[]]
splitOn f (h:t) = let (rh:rt) = splitOn f t
ret = (h:rh):rt in
if f h then []:ret else ret
getExpected (sigil:hunk) =
map tail $ filter (\ (h:_) -> h == ' ' || h == '-') hunk
diffHunk orig hunk =
do let expected = zip [0..] (getExpected hunk)
allIndices = map (\(num,line) -> map (\x->x-num) (elemIndices line orig)) expected
start = head . maximumBy (comparing length) . group . sort . concat $ allIndices
there = take (length expected) $ drop (start-1) orig
writeFile "/tmp/there" (unlines there)
writeFile "/tmp/expected" (unlines $ map snd expected)
--runCommand "diff -U 8 -p /tmp/there /tmp/expected" >>= waitForProcess
runCommand "meld /tmp/there /tmp/expected" >>= waitForProcess
main = do args <- getArgs
if length args /= 1 then
putStrLn "I only take one argument, a diff file, with hunks that failed to apply cleanly"
else
return ()
let name = head args
patch <- fmap lines (readFile name)
let '-':'-':'-':' ':origName = head patch
orig <- fmap lines (readFile origName)
putStrLn $ "patch is " ++ show (length patch) ++ " lines long, orig is " ++ show (length orig) ++ " lines long"
let hunks = tail $ splitOn (\ lin -> "@@" `isPrefixOf` lin) patch
putStrLn $ "and I found " ++ show (length hunks) ++ " hunks"
mapM_ (diffHunk orig) hunks
|
mjrosenb/bend
|
bend.hs
|
Haskell
|
mit
| 1,680
|
{-# LANGUAGE OverloadedStrings #-}
module Text.Marquee.Parser.Block (parseBlocks) where
import Control.Applicative
import Control.Monad
import Control.Monad.State (StateT(..), get, modify, lift)
import Data.Char (isLetter, isUpper)
import Data.Text (Text())
import qualified Data.Text as T
import Data.Attoparsec.Text as Atto
import Data.Attoparsec.Combinator
import Text.Marquee.Parser.Common
import Text.Marquee.Parser.HTML as H
import Text.Marquee.SyntaxTrees.CST (Doc(..), DocElement(..))
import qualified Text.Marquee.SyntaxTrees.CST as C
parseBlocks :: BlockParser Doc
parseBlocks = sepBy block (lift lineEnding)
-- Types
type BlockParser = StateT [Int] Parser
indent :: Int -> BlockParser ()
indent n = modify ((:) n)
unindent :: BlockParser ()
unindent = modify (drop 1)
indentLevel :: BlockParser Int
indentLevel = liftM sum get
-- Useful definitions
bulletMarker :: Parser Char
bulletMarker = oneOf "-+*"
orderedMarker :: Parser (String, Char)
orderedMarker = (,) <$> atMostN1 9 digit <*> oneOf ".)"
-- Parsing
block :: BlockParser DocElement
block = choice [
blankLine
, headingUnderline
, thematicBreak
, heading
, indentedLine
, fenced
, html
, linkRef
-- Container
, blockquote
, unorderedList
, orderedList
-- -- Any other is a paragraph
, paragraph
]
indented :: BlockParser DocElement -> BlockParser DocElement
indented p = indentLevel >>= \level -> count level (lift linespace) >> p
blankLine :: BlockParser DocElement
blankLine = lift $ next (lookAhead lineEnding_) *> return C.blankLine
headingUnderline :: BlockParser DocElement
headingUnderline = lift $ do
optIndent
cs@(c:_) <- setextOf 1 '=' <|> setextOf 2 '-'
return $ C.headingUnderline (if c == '=' then 1 else 2) (T.pack cs)
where setextOf n c = manyN n (char c) <* next (lookAhead lineEnding_)
thematicBreak :: BlockParser DocElement
thematicBreak = lift $ do
optIndent
thematicBreakOf '-' <|> thematicBreakOf '_' <|> thematicBreakOf '*'
return C.thematicBreak
where thematicBreakOf c = manyN 3 (char c <* skipWhile isLinespace) <* next (lookAhead lineEnding_)
heading :: BlockParser DocElement
heading = lift $ do
optIndent
pounds <- atMostN1 6 (char '#')
lookAhead (void linespace) <|> lookAhead lineEnding_
content <- headingInline (length pounds)
return $ C.heading (length pounds) content
indentedLine :: BlockParser DocElement
indentedLine = lift $ C.indentedBlock <$> (string " " *> rawInline)
fenced :: BlockParser DocElement
fenced = do
indentLen <- (+) <$> indentLevel <*> (length <$> lift optIndent)
lift $ do
fence <- fenceOf '`' <|> fenceOf '~'
infoString <- T.pack <$>
manyTill (escaped <|> anyChar)
(lookAhead $ void (char '`') <|> lineEnding)
<* lineEnding
let fenceIndent = atMostN indentLen (char ' ')
closingFence = fenceIndent *> optIndent *> manyN (length fence) (char $ head fence)
content <- manyTill1
(fenceIndent *> Atto.takeTill isLineEnding <* lineEnding_)
(endOfInput <|> lookAhead (closingFence *> next lineEnding_))
closingFence *> takeTill isLineEnding
return $ C.fenced infoString content
where fenceOf c = manyN 3 (char c)
html :: BlockParser DocElement
html = lift optIndent *> (html1to5 <|> html6 <|> html7)
where html1to5 = lift $ do
xs <- H.info <|> H.comment <|> H.cdata <|> H.special <|> H.preFormated
ys <- takeTill isLineEnding
return . C.html $ T.append xs ys
html6 = lift $ do
xs <- H.simpleTag
ys <- tillBlankLine
return . C.html $ T.append xs ys
html7 = lift $ do
xs <- (H.tag <|> H.ctag) <* lookAhead whitespace
ys <- tillBlankLine
return . C.html $ T.append xs ys
tillBlankLine = T.concat <$> manyTill
(Atto.takeWhile1 (not .isLineEnding) <|> Atto.take 1)
(lookAhead $ lineEnding *> emptyLine)
linkRef :: BlockParser DocElement
linkRef = lift $ do
optIndent
ref <- linkLabel <* char ':'
dest <- spacing *> linkDestination
mtitle <- (optionMaybe $ spacing *> linkTitle) <* next (lookAhead lineEnding_)
return $ C.linkReference ref dest mtitle
where spacing = skipWhile isLinespace >> (optional $ lineEnding *> skipMany linespace)
paragraph :: BlockParser DocElement
paragraph = lift $ C.paragraphBlock <$> rawInline
blockquote :: BlockParser DocElement
blockquote = C.blockquoteBlock <$> (lift (optIndent *> char '>' *> skipWhile isLinespace) *> block)
unorderedList :: BlockParser DocElement
unorderedList = do
indent <- lift $ length <$> optIndent
marker <- lift bulletMarker
spaces <- lift $ T.length <$> takeWhile1 isWhitespace
C.unorderedList marker <$> listItem (indent + 1 + spaces)
orderedList :: BlockParser DocElement
orderedList = do
indent <- lift $ length <$> optIndent
(num, marker) <- lift orderedMarker
spaces <- lift $ T.length <$> takeWhile1 isWhitespace
C.orderedList marker (read num) <$> listItem (indent + length num + 1 + spaces)
listItem :: Int -> BlockParser Doc
listItem indentAmount = do
indent indentAmount
level <- indentLevel
x <- block
xs <- concat <$> many (lift lineEnding *> go)
unindent
return (x:xs)
where go = do
x <- optionMaybe $ blankLine <* lift lineEnding
y <- indented block
case x of
Nothing -> return [y]
Just x -> return [x, y]
rawInline :: Parser Text
rawInline = Atto.takeTill isLineEnding
headingInline :: Int -> Parser Text
headingInline headingSize = do
xs <- manyTill anyChar (lookAhead end) <* end
return $ T.pack xs
where end = lookAhead lineEnding_ <|> linespace *> Atto.takeWhile (== '#') *> next (lookAhead lineEnding_)
|
DanielRS/marquee
|
src/Text/Marquee/Parser/Block.hs
|
Haskell
|
mit
| 5,830
|
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.RTCDTMFSender
(js_insertDTMF, insertDTMF, js_getCanInsertDTMF, getCanInsertDTMF,
js_getTrack, getTrack, js_getToneBuffer, getToneBuffer,
js_getDuration, getDuration, js_getInterToneGap, getInterToneGap,
toneChange, RTCDTMFSender, castToRTCDTMFSender, gTypeRTCDTMFSender)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"insertDTMF\"]($2, $3, $4)"
js_insertDTMF :: RTCDTMFSender -> JSString -> Int -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.insertDTMF Mozilla RTCDTMFSender.insertDTMF documentation>
insertDTMF ::
(MonadIO m, ToJSString tones) =>
RTCDTMFSender -> tones -> Int -> Int -> m ()
insertDTMF self tones duration interToneGap
= liftIO
(js_insertDTMF (self) (toJSString tones) duration interToneGap)
foreign import javascript unsafe "($1[\"canInsertDTMF\"] ? 1 : 0)"
js_getCanInsertDTMF :: RTCDTMFSender -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.canInsertDTMF Mozilla RTCDTMFSender.canInsertDTMF documentation>
getCanInsertDTMF :: (MonadIO m) => RTCDTMFSender -> m Bool
getCanInsertDTMF self = liftIO (js_getCanInsertDTMF (self))
foreign import javascript unsafe "$1[\"track\"]" js_getTrack ::
RTCDTMFSender -> IO (Nullable MediaStreamTrack)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.track Mozilla RTCDTMFSender.track documentation>
getTrack ::
(MonadIO m) => RTCDTMFSender -> m (Maybe MediaStreamTrack)
getTrack self = liftIO (nullableToMaybe <$> (js_getTrack (self)))
foreign import javascript unsafe "$1[\"toneBuffer\"]"
js_getToneBuffer :: RTCDTMFSender -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.toneBuffer Mozilla RTCDTMFSender.toneBuffer documentation>
getToneBuffer ::
(MonadIO m, FromJSString result) => RTCDTMFSender -> m result
getToneBuffer self
= liftIO (fromJSString <$> (js_getToneBuffer (self)))
foreign import javascript unsafe "$1[\"duration\"]" js_getDuration
:: RTCDTMFSender -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.duration Mozilla RTCDTMFSender.duration documentation>
getDuration :: (MonadIO m) => RTCDTMFSender -> m Int
getDuration self = liftIO (js_getDuration (self))
foreign import javascript unsafe "$1[\"interToneGap\"]"
js_getInterToneGap :: RTCDTMFSender -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.interToneGap Mozilla RTCDTMFSender.interToneGap documentation>
getInterToneGap :: (MonadIO m) => RTCDTMFSender -> m Int
getInterToneGap self = liftIO (js_getInterToneGap (self))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/RTCDTMFSender.ontonechange Mozilla RTCDTMFSender.ontonechange documentation>
toneChange :: EventName RTCDTMFSender Event
toneChange = unsafeEventName (toJSString "tonechange")
|
manyoo/ghcjs-dom
|
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RTCDTMFSender.hs
|
Haskell
|
mit
| 3,788
|
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Main where
import Control.Applicative
import Control.Monad
import Control.Concurrent.STM
import Data.Hashable
import Data.Function (on)
import qualified Data.Map as M
import qualified Data.List as L
import qualified Control.Concurrent.STM.Map as TTrie
import Test.QuickCheck
import Test.QuickCheck.Monadic
import Test.Framework (defaultMain, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
-- most of this based on the unordered-containers tests
-----------------------------------------------------------------------
main = defaultMain [ testGroup "basic interface"
[ testProperty "lookup" pLookup
, testProperty "insert" pInsert
, testProperty "delete" pDelete
]
, testGroup "unsafe functions"
[ testProperty "phantomLookup" pPhantomLookup
, testProperty "unsafeDelete" pUnsafeDelete
]
, testGroup "conversions"
[ testProperty "fromList" pFromList
, testProperty "unsafeToList" pUnsafeToList
]
]
-----------------------------------------------------------------------
type Model k v = M.Map k v
eq :: (Eq a, Eq k, Hashable k, Ord k)
=> (Model k v -> a) -> (TTrie.Map k v -> IO a) -> [(k, v)] -> Property
eq f g xs = monadicIO $ do
let a = f (M.fromList xs)
b <- run $ g =<< TTrie.fromList xs
assert $ a == b
eq_ :: (Eq k, Eq v, Hashable k, Ord k)
=> (Model k v -> Model k v) -> (TTrie.Map k v -> IO ()) -> [(k, v)] -> Property
eq_ f g xs = monadicIO $ do
let a = M.toAscList $ f $ M.fromList xs
m <- run $ TTrie.fromList xs
run $ g m
b <- run $ unsafeToAscList m
assert $ a == b
unsafeToAscList :: Ord k => TTrie.Map k v -> IO [(k, v)]
unsafeToAscList m = do
xs <- TTrie.unsafeToList m
return $ L.sortBy (compare `on` fst) xs
-----------------------------------------------------------------------
-- key type that generates more hash collisions
newtype Key = K { unK :: Int }
deriving (Arbitrary, Eq, Ord)
instance Show Key where
show = show . unK
instance Hashable Key where
hashWithSalt salt k = hashWithSalt salt (unK k) `mod` 20
-----------------------------------------------------------------------
pLookup :: Key -> [(Key,Int)] -> Property
pLookup k = M.lookup k `eq` (atomically . TTrie.lookup k)
pPhantomLookup :: Key -> [(Key,Int)] -> Property
pPhantomLookup k = M.lookup k `eq` (atomically . TTrie.phantomLookup k)
pInsert :: Key -> Int -> [(Key,Int)] -> Property
pInsert k v = M.insert k v `eq_` (atomically . TTrie.insert k v)
pDelete :: Key -> [(Key,Int)] -> Property
pDelete k = M.delete k `eq_` (atomically . TTrie.delete k)
pUnsafeDelete :: Key -> [(Key,Int)] -> Property
pUnsafeDelete k = M.delete k `eq_` TTrie.unsafeDelete k
pFromList :: [(Key,Int)] -> Property
pFromList = id `eq_` (\_ -> return ())
pUnsafeToList :: [(Key,Int)] -> Property
pUnsafeToList = M.toAscList `eq` unsafeToAscList
|
mcschroeder/ttrie
|
tests/MapProperties.hs
|
Haskell
|
mit
| 3,168
|
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
import System.Environment
import Data.Text
import Control.Monad
import qualified Data.ByteString as BS (writeFile, readFile)
import qualified Codec.Compression.Zlib as ZL
import qualified Data.Text.Encoding as TE
import Data.Serialize as DS
-- newtype NewText = NewText Text deriving Show
instance Serialize Text where
put txt = put $ TE.encodeUtf8 txt
get = fmap TE.decodeUtf8 get
testText = 6::Int-- NewText "eefefef" -- "#.<>[]'_,:=/\\+(){}!?*-|^~&@\8322\8321\8729\8868\8869"
fileName = "testext.bin"
main = do
putStrLn "Writing text to the file..."
let bsw = encode testText
BS.writeFile fileName bsw
putStrLn "Reading the text from the file..."
bsr <- BS.readFile fileName
let tt = decode bsr
case tt of
Left s -> do
putStrLn $ "Error in decoding: " ++ s
return ()
Right (t::Int) -> do
putStrLn $ show t
return ()
|
BitFunctor/bitfunctor-theory
|
aux/testsertext.hs
|
Haskell
|
mit
| 1,080
|
module Graphics.Urho3D.Graphics.Internal.Texture(
Texture
, SharedTexture
, WeakTexture
, textureCntx
, sharedTexturePtrCntx
, weakTexturePtrCntx
) where
import Graphics.Urho3D.Container.Ptr
import qualified Language.C.Inline as C
import qualified Language.C.Inline.Context as C
import qualified Language.C.Types as C
import qualified Data.Map as Map
data Texture
textureCntx :: C.Context
textureCntx = mempty {
C.ctxTypesTable = Map.fromList [
(C.TypeName "Texture", [t| Texture |])
]
}
sharedPtrImpl "Texture"
sharedWeakPtrImpl "Texture"
|
Teaspot-Studio/Urho3D-Haskell
|
src/Graphics/Urho3D/Graphics/Internal/Texture.hs
|
Haskell
|
mit
| 577
|
module Mood where
data Mood = Blah | Woot deriving Show
changeMood :: Mood -> Mood
changeMood Blah = Woot
changeMood _ = Blah
|
mikegehard/haskellBookExercises
|
chapter4/mood.hs
|
Haskell
|
mit
| 136
|
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad (msum)
import Happstack.Server
import Web.Routes.Happstack (implSite)
import BBQ.Route
import Data.Accounts
import Data.RecordPool
import Data.Sheets
import Data.AppConfig
withAcid path action =
openAccountsState path $ \st1 ->
openRecordPools path $ \st2 ->
openSheetsState path $ \st3 ->
action $ AppConfig st1 st2 st3
main :: IO ()
main = do
putStrLn "BBQ is listening on 8000."
withAcid "_state" $ \acid -> simpleHTTP nullConf $ runApp acid server
server :: App Response
server = msum
[ dir "images" $ serveDirectory DisableBrowsing [] "images"
, dirs "static/css" $ serveDirectory DisableBrowsing [] "views/css"
, dirs "static/js" $ serveDirectory DisableBrowsing [] "views/js"
, implSite "https://bbq.yan.ac" "" site
, notFound $ toResponse ("resource not found" :: String)
]
|
yan-ac/bbq.yan.ac
|
bbq.hs
|
Haskell
|
mit
| 908
|
{-# htermination zipWithM :: (a -> b -> Maybe c) -> [a] -> [b] -> Maybe [c] #-}
import Monad
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Monad_zipWithM_3.hs
|
Haskell
|
mit
| 93
|
module Language.Lips.Evaluator where
--------------------
-- Global Imports --
import Control.Monad.State (liftIO)
import Control.Monad
-------------------
-- Local Imports --
import Language.Lips.LanguageDef
import Language.Lips.State
----------
-- Code --
-- Lifting an error
liftError :: Error LipsVal -> LipsVal
liftError (Success a) = a
liftError (Error et) = LList [LAtom "println", LString $ displayErrorType et]
-- Binding a variable
eBind :: String -> LipsVal -> ProgramState (Error LipsVal)
eBind name val = do
evaled <- eval val
pushVariable name evaled
return $ Success lNull
-- Dropping a variable
eDrop :: String -> ProgramState (Error LipsVal)
eDrop name = do
exists <- hasVariable name
case exists of
False -> return $ Error VariableNotDefinedError
True -> do
dropVariable name
return $ Success lNull
-- Performing IO on a LipsVal
performIO :: (LipsVal -> IO ()) -> LipsVal -> ProgramState (Error LipsVal)
performIO fn val = do
errval <- safeEval val
case errval of
Success val -> (liftIO $ fn val) >> (return $ Success lNull)
Error et -> return $ Error et
-- Printing a variable
ePrint :: LipsVal -> ProgramState (Error LipsVal)
ePrint = performIO $ putStr . show
-- Printing a variable with a newline
ePrintln :: LipsVal -> ProgramState (Error LipsVal)
ePrintln = performIO $ putStrLn . show
-- Re-evaluating an accessed variable
eVarLookup :: String -> [LipsVal] -> ProgramState (Error LipsVal)
eVarLookup name args = do
hp <- hasPrimitive name
if hp
then mapM eval args >>= applyPrimitive name
else do
errval <- getVariable name
case errval of
Success val ->
if null args
then safeEval val
else safeEval $ LList (val : args)
Error et -> return $ Error et
-- Applying an LFunction to its arguments
eApply :: LipsVal -> [LipsVal] -> ProgramState (Error LipsVal)
eApply (LFunction names val) args
| length names /= length args = return $ Error InvalidFunctionApplicationError
| otherwise = do
let zipped = zip names args
forM_ zipped (\(name, arg) -> eBind name arg)
v <- safeEval val
forM_ zipped (\(name, arg) -> eDrop name)
return v
-- Safely evaluating things
safeEval :: LipsVal -> ProgramState (Error LipsVal)
safeEval (LList [LAtom "bind" , LAtom name, val]) = eBind name val
safeEval (LList [LAtom "drop" , LAtom name ]) = eDrop name
safeEval (LList [LAtom "print" , val ]) = ePrint val
safeEval (LList [LAtom "println" , val ]) = ePrintln val
safeEval (LList [LAtom "quote" , val ]) = return $ Success val
safeEval (LList (LAtom name : args )) = eVarLookup name args
safeEval (LAtom name ) = eVarLookup name []
safeEval (LList (fn@(LFunction _ _): args )) = eApply fn args
safeEval fn@(LFunction _ _ ) = return $ Success fn
safeEval other = return $ Success other
-- Evaluating a LipsVal (printing any error messages)
eval :: LipsVal -> ProgramState LipsVal
eval lval = do
errval <- safeEval lval
case errval of
Success val -> return val
Error et -> eval $ LList [LAtom "println", LString $ displayErrorType et]
|
crockeo/lips
|
src/lib/Language/Lips/Evaluator.hs
|
Haskell
|
mit
| 3,307
|
-- {{{
{-# LANGUAGE OverloadedStrings, MultiWayIf, LambdaCase #-}
module Main where
---------------------Import-------------------------
import Prelude
import Data.List
import Data.Char
import qualified Data.ByteString.Char8 as BS -- BS.getContents
import qualified Data.Vector as V
import qualified Data.Map as Map
import qualified Data.Set as Set
import qualified Data.HashMap as HM
import qualified Data.Sequence as Seq
import qualified Data.Foldable as Foldable
import Control.Applicative
import Data.Ratio -- x = 5%6
import Data.Maybe
import Text.Regex.Posix
import System.Random -- randomIO, randomRIO, randomRs, newStdGen
import Data.Int -- Int32, Int64
import System.IO
import Data.Bits -- (.&.), (.|.), shiftL...
import Text.Printf -- printf "%0.6f" (1.0)
import Control.Monad
import System.Directory
import System.FilePath
import Data.Aeson
import Control.Exception
import System.Process -- runCommand
-- }}}
main :: IO ()
main = do
return ()
|
abhiranjankumar00/dot-vim
|
skel/skel.hs
|
Haskell
|
mit
| 1,115
|
-- :l C:\Local\Dev\haskell\h4c.hs
-- Exemplos do tutorial http://www.haskell.org/haskellwiki/Haskell_Tutorial_for_C_Programmers
-- 2.5
-- Uma implementação recursiva de fib que usa uma função auxiliar geradora
fib :: Integer -> Integer
fib n = fibGen 0 1 n
fibGen :: Integer -> Integer -> Integer -> Integer
fibGen a b n = case n of
0 -> a
n -> fibGen b (a + b) (n - 1)
-- Uma lista infinita de números de fibonacci
fibs :: [Integer]
fibs = 0 : 1 : [ a + b | (a, b) <- zip fibs (tail fibs) ]
-- 3.3
-- Pequeno teste de aplicação de uma função que recebe dois parâmetros e retorna um terceiro
apply' :: (a -> b -> c) -> a -> b -> c
apply' f a b = f a b
-- Aplica a função do tipo (a -> b) a todos os elementos de a gerando uma nova lista
map' :: (a -> b) -> [a] -> [b]
map' f xs = [ f x | x <- xs ]
-- Versão recursiva de map
mapRec :: (a -> b) -> [a] -> [b]
mapRec f [] = []
mapRec f xs = f (head xs):(mapRec f (tail xs))
fooList :: [Int]
fooList = [3, 1, 5, 4]
bar :: Int -> Int
bar n = n - 2
-- Ex: map bar fooList
-- 3.4
subEachFromTen :: [Int] -> [Int]
subEachFromTen = map (10 -)
-- 4.1
-- Reimplementação de fib usando correspondência de padrão
-- Foi necessário usar Num a, Eq a devido a uma alteração recente na linguagem em que Num não implica mais em Eq
fibPat :: (Num a, Eq a, Num b, Eq b) => a -> b
fibPat n = fibGenPat 0 1 n
fibGenPat :: (Num a, Eq a, Num b, Eq b) => b -> b -> a -> b
fibGenPat x _ 0 = x
fibGenPat x y n = fibGenPat y (x + y) (n - 1)
-- 4.2
showTime :: Int -> Int -> String
showTime hours minutes
| hours > 23 = error "Invalid hours"
| minutes > 59 = error "Invalid minutes"
| hours == 0 = showHour 12 "am"
| hours <= 11 = showHour hours "am"
| hours == 12 = showHour hours "pm"
| otherwise = showHour (hours - 12) "pm"
where
showHour h s = (show h) ++ ":" ++ showMin ++ " " ++ s
showMin
| minutes < 10 = "0" ++ show minutes
| otherwise = show minutes
-- 4.3
showLen :: [a] -> String
showLen lst = (show (theLen)) ++ (if theLen == 1 then " item" else " itens")
where theLen = length lst
-- 4.5 Lambda
-- map (\x -> "the " ++ show x) [1, 2, 3, 4, 5]
-- 4.6 Type constructors
-- main = putStrLn (show 4)
-- main = return ()
sayHello :: Maybe String -> String
sayHello Nothing = "Hello!"
sayHello (Just name) = "Hello, " ++ name ++ "!"
-- Exemplos: sayHello Nothing, sayHello (Just "Felipo")
-- 4.7 Monadas
-- É uma forma de mesclar a programação "imperativa" (com estado, ordem de execução, resolução imediata, entrada/saída, etc.) com a programação funcional.
someFunc :: Int -> Int -> [Int]
someFunc a b = [a, b]
main = do putStr "prompt 1: "
a <- getLine
putStr "prompt 2: "
b <- getLine
putStrLn (show (someFunc (read a) (read b)))
-- Comandos depois da palavra-chave "do" devem estar alinhados para denotar um bloco
test1 = do
putStrLn "Sum 3 numbers"
putStr "num 1: "
a <- getLine
putStr "num 2: "
b <- getLine
putStr "num 3: "
c <- getLine
putStrLn ("Result is " ++ (show ((read a) + (read b) + (read c))))
getName1 :: IO String
getName1 = do
putStr "Please enter your name: "
name <- getLine
putStrLn "Thank you. Please wait."
return name
getName2 :: IO String
getName2 = do
putStr "Please enter your name: "
getLine
{-
O último código dentro de uma Monada deve ter o mesmo tipo de retorno da Monada
:t getLine
getLine :: IO String
Em getName1 é realizado um retorno explícito de uma variável.
Em getName2 é retornado o próprio valor retornado por getLine diretamente
-}
-- 5.1 Where are the for loops
-- Como um "for" é escrito em haskell
bar' :: Int -> Int
bar' x = x*2
foo' :: [Int] -> [Int]
foo' (x:xs) = bar' x : foo' xs
foo' [] = []
-- Equivale a definir foo' = map bar'
-- Muitos casos de "for" são escritos como map, foldr, foldl, sum, dentre outras funções de tratamento de lista de haskell altamente otimizadas
-- Quando não for possível usar nenhum dos casos uma função recursiva deve resolver o problema.
-- 5.2 Lazy Evaluation
data Tree a = Null | Node a (Tree a) (Tree a)
t1 :: Tree Int
t1 = Node 3 (Node 2 Null Null) (Node 5 (Node 4 Null Null) Null)
inOrderList :: Tree a -> [a]
inOrderList Null = []
inOrderList (Node item left right) =
inOrderList left ++ [item] ++ inOrderList right
fooTree :: Int -> Tree Int
fooTree n = Node n (fooTree (n - 1)) (fooTree (n + 1))
t2 = fooTree 0
inOrderListLevel :: Tree a -> Int -> [a]
inOrderListLevel Null _ = []
inOrderListLevel _ 0 = []
inOrderListLevel (Node item left right) n =
inOrderListLevel left (n - 1) ++ [item] ++ inOrderListLevel right (n - 1)
fooTreeLevel :: Int -> Int -> Tree Int
fooTreeLevel _ 0 = Null
fooTreeLevel n l = Node n (fooTreeLevel (n - 1) (l - 1)) (fooTreeLevel (n + 1) (l - 1))
|
feliposz/learning-stuff
|
haskell/h4c.hs
|
Haskell
|
mit
| 4,833
|
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Data.Foldable (traverse_)
import Data.Text (Text)
import Data.Default
import Data.Memory.Types
import Data.Memory.DB.Acid
import Text.Blaze.Html5 (Html, (!), toHtml)
import Clay ((?))
import Happstack.Foundation
import qualified Data.Map as M
import qualified Data.Text.Lazy.Encoding as LazyT
import qualified Data.ByteString.Char8 as B
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import qualified Clay as C
instance PathInfo a => PathInfo [a] where
toPathSegments = concat . fmap toPathSegments
fromPathSegments = many fromPathSegments
instance ToMessage C.Css where
toContentType _ = B.pack "text/css; charset=UTF-8"
toMessage = LazyT.encodeUtf8 . C.render
data Route = Search
| Css
| NewNode [NodeID] Text
| ViewNode [NodeID]
$(derivePathInfo ''Route)
type Memory' = FoundationT' Route MemoryAcid () IO
type Memory = XMLGenT Memory'
type MemoryForm = FoundationForm Route MemoryAcid () IO
instance (Functor m, Monad m) => HasAcidState (FoundationT' url MemoryAcid s m) Node where
getAcidState = acidMemory <$> getAcidSt
outputNode :: [NodeID] -> Node -> Html
outputNode xs (Node nData nMap) = H.div ! A.class_ "box" $ do
H.a ! A.href href $ toHtml (nodeText nData)
traverse_ f (M.toAscList nMap)
where href = H.toValue $ toPathInfo (ViewNode xs)
f (nnID, nn) = outputNode (xs ++ [nnID]) nn
route :: Route -> Memory Response
route Search = ok $ toResponse $ template "Search" $ H.h1 "Search"
route (NewNode xs text) = update (UInsertNode node xs) >>= \case
Nothing -> internalServerError $ toResponse $ template "Internal Server Error" $ "Failed to insert node"
Just node -> ok $ toResponse $ template "New Node" $ H.pre $ outputNode xs node
where node = def { nodeData = def { nodeText = text } }
route (ViewNode xs) = query (QLookupNode xs) >>= \case
Nothing -> internalServerError $ toResponse $ template "Internal Server Error" $ "Failed to lookup node"
Just node -> ok $ toResponse $ template "View Node" $ H.pre $ outputNode xs node
route Css = ok (toResponse css)
main :: IO ()
main = withAcid $ \root -> do
simpleApp id defaultConf (AcidUsing root) () Search "" route
template :: Text -> Html -> Html
template title body = H.docTypeHtml $ do
H.head $ do
H.title (toHtml title)
H.link
! A.type_ "text/css"
! A.rel "stylesheet"
! A.href (H.toValue $ toPathInfo Css)
H.body $ do
body
css :: C.Css
css = do
".box" ? do
C.padding (C.px 3) (C.px 5) (C.px 3) (C.px 5)
C.background (C.rgba 20 24 30 10)
|
shockkolate/brainfart
|
examples/basic/Main.hs
|
Haskell
|
apache-2.0
| 2,914
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeOperators #-}
module Camfort.Specification.StencilsSpec (spec) where
import Control.Monad.Writer.Strict hiding (Sum, Product)
import Data.List
import Camfort.Helpers.Vec
import Camfort.Input
import Camfort.Specification.Stencils
import Camfort.Specification.Stencils.Synthesis
import Camfort.Specification.Stencils.Model
import Camfort.Specification.Stencils.InferenceBackend
import Camfort.Specification.Stencils.InferenceFrontend
import Camfort.Specification.Stencils.Syntax
import qualified Language.Fortran.AST as F
import Language.Fortran.ParserMonad
import Camfort.Reprint
import Camfort.Output
import qualified Data.IntMap as IM
import qualified Data.Set as S
import Data.Functor.Identity
import qualified Data.ByteString.Char8 as B
import System.FilePath
import Test.Hspec
import Test.QuickCheck
spec :: Spec
spec =
describe "Stencils" $ do
describe "Some checks on containing spans" $ do
it "(0)" $ containedWithin (Cons 1 (Cons 1 Nil), Cons 2 (Cons 2 Nil))
(Cons 0 (Cons 0 Nil), Cons 3 (Cons 3 Nil))
`shouldBe` True
it "(1)" $ containedWithin (Cons 0 (Cons 0 Nil), Cons 3 (Cons 3 Nil))
(Cons 1 (Cons 1 Nil), Cons 2 (Cons 2 Nil))
`shouldBe` False
it "(2)" $ containedWithin (Cons 2 (Cons 2 Nil), Cons 2 (Cons 2 Nil))
(Cons 1 (Cons 1 Nil), Cons 2 (Cons 2 Nil))
`shouldBe` True
it "(3)" $ containedWithin (Cons 2 (Cons 2 Nil), Cons 3 (Cons 3 Nil))
(Cons 1 (Cons 1 Nil), Cons 2 (Cons 2 Nil))
`shouldBe` False
it "(4)" $ containedWithin (Cons 2 Nil, Cons 2 Nil)
(Cons 2 Nil, Cons 2 Nil)
`shouldBe` True
it "sorting on indices" $
shouldBe (sort [ Cons 1 (Cons 2 (Cons 1 Nil))
, Cons 2 (Cons 2 (Cons 3 Nil))
, Cons 1 (Cons 3 (Cons 3 Nil))
, Cons 0 (Cons 3 (Cons 1 Nil))
, Cons 1 (Cons 0 (Cons 2 Nil))
, Cons 1 (Cons 1 (Cons 1 Nil))
, Cons 2 (Cons 1 (Cons 1 Nil)) ])
([ Cons 1 (Cons 1 (Cons 1 Nil))
, Cons 2 (Cons 1 (Cons 1 Nil))
, Cons 1 (Cons 2 (Cons 1 Nil))
, Cons 0 (Cons 3 (Cons 1 Nil))
, Cons 1 (Cons 0 (Cons 2 Nil))
, Cons 2 (Cons 2 (Cons 3 Nil))
, Cons 1 (Cons 3 (Cons 3 Nil))
] :: [Vec (S (S (S Z))) Int])
it "composeRegions (1,0)-(1,0) span and (2,0)-(2,0) span" $
shouldBe (coalesce
(Cons 1 (Cons 0 Nil), Cons 1 (Cons 0 Nil))
(Cons 2 (Cons 0 Nil), Cons 2 (Cons 0 Nil)))
$ Just (Cons 1 (Cons 0 Nil), Cons 2 (Cons 0 Nil))
it "composeRegions failing on (1,0)-(2,0) span and (4,0)-(5,0) span" $
shouldBe (coalesce
(Cons 1 (Cons 0 Nil), Cons 2 (Cons 0 Nil))
(Cons 4 (Cons 0 Nil), Cons 5 (Cons 0 Nil)))
Nothing
it "composeRegions failing on (1,0)-(2,0) span and (3,1)-(3,1) span" $
shouldBe (coalesce
(Cons 1 (Cons 0 Nil), Cons 2 (Cons 0 Nil))
(Cons 3 (Cons 1 Nil), Cons 3 (Cons 1 Nil)))
Nothing
it "five point stencil 2D" $
-- Sort the expected value for the sake of easy equality
shouldBe (sort $ inferMinimalVectorRegions fivepoint)
(sort [ (Cons (-1) (Cons 0 Nil), Cons 1 (Cons 0 Nil))
, (Cons 0 (Cons (-1) Nil), Cons 0 (Cons 1 Nil)) ])
it "seven point stencil 3D" $
shouldBe
(sort $ inferMinimalVectorRegions sevenpoint)
(sort
[ (Cons (-1) (Cons 0 (Cons 0 Nil)), Cons 1 (Cons 0 (Cons 0 Nil)))
, (Cons 0 (Cons (-1) (Cons 0 Nil)), Cons 0 (Cons 1 (Cons 0 Nil)))
, (Cons 0 (Cons 0 (Cons (-1) Nil)), Cons 0 (Cons 0 (Cons 1 Nil))) ])
describe "Example stencil inferences" $ do
it "five point stencil 2D" $
inferFromIndicesWithoutLinearity (VL fivepoint)
`shouldBe`
(Specification $ Mult $ Exact $ Spatial
(Sum [ Product [ Centered 1 1 True, Centered 0 2 True]
, Product [ Centered 0 1 True, Centered 1 2 True]
]))
it "seven point stencil 2D" $
inferFromIndicesWithoutLinearity (VL sevenpoint)
`shouldBe`
(Specification $ Mult $ Exact $ Spatial
(Sum [ Product [ Centered 1 1 True, Centered 0 2 True, Centered 0 3 True]
, Product [ Centered 0 1 True, Centered 1 2 True, Centered 0 3 True]
, Product [ Centered 0 1 True, Centered 0 2 True, Centered 1 3 True]
]))
it "five point stencil 2D with blip" $
inferFromIndicesWithoutLinearity (VL fivepointErr)
`shouldBe`
(Specification $ Mult $ Exact $ Spatial
(Sum [ Product [ Centered 1 1 True, Centered 0 2 True],
Product [ Centered 0 1 True, Centered 1 2 True],
Product [ Forward 1 1 True, Forward 1 2 True] ]))
it "centered forward" $
inferFromIndicesWithoutLinearity (VL centeredFwd)
`shouldBe`
(Specification $ Mult $ Exact $ Spatial
(Sum [ Product [ Forward 1 1 True
, Centered 1 2 True] ]))
describe "2D stencil verification" $
mapM_ (test2DSpecVariation (Neighbour "i" 0) (Neighbour "j" 0)) variations
describe "2D stencil verification relative" $
mapM_ (\(a, b, x, y) -> test2DSpecVariation a b (x, y)) variationsRel
describe "3D stencil verification" $
mapM_ test3DSpecVariation variations3D
describe ("Synthesising indexing expressions from offsets is inverse to" ++
"extracting offsets from indexing expressions; and vice versa") $
it "isomorphism" $ property prop_extract_synth_inverse
describe "Inconsistent induction variable usage tests" $ do
it "consistent (1) a(i,j) = b(i+1,j+1) + b(i,j)" $
indicesToSpec' ["i", "j"]
[Neighbour "i" 0, Neighbour "j" 0]
[[offsetToIx "i" 1, offsetToIx "j" 1],
[offsetToIx "i" 0, offsetToIx "j" 0]]
`shouldBe` (Just $ Specification $ Once $ Exact
(Spatial
(Sum [Product [Forward 1 1 False, Forward 1 2 False],
Product [Centered 0 1 True, Centered 0 2 True]])))
it "consistent (2) a(i,c,j) = b(i,j+1) + b(i,j) \
\:: forward(depth=1,dim=2)*pointed(dim=1)" $
indicesToSpec' ["i", "j"]
[Neighbour "i" 0, Constant (F.ValInteger "0"), Neighbour "j" 0]
[[offsetToIx "i" 0, offsetToIx "j" 1],
[offsetToIx "i" 0, offsetToIx "j" 0]]
`shouldBe` (Just $ Specification $ Once $ Exact
(Spatial
(Sum [Product [Centered 0 1 True, Forward 1 2 True]])))
it "consistent (3) a(i+1,c,j) = b(j,i+1) + b(j,i) \
\:: backward(depth=1,dim=2)*pointed(dim=1)" $
indicesToSpec' ["i", "j"]
[Neighbour "i" 1, Constant (F.ValInteger "0"), Neighbour "j" 0]
[[offsetToIx "j" 0, offsetToIx "i" 1],
[offsetToIx "j" 0, offsetToIx "i" 0]]
`shouldBe` (Just $ Specification $ Once $ Exact
(Spatial
(Sum [Product [Centered 0 1 True, Backward 1 2 True]])))
it "consistent (4) a(i+1,j) = b(0,i+1) + b(0,i) \
\:: backward(depth=1,dim=2)" $
indicesToSpec' ["i", "j"]
[Neighbour "i" 1, Neighbour "j" 0]
[[offsetToIx "j" absoluteRep, offsetToIx "i" 1],
[offsetToIx "j" absoluteRep, offsetToIx "i" 0]]
`shouldBe` (Just $ Specification $ Once $ Exact
(Spatial
(Sum [Product [Backward 1 2 True]])))
it "consistent (5) a(i) = b(i,i+1) \
\:: pointed(dim=1)*forward(depth=1,dim=2,nonpointed)" $
indicesToSpec' ["i", "j"]
[Neighbour "i" 0]
[[offsetToIx "i" 0, offsetToIx "i" 1]]
`shouldBe` (Just $ Specification $ Once $ Exact
(Spatial
(Sum [Product [Centered 0 1 True,
Forward 1 2 False]])))
it "consistent (6) a(i) = b(i) + b(0) \
\:: pointed(dim=1)" $
indicesToSpec' ["i", "j"]
[Neighbour "i" 0]
[[offsetToIx "i" 0], [offsetToIx "i" absoluteRep]]
`shouldBe` Nothing
it "inconsistent (1) RHS" $
indicesToSpec' ["i", "j"]
[Neighbour "i" 0, Neighbour "j" 0]
[[offsetToIx "i" 1, offsetToIx "j" 1],
[offsetToIx "j" 0, offsetToIx "i" 0]]
`shouldBe` Nothing
it "inconsistent (2) RHS to LHS" $
indicesToSpec' ["i", "j"]
[Neighbour "i" 0]
[[offsetToIx "i" 1, offsetToIx "j" 1],
[offsetToIx "j" 0, offsetToIx "i" 0]]
`shouldBe` Nothing
-------------------------
-- Some integration tests
-------------------------
let fixturesDir = "tests"
</> "fixtures"
</> "Specification"
</> "Stencils"
example2In = fixturesDir </> "example2.f"
program <- runIO $ readParseSrcDir example2In []
describe "integration test on inference for example2.f" $ do
it "stencil infer" $
fst (callAndSummarise (infer AssignMode '=') program)
`shouldBe`
"\ntests/fixtures/Specification/Stencils/example2.f\n\
\(32:7)-(32:26) stencil readOnce, (backward(depth=1, dim=1)) :: a\n\
\(26:8)-(26:29) stencil readOnce, (pointed(dim=1))*(pointed(dim=2)) :: a\n\
\(24:8)-(24:53) stencil readOnce, (pointed(dim=1))*(centered(depth=1, dim=2)) \
\+ (centered(depth=1, dim=1))*(pointed(dim=2)) :: a\n\
\(41:8)-(41:94) stencil readOnce, (centered(depth=1, dim=2)) \
\+ (centered(depth=1, dim=1)) :: a"
it "stencil check" $
fst (callAndSummarise (\f p -> (check f p, p)) program)
`shouldBe`
"\ntests/fixtures/Specification/Stencils/example2.f\n\
\(23:1)-(23:82) Correct.\n(31:1)-(31:56) Correct."
let example4In = fixturesDir </> "example4.f"
program <- runIO $ readParseSrcDir example4In []
describe "integration test on inference for example4.f" $
it "stencil infer" $
fst (callAndSummarise (infer AssignMode '=') program)
`shouldBe`
"\ntests/fixtures/Specification/Stencils/example4.f\n\
\(6:8)-(6:33) stencil readOnce, (pointed(dim=1)) :: x"
let example5oldStyleFile = fixturesDir </> "example5.f"
example5oldStyleExpected = fixturesDir </> "example5.expected.f"
example5newStyleFile = fixturesDir </> "example5.f90"
example5newStyleExpected = fixturesDir </> "example5.expected.f90"
program5old <- runIO $ readParseSrcDir example5oldStyleFile []
program5oldSrc <- runIO $ readFile example5oldStyleFile
synthExpectedSrc5Old <- runIO $ readFile example5oldStyleExpected
program5new <- runIO $ readParseSrcDir example5newStyleFile []
program5newSrc <- runIO $ readFile example5newStyleFile
synthExpectedSrc5New <- runIO $ readFile example5newStyleExpected
describe "integration test on inference for example5" $ do
describe "stencil synth" $ do
it "inserts correct comment types for old fortran" $
(B.unpack . runIdentity
$ reprint (refactoring Fortran77)
(snd . head . snd $ synth AssignMode '=' (map (\(f, _, p) -> (f, p)) program5old))
(B.pack program5oldSrc))
`shouldBe` synthExpectedSrc5Old
it "inserts correct comment types for modern fortran" $
(B.unpack . runIdentity
$ reprint (refactoring Fortran90)
(snd . head . snd $ synth AssignMode '=' (map (\(f, _, p) -> (f, p)) program5new))
(B.pack program5newSrc))
`shouldBe` synthExpectedSrc5New
-- Indices for the 2D five point stencil (deliberately in an odd order)
fivepoint = [ Cons (-1) (Cons 0 Nil), Cons 0 (Cons (-1) Nil)
, Cons 1 (Cons 0 Nil) , Cons 0 (Cons 1 Nil), Cons 0 (Cons 0 Nil)
]
-- Indices for the 3D seven point stencil
sevenpoint = [ Cons (-1) (Cons 0 (Cons 0 Nil)), Cons 0 (Cons (-1) (Cons 0 Nil))
, Cons 0 (Cons 0 (Cons 1 Nil)), Cons 0 (Cons 1 (Cons 0 Nil))
, Cons 1 (Cons 0 (Cons 0 Nil)), Cons 0 (Cons 0 (Cons (-1) Nil))
, Cons 0 (Cons 0 (Cons 0 Nil))
]
centeredFwd = [ Cons 1 (Cons 0 Nil), Cons 0 (Cons 1 Nil), Cons 0 (Cons (-1) Nil)
, Cons 1 (Cons 1 Nil), Cons 0 (Cons 0 Nil), Cons 1 (Cons (-1) Nil)
] :: [ Vec (S (S Z)) Int ]
-- Examples of unusal patterns
fivepointErr = [ Cons (-1) (Cons 0 Nil)
, Cons 0 (Cons (-1) Nil)
, Cons 1 (Cons 0 Nil)
, Cons 0 (Cons 1 Nil)
, Cons 0 (Cons 0 Nil)
, Cons 1 (Cons 1 Nil) ] :: [ Vec (S (S Z)) Int ]
{- Construct arbtirary vectors and test up to certain sizes -}
instance {-# OVERLAPPING #-} Arbitrary a => Arbitrary (Vec Z a) where
arbitrary = return Nil
instance (Arbitrary (Vec n a), Arbitrary a) => Arbitrary (Vec (S n) a) where
arbitrary = do x <- arbitrary
xs <- arbitrary
return $ Cons x xs
test2DSpecVariation a b (input, expectation) =
it ("format=" ++ show input) $
-- Test inference
indicesToSpec' ["i", "j"] [a, b] (map fromFormatToIx input)
`shouldBe` Just expectedSpec
where
expectedSpec = Specification expectation
fromFormatToIx [ri,rj] = [ offsetToIx "i" ri, offsetToIx "j" rj ]
indicesToSpec' ivs lhs = fst . runWriter . indicesToSpec ivmap "a" lhs
where ivmap = IM.singleton 0 (S.fromList ivs)
variations =
[ ( [ [0,0] ]
, Once $ Exact $ Spatial (Sum [Product [ Centered 0 1 True, Centered 0 2 True]])
)
, ( [ [1,0] ]
, Once $ Exact $ Spatial (Sum [Product [Forward 1 1 False, Centered 0 2 True]])
)
, ( [ [1,0], [0,0], [0,0] ]
, Mult $ Exact $ Spatial (Sum [Product [Forward 1 1 True, Centered 0 2 True]])
)
, ( [ [0,1], [0,0] ]
, Once $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Forward 1 2 True]])
)
, ( [ [1,1], [0,1], [1,0], [0,0] ]
, Once $ Exact $ Spatial (Sum [Product [Forward 1 1 True, Forward 1 2 True]])
)
, ( [ [-1,0], [0,0] ]
, Once $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Centered 0 2 True]])
)
, ( [ [0,-1], [0,0], [0,-1] ]
, Mult $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Backward 1 2 True]])
)
, ( [ [-1,-1], [0,-1], [-1,0], [0,0], [0, -1] ]
, Mult $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Backward 1 2 True]])
)
, ( [ [0,-1], [1,-1], [0,0], [1,0], [1,1], [0,1] ]
, Once $ Exact $ Spatial $ Sum [ Product [ Forward 1 1 True, Centered 1 2 True] ]
)
-- Stencil which is non-contiguous in one direction
, ( [ [0, 4], [1, 4] ]
, Once $ Bound Nothing
(Just (Spatial (Sum [ Product [ Forward 1 1 True
, Forward 4 2 False ] ])))
)
]
variationsRel =
[ -- Stencil which has non-relative indices in one dimension
(Neighbour "i" 0, Constant (F.ValInteger "0"), [ [0, absoluteRep], [1, absoluteRep] ]
, Once $ Exact $ Spatial (Sum [Product [Forward 1 1 True]])
)
, (Neighbour "i" 1, Neighbour "j" 0, [ [0,0] ]
, Once $ Exact $ Spatial (Sum [Product [ Backward 1 1 False, Centered 0 2 True]])
)
, (Neighbour "i" 0, Neighbour "j" 1, [ [0,1] ]
, Once $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Centered 0 2 True]])
)
, (Neighbour "i" 1, Neighbour "j" (-1), [ [1,0], [0,0], [0,0] ]
, Mult $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Forward 1 2 False]])
)
, (Neighbour "i" 0, Neighbour "j" (-1), [ [0,1], [0,0] ]
, Once $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Forward 2 2 False]])
)
-- [0,1] [0,0] [0,-1]
, (Neighbour "i" 1, Neighbour "j" 0, [ [1,1], [1,0], [1,-1] ]
, Once $ Exact $ Spatial (Sum [Product [Centered 0 1 True, Centered 1 2 True]])
)
, (Neighbour "i" 1, Neighbour "j" 0, [ [-2,0], [-1,0] ]
, Once $ Bound Nothing
(Just (Spatial (Sum [Product [ Backward 3 1 False
, Centered 0 2 True ]]))))
, (Constant (F.ValInteger "0"), Neighbour "j" 0, [ [absoluteRep,1], [absoluteRep,0], [absoluteRep,-1] ]
, Once $ Exact $ Spatial (Sum [Product [Centered 1 2 True]])
)
]
test3DSpecVariation (input, expectation) =
it ("format=" ++ show input) $
-- Test inference
indicesToSpec' ["i", "j", "k"]
[Neighbour "i" 0, Neighbour "j" 0, Neighbour "k" 0]
(map fromFormatToIx input)
`shouldBe` Just expectedSpec
where
expectedSpec = Specification expectation
fromFormatToIx [ri,rj,rk] =
[offsetToIx "i" ri, offsetToIx "j" rj, offsetToIx "k" rk]
variations3D =
[ ( [ [-1,0,-1], [0,0,-1], [-1,0,0], [0,0,0] ]
, Once $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Centered 0 2 True, Backward 1 3 True]])
)
, ( [ [1,1,0], [0,1,0] ]
, Once $ Exact $ Spatial (Sum [Product [Forward 1 1 True, Forward 1 2 False, Centered 0 3 True]])
)
, ( [ [-1,0,-1], [0,0,-1], [-1,0,0], [0,0,0] ]
, Once $ Exact $ Spatial (Sum [Product [Backward 1 1 True, Centered 0 2 True, Backward 1 3 True]])
)
]
prop_extract_synth_inverse :: F.Name -> Int -> Bool
prop_extract_synth_inverse v o =
ixToNeighbour' [v] (offsetToIx v o) == Neighbour v o
-- Local variables:
-- mode: haskell
-- haskell-program-name: "cabal repl test-suite:spec"
-- End:
|
mrd/camfort
|
tests/Camfort/Specification/StencilsSpec.hs
|
Haskell
|
apache-2.0
| 18,775
|
module CustomList where
data List a = Nil | Cons a (List a)
deriving Show
emptyList :: List a
emptyList = Nil
isEmpty :: List a -> Bool
isEmpty Nil = True
isEmpty (Cons _ _) = False
cons :: a -> List a -> List a
cons = Cons
head :: List a -> a
head Nil = error "Empty list"
head (Cons x _) = x
tail :: List a -> List a
tail Nil = error "Empty list"
tail (Cons _ xs) = xs
append :: List a -> List a -> List a
append Nil ys = ys
append (Cons x xs) ys = Cons x (append xs ys)
update :: List a -> Int -> a -> List a
update Nil _ _ = error "Empty list"
update (Cons _ xs) 0 y = Cons y xs
update (Cons x xs) i y = Cons x (update xs (i - 1) y)
-- | Compute suffixes of a list
--
-- Examples:
--
-- >>> suffixes Nil
-- Nil
--
-- >>> suffixes (Cons 1 Nil)
-- Cons (Cons 1 Nil) Nil
--
-- >>> suffixes (Cons 1 (Cons 2 (Cons 3 Nil)))
-- Cons (Cons 1 (Cons 2 (Cons 3 Nil))) (Cons (Cons 2 (Cons 3 Nil)) (Cons (Cons 3 Nil) Nil))
suffixes :: List a -> List (List a)
suffixes Nil = Nil
suffixes (Cons x xs) = Cons (Cons x xs) (suffixes xs)
|
wildsebastian/PurelyFunctionalDataStructures
|
chapter02/CustomList.hs
|
Haskell
|
apache-2.0
| 1,052
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module NLP.MorfNCP
( temp
) where
import Control.Monad (forM_)
-- import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.IO as L
import qualified Data.Tagset.Positional as P
import qualified NLP.MorfNCP.Base as Base
import qualified NLP.MorfNCP.Show as Show
import qualified NLP.MorfNCP.NCP as NCP
import qualified NLP.MorfNCP.MSD as MSD
import qualified NLP.MorfNCP.Morfeusz as Morf
---------------------------------------------------
-- Reconcile
---------------------------------------------------
-- -- | Reconcile the tags chosen in NCP with the output graph generated
-- -- by Morfeusz.
-- reconcile
-- :: [Mx.Seg Text]
-- -- ^ Sentence in NCP
-- -> DAG () (Morf.Token)
---------------------------------------------------
-- Temp
---------------------------------------------------
-- | Temporary function.
temp :: FilePath -> FilePath -> IO ()
temp tagsetPath ncpPath = do
tagset <- P.parseTagset tagsetPath <$> readFile tagsetPath
let parseTag x
| x == "ign" = Nothing
| x == "num:comp" = Just $ P.parseTag tagset "numcomp"
| otherwise = Just $ P.parseTag tagset x
showTag may = case may of
Nothing -> "ign"
Just x -> P.showTag tagset x
simpTag = MSD.simplify tagset
procTag = fmap simpTag . parseTag
-- procTag = parseTag
xs <- NCP.getSentences ncpPath
forM_ xs $ \sent -> do
-- putStrLn ">>>"
let orth = NCP.showSent sent
-- L.putStrLn orth >> putStrLn ""
-- mapM_ print $ Morf.analyze orth
-- let dag = map (fmap Morf.fromToken) $ Morf.analyze orth
-- let dag = map (fmap $ fmap MSD.parseMSD' . Morf.fromToken) $ Morf.analyze orth
let dagMorf
= Base.recalcIxsLen
. map (fmap $ fmap procTag . Morf.fromToken)
$ Morf.analyze orth
-- putStrLn "Morfeusz:"
-- mapM_ print dagMorf >> putStrLn ""
let dagNCP
= Base.recalcIxsLen
. Base.fromList
. map (fmap procTag)
$ NCP.fromSent sent
-- let dag = Base.fromList . map (fmap MSD.parseMSD') $ NCP.fromSent sent
-- let dag = Base.fromList $ NCP.fromSent sent
-- putStrLn "NCP:"
-- mapM_ print dagNCP >> putStrLn ""
let dag
= Base.recalcIxs1
. map (fmap $ fmap showTag)
$ Base.merge [dagMorf, dagNCP]
L.putStrLn $ Show.showSent dag
-- putStrLn "Result:"
-- mapM_ print dag
-- putStrLn ">>>\n"
|
kawu/morf-nkjp
|
src/NLP/MorfNCP.hs
|
Haskell
|
bsd-2-clause
| 2,509
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.