code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
-----------------------------------------------------------------------------
-- |
-- License : BSD-3-Clause
-- Maintainer : Oleg Grenrus <[email protected]>
--
-- The repo collaborators API as described on
-- <http://developer.github.com/v3/repos/collaborators/>.
module GitHub.Endpoints.Repos.Collaborators (
collaboratorsOnR,
collaboratorPermissionOnR,
isCollaboratorOnR,
addCollaboratorR,
module GitHub.Data,
) where
import GitHub.Data
import GitHub.Internal.Prelude
import Prelude ()
-- | List collaborators.
-- See <https://developer.github.com/v3/repos/collaborators/#list-collaborators>
collaboratorsOnR :: Name Owner -> Name Repo -> FetchCount -> Request k (Vector SimpleUser)
collaboratorsOnR user repo =
pagedQuery ["repos", toPathPart user, toPathPart repo, "collaborators"] []
-- | Review a user's permission level.
-- <https://developer.github.com/v3/repos/collaborators/#review-a-users-permission-level>
collaboratorPermissionOnR
:: Name Owner -- ^ Repository owner
-> Name Repo -- ^ Repository name
-> Name User -- ^ Collaborator to check permissions of.
-> GenRequest 'MtJSON rw CollaboratorWithPermission
collaboratorPermissionOnR owner repo coll =
query ["repos", toPathPart owner, toPathPart repo, "collaborators", toPathPart coll, "permission"] []
-- | Check if a user is a collaborator.
-- See <https://developer.github.com/v3/repos/collaborators/#check-if-a-user-is-a-collaborator>
isCollaboratorOnR
:: Name Owner -- ^ Repository owner
-> Name Repo -- ^ Repository name
-> Name User -- ^ Collaborator?
-> GenRequest 'MtStatus rw Bool
isCollaboratorOnR user repo coll =
Query ["repos", toPathPart user, toPathPart repo, "collaborators", toPathPart coll] []
-- | Invite a user as a collaborator.
-- See <https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator>
addCollaboratorR
:: Name Owner -- ^ Repository owner
-> Name Repo -- ^ Repository name
-> Name User -- ^ Collaborator to add
-> GenRequest 'MtJSON 'RW (Maybe RepoInvitation)
addCollaboratorR owner repo coll =
Command Put ["repos", toPathPart owner, toPathPart repo, "collaborators", toPathPart coll] mempty
| jwiegley/github | src/GitHub/Endpoints/Repos/Collaborators.hs | bsd-3-clause | 2,278 | 0 | 10 | 402 | 384 | 209 | 175 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE MultiWayIf #-}
module Hans.Dns.Packet (
DNSPacket(..)
, DNSHeader(..)
, OpCode(..)
, RespCode(..)
, Query(..)
, QClass(..)
, QType(..)
, RR(..)
, Type(..)
, Class(..)
, RData(..)
, Name
, getDNSPacket
, putDNSPacket
) where
import Hans.IP4.Packet (IP4,getIP4,putIP4)
import Control.Monad
import Data.Bits
import qualified Data.ByteString as S
import qualified Data.Map.Strict as Map
import qualified Data.Serialize.Get as C
import qualified Data.Foldable as F
import Data.Int
import Data.Serialize ( Putter, runPut, putWord8, putWord16be, putWord32be
, putByteString )
import Data.Word
import MonadLib ( lift, StateT, runStateT, get, set )
import Numeric ( showHex )
-- DNS Packets -----------------------------------------------------------------
data DNSPacket = DNSPacket { dnsHeader :: DNSHeader
, dnsQuestions :: [Query]
, dnsAnswers :: [RR]
, dnsAuthorityRecords :: [RR]
, dnsAdditionalRecords :: [RR]
} deriving (Show)
data DNSHeader = DNSHeader { dnsId :: !Word16
, dnsQuery :: Bool
, dnsOpCode :: OpCode
, dnsAA :: Bool
, dnsTC :: Bool
, dnsRD :: Bool
, dnsRA :: Bool
, dnsRC :: RespCode
} deriving (Show)
data OpCode = OpQuery
| OpIQuery
| OpStatus
| OpReserved !Word16
deriving (Show)
data RespCode = RespNoError
| RespFormatError
| RespServerFailure
| RespNameError
| RespNotImplemented
| RespRefused
| RespReserved !Word16
deriving (Eq,Show)
type Name = [S.ByteString]
data Query = Query { qName :: Name
, qType :: QType
, qClass :: QClass
} deriving (Show)
data RR = RR { rrName :: Name
, rrClass :: Class
, rrTTL :: !Int32
, rrRData :: RData
} deriving (Show)
data QType = QType Type
| AFXR
| MAILB
| MAILA
| QTAny
deriving (Show)
data Type = A
| NS
| MD
| MF
| CNAME
| SOA
| MB
| MG
| MR
| NULL
| PTR
| HINFO
| MINFO
| MX
| AAAA
deriving (Show)
data QClass = QClass Class
| QAnyClass
deriving (Show)
data Class = IN | CS | CH | HS
deriving (Show,Eq)
data RData = RDA IP4
| RDNS Name
| RDMD Name
| RDMF Name
| RDCNAME Name
| RDSOA Name Name !Word32 !Int32 !Int32 !Int32 !Word32
| RDMB Name
| RDMG Name
| RDMR Name
| RDPTR Name
| RDHINFO S.ByteString S.ByteString
| RDMINFO Name Name
| RDMX !Word16 Name
| RDNULL S.ByteString
| RDUnknown Type S.ByteString
deriving (Show)
-- Cereal With Label Compression -----------------------------------------------
data RW = RW { rwOffset :: !Int
, rwLabels :: Map.Map Int Name
} deriving (Show)
type Get = StateT RW C.Get
{-# INLINE unGet #-}
unGet :: Get a -> C.Get a
unGet m =
do (a,_) <- runStateT RW { rwOffset = 0, rwLabels = Map.empty } m
return a
getOffset :: Get Int
getOffset = rwOffset `fmap` get
addOffset :: Int -> Get ()
addOffset off =
do rw <- get
set $! rw { rwOffset = rwOffset rw + off }
lookupPtr :: Int -> Get Name
lookupPtr off =
do rw <- get
when (off >= rwOffset rw) (fail "Invalid offset in pointer")
case Map.lookup off (rwLabels rw) of
Just ls -> return ls
Nothing -> fail $ "Unknown label for offset: " ++ showHex off "\n"
++ show (rwLabels rw)
data Label = Label Int S.ByteString
| Ptr Int Name
deriving (Show)
labelsToName :: [Label] -> Name
labelsToName = F.foldMap toName
where
toName (Label _ l) = [l]
toName (Ptr _ n) = n
addLabels :: [Label] -> Get ()
addLabels labels =
do rw <- get
set $! rw { rwLabels = Map.fromList newLabels `Map.union` rwLabels rw }
where
newLabels = go labels (labelsToName labels)
go (Label off _ : rest) name@(_ : ns) = (off,name) : go rest ns
go (Ptr off _ : _) name = [(off,name)]
go _ _ = []
{-# INLINE liftGet #-}
liftGet :: Int -> C.Get a -> Get a
liftGet n m = do addOffset n
lift m
{-# INLINE getWord8 #-}
getWord8 :: Get Word8
getWord8 = liftGet 1 C.getWord8
{-# INLINE getWord16be #-}
getWord16be :: Get Word16
getWord16be = liftGet 2 C.getWord16be
{-# INLINE getWord32be #-}
getWord32be :: Get Word32
getWord32be = liftGet 4 C.getWord32be
{-# INLINE getInt32be #-}
getInt32be :: Get Int32
getInt32be = fromIntegral `fmap` liftGet 4 C.getWord32be
{-# INLINE getBytes #-}
getBytes :: Int -> Get S.ByteString
getBytes n = liftGet n (C.getBytes n)
isolate :: Int -> Get a -> Get a
isolate n body =
do off <- get
(a,off') <- lift (C.isolate n (runStateT off body))
set off'
return a
label :: String -> Get a -> Get a
label str m =
do off <- get
(a,off') <- lift (C.label str (runStateT off m))
set off'
return a
{-# INLINE putInt32be #-}
putInt32be :: Putter Int32
putInt32be i = putWord32be (fromIntegral i)
-- Parsing ---------------------------------------------------------------------
getDNSPacket :: C.Get DNSPacket
getDNSPacket = unGet $ label "DNSPacket" $
do dnsHeader <- getDNSHeader
qdCount <- getWord16be
anCount <- getWord16be
nsCount <- getWord16be
arCount <- getWord16be
let blockOf c l m = label l (replicateM (fromIntegral c) m)
dnsQuestions <- blockOf qdCount "Questions" getQuery
dnsAnswers <- blockOf anCount "Answers" getRR
dnsAuthorityRecords <- blockOf nsCount "Authority Records" getRR
dnsAdditionalRecords <- blockOf arCount "Additional Records" getRR
return DNSPacket { .. }
-- 1 1 1 1 1 1
-- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | ID |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- |QR| Opcode |AA|TC|RD|RA| Z | RCODE |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | QDCOUNT |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | ANCOUNT |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | NSCOUNT |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | ARCOUNT |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
getDNSHeader :: Get DNSHeader
getDNSHeader = label "DNS Header" $
do dnsId <- getWord16be
flags <- getWord16be
let dnsQuery = not (flags `testBit` 15)
dnsOpCode = parseOpCode (flags `shiftR` 11)
dnsAA = flags `testBit` 10
dnsTC = flags `testBit` 9
dnsRD = flags `testBit` 8
dnsRA = flags `testBit` 7
dnsZ = (flags `shiftR` 4) .&. 0x7
dnsRC = parseRespCode (flags .&. 0xf)
unless (dnsZ == 0) (fail ("Z not zero"))
return DNSHeader { .. }
parseOpCode :: Word16 -> OpCode
parseOpCode 0 = OpQuery
parseOpCode 1 = OpIQuery
parseOpCode 2 = OpStatus
parseOpCode c = OpReserved (c .&. 0xf)
parseRespCode :: Word16 -> RespCode
parseRespCode 0 = RespNoError
parseRespCode 1 = RespFormatError
parseRespCode 2 = RespServerFailure
parseRespCode 3 = RespNameError
parseRespCode 4 = RespNotImplemented
parseRespCode 5 = RespRefused
parseRespCode c = RespReserved (c .&. 0xf)
getQuery :: Get Query
getQuery = label "Question" $
do qName <- getName
qType <- label "QTYPE" getQType
qClass <- label "QCLASS" getQClass
return Query { .. }
-- 1 1 1 1 1 1
-- 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | |
-- / /
-- / NAME /
-- | |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | TYPE |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | CLASS |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | TTL |
-- | |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
-- | RDLENGTH |
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
-- / RDATA /
-- / /
-- +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
getRR :: Get RR
getRR = label "RR" $
do rrName <- getName
ty <- getType
rrClass <- getClass
rrTTL <- getInt32be
rrRData <- getRData ty
return RR { .. }
getType :: Get Type
getType =
do qt <- getQType
case qt of
QType ty -> return ty
_ -> fail ("Invalid TYPE: " ++ show qt)
getQType :: Get QType
getQType =
do tag <- getWord16be
case tag of
1 -> return (QType A)
2 -> return (QType NS)
3 -> return (QType MD)
4 -> return (QType MF)
5 -> return (QType CNAME)
6 -> return (QType SOA)
7 -> return (QType MB)
8 -> return (QType MG)
9 -> return (QType MR)
10 -> return (QType NULL)
12 -> return (QType PTR)
13 -> return (QType HINFO)
14 -> return (QType MINFO)
15 -> return (QType MX)
28 -> return (QType AAAA)
252 -> return AFXR
253 -> return MAILB
254 -> return MAILA
255 -> return QTAny
_ -> fail ("Invalid TYPE: " ++ show tag)
getQClass :: Get QClass
getQClass =
do tag <- getWord16be
case tag of
1 -> return (QClass IN)
2 -> return (QClass CS)
3 -> return (QClass CH)
4 -> return (QClass HS)
255 -> return QAnyClass
_ -> fail ("Invalid CLASS: " ++ show tag)
getName :: Get Name
getName =
do labels <- go
addLabels labels
return (labelsToName labels)
where
go = do off <- getOffset
len <- getWord8
if | len .&. 0xc0 == 0xc0 ->
do l <- getWord8
let ptr = fromIntegral ((0x3f .&. len) `shiftL` 8)
+ fromIntegral l
ns <- lookupPtr ptr
return [Ptr off ns]
| len == 0 ->
return []
| otherwise ->
do l <- getBytes (fromIntegral len)
ls <- go
return (Label off l:ls)
getClass :: Get Class
getClass = label "CLASS" $
do qc <- getQClass
case qc of
QClass c -> return c
QAnyClass -> fail "Invalid CLASS"
getRData :: Type -> Get RData
getRData ty = label (show ty) $
do len <- getWord16be
isolate (fromIntegral len) $ case ty of
A -> RDA `fmap` liftGet 4 getIP4
NS -> RDNS `fmap` getName
MD -> RDMD `fmap` getName
MF -> RDMF `fmap` getName
CNAME -> RDCNAME `fmap` getName
SOA -> do mname <- getName
rname <- getName
serial <- getWord32be
refresh <- getInt32be
retry <- getInt32be
expire <- getInt32be
minTTL <- getWord32be
return (RDSOA mname rname serial refresh retry expire minTTL)
MB -> RDMB `fmap` getName
MG -> RDMG `fmap` getName
MR -> RDMR `fmap` getName
NULL -> RDNULL `fmap` (getBytes =<< lift C.remaining)
PTR -> RDPTR `fmap` getName
HINFO -> do cpuLen <- getWord8
cpu <- getBytes (fromIntegral cpuLen)
osLen <- getWord8
os <- getBytes (fromIntegral osLen)
return (RDHINFO cpu os)
MINFO -> do rmailBx <- getName
emailBx <- getName
return (RDMINFO rmailBx emailBx)
MX -> do pref <- getWord16be
ex <- getName
return (RDMX pref ex)
_ -> RDUnknown ty `fmap` (getBytes =<< lift C.remaining)
-- Rendering -------------------------------------------------------------------
putDNSPacket :: Putter DNSPacket
putDNSPacket DNSPacket{ .. } =
do putDNSHeader dnsHeader
putWord16be (fromIntegral (length dnsQuestions))
putWord16be (fromIntegral (length dnsAnswers))
putWord16be (fromIntegral (length dnsAuthorityRecords))
putWord16be (fromIntegral (length dnsAdditionalRecords))
F.traverse_ putQuery dnsQuestions
F.traverse_ putRR dnsAnswers
F.traverse_ putRR dnsAuthorityRecords
F.traverse_ putRR dnsAdditionalRecords
putDNSHeader :: Putter DNSHeader
putDNSHeader DNSHeader { .. } =
do putWord16be dnsId
let flag i b w | b = setBit w i
| otherwise = clearBit w i
flags = flag 15 (not dnsQuery)
$ flag 10 dnsAA
$ flag 9 dnsTC
$ flag 8 dnsRD
$ flag 7 dnsRA
$ flag 4 False -- dnsZ
$ (renderOpCode dnsOpCode `shiftL` 11) .|. renderRespCode dnsRC
putWord16be flags
renderOpCode :: OpCode -> Word16
renderOpCode OpQuery = 0
renderOpCode OpIQuery = 1
renderOpCode OpStatus = 2
renderOpCode (OpReserved c) = c .&. 0xf
renderRespCode :: RespCode -> Word16
renderRespCode RespNoError = 0
renderRespCode RespFormatError = 1
renderRespCode RespServerFailure = 2
renderRespCode RespNameError = 3
renderRespCode RespNotImplemented = 4
renderRespCode RespRefused = 5
renderRespCode (RespReserved c) = c .&. 0xf
putName :: Putter Name
putName = go
where
go (l:ls)
| S.null l = putWord8 0
| S.length l > 63 = error "Label too big"
| otherwise = do putWord8 (fromIntegral len)
putByteString l
go ls
where
len = S.length l
go [] = putWord8 0
putQuery :: Putter Query
putQuery Query { .. } =
do putName qName
putQType qType
putQClass qClass
putType :: Putter Type
putType A = putWord16be 1
putType NS = putWord16be 2
putType MD = putWord16be 3
putType MF = putWord16be 4
putType CNAME = putWord16be 5
putType SOA = putWord16be 6
putType MB = putWord16be 7
putType MG = putWord16be 8
putType MR = putWord16be 9
putType NULL = putWord16be 10
putType PTR = putWord16be 12
putType HINFO = putWord16be 13
putType MINFO = putWord16be 14
putType MX = putWord16be 15
putType AAAA = putWord16be 28
putQType :: Putter QType
putQType (QType ty) = putType ty
putQType AFXR = putWord16be 252
putQType MAILB = putWord16be 253
putQType MAILA = putWord16be 254
putQType QTAny = putWord16be 255
putQClass :: Putter QClass
putQClass (QClass c) = putClass c
putQClass QAnyClass = putWord16be 255
putRR :: Putter RR
putRR RR { .. } =
do putName rrName
let (ty,rdata) = putRData rrRData
putType ty
putClass rrClass
putWord32be (fromIntegral rrTTL)
putWord16be (fromIntegral (S.length rdata))
putByteString rdata
putClass :: Putter Class
putClass IN = putWord16be 1
putClass CS = putWord16be 2
putClass CH = putWord16be 3
putClass HS = putWord16be 4
putRData :: RData -> (Type,S.ByteString)
putRData rd = case rd of
RDA addr -> rdata A (putIP4 addr)
RDNS name -> rdata NS (putName name)
RDMD name -> rdata MD (putName name)
RDMF name -> rdata MF (putName name)
RDCNAME name -> rdata CNAME (putName name)
RDSOA m r s f t ex ttl ->
rdata SOA $ do putName m
putName r
putWord32be s
putInt32be f
putInt32be t
putInt32be ex
putWord32be ttl
RDMB name -> rdata MB (putName name)
RDMG name -> rdata MG (putName name)
RDMR name -> rdata MR (putName name)
RDNULL bytes -> rdata NULL $ do putWord8 (fromIntegral (S.length bytes))
putByteString bytes
RDPTR name -> rdata PTR (putName name)
RDHINFO cpu os -> rdata HINFO $ do putWord8 (fromIntegral (S.length cpu))
putByteString cpu
putWord8 (fromIntegral (S.length os))
putByteString os
RDMINFO rm em -> rdata MINFO $ do putName rm
putName em
RDMX pref ex -> rdata MX $ do putWord16be pref
putName ex
RDUnknown ty bytes -> (ty,bytes)
where
rdata tag m = (tag,runPut m)
| GaloisInc/HaNS | src/Hans/Dns/Packet.hs | bsd-3-clause | 18,069 | 0 | 21 | 6,944 | 4,997 | 2,504 | 2,493 | 482 | 20 |
module PCP.Patch where
import PCP.Type
import PCP.Form
import PCP.Examples
import Autolib.Util.Wort
import Control.Monad
-- | rectangular area (no wrap-around)
type Patch c = ([c], [Int] ,[c])
patches :: PCP Char
-> Int -- ^ depth (max)
-> Int -- ^ width (max, at start and end)
-> [ Patch Char ]
patches pcp d w = do
start <- alles "01" w
p @ (u, xs, v) <- patches_from pcp d start
guard $ length v <= w
return p
patches_from :: Eq c
=> PCP c
-> Int
-> [c]
-> [ Patch c ]
patches_from pcp depth w = do
(stack, top) <- pf pcp depth [] w [] w
return (w, stack, top)
pf pcp d stack w done [] =
do
guard $ done /= w
return (stack, done)
++ do
guard $ d > 0
pf pcp (pred d) stack w [] done
pf pcp d stack w done ahead = do
(i, (l, r)) <- zip [0..] pcp
let (pre, post) = splitAt (length r) ahead
guard $ pre == r
pf pcp d (i : stack) w (done ++ l) post
| Erdwolf/autotool-bonn | src/PCP/Patch.hs | gpl-2.0 | 980 | 35 | 10 | 320 | 436 | 239 | 197 | 36 | 1 |
import System.Process.Extra
main = system_ "bake-test"
| capital-match/bake | travis.hs | bsd-3-clause | 57 | 0 | 5 | 8 | 15 | 8 | 7 | 2 | 1 |
module EnvSpec (main, spec) where
import TestUtil
import Network.MPD
import System.Posix.Env hiding (getEnvDefault)
main :: IO ()
main = hspec spec
spec :: Spec
spec = do
describe "getEnvDefault" $ do
it "returns the value of an environment variable" $ do
setEnv "FOO" "foo" True
r <- getEnvDefault "FOO" "bar"
r `shouldBe` "foo"
it "returns a given default value if that environment variable is not set" $ do
unsetEnv "FOO"
r <- getEnvDefault "FOO" "bar"
r `shouldBe` "bar"
describe "getConnectionSettings" $ do
it "takes an optional argument, that overrides MPD_HOST" $ do
setEnv "MPD_HOST" "[email protected]" True
Right (host, _, pw) <- getConnectionSettings (Just "foo@bar") Nothing
pw `shouldBe` "foo"
host `shouldBe` "bar"
it "takes an optional argument, that overrides MPD_PORT" $ do
setEnv "MPD_PORT" "8080" True
Right (_, port, _) <- getConnectionSettings Nothing (Just "23")
port `shouldBe` 23
it "returns an error message, if MPD_PORT is not an int" $ do
setEnv "MPD_PORT" "foo" True
r <- getConnectionSettings Nothing Nothing
r `shouldBe` Left "\"foo\" is not a valid port!"
unsetEnv "MPD_PORT"
describe "host" $ do
it "is taken from MPD_HOST" $ do
setEnv "MPD_HOST" "example.com" True
Right (host, _, _) <- getConnectionSettings Nothing Nothing
host `shouldBe` "example.com"
it "is 'localhost' if MPD_HOST is not set" $ do
unsetEnv "MPD_HOST"
Right (host, _, _) <- getConnectionSettings Nothing Nothing
host `shouldBe` "localhost"
describe "port" $ do
it "is taken from MPD_PORT" $ do
setEnv "MPD_PORT" "8080" True
Right (_, port, _) <- getConnectionSettings Nothing Nothing
port `shouldBe` 8080
it "is 6600 if MPD_PORT is not set" $ do
unsetEnv "MPD_PORT"
Right (_, port, _) <- getConnectionSettings Nothing Nothing
port `shouldBe` 6600
describe "password" $ do
it "is taken from MPD_HOST if MPD_HOST is of the form password@host" $ do
setEnv "MPD_HOST" "password@host" True
Right (host, _, pw) <- getConnectionSettings Nothing Nothing
host `shouldBe` "host"
pw `shouldBe` "password"
it "is '' if MPD_HOST is not of the form password@host" $ do
setEnv "MPD_HOST" "example.com" True
Right (_, _, pw) <- getConnectionSettings Nothing Nothing
pw `shouldBe` ""
it "is '' if MPD_HOST is not set" $ do
unsetEnv "MPD_HOST"
Right (_, _, pw) <- getConnectionSettings Nothing Nothing
pw `shouldBe` ""
| beni55/libmpd-haskell | tests/EnvSpec.hs | mit | 2,706 | 0 | 18 | 756 | 733 | 346 | 387 | 64 | 1 |
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd">
<helpset version="2.0" xml:lang="hr-HR">
<title>Core Language Files | ZAP Extension</title>
<maps>
<homeID>top</homeID>
<mapref location="map.jhm"/>
</maps>
<view>
<name>TOC</name>
<label>Contents</label>
<type>org.zaproxy.zap.extension.help.ZapTocView</type>
<data>toc.xml</data>
</view>
<view>
<name>Index</name>
<label>Index</label>
<type>javax.help.IndexView</type>
<data>index.xml</data>
</view>
<view>
<name>Search</name>
<label>Search</label>
<type>javax.help.SearchView</type>
<data engine="com.sun.java.help.search.DefaultSearchEngine">
JavaHelpSearch
</data>
</view>
<view>
<name>Favorites</name>
<label>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | kingthorin/zap-extensions | addOns/coreLang/src/main/javahelp/org/zaproxy/zap/extension/coreLang/resources/help_hr_HR/helpset_hr_HR.hs | apache-2.0 | 980 | 78 | 66 | 160 | 415 | 210 | 205 | -1 | -1 |
{-# LANGUAGE TupleSections #-}
import CoreSyn
import CoreUtils
import Id
import Type
import MkCore
import CallArity (callArityRHS)
import MkId
import SysTools
import DynFlags
import ErrUtils
import Outputable
import TysWiredIn
import Literal
import GHC
import Control.Monad
import Control.Monad.IO.Class
import System.Environment( getArgs )
import VarSet
import PprCore
import Unique
import CoreLint
import FastString
-- Build IDs. use mkTemplateLocal, more predictable than proper uniques
go, go2, x, d, n, y, z, scrut :: Id
[go, go2, x,d, n, y, z, scrut, f] = mkTestIds
(words "go go2 x d n y z scrut f")
[ mkFunTys [intTy, intTy] intTy
, mkFunTys [intTy, intTy] intTy
, intTy
, mkFunTys [intTy] intTy
, mkFunTys [intTy] intTy
, intTy
, intTy
, boolTy
, mkFunTys [intTy, intTy] intTy -- protoypical external function
]
exprs :: [(String, CoreExpr)]
exprs =
[ ("go2",) $
mkRFun go [x]
(mkLet d (mkACase (Var go `mkVarApps` [x])
(mkLams [y] $ Var y)
) $ mkLams [z] $ Var d `mkVarApps` [x]) $
go `mkLApps` [0, 0]
, ("nested_go2",) $
mkRFun go [x]
(mkLet n (mkACase (Var go `mkVarApps` [x])
(mkLams [y] $ Var y)) $
mkACase (Var n) $
mkFun go2 [y]
(mkLet d
(mkACase (Var go `mkVarApps` [x])
(mkLams [y] $ Var y) ) $
mkLams [z] $ Var d `mkVarApps` [x] )$
Var go2 `mkApps` [mkLit 1] ) $
go `mkLApps` [0, 0]
, ("d0 (go 2 would be bad)",) $
mkRFun go [x]
(mkLet d (mkACase (Var go `mkVarApps` [x])
(mkLams [y] $ Var y)
) $
mkLams [z] $ Var f `mkApps` [ Var d `mkVarApps` [x], Var d `mkVarApps` [x] ]) $
go `mkLApps` [0, 0]
, ("go2 (in case crut)",) $
mkRFun go [x]
(mkLet d (mkACase (Var go `mkVarApps` [x])
(mkLams [y] $ Var y)
) $ mkLams [z] $ Var d `mkVarApps` [x]) $
Case (go `mkLApps` [0, 0]) z intTy
[(DEFAULT, [], Var f `mkVarApps` [z,z])]
, ("go2 (in function call)",) $
mkRFun go [x]
(mkLet d (mkACase (Var go `mkVarApps` [x])
(mkLams [y] $ Var y)
) $ mkLams [z] $ Var d `mkVarApps` [x]) $
f `mkLApps` [0] `mkApps` [go `mkLApps` [0, 0]]
, ("go2 (using surrounding interesting let)",) $
mkLet n (f `mkLApps` [0]) $
mkRFun go [x]
(mkLet d (mkACase (Var go `mkVarApps` [x])
(mkLams [y] $ Var y)
) $ mkLams [z] $ Var d `mkVarApps` [x]) $
Var f `mkApps` [n `mkLApps` [0], go `mkLApps` [0, 0]]
, ("go2 (using surrounding boring let)",) $
mkLet z (mkLit 0) $
mkRFun go [x]
(mkLet d (mkACase (Var go `mkVarApps` [x])
(mkLams [y] $ Var y)
) $ mkLams [z] $ Var d `mkVarApps` [x]) $
Var f `mkApps` [Var z, go `mkLApps` [0, 0]]
, ("two calls, one from let and from body (d 1 would be bad)",) $
mkLet d (mkACase (mkLams [y] $ mkLit 0) (mkLams [y] $ mkLit 0)) $
mkFun go [x,y] (mkVarApps (Var d) [x]) $
mkApps (Var d) [mkLApps go [1,2]]
, ("a thunk in a recursion (d 1 would be bad)",) $
mkRLet n (mkACase (mkLams [y] $ mkLit 0) (Var n)) $
mkRLet d (mkACase (mkLams [y] $ mkLit 0) (Var d)) $
Var n `mkApps` [d `mkLApps` [0]]
, ("two thunks, one called multiple times (both arity 1 would be bad!)",) $
mkLet n (mkACase (mkLams [y] $ mkLit 0) (f `mkLApps` [0])) $
mkLet d (mkACase (mkLams [y] $ mkLit 0) (f `mkLApps` [0])) $
Var n `mkApps` [Var d `mkApps` [Var d `mkApps` [mkLit 0]]]
, ("two functions, not thunks",) $
mkLet go (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var f `mkVarApps` [x]))) $
mkLet go2 (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var f `mkVarApps` [x]))) $
Var go `mkApps` [go2 `mkLApps` [0,1], mkLit 0]
, ("a thunk, called multiple times via a forking recursion (d 1 would be bad!)",) $
mkLet d (mkACase (mkLams [y] $ mkLit 0) (f `mkLApps` [0])) $
mkRLet go2 (mkLams [x] (mkACase (Var go2 `mkApps` [Var go2 `mkApps` [mkLit 0, mkLit 0]]) (Var d))) $
go2 `mkLApps` [0,1]
, ("a function, one called multiple times via a forking recursion",) $
mkLet go (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var f `mkVarApps` [x]))) $
mkRLet go2 (mkLams [x] (mkACase (Var go2 `mkApps` [Var go2 `mkApps` [mkLit 0, mkLit 0]]) (go `mkLApps` [0]))) $
go2 `mkLApps` [0,1]
, ("two functions (recursive)",) $
mkRLet go (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go `mkVarApps` [x]))) $
mkRLet go2 (mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go2 `mkVarApps` [x]))) $
Var go `mkApps` [go2 `mkLApps` [0,1], mkLit 0]
, ("mutual recursion (thunks), called mutiple times (both arity 1 would be bad!)",) $
Let (Rec [ (n, mkACase (mkLams [y] $ mkLit 0) (Var d))
, (d, mkACase (mkLams [y] $ mkLit 0) (Var n))]) $
Var n `mkApps` [Var d `mkApps` [Var d `mkApps` [mkLit 0]]]
, ("mutual recursion (functions), but no thunks",) $
Let (Rec [ (go, mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go2 `mkVarApps` [x])))
, (go2, mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go `mkVarApps` [x])))]) $
Var go `mkApps` [go2 `mkLApps` [0,1], mkLit 0]
, ("mutual recursion (functions), one boring (d 1 would be bad)",) $
mkLet d (f `mkLApps` [0]) $
Let (Rec [ (go, mkLams [x, y] (Var d `mkApps` [go2 `mkLApps` [1,2]]))
, (go2, mkLams [x] (mkACase (mkLams [y] $ mkLit 0) (Var go `mkVarApps` [x])))]) $
Var d `mkApps` [go2 `mkLApps` [0,1]]
, ("a thunk (non-function-type), called twice, still calls once",) $
mkLet d (f `mkLApps` [0]) $
mkLet x (d `mkLApps` [1]) $
Var f `mkVarApps` [x, x]
, ("a thunk (function type), called multiple times, still calls once",) $
mkLet d (f `mkLApps` [0]) $
mkLet n (Var f `mkApps` [d `mkLApps` [1]]) $
mkLams [x] $ Var n `mkVarApps` [x]
, ("a thunk (non-function-type), in mutual recursion, still calls once (d 1 would be good)",) $
mkLet d (f `mkLApps` [0]) $
Let (Rec [ (x, Var d `mkApps` [go `mkLApps` [1,2]])
, (go, mkLams [x] $ mkACase (mkLams [z] $ Var x) (Var go `mkVarApps` [x]) ) ]) $
Var go `mkApps` [mkLit 0, go `mkLApps` [0,1]]
, ("a thunk (function type), in mutual recursion, still calls once (d 1 would be good)",) $
mkLet d (f `mkLApps` [0]) $
Let (Rec [ (n, Var go `mkApps` [d `mkLApps` [1]])
, (go, mkLams [x] $ mkACase (Var n) (Var go `mkApps` [Var n `mkVarApps` [x]]) ) ]) $
Var go `mkApps` [mkLit 0, go `mkLApps` [0,1]]
, ("a thunk (non-function-type) co-calls with the body (d 1 would be bad)",) $
mkLet d (f `mkLApps` [0]) $
mkLet x (d `mkLApps` [1]) $
Var d `mkVarApps` [x]
]
main = do
[libdir] <- getArgs
runGhc (Just libdir) $ do
getSessionDynFlags >>= setSessionDynFlags . flip gopt_set Opt_SuppressUniques
dflags <- getSessionDynFlags
liftIO $ forM_ exprs $ \(n,e) -> do
case lintExpr [f,scrut] e of
Just msg -> putMsg dflags (msg $$ text "in" <+> text n)
Nothing -> return ()
putMsg dflags (text n <> char ':')
-- liftIO $ putMsg dflags (ppr e)
let e' = callArityRHS e
let bndrs = varSetElems (allBoundIds e')
-- liftIO $ putMsg dflags (ppr e')
forM_ bndrs $ \v -> putMsg dflags $ nest 4 $ ppr v <+> ppr (idCallArity v)
-- Utilities
mkLApps :: Id -> [Integer] -> CoreExpr
mkLApps v = mkApps (Var v) . map mkLit
mkACase = mkIfThenElse (Var scrut)
mkTestId :: Int -> String -> Type -> Id
mkTestId i s ty = mkSysLocal (mkFastString s) (mkBuiltinUnique i) ty
mkTestIds :: [String] -> [Type] -> [Id]
mkTestIds ns tys = zipWith3 mkTestId [0..] ns tys
mkLet :: Id -> CoreExpr -> CoreExpr -> CoreExpr
mkLet v rhs body = Let (NonRec v rhs) body
mkRLet :: Id -> CoreExpr -> CoreExpr -> CoreExpr
mkRLet v rhs body = Let (Rec [(v, rhs)]) body
mkFun :: Id -> [Id] -> CoreExpr -> CoreExpr -> CoreExpr
mkFun v xs rhs body = mkLet v (mkLams xs rhs) body
mkRFun :: Id -> [Id] -> CoreExpr -> CoreExpr -> CoreExpr
mkRFun v xs rhs body = mkRLet v (mkLams xs rhs) body
mkLit :: Integer -> CoreExpr
mkLit i = Lit (mkLitInteger i intTy)
-- Collects all let-bound IDs
allBoundIds :: CoreExpr -> VarSet
allBoundIds (Let (NonRec v rhs) body) = allBoundIds rhs `unionVarSet` allBoundIds body `extendVarSet` v
allBoundIds (Let (Rec binds) body) =
allBoundIds body `unionVarSet` unionVarSets
[ allBoundIds rhs `extendVarSet` v | (v, rhs) <- binds ]
allBoundIds (App e1 e2) = allBoundIds e1 `unionVarSet` allBoundIds e2
allBoundIds (Case scrut _ _ alts) =
allBoundIds scrut `unionVarSet` unionVarSets
[ allBoundIds e | (_, _ , e) <- alts ]
allBoundIds (Lam _ e) = allBoundIds e
allBoundIds (Tick _ e) = allBoundIds e
allBoundIds (Cast e _) = allBoundIds e
allBoundIds _ = emptyVarSet
| green-haskell/ghc | testsuite/tests/callarity/unittest/CallArity1.hs | bsd-3-clause | 9,333 | 0 | 25 | 2,811 | 4,143 | 2,280 | 1,863 | 195 | 2 |
{-# LANGUAGE Trustworthy #-}
{-# LANGUAGE NoImplicitPrelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Concurrent
-- Copyright : (c) The University of Glasgow 2003
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : non-portable (requires concurrency)
--
-- FFI datatypes and operations that use or require concurrency (GHC only).
--
-----------------------------------------------------------------------------
module Foreign.Concurrent
(
-- * Concurrency-based 'ForeignPtr' operations
-- | These functions generalize their namesakes in the portable
-- "Foreign.ForeignPtr" module by allowing arbitrary 'IO' actions
-- as finalizers. These finalizers necessarily run in a separate
-- thread, cf. /Destructors, Finalizers and Synchronization/,
-- by Hans Boehm, /POPL/, 2003.
newForeignPtr,
addForeignPtrFinalizer,
) where
import GHC.IO ( IO )
import GHC.Ptr ( Ptr )
import GHC.ForeignPtr ( ForeignPtr )
import qualified GHC.ForeignPtr
newForeignPtr :: Ptr a -> IO () -> IO (ForeignPtr a)
--
-- ^Turns a plain memory reference into a foreign object by
-- associating a finalizer - given by the monadic operation - with the
-- reference. The storage manager will start the finalizer, in a
-- separate thread, some time after the last reference to the
-- @ForeignPtr@ is dropped. There is no guarantee of promptness, and
-- in fact there is no guarantee that the finalizer will eventually
-- run at all.
--
-- Note that references from a finalizer do not necessarily prevent
-- another object from being finalized. If A's finalizer refers to B
-- (perhaps using 'touchForeignPtr', then the only guarantee is that
-- B's finalizer will never be started before A's. If both A and B
-- are unreachable, then both finalizers will start together. See
-- 'touchForeignPtr' for more on finalizer ordering.
--
newForeignPtr = GHC.ForeignPtr.newConcForeignPtr
addForeignPtrFinalizer :: ForeignPtr a -> IO () -> IO ()
-- ^This function adds a finalizer to the given @ForeignPtr@. The
-- finalizer will run /before/ all other finalizers for the same
-- object which have already been registered.
--
-- This is a variant of @Foreign.ForeignPtr.addForeignPtrFinalizer@,
-- where the finalizer is an arbitrary @IO@ action. When it is
-- invoked, the finalizer will run in a new thread.
--
-- NB. Be very careful with these finalizers. One common trap is that
-- if a finalizer references another finalized value, it does not
-- prevent that value from being finalized. In particular, 'Handle's
-- are finalized objects, so a finalizer should not refer to a 'Handle'
-- (including @stdout@, @stdin@ or @stderr@).
--
addForeignPtrFinalizer = GHC.ForeignPtr.addForeignPtrConcFinalizer
| ezyang/ghc | libraries/base/Foreign/Concurrent.hs | bsd-3-clause | 2,940 | 0 | 9 | 536 | 174 | 119 | 55 | 14 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.Hpc
-- Copyright : Thomas Tuegel 2011
-- License : BSD3
--
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module provides functions for locating various HPC-related paths and
-- a function for adding the necessary options to a PackageDescription to
-- build test suites with HPC enabled.
module Distribution.Simple.Hpc
( Way(..), guessWay
, htmlDir
, mixDir
, tixDir
, tixFilePath
, markupPackage
, markupTest
) where
import Control.Monad ( when )
import Distribution.ModuleName ( main )
import Distribution.PackageDescription
( TestSuite(..)
, testModules
)
import Distribution.Simple.LocalBuildInfo ( LocalBuildInfo(..) )
import Distribution.Simple.Program
( hpcProgram
, requireProgramVersion
)
import Distribution.Simple.Program.Hpc ( markup, union )
import Distribution.Simple.Utils ( notice )
import Distribution.Version ( anyVersion )
import Distribution.Verbosity ( Verbosity() )
import System.Directory ( createDirectoryIfMissing, doesFileExist )
import System.FilePath
-- -------------------------------------------------------------------------
-- Haskell Program Coverage
data Way = Vanilla | Prof | Dyn
deriving (Bounded, Enum, Eq, Read, Show)
hpcDir :: FilePath -- ^ \"dist/\" prefix
-> Way
-> FilePath -- ^ Directory containing component's HPC .mix files
hpcDir distPref way = distPref </> "hpc" </> wayDir
where
wayDir = case way of
Vanilla -> "vanilla"
Prof -> "prof"
Dyn -> "dyn"
mixDir :: FilePath -- ^ \"dist/\" prefix
-> Way
-> FilePath -- ^ Component name
-> FilePath -- ^ Directory containing test suite's .mix files
mixDir distPref way name = hpcDir distPref way </> "mix" </> name
tixDir :: FilePath -- ^ \"dist/\" prefix
-> Way
-> FilePath -- ^ Component name
-> FilePath -- ^ Directory containing test suite's .tix files
tixDir distPref way name = hpcDir distPref way </> "tix" </> name
-- | Path to the .tix file containing a test suite's sum statistics.
tixFilePath :: FilePath -- ^ \"dist/\" prefix
-> Way
-> FilePath -- ^ Component name
-> FilePath -- ^ Path to test suite's .tix file
tixFilePath distPref way name = tixDir distPref way name </> name <.> "tix"
htmlDir :: FilePath -- ^ \"dist/\" prefix
-> Way
-> FilePath -- ^ Component name
-> FilePath -- ^ Path to test suite's HTML markup directory
htmlDir distPref way name = hpcDir distPref way </> "html" </> name
-- | Attempt to guess the way the test suites in this package were compiled
-- and linked with the library so the correct module interfaces are found.
guessWay :: LocalBuildInfo -> Way
guessWay lbi
| withProfExe lbi = Prof
| withDynExe lbi = Dyn
| otherwise = Vanilla
-- | Generate the HTML markup for a test suite.
markupTest :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^ \"dist/\" prefix
-> String -- ^ Library name
-> TestSuite
-> IO ()
markupTest verbosity lbi distPref libName suite = do
tixFileExists <- doesFileExist $ tixFilePath distPref way $ testName suite
when tixFileExists $ do
-- behaviour of 'markup' depends on version, so we need *a* version
-- but no particular one
(hpc, hpcVer, _) <- requireProgramVersion verbosity
hpcProgram anyVersion (withPrograms lbi)
let htmlDir_ = htmlDir distPref way $ testName suite
markup hpc hpcVer verbosity
(tixFilePath distPref way $ testName suite) mixDirs
htmlDir_
(testModules suite ++ [ main ])
notice verbosity $ "Test coverage report written to "
++ htmlDir_ </> "hpc_index" <.> "html"
where
way = guessWay lbi
mixDirs = map (mixDir distPref way) [ testName suite, libName ]
-- | Generate the HTML markup for all of a package's test suites.
markupPackage :: Verbosity
-> LocalBuildInfo
-> FilePath -- ^ \"dist/\" prefix
-> String -- ^ Library name
-> [TestSuite]
-> IO ()
markupPackage verbosity lbi distPref libName suites = do
let tixFiles = map (tixFilePath distPref way . testName) suites
tixFilesExist <- mapM doesFileExist tixFiles
when (and tixFilesExist) $ do
-- behaviour of 'markup' depends on version, so we need *a* version
-- but no particular one
(hpc, hpcVer, _) <- requireProgramVersion verbosity
hpcProgram anyVersion (withPrograms lbi)
let outFile = tixFilePath distPref way libName
htmlDir' = htmlDir distPref way libName
excluded = concatMap testModules suites ++ [ main ]
createDirectoryIfMissing True $ takeDirectory outFile
union hpc verbosity tixFiles outFile excluded
markup hpc hpcVer verbosity outFile mixDirs htmlDir' excluded
notice verbosity $ "Package coverage report written to "
++ htmlDir' </> "hpc_index.html"
where
way = guessWay lbi
mixDirs = map (mixDir distPref way) $ libName : map testName suites
| tolysz/prepare-ghcjs | spec-lts8/cabal/Cabal/Distribution/Simple/Hpc.hs | bsd-3-clause | 5,350 | 0 | 14 | 1,414 | 1,041 | 553 | 488 | 100 | 3 |
module Thread
( ThreadTree (..)
, ContM (..)
, atom
, stop
, buildThread
)
where
----------------------------------
data ThreadTree req rsp m =
Atom (m (ThreadTree req rsp m))
| Stop
----------------------------------
newtype ContM req rsp m a = ContM ((a-> ThreadTree req rsp m)-> ThreadTree req rsp m)
instance Functor (ContM req rsp m) where
fmap = undefined
instance Applicative (ContM req rsp m) where
pure = undefined
(<*>) = undefined
instance Monad m => Monad (ContM req rsp m) where
m >>= f = contmBind m f
return = contmReturn
contmBind :: (ContM req rsp m a) -> (a -> (ContM req rsp m b)) -> (ContM req rsp m b)
contmBind (ContM x) f =
ContM(\y-> x (\z-> let ContM f' = f z in f' y))
contmReturn :: a -> (ContM req rsp m a)
contmReturn x = ContM(\c -> c x)
{-- how to build primitive ContM blocks... --}
atom :: Monad m => (m a) -> (ContM req rsp m a)
atom mx = ContM( \c -> Atom( do x <- mx; return (c x) ))
stop :: (ContM req rsp m a)
stop = ContM( \c -> Stop )
buildThread :: (ContM req rsp m a) -> ThreadTree req rsp m
buildThread (ContM f) = f (\c->Stop)
----------------------------------
| ezyang/ghc | testsuite/tests/concurrent/prog002/Thread.hs | bsd-3-clause | 1,155 | 0 | 15 | 264 | 526 | 279 | 247 | 29 | 1 |
import qualified Graphics.UI.GLFW as GLFW
import Graphics.GL
import Data.Bits
import Control.Monad
import Linear
import SetupGLFW
import ShaderLoader
import Cube
-------------------------------------------------------------
-- A test to make sure our rendering works without the Oculus
-------------------------------------------------------------
main :: IO a
main = do
let (resX, resY) = (1920, 1080)
win <- setupGLFW "Cube" resX resY
-- Scene rendering setup
shader <- createShaderProgram "test/cube.v.glsl" "test/cube.f.glsl"
cube <- makeCube shader
glClearColor 0 0.1 0.1 1
glEnable GL_DEPTH_TEST
forever $
mainLoop win shader cube
mainLoop :: GLFW.Window -> GLProgram -> Cube -> IO ()
mainLoop win shader cube = do
-- glGetErrors
-- Get mouse/keyboard/OS events from GLFW
GLFW.pollEvents
-- Clear the framebuffer
glClear ( GL_COLOR_BUFFER_BIT .|. GL_DEPTH_BUFFER_BIT )
-- Normally we'd render something here beyond just clearing the screen to a color
glUseProgram (fromIntegral (unGLProgram shader))
let projection = perspective 45 (1920/1080) 0.01 1000
model = mkTransformation 1 (V3 0 0 (-4))
view = lookAt (V3 0 2 0) (V3 0 0 (-4)) (V3 0 1 0)
mvp = projection !*! view !*! model
(x,y,w,h) = (0,0,1920,1080)
glViewport x y w h
renderCube cube mvp
GLFW.swapBuffers win
| lukexi/oculus-mini | test/TestCube.hs | mit | 1,441 | 0 | 14 | 348 | 388 | 199 | 189 | 31 | 1 |
import Control.Monad.Trans.State.Lazy
tick :: State Int String
tick = return "foo"
tick2 :: State Int String
tick2 = do s <- tick
return $ s ++ "bar"
tick3 = do s <- tick
s2 <- tick2
s3 <- tick2
put 1600
return $ s3
type Stack = [Int]
pop :: State Stack Int
pop = do (x:xs) <- get
put xs
return x
push :: Int -> State Stack ()
push a = do xs <- get
put (a:xs)
return ()
stackManip = do push 3
push 3
push 3
i <- pop
push $ i*29
pop
| nlim/haskell-playground | src/Statements.hs | mit | 620 | 0 | 9 | 285 | 245 | 115 | 130 | 26 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
-- module
module Persistence (loadSession, saveSession) where
-- imports
import Control.Applicative
import Control.Monad.Error
import Control.Monad.State
import Data.Aeson as A
import Data.Aeson.Types as A
import qualified Data.ByteString.Base64.Lazy as B
import qualified Data.ByteString.Lazy as B
import System.Directory
import System.FilePath
import System.IO (hFlush, stdout)
import RCL
-- exported functions
loadSession :: (Functor m, MonadIO m) => FilePath -> String -> RTMT m ()
loadSession path app = do
file <- liftIO $ getFile path app
readFrom file `catchError` const createNew
where readFrom file = do
guard =<< liftIO (doesFileExist file)
guard =<< liftIO (readable <$> getPermissions file)
rsess <- liftIO (B.readFile file) >>= decodeSession
guard =<< testToken (token rsess)
put rsess
saveSession :: (Functor m, MonadIO m) => FilePath -> String -> RTMT m ()
saveSession path app = do
file <- liftIO $ getFile path app
sess <- encodeSession <$> session
liftIO $ B.writeFile file sess
-- internal functions
createNew :: (Functor m, MonadIO m) => RTMT m ()
createNew = do
authUrl <- getAuthURL
liftIO $ do
putStrLn "Couldn't find authentification token"
putStrLn $ "Please authorize RCL: " ++ authUrl
putStr "(Press enter when done.)"
hFlush stdout
void getLine
void updateToken
line <- call (method "rtm.timelines.create") >>= extractM (.: "timeline")
modify $ setTimeline line
getFile :: FilePath -> String -> IO FilePath
getFile path app = do
dirName <- getAppUserDataDirectory app
createDirectoryIfMissing True dirName
return $ dirName </> path
decodeSession :: MonadError Failure m => B.ByteString -> m Session
decodeSession = either (throwError . strMsg) return . (B.decode >=> A.eitherDecode >=> parseJ)
encodeSession :: Session -> B.ByteString
encodeSession = B.encode . A.encode . toJ
parseJ :: Value -> Either String Session
parseJ = parseEither $ withObject "session object" $ \o -> do
tk <- o .: "token"
tl <- o .: "timeline"
return $ Session tl tk ""
toJ :: Session -> Value
toJ s = object [
"timeline" .= timeline s,
"token" .= token s
]
| nicuveo/RCL | src/Persistence.hs | mit | 2,461 | 0 | 14 | 617 | 725 | 365 | 360 | 60 | 1 |
data Way = U | R | D | L deriving(Eq, Show)
data Op = Op { opPiece :: Int
, opCost :: Int
, opWay :: [Way] } deriving(Eq, Show)
type Field = [Int]
swapCost = 1
choiceCost = 10
fieldWidth = 4
fieldHeight = 4
maxChoice = 3
magicNum = 0
goal = [0..24] :: [Int]
fie = 1:2:0:[3..24] :: [Int]
solver :: Field -> Field -> Int -> Int -> Way -> Maybe [Op]
solver goalField field count piece way
| goalField == field = Just [(Op (-1) 0 [])] -- 終端
| count > 5 = Nothing
| piece' == Nothing = Nothing
| (jw' - jw) < magicNum = Nothing
| best == Nothing = Nothing
| (length opx) + 1 > maxChoice = Nothing
| opPiece(op) == pieceVal = Just ( (Op piece (opCost(op) + swapCost) (way:opWay(op))) : opx )
| otherwise = Just ( (Op piece (choiceCost + swapCost) [way]) : (op : opx))
where
(Just (op:opx)) = best
best = bestOp $ (choice goalField field' (count + 1)) : (map (solver goalField field' (count + 1) pieceVal) (genWay way))
field' = swapByIndex piece pieceVal field
piece' = afterIndex piece way
(Just pieceVal) = piece'
jw = jwDist goalField field
jw' = jwDist goalField field'
choice :: Field -> Field -> Int -> Maybe [Op]
choice goalField field count = bestOp $ mapNeo (map (solver goalField field count) (wrongList goalField field 0))
genWay :: Way -> [Way]
genWay U = [U,R,L]
genWay R = [U,R,D]
genWay D = [R,D,L]
genWay L = [U,D,L]
{-
tapleList :: a -> [b] -> [(a,b)] -> [(a,b)]
tapleList _ [] list = list
tapleList y x:xs list = (y,x) : tapleList y xs list
-}
mapNeo :: [(Way -> Maybe [Op])] -> [Maybe [Op]]
mapNeo [] = []
mapNeo (f:fs) = (f U) : (f R) : (f D) : (f L) : (mapNeo fs)
bestOp :: [Maybe [Op]] -> Maybe [Op]
bestOp [] = Nothing
bestOp [x] = x
bestOp (x:xs)
| x == Nothing = bestOp xs
| (opCostTotal op) == 0 = x
| otherwise = rase minOp x (bestOp xs)
where
(Just op) = x
minOp :: [Op] -> [Op] -> [Op]
minOp xs ys
| xsCost < ysCost = xs
| otherwise = ys
where xsCost = sum $ map opCost xs
ysCost = sum $ map opCost ys
opCostTotal :: [Op] -> Int
opCostTotal ops = sum $ map opCost ops
rase :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a
rase f (Just a) (Just b) = Just (f a b)
rase _ (Just a) Nothing = Just a
rase _ Nothing (Just b) = Just b
rase _ Nothing Nothing = Nothing
swap :: Int -> Way -> Field -> Maybe Field
swap piece way field = case (afterIndex piece way) of
(Just piece') -> Just $ swapByIndex piece piece' field
(Nothing) -> Nothing
afterIndex :: Int -> Way -> Maybe Int
afterIndex index way
| way == U = if afterU >= 0
then Just afterU
else Nothing
| way == R = if (mod index fieldWidth) + 1 < fieldWidth
then Just $ index + 1
else Nothing
| way == D = if afterD < fieldLength
then Just afterD
else Nothing
| way == L = if (mod index fieldWidth) - 1 >= 0
then Just $ index - 1
else Nothing
where fieldLength = fieldWidth * fieldHeight
afterU = index - fieldWidth
afterD = index + fieldWidth
swapByIndex :: Int -> Int -> Field -> Field
swapByIndex i j xs = reverse $ fst $ foldl f ([],0) xs
where
f (acc, idx) x
| idx == i = (xs!!j:acc, idx+1)
| idx == j = (xs!!i:acc, idx+1)
| otherwise = (x:acc, idx+1)
wrongList :: (Eq a) => [a] -> [a] -> Int -> [Int]
wrongList [] _ _ = []
wrongList _ [] _ = []
wrongList (x:xs) (y:ys) count
| x == y = wrongList xs ys (count + 1)
| otherwise = count : (wrongList xs ys (count + 1))
tJW :: (Eq a) => [a] -> [a] -> Float
tJW [] _ = 0
tJW _ [] = 0
tJW (x:xs) (y:ys)
| x == y = tJW xs ys
| otherwise = (tJW xs ys) + 1
jwDist :: (Eq a) => [a] -> [a] -> Float
jwDist x y = (2 + (m - t) / m ) / 3
where
m = fromIntegral( length(x) ) :: Float
t = (tJW x y) / 2
| inct-www-club/Procon2014 | src/solver.hs | mit | 3,874 | 0 | 14 | 1,116 | 1,970 | 1,023 | 947 | 104 | 5 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
-- for the client: export those types needed for playnow
module Game.Play.Api.Types where
import Control.Lens.TH (makeLenses)
import Data.Aeson (FromJSON, ToJSON)
import GHC.Generics (Generic)
import Servant.Docs (ToSample (..), singleSample)
import Game.Api.Types (AuthInfo, sampleAuthInfo)
import Game.Types (CardKind (..))
data PlayCardRq = PlayCardRq
{ _pcrqCardKind :: CardKind
, _pcrqAuth :: AuthInfo
} deriving (Generic, FromJSON, ToJSON)
instance ToSample PlayCardRq where
toSamples _ =
let _pcrqCardKind = Plain
_pcrqAuth = sampleAuthInfo
in singleSample PlayCardRq{..}
data PlaceBetRq = PlaceBetRq
{ _pbrqValue :: Int
, _pbrqAuth :: AuthInfo
} deriving (Generic, FromJSON, ToJSON)
instance ToSample PlaceBetRq where
toSamples _ =
let _pbrqValue = 3
_pbrqAuth = sampleAuthInfo
in singleSample PlaceBetRq{..}
makeLenses ''PlayCardRq
makeLenses ''PlaceBetRq
| rubenmoor/skull | skull-server/src/Game/Play/Api/Types.hs | mit | 1,138 | 0 | 9 | 268 | 260 | 149 | 111 | 31 | 0 |
module ProjectEuler.Problem56
( problem
) where
import Data.List
import ProjectEuler.Types
problem :: Problem
problem = pureProblem 56 Solved result
digitSum :: Integer -> Int
digitSum = sum . unfoldr f
where
f 0 = Nothing
f n = let (q,r) = n `quotRem` 10 in Just (fromIntegral r, q)
result :: Int
result = maximum [ digitSum (a^b) | a <- [1..100], b <- [1..100 :: Int]]
| Javran/Project-Euler | src/ProjectEuler/Problem56.hs | mit | 389 | 0 | 11 | 85 | 168 | 91 | 77 | 12 | 2 |
-- | <http://strava.github.io/api/v3/activities/>
module Strive.Actions.Activities
( createActivity
, getActivity
, updateActivity
, deleteActivity
, getCurrentActivities
, getRelatedActivities
, getFeed
, getActivityZones
, getActivityLaps
) where
import Data.Aeson (encode)
import Data.ByteString.Char8 (unpack)
import Data.ByteString.Lazy (toStrict)
import Network.HTTP.Client (responseBody, responseStatus)
import Network.HTTP.Types (Query, methodDelete, noContent204, toQuery)
import Strive.Aliases (ActivityId, ElapsedTime, Name, Result, StartTime)
import Strive.Client (Client)
import Strive.Enums (ActivityType)
import Strive.Internal.HTTP (buildRequest, get, performRequest, post, put)
import Strive.Options
( CreateActivityOptions
, GetActivityOptions
, GetCurrentActivitiesOptions
, GetFeedOptions
, GetRelatedActivitiesOptions
, UpdateActivityOptions
)
import Strive.Types
(ActivityDetailed, ActivityLapSummary, ActivitySummary, ActivityZoneDetailed)
-- | <http://strava.github.io/api/v3/activities/#create>
createActivity
:: Client
-> Name
-> ActivityType
-> StartTime
-> ElapsedTime
-> CreateActivityOptions
-> IO (Result ActivityDetailed)
createActivity client name type_ startDateLocal elapsedTime options = post
client
resource
query
where
resource = "api/v3/activities"
query =
toQuery
[ ("name", name)
, ("type", show type_)
, ("start_date_local", unpack (toStrict (encode startDateLocal)))
, ("elapsed_time", show elapsedTime)
]
<> toQuery options
-- | <http://strava.github.io/api/v3/activities/#get-details>
getActivity
:: Client -> ActivityId -> GetActivityOptions -> IO (Result ActivitySummary)
getActivity client activityId options = get client resource query
where
resource = "api/v3/activities/" <> show activityId
query = toQuery options
-- | <http://strava.github.io/api/v3/activities/#put-updates>
updateActivity
:: Client
-> ActivityId
-> UpdateActivityOptions
-> IO (Result ActivityDetailed)
updateActivity client activityId options = put client resource query
where
resource = "api/v3/activities/" <> show activityId
query = toQuery options
-- | <http://strava.github.io/api/v3/activities/#delete>
deleteActivity :: Client -> ActivityId -> IO (Result ())
deleteActivity client activityId = do
request <- buildRequest methodDelete client resource query
response <- performRequest client request
return
(if responseStatus response == noContent204
then Right ()
else Left (response, unpack (toStrict (responseBody response)))
)
where
resource = "api/v3/activities/" <> show activityId
query = [] :: Query
-- | <http://strava.github.io/api/v3/activities/#get-activities>
getCurrentActivities
:: Client -> GetCurrentActivitiesOptions -> IO (Result [ActivitySummary])
getCurrentActivities client options = get client resource query
where
resource = "api/v3/athlete/activities"
query = toQuery options
-- | <http://strava.github.io/api/v3/activities/#get-related>
getRelatedActivities
:: Client
-> ActivityId
-> GetRelatedActivitiesOptions
-> IO (Result [ActivitySummary])
getRelatedActivities client activityId options = get client resource query
where
resource = "api/v3/activities/" <> show activityId <> "/related"
query = toQuery options
-- | <http://strava.github.io/api/v3/activities/#get-feed>
getFeed :: Client -> GetFeedOptions -> IO (Result [ActivitySummary])
getFeed client options = get client resource query
where
resource = "api/v3/activities/following"
query = toQuery options
-- | <http://strava.github.io/api/v3/activities/#zones>
getActivityZones :: Client -> ActivityId -> IO (Result [ActivityZoneDetailed])
getActivityZones client activityId = get client resource query
where
resource = "api/v3/activities/" <> show activityId <> "/zones"
query = [] :: Query
-- | <http://strava.github.io/api/v3/activities/#laps>
getActivityLaps :: Client -> ActivityId -> IO (Result [ActivityLapSummary])
getActivityLaps client activityId = get client resource query
where
resource = "api/v3/activities/" <> show activityId <> "/laps"
query = [] :: Query
| tfausak/strive | source/library/Strive/Actions/Activities.hs | mit | 4,194 | 0 | 16 | 638 | 964 | 521 | 443 | 96 | 2 |
module Data.Bson.Binary.Tests
( tests
) where
import Data.Binary (encode, decode)
import Test.Tasty (TestTree, testGroup)
import Test.Tasty.QuickCheck (testProperty)
import Data.Bson (Document)
import Data.Bson.Binary ()
import Data.Bson.Tests.Instances ()
testEncodeDecodeDocument :: Document -> Bool
testEncodeDecodeDocument doc = (==) doc $ decode $ encode doc
tests :: TestTree
tests = testGroup "Data.Bson.Binary.Tests"
[ testProperty "testEncodeDecodeDocument" testEncodeDecodeDocument
]
| lambda-llama/bresson | tests/Data/Bson/Binary/Tests.hs | mit | 515 | 0 | 7 | 74 | 135 | 80 | 55 | 13 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Test.SimpleTable where
import DB.Model.SimpleTable
import qualified DB.Model.SimpleTable as S
import DB.Model.MultiTable (MultiTable)
import qualified DB.Model.MultiTable as M
import Test.Hspec
data Test m = Test {
key :: m Int,
f :: m String,
c :: m String,
n :: m String
} deriving (Generic)
instance SimpleTable Test where
relation = Test {
key = S.IsKey "Test" "id",
f = S.IsCol "f",
c = S.IsConst "c",
n = S.IsNull
}
test :: IO ()
test = hspec $ do
it "Convert Table.relation to MultiTable.relation" $ do
let expect = Test {
key = M.IsKey [("Test", "id")],
f = M.IsCol "Test" "f",
c = M.IsConst "c",
n = M.IsNull
}
M.relation `shouldBe` expect
| YLiLarry/db-model | test/Test/SimpleTable.hs | mit | 837 | 0 | 18 | 266 | 261 | 150 | 111 | 28 | 1 |
module LispLovesMe where
import Text.ParserCombinators.Parsec hiding (spaces)
import Data.List (intercalate)
data AST = I32 Int
| Sym String
| Nul
| Err
| Lst [AST]
| Boo Bool
| Nod AST [AST]
deriving (Eq, Show)
spaces :: Parser String
spaces = many $ oneOf " ,\r\n\t"
spaces1 :: Parser String
spaces1 = many1 $ oneOf " ,\r\n\t"
parseLisp :: Parser AST
parseLisp = try parseNod <|> parseExpr
parseNod :: Parser AST
parseNod = do
spaces
char '('
e <- spaces *> parseExpr <* spaces
es <- parseExpr `sepEndBy` spaces
spaces
char ')'
spaces
return $ Nod e es
parseExpr :: Parser AST
parseExpr = spaces *>
(try parseBoolean
<|> try parseNull
<|> parseSymbol
<|> parseNumber
<|> parseNod) <* spaces
where
parseSymbol = do
s <- noneOf $ " ,\n\t\r()" ++ [ '0' .. '9' ]
ss <- many $ noneOf " ,\n\t\r()"
return $ Sym (s:ss)
parseNumber = I32 . read <$> many1 digit
parseBoolean = (string "true" *> return (Boo True)) <|> (string "false" *> return (Boo False))
parseNull = (string "()" <|> string "null") *> return Nul
-- if Err
eval :: AST -> AST
eval (Nod (Sym f) es) =
case f `lookup` preludeFunctions of
Nothing -> Err
Just func -> func es
eval (Nod _ _) = Err
eval (Lst as) = Lst (map eval as)
eval x = x
is_i32 :: AST -> Bool
is_i32 (I32 _) = True
is_i32 _ = False
is_bool :: AST -> Bool
is_bool (Boo _) = True
is_bool _ = False
is_list :: AST -> Bool
is_list (Lst _) = True
is_list _ = False
seq_op :: (Int -> Int -> Int) -> [AST] -> AST
seq_op f es = let vs = map eval es
in if all is_i32 vs
then foldl1 (\(I32 x) (I32 y) -> I32 (f x y)) vs
else Err
bin_op :: (Int -> Int -> Bool) -> [AST] -> AST
bin_op f es | length es /= 2 = Err
| otherwise = let vs = map eval es
in if all is_i32 vs
then let (I32 x) = head vs
(I32 y) = last vs
in Boo (f x y)
else Err
cond :: [AST] -> AST
cond es | length es < 2 = Err
| otherwise = let (a:b:c) = map eval es
in if is_bool a
then let (Boo cc) = a
in if cc
then b
else if null c
then Nul
else head c
else Err
no :: [AST] -> AST
no es | length es /= 1 = Err
| otherwise = let v = eval (head es)
in if is_bool v
then let (Boo x) = v in Boo (not x)
else Err
range :: [AST] -> AST
range es | length es /= 2 = Err
| otherwise = let vs@[v1, v2] = map eval es
in if all is_i32 vs
then let (I32 x) = v1
(I32 y) = v2
in Lst $ I32 <$> [x .. y]
else Err
size :: [AST] -> AST
size es | length es /= 1 = Err
| otherwise = let v = eval (head es)
in if is_list v
then let (Lst ls) = v in I32 (length ls)
else Err
rev :: [AST] -> AST
rev es | length es /= 1 = Err
| otherwise = let v = eval (head es)
in if is_list v
then let (Lst ls) = v in Lst (reverse ls)
else Err
preludeFunctions :: [(String, [AST] -> AST)]
preludeFunctions =
[ ("+", seq_op (+))
, ("*", seq_op (*))
, ("-", seq_op (-))
, ("/", seq_op div)
, ("^", seq_op (^))
, (">", bin_op (>))
, ("<", bin_op (<))
, ("!", no)
, ("list", Lst)
, ("size", size)
, ("reverse", rev)
, ("..", range)
, ("==", bin_op (==))
, (">=", bin_op (>=))
, ("<=", bin_op (<=))
, ("!=", bin_op (/=))
, ("if", cond)
]
lisp2s :: AST -> String
lisp2s (I32 i) = show i
lisp2s (Sym s) = s
lisp2s Nul = "null"
lisp2s (Boo True) = "true"
lisp2s (Boo False) = "false"
lisp2s (Nod e es) = "(" ++ intercalate " " (map lisp2s (e:es)) ++ ")"
lispPretty :: String -> Maybe String
lispPretty s = case parse (parseLisp <* eof) "" s of
Left _ -> Nothing
Right ast -> Just $ lisp2s ast
lispEval :: String -> Maybe AST
lispEval s = case parse (parseLisp <* eof) "" s of
Left _ -> Nothing
Right ast -> Just (eval ast) | delta4d/codewars | kata/i-love-lisp/LispLovesMe.hs | mit | 4,742 | 0 | 14 | 2,031 | 1,874 | 959 | 915 | 142 | 4 |
{-# LANGUAGE OverloadedStrings #-}
module System.PassengerCheck.HealthSpec (spec) where
import Test.Hspec
import System.PassengerCheck.Types
import System.PassengerCheck.Health
import System.Nagios.Plugin (CheckStatus(..))
spec :: Spec
spec = do
describe "queuedRequests" $
it "returns the number of queued requests" $
queuedRequests (PassengerStatus 15 2 3 [4, 5]) `shouldBe` 12
describe "status" $ do
it "returns Critical when the queue is >= 90% full" $
status (PassengerStatus 10 2 7 [1, 1]) `shouldBe`
(Critical, "Queue is at or above 90% full")
it "returns Warning when the queue is >= 50% full" $
status (PassengerStatus 10 2 3 [1, 1]) `shouldBe`
(Warning, "Queue is at or above 50% full")
it "returns OK when the queue is < 50% full" $
status (PassengerStatus 10 2 1 [0, 0]) `shouldBe`
(OK, "Queue is less than 50% full")
| stackbuilders/passenger-check | spec/System/PassengerCheck/HealthSpec.hs | mit | 906 | 0 | 15 | 203 | 238 | 131 | 107 | 21 | 1 |
{- |
Module : Main
Copyright : Justin Ethier
Licence : MIT (see LICENSE in the distribution)
Maintainer : github.com/justinethier
Stability : experimental
Portability : portable
This file implements a REPL /shell/ to host the interpreter, and also
allows execution of stand-alone files containing Scheme code.
-}
module Main where
import qualified Language.Scheme.Core as LSC -- Scheme Interpreter
import Language.Scheme.Types -- Scheme data types
import qualified Language.Scheme.Util as LSU (countAllLetters, countLetters, strip)
import qualified Language.Scheme.Variables as LSV -- Scheme variable operations
import Control.Monad.Except
import qualified Data.Char as DC
import qualified Data.List as DL
import Data.Maybe (fromMaybe)
import System.Console.GetOpt
import qualified System.Console.Haskeline as HL
import qualified System.Console.Haskeline.Completion as HLC
import System.Environment
import System.Exit (exitSuccess)
import System.IO
main :: IO ()
main = do
args <- getArgs
let (actions, nonOpts, _) = getOpt Permute options args
opts <- foldl (>>=) (return defaultOptions) actions
let Options {optInter = interactive, optSchemeRev = schemeRev} = opts
if null nonOpts
then do
LSC.showBanner
env <- liftIO $ getRuntimeEnv schemeRev
runRepl env
else do
runOne (getRuntimeEnv schemeRev) nonOpts interactive
--
-- Command line options section
--
data Options = Options {
optInter :: Bool,
optSchemeRev :: String -- RxRS version
}
-- |Default values for the command line options
defaultOptions :: Options
defaultOptions = Options {
optInter = False,
optSchemeRev = "5"
}
options :: [OptDescr (Options -> IO Options)]
options = [
Option ['i'] ["interactive"] (NoArg getInter) "load file and run REPL",
Option ['r'] ["revision"] (ReqArg writeRxRSVersion "Scheme") "scheme RxRS version",
Option ['h', '?'] ["help"] (NoArg showHelp) "show usage information"
]
where
getInter opt = return opt { optInter = True }
writeRxRSVersion arg opt = return opt { optSchemeRev = arg }
showHelp :: Options -> IO Options
showHelp _ = do
putStrLn "Usage: huski [options] [file]"
putStrLn ""
putStrLn " huski is the husk scheme interpreter."
putStrLn ""
putStrLn " File is a scheme source file to execute. If no file is specified"
putStrLn " the husk REPL will be started."
putStrLn ""
putStrLn " Options may be any of the following:"
putStrLn ""
putStrLn " -h, --help Display this information"
putStrLn " -i Start interactive REPL after file is executed. This"
putStrLn " option has no effect if a file is not specified. "
-- putStrLn " --revision rev Specify the scheme revision to use:"
-- putStrLn ""
-- putStrLn " 5 - r5rs (default)"
-- putStrLn " 7 - r7rs small"
putStrLn ""
exitSuccess
--
-- REPL Section
--
flushStr :: String -> IO ()
flushStr str = putStr str >> hFlush stdout
getRuntimeEnv :: String -> IO Env
getRuntimeEnv "7" = LSC.r7rsEnv
getRuntimeEnv _ = LSC.r5rsEnv
-- |Execute a single scheme file from the command line
runOne :: IO Env -> [String] -> Bool -> IO ()
runOne initEnv args interactive = do
env <- initEnv >>= flip LSV.extendEnv
[((LSV.varNamespace, "args"),
List $ map String $ drop 1 args)]
result <- (LSC.runIOThrows $ liftM show $
LSC.evalLisp env (List [Atom "load", String (head args)]))
_ <- case result of
Just errMsg -> putStrLn errMsg
_ -> do
-- Call into (main) if it exists...
alreadyDefined <- liftIO $ LSV.isBound env "main"
let argv = List $ map String args
when alreadyDefined (do
mainResult <- (LSC.runIOThrows $ liftM show $
LSC.evalLisp env (List [Atom "main", List [Atom "quote", argv]]))
case mainResult of
Just errMsg -> putStrLn errMsg
_ -> return ())
when interactive (do
runRepl env)
-- |Start the REPL (interactive interpreter)
runRepl :: Env -> IO ()
runRepl env' = do
let settings = HL.Settings (completeScheme env') Nothing True
HL.runInputT settings (loop env')
where
-- Main REPL loop
loop :: Env -> HL.InputT IO ()
loop env = do
minput <- HL.getInputLine "huski> "
case minput of
Nothing -> return ()
Just i -> do
case LSU.strip i of
"quit" -> return ()
"" -> loop env -- ignore inputs of just whitespace
input -> do
inputLines <- getMultiLine [input]
let input' = unlines inputLines
result <- liftIO (LSC.evalString env input')
if not (null result)
then do HL.outputStrLn result
loop env
else loop env
-- Read another input line, if necessary
getMultiLine previous = do
if test previous
then do
mb_input <- HL.getInputLine ""
case mb_input of
Nothing -> return previous
Just input -> getMultiLine $ previous ++ [input]
else return previous
-- Check if we need another input line
-- This just does a bare minimum, and could be more robust
test ls = do
let cOpen = LSU.countAllLetters '(' ls
cClose = LSU.countAllLetters ')' ls
cOpen > cClose
-- |Auto-complete using scheme symbols
completeScheme :: Env -> (String, String)
-> IO (String, [HLC.Completion])
-- Right after a ')' it seems more useful to autocomplete next closed parenthesis
completeScheme _ (lnL@(')':_), _) = do
let cOpen = LSU.countLetters '(' lnL
cClose = LSU.countLetters ')' lnL
if cOpen > cClose
then return (lnL, [HL.Completion ")" ")" False])
else return (lnL, [])
completeScheme env (lnL, lnR) = do
complete $ reverse $ readAtom lnL
where
complete ('"' : _) = do
-- Special case, inside a string it seems more
-- useful to autocomplete filenames
liftIO $ HLC.completeFilename (lnL, lnR)
complete pre = do
-- Get list of possible completions from ENV
xps <- LSV.recExportsFromEnv env
let allDefs = xps ++ specialForms
let allDefs' = filter (\ (Atom a) -> DL.isPrefixOf pre a) allDefs
let comps = map (\ (Atom a) -> HL.Completion a a False) allDefs'
-- Get unused portion of the left-hand string
let unusedLnL = fromMaybe lnL (DL.stripPrefix (reverse pre) lnL)
return (unusedLnL, comps)
-- Not loaded into an env, so we need to list them here
specialForms = map Atom [
"define"
, "define-syntax"
, "expand"
, "hash-table-delete!"
, "hash-table-set!"
, "if"
, "lambda"
, "let-syntax"
, "letrec-syntax"
, "quote"
, "set!"
, "set-car!"
, "set-cdr!"
, "string-set!"
, "vector-set!"]
-- Read until the end of the current symbol (atom), if there is one.
-- There is also a special case for files if a double-quote is found.
readAtom (c:cs)
| c == '"' = ['"'] -- Save to indicate file completion to caller
| c == '(' = []
| c == '[' = []
| DC.isSpace c = []
| otherwise = (c : readAtom cs)
readAtom [] = []
| justinethier/husk-scheme | hs-src/Interpreter/shell.hs | mit | 7,473 | 0 | 26 | 2,185 | 1,860 | 949 | 911 | 158 | 7 |
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
module Api.MimeTypes
( Markdown
) where
import qualified Data.ByteString.Lazy as LBS
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Network.HTTP.Media ((//), (/:))
import Servant as S
data Markdown
instance S.Accept Markdown where
contentType _ = "text" // "markdown" /: ("charset", "utf-8")
instance S.MimeRender Markdown Text where
mimeRender _ text = LBS.fromStrict (encodeUtf8 text)
| gust/feature-creature | legacy/lib/Api/MimeTypes.hs | mit | 497 | 0 | 8 | 73 | 134 | 81 | 53 | -1 | -1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.HTMLInputElement
(js_stepUp, stepUp, js_stepDown, stepDown, js_checkValidity,
checkValidity, js_setCustomValidity, setCustomValidity, js_select,
select, js_setRangeText, setRangeText, js_setRangeText4,
setRangeText4, js_setSelectionRange, setSelectionRange,
js_setAccept, setAccept, js_getAccept, getAccept, js_setAlt,
setAlt, js_getAlt, getAlt, js_setAutocomplete, setAutocomplete,
js_getAutocomplete, getAutocomplete, js_setAutofocus, setAutofocus,
js_getAutofocus, getAutofocus, js_setDefaultChecked,
setDefaultChecked, js_getDefaultChecked, getDefaultChecked,
js_setChecked, setChecked, js_getChecked, getChecked,
js_setDirName, setDirName, js_getDirName, getDirName,
js_setDisabled, setDisabled, js_getDisabled, getDisabled,
js_getForm, getForm, js_setFiles, setFiles, js_getFiles, getFiles,
js_setFormAction, setFormAction, js_getFormAction, getFormAction,
js_setFormEnctype, setFormEnctype, js_getFormEnctype,
getFormEnctype, js_setFormMethod, setFormMethod, js_getFormMethod,
getFormMethod, js_setFormNoValidate, setFormNoValidate,
js_getFormNoValidate, getFormNoValidate, js_setFormTarget,
setFormTarget, js_getFormTarget, getFormTarget, js_setHeight,
setHeight, js_getHeight, getHeight, js_setIndeterminate,
setIndeterminate, js_getIndeterminate, getIndeterminate,
js_getList, getList, js_setMax, setMax, js_getMax, getMax,
js_setMaxLength, setMaxLength, js_getMaxLength, getMaxLength,
js_setMin, setMin, js_getMin, getMin, js_setMultiple, setMultiple,
js_getMultiple, getMultiple, js_setName, setName, js_getName,
getName, js_setPattern, setPattern, js_getPattern, getPattern,
js_setPlaceholder, setPlaceholder, js_getPlaceholder,
getPlaceholder, js_setReadOnly, setReadOnly, js_getReadOnly,
getReadOnly, js_setRequired, setRequired, js_getRequired,
getRequired, js_setSize, setSize, js_getSize, getSize, js_setSrc,
setSrc, js_getSrc, getSrc, js_setStep, setStep, js_getStep,
getStep, js_setType, setType, js_getType, getType,
js_setDefaultValue, setDefaultValue, js_getDefaultValue,
getDefaultValue, js_setValue, setValue, js_getValue, getValue,
js_setValueAsDate, setValueAsDate, js_getValueAsDate,
getValueAsDate, js_setValueAsNumber, setValueAsNumber,
js_getValueAsNumber, getValueAsNumber, js_setWidth, setWidth,
js_getWidth, getWidth, js_getWillValidate, getWillValidate,
js_getValidity, getValidity, js_getValidationMessage,
getValidationMessage, js_getLabels, getLabels,
js_setSelectionStart, setSelectionStart, js_getSelectionStart,
getSelectionStart, js_setSelectionEnd, setSelectionEnd,
js_getSelectionEnd, getSelectionEnd, js_setSelectionDirection,
setSelectionDirection, js_getSelectionDirection,
getSelectionDirection, js_setAlign, setAlign, js_getAlign,
getAlign, js_setUseMap, setUseMap, js_getUseMap, getUseMap,
js_setIncremental, setIncremental, js_getIncremental,
getIncremental, js_setAutocorrect, setAutocorrect,
js_getAutocorrect, getAutocorrect, js_setAutocapitalize,
setAutocapitalize, js_getAutocapitalize, getAutocapitalize,
js_setCapture, setCapture, js_getCapture, getCapture,
HTMLInputElement, castToHTMLInputElement, gTypeHTMLInputElement)
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 (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
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.Enums
foreign import javascript unsafe "$1[\"stepUp\"]($2)" js_stepUp ::
JSRef HTMLInputElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.stepUp Mozilla HTMLInputElement.stepUp documentation>
stepUp :: (MonadIO m) => HTMLInputElement -> Int -> m ()
stepUp self n = liftIO (js_stepUp (unHTMLInputElement self) n)
foreign import javascript unsafe "$1[\"stepDown\"]($2)" js_stepDown
:: JSRef HTMLInputElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.stepDown Mozilla HTMLInputElement.stepDown documentation>
stepDown :: (MonadIO m) => HTMLInputElement -> Int -> m ()
stepDown self n = liftIO (js_stepDown (unHTMLInputElement self) n)
foreign import javascript unsafe
"($1[\"checkValidity\"]() ? 1 : 0)" js_checkValidity ::
JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checkValidity Mozilla HTMLInputElement.checkValidity documentation>
checkValidity :: (MonadIO m) => HTMLInputElement -> m Bool
checkValidity self
= liftIO (js_checkValidity (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"setCustomValidity\"]($2)"
js_setCustomValidity ::
JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setCustomValidity Mozilla HTMLInputElement.setCustomValidity documentation>
setCustomValidity ::
(MonadIO m, ToJSString error) =>
HTMLInputElement -> Maybe error -> m ()
setCustomValidity self error
= liftIO
(js_setCustomValidity (unHTMLInputElement self)
(toMaybeJSString error))
foreign import javascript unsafe "$1[\"select\"]()" js_select ::
JSRef HTMLInputElement -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.select Mozilla HTMLInputElement.select documentation>
select :: (MonadIO m) => HTMLInputElement -> m ()
select self = liftIO (js_select (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"setRangeText\"]($2)"
js_setRangeText :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setRangeText Mozilla HTMLInputElement.setRangeText documentation>
setRangeText ::
(MonadIO m, ToJSString replacement) =>
HTMLInputElement -> replacement -> m ()
setRangeText self replacement
= liftIO
(js_setRangeText (unHTMLInputElement self)
(toJSString replacement))
foreign import javascript unsafe
"$1[\"setRangeText\"]($2, $3, $4,\n$5)" js_setRangeText4 ::
JSRef HTMLInputElement ->
JSString -> Word -> Word -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setRangeText Mozilla HTMLInputElement.setRangeText documentation>
setRangeText4 ::
(MonadIO m, ToJSString replacement, ToJSString selectionMode) =>
HTMLInputElement ->
replacement -> Word -> Word -> selectionMode -> m ()
setRangeText4 self replacement start end selectionMode
= liftIO
(js_setRangeText4 (unHTMLInputElement self)
(toJSString replacement)
start
end
(toJSString selectionMode))
foreign import javascript unsafe
"$1[\"setSelectionRange\"]($2, $3,\n$4)" js_setSelectionRange ::
JSRef HTMLInputElement -> Int -> Int -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.setSelectionRange Mozilla HTMLInputElement.setSelectionRange documentation>
setSelectionRange ::
(MonadIO m, ToJSString direction) =>
HTMLInputElement -> Int -> Int -> direction -> m ()
setSelectionRange self start end direction
= liftIO
(js_setSelectionRange (unHTMLInputElement self) start end
(toJSString direction))
foreign import javascript unsafe "$1[\"accept\"] = $2;"
js_setAccept :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.accept Mozilla HTMLInputElement.accept documentation>
setAccept ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setAccept self val
= liftIO (js_setAccept (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"accept\"]" js_getAccept ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.accept Mozilla HTMLInputElement.accept documentation>
getAccept ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getAccept self
= liftIO
(fromJSString <$> (js_getAccept (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"alt\"] = $2;" js_setAlt ::
JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.alt Mozilla HTMLInputElement.alt documentation>
setAlt ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setAlt self val
= liftIO (js_setAlt (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"alt\"]" js_getAlt ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.alt Mozilla HTMLInputElement.alt documentation>
getAlt ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getAlt self
= liftIO (fromJSString <$> (js_getAlt (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"autocomplete\"] = $2;"
js_setAutocomplete :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocomplete Mozilla HTMLInputElement.autocomplete documentation>
setAutocomplete ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setAutocomplete self val
= liftIO
(js_setAutocomplete (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"autocomplete\"]"
js_getAutocomplete :: JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocomplete Mozilla HTMLInputElement.autocomplete documentation>
getAutocomplete ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getAutocomplete self
= liftIO
(fromJSString <$> (js_getAutocomplete (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"autofocus\"] = $2;"
js_setAutofocus :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autofocus Mozilla HTMLInputElement.autofocus documentation>
setAutofocus :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setAutofocus self val
= liftIO (js_setAutofocus (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"autofocus\"] ? 1 : 0)"
js_getAutofocus :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autofocus Mozilla HTMLInputElement.autofocus documentation>
getAutofocus :: (MonadIO m) => HTMLInputElement -> m Bool
getAutofocus self
= liftIO (js_getAutofocus (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"defaultChecked\"] = $2;"
js_setDefaultChecked :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultChecked Mozilla HTMLInputElement.defaultChecked documentation>
setDefaultChecked ::
(MonadIO m) => HTMLInputElement -> Bool -> m ()
setDefaultChecked self val
= liftIO (js_setDefaultChecked (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"defaultChecked\"] ? 1 : 0)"
js_getDefaultChecked :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultChecked Mozilla HTMLInputElement.defaultChecked documentation>
getDefaultChecked :: (MonadIO m) => HTMLInputElement -> m Bool
getDefaultChecked self
= liftIO (js_getDefaultChecked (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"checked\"] = $2;"
js_setChecked :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checked Mozilla HTMLInputElement.checked documentation>
setChecked :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setChecked self val
= liftIO (js_setChecked (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"checked\"] ? 1 : 0)"
js_getChecked :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.checked Mozilla HTMLInputElement.checked documentation>
getChecked :: (MonadIO m) => HTMLInputElement -> m Bool
getChecked self = liftIO (js_getChecked (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"dirName\"] = $2;"
js_setDirName :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.dirName Mozilla HTMLInputElement.dirName documentation>
setDirName ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setDirName self val
= liftIO (js_setDirName (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"dirName\"]" js_getDirName ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.dirName Mozilla HTMLInputElement.dirName documentation>
getDirName ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getDirName self
= liftIO
(fromJSString <$> (js_getDirName (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"disabled\"] = $2;"
js_setDisabled :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.disabled Mozilla HTMLInputElement.disabled documentation>
setDisabled :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setDisabled self val
= liftIO (js_setDisabled (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"disabled\"] ? 1 : 0)"
js_getDisabled :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.disabled Mozilla HTMLInputElement.disabled documentation>
getDisabled :: (MonadIO m) => HTMLInputElement -> m Bool
getDisabled self
= liftIO (js_getDisabled (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"form\"]" js_getForm ::
JSRef HTMLInputElement -> IO (JSRef HTMLFormElement)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.form Mozilla HTMLInputElement.form documentation>
getForm ::
(MonadIO m) => HTMLInputElement -> m (Maybe HTMLFormElement)
getForm self
= liftIO ((js_getForm (unHTMLInputElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"files\"] = $2;" js_setFiles
:: JSRef HTMLInputElement -> JSRef FileList -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.files Mozilla HTMLInputElement.files documentation>
setFiles ::
(MonadIO m) => HTMLInputElement -> Maybe FileList -> m ()
setFiles self val
= liftIO
(js_setFiles (unHTMLInputElement self) (maybe jsNull pToJSRef val))
foreign import javascript unsafe "$1[\"files\"]" js_getFiles ::
JSRef HTMLInputElement -> IO (JSRef FileList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.files Mozilla HTMLInputElement.files documentation>
getFiles :: (MonadIO m) => HTMLInputElement -> m (Maybe FileList)
getFiles self
= liftIO ((js_getFiles (unHTMLInputElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"formAction\"] = $2;"
js_setFormAction :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formAction Mozilla HTMLInputElement.formAction documentation>
setFormAction ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setFormAction self val
= liftIO
(js_setFormAction (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"formAction\"]"
js_getFormAction :: JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formAction Mozilla HTMLInputElement.formAction documentation>
getFormAction ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getFormAction self
= liftIO
(fromJSString <$> (js_getFormAction (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"formEnctype\"] = $2;"
js_setFormEnctype ::
JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formEnctype Mozilla HTMLInputElement.formEnctype documentation>
setFormEnctype ::
(MonadIO m, ToJSString val) =>
HTMLInputElement -> Maybe val -> m ()
setFormEnctype self val
= liftIO
(js_setFormEnctype (unHTMLInputElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"formEnctype\"]"
js_getFormEnctype ::
JSRef HTMLInputElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formEnctype Mozilla HTMLInputElement.formEnctype documentation>
getFormEnctype ::
(MonadIO m, FromJSString result) =>
HTMLInputElement -> m (Maybe result)
getFormEnctype self
= liftIO
(fromMaybeJSString <$>
(js_getFormEnctype (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"formMethod\"] = $2;"
js_setFormMethod ::
JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formMethod Mozilla HTMLInputElement.formMethod documentation>
setFormMethod ::
(MonadIO m, ToJSString val) =>
HTMLInputElement -> Maybe val -> m ()
setFormMethod self val
= liftIO
(js_setFormMethod (unHTMLInputElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"formMethod\"]"
js_getFormMethod ::
JSRef HTMLInputElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formMethod Mozilla HTMLInputElement.formMethod documentation>
getFormMethod ::
(MonadIO m, FromJSString result) =>
HTMLInputElement -> m (Maybe result)
getFormMethod self
= liftIO
(fromMaybeJSString <$>
(js_getFormMethod (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"formNoValidate\"] = $2;"
js_setFormNoValidate :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formNoValidate Mozilla HTMLInputElement.formNoValidate documentation>
setFormNoValidate ::
(MonadIO m) => HTMLInputElement -> Bool -> m ()
setFormNoValidate self val
= liftIO (js_setFormNoValidate (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"formNoValidate\"] ? 1 : 0)"
js_getFormNoValidate :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formNoValidate Mozilla HTMLInputElement.formNoValidate documentation>
getFormNoValidate :: (MonadIO m) => HTMLInputElement -> m Bool
getFormNoValidate self
= liftIO (js_getFormNoValidate (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"formTarget\"] = $2;"
js_setFormTarget :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formTarget Mozilla HTMLInputElement.formTarget documentation>
setFormTarget ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setFormTarget self val
= liftIO
(js_setFormTarget (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"formTarget\"]"
js_getFormTarget :: JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.formTarget Mozilla HTMLInputElement.formTarget documentation>
getFormTarget ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getFormTarget self
= liftIO
(fromJSString <$> (js_getFormTarget (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"height\"] = $2;"
js_setHeight :: JSRef HTMLInputElement -> Word -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.height Mozilla HTMLInputElement.height documentation>
setHeight :: (MonadIO m) => HTMLInputElement -> Word -> m ()
setHeight self val
= liftIO (js_setHeight (unHTMLInputElement self) val)
foreign import javascript unsafe "$1[\"height\"]" js_getHeight ::
JSRef HTMLInputElement -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.height Mozilla HTMLInputElement.height documentation>
getHeight :: (MonadIO m) => HTMLInputElement -> m Word
getHeight self = liftIO (js_getHeight (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"indeterminate\"] = $2;"
js_setIndeterminate :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.indeterminate Mozilla HTMLInputElement.indeterminate documentation>
setIndeterminate :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setIndeterminate self val
= liftIO (js_setIndeterminate (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"indeterminate\"] ? 1 : 0)"
js_getIndeterminate :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.indeterminate Mozilla HTMLInputElement.indeterminate documentation>
getIndeterminate :: (MonadIO m) => HTMLInputElement -> m Bool
getIndeterminate self
= liftIO (js_getIndeterminate (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"list\"]" js_getList ::
JSRef HTMLInputElement -> IO (JSRef HTMLElement)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.list Mozilla HTMLInputElement.list documentation>
getList :: (MonadIO m) => HTMLInputElement -> m (Maybe HTMLElement)
getList self
= liftIO ((js_getList (unHTMLInputElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"max\"] = $2;" js_setMax ::
JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.max Mozilla HTMLInputElement.max documentation>
setMax ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setMax self val
= liftIO (js_setMax (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"max\"]" js_getMax ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.max Mozilla HTMLInputElement.max documentation>
getMax ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getMax self
= liftIO (fromJSString <$> (js_getMax (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"maxLength\"] = $2;"
js_setMaxLength :: JSRef HTMLInputElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.maxLength Mozilla HTMLInputElement.maxLength documentation>
setMaxLength :: (MonadIO m) => HTMLInputElement -> Int -> m ()
setMaxLength self val
= liftIO (js_setMaxLength (unHTMLInputElement self) val)
foreign import javascript unsafe "$1[\"maxLength\"]"
js_getMaxLength :: JSRef HTMLInputElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.maxLength Mozilla HTMLInputElement.maxLength documentation>
getMaxLength :: (MonadIO m) => HTMLInputElement -> m Int
getMaxLength self
= liftIO (js_getMaxLength (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"min\"] = $2;" js_setMin ::
JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.min Mozilla HTMLInputElement.min documentation>
setMin ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setMin self val
= liftIO (js_setMin (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"min\"]" js_getMin ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.min Mozilla HTMLInputElement.min documentation>
getMin ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getMin self
= liftIO (fromJSString <$> (js_getMin (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"multiple\"] = $2;"
js_setMultiple :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.multiple Mozilla HTMLInputElement.multiple documentation>
setMultiple :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setMultiple self val
= liftIO (js_setMultiple (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"multiple\"] ? 1 : 0)"
js_getMultiple :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.multiple Mozilla HTMLInputElement.multiple documentation>
getMultiple :: (MonadIO m) => HTMLInputElement -> m Bool
getMultiple self
= liftIO (js_getMultiple (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName ::
JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.name Mozilla HTMLInputElement.name documentation>
setName ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setName self val
= liftIO (js_setName (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"name\"]" js_getName ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.name Mozilla HTMLInputElement.name documentation>
getName ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getName self
= liftIO (fromJSString <$> (js_getName (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"pattern\"] = $2;"
js_setPattern :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.pattern Mozilla HTMLInputElement.pattern documentation>
setPattern ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setPattern self val
= liftIO (js_setPattern (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"pattern\"]" js_getPattern ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.pattern Mozilla HTMLInputElement.pattern documentation>
getPattern ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getPattern self
= liftIO
(fromJSString <$> (js_getPattern (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"placeholder\"] = $2;"
js_setPlaceholder :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.placeholder Mozilla HTMLInputElement.placeholder documentation>
setPlaceholder ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setPlaceholder self val
= liftIO
(js_setPlaceholder (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"placeholder\"]"
js_getPlaceholder :: JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.placeholder Mozilla HTMLInputElement.placeholder documentation>
getPlaceholder ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getPlaceholder self
= liftIO
(fromJSString <$> (js_getPlaceholder (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"readOnly\"] = $2;"
js_setReadOnly :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.readOnly Mozilla HTMLInputElement.readOnly documentation>
setReadOnly :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setReadOnly self val
= liftIO (js_setReadOnly (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"readOnly\"] ? 1 : 0)"
js_getReadOnly :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.readOnly Mozilla HTMLInputElement.readOnly documentation>
getReadOnly :: (MonadIO m) => HTMLInputElement -> m Bool
getReadOnly self
= liftIO (js_getReadOnly (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"required\"] = $2;"
js_setRequired :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.required Mozilla HTMLInputElement.required documentation>
setRequired :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setRequired self val
= liftIO (js_setRequired (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"required\"] ? 1 : 0)"
js_getRequired :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.required Mozilla HTMLInputElement.required documentation>
getRequired :: (MonadIO m) => HTMLInputElement -> m Bool
getRequired self
= liftIO (js_getRequired (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"size\"] = $2;" js_setSize ::
JSRef HTMLInputElement -> Word -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.size Mozilla HTMLInputElement.size documentation>
setSize :: (MonadIO m) => HTMLInputElement -> Word -> m ()
setSize self val
= liftIO (js_setSize (unHTMLInputElement self) val)
foreign import javascript unsafe "$1[\"size\"]" js_getSize ::
JSRef HTMLInputElement -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.size Mozilla HTMLInputElement.size documentation>
getSize :: (MonadIO m) => HTMLInputElement -> m Word
getSize self = liftIO (js_getSize (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"src\"] = $2;" js_setSrc ::
JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.src Mozilla HTMLInputElement.src documentation>
setSrc ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setSrc self val
= liftIO (js_setSrc (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"src\"]" js_getSrc ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.src Mozilla HTMLInputElement.src documentation>
getSrc ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getSrc self
= liftIO (fromJSString <$> (js_getSrc (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"step\"] = $2;" js_setStep ::
JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.step Mozilla HTMLInputElement.step documentation>
setStep ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setStep self val
= liftIO (js_setStep (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"step\"]" js_getStep ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.step Mozilla HTMLInputElement.step documentation>
getStep ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getStep self
= liftIO (fromJSString <$> (js_getStep (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"type\"] = $2;" js_setType ::
JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.type Mozilla HTMLInputElement.type documentation>
setType ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setType self val
= liftIO (js_setType (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"type\"]" js_getType ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.type Mozilla HTMLInputElement.type documentation>
getType ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getType self
= liftIO (fromJSString <$> (js_getType (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"defaultValue\"] = $2;"
js_setDefaultValue ::
JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultValue Mozilla HTMLInputElement.defaultValue documentation>
setDefaultValue ::
(MonadIO m, ToJSString val) =>
HTMLInputElement -> Maybe val -> m ()
setDefaultValue self val
= liftIO
(js_setDefaultValue (unHTMLInputElement self)
(toMaybeJSString val))
foreign import javascript unsafe "$1[\"defaultValue\"]"
js_getDefaultValue ::
JSRef HTMLInputElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.defaultValue Mozilla HTMLInputElement.defaultValue documentation>
getDefaultValue ::
(MonadIO m, FromJSString result) =>
HTMLInputElement -> m (Maybe result)
getDefaultValue self
= liftIO
(fromMaybeJSString <$>
(js_getDefaultValue (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue
:: JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.value Mozilla HTMLInputElement.value documentation>
setValue ::
(MonadIO m, ToJSString val) =>
HTMLInputElement -> Maybe val -> m ()
setValue self val
= liftIO
(js_setValue (unHTMLInputElement self) (toMaybeJSString val))
foreign import javascript unsafe "$1[\"value\"]" js_getValue ::
JSRef HTMLInputElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.value Mozilla HTMLInputElement.value documentation>
getValue ::
(MonadIO m, FromJSString result) =>
HTMLInputElement -> m (Maybe result)
getValue self
= liftIO
(fromMaybeJSString <$> (js_getValue (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"valueAsDate\"] = $2;"
js_setValueAsDate :: JSRef HTMLInputElement -> JSRef Date -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsDate Mozilla HTMLInputElement.valueAsDate documentation>
setValueAsDate ::
(MonadIO m, IsDate val) => HTMLInputElement -> Maybe val -> m ()
setValueAsDate self val
= liftIO
(js_setValueAsDate (unHTMLInputElement self)
(maybe jsNull (unDate . toDate) val))
foreign import javascript unsafe "$1[\"valueAsDate\"]"
js_getValueAsDate :: JSRef HTMLInputElement -> IO (JSRef Date)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsDate Mozilla HTMLInputElement.valueAsDate documentation>
getValueAsDate :: (MonadIO m) => HTMLInputElement -> m (Maybe Date)
getValueAsDate self
= liftIO
((js_getValueAsDate (unHTMLInputElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"valueAsNumber\"] = $2;"
js_setValueAsNumber :: JSRef HTMLInputElement -> Double -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsNumber Mozilla HTMLInputElement.valueAsNumber documentation>
setValueAsNumber ::
(MonadIO m) => HTMLInputElement -> Double -> m ()
setValueAsNumber self val
= liftIO (js_setValueAsNumber (unHTMLInputElement self) val)
foreign import javascript unsafe "$1[\"valueAsNumber\"]"
js_getValueAsNumber :: JSRef HTMLInputElement -> IO Double
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.valueAsNumber Mozilla HTMLInputElement.valueAsNumber documentation>
getValueAsNumber :: (MonadIO m) => HTMLInputElement -> m Double
getValueAsNumber self
= liftIO (js_getValueAsNumber (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"width\"] = $2;" js_setWidth
:: JSRef HTMLInputElement -> Word -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.width Mozilla HTMLInputElement.width documentation>
setWidth :: (MonadIO m) => HTMLInputElement -> Word -> m ()
setWidth self val
= liftIO (js_setWidth (unHTMLInputElement self) val)
foreign import javascript unsafe "$1[\"width\"]" js_getWidth ::
JSRef HTMLInputElement -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.width Mozilla HTMLInputElement.width documentation>
getWidth :: (MonadIO m) => HTMLInputElement -> m Word
getWidth self = liftIO (js_getWidth (unHTMLInputElement self))
foreign import javascript unsafe "($1[\"willValidate\"] ? 1 : 0)"
js_getWillValidate :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.willValidate Mozilla HTMLInputElement.willValidate documentation>
getWillValidate :: (MonadIO m) => HTMLInputElement -> m Bool
getWillValidate self
= liftIO (js_getWillValidate (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"validity\"]" js_getValidity
:: JSRef HTMLInputElement -> IO (JSRef ValidityState)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.validity Mozilla HTMLInputElement.validity documentation>
getValidity ::
(MonadIO m) => HTMLInputElement -> m (Maybe ValidityState)
getValidity self
= liftIO ((js_getValidity (unHTMLInputElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"validationMessage\"]"
js_getValidationMessage :: JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.validationMessage Mozilla HTMLInputElement.validationMessage documentation>
getValidationMessage ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getValidationMessage self
= liftIO
(fromJSString <$>
(js_getValidationMessage (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"labels\"]" js_getLabels ::
JSRef HTMLInputElement -> IO (JSRef NodeList)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.labels Mozilla HTMLInputElement.labels documentation>
getLabels :: (MonadIO m) => HTMLInputElement -> m (Maybe NodeList)
getLabels self
= liftIO ((js_getLabels (unHTMLInputElement self)) >>= fromJSRef)
foreign import javascript unsafe "$1[\"selectionStart\"] = $2;"
js_setSelectionStart :: JSRef HTMLInputElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionStart Mozilla HTMLInputElement.selectionStart documentation>
setSelectionStart :: (MonadIO m) => HTMLInputElement -> Int -> m ()
setSelectionStart self val
= liftIO (js_setSelectionStart (unHTMLInputElement self) val)
foreign import javascript unsafe "$1[\"selectionStart\"]"
js_getSelectionStart :: JSRef HTMLInputElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionStart Mozilla HTMLInputElement.selectionStart documentation>
getSelectionStart :: (MonadIO m) => HTMLInputElement -> m Int
getSelectionStart self
= liftIO (js_getSelectionStart (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"selectionEnd\"] = $2;"
js_setSelectionEnd :: JSRef HTMLInputElement -> Int -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionEnd Mozilla HTMLInputElement.selectionEnd documentation>
setSelectionEnd :: (MonadIO m) => HTMLInputElement -> Int -> m ()
setSelectionEnd self val
= liftIO (js_setSelectionEnd (unHTMLInputElement self) val)
foreign import javascript unsafe "$1[\"selectionEnd\"]"
js_getSelectionEnd :: JSRef HTMLInputElement -> IO Int
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionEnd Mozilla HTMLInputElement.selectionEnd documentation>
getSelectionEnd :: (MonadIO m) => HTMLInputElement -> m Int
getSelectionEnd self
= liftIO (js_getSelectionEnd (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"selectionDirection\"] = $2;"
js_setSelectionDirection ::
JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionDirection Mozilla HTMLInputElement.selectionDirection documentation>
setSelectionDirection ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setSelectionDirection self val
= liftIO
(js_setSelectionDirection (unHTMLInputElement self)
(toJSString val))
foreign import javascript unsafe "$1[\"selectionDirection\"]"
js_getSelectionDirection :: JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.selectionDirection Mozilla HTMLInputElement.selectionDirection documentation>
getSelectionDirection ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getSelectionDirection self
= liftIO
(fromJSString <$>
(js_getSelectionDirection (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"align\"] = $2;" js_setAlign
:: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.align Mozilla HTMLInputElement.align documentation>
setAlign ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setAlign self val
= liftIO (js_setAlign (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"align\"]" js_getAlign ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.align Mozilla HTMLInputElement.align documentation>
getAlign ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getAlign self
= liftIO (fromJSString <$> (js_getAlign (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"useMap\"] = $2;"
js_setUseMap :: JSRef HTMLInputElement -> JSString -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.useMap Mozilla HTMLInputElement.useMap documentation>
setUseMap ::
(MonadIO m, ToJSString val) => HTMLInputElement -> val -> m ()
setUseMap self val
= liftIO (js_setUseMap (unHTMLInputElement self) (toJSString val))
foreign import javascript unsafe "$1[\"useMap\"]" js_getUseMap ::
JSRef HTMLInputElement -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.useMap Mozilla HTMLInputElement.useMap documentation>
getUseMap ::
(MonadIO m, FromJSString result) => HTMLInputElement -> m result
getUseMap self
= liftIO
(fromJSString <$> (js_getUseMap (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"incremental\"] = $2;"
js_setIncremental :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.incremental Mozilla HTMLInputElement.incremental documentation>
setIncremental :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setIncremental self val
= liftIO (js_setIncremental (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"incremental\"] ? 1 : 0)"
js_getIncremental :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.incremental Mozilla HTMLInputElement.incremental documentation>
getIncremental :: (MonadIO m) => HTMLInputElement -> m Bool
getIncremental self
= liftIO (js_getIncremental (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"autocorrect\"] = $2;"
js_setAutocorrect :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocorrect Mozilla HTMLInputElement.autocorrect documentation>
setAutocorrect :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setAutocorrect self val
= liftIO (js_setAutocorrect (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"autocorrect\"] ? 1 : 0)"
js_getAutocorrect :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocorrect Mozilla HTMLInputElement.autocorrect documentation>
getAutocorrect :: (MonadIO m) => HTMLInputElement -> m Bool
getAutocorrect self
= liftIO (js_getAutocorrect (unHTMLInputElement self))
foreign import javascript unsafe "$1[\"autocapitalize\"] = $2;"
js_setAutocapitalize ::
JSRef HTMLInputElement -> JSRef (Maybe JSString) -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocapitalize Mozilla HTMLInputElement.autocapitalize documentation>
setAutocapitalize ::
(MonadIO m, ToJSString val) =>
HTMLInputElement -> Maybe val -> m ()
setAutocapitalize self val
= liftIO
(js_setAutocapitalize (unHTMLInputElement self)
(toMaybeJSString val))
foreign import javascript unsafe "$1[\"autocapitalize\"]"
js_getAutocapitalize ::
JSRef HTMLInputElement -> IO (JSRef (Maybe JSString))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.autocapitalize Mozilla HTMLInputElement.autocapitalize documentation>
getAutocapitalize ::
(MonadIO m, FromJSString result) =>
HTMLInputElement -> m (Maybe result)
getAutocapitalize self
= liftIO
(fromMaybeJSString <$>
(js_getAutocapitalize (unHTMLInputElement self)))
foreign import javascript unsafe "$1[\"capture\"] = $2;"
js_setCapture :: JSRef HTMLInputElement -> Bool -> IO ()
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.capture Mozilla HTMLInputElement.capture documentation>
setCapture :: (MonadIO m) => HTMLInputElement -> Bool -> m ()
setCapture self val
= liftIO (js_setCapture (unHTMLInputElement self) val)
foreign import javascript unsafe "($1[\"capture\"] ? 1 : 0)"
js_getCapture :: JSRef HTMLInputElement -> IO Bool
-- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement.capture Mozilla HTMLInputElement.capture documentation>
getCapture :: (MonadIO m) => HTMLInputElement -> m Bool
getCapture self = liftIO (js_getCapture (unHTMLInputElement self)) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/HTMLInputElement.hs | mit | 47,804 | 708 | 11 | 7,604 | 9,559 | 4,992 | 4,567 | 694 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html
module Stratosphere.Resources.ElasticBeanstalkApplicationVersion where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.ElasticBeanstalkApplicationVersionSourceBundle
-- | Full data type definition for ElasticBeanstalkApplicationVersion. See
-- 'elasticBeanstalkApplicationVersion' for a more convenient constructor.
data ElasticBeanstalkApplicationVersion =
ElasticBeanstalkApplicationVersion
{ _elasticBeanstalkApplicationVersionApplicationName :: Val Text
, _elasticBeanstalkApplicationVersionDescription :: Maybe (Val Text)
, _elasticBeanstalkApplicationVersionSourceBundle :: ElasticBeanstalkApplicationVersionSourceBundle
} deriving (Show, Eq)
instance ToResourceProperties ElasticBeanstalkApplicationVersion where
toResourceProperties ElasticBeanstalkApplicationVersion{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::ElasticBeanstalk::ApplicationVersion"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ (Just . ("ApplicationName",) . toJSON) _elasticBeanstalkApplicationVersionApplicationName
, fmap (("Description",) . toJSON) _elasticBeanstalkApplicationVersionDescription
, (Just . ("SourceBundle",) . toJSON) _elasticBeanstalkApplicationVersionSourceBundle
]
}
-- | Constructor for 'ElasticBeanstalkApplicationVersion' containing required
-- fields as arguments.
elasticBeanstalkApplicationVersion
:: Val Text -- ^ 'ebavApplicationName'
-> ElasticBeanstalkApplicationVersionSourceBundle -- ^ 'ebavSourceBundle'
-> ElasticBeanstalkApplicationVersion
elasticBeanstalkApplicationVersion applicationNamearg sourceBundlearg =
ElasticBeanstalkApplicationVersion
{ _elasticBeanstalkApplicationVersionApplicationName = applicationNamearg
, _elasticBeanstalkApplicationVersionDescription = Nothing
, _elasticBeanstalkApplicationVersionSourceBundle = sourceBundlearg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-applicationname
ebavApplicationName :: Lens' ElasticBeanstalkApplicationVersion (Val Text)
ebavApplicationName = lens _elasticBeanstalkApplicationVersionApplicationName (\s a -> s { _elasticBeanstalkApplicationVersionApplicationName = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-description
ebavDescription :: Lens' ElasticBeanstalkApplicationVersion (Maybe (Val Text))
ebavDescription = lens _elasticBeanstalkApplicationVersionDescription (\s a -> s { _elasticBeanstalkApplicationVersionDescription = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-beanstalk-version.html#cfn-elasticbeanstalk-applicationversion-sourcebundle
ebavSourceBundle :: Lens' ElasticBeanstalkApplicationVersion ElasticBeanstalkApplicationVersionSourceBundle
ebavSourceBundle = lens _elasticBeanstalkApplicationVersionSourceBundle (\s a -> s { _elasticBeanstalkApplicationVersionSourceBundle = a })
| frontrowed/stratosphere | library-gen/Stratosphere/Resources/ElasticBeanstalkApplicationVersion.hs | mit | 3,311 | 0 | 15 | 307 | 364 | 210 | 154 | 37 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
#if __GLASGOW_HASKELL__ >= 802
-- Retain support for older compilers, assuming dependency versions which do too
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE StandaloneDeriving #-}
#endif
module TestSite (
User(..),
migrateAll,
App(..),
Route(..),
Handler,
runDB
) where
import Control.Monad (when)
import Data.Text
import Database.Persist.Sqlite
import Network.HTTP.Client.Conduit (Manager)
import Yesod
import Yesod.Auth
import Yesod.Auth.HashDB (HashDBUser(..), authHashDB,
submitRouteHashDB)
import Yesod.Auth.Message (AuthMessage (InvalidLogin))
-- Trivial example site needing authentication
--
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
User
name Text
password Text Maybe
UniqueUser name
deriving Show
|]
instance HashDBUser User where
userPasswordHash = userPassword
setPasswordHash h u = u { userPassword = Just h }
data App = App
{ appHttpManager :: Manager
, appDBConnection :: SqlBackend
}
#if !MIN_VERSION_yesod_core(1,6,0)
#define liftHandler lift
#define doRunDB runDB
getAppHttpManager :: App -> Manager
getAppHttpManager = appHttpManager
#else
#define doRunDB liftHandler $ runDB
getAppHttpManager :: (MonadHandler m, HandlerSite m ~ App) => m Manager
getAppHttpManager = appHttpManager <$> getYesod
#endif
mkYesod "App" [parseRoutes|
/ HomeR GET
/prot ProtectedR GET
/auth AuthR Auth getAuth
|]
instance Yesod App where
approot = ApprootStatic "http://localhost:3000"
authRoute _ = Just $ AuthR LoginR
isAuthorized ProtectedR _ = do
mu <- maybeAuthId
return $ case mu of
Nothing -> AuthenticationRequired
Just _ -> Authorized
-- Other pages (HomeR and AuthR _) do not require login
isAuthorized _ _ = return Authorized
-- CSRF middleware requires yesod-core-1.4.14, yesod-test >= 1.5 is
-- required so that tests can get at the token.
yesodMiddleware = defaultCsrfMiddleware . defaultYesodMiddleware
instance YesodPersist App where
type YesodPersistBackend App = SqlBackend
runDB action = do
master <- getYesod
runSqlConn action $ appDBConnection master
instance YesodAuth App where
type AuthId App = UserId
loginDest _ = HomeR
logoutDest _ = HomeR
authenticate creds = doRunDB $ do
x <- getBy $ UniqueUser $ credsIdent creds
case x of
Just (Entity uid _) -> return $ Authenticated uid
Nothing -> return $ UserError InvalidLogin
authPlugins _ = [ authHashDB (Just . UniqueUser) ]
authHttpManager = getAppHttpManager
loginHandler = do
submission <- submitRouteHashDB
render <- liftHandler getUrlRender
typedContent@(TypedContent ct _) <- selectRep $ do
provideRepType typeHtml $ return emptyContent
-- Dummy: the real Html version is at the end
provideJson $ object [("loginUrl", toJSON $ render submission)]
when (ct == typeJson) $
sendResponse typedContent -- Short-circuit JSON response
defaultLoginHandler -- Html response
instance YesodAuthPersist App
instance RenderMessage App FormMessage where
renderMessage _ _ = defaultFormMessage
getHomeR :: Handler Html
getHomeR = do
mauth <- maybeAuth
let mname = userName . entityVal <$> mauth
defaultLayout
[whamlet|
<p>Your current auth ID: #{show mname}
$maybe _ <- mname
<p>
<a href=@{AuthR LogoutR}>Logout
$nothing
<p>
<a href=@{AuthR LoginR}>Go to the login page
<p><a href=@{ProtectedR}>Go to protected page
|]
-- This page requires a valid login
getProtectedR :: Handler Html
getProtectedR = defaultLayout
[whamlet|
<p>OK, you are logged in so you are allowed to see this!
<p><a href=@{HomeR}>Go to home page
|]
| paul-rouse/yesod-auth-hashdb | test/TestSite.hs | mit | 4,580 | 0 | 17 | 1,327 | 722 | 394 | 328 | 84 | 1 |
module Problem02 (partA, partB) where
import Data.Monoid
import Text.Megaparsec
import Text.Megaparsec.String
inputLocation :: FilePath
inputLocation = "input/input02.txt"
data Offset = Negative | Neutral | Positive
deriving (Eq,Show,Enum,Ord)
instance Monoid Offset where
mempty = Neutral
mappend Negative Positive = Neutral
mappend Negative _ = Negative
mappend Positive Negative = Neutral
mappend Positive _ = Positive
mappend Neutral a = a
data Position = Position Offset Offset
deriving (Eq,Show)
instance Monoid Position where
mempty = Position mempty mempty
Position ax ay `mappend` Position bx by = Position (ax <> bx) (ay <> by)
positionToNumber :: Position -> Int
positionToNumber (Position Negative Negative) = 1
positionToNumber (Position Neutral Negative) = 2
positionToNumber (Position Positive Negative) = 3
positionToNumber (Position Negative Neutral ) = 4
positionToNumber (Position Neutral Neutral ) = 5
positionToNumber (Position Positive Neutral ) = 6
positionToNumber (Position Negative Positive) = 7
positionToNumber (Position Neutral Positive) = 8
positionToNumber (Position Positive Positive) = 9
parseInstruction :: Parser [[Position]]
parseInstruction = helper `sepBy` eol
where helper = many $ (Position Neutral Negative <$ char 'U')
<|> (Position Neutral Positive <$ char 'D')
<|> (Position Positive Neutral <$ char 'R')
<|> (Position Negative Neutral <$ char 'L')
partA :: IO ()
partA = readFile inputLocation >>= print . fmap (foldMap show . runA) . runParser parseInstruction ""
runA :: [[Position]] -> [Int]
runA = map positionToNumber . helper mempty . filter (not . null)
where helper _ [] = []
helper s (x : xs) = newS : helper newS xs
where newS = foldl mappend s x
data PositionB = PositionB Int Int
deriving (Eq,Show)
isValidGrid :: PositionB -> Bool
isValidGrid (PositionB x y) = abs x <= 2 && abs y <= helper (abs x)
where helper 0 = 2
helper 1 = 1
helper 2 = 0
movePosition :: PositionB -> (Int,Int) -> PositionB
movePosition p@(PositionB sx sy) (dx,dy) = if isValidGrid newPos then newPos else p
where newPos = PositionB (sx + dx) (sy + dy)
parseBInstructions :: Parser [[(Int,Int)]]
parseBInstructions = helper `sepBy` eol
where helper = many $ ((0,-1) <$ char 'U')
<|> ((0,1 ) <$ char 'D')
<|> ((1,0) <$ char 'R')
<|> ((-1,0) <$ char 'L')
gridBToNum :: PositionB -> Char
gridBToNum (PositionB 0 (-2)) = '1'
gridBToNum (PositionB (-1) (-1)) = '2'
gridBToNum (PositionB 0 (-1)) = '3'
gridBToNum (PositionB 1 (-1)) = '4'
gridBToNum (PositionB (-2) 0) = '5'
gridBToNum (PositionB (-1) 0) = '6'
gridBToNum (PositionB 0 0) = '7'
gridBToNum (PositionB 1 0) = '8'
gridBToNum (PositionB 2 0) = '9'
gridBToNum (PositionB (-1) 1) = 'A'
gridBToNum (PositionB 0 1) = 'B'
gridBToNum (PositionB 1 1) = 'C'
gridBToNum (PositionB 0 2) = 'D'
gridBToNum (PositionB x y) = error $ "Grid to num: " ++ show x ++ " " ++ show y
runB :: [[(Int,Int)]] -> [Char]
runB = map gridBToNum . helper (PositionB (-2) 0) . filter (not . null)
where helper _ [] = []
helper s (x : xs) = newS : helper newS xs
where newS = foldl movePosition s x
partB :: IO ()
partB = readFile inputLocation >>= print . fmap runB . runParser parseBInstructions ""
| edwardwas/adventOfCodeTwo | src/Problem02.hs | mit | 3,402 | 0 | 14 | 771 | 1,387 | 722 | 665 | 81 | 3 |
{-# LANGUAGE TypeSynonymInstances #-}
module Tasks.Cli.Types
(
SerProject (..)
, serProj
, serProjIndices
, serProjProject
, unserProj
, serProjects
, unserProjects
, exSerProject
, DBFormat(..)
, exDBFormat
, dbFormatSave
, (^||^)
, (^&&^)
) where
import Control.Monad
import Data.Binary
-- import qualified Data.ByteString as BW
import Data.List (elemIndex)
import System.Directory
import System.FilePath
import Tasks.Task
import Tasks.Project
-- SerProject (with project tasks removed when given) and
-- an array of integers representing the indexes of the tasks.
-- This way you can create a table of tasks at one central location, and
-- refer to them with ints otherwise
data SerProject = SerProject Project [Int] deriving (Show, Read, Eq)
instance Binary SerProject where
put (SerProject prj ints) = put prj >> put ints
get = do
prj <- get
ints <- get
return $ SerProject prj ints
serProj' :: [Task] -> [Task] -> [Int]
serProj' alltasks [] = []
serProj' [] ptasks = []
serProj' alltasks (pt:pts) = case pt `elemIndex` alltasks of
(Just idx) -> idx : serProj' alltasks pts
otherwise -> serProj' alltasks pts
-- serProject takes a project and a set of tasks, looking up the project's
-- tasks and building a list of ints representing the project's tasks respective
-- indexes in the passed task list
serProj :: Project -> [Task] -> SerProject
serProj prj [] = SerProject prj []
serProj prj@(Project { projectTasks = ptsks }) alltasks
| null ptsks = SerProject prjtskless []
| otherwise = SerProject prjtskless (serProj' alltasks ptsks)
where
prjtskless = prj { projectTasks = [] }
-- unserProj takes a serialized project and a set of coresponding tasks and
-- constructs the original project using it.
unserProj :: SerProject -> [Task] -> Project
unserProj (SerProject prj sints) alltasks =
prj { projectTasks = map (alltasks!!) sints }
-- serProjProject takes a serialized project and returns its contained project
serProjProject :: SerProject -> Project
serProjProject (SerProject prj _) = prj
-- serProjIndices takes a serialized project and returns its indexes
serProjIndices :: SerProject -> [Int]
serProjIndices (SerProject _ ints) = ints
serProjects :: [Project] -> [Task] -> [SerProject]
serProjects [] _ = []
serProjects _ [] = []
serProjects prjs tsks = map (flip serProj $ tsks) prjs
unserProjects :: [SerProject] -> [Task] -> [Project]
unserProjects [] _ = []
unserProjects _ [] = []
unserProjects sprjs tsks = map (flip unserProj $ tsks) sprjs
exSerProject = serProj exProject1 exTasks
encSerProject = encode exSerProject
decSerProject = (decode encSerProject) :: SerProject
-- Tasks at the beginning of the file, projects afterwards
data DBFormat = DBFormat [Task] [Project] deriving (Show, Read)
instance Binary DBFormat where
get = do
tasks <- get
serProjs <- get
return $ DBFormat tasks (unserProjects serProjs tasks)
put (DBFormat tasks projs) = do
put tasks
put (serProjects projs tasks)
exDBFormat = DBFormat exTasks exProjects
encDBFormat = encode exDBFormat
decDBFormat = (decode encDBFormat) :: DBFormat
-- Monadic boolean or, written to prevent unnecessary binding
(^||^) :: (Monad m) => m Bool -> m Bool -> m Bool
l ^||^ r = l >>= \lval ->
if lval == True then
return lval
else
r
-- Monadic boolean and, written to prevent unnecessary binding
(^&&^) :: (Monad m) => m Bool -> m Bool -> m Bool
l ^&&^ r = l >>= \lval ->
if lval == False then
return False
else
r
{-(^|||^) :: (Monad m) => (a -> Bool) -> m a -> (m a -> m a)
f ^|||^ m1 = -}
dbFormatSave :: DBFormat -> FilePath -> IO Bool
dbFormatSave (DBFormat tasks project) fp = do
fp <- fixedfp
dfe fp ^||^ validPerms perm
where
dfe fp = putStrLn "dfe" >> doesFileExist fp
fixedfp = canonicalizePath $ normalise fp -- normalize the path
perm = getPermissions fp
validPerms p = (liftM and) $ mapM (\f -> f p) (map liftM [readable, writable])
| BigEndian/tasks | tasks-cli/Tasks/Cli/Types.hs | gpl-2.0 | 4,077 | 0 | 11 | 890 | 1,143 | 606 | 537 | 90 | 2 |
{- Trabalho 2
Resp.: Rodrigo Ferreira Guimarães
Disc.: Linguaguem de Programação
Orie.: Rodrigo Bonifácio
Func.: Corpo de prova para a linguaguem F6LAE desenvolvida.
-}
module F6LAE_Tst where
{- Módulos necessários para a realização dos testes -}
import Test.HUnit
import F6LAE
{- Traduções semânticas para o desenvolvimento do teste -}
inter e1 = interp e1 [] []
inter1 e1 r1 = interp e1 r1 []
eval e1 = avaliar e1 [] []
eval1 e1 r1 = avaliar e1 r1 []
check e1 = checkTipo e1 [] []
check1 e1 r1 = checkTipo e1 r2 []
where r2 = map v2e r1
ref_0 = [("y", NumV 2)]
ref_1 = [("y", NumV 2), ("x", NumV 5)]
let_0 = Let "x" (Add (Num 2) (Num 3))
let_1 = Let "y" (Add (Ref "x") (Ref "x"))
let_2 = Let "z" (Sub (Ref "y") (Num 4))
let_3 = Let "w" (Num 3)
let_4 = Let "x" (Add (Num 10) (Num 5))
let_5 = Let "y" (Add (Ref "x") (Num 20))
let_6 = Let "x" (Num 5)
{- Retornos desejados para os testes a serem realizados -}
ret_0 = (NumV 3)
ava_0 = (Num 3)
ret_1 = (NumV 500)
ava_1 = (Add (Num 200) (Num 300))
ret_2 = (NumV 100)
ava_2 = (Sub (Num 300) (Num 200))
ret_3 = error "variable x not found"
ret_4 = (NumV 5)
ava_3 = (Ref "x")
ret_5 = NumV 8
ava_4 = let_0 (Num 8)
ret_6 = NumV 5
-- let x = 2 + 3 in x
ava_5 = let_0 (Ref "x")
ava_6 = let_0 (let_1 (Num 8))
ret_7 = NumV 10
ava_7 = let_0 (let_1 (Ref "y"))
ava_8 = let_0 (let_1 (let_2 (let_3 (Add (Ref "w") (Num 2)))))
ava_9 = let_0 (let_1 (let_2 (let_3 (Add (Ref "w") (Ref "x")))))
ava_10 = (IfZero (Num 0) (Num 8) (Num 5))
ret_8 = error "Erro de tipo"
ava_11 = (IfZero (Num 2) (Num 8) (Bool True))
ava_12 = (IfZero (Add (Num 200) (Bool True)) (Num 8) (Num 5))
ret_35 = NumV 40
ava_13 = let_4 (let_5 (let_6 (Add (Ref "y") (Ref "x"))))
{- Testes a serem realizados -}
tc_0 = TestCase (assertEqual "Num 003" ret_0 (inter ava_0))
tc_1 = TestCase (assertEqual "Num 500" ret_1 (inter ava_1))
tc_2 = TestCase (assertEqual "Num 100" ret_2 (inter ava_2))
tc_3 = TestCase (assertEqual "Err Ref" ret_3 (inter ava_3))
tc_4 = TestCase (assertEqual "Err Ref" ret_3 (inter1 ava_3 ref_0))
tc_5 = TestCase (assertEqual "Ref Num" ret_4 (inter1 ava_3 ref_1))
tc_6 = TestCase (assertEqual "Let Laz" ret_5 (inter ava_4))
tc_7 = TestCase (assertEqual "Let Laz" ret_6 (inter ava_5))
tc_8 = TestCase (assertEqual "Let Laz" ret_5 (inter ava_6))
tc_9 = TestCase (assertEqual "Let Laz" ret_7 (inter ava_7))
tc_10 = TestCase (assertEqual "Let Laz" ret_6 (inter ava_8))
tc_11 = TestCase (assertEqual "Let Laz" ret_5 (inter ava_9))
tc_12 = TestCase (assertEqual "IfZ Zer" ret_5 (inter ava_10))
tc_13 = TestCase (assertEqual "IfZ NZe" ret_8 (inter ava_11))
tc_14 = TestCase (assertEqual "IfZ NZe" ret_8 (inter ava_12))
tc_15 = TestCase (assertEqual "Let Laz" ret_8 (inter ava_13))
{- Compilação dos testes a serem executados -}
tc_todos = TestList (map (\tc -> (TestLabel "" tc)) [tc_0, tc_1,
tc_2, tc_3,
tc_4, tc_5,
tc_6, tc_7,
tc_8, tc_9,
tc_10, tc_11,
tc_12, tc_13,
tc_14, tc_15])
-- Realização dos testes
exeTst = runTestTT tc_todos
| rodrigofegui/UnB | 2017.2/Linguagens de Programação/Trab 2/F6LAE_Tst.hs | gpl-3.0 | 3,662 | 0 | 15 | 1,233 | 1,327 | 685 | 642 | 68 | 1 |
{-# LANGUAGE OverloadedStrings #-}
import Hakyll
main :: IO ()
main = hakyll $ do
match "assets/**" $ do
route idRoute
compile copyFileCompiler
match ("about.markdown" .||. "contact.markdown") $ do
route $ setExtension "html"
compile
$ pandocCompiler
>>= loadAndApplyTemplate "templates/page.html" context
>>= relativizeUrls
match "posts/*" $ do
route $ setExtension "html"
compile
$ pandocCompiler
>>= loadAndApplyTemplate "templates/post.html" context
>>= relativizeUrls
match "pages/index.html" $ do
route (constRoute "index.html")
compile $ do
posts <- recentFirst =<< loadAll "posts/*"
let indexCtx =
listField "posts" context (return posts)
<> constField "title" "Home"
<> context
<> defaultContext
getResourceBody
>>= applyAsTemplate indexCtx
>>= loadAndApplyTemplate "templates/default.html" indexCtx
>>= relativizeUrls
match ("includes/*" .||. "templates/*") $ compile templateCompiler
context :: Context String
context = authorCtx <> postCtx <> siteCtx
authorCtx :: Context String
authorCtx =
constField "author" "Vincibean"
<> constField "author_image" "../assets/img/Vincibean.jpeg"
<> constField "author_bio" ""
<> defaultContext
postCtx :: Context String
postCtx = dateField "date" "%B %e, %Y" <> defaultContext
siteCtx :: Context String
siteCtx =
constField "site_title" "Vincibean"
<> constField "site_logo" "../assets/img/icosaedron.svg"
<> constField "site_description" "Just a Bunch of Tips"
<> constField "site_cover" "../assets/img/geometric.jpg"
<> constField "page_url" "https://vincibean.github.io"
<> defaultContext
| Vincibean/Vincibean.github.io | site/site.hs | gpl-3.0 | 1,794 | 0 | 22 | 435 | 399 | 182 | 217 | 51 | 1 |
{---------------------------------------------------------------------}
{- Copyright 2015 Nathan Bloomfield -}
{- -}
{- This file is part of Feivel. -}
{- -}
{- Feivel is free software: you can redistribute it and/or modify -}
{- it under the terms of the GNU General Public License version 3, -}
{- as published by the Free Software Foundation. -}
{- -}
{- Feivel is distributed in the hope that it will be useful, but -}
{- WITHOUT ANY WARRANTY; without even the implied warranty of -}
{- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -}
{- GNU General Public License for more details. -}
{- -}
{- You should have received a copy of the GNU General Public License -}
{- along with Feivel. If not, see <http://www.gnu.org/licenses/>. -}
{---------------------------------------------------------------------}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
module Feivel.Eval.Expr (
evalToGlyph
) where
import Feivel.Eval.Util
import Feivel.Eval.ZZMod ()
import Feivel.Eval.Perm ()
import Feivel.Eval.Rat ()
import Feivel.Eval.Poly ()
import Feivel.Eval.Mat ()
import Feivel.Eval.Bool ()
import Feivel.Eval.Int ()
import Feivel.Eval.Mac ()
import Feivel.Eval.List ()
import Feivel.Eval.Str ()
import Feivel.Eval.Tuple ()
import Feivel.Eval.Doc (evalToGlyph)
instance Eval Expr where
eval (DocE x) = fmap toExpr $ eval x
eval (StrE x) = fmap toExpr $ eval x
eval (IntE x) = fmap toExpr $ eval x
eval (BoolE x) = fmap toExpr $ eval x
eval (RatE x) = fmap toExpr $ eval x
eval (ListE x) = fmap toExpr $ eval x
eval (MacE x) = fmap toExpr $ eval x
eval (MatE x) = fmap toExpr $ eval x
eval (PolyE x) = fmap toExpr $ eval x
eval (PermE x) = fmap toExpr $ eval x
eval (ZZModE x) = fmap toExpr $ eval x
eval (TupleE x) = fmap toExpr $ eval x
instance Glyph Expr where
toGlyph expr = case expr of
IntE x -> toGlyph x
StrE x -> toGlyph x
BoolE x -> toGlyph x
RatE x -> toGlyph x
ListE x -> toGlyph x
MatE x -> toGlyph x
DocE x -> toGlyph x
PolyE x -> toGlyph x
PermE x -> toGlyph x
ZZModE x -> toGlyph x
MacE x -> toGlyph x
TupleE x -> toGlyph x
| nbloomf/feivel | src/Feivel/Eval/Expr.hs | gpl-3.0 | 2,653 | 0 | 9 | 906 | 608 | 311 | 297 | 45 | 0 |
{-# LANGUAGE OverloadedStrings #-}
import Control.Monad
import Control.Applicative
import Data.Text (Text)
import qualified Data.Text.Lazy as DTL
import HSH (run)
import Network.Mail.Client.Gmail (sendGmail)
import Network.Mail.Mime
import System.Environment (getArgs)
import Data.String.Utils (split)
import GetParams
{-
- Lifted from getAllCommitHash oldestLine project
- is this LazyIO?
-
- TODO
- Put a provision to link all the commits to links in bitbucket repo
- -}
getChangeLog :: String -> Int -> IO [String]
getChangeLog repoPath numberOfHeads = do
content <- run $ "git -C " ++ repoPath ++ " --no-pager log --pretty=oneline --abbrev-commit" :: IO String
let changeLog = take numberOfHeads $ lines content
return changeLog
{-
- Takes username and from field from EmailParam and constructs an Address type data
- -}
formAddress :: Text -> LazyIntText -> Address
formAddress uname from = Address (Just uname) (DTL.toStrict from)
{-
- Format the entire md5sum output to look like this
- 123312657984.. FILENAME (without path prefix)
- -}
formatSum :: String -> String
formatSum md5sum = last (split "/" (wordsmd5 !! 1)) ++ " -> " ++ (wordsmd5 !! 0)
where wordsmd5 = words md5sum
{-
- Get the md5sum of the file
- Get it from terminal(quick and dirty) instead of using another library
- -}
getmd5sum :: FilePath -> IO String
getmd5sum file = do
md5sum <- run $ "md5sum " ++ file
return $ formatSum md5sum
{-
- Takes emailBody from EmailParam Data appends changeLog and returns it
-}
prepareBody :: EmailParam -> IO String
prepareBody param = do
changeLog <- getChangeLog (repoPath param) (nCommits param)
fileSums <- (liftM unlines) $ mapM getmd5sum (attachment param)
return $ (DTL.unpack.emailBody) param ++ "\nChangeLog:\n\n" ++ (foldl1 (\x y -> x ++ "\n" ++ y) changeLog) ++ "\n\nCHECKSUMS\n" ++ fileSums ++ "\n\n" ++ (signature param)
sendSingleMail :: EmailParam -> String -> LazyIntText -> IO()
sendSingleMail param emailContent toId = sendGmail (from param) (passwd param) (formAddress (uname param) (from param)) (map (formAddress "") [toId]) (map (formAddress "") (cc param)) [] (subject param) (DTL.pack emailContent) (attachment param) (timeout param)
{-
- Takes EmailParam data and plugs it in sendGmail function
- -}
emailBuild :: EmailParam -> IO()
emailBuild param = do
emailContent <- prepareBody param
mapM_ (sendSingleMail param emailContent) (to param)
main :: IO ()
main = do
-- The first argument is path to emailParam json file
args <- getArgs
-- Get JSON and decode
d <- getData (args !! 0)
emailBuild d
putStrLn "Emailed successfully.."
| manojgudi/email_builds | email_build.hs | gpl-3.0 | 2,671 | 0 | 17 | 504 | 717 | 365 | 352 | 42 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Logging.Projects.Locations.Operations.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Lists operations that match the specified filter in the request. If the
-- server doesn\'t support this method, it returns UNIMPLEMENTED.NOTE: the
-- name binding allows API services to override the binding to use
-- different resource name schemes, such as users\/*\/operations. To
-- override the binding, API services can add a binding such as
-- \"\/v1\/{name=users\/*}\/operations\" to their service configuration.
-- For backwards compatibility, the default name includes the operations
-- collection id, however overriding users must ensure the name binding is
-- the parent resource, without the operations collection id.
--
-- /See:/ <https://cloud.google.com/logging/docs/ Cloud Logging API Reference> for @logging.projects.locations.operations.list@.
module Network.Google.Resource.Logging.Projects.Locations.Operations.List
(
-- * REST Resource
ProjectsLocationsOperationsListResource
-- * Creating a Request
, projectsLocationsOperationsList
, ProjectsLocationsOperationsList
-- * Request Lenses
, plolXgafv
, plolUploadProtocol
, plolAccessToken
, plolUploadType
, plolName
, plolFilter
, plolPageToken
, plolPageSize
, plolCallback
) where
import Network.Google.Logging.Types
import Network.Google.Prelude
-- | A resource alias for @logging.projects.locations.operations.list@ method which the
-- 'ProjectsLocationsOperationsList' request conforms to.
type ProjectsLocationsOperationsListResource =
"v2" :>
Capture "name" Text :>
"operations" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "filter" Text :>
QueryParam "pageToken" Text :>
QueryParam "pageSize" (Textual Int32) :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
Get '[JSON] ListOperationsResponse
-- | Lists operations that match the specified filter in the request. If the
-- server doesn\'t support this method, it returns UNIMPLEMENTED.NOTE: the
-- name binding allows API services to override the binding to use
-- different resource name schemes, such as users\/*\/operations. To
-- override the binding, API services can add a binding such as
-- \"\/v1\/{name=users\/*}\/operations\" to their service configuration.
-- For backwards compatibility, the default name includes the operations
-- collection id, however overriding users must ensure the name binding is
-- the parent resource, without the operations collection id.
--
-- /See:/ 'projectsLocationsOperationsList' smart constructor.
data ProjectsLocationsOperationsList =
ProjectsLocationsOperationsList'
{ _plolXgafv :: !(Maybe Xgafv)
, _plolUploadProtocol :: !(Maybe Text)
, _plolAccessToken :: !(Maybe Text)
, _plolUploadType :: !(Maybe Text)
, _plolName :: !Text
, _plolFilter :: !(Maybe Text)
, _plolPageToken :: !(Maybe Text)
, _plolPageSize :: !(Maybe (Textual Int32))
, _plolCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsLocationsOperationsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'plolXgafv'
--
-- * 'plolUploadProtocol'
--
-- * 'plolAccessToken'
--
-- * 'plolUploadType'
--
-- * 'plolName'
--
-- * 'plolFilter'
--
-- * 'plolPageToken'
--
-- * 'plolPageSize'
--
-- * 'plolCallback'
projectsLocationsOperationsList
:: Text -- ^ 'plolName'
-> ProjectsLocationsOperationsList
projectsLocationsOperationsList pPlolName_ =
ProjectsLocationsOperationsList'
{ _plolXgafv = Nothing
, _plolUploadProtocol = Nothing
, _plolAccessToken = Nothing
, _plolUploadType = Nothing
, _plolName = pPlolName_
, _plolFilter = Nothing
, _plolPageToken = Nothing
, _plolPageSize = Nothing
, _plolCallback = Nothing
}
-- | V1 error format.
plolXgafv :: Lens' ProjectsLocationsOperationsList (Maybe Xgafv)
plolXgafv
= lens _plolXgafv (\ s a -> s{_plolXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
plolUploadProtocol :: Lens' ProjectsLocationsOperationsList (Maybe Text)
plolUploadProtocol
= lens _plolUploadProtocol
(\ s a -> s{_plolUploadProtocol = a})
-- | OAuth access token.
plolAccessToken :: Lens' ProjectsLocationsOperationsList (Maybe Text)
plolAccessToken
= lens _plolAccessToken
(\ s a -> s{_plolAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
plolUploadType :: Lens' ProjectsLocationsOperationsList (Maybe Text)
plolUploadType
= lens _plolUploadType
(\ s a -> s{_plolUploadType = a})
-- | The name of the operation\'s parent resource.
plolName :: Lens' ProjectsLocationsOperationsList Text
plolName = lens _plolName (\ s a -> s{_plolName = a})
-- | The standard list filter.
plolFilter :: Lens' ProjectsLocationsOperationsList (Maybe Text)
plolFilter
= lens _plolFilter (\ s a -> s{_plolFilter = a})
-- | The standard list page token.
plolPageToken :: Lens' ProjectsLocationsOperationsList (Maybe Text)
plolPageToken
= lens _plolPageToken
(\ s a -> s{_plolPageToken = a})
-- | The standard list page size.
plolPageSize :: Lens' ProjectsLocationsOperationsList (Maybe Int32)
plolPageSize
= lens _plolPageSize (\ s a -> s{_plolPageSize = a})
. mapping _Coerce
-- | JSONP
plolCallback :: Lens' ProjectsLocationsOperationsList (Maybe Text)
plolCallback
= lens _plolCallback (\ s a -> s{_plolCallback = a})
instance GoogleRequest
ProjectsLocationsOperationsList
where
type Rs ProjectsLocationsOperationsList =
ListOperationsResponse
type Scopes ProjectsLocationsOperationsList =
'["https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only",
"https://www.googleapis.com/auth/logging.admin",
"https://www.googleapis.com/auth/logging.read"]
requestClient ProjectsLocationsOperationsList'{..}
= go _plolName _plolXgafv _plolUploadProtocol
_plolAccessToken
_plolUploadType
_plolFilter
_plolPageToken
_plolPageSize
_plolCallback
(Just AltJSON)
loggingService
where go
= buildClient
(Proxy ::
Proxy ProjectsLocationsOperationsListResource)
mempty
| brendanhay/gogol | gogol-logging/gen/Network/Google/Resource/Logging/Projects/Locations/Operations/List.hs | mpl-2.0 | 7,535 | 0 | 19 | 1,667 | 984 | 575 | 409 | 141 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.OperatingSystems.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Retrieves a list of operating systems.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.operatingSystems.list@.
module Network.Google.Resource.DFAReporting.OperatingSystems.List
(
-- * REST Resource
OperatingSystemsListResource
-- * Creating a Request
, operatingSystemsList
, OperatingSystemsList
-- * Request Lenses
, oslProFileId
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.operatingSystems.list@ method which the
-- 'OperatingSystemsList' request conforms to.
type OperatingSystemsListResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"operatingSystems" :>
QueryParam "alt" AltJSON :>
Get '[JSON] OperatingSystemsListResponse
-- | Retrieves a list of operating systems.
--
-- /See:/ 'operatingSystemsList' smart constructor.
newtype OperatingSystemsList = OperatingSystemsList'
{ _oslProFileId :: Textual Int64
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'OperatingSystemsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oslProFileId'
operatingSystemsList
:: Int64 -- ^ 'oslProFileId'
-> OperatingSystemsList
operatingSystemsList pOslProFileId_ =
OperatingSystemsList'
{ _oslProFileId = _Coerce # pOslProFileId_
}
-- | User profile ID associated with this request.
oslProFileId :: Lens' OperatingSystemsList Int64
oslProFileId
= lens _oslProFileId (\ s a -> s{_oslProFileId = a})
. _Coerce
instance GoogleRequest OperatingSystemsList where
type Rs OperatingSystemsList =
OperatingSystemsListResponse
type Scopes OperatingSystemsList =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient OperatingSystemsList'{..}
= go _oslProFileId (Just AltJSON) dFAReportingService
where go
= buildClient
(Proxy :: Proxy OperatingSystemsListResource)
mempty
| rueshyna/gogol | gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/OperatingSystems/List.hs | mpl-2.0 | 3,077 | 0 | 13 | 675 | 320 | 194 | 126 | 52 | 1 |
{-# LANGUAGE OverloadedStrings, TypeFamilies #-}
module Model.Slot.Types
( SlotId(..)
, Slot(..)
, slotId
, containerSlotId
, containerSlot
, getSlotReleaseMaybe
) where
import Has (Has(..))
import Model.Id
import Model.Kind
import Model.Segment
import Model.Container.Types
import Model.Permission.Types
import Model.Release.Types
import Model.Volume.Types
data SlotId = SlotId
{ slotContainerId :: !(Id Container)
, slotSegmentId :: !Segment
} deriving (Eq, Show)
type instance IdType Slot = SlotId
containerSlotId :: Id Container -> Id Slot
containerSlotId c = Id $ SlotId c fullSegment
data Slot = Slot
{ slotContainer :: !Container
, slotSegment :: !Segment
}
{-
instance Show Slot where
show _ = "Slot"
-}
slotId :: Slot -> Id Slot
slotId (Slot c s) = Id $ SlotId (containerId (containerRow c)) s
containerSlot :: Container -> Slot
containerSlot c = Slot c fullSegment
instance Kinded Slot where
kindOf _ = "slot"
instance Has Container Slot where
view = slotContainer
instance Has Model.Permission.Types.Permission Slot where
view = view . slotContainer
instance Has Model.Volume.Types.Volume Slot where
view = view . slotContainer
instance Has (Maybe Model.Release.Types.Release) Slot where
view = view . slotContainer
instance Has (Id Container) Slot where
view = view . slotContainer
instance Has Segment Slot where
view = slotSegment
getSlotReleaseMaybe :: Slot -> Maybe Release
getSlotReleaseMaybe = containerRelease . slotContainer
| databrary/databrary | src/Model/Slot/Types.hs | agpl-3.0 | 1,496 | 0 | 11 | 256 | 431 | 240 | 191 | -1 | -1 |
-- -*-haskell-*-
-- GIMP Toolkit (GTK) Widget Scrollbar
--
-- Author : Axel Simon
--
-- Created: 15 May 2001
--
-- Copyright (C) 1999-2005 Axel Simon
--
-- This library is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- This library is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- Lesser General Public License for more details.
--
-- |
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable (depends on GHC)
--
-- Base class for 'Graphics.UI.Gtk.Scrolling.HScrollbar' and
-- 'Graphics.UI.Gtk.Scrolling.VScrollbar'
--
module Graphics.UI.Gtk.Abstract.Scrollbar (
-- * Detail
--
-- | The 'Scrollbar' widget is an abstract base class for
-- 'Graphics.UI.Gtk.Scrolling.HScrollbar' and
-- 'Graphics.UI.Gtk.Scrolling.VScrollbar'. It is not very useful in itself.
--
-- The position of the thumb in a scrollbar is controlled by the scroll
-- adjustments. See 'Graphics.UI.Gtk.Misc.Adjustment' for the fields in an
-- adjustment - for
-- 'Scrollbar', the \"value\" field represents the position of the scrollbar,
-- which must be between the \"lower\" field and \"upper - page_size.\" The
-- \"page_size\" field represents the size of the visible scrollable area. The
-- \"step_increment\" and \"page_increment\" fields are used when the user asks
-- to step down (using the small stepper arrows) or page down (using for
-- example the PageDown key).
-- * Class Hierarchy
-- |
-- @
-- | 'System.Glib.GObject'
-- | +----'Graphics.UI.Gtk.Abstract.Object'
-- | +----'Graphics.UI.Gtk.Abstract.Widget'
-- | +----'Graphics.UI.Gtk.Abstract.Range'
-- | +----Scrollbar
-- | +----'Graphics.UI.Gtk.Scrolling.HScrollbar'
-- | +----'Graphics.UI.Gtk.Scrolling.VScrollbar'
-- @
-- * Types
Scrollbar,
ScrollbarClass,
castToScrollbar,
toScrollbar,
) where
import Graphics.UI.Gtk.Types (Scrollbar, ScrollbarClass,
castToScrollbar, toScrollbar)
| thiagoarrais/gtk2hs | gtk/Graphics/UI/Gtk/Abstract/Scrollbar.hs | lgpl-2.1 | 2,370 | 0 | 5 | 479 | 99 | 85 | 14 | 7 | 0 |
module HEP.Jet.FastJet.Class.GhostedAreaSpec where
| wavewave/HFastJet | oldsrc/HEP/Jet/FastJet/Class/GhostedAreaSpec.hs | lgpl-2.1 | 53 | 0 | 3 | 5 | 9 | 7 | 2 | 1 | 0 |
import Test.HUnit
import P9x.P00.P00_
import Data.List(nub)
import System.Random(setStdGen, mkStdGen)
import P9x.Util(doExpectEqual)
main :: IO Counts
main = do
(\f -> doExpectEqual "P01" 8 (f [1, 1, 2, 3, 5, 8])) `mapM_`
[myLast', myLast'', myLast''', myLast'''', myLast''''']
(\f -> doExpectEqual "P02" 5 (f [1, 1, 2, 3, 5, 8])) `mapM_`
[myButLast, myButLast', myButLast'', myButLast''', myButLast'''', lastbut1]
doExpectEqual "P02" (Just 5) (lastbut1safe [1, 1, 2, 3, 5, 8])
(\f -> doExpectEqual "P03" 2 (f 2 [1, 1, 2, 3, 5, 8])) `mapM_`
[elementAt, elementAt', elementAt'', elementAt''', elementAt_w'pf]
(\f -> doExpectEqual "P04" 6 (f [1, 1, 2, 3, 5, 8])) `mapM_`
[myLength, myLength1', myLength2', myLength3', myLength4', myLength5', myLength6', myLength1'', myLength2'', myLength3'']
(\f -> doExpectEqual "P05" [8, 5, 3, 2, 1, 1] (f [1, 1, 2, 3, 5, 8])) `mapM_`
[reverse', reverse'', reverse''', reverse'''']
let isPalindromFunctions = [isPalindrome, isPalindrome'1, isPalindrome'2, isPalindrome'3,
isPalindrome'4, isPalindrome'5, isPalindrome'6, isPalindrome'7] :: [[Int] -> Bool]
(\f -> doExpectEqual "P06" False (f [1, 2, 3, 4, 5])) `mapM_` isPalindromFunctions
(\f -> doExpectEqual "P06" True (f [1, 2, 3, 2, 1])) `mapM_` isPalindromFunctions
let flattenFunctions = [flatten, flatten', flatten'2, flatten'3, flatten'4, flatten'5, flatten'6]
(\f -> doExpectEqual "P07" [1, 2] (f $ List[Elem 1, Elem 2])) `mapM_` flattenFunctions
(\f -> doExpectEqual "P07" [1, 2, 3] (f $ List[nestedList [1, 2], Elem 3])) `mapM_` flattenFunctions
(\f -> doExpectEqual "P07" [1, 2, 3] (f $ List[List[Elem 1, Elem 2], List[Elem 3]])) `mapM_` flattenFunctions
let compressFunctions = [compress, compress', compress'2, compress'3, compress'4, compress'5, compress'6, compress'7] :: [[Char] -> [Char]]
(\f -> doExpectEqual "P08" "abcade" (f "aaaabccaadeeee")) `mapM_` compressFunctions
let packFunctions = [pack, pack', pack'2, pack'3, pack'4, pack'5]
(\f -> doExpectEqual "P09" ["aaaa", "b", "cc", "aa", "d", "eeee"] (f "aaaabccaadeeee")) `mapM_` packFunctions
let encodeFunctions = [encode, encode', encode'2, encode'3, encode'4, encode'5, encode'6, encode'7]
(\f -> doExpectEqual "P10" [(4,'a'), (1,'b'), (2,'c'), (2,'a'), (1,'d'), (4,'e')] (f "aaaabccaadeeee")) `mapM_` encodeFunctions
let encodeModifiedFunctions = [encodeModified, encodeModified'] :: Eq a => [[a] -> [ListItem a]]
(\f -> doExpectEqual "P11"
[Multiple 4 'a', Single 'b', Multiple 2 'c', Multiple 2 'a', Single 'd', Multiple 4 'e']
(f "aaaabccaadeeee")) `mapM_` encodeModifiedFunctions
let decodeFunctions = [decode, decode', decode'2] :: Eq a => [[(Int, a)] -> [a]]
(\f -> doExpectEqual "P12" "aaaabccaadeeee"
(f [(4, 'a'), (1, 'b'), (2, 'c'), (2, 'a'), (1, 'd'), (4, 'e')]))
`mapM_` decodeFunctions
let decodeModifiedFunctions = [decodeModified, decodeModified', decodeModified'2, decodeModified'3]
(\f -> doExpectEqual "P12"
"aaaabccaadeeee"
(f [Multiple 4 'a', Single 'b', Multiple 2 'c', Multiple 2 'a', Single 'd', Multiple 4 'e']))
`mapM_` decodeModifiedFunctions
let encodeDirectFunctions = [encodeDirect, encodeDirect']
(\f -> doExpectEqual "P13"
[Multiple 4 'a', Single 'b', Multiple 2 'c', Multiple 2 'a', Single 'd', Multiple 4 'e']
(f "aaaabccaadeeee")) `mapM_` encodeDirectFunctions
let duplicateFunctions = [dupli, dupli', dupli'2, dupli'3, dupli'4, dupli'5, dupli'6, dupli'7, dupli'8, dupli'9]
(\f -> doExpectEqual "P14" "aabbccccdd" (f "abccd")) `mapM_` duplicateFunctions
let replicateFunctions = [repli, repli', repli'2, repli'3]
(\f -> doExpectEqual "P15" "aaabbbccccccddd" (f "abccd" 3)) `mapM_` replicateFunctions
let dropEveryFunctions = [dropEvery, dropEvery', dropEvery'2, dropEvery'3, dropEvery'4, dropEvery'5, dropEvery'6, dropEvery'7, dropEvery'8, dropEvery'9, dropEvery'10]
(\f -> doExpectEqual "P16" "abdeghjk" (f "abcdefghijk" 3)) `mapM_` dropEveryFunctions
let splitFunctions = [split, split', split'2, split'3, split'4, split'5, split'6, split'7]
(\f -> doExpectEqual "P17" ("abc", "defghijk") (f "abcdefghijk" 3)) `mapM_` splitFunctions
let sliceFunctions = [slice, slice'2, slice'3, slice'4, slice'5, slice'6]
(\f -> doExpectEqual "P18" "cdefg" (f "abcdefghijk" 3 7)) `mapM_` sliceFunctions
let rotateFunctions = [rotate, rotate', rotate'2, rotate'3, rotate'4, rotate'5, rotate'6, rotate'7]
(\f -> doExpectEqual "P19" "defghijkabc" (f "abcdefghijk" 3)) `mapM_` rotateFunctions
let removeAtFunctions = [removeAt, removeAt', removeAt'2, removeAt'3, removeAt'4]
(\f -> doExpectEqual "P20" ('b', "acd") (f 1 "abcd")) `mapM_` removeAtFunctions
let insertAtFunctions = [insertAt, insertAt', insertAt'', insertAt''']
(\f -> doExpectEqual "P21" ("a!bcd") (f '!' "abcd" 1)) `mapM_` insertAtFunctions
let rangeFunctions = [range, range2, range3, range4, range5, range6]
(\f -> doExpectEqual "P22" [] (f 4 3)) `mapM_` rangeFunctions
(\f -> doExpectEqual "P22" [4] (f 4 4)) `mapM_` rangeFunctions
(\f -> doExpectEqual "P22" [4, 5, 6, 7, 8, 9] (f 4 9)) `mapM_` rangeFunctions
let randomSelectFunctionsIO = [rnd_select, rnd_select2, rnd_select3, rnd_select4, rnd_select5]
(\f ->
do setStdGen $ mkStdGen 234
result <- f [1,2,3,4,5] 3
let desc = "P23 IO" ++ (show result)
doExpectEqual desc 3 (length result)
doExpectEqual desc True (all (\it -> it>=1 && it<=5) result)
-- It's not clear from the problem description if selected elements have to be unique.
-- The above solutions return non-unique results.
-- doExpectEqual desc True ((length $ nub result) == length result)
) `mapM_` randomSelectFunctionsIO
-- skip diff_select2 because it uses rnd_select which doesn't return unique numbers
-- skip diff_select3 because it doesn't return unique numbers
-- skip diff_select4,5 because of different function type and non-unique result
let diffSelectFunctionsIO = [diff_select]
(\f ->
do setStdGen $ mkStdGen 234
result <- f 3 10
let desc = "P24 IO " ++ (show result)
doExpectEqual desc 3 (length result)
doExpectEqual desc True (all (\it -> it>=1 && it<=10) result)
doExpectEqual desc True ((length $ nub result) == length result)
) `mapM_` diffSelectFunctionsIO
let rndPermFunctionsIO = [rnd_perm2, rnd_perm3, rnd_perm4]
(\f ->
do setStdGen $ mkStdGen 123
result <- f [1,2,3,4]
let desc = "P25 IO" ++ (show result)
doExpectEqual desc 4 (length result)
doExpectEqual desc True (all (\it -> it>=1 && it<=4) result)
doExpectEqual desc True ((length $ nub result) == length result)
) `mapM_` rndPermFunctionsIO
let combinationFunctions = [combinations, combinations2, combinations3, combinations4,
combinations5, combinations6, combinations7]
(\f ->
do doExpectEqual "P26" [[]] (f 0 "")
doExpectEqual "P26" ["a", "b", "c"] (f 1 "abc")
doExpectEqual "P26" ["ab", "ac", "bc"] (f 2 "abc")
doExpectEqual "P26" ["abc"] (f 3 "abc")
) `mapM_` combinationFunctions
let groupFunctions = [groupSubsets, groupSubsets2, groupSubsets3]
(\f ->
do doExpectEqual "P27" [[]] (f [] "")
doExpectEqual "P27" [] (f [1] "")
doExpectEqual "P27" [["a"]] (f [1] "a")
doExpectEqual "P27" [["a"], ["b"]] (f [1] "ab")
doExpectEqual "P27" [["a", "b"], ["b", "a"]] (f [1, 1] "ab")
) `mapM_` groupFunctions
let lengthSortFunctions = [lsort, lsort2, lsort3, lsort4]
(\f ->
do doExpectEqual "P28a"
["o", "de", "de", "mn", "abc", "fgh", "ijkl"]
(f ["abc", "de", "fgh", "de", "ijkl", "mn", "o"])
) `mapM_` lengthSortFunctions
let lengthFrequencySortFunctions = [lfsort, lfsort2, lfsort3, lfsort4, lfsort5]
(\f ->
do doExpectEqual "P28b"
["o", "abc", "fgh", "de", "de", "mn"]
(f ["abc", "de", "fgh", "de", "mn", "o"])
) `mapM_` lengthFrequencySortFunctions
let primeFunctions = [isPrime]
let primeTest f = doExpectEqual "P31" expected actual
where expected = [(1,False),(2,True),(3,True),(4,False),(5,True),
(6,False),(7,True),(8,False),(9,False),(10,False)]
actual = map (\it -> (it, f it)) [1..10]
primeTest `mapM_` primeFunctions
let gcdFunctions = [myGCD, myGCD2]
let gcdResults = [ (1, 1, 1), (2, 4, 2), (4, 2, 2), (-10, 5, 5) ]
(\f ->
do doExpectEqual "P32" gcdResults
(map (\(n1, n2, _) -> (n1, n2, f n1 n2)) gcdResults)
) `mapM_` gcdFunctions
doExpectEqual "P33" True (coprime 1 1)
doExpectEqual "P33" True (coprime 1 2)
doExpectEqual "P33" True (coprime 4 9)
doExpectEqual "P33" False (coprime 4 6)
-- TODO P34
let totientFunctions = [totient, totient2, totient3]
let totientResults = [1,2,2,4,2,6,4,6,4,10,4,12,6,8,8,16,6,18,8]
(\f ->
do doExpectEqual "P34" totientResults (map f [2..20])
) `mapM_` totientFunctions
-- TODO P35
return $ (Counts 0 0 0 0)
| dkandalov/katas | haskell/p99/src/p9x/p00/P00_Test.hs | unlicense | 9,449 | 0 | 19 | 2,181 | 3,686 | 2,068 | 1,618 | 145 | 1 |
module TrmX_ActionsTest where
import Test.Hspec
import TrmX
import TrmX_Actions
import qualified Data.Map as M
import qualified Data.Set as S
main :: IO ()
main = hspec $ do
describe "TrmX_Actions" $ do
describe "prmComp" $ do
it "returns a composition of a pair of permutations p1 p2 such that p1.p2 and applied from lhs to rhs" $
prmComp [("a", "b")] [("a" ,"c"),("d" ,"e")] `shouldBe` ([("a" ,"b"),("a" ,"c"),("d" ,"e")]::Prm)
describe "prmAtmApp" $ do
it "applies a permutation to an atom" $
prmAtmApp [("a" ,"c"),("c" ,"e")] "a" `shouldBe` ("e"::Atm)
describe "prmAsbApp" $ do
context "when provided with an empty mapping of atm substitutions" $ do
it " it returns the empty mapping" $
prmAsbApp [("a" ,"c"),("d" ,"e")] (M.fromList ([])) `shouldBe` (M.fromList ([]))
context "when provided with an empty permutation" $ do
it " it returns the mapping without identity mappings" $
prmAsbApp [] (M.fromList ([("a",AtmTrm "a"),("b",AtmTrm "c")])) `shouldBe` (M.fromList ([("b",AtmTrm "c")]))
context "when provided with a permutation and a mapping" $ do
it " it returns the permuted mapping without identity mappings" $
prmAsbApp [("a" ,"c"),("d" ,"e")] (M.fromList ([("a",AtmTrm "a"),("c",AtmTrm "d")])) `shouldBe` (M.fromList ([("a",AtmTrm "e")]))
describe "prmTrmApp" $ do
it "applies a permutation to a term; identity mappings of atm substitutions are removed" $
prmTrmApp [("a" ,"c"),("c" ,"e")] (AppTrm "f" (TplTrm [AtmTrm "a", AbsTrm "c" (VarTrm (M.fromList ([("a",AtmTrm "a"),("c",AtmTrm "e")])) [("a", "b")] "X")])::Trm) `shouldBe`(AppTrm "f" (TplTrm [AtmTrm "e", AbsTrm "a" (VarTrm (M.fromList ([("a",AtmTrm "c")])) [("a", "b"),("a" ,"c"),("c" ,"e")] "X")])::Trm)
describe "prmSupp" $ do
it "returns the support of a permutation p, ie., {a | p(a) /= a, a <- p}." $
prmSupp [("c","e"),("a","a"),("b" ,"d"),("c" ,"e")] `shouldBe` (S.fromList ["b","d"])
describe "prmDs" $ do
it "Returns the Difference Set between a pair of permutations, that is, for permutations p,p' and atom a, if p(a)=b and p'(a)=c, for any two distinct atoms b,c, then atom a is in their Difference set." $
prmDs [("c","e"),("e" ,"d")] [("c","d"), ("e","f")] `shouldBe` (S.fromList ["d","e","f"])
describe "aSbDom" $ do
it "Returns the set of atoms in the domain of atm subst mappings; excludes identity mappings." $
aSbDom (M.fromList ([("a",AtmTrm "a"),("c",AtmTrm "d")])) `shouldBe` (S.fromList ["c"])
describe "aSbImg" $ do
it "Returns the image of atm subst mappings; excludes identity mappings." $
aSbImg (M.fromList ([("a",AtmTrm "a"),("b",AtmTrm "d"), ("c",AbsTrm "d" (AtmTrm "c"))])) `shouldBe` (S.fromList [AtmTrm "d", AbsTrm "d" (AtmTrm "c")])
describe "atmActDom" $ do
it "Returns the set of atoms in the domain; excludes identity mappings." $
atmActDom (M.fromList ([("a",AtmTrm "a"),("c",AtmTrm "d")])) [("c","e"),("a","a"),("b" ,"d"),("c" ,"e")] `shouldBe` (S.fromList ["c","b","d"])
describe "ctxGen" $ do
it "Generates a freshness context given a set of atoms and a set of variables." $
ctxGen (S.fromList (["a","b"])) (S.fromList (["X","Y"])) `shouldBe` (S.fromList [("a","X"), ("b", "X" ), ("a","Y"), ("b","Y")])
| susoDominguez/eNominalTerms-Alpha | TrmX_ActionsTest.hs | unlicense | 3,470 | 0 | 30 | 795 | 1,292 | 716 | 576 | 46 | 1 |
-- (**) Rotate a list N places to the left.
--
-- Hint: Use the predefined functions length and (++).
--
-- Examples:
--
-- * (rotate '(a b c d e f g h) 3)
-- (D E F G H A B C)
--
-- * (rotate '(a b c d e f g h) -2)
-- (G H A B C D E F)
-- Examples in Haskell:
--
-- *Main> rotate ['a','b','c','d','e','f','g','h'] 3
-- "defghabc"
--
-- *Main> rotate ['a','b','c','d','e','f','g','h'] (-2)
-- "ghabcdef"
rotate :: [a] -> Int -> [a]
rotate xs n
| n >= 0 = snd slice ++ fst slice
| otherwise = rotate xs (length xs + n)
where
slice = splitAt n xs
| tiann/haskell-learning | haskell99/p19/main.hs | apache-2.0 | 561 | 0 | 9 | 138 | 104 | 59 | 45 | 5 | 1 |
module Problem063 where
main =
print $ length [n | b <- [1 .. 9], p <- ps, let n = b ^ p, length (show n) == p]
where ps = takeWhile (\p -> length (show (9 ^ p)) >= p) [1 ..]
| vasily-kartashov/playground | euler/problem-063.hs | apache-2.0 | 181 | 0 | 15 | 50 | 116 | 62 | 54 | 4 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
import Data.List
class Foo a where
foo :: a -> String
-- Now will error due to the compiler don't know which one to call between
-- String and [char]
instance (Foo a) => Foo [a] where
foo = concat . intersperse ", " . map foo
instance Foo Char where
foo c = [c]
instance Foo String where
foo = id
| EricYT/Haskell | src/chapter-6-4.hs | apache-2.0 | 375 | 0 | 8 | 88 | 98 | 52 | 46 | 10 | 0 |
--------------------------------------------------------------------------------
-- |
-- Module : Network.SimpleIRC.Core.Lens
-- Copyright : (C) 2014 Ricky Elrod
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Ricky Elrod <[email protected]>
-- Stability : provisional
-- Portability : portable
--
-- This module provides lenses for types in
-- <https://hackage.haskell.org/package/simpleirc/docs/Network-SimpleIRC-Core.html Network.SimpleIRC.Core>.
-------------------------------------------------------------------------------
module Network.SimpleIRC.Core.Lens
( -- * 'IrcConfig'
addr, port, secure, nick, pass, username, realname, channels, events,
ctcpVersion, ctcpTime, ctcpPingTimeoutInterval
) where
import Network.SimpleIRC.Core
addr
:: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig
addr fn (IrcConfig a b c d e f g h i j k l) =
fmap (\a' -> IrcConfig a' b c d e f g h i j k l) (fn a)
port :: Functor f => (Int -> f Int) -> IrcConfig -> f IrcConfig
port fn (IrcConfig a b c d e f g h i j k l) =
fmap (\b' -> IrcConfig a b' c d e f g h i j k l) (fn b)
secure :: Functor f => (Bool -> f Bool) -> IrcConfig -> f IrcConfig
secure fn (IrcConfig a b c d e f g h i j k l) =
fmap (\c' -> IrcConfig a b c' d e f g h i j k l) (fn c)
nick
:: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig
nick fn (IrcConfig a b c d e f g h i j k l) =
fmap (\d' -> IrcConfig a b c d' e f g h i j k l) (fn d)
pass
:: Functor f =>
(Maybe String -> f (Maybe String)) -> IrcConfig -> f IrcConfig
pass fn (IrcConfig a b c d e f g h i j k l) =
fmap (\e' -> IrcConfig a b c d e' f g h i j k l) (fn e)
username
:: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig
username fn (IrcConfig a b c d e f g h i j k l) =
fmap (\f' -> IrcConfig a b c d e f' g h i j k l) (fn f)
realname
:: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig
realname fn (IrcConfig a b c d e f g h i j k l) =
fmap (\g' -> IrcConfig a b c d e f g' h i j k l) (fn g)
channels
:: Functor f =>
([String] -> f [String]) -> IrcConfig -> f IrcConfig
channels fn (IrcConfig a b c d e f g h i j k l) =
fmap (\h' -> IrcConfig a b c d e f g h' i j k l) (fn h)
events
:: Functor f =>
([IrcEvent] -> f [IrcEvent]) -> IrcConfig -> f IrcConfig
events fn (IrcConfig a b c d e f g h i j k l) =
fmap (\i' -> IrcConfig a b c d e f g h i' j k l) (fn i)
ctcpVersion
:: Functor f => (String -> f String) -> IrcConfig -> f IrcConfig
ctcpVersion fn (IrcConfig a b c d e f g h i j k l) =
fmap (\j' -> IrcConfig a b c d e f g h i j' k l) (fn j)
ctcpTime
:: Functor f =>
(IO String -> f (IO String)) -> IrcConfig -> f IrcConfig
ctcpTime fn (IrcConfig a b c d e f g h i j k l) =
fmap (\k' -> IrcConfig a b c d e f g h i j k' l) (fn k)
ctcpPingTimeoutInterval
:: Functor f => (Int -> f Int) -> IrcConfig -> f IrcConfig
ctcpPingTimeoutInterval fn (IrcConfig a b c d e f g h i j k l) =
fmap (\l' -> IrcConfig a b c d e f g h i j k l') (fn l)
| relrod/simpleirc-lens | src/Network/SimpleIRC/Core/Lens.hs | bsd-2-clause | 3,054 | 0 | 11 | 781 | 1,475 | 748 | 727 | 55 | 1 |
import Prelude
data Encoded a = Single a | Multiple Int a
deriving Show
encodeDirect :: Eq a => [a] -> [Encoded a]
encodeDirect [] = []
encodeDirect xs = foldr (append) [] xs
where
append y [] = [Single y]
append y ((Single z):zs)
| (y == z) = (Multiple 2 z):zs
| otherwise = (Single y):(Single z):zs
append y ((Multiple n z):zs)
| (y == z) = (Multiple (n + 1) z):zs
| otherwise = (Single y):(Multiple n z):zs
| 2dor/99-problems-Haskell | 11-20-lists-continued/problem-13.hs | bsd-2-clause | 492 | 0 | 12 | 163 | 266 | 135 | 131 | 13 | 3 |
{-# LANGUAGE OverloadedStrings, ViewPatterns #-}
import qualified Prelude as P
import BasicPrelude
import Filesystem.Path.CurrentOS (decodeString)
import System.Environment (getArgs)
import qualified Data.Text.Encoding as T
import qualified Data.Ini.Reader as Ini
import Data.Conduit.Network (runTCPServer, serverSettings, HostPreference(HostAny), serverNeedLocalAddr)
import Network.HTTP.Conduit
import qualified Network.Aliyun as Ali
import Network.FTP.Server
import Network.FTP.Backend.Cloud
main = do
[P.read -> port, path] <- getArgs
conf <- loadCloudConf path
let serverConf = (serverSettings port HostAny){serverNeedLocalAddr=True}
runCloudBackend conf $ runTCPServer serverConf ftpServer
| yihuang/cloud-ftp | Main.hs | bsd-3-clause | 715 | 0 | 12 | 89 | 175 | 106 | 69 | 17 | 1 |
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ConstraintKinds #-}
module Types where
import Util
import Network
import Vector
import Static
import Static.Image
import Network.Label
import Data.Singletons.Prelude
import Data.Singletons.TypeLits
import Data.Singletons.Prelude.List
import Data.Serialize
import Conduit
class Pretty a where
pretty :: a -> String
-- | A GameState is a data type that fully describes a games' state.
class ( KnownSymbol (Title g)
, KnownNat (ScreenWidth g)
, KnownNat (ScreenHeight g)
, Show g, Pretty g
) => GameState g where
label :: g -> LabelVec g
delabel :: LabelVec g -> g
rootDir :: Path g
parse :: Path g -> LabelVec g
type Title g :: Symbol
type ScreenWidth g :: Nat -- ^ The width of a screen of this game in pixels.
-- This value and the height are mostly used to
-- scale the positions and dimensions of widgets
type ScreenHeight g :: Nat
type Widgets g :: [*]
class ( KnownNat (Height w), KnownNat (Width w), KnownNat (Length (Positions w))
, KnownNat (ScreenWidth (Parent w)), KnownNat (ScreenHeight (Parent w))
, KnownNat (Sum (DataShape w)), KnownNat ((Sum (DataShape w)) :* (Length (Positions w)))
, SingI (Positions w), Measure (InputShape w)
, SingI (DataShape w)
, KnownNat (SampleWidth w)
, KnownNat (SampleHeight w)
, KnownNat (Length (Positions w) :* SampleWidth w)
, (NOutput (Network (InputShape w) (NetConfig w))) ~ (ZZ ::. Length (Positions w) ::. Sum (DataShape w))
) => Widget w where
toLabel :: w -> WLabel w
fromLabel :: LabelParser w
params :: Params w
-- Widget description
type Positions w :: [(Nat, Nat)]
type DataShape w :: [Nat]
type Width w :: Nat
type Height w :: Nat
type Parent w :: *
-- Widget classifier configuration
type SampleWidth w :: Nat
type SampleHeight w :: Nat
type NetConfig w :: [*]
newtype Params w = Params LearningParameters
type InputShape w = ZZ ::. Length (Positions w) ::. 3 ::. SampleHeight w ::. SampleWidth w
type OutputShape w = LabelComposite (Length (Positions w)) (DataShape w)
type BatchInputShape w n = ZZ ::. n :* Length (Positions w) ::. 3 ::. SampleHeight w ::. SampleWidth w
type BatchOutputShape w n = ZZ ::. n :* Length (Positions w) ::. Sum (DataShape w)
newtype WLabel w = WLabel (OutputShape w)
deriving instance Serialize (OutputShape w) => Serialize (WLabel w)
deriving instance Creatable (OutputShape w) => Creatable (WLabel w)
deriving instance Show (OutputShape w) => Show (WLabel w)
deriving instance Eq (OutputShape w) => Eq (WLabel w)
newtype WNetwork w = WNetwork (Network (InputShape w) (NetConfig w))
deriving instance Serialize (Network (InputShape w) (NetConfig w)) => Serialize (WNetwork w)
deriving instance Creatable (Network (InputShape w) (NetConfig w)) => Creatable (WNetwork w)
deriving instance Show (Network (InputShape w) (NetConfig w)) => Show (WNetwork w)
newtype WInput w = WInput (SArray U (InputShape w))
deriving instance Serialize (SArray U (InputShape w)) => Serialize (WInput w)
deriving instance Creatable (SArray U (InputShape w)) => Creatable (WInput w)
deriving instance Show (SArray U (InputShape w)) => Show (WInput w)
newtype WBatch n w = WBatch ( SArray U (BatchInputShape w n)
, SArray U (BatchOutputShape w n))
deriving instance ( Serialize (SArray U (BatchInputShape w n))
, Serialize (SArray U (BatchOutputShape w n))
) => Serialize (WBatch n w)
deriving instance ( Show (SArray U (BatchInputShape w n))
, Show (SArray U (BatchOutputShape w n))
) => Show (WBatch n w)
newtype LabelVec g = LabelVec (Vec WLabel (Widgets g))
deriving instance Show (Vec WLabel (Widgets g)) => Show (LabelVec g)
deriving instance Eq (Vec WLabel (Widgets g)) => Eq (LabelVec g)
type InputVec g = Vec WInput (Widgets g)
type NetworkVec g = Vec WNetwork (Widgets g)
type BatchVec n g = Vec (WBatch n) (Widgets g)
type BatchC n g = RTConduit (Screenshot g, LabelVec g) (Vec (WBatch n) (Widgets g))
newtype Visor game = Visor (NetworkVec game)
deriving instance Serialize (NetworkVec game) => Serialize (Visor game)
deriving instance Creatable (NetworkVec game) => Creatable (Visor game)
newtype Screenshot g = Screenshot BMP
newtype Path g = Path {unpath :: FilePath}
instance Show (Path g) where show (Path p) = p
type RTSource a = Source (ResourceT IO) a
type RTConduit a b = Conduit a (ResourceT IO) b
type RTSink a = Sink a (ResourceT IO) ()
| jonascarpay/visor | src/Types.hs | bsd-3-clause | 5,061 | 0 | 13 | 1,176 | 1,729 | 923 | 806 | 103 | 0 |
-- |
-- Module : Language.Logo
-- Copyright : (c) 2013-2016, the HLogo team
-- License : BSD3
-- Maintainer : Nikolaos Bezirgiannis <[email protected]>
-- Stability : experimental
--
-- Main wrapper module; the only module that should be imported by the model
module Language.Logo
(
module Language.Logo.Keyword,
module Language.Logo.Prim,
module Language.Logo.Exception,
module Language.Logo.Base,
module Prelude,
forever, when, liftM, liftM2
)
where
import Prelude hiding (show, print, length)
import Language.Logo.Keyword
import Language.Logo.Prim
import Language.Logo.Exception
import Language.Logo.Base
import Control.Monad (forever, when, liftM, liftM2)
| bezirg/hlogo | src/Language/Logo.hs | bsd-3-clause | 721 | 0 | 5 | 145 | 118 | 82 | 36 | 14 | 0 |
module Util.Integral where
instance Integral Float where
quotRem a b = (fab, (ab - fab)*b)
where
ab = a/b
fab = floor ab
toInteger = floor
instance Integral Double where
quotRem a b = (fab, (ab - fab)*b)
where
ab = a/b
fab = floor ab
toInteger = floor
| phylake/haskell-util | Integral.hs | bsd-3-clause | 295 | 0 | 9 | 92 | 124 | 68 | 56 | 11 | 0 |
{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveDataTypeable, TemplateHaskell, DeriveGeneric #-}
module OpenGL.Evaluator.GLPrimitives where
import Data.Word
import qualified Data.ByteString as BS
import Data.Data
import Data.Typeable
import Foreign
import Foreign.C.Types
import Foreign.Storable
import Data.Binary
import Data.Binary.Get
import Data.Binary.Put
import Data.Binary.IEEE754
import Data.DeriveTH
import Test.QuickCheck
import GHC.Generics
newtype GLbitfield = GLbitfield Word32
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLboolean = GLboolean Bool
deriving(Show, Eq, Storable, Data, Typeable, Arbitrary, Generic)
instance Binary GLboolean where
put (GLboolean x) = if x then putWord8 1 else putWord8 0
get = undefined
newtype GLbyte = GLbyte Word8
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLchar = GLchar Char
deriving(Show, Eq, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLclampf = GLclampf Float
deriving(Show, Eq, Num, Storable, Ord, Fractional, Real, Data, Typeable, Arbitrary, Generic)
instance Binary GLclampf where
put (GLclampf x) = putFloat32le x
get = undefined
newtype GLenum = GLenum Word32
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLfloat = GLfloat Float
deriving(Show, Eq, Num, Storable, Ord, Fractional, Real, Data, Typeable, Arbitrary, Generic)
instance Binary GLfloat where
put (GLfloat x) = putFloat32le x
get = undefined
newtype GLint = GLint Int32
deriving(Show, Eq, Num, Storable, Data, Typeable, Arbitrary, Generic)
instance Binary GLint where
put (GLint x) = putWord32le $ fromIntegral x
get = undefined
newtype GLshort = GLshort Int16
deriving(Show, Eq, Num, Storable, Data, Typeable, Arbitrary, Generic)
instance Binary GLshort where
put (GLshort x) = putWord16le $ fromIntegral x
get = undefined
newtype GLsizei = GLsizei Word32
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLubyte = GLubyte Word8
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLuint = GLuint Word32
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLushort = GLushort Word16
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLfixed = GLfixed Word32
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
newtype GLclampx = GLclampx Word32
deriving(Show, Eq, Num, Storable, Binary, Data, Typeable, Arbitrary, Generic)
type GLIntPtr = GLuint
type GLsizeiptr = GLuint
data MatrixUniformType = MATRIX_UNIFORM_2X2
| MATRIX_UNIFORM_3X3
| MATRIX_UNIFORM_4X4
deriving(Show, Eq, Data, Typeable, Generic)
$(derive makeBinary ''MatrixUniformType)
$(derive makeArbitrary ''MatrixUniformType)
type GLError = GLenum
type GLPointer = GLuint
type Id = GLuint
type GLId = GLuint | jfischoff/opengl-eval | src/OpenGL/Evaluator/GLPrimitives.hs | bsd-3-clause | 3,172 | 0 | 8 | 642 | 1,053 | 568 | 485 | 73 | 0 |
{-# LANGUAGE NoImplicitPrelude, UnicodeSyntax #-}
-- |Help.Imports provides a central location for universally shared exports, primarily
-- the non-standard Prelude.
module Help.Imports ( -- *Overrides
FilePath
-- *Re-Exports
, module ClassyPrelude
, module Data.Eq.Unicode
) where
import ClassyPrelude hiding (FilePath)
import Data.Eq.Unicode
-- |Overrides the default @ClassyPrelude@ @FilePath@ for fun and profit.
type FilePath = String
| argiopetech/help | Help/Imports.hs | bsd-3-clause | 547 | 0 | 5 | 163 | 49 | 35 | 14 | 8 | 0 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Reactive.Banana.DOM.Widget
( ReactiveDom, CleanupHandler, IsWidget(..), IsEventWidget(..), WidgetInstance,
mkWidget, removeWidget, fromWidgetInstance,
widgetRoot, mkSubWidget, registerCleanupIO, handleBehavior,
rsFlipFlop, newBehavior
) where
import Control.Lens
import Control.Monad
import Control.Monad.Writer
import Data.Typeable
import GHCJS.DOM.Element (Element, setAttribute)
import GHCJS.DOM.Node (getParentNode, removeChild)
import GHCJS.DOM.Types (IsNode)
import Reactive.Banana
import Reactive.Banana.Frameworks
--- | The 'Monad' in which 'WidgetInstance' creation is enacted. Use 'registerCleanupIO'
--- to register cleanup handles. Use 'mkSubWidget' to create sub 'WidgetInstance's
type ReactiveDom a = WriterT [CleanupHandler] MomentIO a
-- | a type class for all reactive widgets
class IsWidget w where
data WidgetInput w :: *
-- | Create and register widget 'w'. Returns the widget and its root 'Element'.
-- Use 'mkSubWidget' to creat sub widgets.
mkWidgetInstance :: (IsNode parent) =>
parent -> WidgetInput w -> ReactiveDom (w, Element)
-- | A widget witch emits an 'Event'
class (IsWidget w) => IsEventWidget w where
type WidgetEventType w :: *
widgetEvent :: w -> Event (WidgetEventType w)
type CleanupHandler = MomentIO ()
-- | Represents an instance of an 'IsWidget'
newtype WidgetInstance w = WidgetInstance (w, CleanupHandler, Element)
makePrisms ''WidgetInstance
-- | Register an 'IO' action as cleanup function in 'ReactiveDom'
registerCleanupIO :: IO () -> ReactiveDom ()
registerCleanupIO = tell . pure . liftIO
-- | Get the widget from a 'WidgetInstance'
fromWidgetInstance :: (IsWidget w) => WidgetInstance w -> w
fromWidgetInstance = view $ _WidgetInstance . _1
-- | Should deregister all event handlers, kill threads etc.
widgetCleanup :: (IsWidget w) => WidgetInstance w -> CleanupHandler
widgetCleanup = view $ _WidgetInstance . _2
-- | Get the root 'Element' of a 'WidgetInstance'
widgetRoot :: (IsWidget w) => WidgetInstance w -> Element
widgetRoot = view $ _WidgetInstance . _3
-- | Creates a new 'WidgetInstance' in the DOM
mkWidget :: (Typeable w, IsWidget w, IsNode parent) =>
parent -> WidgetInput w -> MomentIO (WidgetInstance w)
mkWidget parent i = do
(r, cs) <- runWriterT $ mkWidgetInstance parent i
let widgetClass = mkWidgetClassName . show . typeOf . view _1 $ r
liftIOLater . setAttribute (r ^. _2) ("data-widget" :: String) $ widgetClass
return $ _WidgetInstance # (r ^. _1, sequence_ cs, r ^. _2)
where mkWidgetClassName = takeWhile (not . (==) ' ')
-- | Calls cleanup of 'WidgetInstance' tree. Removes element from DOM.
removeWidget :: (IsWidget w) => WidgetInstance w -> MomentIO ()
removeWidget w = do
widgetCleanup w
let r = widgetRoot w
pM <- getParentNode r
case pM of
Nothing -> return ()
Just p -> void $ removeChild p (pure r)
-- | Creates a sub widget in the 'ReactiveDom' 'Monad'.
mkSubWidget :: (Typeable w, IsWidget w, IsNode parent) =>
parent -> WidgetInput w -> ReactiveDom (WidgetInstance w)
mkSubWidget parent i = do
w <- lift . mkWidget parent $ i
tell . pure . widgetCleanup $ w
return w
newBehavior :: a -> MomentIO (Behavior a, a -> IO ())
newBehavior s0 = do
(e, fe) <- newEvent
(,) <$> stepper s0 e <*> pure fe
-- | register an handler for changes on a 'Behavior'
handleBehavior :: Behavior a -> Handler a -> ReactiveDom ()
handleBehavior a = lift . handleBehavior' a
handleBehavior' :: Behavior a -> Handler a -> MomentIO ()
handleBehavior' a h = do
valueBLater a >>= liftIOLater . h
changes a >>= reactimate' . fmap (fmap h)
rsFlipFlop :: Behavior Bool -> Behavior Bool -> MomentIO (Behavior Bool)
rsFlipFlop s r = do
(b, fire) <- newBehavior False
handleBehavior' s $ \a -> when a $ fire True
handleBehavior' r $ \a -> when a $ fire False
return b
| open-etcs/openetcs-dmi | src/Reactive/Banana/DOM/Widget.hs | bsd-3-clause | 4,195 | 0 | 13 | 924 | 1,111 | 579 | 532 | 75 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module Data.Type.Uniform where
import Data.Kind
import Data.Type.Length
import Type.Class.Known
import Type.Class.Witness
import Data.Type.Nat
import Type.Family.List.Util
import Type.Family.Constraint
import Type.Family.List
-- | A @'Uniform' a as@ is a witness that every item in @as@ is
-- (identically) @a@.
data Uniform :: a -> [a] -> Type where
UØ :: Uniform a '[]
US :: !(Uniform a as) -> Uniform a (a ': as)
deriving instance Show (Uniform a as)
uniformLength :: Uniform n ns -> Length ns
uniformLength = \case
UØ -> LZ
US u -> LS (uniformLength u)
instance Known (Uniform n) '[] where
known = UØ
instance Known (Uniform n) ns => Known (Uniform n) (n ': ns) where
known = US known
-- instance (m ~ Len ns) => Witness ØC (Known Nat m) (Uniform n ns) where
-- (\\) r = \case
-- UØ -> r
-- US u -> r \\ u
instance Witness ØC (Known Length ms) (Uniform m ms) where
(\\) r = \case
UØ -> r
US u -> r \\ u
appendUniform
:: Uniform o ns
-> Uniform o ms
-> Uniform o (ns ++ ms)
appendUniform = \case
UØ -> id
US u -> US . appendUniform u
replicateUniform
:: forall x n. ()
=> Nat n
-> Uniform x (Replicate n x)
replicateUniform = \case
Z_ -> UØ
S_ n -> US (replicateUniform @x n)
| mstksg/tensor-ops | src/Data/Type/Uniform.hs | bsd-3-clause | 1,854 | 1 | 11 | 540 | 483 | 260 | 223 | -1 | -1 |
module Bump where
import Control.Monad.Error (throwError, liftIO)
import qualified Data.List as List
import qualified Catalog
import qualified CommandLine.Helpers as Cmd
import qualified Diff.Compare as Compare
import qualified Docs
import qualified Elm.Docs as Docs
import qualified Elm.Package.Description as Desc
import qualified Elm.Package.Name as N
import qualified Elm.Package.Paths as Path
import qualified Elm.Package.Version as V
import qualified Manager
bump :: Manager.Manager ()
bump =
do description <- Desc.read Path.description
let name = Desc.name description
let statedVersion = Desc.version description
newDocs <- Docs.generate description
maybeVersions <- Catalog.versions name
case maybeVersions of
Nothing ->
validateInitialVersion description
Just publishedVersions ->
let baseVersions = map (\(old, _, _) -> old) (validBumps publishedVersions) in
if statedVersion `elem` baseVersions
then suggestVersion newDocs name statedVersion description
else throwError (unbumpable baseVersions)
return ()
unbumpable :: [V.Version] -> String
unbumpable baseVersions =
let versions = map head (List.group (List.sort baseVersions))
in
unlines
[ "To bump you must start with an already published version number in"
, Path.description ++ ", giving us a starting point to bump from."
, ""
, "The version numbers that can be bumped include the following subset of"
, "published versions:"
, " " ++ List.intercalate ", " (map V.toString versions)
, ""
, "Switch back to one of these versions before running 'elm-package bump'"
, "again."
]
data Validity
= Valid
| Invalid
| Changed V.Version
validateInitialVersion :: Desc.Description -> Manager.Manager Validity
validateInitialVersion description =
do Cmd.out explanation
if Desc.version description == V.initialVersion
then Cmd.out goodMsg >> return Valid
else changeVersion badMsg description V.initialVersion
where
explanation =
unlines
[ "This package has never been published before. Here's how things work:"
, ""
, " * Versions all have exactly three parts: MAJOR.MINOR.PATCH"
, ""
, " * All packages start with initial version " ++ V.toString V.initialVersion
, ""
, " * Versions are incremented based on how the API changes:"
, ""
, " PATCH - the API is the same, no risk of breaking code"
, " MINOR - values have been added, existing values are unchanged"
, " MAJOR - existing values have been changed or removed"
, ""
, " * I will bump versions for you, automatically enforcing these rules"
, ""
]
goodMsg =
"The version number in " ++ Path.description ++ " is correct so you are all set!"
badMsg =
concat
[ "It looks like the version in " ++ Path.description ++ " has been changed though!\n"
, "Would you like me to change it back to " ++ V.toString V.initialVersion ++ "? (y/n) "
]
changeVersion :: String -> Desc.Description -> V.Version -> Manager.Manager Validity
changeVersion explanation description newVersion =
do liftIO $ putStr explanation
yes <- liftIO Cmd.yesOrNo
case yes of
False -> do
Cmd.out "Okay, no changes were made."
return Invalid
True -> do
liftIO $ Desc.write (description { Desc.version = newVersion })
Cmd.out $ "Version changed to " ++ V.toString newVersion ++ "."
return (Changed newVersion)
suggestVersion
:: [Docs.Documentation]
-> N.Name
-> V.Version
-> Desc.Description
-> Manager.Manager Validity
suggestVersion newDocs name version description =
do changes <- Compare.computeChanges newDocs name version
let newVersion = Compare.bumpBy changes version
changeVersion (infoMsg changes newVersion) description newVersion
where
infoMsg changes newVersion =
let old = V.toString version
new = V.toString newVersion
magnitude = show (Compare.packageChangeMagnitude changes)
in
concat
[ "Based on your new API, this should be a ", magnitude, " change (", old, " => ", new, ")\n"
, "Bail out of this command and run 'elm-package diff' for a full explanation.\n"
, "\n"
, "Should I perform the update (", old, " => ", new, ") in ", Path.description, "? (y/n) "
]
validateVersion
:: [Docs.Documentation]
-> N.Name
-> V.Version
-> [V.Version]
-> Manager.Manager Validity
validateVersion newDocs name statedVersion publishedVersions =
case List.find (\(_ ,new, _) -> statedVersion == new) bumps of
Nothing ->
let isPublished = statedVersion `elem` publishedVersions
in
throwError (if isPublished then alreadyPublished else invalidBump)
Just (old, new, magnitude) ->
do changes <- Compare.computeChanges newDocs name old
let realNew = Compare.bumpBy changes old
case new == realNew of
False ->
throwError (badBump old new realNew magnitude changes)
True -> do
Cmd.out (looksGood old new magnitude)
return Valid
where
bumps = validBumps publishedVersions
looksGood old new magnitude =
"Version number " ++ V.toString new ++ " verified (" ++ show magnitude
++ " change, " ++ V.toString old ++ " => " ++ V.toString new ++ ")"
alreadyPublished =
"Version " ++ V.toString statedVersion
++ " has already been published, but you are trying to publish\n"
++ "it again! Run the following command to see what the new version should be.\n"
++ "\n elm-package bump\n"
invalidBump =
unlines
[ "The version listed in " ++ Path.description ++ " is neither a previously"
, "published version, nor a valid version bump."
, ""
, "Set the version number in " ++ Path.description ++ " to the released version"
, "that you are improving upon. If you are working on the latest API, that means"
, "you are modifying version " ++ V.toString (last publishedVersions) ++ "."
, ""
, "From there, we can compute which version comes next based on the API changes"
, "when you run the following command."
, ""
, " elm-package bump"
]
badBump old new realNew magnitude changes =
unlines
[ "It looks like you are trying to bump from version " ++ V.toString old ++ " to " ++ V.toString new ++ "."
, "This implies you are making a " ++ show magnitude ++ " change, but when we compare"
, "the " ++ V.toString old ++ " API to the API you have now it seems that it should"
, "really be a " ++ show (Compare.packageChangeMagnitude changes) ++ " change (" ++ V.toString realNew ++ ")."
, ""
, "Run the following command to see the API diff we are working from:"
, ""
, " elm-package diff " ++ V.toString old
, ""
, "The easiest way to bump versions is to let us do it automatically. If you set"
, "the version number in " ++ Path.description ++ " to the released version"
, "that you are improving upon, we will compute which version should come next"
, "when you run:"
, ""
, " elm-package bump"
]
-- VALID BUMPS
validBumps :: [V.Version] -> [(V.Version, V.Version, Compare.Magnitude)]
validBumps publishedVersions =
[ (majorPoint, V.bumpMajor majorPoint, Compare.MAJOR) ]
++ map (\v -> (v, V.bumpMinor v, Compare.MINOR)) minorPoints
++ map (\v -> (v, V.bumpPatch v, Compare.PATCH)) patchPoints
where
patchPoints = V.filterLatest V.majorAndMinor publishedVersions
minorPoints = V.filterLatest V.major publishedVersions
majorPoint = head publishedVersions
| rtfeldman/elm-package | src/Bump.hs | bsd-3-clause | 8,561 | 0 | 17 | 2,741 | 1,709 | 897 | 812 | 172 | 4 |
-- HSlippyMap Exemple
import HSlippyMap
{--
let max = tileFromLatLong 48.9031 2.5214 10
let min = tileFromLatLong 48.8146 2.1732 10
mapM (\(x,y) -> mapM (\y'-> print $ "http://tile.openstreetmap.org/" ++ show z ++ "/" \
++ show x ++ "/" ++ show y' ++ ".png") y) [(x,[(minimum [tymin, tymax])..(maximum [tymin\
,tymax])]) | x <- [(minimum [txmin, txmax])..(maximum [txmin, txmax])]]
--}
main = do
--mapM (print . show . tileFromLatLong lat long) [0..18]
mapM (\(x,y) -> mapM (\y'->
print $ "http://tile.openstreetmap.org/" ++ show z ++ "/" ++ show x ++ "/" ++ show y' ++ ".png") y)
[(x,[(minimum [tymin, tymax])..(maximum [tymin,tymax])]) | x <- [(minimum [txmin, txmax])..(maximum [txmin, txmax])]]
where
min = tileFromLatLong 49.13 3.05 8
max = tileFromLatLong (-48.57) 1.66 8
txmin = tx min
txmax = tx max
tymax = ty min
tymin = ty max
z = tz min
| j4/HSlippyMap | hsl.hs | bsd-3-clause | 914 | 0 | 19 | 205 | 230 | 124 | 106 | 12 | 1 |
{-
- 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 DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE UndecidableInstances #-}
-- | A class for monads which describe quantum circuits, with various gates and circuit combinators.
module Control.Monad.Quantum.Base.Class (
Bit(..), negateBit, bit,
MonadQuantumBase(..),
newWires, ancillae,
applyZ, applyS, applyT, applyZC, cnotWire, cnotWires,
with_, parallel, parallel_,
parallels, parallels_, mapParM, mapParM_, forParM, forParM_,
swapWire, swapWires,
bitToWire, cnotBit) where
import Control.Applicative (Applicative, (<*>))
import qualified Control.Applicative as Applicative
import Control.Monad (void, when)
import Control.Monad.Reader (ReaderT(ReaderT), runReaderT)
import Control.Monad.Trans (lift)
import Data.Foldable (Foldable)
import qualified Data.Foldable as Foldable
import Data.Functor ((<$>))
import Data.Hashable (Hashable(hashWithSalt))
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Traversable (Traversable)
import qualified Data.Traversable as Traversable
import Data.Typeable (Typeable)
import Control.Monad.Memo.Null
import Util (replicateA_, genericReplicateA_)
-- |A Bit is a Boolean constant, a wire, or the negation of a wire.
-- A circuit can accept a Bit as part of its input when the operation
-- implemented by the circuit is block-diagonal with respect to that qubit of the input.
data Bit w = BitConst !Bool | BitWire !Bool w
deriving (Eq, Show, Functor, Foldable, Traversable, Typeable)
instance Hashable w => Hashable (Bit w) where
s `hashWithSalt` (BitConst False) = s `hashWithSalt` (0 :: Int)
s `hashWithSalt` (BitConst True) = s `hashWithSalt` (1 :: Int)
s `hashWithSalt` (BitWire False w) = s `hashWithSalt` (2 :: Int) `hashWithSalt` w
s `hashWithSalt` (BitWire True w) = s `hashWithSalt` (3 :: Int) `hashWithSalt` w
-- |The negation of a `Bit`.
negateBit :: Bit w -> Bit w
negateBit (BitConst b) = BitConst $ not b
negateBit (BitWire neg w) = BitWire (not neg) w
-- |Convert a wire to a `Bit`.
bit :: w -> Bit w
bit = BitWire False
-- | A monad which represents basic quantum circuits and their compositions.
-- @w@ is the type for wires.
class (Applicative m, Monad m) => MonadQuantumBase w m | m -> w where
-- | Return a new qubit.
newWire :: m w
-- | Return a new qubit which is initialized to |0\>.
ancilla :: m w
-- | Apply NOT (Pauli-X) to the given wire.
applyX :: w -> m ()
-- | Apply the Pauli-Y gate.
applyY :: w -> m ()
-- | Apply the Pauli-Z gate to a wire or its negation.
-- This is the low-level interface for an implementor of `MonadQuantumBase`;
-- for a user, it is easier to use `applyZ`.
rawApplyZ :: w -> Bool -> m ()
-- | Apply the Hadamard gate.
applyH :: w -> m ()
-- | Apply the S gate, or its inverse if the third argument is True.
-- This is the low-level interface for an implementor of `MonadQuantumBase`;
-- for a user, it is easier to use `applyS`.
rawApplyS :: w -> Bool -> Bool -> m ()
-- | Apply the T gate, or its inverse if the third argument is True.
-- This is the low-level interface for an implementor of `MonadQuantumBase`;
-- for a user, it is easier to use `applyT`.
rawApplyT :: w -> Bool -> Bool -> m ()
-- | Negate the global phase.
-- This is no-op if the current control context is empty.
negateGlobalPhase :: m ()
-- | Shift the global phase by pi/2 (if the argument is False) or -pi/2 (if the argument is True).
-- This is no-op if the current control context is empty.
rotateGlobalPhase90 :: Bool -> m ()
-- | Shift the global phase by pi/4 (if the argument is False) or -pi/4 (if the argument is True).
-- This is no-op if the current control context is empty.
rotateGlobalPhase45 :: Bool -> m ()
-- | Apply controlled Pauli-Z.
--
-- The two wires must be different.
rawApplyZC :: w -> Bool -> w -> Bool -> m ()
-- | @cnotWire w w1@ applies CNOT (controlled Pauli-X) with target @w@ controlled by @w1@.
--
-- @w@ and @w1@ must not refer to the same wire.
rawCnotWire :: w -> w -> Bool -> m ()
-- | Given two sequences of wires, apply CNOT to each pair of wires at the corresponding position.
--
-- Precondition:
--
-- * The given wires are all distinct.
rawCnotWires :: [(w, w, Bool)] -> m ()
-- | @with prepare body@ is the sequential composition of @prepare@, @body@, and the inverse of @prepare@,
-- where @body@ takes the result of @prepare@ as its argument.
--
-- Precondition:
--
-- * The composition restores all the ancillae introduced by @prepare@ to the initial state |0\>.
with :: m a -> (a -> m b) -> m b
-- | Apply given two circuits, possibly in parallel.
-- Implementations may choose to apply the given circuits sequentially.
--
-- Precondition:
--
-- * The two circuits do not refer to the same wire.
bindParallel :: m a -> (a -> m b) -> m b
-- | Apply the inverse of a given unitary circuit.
--
-- Precondition:
--
-- * The given circuit is unitary; that is, the circuit deallocates all new wires which it allocates.
invert :: m a -> m a
-- |Apply the given circuit with the empty control context.
withoutCtrls :: m a -> m a
-- | @replicateQ n m@ evaluates to the sequential composition of @n@ copies of circuit @m@.
{-# INLINABLE replicateQ #-}
replicateQ :: Int -> m a -> m (Seq a)
replicateQ = Seq.replicateA
-- | @replicateParallelQ n m@ evaluates to the possibly parallel composition of @n@ copies of circuit @m@.
-- This is useful when preparing many copies of a state in new wires without referring to any old wires.
--
-- Precondition:
--
-- * No two of the @n@ copies refer to the same wire.
-- This means that the given circuit cannot refer to any old wires unless @n@ <= 1.
{-# INLINABLE replicateParallelQ #-}
replicateParallelQ :: Int -> m a -> m (Seq a)
replicateParallelQ n =
getParallel . Seq.replicateA n . Parallel
-- | @replicateQ_ n m@ evaluates to the sequential composition of @n@ copies of circuit @m@, and discards the result.
{-# INLINABLE replicateQ_ #-}
replicateQ_ :: Int -> m () -> m ()
replicateQ_ = replicateA_
-- | @replicateParallelQ n m@ evaluates to the possibly parallel composition of @n@ copies of circuit @m@, and discards the result.
--
-- Precondition:
--
-- * No two of the @n@ copies refer to the same wire.
-- This means that the given circuit cannot refer to any old wires unless @n@ <= 1.
{-# INLINABLE replicateParallelQ_ #-}
replicateParallelQ_ :: Int -> m () -> m ()
replicateParallelQ_ n =
getParallel . replicateA_ n . Parallel
-- | Generic version of `replicateQ_`.
--
-- Note: There is no @genericReplicateQ@ because `Seq` cannot handle size larger than `Int`.
{-# INLINABLE genericReplicateQ_ #-}
genericReplicateQ_ :: Integral i => i -> m () -> m ()
genericReplicateQ_ = genericReplicateA_
-- | Generic version of `replicateParallelQ_`.
--
-- Note: There is no @genericFastReplicateParallelM@ because `Seq` cannot handle size larger than `Int`.
{-# INLINABLE genericReplicateParallelQ_ #-}
genericReplicateParallelQ_ :: Integral i => i -> m () -> m ()
genericReplicateParallelQ_ n =
getParallel . genericReplicateA_ n . Parallel
-- | Return new qubits.
newWires :: MonadQuantumBase w m => Int -> m (Seq w)
newWires n
| n >= 0 = replicateParallelQ n newWire
| otherwise = error "newWires: the number of qubits must be nonnegative"
{-# INLINABLE newWires #-}
-- | Return new qubits which are initialized to |0\>.
ancillae :: MonadQuantumBase w m => Int -> m (Seq w)
ancillae n
| n >= 0 = replicateParallelQ n ancilla
| otherwise = error "ancillae: the number of ancillae must be nonnegative"
{-# INLINABLE ancillae #-}
-- | Apply the Pauli-Z gate.
applyZ :: MonadQuantumBase w m => Bit w -> m ()
applyZ (BitConst False) = return ()
applyZ (BitConst True) = negateGlobalPhase
applyZ (BitWire neg w) = rawApplyZ w neg
-- | Apply the S gate, or its inverse if the second argument is True.
applyS :: MonadQuantumBase w m => Bit w -> Bool -> m ()
applyS (BitConst False) _ = return ()
applyS (BitConst True) inv = rotateGlobalPhase90 inv
applyS (BitWire neg w) inv = rawApplyS w neg inv
-- | Apply the T gate, or its inverse if the second argument is True.
applyT :: MonadQuantumBase w m => Bit w -> Bool -> m ()
applyT (BitConst False) _ = return ()
applyT (BitConst True) inv = rotateGlobalPhase45 inv
applyT (BitWire neg w) inv = rawApplyT w neg inv
-- | Apply controlled Pauli-Z.
--
-- The two wires must be different.
applyZC :: MonadQuantumBase w m => Bit w -> Bit w -> m ()
applyZC (BitConst False) _ = return ()
applyZC (BitConst True) b = applyZ b
applyZC _ (BitConst False) = return ()
applyZC a (BitConst True) = applyZ a
applyZC (BitWire nega a) (BitWire negb b) = rawApplyZC a nega b negb
-- | @cnotWire w w1@ applies CNOT (controlled Pauli-X) with target @w@ controlled by @w1@.
--
-- @w@ and @w1@ must not refer to the same wire.
cnotWire :: MonadQuantumBase w m => w -> Bit w -> m ()
cnotWire _ (BitConst False) = return ()
cnotWire w (BitConst True) = applyX w
cnotWire w (BitWire neg w1) = rawCnotWire w w1 neg
-- | Given two sequences of wires, apply CNOT to each pair of wires at the corresponding position.
--
-- Precondition:
--
-- * The given wires are all distinct.
cnotWires :: MonadQuantumBase w m => Seq w -> Seq (Bit w) -> m ()
cnotWires targ ctrl =
if Seq.length targ /= Seq.length ctrl then
error "cnotWires: lengths do not match"
else if null cnots then
if null nots then
return ()
else
mapParM_ applyX nots
else
if null nots then
rawCnotWires cnots
else
parallel_
(rawCnotWires cnots)
(mapParM_ applyX nots)
where
pairs = zip (Foldable.toList targ) (Foldable.toList ctrl)
cnots = [(t, c, neg) | (t, BitWire neg c) <- pairs]
nots = [t | (t, BitConst True) <- pairs]
-- | @with_ prepare body@ is the sequential composition of @prepare@, @body@, and the inverse of @prepare@.
-- The result of @prepare@ is discarded.
--
-- Precondition:
--
-- * The composition restores all the ancillae introduced by @prepare@ to the initial state |0\>.
with_ :: MonadQuantumBase w m => m () -> m a -> m a
with_ prepare body =
with prepare (const body)
{-# INLINABLE with_ #-}
-- | Apply given two circuits, possibly in parallel.
-- Implementations may choose to apply the given circuits sequentially.
--
-- Precondition:
--
-- * The two circuits do not refer to the same wire.
parallel :: MonadQuantumBase w m => m a -> m b -> m (a, b)
parallel ma mb =
bindParallel ma (\a -> (\b -> (a, b)) <$> mb)
-- | The same as `parallel`, but discards the result.
parallel_ :: MonadQuantumBase w m => m a -> m b -> m ()
parallel_ a b = void (parallel a b)
{-# INLINABLE parallel_ #-}
-- Although any instance of MonadQuantumBase is an applicative functor,
-- @pure@ may not be an identity of @\mf mx -> uncurry id <$> parallel mf mx@
-- because @parallel@ may compress the control context.
-- This is why we define two cases here.
data Parallel w m a = ParallelPure a | Parallel (m a)
deriving Functor
getParallel :: Applicative m => Parallel w m a -> m a
getParallel (ParallelPure x) = Applicative.pure x
getParallel (Parallel mx) = mx
instance MonadQuantumBase w m => Applicative (Parallel w m) where
pure = ParallelPure
ParallelPure f <*> mx = f <$> mx
Parallel mf <*> ParallelPure x = Parallel (($ x) <$> mf)
Parallel mf <*> Parallel mx = Parallel (uncurry id <$> parallel mf mx)
-- | Apply the circuits in the given container possibly in parallel, and return the results in the container of the same form.
--
-- Precondition:
--
-- No two of the given circuits refer to the same wire.
parallels :: (MonadQuantumBase w m, Traversable t) => t (m a) -> m (t a)
parallels ms = getParallel $ Traversable.traverse Parallel ms
{-# INLINABLE parallels #-}
-- | Apply the circuits in the given container possibly in parallel, and discard the results.
--
-- Precondition:
--
-- No two of the given circuits refer to the same wire.
parallels_ :: (MonadQuantumBase w m, Foldable t) => t (m a) -> m ()
parallels_ ms = getParallel $ Foldable.traverse_ Parallel ms
{-# INLINABLE parallels_ #-}
-- | Apply the circuit to the elements in the given container possibly in parallel,
-- and return the results in the container of the same form.
--
-- Precondition:
--
-- No two of the given circuits refer to the same wire.
mapParM :: (MonadQuantumBase w m, Traversable t) => (a -> m b) -> t a -> m (t b)
mapParM f xs = getParallel $ Traversable.traverse (Parallel . f) xs
{-# INLINABLE mapParM #-}
-- | Apply the circuit to the elements in the given container possibly in parallel, and discard the results.
--
-- Precondition:
--
-- No two of the given circuits refer to the same wire.
mapParM_ :: (MonadQuantumBase w m, Foldable t) => (a -> m b) -> t a -> m ()
mapParM_ f xs = getParallel $ Foldable.traverse_ (Parallel . f) xs
{-# INLINABLE mapParM_ #-}
-- | `mapParM` with its arguments flipped.
forParM :: (MonadQuantumBase w m, Traversable t) => t a -> (a -> m b) -> m (t b)
forParM = flip mapParM
{-# INLINABLE forParM #-}
-- | `mapParM_` with its arguments flipped.
forParM_ :: (MonadQuantumBase w m, Foldable t) => t a -> (a -> m b) -> m ()
forParM_ = flip mapParM_
{-# INLINABLE forParM_ #-}
-- | Apply the swap gate to two wires.
--
-- The two wires must be distinct.
swapWire :: MonadQuantumBase w m => w -> w -> m ()
swapWire w1 w2 =
with_ (cnotWire w1 (bit w2)) $
cnotWire w2 (bit w1)
{-# INLINABLE swapWire #-}
-- | Given two sequences of wires, apply the swap gate to each pair of wires at the corresponding position.
--
-- All the given wires must be distinct.
swapWires :: MonadQuantumBase w m => Seq w -> Seq w -> m ()
swapWires ws1 ws2 =
if Seq.length ws1 /= Seq.length ws2 then
error "swapWires: lengths do not match"
else
with_ (cnotWires ws1 (bit <$> ws2)) $
cnotWires ws2 (bit <$> ws1)
{-# INLINABLE swapWires #-}
-- |Convert a `Bit` to a wire, possibly consuming the given Bit.
--
-- If the input `Bit` is a wire, the returned wire is the same as the input wire.
-- Therefore, the input bit should be considered as “consumed”
-- while the wire returned by this function is being used.
bitToWire :: MonadQuantumBase w m => Bit w -> m w
bitToWire (BitConst b) = withoutCtrls $ do
w <- ancilla
when b $ applyX w
return w
bitToWire (BitWire neg w) = withoutCtrls $ do
when neg $ applyX w
return w
{-# INLINABLE bitToWire #-}
-- |@cnotBit t c@ returns a `Bit` representing @t XOR c@, possibly consuming @t@.
--
-- If @t@ is a wire, then this wire is returned.
-- Therefore, @t@ should be considered as “consumed”
-- while the bit returned by this function is being used.
cnotBit :: MonadQuantumBase w m => Bit w -> Bit w -> m (Bit w)
cnotBit (BitConst t) (BitConst c) =
return $ BitConst (t /= c)
cnotBit t c = withoutCtrls $ do
t' <- bitToWire t
cnotWire t' c
return $ bit t'
{-# INLINABLE cnotBit #-}
-- Instance for ReaderT
-- Requires UndecidableInstances.
instance MonadQuantumBase w m => MonadQuantumBase w (ReaderT r m) where
newWire = lift newWire
{-# INLINABLE newWire #-}
ancilla = lift ancilla
{-# INLINABLE ancilla #-}
applyX w = lift $ applyX w
{-# INLINABLE applyX #-}
applyY w = lift $ applyY w
{-# INLINABLE applyY #-}
rawApplyZ w neg = lift $ rawApplyZ w neg
{-# INLINABLE rawApplyZ #-}
applyH w = lift $ applyH w
{-# INLINABLE applyH #-}
rawApplyS w neg inv = lift $ rawApplyS w neg inv
{-# INLINABLE rawApplyS #-}
rawApplyT w neg inv = lift $ rawApplyT w neg inv
{-# INLINABLE rawApplyT #-}
negateGlobalPhase =
lift negateGlobalPhase
{-# INLINABLE negateGlobalPhase #-}
rotateGlobalPhase90 =
lift . rotateGlobalPhase90
{-# INLINABLE rotateGlobalPhase90 #-}
rotateGlobalPhase45 =
lift . rotateGlobalPhase45
{-# INLINABLE rotateGlobalPhase45 #-}
rawApplyZC a nega b negb = lift $ rawApplyZC a nega b negb
{-# INLINABLE rawApplyZC #-}
rawCnotWire w w1 neg = lift $ rawCnotWire w w1 neg
{-# INLINABLE rawCnotWire #-}
rawCnotWires ws = lift $ rawCnotWires ws
{-# INLINABLE rawCnotWires #-}
with prepare body = ReaderT $ \r ->
with (runReaderT prepare r) $ \a ->
runReaderT (body a) r
{-# INLINABLE with #-}
bindParallel m1 m2 = ReaderT $ \r ->
bindParallel (runReaderT m1 r) (\a -> runReaderT (m2 a) r)
{-# INLINABLE bindParallel #-}
invert m = ReaderT $ \r ->
invert (runReaderT m r)
{-# INLINABLE invert #-}
withoutCtrls m = ReaderT $ \r ->
withoutCtrls (runReaderT m r)
replicateQ n m = ReaderT $ \r ->
replicateQ n (runReaderT m r)
{-# INLINABLE replicateQ #-}
replicateParallelQ n m = ReaderT $ \r ->
replicateParallelQ n (runReaderT m r)
{-# INLINABLE replicateParallelQ #-}
replicateQ_ n m = ReaderT $ \r ->
replicateQ_ n (runReaderT m r)
{-# INLINABLE replicateQ_ #-}
replicateParallelQ_ n m = ReaderT $ \r ->
replicateParallelQ_ n (runReaderT m r)
{-# INLINABLE replicateParallelQ_ #-}
genericReplicateQ_ n m = ReaderT $ \r ->
genericReplicateQ_ n (runReaderT m r)
{-# INLINABLE genericReplicateQ_ #-}
genericReplicateParallelQ_ n m = ReaderT $ \r ->
genericReplicateParallelQ_ n (runReaderT m r)
{-# INLINABLE genericReplicateParallelQ_ #-}
-- Instance for MemoNullT
-- Requires UndecidableInstances.
instance MonadQuantumBase w m => MonadQuantumBase w (MemoNullT k m) where
newWire = lift newWire
{-# INLINABLE newWire #-}
ancilla = lift ancilla
{-# INLINABLE ancilla #-}
applyX w = lift $ applyX w
{-# INLINABLE applyX #-}
applyY w = lift $ applyY w
{-# INLINABLE applyY #-}
rawApplyZ w neg = lift $ rawApplyZ w neg
{-# INLINABLE rawApplyZ #-}
applyH w = lift $ applyH w
{-# INLINABLE applyH #-}
rawApplyS w neg inv = lift $ rawApplyS w neg inv
{-# INLINABLE rawApplyS #-}
rawApplyT w neg inv = lift $ rawApplyT w neg inv
{-# INLINABLE rawApplyT #-}
negateGlobalPhase =
lift negateGlobalPhase
{-# INLINABLE negateGlobalPhase #-}
rotateGlobalPhase90 =
lift . rotateGlobalPhase90
{-# INLINABLE rotateGlobalPhase90 #-}
rotateGlobalPhase45 =
lift . rotateGlobalPhase45
{-# INLINABLE rotateGlobalPhase45 #-}
rawApplyZC a nega b negb = lift $ rawApplyZC a nega b negb
{-# INLINABLE rawApplyZC #-}
rawCnotWire w w1 neg = lift $ rawCnotWire w w1 neg
{-# INLINABLE rawCnotWire #-}
rawCnotWires ws = lift $ rawCnotWires ws
{-# INLINABLE rawCnotWires #-}
with prepare body = MemoNullT $
with (runMemoNullT prepare) $ \a ->
runMemoNullT (body a)
{-# INLINABLE with #-}
bindParallel m1 m2 = MemoNullT $
bindParallel (runMemoNullT m1) (\a -> runMemoNullT (m2 a))
{-# INLINABLE bindParallel #-}
invert m = MemoNullT $
invert (runMemoNullT m)
{-# INLINABLE invert #-}
withoutCtrls m = MemoNullT $
withoutCtrls (runMemoNullT m)
replicateQ n m = MemoNullT $
replicateQ n (runMemoNullT m)
{-# INLINABLE replicateQ #-}
replicateParallelQ n m = MemoNullT $
replicateParallelQ n (runMemoNullT m)
{-# INLINABLE replicateParallelQ #-}
replicateQ_ n m = MemoNullT $
replicateQ_ n (runMemoNullT m)
{-# INLINABLE replicateQ_ #-}
replicateParallelQ_ n m = MemoNullT $
replicateParallelQ_ n (runMemoNullT m)
{-# INLINABLE replicateParallelQ_ #-}
genericReplicateQ_ n m = MemoNullT $
genericReplicateQ_ n (runMemoNullT m)
{-# INLINABLE genericReplicateQ_ #-}
genericReplicateParallelQ_ n m = MemoNullT $
genericReplicateParallelQ_ n (runMemoNullT m)
{-# INLINABLE genericReplicateParallelQ_ #-}
| ti1024/hacq | src/Control/Monad/Quantum/Base/Class.hs | bsd-3-clause | 20,174 | 0 | 13 | 4,320 | 4,519 | 2,377 | 2,142 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
--------------------------------------------------------------------------------
-- |
-- Module : Network.OpenID.Discovery
-- Copyright : (c) Trevor Elliott, 2008
-- License : BSD3
--
-- Maintainer : Trevor Elliott <[email protected]>
-- Stability :
-- Portability :
--
module Network.OpenID.Discovery (
-- * Discovery
discover
) where
-- Friends
import Network.OpenID.Types
import Text.XRDS
-- Libraries
import Data.Char
import Data.List
import Data.Maybe
import MonadLib
import Network.HTTP
import Network.URI
type M = ExceptionT Error
-- | Attempt to resolve an OpenID endpoint, and user identifier.
discover :: Monad m
=> Resolver m -> Identifier -> m (Either Error (Provider,Identifier))
discover resolve ident = do
res <- runExceptionT (discoverYADIS resolve ident Nothing)
case res of
Right {} -> return res
_ -> runExceptionT (discoverHTML resolve ident)
-- YADIS-Based Discovery -------------------------------------------------------
-- | Attempt a YADIS based discovery, given a valid identifier. The result is
-- an OpenID endpoint, and the actual identifier for the user.
discoverYADIS :: Monad m
=> Resolver m -> Identifier -> Maybe String
-> M m (Provider,Identifier)
discoverYADIS resolve ident mb_loc = do
let err = raise . Error
uri = fromMaybe (getIdentifier ident) mb_loc
case parseURI uri of
Nothing -> err "Unable to parse identifier as a URI"
Just uri -> do
estr <- lift $ resolve Request
{ rqMethod = GET
, rqURI = uri
, rqHeaders = []
, rqBody = ""
}
case estr of
Left e -> err $ "HTTP request error: " ++ show e
Right rsp -> case rspCode rsp of
(2,0,0) -> case findHeader (HdrCustom "X-XRDS-Location") rsp of
Just loc -> discoverYADIS resolve ident (Just loc)
_ -> do
let e = err "Unable to parse YADIS document"
doc <- maybe e return $ parseXRDS $ rspBody rsp
parseYADIS ident doc
_ -> err $ "HTTP request error: unexpected response code "++show (rspCode rsp)
-- | Parse out an OpenID endpoint, and actual identifier from a YADIS xml
-- document.
parseYADIS :: ExceptionM m Error
=> Identifier -> XRDS -> m (Provider,Identifier)
parseYADIS ident = handleError . listToMaybe . mapMaybe isOpenId . concat
where
handleError = maybe e return
where e = raise (Error "YADIS document doesn't include an OpenID provider")
isOpenId svc = do
let tys = serviceTypes svc
localId = maybe ident Identifier $ listToMaybe $ serviceLocalIDs svc
f (x,y) | x `elem` tys = Just y
| otherwise = mzero
lid <- listToMaybe $ mapMaybe f
[ ("http://specs.openid.net/auth/2.0/server", ident)
-- claimed identifiers
, ("http://specs.openid.net/auth/2.0/signon", localId)
, ("http://openid.net/signon/1.0" , localId)
, ("http://openid.net/signon/1.1" , localId)
]
uri <- parseProvider =<< listToMaybe (serviceURIs svc)
return (uri,lid)
-- HTML-Based Discovery --------------------------------------------------------
-- | Attempt to discover an OpenID endpoint, from an HTML document. The result
-- will be an endpoint on success, and the actual identifier of the user.
discoverHTML :: Monad m
=> Resolver m -> Identifier -> M m (Provider,Identifier)
discoverHTML resolve ident = do
let err = raise . Error
case parseURI (getIdentifier ident) of
Nothing -> err "Unable to parse identifier as a URI"
Just uri -> do
estr <- lift $ resolve Request
{ rqMethod = GET
, rqURI = uri
, rqHeaders = []
, rqBody = ""
}
case estr of
Left e -> err $ "HTTP request error: " ++ show e
Right rsp -> case rspCode rsp of
(2,0,0) -> maybe (err "Unable to find identifier in HTML") return
$ parseHTML ident $ rspBody rsp
_ -> err $ "HTTP request error: unexpected response code "++show (rspCode rsp)
-- | Parse out an OpenID endpoint and an actual identifier from an HTML
-- document.
parseHTML :: Identifier -> String -> Maybe (Provider,Identifier)
parseHTML ident = resolve
. filter isOpenId
. linkTags
. htmlTags
where
isOpenId (rel,_) = "openid" `isPrefixOf` rel
resolve ls = do
prov <- parseProvider =<< lookup "openid2.provider" ls
let lid = maybe ident Identifier $ lookup "openid2.local_id" ls
return (prov,lid)
-- | Filter out link tags from a list of html tags.
linkTags :: [String] -> [(String,String)]
linkTags = mapMaybe f . filter p
where
p = ("link " `isPrefixOf`)
f xs = do
let ys = unfoldr splitAttr (drop 5 xs)
x <- lookup "rel" ys
y <- lookup "href" ys
return (x,y)
-- | Split a string into strings of html tags.
htmlTags :: String -> [String]
htmlTags [] = []
htmlTags xs = case break (== '<') xs of
(as,_:bs) -> fmt as : htmlTags bs
(as,[]) -> [as]
where
fmt as = case break (== '>') as of
(bs,_) -> bs
-- | Split out values from a key="value" like string, in a way that
-- is suitable for use with unfoldr.
splitAttr :: String -> Maybe ((String,String),String)
splitAttr xs = case break (== '=') xs of
(_,[]) -> Nothing
(key,_:'"':ys) -> f key (== '"') ys
(key,_:ys) -> f key isSpace ys
where
f key p cs = case break p cs of
(_,[]) -> Nothing
(value,_:rest) -> Just ((key,value), dropWhile isSpace rest)
| substack/hsopenid | src/Network/OpenID/Discovery.hs | bsd-3-clause | 5,704 | 0 | 26 | 1,576 | 1,550 | 802 | 748 | 111 | 5 |
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Data.DList.Instances () where
-- don't define instance for dlist>=0.8 && base>=4.9
#if !(MIN_VERSION_base(4,9,0)) || !(MIN_VERSION_dlist(0,8,0))
import Data.DList
import Data.Semigroup
instance Semigroup (DList a) where
(<>) = append
#endif
| gregwebs/dlist-instances | Data/DList/Instances.hs | bsd-3-clause | 311 | 0 | 7 | 41 | 46 | 30 | 16 | 7 | 0 |
{-# LANGUAGE NoImplicitPrelude, UnicodeSyntax, OverloadedStrings, TemplateHaskell #-}
module Help.Settings ( -- *The Settings type
Settings
-- *Lens getters for Settings
, ymlFile
, logFile
, logCollection
, logParser
, adminHost
, adminPort
, database
, servers
, mongoHost
-- *The TCPConnection type
, TCPConnection
-- *Lens getters for TCPConnections
, port
, collection
, parser
-- *Utilities
, loadSettings
) where
import Help.Imports
import Help.Logging.Parse
import Control.Lens.Getter (to, Getter)
import qualified Data.Yaml.Config as YAML (lookup, load)
import Data.Aeson.Types hiding (Parser, parse)
import Data.Attoparsec.Text
import Database.MongoDB (Document)
import Options
data Settings = Settings { _ymlFile ∷ FilePath
, _logFile ∷ FilePath
, _logCollection ∷ Text
, _logParser ∷ Maybe (Parser Document)
, _database ∷ Text
, _adminHost ∷ FilePath
, _adminPort ∷ Int
, _servers ∷ [TCPConnection]
, _mongoHost ∷ String
}
data TCPConnection = TCPConnection { _port ∷ Int
, _collection ∷ Text
, _parser ∷ Parser Document
}
data TempSettings = TempSettings { tempYmlFile ∷ Maybe FilePath
, tempLogFile ∷ Maybe FilePath
, tempLogCollection ∷ Maybe Text
, tempLogParser ∷ Maybe (Parser Document)
, tempDatabase ∷ Maybe Text
, tempAdminHost ∷ Maybe String
, tempAdminPort ∷ Maybe Int
, tempServers ∷ Maybe [TCPConnection]
, tempMongoHost ∷ Maybe String
}
instance FromJSON TCPConnection where
parseJSON (Object v) = do
testRecord <- v .: "sampleRecord"
parserLine <- v .: "recordFormat"
let p = makeRecordParser parserLine
if not $ goodParser p testRecord
then error $ "Specified parser does not parse line " ++ unpack parserLine
else do
TCPConnection <$> v .: "port"
<*> v .: "collection"
<*> (pure $! p)
parseJSON _ = mempty
goodParser ∷ Parser Document → Text → Bool
goodParser p t = let parseResult = parse p t
in case parseResult of
Done "" _ -> True
_ -> False
ymlFile ∷ Getter Settings FilePath
ymlFile = to _ymlFile
logFile ∷ Getter Settings FilePath
logFile = to _logFile
logCollection ∷ Getter Settings Text
logCollection = to _logCollection
logParser ∷ Getter Settings (Maybe (Parser Document))
logParser = to _logParser
database ∷ Getter Settings Text
database = to _database
adminHost ∷ Getter Settings FilePath
adminHost = to _adminHost
adminPort ∷ Getter Settings Int
adminPort = to _adminPort
servers ∷ Getter Settings [TCPConnection]
servers = to _servers
port ∷ Getter TCPConnection Int
port = to _port
collection ∷ Getter TCPConnection Text
collection = to _collection
parser ∷ Getter TCPConnection (Parser Document)
parser = to _parser
mongoHost ∷ Getter Settings String
mongoHost = to _mongoHost
defineOptions "MainOptions" $ do
stringOption "cliYml" "yamlFile" "help.yaml"
"The default YAML configuration file"
stringOption "cliLogFile" "logFile" ""
"A log file from which to import"
textOption "cliLogCollection" "collection" "default"
"The MongoDB collection to import to"
textOption "cliRecordFormat" "recordFormat" ""
"The format of the records in the log file"
-- |Loads all settings and creates one authoritative set
loadSettings ∷ IO Settings
loadSettings = do
cliSettings ← loadCLISettings
ymlSettings ← loadYMLSettings $ loadableYmlFile $ cliSettings `overrides` defaultSettings
return $ verifySettings $ cliSettings `overrides` ymlSettings `overrides` defaultSettings
-- |Changes a TempSettings to a Settings, assuming it contains all required options
verifySettings ∷ TempSettings → Settings
verifySettings (TempSettings (Just s1) (Just s2) (Just s3) s4 (Just s5) (Just s6) (Just s7) (Just s8) (Just s9)) = Settings s1 s2 s3 s4 s5 s6 s7 s8 s9
verifySettings _ = error "Not all settings set" -- TODO: Handle this better
-- |Loads command-line settings from the output of @getArgs@
loadCLISettings ∷ IO TempSettings
loadCLISettings = runCommand $ \opts _ -> do
let p = if null $ cliYml opts
then Nothing
else Just $! makeRecordParser $ cliRecordFormat opts
return $ emptySettings { tempYmlFile = (Just $ cliYml opts)
, tempLogFile = (Just $ cliLogFile opts)
, tempLogCollection = (Just $ cliLogCollection opts)
, tempLogParser = p
}
-- |Loads settings from a YAML file
loadYMLSettings ∷ FilePath → IO TempSettings
loadYMLSettings yamlFile = do
yaml <- YAML.load yamlFile
let aHost = YAML.lookup yaml "adminHost"
aPort = YAML.lookup yaml "adminPort"
serve = YAML.lookup yaml "servers"
mHost = YAML.lookup yaml "mongoHost"
datab = YAML.lookup yaml "database"
return $ TempSettings Nothing Nothing datab Nothing Nothing aHost aPort serve mHost
-- |Default settings
defaultSettings ∷ TempSettings
defaultSettings = TempSettings (Just "help.yaml") Nothing Nothing Nothing (Just "help-db") (Just "localhost") (Just 8080) Nothing (Just "127.0.0.1")
-- |Empty settings
emptySettings ∷ TempSettings
emptySettings = TempSettings Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing
-- |Takes two TempSettings and returns a new TempSettings, favoring settings in the first over the second
overrides ∷ TempSettings → TempSettings → TempSettings
overrides ns os = let yF = if isJust $ tempYmlFile ns
then tempYmlFile ns
else tempYmlFile os
lF = if isJust $ tempLogFile ns
then tempLogFile ns
else tempLogFile os
lC = if isJust $ tempLogCollection ns
then tempLogCollection ns
else tempLogCollection os
lP = if isJust $ tempLogParser ns
then tempLogParser ns
else tempLogParser os
db = if isJust $ tempDatabase ns
then tempDatabase ns
else tempDatabase os
aH = if isJust $ tempAdminHost ns
then tempAdminHost ns
else tempAdminHost os
aP = if isJust $ tempAdminPort ns
then tempAdminPort ns
else tempAdminPort os
ss = if isJust $ tempServers ns
then tempServers ns
else tempServers os
mH = if isJust $ tempMongoHost ns
then tempMongoHost ns
else tempMongoHost os
in TempSettings yF lF lC lP db aH aP ss mH
-- |Pull the YAML file from TempSettings. In the event that the current stack doesn't have a file, fallback to default.
--
-- IN THE EVENT THAT NO DEFAULT FILE EXISTS, THIS WILL LOOP INFINITELY!
loadableYmlFile ∷ TempSettings → FilePath
loadableYmlFile s = case tempYmlFile s of
(Just f) → f
Nothing → loadableYmlFile defaultSettings
| argiopetech/help | Help/Settings.hs | bsd-3-clause | 8,648 | 0 | 15 | 3,386 | 1,673 | 877 | 796 | 159 | 10 |
{-# LANGUAGE OverloadedStrings #-}
module Network.API.TLDR.Types.Time (
Time(..),
LastActive(..),
CreatedAt(..)
) where
import Data.Aeson
import Data.Aeson.Types (typeMismatch)
import Data.Text (unpack)
import Data.Time (parseTime, Day(..))
import Data.Time.RFC3339 (readRFC3339)
import Data.Time.LocalTime (ZonedTime(..))
import System.Locale (defaultTimeLocale)
newtype Time = Time
{time :: ZonedTime} deriving (Show)
instance FromJSON Time where
parseJSON (String t) =
case readRFC3339 (unpack t) of
Just d -> return $ Time d
_ -> fail "could not parse time"
parseJSON v = typeMismatch "Time" v
type LastActive = Time
type CreatedAt = Time
| joshrotenberg/tldrio-hs | Network/API/TLDR/Types/Time.hs | bsd-3-clause | 806 | 0 | 10 | 246 | 217 | 129 | 88 | 22 | 0 |
module FireHazard
(grid,
instructions,
lightsLit)
where
import qualified Data.ByteString.Lazy.Char8 as C
import Data.Vector as V (replicate,accum, Vector, foldr, sum)
data Switch = ON | OFF | Toggle deriving (Eq, Show)
type Grid = V.Vector (V.Vector Int)
rv :: V.Vector Int
rv = V.replicate 1000 0
grid :: Grid
grid = V.replicate 1000 rv
lightsLit :: Grid -> Int
lightsLit g = V.foldr (\e a -> (V.sum e) + a) 0 g
updateCol :: Int -> Switch -> Int
updateCol e v
| v == Toggle && e == 0 = 1
| v == Toggle && e == 1 = 0
| v == ON && e == 0 = 1
| v == OFF && e == 1 = 0
| otherwise = e
updateRow :: V.Vector Int -> [(Int,Switch)] -> V.Vector Int
updateRow v cu = V.accum updateCol v cu
updateGrid :: Grid -> [(Int,[(Int,Switch)])] -> Grid
updateGrid g ru = V.accum updateRow g ru
switchInst :: [C.ByteString] -> Switch
switchInst bs
| (head bs) == C.pack "turn" && (head $ tail bs) == C.pack "on" = ON
| (head bs) == C.pack "toggle" = Toggle
| otherwise = OFF
bsToGrid :: C.ByteString -> Int
bsToGrid bs = case C.readInt bs of
Nothing -> 0
Just (n, _) -> n
startEndInst :: [C.ByteString] -> ([Int], [Int])
startEndInst xs
| head xs == C.pack "turn" =
(map bsToGrid (C.split ',' (xs !! 2)),
map bsToGrid (C.split ',' (xs !! 4)))
| otherwise = ( map bsToGrid (C.split ',' (xs !! 1)),
map bsToGrid (C.split ',' (xs !! 3)))
instructions :: C.ByteString -> Grid -> Grid
instructions bs g = updateGrid g r
where s = C.split ' ' bs
si = switchInst s
((cs:rs:_), (ce:re:_)) = startEndInst s
c = [(x, si) | x <- [cs..ce]]
r = [(y, c) | y <- [rs..re]]
| cvsekhar/adventofcode | src/FireHazard.hs | bsd-3-clause | 1,901 | 0 | 12 | 668 | 845 | 444 | 401 | 48 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Authoring.Combinator.Meta where
import Control.Monad.Writer
import Data.Text (Text)
import Text.Authoring.Document
import Text.Authoring.Combinator.Writer
-- | wrap the argument @x@ using curly braces "{x}"
braces :: (MonadWriter t m, HasDocument t) => m () -> m ()
braces con = do
raw "{"
con
raw "}"
-- | command0 x = "\x "
command0 :: (MonadWriter t m, HasDocument t) => Text -> m ()
command0 x = do
raw "\\"
raw x
raw "{}"
-- | command1 x con = "\x{con}"
command1 :: (MonadWriter t m, HasDocument t) => Text -> m () -> m ()
command1 x con = do
raw "\\"
raw x
raw "{"
con
raw "}"
-- | commandI x con = "{\x con}"
commandI :: (MonadWriter t m, HasDocument t) => Text -> m () -> m ()
commandI x con = do
raw "{\\"
raw x
raw " "
con
raw "}"
-- | environment x con = "\begin{x}con\end{x}"
environment :: (MonadWriter t m, HasDocument t) => Text -> m () -> m ()
environment x con = do
raw "\\begin{"
raw x
raw "}"
con
raw "\\end{"
raw x
raw "}"
| nushio3/authoring | src/Text/Authoring/Combinator/Meta.hs | bsd-3-clause | 1,090 | 0 | 9 | 291 | 402 | 190 | 212 | 39 | 1 |
lend amount balance = let reserve = 100
newBalance = balance - amount
in if balance < reserve
then Nothing
else Just newBalance
lend2 amount balance = if amount < reserve * 0.5
then Just newBalance
else Nothing
where reserve = 100
newBalance = balance - amount
lend3 amount balance
| amount <= 0 = Nothing
| amount > reserve * 0.5 = Nothing
| otherwise = Just newBalance
where reserve = 100
newBalance = balance - amount
| NeonGraal/rwh-stack | ch03/Lending.hs | bsd-3-clause | 656 | 0 | 9 | 313 | 156 | 78 | 78 | 16 | 2 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
module Duckling.Quantity.EN.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Duckling.Dimensions.Types
import Duckling.Quantity.EN.Corpus
import Duckling.Testing.Asserts
tests :: TestTree
tests = testGroup "EN Tests"
[ makeCorpusTest [Seal Quantity] corpus
, makeCorpusTest [Seal Quantity] latentCorpus
]
| facebookincubator/duckling | tests/Duckling/Quantity/EN/Tests.hs | bsd-3-clause | 557 | 0 | 9 | 87 | 93 | 57 | 36 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
module Main where
import Arch
import MainCommon
import Data.String.Conv (toS)
import Data.Aeson (encode)
main :: IO ()
main = do
doc <- getDocumentByArgs
let packageStats = PackagesStats
<$> f "core"
<*> f "extra"
<*> f "community"
<*> f "multilib"
<*> f "unknown"
where f x = extractRights ( parseArchDoc x $ doc )
case packageStats of
Right pkgs -> do
writeFile "packageStatistics.json" . toS $ encode pkgs
print ("Success" :: String)
Left l -> putStrLn l
| chrissound/ArchLinuxPkgStatsScraper | app/Main.hs | bsd-3-clause | 628 | 0 | 15 | 188 | 179 | 88 | 91 | 22 | 2 |
module WeightForWeight where
import Data.Char (digitToInt)
import Data.List (sortBy)
import Data.Ord (comparing)
-- | Sort numbers by the sum of their digits (5 kyu)
-- | Link: https://biturl.io/SortWeight
-- | Refactored solution I came up with after completition of this kata
-- originally I compared the number and digSum separately (see Lesson learned)
orderWeight :: String -> String
orderWeight xs = unwords $ sortBy (comparing digSum) (words xs)
where
digSum x = (sum $ map digitToInt x, x)
-- | Lesson learned: When comparing tuples, x1 and x2 are compared first
-- and then if they are equal, y1 and y2 are compared second etc.
| Eugleo/Code-Wars | src/number-kata/WeightForWeight.hs | bsd-3-clause | 646 | 0 | 9 | 114 | 103 | 59 | 44 | 7 | 1 |
import Graphics.Rendering.Chart.Easy
import Graphics.Rendering.Chart.Backend.Cairo
import Data.Time.LocalTime
import Test.Examples.Prices(prices,mkDate,filterPrices)
prices' :: [(LocalTime,Double,Double)]
prices' = filterPrices prices (mkDate 1 1 2005) (mkDate 31 12 2006)
main = toFile def "example2_big.png" $ do
layoutlr_title .= "Price History"
layoutlr_left_axis . laxis_override .= axisGridHide
layoutlr_right_axis . laxis_override .= axisGridHide
plotLeft (line "price 1" [ [ (d,v) | (d,v,_) <- prices'] ])
plotRight (line "price 2" [ [ (d,v) | (d,_,v) <- prices'] ])
{-
import System.Environment(getArgs)
import Data.Colour.Names
import Data.Colour
import Control.Lens
import Data.Default.Class
import Data.Time.LocalTime
import Graphics.Rendering.Chart
import Graphics.Rendering.Chart.Backend.Cairo
import Prices(prices,mkDate,filterPrices)
prices' :: [(LocalTime,Double,Double)]
prices' = filterPrices prices (mkDate 1 1 2005) (mkDate 31 12 2006)
chart = toRenderable layout
where
price1 = plot_lines_style . line_color .~ opaque blue
$ plot_lines_values .~ [ [ (d,v) | (d,v,_) <- prices'] ]
$ plot_lines_title .~ "price 1"
$ def
price2 = plot_lines_style . line_color .~ opaque green
$ plot_lines_values .~ [ [ (d,v) | (d,_,v) <- prices'] ]
$ plot_lines_title .~ "price 2"
$ def
layout = layoutlr_title .~"Price History"
$ layoutlr_left_axis . laxis_override .~ axisGridHide
$ layoutlr_right_axis . laxis_override .~ axisGridHide
$ layoutlr_x_axis . laxis_override .~ axisGridHide
$ layoutlr_plots .~ [Left (toPlot price1),
Right (toPlot price2)]
$ layoutlr_grid_last .~ False
$ def
main = renderableToFile def "example2_big.png" chart
-}
| visood/bioalgo | test/Test/Examples/Plots/priceHistory.hs | bsd-3-clause | 1,859 | 0 | 15 | 413 | 218 | 122 | 96 | -1 | -1 |
{-# LANGUAGE RebindableSyntax #-}
-- Copyright : (C) 2009 Corey O'Connor
-- License : BSD-style (see the file LICENSE)
import Bind.Marshal.Prelude
import Bind.Marshal.Verify
import Bind.Marshal.StdLib.Dynamic.ByteString.Lazy.Des
main = run_test $ do
returnM () :: Test ()
| coreyoconnor/bind-marshal | test/verify_stdlib_dynamic_bytestring_lazy_des.hs | bsd-3-clause | 288 | 0 | 9 | 51 | 51 | 31 | 20 | 6 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
module Server where
import Control.Monad.IO.Class
import Control.Monad.Reader
import Control.Monad.Trans.Either
import Data.Aeson
import Data.Aeson.Types
import Data.Attoparsec.ByteString
import Data.ByteString (ByteString)
import Data.Int
import Data.List
import Data.String.Conversions
import Data.Time.Calendar
import GHC.Generics
import Lucid
import Servant.HTML.Lucid(HTML)
import Network.HTTP.Media ((//), (/:))
import Network.Wai
import Network.Wai.Handler.Warp
import Servant
import System.Directory
import Text.Blaze
import Text.Blaze.Html.Renderer.Utf8
import qualified Data.Aeson.Parser
import qualified Text.Blaze.Html
main :: IO ()
main = run 8081 app
-- 'serve' comes from servant and hands you a WAI Application,
-- which you can think of as an "abstract" web application,
-- not yet a webserver.
app :: Application
app = serve (Proxy :: Proxy (UserAPI :<|> PersonAPI)) (server :<|> server4)
type API = UserAPI :<|> PersonAPI
type UserAPI = "users" :> Get '[JSON] [User]
:<|> "albert" :> Get '[JSON] User
:<|> "isaac" :> Get '[JSON] User
type PersonAPI = "persons" :> Get '[JSON, HTML] [Person]
--------------
-------------
data User = User
{ name :: String
, age :: Int
, email :: String
-- , registration_date :: Day
} deriving (Eq, Show, Generic)
instance ToJSON User
isaac :: User
isaac = User "Isaac Newton" 372 "[email protected]" -- (fromGregorian 1683 3 1)
albert :: User
albert = User "Albert Einstein" 136 "[email protected]" -- (fromGregorian 1905 12 1)
users :: [User]
users = [isaac, albert]
server :: Server UserAPI
server = return users
:<|> return albert
:<|> return isaac
server4 = return persons
userAPI :: Proxy UserAPI
userAPI = Proxy
data Person = Person
{ firstName :: String
, lastName :: String
} deriving Generic -- for the JSON instance
instance ToJSON Person
-- HTML serialization of a single person
instance ToHtml Person where
toHtml person =
tr_ $ do
td_ (toHtml $ firstName person)
td_ (toHtml $ lastName person)
-- do not worry too much about this
toHtmlRaw = toHtml
-- HTML serialization of a list of persons
instance ToHtml [Person] where
toHtml persons = table_ $ do
tr_ $ do
th_ "first name"
th_ "last name"
-- this just calls toHtml on each person of the list
-- and concatenates the resulting pieces of HTML together
foldMap toHtml persons
toHtmlRaw = toHtml
persons :: [Person]
persons =
[ Person "Isaac" "Newton"
, Person "Albert" "Einstein"
]
personAPI :: Proxy PersonAPI
personAPI = Proxy
| odr/pers | app/Server.hs | bsd-3-clause | 2,863 | 0 | 12 | 544 | 670 | 386 | 284 | -1 | -1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE RecordWildCards #-}
module IOCP.Worker (
Worker,
new,
enqueue,
-- * Helpers
forkOSUnmasked,
) where
import Control.Concurrent
import Control.Exception (mask_)
import Control.Monad (forever, void)
import Data.IORef
import GHC.IO (unsafeUnmask)
data Worker = Worker
{ workerJobs :: !(IORef JobList)
, workerWake :: !(MVar ())
}
instance Eq Worker where
Worker a _ == Worker b _ = a == b
-- | Fork an OS thread, and return a handle for sending jobs to it.
new :: IO Worker
new = do
workerJobs <- newIORef id
workerWake <- newEmptyMVar
_ <- forkOSUnmasked $ forever $ do
takeMVar workerWake
jobs <- atomicModifyIORef workerJobs $ \jobs -> (id, jobs)
runJobList jobs
return Worker{..}
-- | Add a job to the work queue. Jobs are executed in the order they are
-- queued, and every job is run in the same OS thread.
--
-- A job should not block for long or throw an exception, as this will prevent
-- future jobs from running.
--
-- Exception safety: atomic, non-interruptible
enqueue :: Worker -> IO () -> IO ()
enqueue Worker{..} io =
mask_ $ do
!() <- atomicModifyIORef workerJobs $ \jobs -> (snocJobList jobs io, ())
void $ tryPutMVar workerWake ()
------------------------------------------------------------------------
-- Helpers
forkOSUnmasked :: IO () -> IO ThreadId
forkOSUnmasked = forkOS . unsafeUnmask
-- A difference list, but with (x >>) instead of (x :)
type JobList = IO () -> IO ()
-- | Append an action to the job list, so it will
-- run /after/ the existing actions.
snocJobList :: JobList -> IO () -> JobList
snocJobList dl io = dl . (io >>)
runJobList :: JobList -> IO ()
runJobList dl = dl (return ())
| joeyadams/haskell-iocp | IOCP/Worker.hs | bsd-3-clause | 1,794 | 0 | 14 | 418 | 450 | 236 | 214 | 42 | 1 |
module Graphomania.Builder.FromVertices
(
) where
-- TODO:
-- - Граф Fold по вершинам.
-- - Вершина. Внешний ID; Тэг (не испльзуется); Fold по рёбрам.
-- - Ребро. ID вершины, на которую оно указывает + Тэг.
-- ID вершины является внутренним идентификатором, но для вершины исходного графа.
-- 1. не использовать здесь внешние ID вершин.
-- они у нас будут храниться как тёги.
-- 2. Внутренние идентификаторы вершин меняются, как следствие мы строим
-- 2 карты: ИД исход -> Ид целевая, Ид целевая -> ИД исход
| schernichkin/BSPM | graphomania/src/Graphomania/Builder/FromVertices.hs | bsd-3-clause | 829 | 0 | 3 | 97 | 19 | 16 | 3 | 2 | 0 |
-- | Some auxiliary crypto types
module UTxO.Crypto (
-- * Key-pairs
RegularKeyPair(..)
, EncKeyPair(..)
, RedeemKeyPair(..)
, regularKeyPair
, encKeyPair
, encToRegular
-- * Abstract API
, SomeKeyPair(..)
, TxOwnedInput
, ClassifiedInputs(..)
, classifyInputs
-- * Delegation
, DelegatedTo(..)
) where
import Formatting (bprint, build, (%))
import qualified Formatting.Buildable
import Universum
import Pos.Chain.Delegation (ProxySKHeavy)
import Pos.Chain.Txp (TxIn)
import Pos.Core
import Pos.Crypto
{-------------------------------------------------------------------------------
Keypairs
-------------------------------------------------------------------------------}
data RegularKeyPair = RegularKeyPair {
regKpSec :: SecretKey
, regKpPub :: PublicKey
, regKpHash :: AddressHash PublicKey
}
deriving (Show)
data EncKeyPair = EncKeyPair {
encKpEnc :: EncryptedSecretKey
, encKpSec :: SecretKey
, encKpPub :: PublicKey
, encKpHash :: AddressHash PublicKey
}
deriving (Show)
data RedeemKeyPair = RedeemKeyPair {
redKpSec :: RedeemSecretKey
, redKpPub :: RedeemPublicKey
}
deriving (Show)
regularKeyPair :: SecretKey -> RegularKeyPair
regularKeyPair regKpSec = RegularKeyPair {..}
where
regKpPub = toPublic regKpSec
regKpHash = addressHash regKpPub
encKeyPair :: EncryptedSecretKey -> EncKeyPair
encKeyPair encKpEnc = EncKeyPair {..}
where
encKpSec = encToSecret encKpEnc
encKpPub = encToPublic encKpEnc
encKpHash = addressHash encKpPub
encToRegular :: EncKeyPair -> RegularKeyPair
encToRegular EncKeyPair{..} = RegularKeyPair{..}
where
regKpSec = encKpSec
regKpPub = encKpPub
regKpHash = encKpHash
{-------------------------------------------------------------------------------
Abstract over the various kinds of keypairs we have
-------------------------------------------------------------------------------}
data SomeKeyPair =
KeyPairRegular RegularKeyPair
| KeyPairEncrypted EncKeyPair
| KeyPairRedeem RedeemKeyPair
-- | An input to a transaction together with evidence that it's yours
--
-- (This is the singular form of 'TxOwnedInputs', which is defined in the
-- Cardano core libraries.)
type TxOwnedInput a = (a, TxIn)
data ClassifiedInputs =
-- | This is regular set of inputs
InputsRegular [TxOwnedInput RegularKeyPair]
-- | When redeeming from an AVVM address, we can only have a single input
| InputsRedeem (TxOwnedInput RedeemKeyPair)
-- | Classify a set of inputs
--
-- Maybe return an error message if the transaction contains an invalid
-- combination of inputs.
classifyInputs :: [TxOwnedInput SomeKeyPair] -> Either Text ClassifiedInputs
classifyInputs = \case
[] -> Left "No inputs"
(i:is) -> case classifyInput i of
Left i' -> go (InputsRegular [i']) is
Right i' -> go (InputsRedeem i' ) is
where
go :: ClassifiedInputs -> [TxOwnedInput SomeKeyPair] -> Either Text ClassifiedInputs
go acc [] = Right $ reverseAcc acc
go (InputsRedeem _) (_:_) = Left "Can only have a single redemption input"
go (InputsRegular acc) (i:is) =
case classifyInput i of
Left i' -> go (InputsRegular (i':acc)) is
Right _ -> Left "Cannot mix redemption inputs with other inputs"
classifyInput :: TxOwnedInput SomeKeyPair
-> Either (TxOwnedInput RegularKeyPair)
(TxOwnedInput RedeemKeyPair)
classifyInput (KeyPairRegular kp, inp) = Left (kp, inp)
classifyInput (KeyPairEncrypted kp, inp) = Left (encToRegular kp, inp)
classifyInput (KeyPairRedeem kp, inp) = Right (kp, inp)
reverseAcc :: ClassifiedInputs -> ClassifiedInputs
reverseAcc (InputsRegular inps) = InputsRegular $ reverse inps
reverseAcc (InputsRedeem inp) = InputsRedeem $ inp
{-------------------------------------------------------------------------------
Delegation
-------------------------------------------------------------------------------}
data DelegatedTo a = DelegatedTo {
delTo :: a
, delPSK :: ProxySKHeavy
}
deriving (Show)
{-------------------------------------------------------------------------------
Pretty-printing
-------------------------------------------------------------------------------}
instance Buildable RegularKeyPair where
build RegularKeyPair{..} = bprint
( "RegularKeyPair"
% "{ sec: " % build
% ", pub: " % build
% ", hash: " % build
% "}"
)
regKpSec
regKpPub
regKpHash
instance Buildable EncKeyPair where
build EncKeyPair{..} = bprint
( "EncKeyPair"
% "{ sec: " % build
% ", pub: " % build
% ", hash: " % build
% "}"
)
encKpSec
encKpPub
encKpHash
instance Buildable RedeemKeyPair where
build RedeemKeyPair{..} = bprint
( "RedeemKeyPair"
% "{ sec: " % build
% ", pub: " % build
% "}"
)
redKpSec
redKpPub
instance Buildable a => Buildable (DelegatedTo a) where
build DelegatedTo{..} = bprint
( "DelegatedTo"
% "{ to: " % build
% ", psk: " % build
% "}"
)
delTo
delPSK
| input-output-hk/cardano-sl | utxo/src/UTxO/Crypto.hs | apache-2.0 | 5,350 | 0 | 14 | 1,285 | 1,108 | 606 | 502 | -1 | -1 |
import Application (appMain)
import Prelude (IO)
main :: IO ()
main = appMain
| sulami/hGM | app/main.hs | bsd-3-clause | 103 | 0 | 6 | 38 | 32 | 18 | 14 | 4 | 1 |
-- (c) The University of Glasgow 2006
--
-- FamInstEnv: Type checked family instance declarations
{-# LANGUAGE CPP, GADTs, ScopedTypeVariables #-}
module FamInstEnv (
FamInst(..), FamFlavor(..), famInstAxiom, famInstTyCon, famInstRHS,
famInstsRepTyCons, famInstRepTyCon_maybe, dataFamInstRepTyCon,
pprFamInst, pprFamInsts,
mkImportedFamInst,
FamInstEnvs, FamInstEnv, emptyFamInstEnv, emptyFamInstEnvs,
extendFamInstEnv, deleteFromFamInstEnv, extendFamInstEnvList,
identicalFamInstHead, famInstEnvElts, familyInstances,
-- * CoAxioms
mkCoAxBranch, mkBranchedCoAxiom, mkUnbranchedCoAxiom, mkSingleCoAxiom,
mkNewTypeCoAxiom,
FamInstMatch(..),
lookupFamInstEnv, lookupFamInstEnvConflicts, lookupFamInstEnvByTyCon,
isDominatedBy, apartnessCheck,
-- Injectivity
InjectivityCheckResult(..),
lookupFamInstEnvInjectivityConflicts, injectiveBranches,
-- Normalisation
topNormaliseType, topNormaliseType_maybe,
normaliseType, normaliseTcApp,
reduceTyFamApp_maybe,
-- Flattening
flattenTys
) where
#include "HsVersions.h"
import Unify
import Type
import TyCoRep
import TyCon
import Coercion
import CoAxiom
import VarSet
import VarEnv
import Name
import PrelNames ( eqPrimTyConKey )
import UniqFM
import Outputable
import Maybes
import TrieMap
import Unique
import Util
import Var
import Pair
import SrcLoc
import FastString
import MonadUtils
import Control.Monad
import Data.Function ( on )
import Data.List( mapAccumL )
{-
************************************************************************
* *
Type checked family instance heads
* *
************************************************************************
Note [FamInsts and CoAxioms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* CoAxioms and FamInsts are just like
DFunIds and ClsInsts
* A CoAxiom is a System-FC thing: it can relate any two types
* A FamInst is a Haskell source-language thing, corresponding
to a type/data family instance declaration.
- The FamInst contains a CoAxiom, which is the evidence
for the instance
- The LHS of the CoAxiom is always of form F ty1 .. tyn
where F is a type family
-}
data FamInst -- See Note [FamInsts and CoAxioms]
= FamInst { fi_axiom :: CoAxiom Unbranched -- The new coercion axiom
-- introduced by this family
-- instance
-- INVARIANT: apart from freshening (see below)
-- fi_tvs = cab_tvs of the (single) axiom branch
-- fi_cvs = cab_cvs ...ditto...
-- fi_tys = cab_lhs ...ditto...
-- fi_rhs = cab_rhs ...ditto...
, fi_flavor :: FamFlavor
-- Everything below here is a redundant,
-- cached version of the two things above
-- except that the TyVars are freshened
, fi_fam :: Name -- Family name
-- Used for "rough matching"; same idea as for class instances
-- See Note [Rough-match field] in InstEnv
, fi_tcs :: [Maybe Name] -- Top of type args
-- INVARIANT: fi_tcs = roughMatchTcs fi_tys
-- Used for "proper matching"; ditto
, fi_tvs :: [TyVar] -- Template tyvars for full match
, fi_cvs :: [CoVar] -- Template covars for full match
-- Like ClsInsts, these variables are always fresh
-- See Note [Template tyvars are fresh] in InstEnv
, fi_tys :: [Type] -- The LHS type patterns
-- May be eta-reduced; see Note [Eta reduction for data families]
, fi_rhs :: Type -- the RHS, with its freshened vars
}
data FamFlavor
= SynFamilyInst -- A synonym family
| DataFamilyInst TyCon -- A data family, with its representation TyCon
{- Note [Eta reduction for data families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider this
data family T a b :: *
newtype instance T Int a = MkT (IO a) deriving( Monad )
We'd like this to work.
From the 'newtype instance' you might think we'd get:
newtype TInt a = MkT (IO a)
axiom ax1 a :: T Int a ~ TInt a -- The newtype-instance part
axiom ax2 a :: TInt a ~ IO a -- The newtype part
But now what can we do? We have this problem
Given: d :: Monad IO
Wanted: d' :: Monad (T Int) = d |> ????
What coercion can we use for the ???
Solution: eta-reduce both axioms, thus:
axiom ax1 :: T Int ~ TInt
axiom ax2 :: TInt ~ IO
Now
d' = d |> Monad (sym (ax2 ; ax1))
This eta reduction happens for data instances as well as newtype
instances. Here we want to eta-reduce the data family axiom.
All this is done in TcInstDcls.tcDataFamInstDecl.
See also Note [Newtype eta] in TyCon.
Bottom line:
For a FamInst with fi_flavour = DataFamilyInst rep_tc,
- fi_tvs may be shorter than tyConTyVars of rep_tc
- fi_tys may be shorter than tyConArity of the family tycon
i.e. LHS is unsaturated
- fi_rhs will be (rep_tc fi_tvs)
i.e. RHS is un-saturated
But when fi_flavour = SynFamilyInst,
- fi_tys has the exact arity of the family tycon
-}
-- Obtain the axiom of a family instance
famInstAxiom :: FamInst -> CoAxiom Unbranched
famInstAxiom = fi_axiom
-- Split the left-hand side of the FamInst
famInstSplitLHS :: FamInst -> (TyCon, [Type])
famInstSplitLHS (FamInst { fi_axiom = axiom, fi_tys = lhs })
= (coAxiomTyCon axiom, lhs)
-- Get the RHS of the FamInst
famInstRHS :: FamInst -> Type
famInstRHS = fi_rhs
-- Get the family TyCon of the FamInst
famInstTyCon :: FamInst -> TyCon
famInstTyCon = coAxiomTyCon . famInstAxiom
-- Return the representation TyCons introduced by data family instances, if any
famInstsRepTyCons :: [FamInst] -> [TyCon]
famInstsRepTyCons fis = [tc | FamInst { fi_flavor = DataFamilyInst tc } <- fis]
-- Extracts the TyCon for this *data* (or newtype) instance
famInstRepTyCon_maybe :: FamInst -> Maybe TyCon
famInstRepTyCon_maybe fi
= case fi_flavor fi of
DataFamilyInst tycon -> Just tycon
SynFamilyInst -> Nothing
dataFamInstRepTyCon :: FamInst -> TyCon
dataFamInstRepTyCon fi
= case fi_flavor fi of
DataFamilyInst tycon -> tycon
SynFamilyInst -> pprPanic "dataFamInstRepTyCon" (ppr fi)
{-
************************************************************************
* *
Pretty printing
* *
************************************************************************
-}
instance NamedThing FamInst where
getName = coAxiomName . fi_axiom
instance Outputable FamInst where
ppr = pprFamInst
-- Prints the FamInst as a family instance declaration
-- NB: FamInstEnv.pprFamInst is used only for internal, debug printing
-- See pprTyThing.pprFamInst for printing for the user
pprFamInst :: FamInst -> SDoc
pprFamInst famInst
= hang (pprFamInstHdr famInst) 2 (ifPprDebug debug_stuff)
where
ax = fi_axiom famInst
debug_stuff = vcat [ text "Coercion axiom:" <+> ppr ax
, text "Tvs:" <+> ppr (fi_tvs famInst)
, text "LHS:" <+> ppr (fi_tys famInst)
, text "RHS:" <+> ppr (fi_rhs famInst) ]
pprFamInstHdr :: FamInst -> SDoc
pprFamInstHdr fi@(FamInst {fi_flavor = flavor})
= pprTyConSort <+> pp_instance <+> pp_head
where
-- For *associated* types, say "type T Int = blah"
-- For *top level* type instances, say "type instance T Int = blah"
pp_instance
| isTyConAssoc fam_tc = empty
| otherwise = text "instance"
(fam_tc, etad_lhs_tys) = famInstSplitLHS fi
vanilla_pp_head = pprTypeApp fam_tc etad_lhs_tys
pp_head | DataFamilyInst rep_tc <- flavor
, isAlgTyCon rep_tc
, let extra_tvs = dropList etad_lhs_tys (tyConTyVars rep_tc)
, not (null extra_tvs)
= getPprStyle $ \ sty ->
if debugStyle sty
then vanilla_pp_head -- With -dppr-debug just show it as-is
else pprTypeApp fam_tc (etad_lhs_tys ++ mkTyVarTys extra_tvs)
-- Without -dppr-debug, eta-expand
-- See Trac #8674
-- (This is probably over the top now that we use this
-- only for internal debug printing; PprTyThing.pprFamInst
-- is used for user-level printing.)
| otherwise
= vanilla_pp_head
pprTyConSort = case flavor of
SynFamilyInst -> text "type"
DataFamilyInst tycon
| isDataTyCon tycon -> text "data"
| isNewTyCon tycon -> text "newtype"
| isAbstractTyCon tycon -> text "data"
| otherwise -> text "WEIRD" <+> ppr tycon
pprFamInsts :: [FamInst] -> SDoc
pprFamInsts finsts = vcat (map pprFamInst finsts)
{-
Note [Lazy axiom match]
~~~~~~~~~~~~~~~~~~~~~~~
It is Vitally Important that mkImportedFamInst is *lazy* in its axiom
parameter. The axiom is loaded lazily, via a forkM, in TcIface. Sometime
later, mkImportedFamInst is called using that axiom. However, the axiom
may itself depend on entities which are not yet loaded as of the time
of the mkImportedFamInst. Thus, if mkImportedFamInst eagerly looks at the
axiom, a dependency loop spontaneously appears and GHC hangs. The solution
is simply for mkImportedFamInst never, ever to look inside of the axiom
until everything else is good and ready to do so. We can assume that this
readiness has been achieved when some other code pulls on the axiom in the
FamInst. Thus, we pattern match on the axiom lazily (in the where clause,
not in the parameter list) and we assert the consistency of names there
also.
-}
-- Make a family instance representation from the information found in an
-- interface file. In particular, we get the rough match info from the iface
-- (instead of computing it here).
mkImportedFamInst :: Name -- Name of the family
-> [Maybe Name] -- Rough match info
-> CoAxiom Unbranched -- Axiom introduced
-> FamInst -- Resulting family instance
mkImportedFamInst fam mb_tcs axiom
= FamInst {
fi_fam = fam,
fi_tcs = mb_tcs,
fi_tvs = tvs,
fi_cvs = cvs,
fi_tys = tys,
fi_rhs = rhs,
fi_axiom = axiom,
fi_flavor = flavor }
where
-- See Note [Lazy axiom match]
~(CoAxBranch { cab_lhs = tys
, cab_tvs = tvs
, cab_cvs = cvs
, cab_rhs = rhs }) = coAxiomSingleBranch axiom
-- Derive the flavor for an imported FamInst rather disgustingly
-- Maybe we should store it in the IfaceFamInst?
flavor = case splitTyConApp_maybe rhs of
Just (tc, _)
| Just ax' <- tyConFamilyCoercion_maybe tc
, ax' == axiom
-> DataFamilyInst tc
_ -> SynFamilyInst
{-
************************************************************************
* *
FamInstEnv
* *
************************************************************************
Note [FamInstEnv]
~~~~~~~~~~~~~~~~~
A FamInstEnv maps a family name to the list of known instances for that family.
The same FamInstEnv includes both 'data family' and 'type family' instances.
Type families are reduced during type inference, but not data families;
the user explains when to use a data family instance by using contructors
and pattern matching.
Nevertheless it is still useful to have data families in the FamInstEnv:
- For finding overlaps and conflicts
- For finding the representation type...see FamInstEnv.topNormaliseType
and its call site in Simplify
- In standalone deriving instance Eq (T [Int]) we need to find the
representation type for T [Int]
Note [Varying number of patterns for data family axioms]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For data families, the number of patterns may vary between instances.
For example
data family T a b
data instance T Int a = T1 a | T2
data instance T Bool [a] = T3 a
Then we get a data type for each instance, and an axiom:
data TInt a = T1 a | T2
data TBoolList a = T3 a
axiom ax7 :: T Int ~ TInt -- Eta-reduced
axiom ax8 a :: T Bool [a] ~ TBoolList a
These two axioms for T, one with one pattern, one with two;
see Note [Eta reduction for data families]
-}
type FamInstEnv = UniqFM FamilyInstEnv -- Maps a family to its instances
-- See Note [FamInstEnv]
type FamInstEnvs = (FamInstEnv, FamInstEnv)
-- External package inst-env, Home-package inst-env
newtype FamilyInstEnv
= FamIE [FamInst] -- The instances for a particular family, in any order
instance Outputable FamilyInstEnv where
ppr (FamIE fs) = text "FamIE" <+> vcat (map ppr fs)
-- INVARIANTS:
-- * The fs_tvs are distinct in each FamInst
-- of a range value of the map (so we can safely unify them)
emptyFamInstEnvs :: (FamInstEnv, FamInstEnv)
emptyFamInstEnvs = (emptyFamInstEnv, emptyFamInstEnv)
emptyFamInstEnv :: FamInstEnv
emptyFamInstEnv = emptyUFM
famInstEnvElts :: FamInstEnv -> [FamInst]
famInstEnvElts fi = [elt | FamIE elts <- eltsUFM fi, elt <- elts]
familyInstances :: (FamInstEnv, FamInstEnv) -> TyCon -> [FamInst]
familyInstances (pkg_fie, home_fie) fam
= get home_fie ++ get pkg_fie
where
get env = case lookupUFM env fam of
Just (FamIE insts) -> insts
Nothing -> []
extendFamInstEnvList :: FamInstEnv -> [FamInst] -> FamInstEnv
extendFamInstEnvList inst_env fis = foldl extendFamInstEnv inst_env fis
extendFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv
extendFamInstEnv inst_env
ins_item@(FamInst {fi_fam = cls_nm})
= addToUFM_C add inst_env cls_nm (FamIE [ins_item])
where
add (FamIE items) _ = FamIE (ins_item:items)
deleteFromFamInstEnv :: FamInstEnv -> FamInst -> FamInstEnv
-- Used only for overriding in GHCi
deleteFromFamInstEnv inst_env fam_inst@(FamInst {fi_fam = fam_nm})
= adjustUFM adjust inst_env fam_nm
where
adjust :: FamilyInstEnv -> FamilyInstEnv
adjust (FamIE items)
= FamIE (filterOut (identicalFamInstHead fam_inst) items)
identicalFamInstHead :: FamInst -> FamInst -> Bool
-- ^ True when the LHSs are identical
-- Used for overriding in GHCi
identicalFamInstHead (FamInst { fi_axiom = ax1 }) (FamInst { fi_axiom = ax2 })
= coAxiomTyCon ax1 == coAxiomTyCon ax2
&& numBranches brs1 == numBranches brs2
&& and ((zipWith identical_branch `on` fromBranches) brs1 brs2)
where
brs1 = coAxiomBranches ax1
brs2 = coAxiomBranches ax2
identical_branch br1 br2
= isJust (tcMatchTys lhs1 lhs2)
&& isJust (tcMatchTys lhs2 lhs1)
where
lhs1 = coAxBranchLHS br1
lhs2 = coAxBranchLHS br2
{-
************************************************************************
* *
Compatibility
* *
************************************************************************
Note [Apartness]
~~~~~~~~~~~~~~~~
In dealing with closed type families, we must be able to check that one type
will never reduce to another. This check is called /apartness/. The check
is always between a target (which may be an arbitrary type) and a pattern.
Here is how we do it:
apart(target, pattern) = not (unify(flatten(target), pattern))
where flatten (implemented in flattenTys, below) converts all type-family
applications into fresh variables. (See Note [Flattening].)
Note [Compatibility]
~~~~~~~~~~~~~~~~~~~~
Two patterns are /compatible/ if either of the following conditions hold:
1) The patterns are apart.
2) The patterns unify with a substitution S, and their right hand sides
equal under that substitution.
For open type families, only compatible instances are allowed. For closed
type families, the story is slightly more complicated. Consider the following:
type family F a where
F Int = Bool
F a = Int
g :: Show a => a -> F a
g x = length (show x)
Should that type-check? No. We need to allow for the possibility that 'a'
might be Int and therefore 'F a' should be Bool. We can simplify 'F a' to Int
only when we can be sure that 'a' is not Int.
To achieve this, after finding a possible match within the equations, we have to
go back to all previous equations and check that, under the
substitution induced by the match, other branches are surely apart. (See
Note [Apartness].) This is similar to what happens with class
instance selection, when we need to guarantee that there is only a match and
no unifiers. The exact algorithm is different here because the the
potentially-overlapping group is closed.
As another example, consider this:
type family G x where
G Int = Bool
G a = Double
type family H y
-- no instances
Now, we want to simplify (G (H Char)). We can't, because (H Char) might later
simplify to be Int. So, (G (H Char)) is stuck, for now.
While everything above is quite sound, it isn't as expressive as we'd like.
Consider this:
type family J a where
J Int = Int
J a = a
Can we simplify (J b) to b? Sure we can. Yes, the first equation matches if
b is instantiated with Int, but the RHSs coincide there, so it's all OK.
So, the rule is this: when looking up a branch in a closed type family, we
find a branch that matches the target, but then we make sure that the target
is apart from every previous *incompatible* branch. We don't check the
branches that are compatible with the matching branch, because they are either
irrelevant (clause 1 of compatible) or benign (clause 2 of compatible).
-}
-- See Note [Compatibility]
compatibleBranches :: CoAxBranch -> CoAxBranch -> Bool
compatibleBranches (CoAxBranch { cab_lhs = lhs1, cab_rhs = rhs1 })
(CoAxBranch { cab_lhs = lhs2, cab_rhs = rhs2 })
= case tcUnifyTysFG (const BindMe) lhs1 lhs2 of
SurelyApart -> True
Unifiable subst
| Type.substTy subst rhs1 `eqType` Type.substTy subst rhs2
-> True
_ -> False
-- | Result of testing two type family equations for injectiviy.
data InjectivityCheckResult
= InjectivityAccepted
-- ^ Either RHSs are distinct or unification of RHSs leads to unification of
-- LHSs
| InjectivityUnified CoAxBranch CoAxBranch
-- ^ RHSs unify but LHSs don't unify under that substitution. Relevant for
-- closed type families where equation after unification might be
-- overlpapped (in which case it is OK if they don't unify). Constructor
-- stores axioms after unification.
-- | Check whether two type family axioms don't violate injectivity annotation.
injectiveBranches :: [Bool] -> CoAxBranch -> CoAxBranch
-> InjectivityCheckResult
injectiveBranches injectivity
ax1@(CoAxBranch { cab_lhs = lhs1, cab_rhs = rhs1 })
ax2@(CoAxBranch { cab_lhs = lhs2, cab_rhs = rhs2 })
-- See Note [Verifying injectivity annotation]. This function implements first
-- check described there.
= let getInjArgs = filterByList injectivity
in case tcUnifyTyWithTFs True rhs1 rhs2 of -- True = two-way pre-unification
Nothing -> InjectivityAccepted -- RHS are different, so equations are
-- injective.
Just subst -> -- RHS unify under a substitution
let lhs1Subst = Type.substTys subst (getInjArgs lhs1)
lhs2Subst = Type.substTys subst (getInjArgs lhs2)
-- If LHSs are equal under the substitution used for RHSs then this pair
-- of equations does not violate injectivity annotation. If LHSs are not
-- equal under that substitution then this pair of equations violates
-- injectivity annotation, but for closed type families it still might
-- be the case that one LHS after substitution is unreachable.
in if eqTypes lhs1Subst lhs2Subst
then InjectivityAccepted
else InjectivityUnified ( ax1 { cab_lhs = Type.substTys subst lhs1
, cab_rhs = Type.substTy subst rhs1 })
( ax2 { cab_lhs = Type.substTys subst lhs2
, cab_rhs = Type.substTy subst rhs2 })
-- takes a CoAxiom with unknown branch incompatibilities and computes
-- the compatibilities
-- See Note [Storing compatibility] in CoAxiom
computeAxiomIncomps :: [CoAxBranch] -> [CoAxBranch]
computeAxiomIncomps branches
= snd (mapAccumL go [] branches)
where
go :: [CoAxBranch] -> CoAxBranch -> ([CoAxBranch], CoAxBranch)
go prev_brs cur_br
= (cur_br : prev_brs, new_br)
where
new_br = cur_br { cab_incomps = mk_incomps prev_brs cur_br }
mk_incomps :: [CoAxBranch] -> CoAxBranch -> [CoAxBranch]
mk_incomps prev_brs cur_br
= filter (not . compatibleBranches cur_br) prev_brs
{-
************************************************************************
* *
Constructing axioms
These functions are here because tidyType / tcUnifyTysFG
are not available in CoAxiom
Also computeAxiomIncomps is too sophisticated for CoAxiom
* *
************************************************************************
Note [Tidy axioms when we build them]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We print out axioms and don't want to print stuff like
F k k a b = ...
Instead we must tidy those kind variables. See Trac #7524.
-}
-- all axiom roles are Nominal, as this is only used with type families
mkCoAxBranch :: [TyVar] -- original, possibly stale, tyvars
-> [CoVar] -- possibly stale covars
-> [Type] -- LHS patterns
-> Type -- RHS
-> [Role]
-> SrcSpan
-> CoAxBranch
mkCoAxBranch tvs cvs lhs rhs roles loc
= CoAxBranch { cab_tvs = tvs1
, cab_cvs = cvs1
, cab_lhs = tidyTypes env lhs
, cab_roles = roles
, cab_rhs = tidyType env rhs
, cab_loc = loc
, cab_incomps = placeHolderIncomps }
where
(env1, tvs1) = tidyTyCoVarBndrs emptyTidyEnv tvs
(env, cvs1) = tidyTyCoVarBndrs env1 cvs
-- See Note [Tidy axioms when we build them]
-- all of the following code is here to avoid mutual dependencies with
-- Coercion
mkBranchedCoAxiom :: Name -> TyCon -> [CoAxBranch] -> CoAxiom Branched
mkBranchedCoAxiom ax_name fam_tc branches
= CoAxiom { co_ax_unique = nameUnique ax_name
, co_ax_name = ax_name
, co_ax_tc = fam_tc
, co_ax_role = Nominal
, co_ax_implicit = False
, co_ax_branches = manyBranches (computeAxiomIncomps branches) }
mkUnbranchedCoAxiom :: Name -> TyCon -> CoAxBranch -> CoAxiom Unbranched
mkUnbranchedCoAxiom ax_name fam_tc branch
= CoAxiom { co_ax_unique = nameUnique ax_name
, co_ax_name = ax_name
, co_ax_tc = fam_tc
, co_ax_role = Nominal
, co_ax_implicit = False
, co_ax_branches = unbranched (branch { cab_incomps = [] }) }
mkSingleCoAxiom :: Role -> Name
-> [TyVar] -> [CoVar] -> TyCon -> [Type] -> Type
-> CoAxiom Unbranched
-- Make a single-branch CoAxiom, incluidng making the branch itself
-- Used for both type family (Nominal) and data family (Representational)
-- axioms, hence passing in the Role
mkSingleCoAxiom role ax_name tvs cvs fam_tc lhs_tys rhs_ty
= CoAxiom { co_ax_unique = nameUnique ax_name
, co_ax_name = ax_name
, co_ax_tc = fam_tc
, co_ax_role = role
, co_ax_implicit = False
, co_ax_branches = unbranched (branch { cab_incomps = [] }) }
where
branch = mkCoAxBranch tvs cvs lhs_tys rhs_ty
(map (const Nominal) tvs)
(getSrcSpan ax_name)
-- | Create a coercion constructor (axiom) suitable for the given
-- newtype 'TyCon'. The 'Name' should be that of a new coercion
-- 'CoAxiom', the 'TyVar's the arguments expected by the @newtype@ and
-- the type the appropriate right hand side of the @newtype@, with
-- the free variables a subset of those 'TyVar's.
mkNewTypeCoAxiom :: Name -> TyCon -> [TyVar] -> [Role] -> Type -> CoAxiom Unbranched
mkNewTypeCoAxiom name tycon tvs roles rhs_ty
= CoAxiom { co_ax_unique = nameUnique name
, co_ax_name = name
, co_ax_implicit = True -- See Note [Implicit axioms] in TyCon
, co_ax_role = Representational
, co_ax_tc = tycon
, co_ax_branches = unbranched (branch { cab_incomps = [] }) }
where
branch = mkCoAxBranch tvs [] (mkTyVarTys tvs) rhs_ty
roles (getSrcSpan name)
{-
************************************************************************
* *
Looking up a family instance
* *
************************************************************************
@lookupFamInstEnv@ looks up in a @FamInstEnv@, using a one-way match.
Multiple matches are only possible in case of type families (not data
families), and then, it doesn't matter which match we choose (as the
instances are guaranteed confluent).
We return the matching family instances and the type instance at which it
matches. For example, if we lookup 'T [Int]' and have a family instance
data instance T [a] = ..
desugared to
data :R42T a = ..
coe :Co:R42T a :: T [a] ~ :R42T a
we return the matching instance '(FamInst{.., fi_tycon = :R42T}, Int)'.
-}
-- when matching a type family application, we get a FamInst,
-- and the list of types the axiom should be applied to
data FamInstMatch = FamInstMatch { fim_instance :: FamInst
, fim_tys :: [Type]
, fim_cos :: [Coercion]
}
-- See Note [Over-saturated matches]
instance Outputable FamInstMatch where
ppr (FamInstMatch { fim_instance = inst
, fim_tys = tys
, fim_cos = cos })
= text "match with" <+> parens (ppr inst) <+> ppr tys <+> ppr cos
lookupFamInstEnvByTyCon :: FamInstEnvs -> TyCon -> [FamInst]
lookupFamInstEnvByTyCon (pkg_ie, home_ie) fam_tc
= get pkg_ie ++ get home_ie
where
get ie = case lookupUFM ie fam_tc of
Nothing -> []
Just (FamIE fis) -> fis
lookupFamInstEnv
:: FamInstEnvs
-> TyCon -> [Type] -- What we are looking for
-> [FamInstMatch] -- Successful matches
-- Precondition: the tycon is saturated (or over-saturated)
lookupFamInstEnv
= lookup_fam_inst_env match
where
match _ _ tpl_tys tys = tcMatchTys tpl_tys tys
lookupFamInstEnvConflicts
:: FamInstEnvs
-> FamInst -- Putative new instance
-> [FamInstMatch] -- Conflicting matches (don't look at the fim_tys field)
-- E.g. when we are about to add
-- f : type instance F [a] = a->a
-- we do (lookupFamInstConflicts f [b])
-- to find conflicting matches
--
-- Precondition: the tycon is saturated (or over-saturated)
lookupFamInstEnvConflicts envs fam_inst@(FamInst { fi_axiom = new_axiom })
= lookup_fam_inst_env my_unify envs fam tys
where
(fam, tys) = famInstSplitLHS fam_inst
-- In example above, fam tys' = F [b]
my_unify (FamInst { fi_axiom = old_axiom }) tpl_tvs tpl_tys _
= ASSERT2( tyCoVarsOfTypes tys `disjointVarSet` tpl_tvs,
(ppr fam <+> ppr tys) $$
(ppr tpl_tvs <+> ppr tpl_tys) )
-- Unification will break badly if the variables overlap
-- They shouldn't because we allocate separate uniques for them
if compatibleBranches (coAxiomSingleBranch old_axiom) new_branch
then Nothing
else Just noSubst
-- Note [Family instance overlap conflicts]
noSubst = panic "lookupFamInstEnvConflicts noSubst"
new_branch = coAxiomSingleBranch new_axiom
--------------------------------------------------------------------------------
-- Type family injectivity checking bits --
--------------------------------------------------------------------------------
{- Note [Verifying injectivity annotation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Injectivity means that the RHS of a type family uniquely determines the LHS (see
Note [Type inference for type families with injectivity]). User informs about
injectivity using an injectivity annotation and it is GHC's task to verify that
that annotation is correct wrt. to type family equations. Whenever we see a new
equation of a type family we need to make sure that adding this equation to
already known equations of a type family does not violate injectivity annotation
supplied by the user (see Note [Injectivity annotation]). Of course if the type
family has no injectivity annotation then no check is required. But if a type
family has injectivity annotation we need to make sure that the following
conditions hold:
1. For each pair of *different* equations of a type family, one of the following
conditions holds:
A: RHSs are different.
B1: OPEN TYPE FAMILIES: If the RHSs can be unified under some substitution
then it must be possible to unify the LHSs under the same substitution.
Example:
type family FunnyId a = r | r -> a
type instance FunnyId Int = Int
type instance FunnyId a = a
RHSs of these two equations unify under [ a |-> Int ] substitution.
Under this substitution LHSs are equal therefore these equations don't
violate injectivity annotation.
B2: CLOSED TYPE FAMILIES: If the RHSs can be unified under some
substitution then either the LHSs unify under the same substitution or
the LHS of the latter equation is overlapped by earlier equations.
Example 1:
type family SwapIntChar a = r | r -> a where
SwapIntChar Int = Char
SwapIntChar Char = Int
SwapIntChar a = a
Say we are checking the last two equations. RHSs unify under [ a |->
Int ] substitution but LHSs don't. So we apply the substitution to LHS
of last equation and check whether it is overlapped by any of previous
equations. Since it is overlapped by the first equation we conclude
that pair of last two equations does not violate injectivity
annotation.
A special case of B is when RHSs unify with an empty substitution ie. they
are identical.
If any of the above two conditions holds we conclude that the pair of
equations does not violate injectivity annotation. But if we find a pair
of equations where neither of the above holds we report that this pair
violates injectivity annotation because for a given RHS we don't have a
unique LHS. (Note that (B) actually implies (A).)
Note that we only take into account these LHS patterns that were declared
as injective.
2. If a RHS of a type family equation is a bare type variable then
all LHS variables (including implicit kind variables) also have to be bare.
In other words, this has to be a sole equation of that type family and it has
to cover all possible patterns. So for example this definition will be
rejected:
type family W1 a = r | r -> a
type instance W1 [a] = a
If it were accepted we could call `W1 [W1 Int]`, which would reduce to
`W1 Int` and then by injectivity we could conclude that `[W1 Int] ~ Int`,
which is bogus.
3. If a RHS of a type family equation is a type family application then the type
family is rejected as not injective.
4. If a LHS type variable that is declared as injective is not mentioned on
injective position in the RHS then the type family is rejected as not
injective. "Injective position" means either an argument to a type
constructor or argument to a type family on injective position.
See also Note [Injective type families] in TyCon
-}
-- | Check whether an open type family equation can be added to already existing
-- instance environment without causing conflicts with supplied injectivity
-- annotations. Returns list of conflicting axioms (type instance
-- declarations).
lookupFamInstEnvInjectivityConflicts
:: [Bool] -- injectivity annotation for this type family instance
-- INVARIANT: list contains at least one True value
-> FamInstEnvs -- all type instances seens so far
-> FamInst -- new type instance that we're checking
-> [CoAxBranch] -- conflicting instance delcarations
lookupFamInstEnvInjectivityConflicts injList (pkg_ie, home_ie)
fam_inst@(FamInst { fi_axiom = new_axiom })
-- See Note [Verifying injectivity annotation]. This function implements
-- check (1.B1) for open type families described there.
= lookup_inj_fam_conflicts home_ie ++ lookup_inj_fam_conflicts pkg_ie
where
fam = famInstTyCon fam_inst
new_branch = coAxiomSingleBranch new_axiom
-- filtering function used by `lookup_inj_fam_conflicts` to check whether
-- a pair of equations conflicts with the injectivity annotation.
isInjConflict (FamInst { fi_axiom = old_axiom })
| InjectivityAccepted <-
injectiveBranches injList (coAxiomSingleBranch old_axiom) new_branch
= False -- no conflict
| otherwise = True
lookup_inj_fam_conflicts ie
| isOpenFamilyTyCon fam, Just (FamIE insts) <- lookupUFM ie fam
= map (coAxiomSingleBranch . fi_axiom) $
filter isInjConflict insts
| otherwise = []
--------------------------------------------------------------------------------
-- Type family overlap checking bits --
--------------------------------------------------------------------------------
{-
Note [Family instance overlap conflicts]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- In the case of data family instances, any overlap is fundamentally a
conflict (as these instances imply injective type mappings).
- In the case of type family instances, overlap is admitted as long as
the right-hand sides of the overlapping rules coincide under the
overlap substitution. eg
type instance F a Int = a
type instance F Int b = b
These two overlap on (F Int Int) but then both RHSs are Int,
so all is well. We require that they are syntactically equal;
anything else would be difficult to test for at this stage.
-}
------------------------------------------------------------
-- Might be a one-way match or a unifier
type MatchFun = FamInst -- The FamInst template
-> TyVarSet -> [Type] -- fi_tvs, fi_tys of that FamInst
-> [Type] -- Target to match against
-> Maybe TCvSubst
lookup_fam_inst_env' -- The worker, local to this module
:: MatchFun
-> FamInstEnv
-> TyCon -> [Type] -- What we are looking for
-> [FamInstMatch]
lookup_fam_inst_env' match_fun ie fam match_tys
| isOpenFamilyTyCon fam
, Just (FamIE insts) <- lookupUFM ie fam
= find insts -- The common case
| otherwise = []
where
find [] = []
find (item@(FamInst { fi_tcs = mb_tcs, fi_tvs = tpl_tvs, fi_cvs = tpl_cvs
, fi_tys = tpl_tys }) : rest)
-- Fast check for no match, uses the "rough match" fields
| instanceCantMatch rough_tcs mb_tcs
= find rest
-- Proper check
| Just subst <- match_fun item (mkVarSet tpl_tvs) tpl_tys match_tys1
= (FamInstMatch { fim_instance = item
, fim_tys = substTyVars subst tpl_tvs `chkAppend` match_tys2
, fim_cos = ASSERT( all (isJust . lookupCoVar subst) tpl_cvs )
substCoVars subst tpl_cvs
})
: find rest
-- No match => try next
| otherwise
= find rest
where
(rough_tcs, match_tys1, match_tys2) = split_tys tpl_tys
-- Precondition: the tycon is saturated (or over-saturated)
-- Deal with over-saturation
-- See Note [Over-saturated matches]
split_tys tpl_tys
| isTypeFamilyTyCon fam
= pre_rough_split_tys
| otherwise
= let (match_tys1, match_tys2) = splitAtList tpl_tys match_tys
rough_tcs = roughMatchTcs match_tys1
in (rough_tcs, match_tys1, match_tys2)
(pre_match_tys1, pre_match_tys2) = splitAt (tyConArity fam) match_tys
pre_rough_split_tys
= (roughMatchTcs pre_match_tys1, pre_match_tys1, pre_match_tys2)
lookup_fam_inst_env -- The worker, local to this module
:: MatchFun
-> FamInstEnvs
-> TyCon -> [Type] -- What we are looking for
-> [FamInstMatch] -- Successful matches
-- Precondition: the tycon is saturated (or over-saturated)
lookup_fam_inst_env match_fun (pkg_ie, home_ie) fam tys
= lookup_fam_inst_env' match_fun home_ie fam tys
++ lookup_fam_inst_env' match_fun pkg_ie fam tys
{-
Note [Over-saturated matches]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It's ok to look up an over-saturated type constructor. E.g.
type family F a :: * -> *
type instance F (a,b) = Either (a->b)
The type instance gives rise to a newtype TyCon (at a higher kind
which you can't do in Haskell!):
newtype FPair a b = FP (Either (a->b))
Then looking up (F (Int,Bool) Char) will return a FamInstMatch
(FPair, [Int,Bool,Char])
The "extra" type argument [Char] just stays on the end.
We handle data families and type families separately here:
* For type families, all instances of a type family must have the
same arity, so we can precompute the split between the match_tys
and the overflow tys. This is done in pre_rough_split_tys.
* For data family instances, though, we need to re-split for each
instance, because the breakdown might be different for each
instance. Why? Because of eta reduction; see
Note [Eta reduction for data families].
-}
-- checks if one LHS is dominated by a list of other branches
-- in other words, if an application would match the first LHS, it is guaranteed
-- to match at least one of the others. The RHSs are ignored.
-- This algorithm is conservative:
-- True -> the LHS is definitely covered by the others
-- False -> no information
-- It is currently (Oct 2012) used only for generating errors for
-- inaccessible branches. If these errors go unreported, no harm done.
-- This is defined here to avoid a dependency from CoAxiom to Unify
isDominatedBy :: CoAxBranch -> [CoAxBranch] -> Bool
isDominatedBy branch branches
= or $ map match branches
where
lhs = coAxBranchLHS branch
match (CoAxBranch { cab_lhs = tys })
= isJust $ tcMatchTys tys lhs
{-
************************************************************************
* *
Choosing an axiom application
* *
************************************************************************
The lookupFamInstEnv function does a nice job for *open* type families,
but we also need to handle closed ones when normalising a type:
-}
reduceTyFamApp_maybe :: FamInstEnvs
-> Role -- Desired role of result coercion
-> TyCon -> [Type]
-> Maybe (Coercion, Type)
-- Attempt to do a *one-step* reduction of a type-family application
-- but *not* newtypes
-- Works on type-synonym families always; data-families only if
-- the role we seek is representational
-- It does *not* normlise the type arguments first, so this may not
-- go as far as you want. If you want normalised type arguments,
-- use normaliseTcArgs first.
--
-- The TyCon can be oversaturated.
-- Works on both open and closed families
--
-- Always returns a *homogeneous* coercion -- type family reductions are always
-- homogeneous
reduceTyFamApp_maybe envs role tc tys
| Phantom <- role
= Nothing
| case role of
Representational -> isOpenFamilyTyCon tc
_ -> isOpenTypeFamilyTyCon tc
-- If we seek a representational coercion
-- (e.g. the call in topNormaliseType_maybe) then we can
-- unwrap data families as well as type-synonym families;
-- otherwise only type-synonym families
, FamInstMatch { fim_instance = FamInst { fi_axiom = ax }
, fim_tys = inst_tys
, fim_cos = inst_cos } : _ <- lookupFamInstEnv envs tc tys
-- NB: Allow multiple matches because of compatible overlap
= let co = mkUnbranchedAxInstCo role ax inst_tys inst_cos
ty = pSnd (coercionKind co)
in Just (co, ty)
| Just ax <- isClosedSynFamilyTyConWithAxiom_maybe tc
, Just (ind, inst_tys, inst_cos) <- chooseBranch ax tys
= let co = mkAxInstCo role ax ind inst_tys inst_cos
ty = pSnd (coercionKind co)
in Just (co, ty)
| Just ax <- isBuiltInSynFamTyCon_maybe tc
, Just (coax,ts,ty) <- sfMatchFam ax tys
= let co = mkAxiomRuleCo coax (zipWith mkReflCo (coaxrAsmpRoles coax) ts)
in Just (co, ty)
| otherwise
= Nothing
-- The axiom can be oversaturated. (Closed families only.)
chooseBranch :: CoAxiom Branched -> [Type]
-> Maybe (BranchIndex, [Type], [Coercion]) -- found match, with args
chooseBranch axiom tys
= do { let num_pats = coAxiomNumPats axiom
(target_tys, extra_tys) = splitAt num_pats tys
branches = coAxiomBranches axiom
; (ind, inst_tys, inst_cos)
<- findBranch (fromBranches branches) target_tys
; return ( ind, inst_tys `chkAppend` extra_tys, inst_cos ) }
-- The axiom must *not* be oversaturated
findBranch :: [CoAxBranch] -- branches to check
-> [Type] -- target types
-> Maybe (BranchIndex, [Type], [Coercion])
-- coercions relate requested types to returned axiom LHS at role N
findBranch branches target_tys
= go 0 branches
where
go ind (branch@(CoAxBranch { cab_tvs = tpl_tvs, cab_cvs = tpl_cvs
, cab_lhs = tpl_lhs
, cab_incomps = incomps }) : rest)
= let in_scope = mkInScopeSet (unionVarSets $
map (tyCoVarsOfTypes . coAxBranchLHS) incomps)
-- See Note [Flattening] below
flattened_target = flattenTys in_scope target_tys
in case tcMatchTys tpl_lhs target_tys of
Just subst -- matching worked. now, check for apartness.
| apartnessCheck flattened_target branch
-> -- matching worked & we're apart from all incompatible branches.
-- success
ASSERT( all (isJust . lookupCoVar subst) tpl_cvs )
Just (ind, substTyVars subst tpl_tvs, substCoVars subst tpl_cvs)
-- failure. keep looking
_ -> go (ind+1) rest
-- fail if no branches left
go _ [] = Nothing
-- | Do an apartness check, as described in the "Closed Type Families" paper
-- (POPL '14). This should be used when determining if an equation
-- ('CoAxBranch') of a closed type family can be used to reduce a certain target
-- type family application.
apartnessCheck :: [Type] -- ^ /flattened/ target arguments. Make sure
-- they're flattened! See Note [Flattening].
-- (NB: This "flat" is a different
-- "flat" than is used in TcFlatten.)
-> CoAxBranch -- ^ the candidate equation we wish to use
-- Precondition: this matches the target
-> Bool -- ^ True <=> equation can fire
apartnessCheck flattened_target (CoAxBranch { cab_incomps = incomps })
= all (isSurelyApart
. tcUnifyTysFG (const BindMe) flattened_target
. coAxBranchLHS) incomps
where
isSurelyApart SurelyApart = True
isSurelyApart _ = False
{-
************************************************************************
* *
Looking up a family instance
* *
************************************************************************
Note [Normalising types]
~~~~~~~~~~~~~~~~~~~~~~~~
The topNormaliseType function removes all occurrences of type families
and newtypes from the top-level structure of a type. normaliseTcApp does
the type family lookup and is fairly straightforward. normaliseType is
a little more involved.
The complication comes from the fact that a type family might be used in the
kind of a variable bound in a forall. We wish to remove this type family
application, but that means coming up with a fresh variable (with the new
kind). Thus, we need a substitution to be built up as we recur through the
type. However, an ordinary TCvSubst just won't do: when we hit a type variable
whose kind has changed during normalisation, we need both the new type
variable *and* the coercion. We could conjure up a new VarEnv with just this
property, but a usable substitution environment already exists:
LiftingContexts from the liftCoSubst family of functions, defined in Coercion.
A LiftingContext maps a type variable to a coercion and a coercion variable to
a pair of coercions. Let's ignore coercion variables for now. Because the
coercion a type variable maps to contains the destination type (via
coercionKind), we don't need to store that destination type separately. Thus,
a LiftingContext has what we need: a map from type variables to (Coercion,
Type) pairs.
We also benefit because we can piggyback on the liftCoSubstVarBndr function to
deal with binders. However, I had to modify that function to work with this
application. Thus, we now have liftCoSubstVarBndrCallback, which takes
a function used to process the kind of the binder. We don't wish
to lift the kind, but instead normalise it. So, we pass in a callback function
that processes the kind of the binder.
After that brilliant explanation of all this, I'm sure you've forgotten the
dangling reference to coercion variables. What do we do with those? Nothing at
all. The point of normalising types is to remove type family applications, but
there's no sense in removing these from coercions. We would just get back a
new coercion witnessing the equality between the same types as the original
coercion. Because coercions are irrelevant anyway, there is no point in doing
this. So, whenever we encounter a coercion, we just say that it won't change.
That's what the CoercionTy case is doing within normalise_type.
-}
topNormaliseType :: FamInstEnvs -> Type -> Type
topNormaliseType env ty = case topNormaliseType_maybe env ty of
Just (_co, ty') -> ty'
Nothing -> ty
topNormaliseType_maybe :: FamInstEnvs -> Type -> Maybe (Coercion, Type)
-- ^ Get rid of *outermost* (or toplevel)
-- * type function redex
-- * data family redex
-- * newtypes
-- returning an appropriate Representational coercion. Specifically, if
-- topNormaliseType_maybe env ty = Maybe (co, ty')
-- then
-- (a) co :: ty ~R ty'
-- (b) ty' is not a newtype, and is not a type-family or data-family redex
--
-- However, ty' can be something like (Maybe (F ty)), where
-- (F ty) is a redex.
--
-- Its a bit like Type.repType, but handles type families too
topNormaliseType_maybe env ty
= topNormaliseTypeX_maybe stepper ty
where
stepper = unwrapNewTypeStepper `composeSteppers` tyFamStepper
tyFamStepper rec_nts tc tys -- Try to step a type/data familiy
= let (args_co, ntys) = normaliseTcArgs env Representational tc tys in
-- NB: It's OK to use normaliseTcArgs here instead of
-- normalise_tc_args (which takes the LiftingContext described
-- in Note [Normalising types]) because the reduceTyFamApp below
-- works only at top level. We'll never recur in this function
-- after reducing the kind of a bound tyvar.
case reduceTyFamApp_maybe env Representational tc ntys of
Just (co, rhs) -> NS_Step rec_nts rhs (args_co `mkTransCo` co)
_ -> NS_Done
---------------
normaliseTcApp :: FamInstEnvs -> Role -> TyCon -> [Type] -> (Coercion, Type)
-- See comments on normaliseType for the arguments of this function
normaliseTcApp env role tc tys
= initNormM env role (tyCoVarsOfTypes tys) $
normalise_tc_app tc tys
-- See Note [Normalising types] about the LiftingContext
normalise_tc_app :: TyCon -> [Type] -> NormM (Coercion, Type)
normalise_tc_app tc tys
= do { (args_co, ntys) <- normalise_tc_args tc tys
; case expandSynTyCon_maybe tc ntys of
{ Just (tenv, rhs, ntys') ->
do { (co2, ninst_rhs)
<- normalise_type (substTy (mkTvSubstPrs tenv) rhs)
; return $
if isReflCo co2
then (args_co, mkTyConApp tc ntys)
else (args_co `mkTransCo` co2, mkAppTys ninst_rhs ntys') }
; Nothing ->
do { env <- getEnv
; role <- getRole
; case reduceTyFamApp_maybe env role tc ntys of
Just (first_co, ty')
-> do { (rest_co,nty) <- normalise_type ty'
; return ( args_co `mkTransCo` first_co `mkTransCo` rest_co
, nty ) }
_ -> -- No unique matching family instance exists;
-- we do not do anything
return (args_co, mkTyConApp tc ntys) }}}
---------------
-- | Normalise arguments to a tycon
normaliseTcArgs :: FamInstEnvs -- ^ env't with family instances
-> Role -- ^ desired role of output coercion
-> TyCon -- ^ tc
-> [Type] -- ^ tys
-> (Coercion, [Type]) -- ^ co :: tc tys ~ tc new_tys
normaliseTcArgs env role tc tys
= initNormM env role (tyCoVarsOfTypes tys) $
normalise_tc_args tc tys
normalise_tc_args :: TyCon -> [Type] -- tc tys
-> NormM (Coercion, [Type]) -- (co, new_tys), where
-- co :: tc tys ~ tc new_tys
normalise_tc_args tc tys
= do { role <- getRole
; (cois, ntys) <- zipWithAndUnzipM normalise_type_role
tys (tyConRolesX role tc)
; return (mkTyConAppCo role tc cois, ntys) }
where
normalise_type_role ty r = withRole r $ normalise_type ty
---------------
normaliseType :: FamInstEnvs
-> Role -- desired role of coercion
-> Type -> (Coercion, Type)
normaliseType env role ty
= initNormM env role (tyCoVarsOfType ty) $ normalise_type ty
normalise_type :: Type -- old type
-> NormM (Coercion, Type) -- (coercion,new type), where
-- co :: old-type ~ new_type
-- Normalise the input type, by eliminating *all* type-function redexes
-- but *not* newtypes (which are visible to the programmer)
-- Returns with Refl if nothing happens
-- Does nothing to newtypes
-- The returned coercion *must* be *homogeneous*
-- See Note [Normalising types]
-- Try to not to disturb type synonyms if possible
normalise_type
= go
where
go (TyConApp tc tys) = normalise_tc_app tc tys
go ty@(LitTy {}) = do { r <- getRole
; return (mkReflCo r ty, ty) }
go (AppTy ty1 ty2)
= do { (co, nty1) <- go ty1
; (arg, nty2) <- withRole Nominal $ go ty2
; return (mkAppCo co arg, mkAppTy nty1 nty2) }
go (ForAllTy (Anon ty1) ty2)
= do { (co1, nty1) <- go ty1
; (co2, nty2) <- go ty2
; r <- getRole
; return (mkFunCo r co1 co2, mkFunTy nty1 nty2) }
go (ForAllTy (Named tyvar vis) ty)
= do { (lc', tv', h, ki') <- normalise_tyvar_bndr tyvar
; (co, nty) <- withLC lc' $ normalise_type ty
; let tv2 = setTyVarKind tv' ki'
; return (mkForAllCo tv' h co, mkNamedForAllTy tv2 vis nty) }
go (TyVarTy tv) = normalise_tyvar tv
go (CastTy ty co)
= do { (nco, nty) <- go ty
; lc <- getLC
; let co' = substRightCo lc co
; return (castCoercionKind nco co co', mkCastTy nty co') }
go (CoercionTy co)
= do { lc <- getLC
; r <- getRole
; let right_co = substRightCo lc co
; return ( mkProofIrrelCo r
(liftCoSubst Nominal lc (coercionType co))
co right_co
, mkCoercionTy right_co ) }
normalise_tyvar :: TyVar -> NormM (Coercion, Type)
normalise_tyvar tv
= ASSERT( isTyVar tv )
do { lc <- getLC
; r <- getRole
; return $ case liftCoSubstTyVar lc r tv of
Just co -> (co, pSnd $ coercionKind co)
Nothing -> (mkReflCo r ty, ty) }
where ty = mkTyVarTy tv
normalise_tyvar_bndr :: TyVar -> NormM (LiftingContext, TyVar, Coercion, Kind)
normalise_tyvar_bndr tv
= do { lc1 <- getLC
; env <- getEnv
; let callback lc ki = runNormM (normalise_type ki) env lc Nominal
; return $ liftCoSubstVarBndrCallback callback lc1 tv }
-- | a monad for the normalisation functions, reading 'FamInstEnvs',
-- a 'LiftingContext', and a 'Role'.
newtype NormM a = NormM { runNormM ::
FamInstEnvs -> LiftingContext -> Role -> a }
initNormM :: FamInstEnvs -> Role
-> TyCoVarSet -- the in-scope variables
-> NormM a -> a
initNormM env role vars (NormM thing_inside)
= thing_inside env lc role
where
in_scope = mkInScopeSet vars
lc = emptyLiftingContext in_scope
getRole :: NormM Role
getRole = NormM (\ _ _ r -> r)
getLC :: NormM LiftingContext
getLC = NormM (\ _ lc _ -> lc)
getEnv :: NormM FamInstEnvs
getEnv = NormM (\ env _ _ -> env)
withRole :: Role -> NormM a -> NormM a
withRole r thing = NormM $ \ envs lc _old_r -> runNormM thing envs lc r
withLC :: LiftingContext -> NormM a -> NormM a
withLC lc thing = NormM $ \ envs _old_lc r -> runNormM thing envs lc r
instance Monad NormM where
ma >>= fmb = NormM $ \env lc r ->
let a = runNormM ma env lc r in
runNormM (fmb a) env lc r
instance Functor NormM where
fmap = liftM
instance Applicative NormM where
pure x = NormM $ \ _ _ _ -> x
(<*>) = ap
{-
************************************************************************
* *
Flattening
* *
************************************************************************
Note [Flattening]
~~~~~~~~~~~~~~~~~
As described in "Closed type families with overlapping equations"
http://research.microsoft.com/en-us/um/people/simonpj/papers/ext-f/axioms-extended.pdf
we need to flatten core types before unifying them, when checking for "surely-apart"
against earlier equations of a closed type family.
Flattening means replacing all top-level uses of type functions with
fresh variables, *taking care to preserve sharing*. That is, the type
(Either (F a b) (F a b)) should flatten to (Either c c), never (Either
c d).
Here is a nice example of why it's all necessary:
type family F a b where
F Int Bool = Char
F a b = Double
type family G a -- open, no instances
How do we reduce (F (G Float) (G Float))? The first equation clearly doesn't match,
while the second equation does. But, before reducing, we must make sure that the
target can never become (F Int Bool). Well, no matter what G Float becomes, it
certainly won't become *both* Int and Bool, so indeed we're safe reducing
(F (G Float) (G Float)) to Double.
This is necessary not only to get more reductions (which we might be
willing to give up on), but for substitutivity. If we have (F x x), we
can see that (F x x) can reduce to Double. So, it had better be the
case that (F blah blah) can reduce to Double, no matter what (blah)
is! Flattening as done below ensures this.
flattenTys is defined here because of module dependencies.
-}
data FlattenEnv = FlattenEnv { fe_type_map :: TypeMap TyVar
, fe_subst :: TCvSubst }
emptyFlattenEnv :: InScopeSet -> FlattenEnv
emptyFlattenEnv in_scope
= FlattenEnv { fe_type_map = emptyTypeMap
, fe_subst = mkEmptyTCvSubst in_scope }
-- See Note [Flattening]
flattenTys :: InScopeSet -> [Type] -> [Type]
flattenTys in_scope tys = snd $ coreFlattenTys env tys
where
-- when we hit a type function, we replace it with a fresh variable
-- but, we need to make sure that this fresh variable isn't mentioned
-- *anywhere* in the types we're flattening, even if locally-bound in
-- a forall. That way, we can ensure consistency both within and outside
-- of that forall.
all_in_scope = in_scope `extendInScopeSetSet` allTyVarsInTys tys
env = emptyFlattenEnv all_in_scope
coreFlattenTys :: FlattenEnv -> [Type] -> (FlattenEnv, [Type])
coreFlattenTys = go []
where
go rtys env [] = (env, reverse rtys)
go rtys env (ty : tys)
= let (env', ty') = coreFlattenTy env ty in
go (ty' : rtys) env' tys
coreFlattenTy :: FlattenEnv -> Type -> (FlattenEnv, Type)
coreFlattenTy = go
where
go env ty | Just ty' <- coreView ty = go env ty'
go env (TyVarTy tv) = (env, substTyVar (fe_subst env) tv)
go env (AppTy ty1 ty2) = let (env1, ty1') = go env ty1
(env2, ty2') = go env1 ty2 in
(env2, AppTy ty1' ty2')
go env (TyConApp tc tys)
-- NB: Don't just check if isFamilyTyCon: this catches *data* families,
-- which are generative and thus can be preserved during flattening
| not (isGenerativeTyCon tc Nominal)
= let (env', tv) = coreFlattenTyFamApp env tc tys in
(env', mkTyVarTy tv)
| otherwise
= let (env', tys') = coreFlattenTys env tys in
(env', mkTyConApp tc tys')
go env (ForAllTy (Anon ty1) ty2) = let (env1, ty1') = go env ty1
(env2, ty2') = go env1 ty2 in
(env2, mkFunTy ty1' ty2')
go env (ForAllTy (Named tv vis) ty)
= let (env1, tv') = coreFlattenVarBndr env tv
(env2, ty') = go env1 ty in
(env2, mkNamedForAllTy tv' vis ty')
go env ty@(LitTy {}) = (env, ty)
go env (CastTy ty co) = let (env1, ty') = go env ty
(env2, co') = coreFlattenCo env1 co in
(env2, CastTy ty' co')
go env (CoercionTy co) = let (env', co') = coreFlattenCo env co in
(env', CoercionTy co')
-- when flattening, we don't care about the contents of coercions.
-- so, just return a fresh variable of the right (flattened) type
coreFlattenCo :: FlattenEnv -> Coercion -> (FlattenEnv, Coercion)
coreFlattenCo env co
= (env2, mkCoVarCo covar)
where
(env1, kind') = coreFlattenTy env (coercionType co)
fresh_name = mkFlattenFreshCoName
subst1 = fe_subst env1
in_scope = getTCvInScope subst1
covar = uniqAway in_scope (mkCoVar fresh_name kind')
env2 = env1 { fe_subst = subst1 `extendTCvInScope` covar }
coreFlattenVarBndr :: FlattenEnv -> TyVar -> (FlattenEnv, TyVar)
coreFlattenVarBndr env tv
| kind' `eqType` kind
= ( env { fe_subst = extendTvSubst old_subst tv (mkTyVarTy tv) }
-- override any previous binding for tv
, tv)
| otherwise
= let new_tv = uniqAway (getTCvInScope old_subst) (setTyVarKind tv kind')
new_subst = extendTvSubstWithClone old_subst tv new_tv
in
(env' { fe_subst = new_subst }, new_tv)
where
kind = tyVarKind tv
(env', kind') = coreFlattenTy env kind
old_subst = fe_subst env
coreFlattenTyFamApp :: FlattenEnv
-> TyCon -- type family tycon
-> [Type] -- args
-> (FlattenEnv, TyVar)
coreFlattenTyFamApp env fam_tc fam_args
= case lookupTypeMap type_map fam_ty of
Just tv -> (env, tv)
-- we need fresh variables here, but this is called far from
-- any good source of uniques. So, we just use the fam_tc's unique
-- and trust uniqAway to avoid clashes. Recall that the in_scope set
-- contains *all* tyvars, even locally bound ones elsewhere in the
-- overall type, so this really is fresh.
Nothing -> let tyvar_name = mkFlattenFreshTyName fam_tc
tv = uniqAway (getTCvInScope subst) $
mkTyVar tyvar_name (typeKind fam_ty)
env' = env { fe_type_map = extendTypeMap type_map fam_ty tv
, fe_subst = extendTCvInScope subst tv }
in (env', tv)
where fam_ty = mkTyConApp fam_tc fam_args
FlattenEnv { fe_type_map = type_map
, fe_subst = subst } = env
-- | Get the set of all type variables mentioned anywhere in the list
-- of types. These variables are not necessarily free.
allTyVarsInTys :: [Type] -> VarSet
allTyVarsInTys [] = emptyVarSet
allTyVarsInTys (ty:tys) = allTyVarsInTy ty `unionVarSet` allTyVarsInTys tys
-- | Get the set of all type variables mentioned anywhere in a type.
allTyVarsInTy :: Type -> VarSet
allTyVarsInTy = go
where
go (TyVarTy tv) = unitVarSet tv
go (AppTy ty1 ty2) = (go ty1) `unionVarSet` (go ty2)
go (TyConApp _ tys) = allTyVarsInTys tys
go (ForAllTy bndr ty) =
caseBinder bndr (\tv -> unitVarSet tv) (const emptyVarSet)
`unionVarSet` go (binderType bndr) `unionVarSet` go ty
-- don't remove the tv from the set!
go (LitTy {}) = emptyVarSet
go (CastTy ty co) = go ty `unionVarSet` go_co co
go (CoercionTy co) = go_co co
go_co (Refl _ ty) = go ty
go_co (TyConAppCo _ _ args) = go_cos args
go_co (AppCo co arg) = go_co co `unionVarSet` go_co arg
go_co (ForAllCo tv h co)
= unionVarSets [unitVarSet tv, go_co co, go_co h]
go_co (CoVarCo cv) = unitVarSet cv
go_co (AxiomInstCo _ _ cos) = go_cos cos
go_co (UnivCo p _ t1 t2) = go_prov p `unionVarSet` go t1 `unionVarSet` go t2
go_co (SymCo co) = go_co co
go_co (TransCo c1 c2) = go_co c1 `unionVarSet` go_co c2
go_co (NthCo _ co) = go_co co
go_co (LRCo _ co) = go_co co
go_co (InstCo co arg) = go_co co `unionVarSet` go_co arg
go_co (CoherenceCo c1 c2) = go_co c1 `unionVarSet` go_co c2
go_co (KindCo co) = go_co co
go_co (SubCo co) = go_co co
go_co (AxiomRuleCo _ cs) = go_cos cs
go_cos = foldr (unionVarSet . go_co) emptyVarSet
go_prov UnsafeCoerceProv = emptyVarSet
go_prov (PhantomProv co) = go_co co
go_prov (ProofIrrelProv co) = go_co co
go_prov (PluginProv _) = emptyVarSet
go_prov (HoleProv _) = emptyVarSet
mkFlattenFreshTyName :: Uniquable a => a -> Name
mkFlattenFreshTyName unq
= mkSysTvName (getUnique unq) (fsLit "flt")
mkFlattenFreshCoName :: Name
mkFlattenFreshCoName
= mkSystemVarName (deriveUnique eqPrimTyConKey 71) (fsLit "flc")
| oldmanmike/ghc | compiler/types/FamInstEnv.hs | bsd-3-clause | 64,841 | 6 | 21 | 18,404 | 9,348 | 5,029 | 4,319 | -1 | -1 |
{-# LANGUAGE ExistentialQuantification #-}
-- |This module provides widgets to center other widgets horizontally
-- and vertically. These centering widgets relay focus and key events
-- to their children.
module Graphics.Vty.Widgets.Centering
( HCentered
, VCentered
, hCentered
, vCentered
, centered
)
where
import Graphics.Vty.Widgets.Core
import Graphics.Vty
import Graphics.Vty.Widgets.Util
data HCentered a = (Show a) => HCentered (Widget a)
instance Show (HCentered a) where
show (HCentered _) = "HCentered { ... }"
-- |Wrap another widget to center it horizontally.
hCentered :: (Show a) => Widget a -> IO (Widget (HCentered a))
hCentered ch = do
wRef <- newWidget (HCentered ch) $ \w ->
w { growHorizontal_ = const $ return True
, growVertical_ = \(HCentered child) -> growVertical child
, render_ = \this s ctx -> do
HCentered child <- getState this
img <- render child s ctx
let attr' = getNormalAttr ctx
(half, half') = centered_halves regionWidth s (imageWidth img)
return $ if half > 0
then horizCat [ charFill attr' ' ' half (imageHeight img)
, img
, charFill attr' ' ' half' (imageHeight img)
]
else img
, setCurrentPosition_ =
\this pos -> do
HCentered child <- getState this
s <- getCurrentSize this
chSz <- getCurrentSize child
let (half, _) = centered_halves regionWidth s (regionWidth chSz)
chPos = pos `plusWidth` half
setCurrentPosition child chPos
, getCursorPosition_ = \this -> do
HCentered child <- getState this
getCursorPosition child
}
wRef `relayKeyEvents` ch
wRef `relayFocusEvents` ch
return wRef
data VCentered a = (Show a) => VCentered (Widget a)
instance Show (VCentered a) where
show (VCentered _) = "VCentered { ... }"
-- |Wrap another widget to center it vertically.
vCentered :: (Show a) => Widget a -> IO (Widget (VCentered a))
vCentered ch = do
wRef <- newWidget (VCentered ch) $ \w ->
w { growVertical_ = const $ return True
, growHorizontal_ = const $ growHorizontal ch
, render_ = \this s ctx -> do
VCentered child <- getState this
img <- render child s ctx
let attr' = getNormalAttr ctx
(half, half') = centered_halves regionHeight s (imageHeight img)
return $ if half > 0
then vertCat [ charFill attr' ' ' (imageWidth img) half
, img
, charFill attr' ' ' (imageWidth img) half'
]
else img
, setCurrentPosition_ =
\this pos -> do
VCentered child <- getState this
s <- getCurrentSize this
chSz <- getCurrentSize child
let (half, _) = centered_halves regionHeight s (regionHeight chSz)
chPos = pos `plusHeight` half
setCurrentPosition child chPos
, getCursorPosition_ = \this -> do
VCentered child <- getState this
getCursorPosition child
}
wRef `relayKeyEvents` ch
wRef `relayFocusEvents` ch
return wRef
-- |Wrap another widget to center it both vertically and horizontally.
centered :: (Show a) => Widget a -> IO (Widget (VCentered (HCentered a)))
centered wRef = vCentered =<< hCentered wRef
centered_halves :: (DisplayRegion -> Int) -> DisplayRegion -> Int -> (Int, Int)
centered_halves region_size s obj_sz =
let remaining = region_size s - obj_sz
half = remaining `div` 2
half' = if remaining `mod` 2 == 0
then half
else half + 1
in (half, half')
| KommuSoft/vty-ui | src/Graphics/Vty/Widgets/Centering.hs | bsd-3-clause | 4,135 | 0 | 21 | 1,545 | 1,095 | 561 | 534 | 84 | 2 |
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE UnboxedTuples #-}
{-# OPTIONS_HADDOCK hide #-}
-- |
-- Module : Data.Array.Accelerate.Lifetime
-- Copyright : [2015] Robert Clifton-Everest, Manuel M T Chakravarty, Gabriele Keller
-- License : BSD3
--
-- Maintainer : Robert Clifton-Everest <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.Lifetime (
Lifetime, newLifetime, withLifetime, addFinalizer, finalize, mkWeak,
mkWeakPtr, unsafeGetValue
) where
import Control.Applicative
import Data.Function ( on )
import Data.IORef ( mkWeakIORef, atomicModifyIORef' )
import Prelude
import GHC.Base ( touch#, IO(..))
import GHC.IORef ( IORef(.. ), newIORef )
import GHC.Prim ( mkWeak# )
import GHC.STRef ( STRef(..) )
import GHC.Weak ( Weak(..) )
-- | A lifetime represents a value with attached finalizers. This is similar to
-- the functionality provided by "System.Mem.Weak", but has the following
-- stronger properties:
--
-- * Unless explicitly forced, finalizers will not fire until after the
-- 'Lifetime' has become unreachable, where \"reachability\" is the same as
-- defined in "System.Mem.Weak". That is to say, there is no issue with
-- creating a 'Lifetime' for a non-primitve type and finalizers firing while
-- an object is still reachable.
--
-- * Finalizers are fired sequentially in reverse of the order in which they
-- were attached.
--
-- * As the finalizers are attached to the 'Lifetime' and not the underlying
-- value, there is no danger in storing it UNPACKED as part of another
-- structure.
--
data Lifetime a = Lifetime {-# UNPACK #-} !(IORef [IO ()]) {-# UNPACK #-} !(Weak (IORef [IO ()])) a
instance Eq a => Eq (Lifetime a) where
(==) = (==) `on` unsafeGetValue
-- | Construct a new 'Lifetime' from the given value.
--
newLifetime :: a -> IO (Lifetime a)
newLifetime a = do
ref <- newIORef []
weak <- mkWeakIORef ref (finalizer ref)
return $! Lifetime ref weak a
-- | This provides a way of looking at the value inside a 'Lifetime'. The
-- supplied function is executed immediately and the 'Lifetime' kept alive
-- throughout its execution. It is important to not let the value /leak/ outside
-- the function, either by returning it or by lazy IO.
--
withLifetime :: Lifetime a -> (a -> IO b) -> IO b
withLifetime (Lifetime ref _ a) f = f a <* touch ref
-- | Attaches a finalizer to a 'Lifetime'. Like in "System.Mem.Weak", there is
-- no guarantee that the finalizers will eventually run. If they do run,
-- they will be executed in the order in which they were supplied.
--
addFinalizer :: Lifetime a -> IO () -> IO ()
addFinalizer (Lifetime ref _ _) f = atomicModifyIORef' ref (\fs -> (f:fs,()))
-- | Causes any finalizers associated with the given lifetime to be run
-- immediately on the calling thread.
--
-- Because the finalizer is run on the calling thread. Care should be taken to
-- ensure that the it does not try to acquire any locks the calling thread might
-- already possess. This can result in deadlock and is in contrast to calling
-- 'System.Mem.Weak.finalize' on 'System.Mem.Weak.Weak'.
--
finalize :: Lifetime a -> IO ()
finalize (Lifetime ref _ _) = finalizer ref
-- | Create a weak pointer from a 'Lifetime' to the supplied value.
--
-- Because weak pointers have their own concept of finalizers, it is important
-- to note these behaviours:
--
-- * Calling 'System.Mem.Weak.finalize' causes the finalizers attached to the
-- lifetime to be scheduled, and run in the correct order, but does not
-- guarantee they will execute on the calling thread.
--
-- * If 'deRefWeak' returns Nothing, there is no guarantee that the finalizers
-- have already run.
--
mkWeak :: Lifetime k -> v -> IO (Weak v)
mkWeak (Lifetime ref@(IORef (STRef r#)) _ _) v = IO $ \s ->
case mkWeak# r# v f s of (# s', w# #) -> (# s', Weak w# #)
where
f = finalizer ref
-- A specialised version of 'mkWeak' where the key and value are the same
-- 'Lifetime'.
--
-- > mkWeakPtr key = mkWeak key key
--
mkWeakPtr :: Lifetime a -> IO (Weak (Lifetime a))
mkWeakPtr l = mkWeak l l
-- | Retrieve the value from a lifetime. This is unsafe because, unless the
-- 'Lifetime' is still reachable, the finalizers may fire, potentially
-- invalidating the value.
--
unsafeGetValue :: Lifetime a -> a
unsafeGetValue (Lifetime _ _ a) = a
-- The actual finalizer for 'Lifetime's.
--
finalizer :: IORef [IO ()] -> IO ()
finalizer ref = do
fins <- atomicModifyIORef' ref ([],)
sequence_ fins
-- Touch an 'IORef', keeping it alive.
--
touch :: IORef a -> IO ()
touch r = IO $ \s -> case touch# r s of s' -> (# s', () #)
| rrnewton/accelerate | Data/Array/Accelerate/Lifetime.hs | bsd-3-clause | 4,837 | 0 | 14 | 1,018 | 831 | 469 | 362 | 44 | 1 |
----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) Spencer Janssen 2007
-- License : BSD3-style (see LICENSE)
--
-- Maintainer : [email protected]
-- Stability : unstable
-- Portability : not portable, uses mtl, X11, posix
--
-- xmonad, a minimalist, tiling window manager for X11
--
-----------------------------------------------------------------------------
module Main (main) where
import XMonad
import Control.Monad (unless)
import System.Info
import System.Environment
import System.Posix.Process (executeFile)
import System.Exit (exitFailure)
import Paths_xmonad (version)
import Data.Version (showVersion)
import Graphics.X11.Xinerama (compiledWithXinerama)
-- | The entry point into xmonad. Attempts to compile any custom main
-- for xmonad, and if it doesn't find one, just launches the default.
main :: IO ()
main = do
installSignalHandlers -- important to ignore SIGCHLD to avoid zombies
args <- getArgs
let launch = catchIO buildLaunch >> xmonad def
case args of
[] -> launch
("--resume":_) -> launch
["--help"] -> usage
["--recompile"] -> recompile True >>= flip unless exitFailure
["--replace"] -> launch
["--restart"] -> sendRestart >> return ()
["--version"] -> putStrLn $ unwords shortVersion
["--verbose-version"] -> putStrLn . unwords $ shortVersion ++ longVersion
_ -> fail "unrecognized flags"
where
shortVersion = ["xmonad", showVersion version]
longVersion = [ "compiled by", compilerName, showVersion compilerVersion
, "for", arch ++ "-" ++ os
, "\nXinerama:", show compiledWithXinerama ]
usage :: IO ()
usage = do
self <- getProgName
putStr . unlines $
concat ["Usage: ", self, " [OPTION]"] :
"Options:" :
" --help Print this message" :
" --version Print the version number" :
" --recompile Recompile your ~/.xmonad/xmonad.hs" :
" --replace Replace the running window manager with xmonad" :
" --restart Request a running xmonad process to restart" :
[]
-- | Build "~\/.xmonad\/xmonad.hs" with ghc, then execute it. If there are no
-- errors, this function does not return. An exception is raised in any of
-- these cases:
--
-- * ghc missing
--
-- * both "~\/.xmonad\/xmonad.hs" and "~\/.xmonad\/xmonad-$arch-$os" missing
--
-- * xmonad.hs fails to compile
--
-- ** wrong ghc in path (fails to compile)
--
-- ** type error, syntax error, ..
--
-- * Missing XMonad\/XMonadContrib modules due to ghc upgrade
--
buildLaunch :: IO ()
buildLaunch = do
recompile False
dir <- getXMonadDir
args <- getArgs
executeFile (dir ++ "/xmonad-"++arch++"-"++os) False args Nothing
return ()
sendRestart :: IO ()
sendRestart = do
dpy <- openDisplay ""
rw <- rootWindow dpy $ defaultScreen dpy
xmonad_restart <- internAtom dpy "XMONAD_RESTART" False
allocaXEvent $ \e -> do
setEventType e clientMessage
setClientMessageEvent e rw xmonad_restart 32 0 currentTime
sendEvent dpy rw False structureNotifyMask e
sync dpy False
| atupal/xmonad-mirror | xmonad/Main.hs | mit | 3,413 | 0 | 16 | 932 | 608 | 323 | 285 | 58 | 9 |
module Network.Haskoin.Wallet.Tests (tests) where
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Data.Aeson (FromJSON, ToJSON, encode, decode)
import Network.Haskoin.Wallet.Arbitrary ()
import Network.Haskoin.Wallet
tests :: [Test]
tests =
[ testGroup "Serialize & de-serialize types to JSON"
[ testProperty "AccountType" (metaID :: AccountType -> Bool)
, testProperty "TxAction" (metaID :: TxAction -> Bool)
, testProperty "NodeAction" (metaID :: NodeAction -> Bool)
]
]
metaID :: (FromJSON a, ToJSON a, Eq a) => a -> Bool
metaID x = (decode . encode) [x] == Just [x]
| tphyahoo/haskoin-wallet | tests/Network/Haskoin/Wallet/Tests.hs | unlicense | 674 | 0 | 10 | 129 | 209 | 122 | 87 | 14 | 1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleContexts #-}
import Control.CP.FD.Example
-- diffList: the differences between successive elements of a list
diffList l = exists $ \d -> do -- request a (collection) variable d
let n = size l -- introduce n as alias for size l
size d @= n-1 -- size of d must be one less than l
loopall (0,n-2) $ \i -> do -- for each i in [0..n-2]
d!i @= abs (l!i - l!(i+1)) -- d[i] = abs(l[i]-l[i+1])
return d -- and return d to the caller
model :: ExampleModel ModelInt -- type signature
model n = -- function 'model' takes argument n
exists $ \x -> do -- request a (collection) variable x
size x @= n -- whose size must be n
d <- diffList x -- d becomes the diffList of x
x `allin` (cte 0,n-1) -- all x elements are in [0..n-1]
d `allin` (cte 1,n-1) -- all d elements are in [1..n-1]
allDiff x -- all x elements are different
allDiff d -- all d elements are different
x @!! 0 @< x @!! 1 -- some symmetry breaking
d @!! 0 @> d ! (n-2) -- some symmetry breaking
return x -- return the list itself
main = example_sat_main_single_expr model
| neothemachine/monadiccp | examples/AllInterval.hs | bsd-3-clause | 1,386 | 0 | 18 | 523 | 291 | 152 | 139 | 22 | 1 |
{-# LANGUAGE RankNTypes #-}
module Toplevel where
import Data.Char(isAlpha,isDigit)
import Data.List(partition,(\\),nub,find,deleteBy,sort)
import Data.Map(Map,toList)
import System.IO
import Version(version,buildtime)
import Syntax
import ParserDef(getInt,pCommand,parseString,Command(..)
,program,parseHandle)
import LangEval(Env(..),env0,eval,elaborate,Prefix(..),mPatStrict,extendV)
import Monads(FIO(..),unFIO,runFIO,fixFIO,fio,resetNext
,write,writeln,readln,unTc,tryAndReport,fio,fioFailD
,errF,report,writeRef,handleP)
import Auxillary(plist,plistf,backspace,Loc(..),extendL,DispInfo,DispElem(..),eitherM)
import SCC(topSortR)
import Control.Monad(when)
import Infer(TcEnv(sourceFiles,tyfuns),completionEntry,lineEditReadln,initTcEnv
,mode0,modes,checkDecs,imports,addListToFM,appendFM2
,var_env,type_env,rules,runtime_env,syntaxExt)
import RankN(pprint,Z,failD,disp0,dispRef)
import Manual(makeManual)
import Commands
import SyntaxExt(synName,synKey)
import System.Environment(getArgs)
import Data.Time.Clock(UTCTime,getCurrentTime)
import System.IO(hClose)
import Control.Exception(try,IOException)
import System.FilePath(splitFileName)
import System.Directory(setCurrentDirectory,getDirectoryContents,getModificationTime)
-- import System.Console.Readline(setCompletionEntryFunction)
-- setCompletionEntryFunction :: Maybe (String -> IO [String]) -> IO ()
-------------------------------------------------------------
-- The programmer interface: the top level loop.
-- it performs the read-eval-typecheck-print loop.
-- It catches exceptions, and ties all the other pieces together.
----------------------------------------------
-- Perform one Read-Eval-Print action.
-- readEvalPrint :: [String] -> (TcEnv) -> FIO(TcEnv)
readEvalPrint commandTable sources tenv =
do { let tabExpandFun = completionEntry tenv
white c = elem c " \t\n"
; input <- lineEditReadln "prompt> " tabExpandFun
; z <- parseString pCommand input
; case z of
Left s -> do {writeln s; return (tenv) }
Right(x,rest) | all white rest ->
case x of
(ColonCom com str) -> dispatchColon commandTable tenv com str
(ExecCom e) -> execExp tenv e
(DrawCom p e) -> drawPatExp tenv p e
(LetCom d) -> letDec elabDs tenv d
(EmptyCom) -> return tenv
Right(x,rest) -> fail ("\nI parsed the command:\n "++show x++
"\nBut there was some trailing text: "++rest)
}
-- Repeat Read-Eval-Print until the :q command is given
topLoop commandTable sources env = tryAndReport
(do { fio(hFlush stdout)
; fio(writeRef dispRef disp0)
; env' <- (readEvalPrint commandTable sources init)
; topLoop commandTable (sourceFiles env') env'
}) (report (topLoop commandTable (sourceFiles init) init))
where init = (env{sourceFiles=sources})
------------------------------------------------------------------
-- Commands for load files, then going into the toplevel loop
------------------------------------------------------------------
-- load just the prelude and then go into the toplevel loop
main :: IO ()
main = runFIO(do { let sources = ["LangPrelude.prg"]
; writeln ("Loading source files = "++show sources)
; fio $ hSetBuffering stdout NoBuffering
; fio $ hSetBuffering stdin NoBuffering
; (env1,time) <-
tryAndReport (elabFile 0 "LangPrelude.prg" initTcEnv)
(report (return(initTcEnv,undefined)))
; let sources2 = sourceFiles env1
; topLoop (commandF (elabFile 0)) sources2 env1
; return () }) errF
-- Load the prelude and then load the file "s", and then go into the toplevel loop.
go :: String -> IO ()
go s =
runFIO(do { writeln (version++" -- Type ':?' for command line help."++"\n\n")
; let sources = ["LangPrelude.prg",s]
; writeln ("Loading source files = "++show sources)
; writeln "loading the prelude (LangPrelude.prg)"
; (env,time) <- tryAndReport (elabFile 0 "LangPrelude.prg" initTcEnv)
(report (return (initTcEnv,undefined)))
; (env2,time2) <- elabFile 0 s env
; let sources2 = sourceFiles env2
; topLoop (commandF (elabFile 0)) sources2 env2
; return () }) errF
-- Don't load the prelude, just load "s" then go into the toplevel loop.
run :: String -> IO ()
run s = runFIO(do { let (dir,name) = splitFileName s
; fio (when (not (null dir)) (setCurrentDirectory dir))
; writeRef modes mode0
; writeln ("Loading source files = "++show [s])
; let init = (initTcEnv{sourceFiles = [s]})
; (env1,time) <- tryAndReport (elabFile 0 s init)
(report (return (init,undefined)))
; let sources2 = sourceFiles env1
; topLoop (commandF (elabFile 0)) sources2 env1
; return () }) errF
-- Try to load a file, if it fails for any reason, exit the program
-- with an unrecoverable error. Used in testing, where failure means
-- a major error, something very bad (and unexpected), has happened
try_to_load s =
runFIO(do { writeln ("loading "++s)
; (env1,time) <- tryAndReport (elabFile 0 s initTcEnv) err2
; writeln (s++" successfully loaded")
; return () }) errF
where err2 loc mess = error ("At "++show loc++"\n"++mess)
-- Get the file to "run" from the command line arguments, then "run" it
omega :: IO()
omega =
do { args <- getArgs
; putStr (version++"\n")
; putStr ("Build Date: "++buildtime++"\n\n")
; putStr "Type ':?' for command line help.\n"
; case args of
[] -> run "LangPrelude.prg"
("-tests" : dir : _) -> alltests dir
("-manual" : dir : _) -> makeManual dir
(file : _) -> run file
}
-------------------------------------------------------------------------------
-- elabDs is the interface to everything. Elaborates a mutually recursive [Dec]
-- other functions read the [Dec] from files and call this function
elabDs :: [Dec] -> TcEnv -> FIO TcEnv
elabDs ds (tenv) =
do { let nam (Global s) = s
-- ; write ((display (map nam (concat (map decname ds))))++" ")
; (tenv1,ds1,cs1) <- checkDecs tenv ds -- type check the list
--; mapM (writeln .show) ds
--; mapM (writeln . show) ds1
; when (not (null cs1))
(fioFailD 3 disp0 [Ds "Unsolved constraints (type 2): ",Ds (show cs1)])
; env1 <- elaborate None ds1 (runtime_env tenv) -- evaluate the list
; return(tenv1 { runtime_env = env1 })
}
display [s] = s
display ss = plistf id "(" ss " " ")"
------------------------------------------------------------------
-- Get a [Dec] from a file name
parseDecs :: String -> FIO [Dec]
parseDecs file =
do { hndl <- eitherM (fio (try $ openFile file ReadMode))
(\ err -> fail ("\nProblem opening file: "++file++" ("++show (err :: IOException)++")"))
return
; let err mess = fio (hClose hndl >> fail mess) -- if parsing fails, we should close the file
; x <- handleP (const True) 10
(fio $ parseHandle program file hndl) err
; fio (hClose hndl)
; case x of
Left s -> fail s
Right (Program ds) -> return ds
}
-------------------------------------------------------------------------
-- Omega has a very simple importing mechanism. A user writes:
-- import "xx.prg" (f,g,T)
-- to import the file named "xx.prg", all symbols with names "f", "g", "T"
-- (no matter what namespace they appear in) are imported into the
-- current environment. Usually "xx.prg" is a complete path as Omega's
-- notion of current directory is quite primitive.
-- import "xx.prg" means import everything from "xx.prg"
importP (Import s vs) = True
importP _ = False
importName (Import s vs) = s
------------------------------------------------------------
-- Read a [Dec] from a file, then split it into imports and
-- binding groups, uses elabDs to do the work.
indent n = replicate ((n-1)*3) ' '
nameOf (name,time,deps,env) = name
elabFile :: Int -> String -> TcEnv -> FIO(TcEnv, UTCTime)
elabFile count file (tenv) =
do { time <- fio getCurrentTime
; all <- parseDecs file
; let (importL,ds) = partition importP all
(dss,pairs) = topSortR freeOfDec ds
; writeln(indent count++"->Loading import "++basename file)
; (tenv2,importList) <- importManyFiles (count + 1) importL tenv
--; mapM (writeln . (++"\n"). show) ds
--; writeln ("\nelaborating "++file++"\n"++show(map freeOfDec ds)++"\n pairs\n"++show pairs)
-- Check for multiple definitions in the file
; multDef ds (concat (map fst pairs))
-- Check if any names are already declared
; mapM (notDup tenv2 file) (foldr (\ (exs,deps) ss -> exs++ss) [] pairs)
; tenv3 <- foldF elabDs (tenv2) dss
; let tenv4 = adjustImports file time importList tenv3
; writeln ((indent (count+1))++"<-"++file++" loaded.")
; return (tenv4,time)
}
adjustImports name time deps new = new2
where -- a little recursive knot tying so the env being defined (new2) is
-- also stored in the imports list of the function being added
new2 = new {imports = m : (filter pred (imports new))}
m = (name,time,deps,new2)
keepers = map fst deps
pred (nm1,time1,deps1,env1) = elem nm1 keepers
addI [] old = old
addI ((m@(nm,time,deps,env)):more) old = (nm,time,deps,env): (addI more (deleteBy same m old))
where same (nm1,time1,deps1,env1) (nm2,time2,deps2,env2) = nm1 == nm2
lookupDeps nm env = case find match (imports env) of
Nothing -> fail ("Unknown module when lokking up dependency list: "++nm)
Just(nm,time,deps,env) -> return deps
where match (name,time,deps,env) = name==nm
showimp message env = message++plistf nameOf "(" (imports env) "," ")."
importManyFiles:: Int -> [Dec] -> TcEnv -> FIO (TcEnv, [(String, UTCTime)])
importManyFiles count [] tenv = return (tenv,[])
importManyFiles count (d:ds) tenv =
do { (next,name,time) <- importFile count d tenv
; (next2,ts) <- importManyFiles count ds next
; return(next2,(name,time):ts) }
importFile :: Int -> Dec -> TcEnv -> FIO(TcEnv,String,UTCTime)
importFile count (Import name vs) tenv =
case find (\(nm,time,deps,env)->name==nm) (imports tenv) of
Just (nm,time,deps,env) ->
do { writeln (indent count++"Import "++name++" already loaded.")
; return (importNames nm vs env tenv,nm,time) }
Nothing -> do { (new,time) <- elabFile count name tenv
; deps <- lookupDeps name new
; unknownExt vs (syntaxExt new)
; let new2 = adjustImports name time deps new
; return(importNames name vs new2 tenv,name,time) }
importNames :: String -> Maybe [ImportItem] -> TcEnv -> TcEnv -> TcEnv
importNames name items new old =
old { imports = addI (imports new) (imports old)
, var_env = addListToFM (var_env old) (filter okToAddVar (toList (var_env new)))
, type_env = filter q (type_env new) ++ type_env old
, runtime_env = add (runtime_env new) (runtime_env old)
, rules = appendFM2 (rules old) (filter p2 (toList (rules new)))
, syntaxExt = addSyntax syntax (syntaxExt new) (syntaxExt old)
, tyfuns = filter okToAddTyFun (tyfuns new) ++ tyfuns old
}
where elemOf x Nothing = True -- No import list, so everything is imported
elemOf x (Just vs) = elem x vs -- is it in the import list?
okToAddVar :: forall a . (Var, a) -> Bool
okToAddVar (x,y) = elemOf x vs
okToAddTyFun (x,y) = elemOf (Global x) vs
p2 (s,y) = elemOf (Global s) vs
q (str,tau,polyk) = elemOf (Global str) vs
add (Ev xs) (Ev ys) = Ev (filter okToAddVar xs ++ ys)
accV (VarImport v) vs = v:vs -- used to fold over the runtime environment
accV _ vs = vs
accSyn (SyntaxImport nm tag) vs = (nm,tag):vs -- fold over syntax imports
accSyn _ vs = vs
(vs,syntax) = case items of
Just zs -> (Just(foldr accV [] zs),Just(foldr accSyn [] zs))
Nothing -> (Nothing,Nothing)
addSyntax Nothing new old = new ++ old
addSyntax (Just imports) new old = foldr acc old new
where acc ext old = if (synName ext,synKey ext) `elem` imports
then ext:old else old
unknownExt Nothing new = return ()
unknownExt (Just []) new = return ()
unknownExt (Just(VarImport x : xs)) new = unknownExt (Just xs) new
unknownExt (Just(SyntaxImport nm tag : xs)) new =
if any good new
then unknownExt (Just xs) new
else fail ("\nImporting unknown extension: "++nm++"("++tag++")")
where good ext = synName ext == nm && synKey ext == tag
multDef :: [Dec] -> [Var] -> FIO ()
multDef ds names = if null dups then return () else fail (foldr report "" dups)
where dups = nub(names \\ nub names)
locs = concat(map decloc ds)
report :: Var -> String -> String
report nm s = show nm ++ " is multiply defined at lines "++show (foldr acc [] locs)++"\n"++s
where acc (name,SrcLoc _ line col) ls = if nm==name then line:ls else ls
acc (name,Z) ls = ls
-----------------------------------------------------
-- this command is for the maintainers of Omega, it tries
-- to load all the files in the TestPrograms directory with
-- extension ".prg" It is used to exercise Omega.
alltests dir =
do { setCurrentDirectory dir
; files' <- getDirectoryContents "."
; let ok x = case reverse x of { ('g':'r':'p':'.':_) -> True; _ -> False}
; let files = sort files'
; print (filter ok files)
; mapM try_to_load (filter ok files)
; setCurrentDirectory ".."
}
-------------------------------------------------------------------------------
------------------------------------------------------------------
-- Some shortcuts to running the interpreter
work = run "work.prg"
ky = run "D:/IntelWork/Kyung2.prg"
bad = run "D:/work/sheard/research/omega/badPrograms/shaped.prg"
qq = run "d:/LogicBlox/Code/LogicMetaGenerator/Text/meaning.prg"
add = run "D:/IntelWork/adder.prg"
temp = run "D:/IntelWork/temp.prg"
circ = run "Examples/RecursiveCircuit.prg"
parse = run "Examples/Parser.prg"
tests = go "tests.prg"
tm = go "toMetaMl.prg"
q s = go ("C:/tmp/OmegaExamples/"++s++".prg")
| cartazio/omega | src/Toplevel.hs | bsd-3-clause | 14,847 | 0 | 21 | 3,697 | 4,552 | 2,413 | 2,139 | 238 | 7 |
module Get.Init where
import System.IO (hFlush, stdout)
import Data.Aeson.Encode.Pretty (encodePretty)
import qualified Elm.Package.Name as N
import qualified Elm.Package.Version as V
import qualified Elm.Package.Description as D
import qualified Elm.Package.Paths as Path
import qualified Data.ByteString.Lazy as BS
askForChecked :: (String -> Either String a) -> String -> IO a
askForChecked check request = do
putStr $ request ++ " "
hFlush stdout
answer <- getLine
case check answer of
Right result -> return result
Left message -> do putStrLn message
askForChecked check request
eitherFromMaybe :: a -> Maybe b -> Either a b
eitherFromMaybe def val = case val of
Just r -> Right r
Nothing -> Left def
injectDefault :: Maybe [a] -> [a] -> [a]
injectDefault (Just xs) [] = xs
injectDefault _ ys = ys
askForVersion :: Maybe String -> String -> IO V.Version
askForVersion def req = askForChecked check req
where check = (eitherFromMaybe "Wrong version format!" . V.fromString . injectDefault def)
askFor :: String -> IO String
askFor req = askForChecked Right req
askForWithDefault :: String -> String -> IO String
askForWithDefault def req = askForChecked (Right . injectDefault (Just def)) req
askForLimited :: String -> Int -> String -> IO String
askForLimited name limit req = askForChecked check req
where check str = if length str > limit
then Left errorMessage
else Right str
errorMessage = concat [ name
, " length shouldn't exceed "
, show limit
, " characters!"]
readDeps :: IO D.Description
readDeps = do
projectName <- askFor "Project name:"
userName <- askFor "Github user name:"
version <- askForVersion (Just "0.1.0") "Initial version? [default: 0.1.0]"
summary <- askForLimited "Summary" 80 "Summary:"
description <- askFor "Description:"
license <- askForWithDefault "BSD3" "License? [default: BSD3]"
repo <- askFor "Repository address?"
elmVersion <- askForVersion Nothing "Elm version?"
return $ D.Description (N.Name userName projectName) version summary description license repo [] [] elmVersion [] []
initialize :: IO ()
initialize = do
dependencies <- readDeps
BS.writeFile Path.description (encodePretty dependencies)
| laszlopandy/elm-package | src/Get/Init.hs | bsd-3-clause | 2,361 | 0 | 12 | 538 | 718 | 358 | 360 | 55 | 2 |
module ShouldCompile where
(<>) :: (a -> Maybe b) -> (b -> Maybe c) -> (a -> Maybe c)
(m1 <> m2) a1 = case m1 a1 of
Nothing -> Nothing
Just a2 -> m2 a2
| ezyang/ghc | testsuite/tests/parser/should_compile/read026.hs | bsd-3-clause | 209 | 0 | 11 | 93 | 91 | 46 | 45 | 5 | 2 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module TH_RichKinds2 where
import Data.Char
import Data.List
import Language.Haskell.TH
$(return [OpenTypeFamilyD (TypeFamilyHead
(mkName "Map") [KindedTV (mkName "f")
(AppT (AppT ArrowT (VarT (mkName "k1")))
(VarT (mkName "k2"))),
KindedTV (mkName "l")
(AppT ListT
(VarT (mkName "k1")))]
(KindSig (AppT ListT (VarT (mkName "k2")))) Nothing)])
$( let fixKs :: String -> String -- need to remove TH renaming index from k variables
fixKs s =
case (elemIndex 'k' s) of
Nothing -> s
Just i ->
if i == (length s) || (s !! (i+1) /= '_') then s else
let (prefix, suffix) = splitAt (i+2) s -- the +2 for the "k_"
(index, rest) = span isDigit suffix in
if length index == 0 then s else
prefix ++ "0" ++ (fixKs rest)
in
do decls <- [d| data SMaybe :: (k -> *) -> (Maybe k) -> * where
SNothing :: SMaybe s 'Nothing
SJust :: s a -> SMaybe s ('Just a)
type instance Map f '[] = '[]
type instance Map f (h ': t) = ((f h) ': (Map f t))
|]
reportWarning (fixKs (pprint decls))
return decls )
data SBool :: Bool -> * where
SFalse :: SBool 'False
STrue :: SBool 'True
mbool :: SMaybe SBool ('Just 'False)
mbool = SJust SFalse
| ezyang/ghc | testsuite/tests/th/TH_RichKinds2.hs | bsd-3-clause | 1,698 | 0 | 21 | 620 | 444 | 231 | 213 | 41 | 1 |
{-# LANGUAGE TypeFamilies #-}
module B where
class Entity v where
data Fields v
instance Show (Fields v) where show = undefined
| wxwxwwxxx/ghc | testsuite/tests/driver/T5147/B1.hs | bsd-3-clause | 134 | 0 | 7 | 28 | 37 | 21 | 16 | 5 | 0 |
module ShouldFail where
data Foo = MkFoo Bool
instance Eq Foo where
(MkFoo x) == (MkFoo y) = x == y
instance Eq Foo where
-- forgot to type "Ord" above
(MkFoo x) <= (MkFoo y) = x <= y
| urbanslug/ghc | testsuite/tests/typecheck/should_fail/tcfail056.hs | bsd-3-clause | 200 | 0 | 8 | 56 | 84 | 43 | 41 | 6 | 0 |
{-# LANGUAGE OverloadedStrings #-}
-- | The @futhark@ command line program.
module Main (main) where
import Control.Exception
import Control.Monad
import Data.List (sortOn)
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.IO as T
import qualified Futhark.CLI.Autotune as Autotune
import qualified Futhark.CLI.Bench as Bench
import qualified Futhark.CLI.C as C
import qualified Futhark.CLI.CUDA as CCUDA
import qualified Futhark.CLI.Check as Check
import qualified Futhark.CLI.Datacmp as Datacmp
import qualified Futhark.CLI.Dataset as Dataset
import qualified Futhark.CLI.Defs as Defs
import qualified Futhark.CLI.Dev as Dev
import qualified Futhark.CLI.Doc as Doc
import qualified Futhark.CLI.Literate as Literate
import qualified Futhark.CLI.Misc as Misc
import qualified Futhark.CLI.Multicore as Multicore
import qualified Futhark.CLI.MulticoreWASM as MulticoreWASM
import qualified Futhark.CLI.OpenCL as OpenCL
import qualified Futhark.CLI.Pkg as Pkg
import qualified Futhark.CLI.PyOpenCL as PyOpenCL
import qualified Futhark.CLI.Python as Python
import qualified Futhark.CLI.Query as Query
import qualified Futhark.CLI.REPL as REPL
import qualified Futhark.CLI.Run as Run
import qualified Futhark.CLI.Test as Test
import qualified Futhark.CLI.WASM as WASM
import Futhark.Error
import Futhark.Util (maxinum)
import Futhark.Util.Options
import GHC.IO.Encoding (setLocaleEncoding)
import GHC.IO.Exception (IOErrorType (..), IOException (..))
import System.Environment
import System.Exit
import System.IO
import Prelude
type Command = String -> [String] -> IO ()
commands :: [(String, (Command, String))]
commands =
sortOn
fst
[ ("dev", (Dev.main, "Run compiler passes directly.")),
("repl", (REPL.main, "Run interactive Read-Eval-Print-Loop.")),
("run", (Run.main, "Run a program through the (slow!) interpreter.")),
("c", (C.main, "Compile to sequential C.")),
("opencl", (OpenCL.main, "Compile to C calling OpenCL.")),
("cuda", (CCUDA.main, "Compile to C calling CUDA.")),
("multicore", (Multicore.main, "Compile to multicore C.")),
("python", (Python.main, "Compile to sequential Python.")),
("pyopencl", (PyOpenCL.main, "Compile to Python calling PyOpenCL.")),
("wasm", (WASM.main, "Compile to WASM with sequential C")),
("wasm-multicore", (MulticoreWASM.main, "Compile to WASM with multicore C")),
("test", (Test.main, "Test Futhark programs.")),
("bench", (Bench.main, "Benchmark Futhark programs.")),
("dataset", (Dataset.main, "Generate random test data.")),
("datacmp", (Datacmp.main, "Compare Futhark data files for equality.")),
("dataget", (Misc.mainDataget, "Extract test data.")),
("doc", (Doc.main, "Generate documentation for Futhark code.")),
("pkg", (Pkg.main, "Manage local packages.")),
("check", (Check.main, "Type-check a program.")),
("check-syntax", (Misc.mainCheckSyntax, "Syntax-check a program.")),
("imports", (Misc.mainImports, "Print all non-builtin imported Futhark files.")),
("hash", (Misc.mainHash, "Print hash of program AST.")),
("autotune", (Autotune.main, "Autotune threshold parameters.")),
("defs", (Defs.main, "Show location and name of all definitions.")),
("query", (Query.main, "Query semantic information about program.")),
("literate", (Literate.main, "Process a literate Futhark program."))
]
msg :: String
msg =
unlines $
["<command> options...", "Commands:", ""]
++ [ " " <> cmd <> replicate (k - length cmd) ' ' <> desc
| (cmd, (_, desc)) <- commands
]
where
k = maxinum (map (length . fst) commands) + 3
-- | Catch all IO exceptions and print a better error message if they
-- happen.
reportingIOErrors :: IO () -> IO ()
reportingIOErrors =
flip
catches
[ Handler onExit,
Handler onICE,
Handler onIOException,
Handler onError
]
where
onExit :: ExitCode -> IO ()
onExit = throwIO
onICE :: InternalError -> IO ()
onICE (Error CompilerLimitation s) = do
T.hPutStrLn stderr "Known compiler limitation encountered. Sorry."
T.hPutStrLn stderr "Revise your program or try a different Futhark compiler."
T.hPutStrLn stderr s
exitWith $ ExitFailure 1
onICE (Error CompilerBug s) = do
T.hPutStrLn stderr "Internal compiler error."
T.hPutStrLn stderr "Please report this at https://github.com/diku-dk/futhark/issues."
T.hPutStrLn stderr s
exitWith $ ExitFailure 1
onError :: SomeException -> IO ()
onError e
| Just UserInterrupt <- asyncExceptionFromException e =
return () -- This corresponds to CTRL-C, which is not an error.
| otherwise = do
T.hPutStrLn stderr "Internal compiler error (unhandled IO exception)."
T.hPutStrLn stderr "Please report this at https://github.com/diku-dk/futhark/issues"
T.hPutStrLn stderr $ T.pack $ show e
exitWith $ ExitFailure 1
onIOException :: IOException -> IO ()
onIOException e
| ioe_type e == ResourceVanished =
exitWith $ ExitFailure 1
| otherwise = throw e
main :: IO ()
main = reportingIOErrors $ do
hSetEncoding stdout utf8
hSetEncoding stderr utf8
setLocaleEncoding utf8
args <- getArgs
prog <- getProgName
case args of
cmd : args'
| Just (m, _) <- lookup cmd commands -> m (unwords [prog, cmd]) args'
_ -> mainWithOptions () [] msg (const . const Nothing) prog args
| diku-dk/futhark | src/main.hs | isc | 5,513 | 0 | 16 | 1,082 | 1,438 | 848 | 590 | 124 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Store.SQL.Util.Pivots where
{-- Pivot tables ---------------------------------------------------------------
Last week you were able to scan the database, extract rows of name(s), parse
the names, then store them as parsed entities in the database connected to the
source article via a join-table. These join tables, also known as 'pivot
tables,' are prevalent and follow a certain structure. Instead of the specific
ArticlePersonJoin structure, we'll declare and use the general Pivot type here.
--}
import Control.Arrow (second)
import Control.Monad.State
import Data.Aeson
import qualified Data.Map as Map
import qualified Data.Set as Set
import Database.PostgreSQL.Simple
import Database.PostgreSQL.Simple.SqlQQ
import Database.PostgreSQL.Simple.ToRow
import Database.PostgreSQL.Simple.FromRow
import Database.PostgreSQL.Simple.ToField
-- below import available via 1HaskellADay git repository
import Data.MemoizingTable (MemoizingState, MemoizingTable(MT))
import qualified Data.MemoizingTable as MT
import Store.SQL.Util.Indexed
data Pivot = Pvt { srcIx, trgId :: Integer }
deriving (Eq, Ord, Show)
-- creates a Pivot value from source and destination table indices
joinValue :: Indexed i => i -> Index -> Pivot
joinValue i j = Pvt (idx i) (idx j)
-- and a pivot as a pair:
toTup :: Pivot -> (Integer, Integer)
toTup (Pvt a b) = (a, b)
-- and now we need a pivot-inserter
instance ToRow Pivot where
toRow (Pvt i j) = map toField [i,j]
-- and to insert the pivots is simply using the pivot table insert statement,
-- in this case insertArtPersJoinStmt, with the inserter function.
{-- e.g.:
>>> inserter conn insertArtPersJoinStmt (zipWith joinValue pers ixpers)
--}
instance FromRow Pivot where
fromRow = Pvt <$> field <*> field
instance ToJSON Pivot where
toJSON (Pvt k1 k2) = object ["article_id" .= k1, "subject_id" .= k2]
{--
This happens frequently: we need to tie together a symbol table to the primary
table. The symbol table is built in a MemoizingTable
--}
buildPivots :: Ord val => Monad m => MemoizingState m [Pivot] Integer val
buildPivots = get >>= \(MT _ keys _, joins) ->
return (map (uncurry Pvt)
(concatMap (sequence . (second (map (keys Map.!))))
(Map.toList joins)))
{--
Keywords, Authors, and sections. All three follow the same pattern:
* fetch previously stored values
* memoize
* materials values from article set, see which values are new
* store new values, relate all values.
If we are following the same pattern, is there a generalization of the
functions for all of this, so we can have one function that does the work
for any memoize-y type? What would this function look like?
--}
memoizeStore :: ToRow a => Ord a =>
Connection
-> (Connection -> IO [IxValue a])
-> (Connection -> [a] -> IO [Index])
-> Query
-> (article -> [a])
-> [IxValue article]
-> IO ()
memoizeStore conn fetcher storer pivotQuery getter ixarts =
-- so, 1. we need to fetch currently-stored values and start the MemoizingTable
fetcher conn >>= \ixvals ->
let memtable = MT.start (map ix2tup ixvals)
(ids,arts) = unzip (map ix2tup ixarts)
stat = execState (zipWithM_ MT.triageM ids (map getter arts))
(memtable,Map.empty)
substate = Set.toList (MT.newValues (fst stat))
in storer conn substate >>= \ixnewvals ->
let table = MT.update (zip (map idx ixnewvals) substate) (fst stat)
in void (executeMany conn pivotQuery
(evalState buildPivots (table, snd stat)))
| geophf/1HaskellADay | exercises/HAD/Store/SQL/Util/Pivots.hs | mit | 3,684 | 0 | 19 | 794 | 775 | 424 | 351 | -1 | -1 |
{-|
Module : Types
Description : Example of types operations in Haskell
Copyright : (c) Fabrício Olivetti, 2017
License : GPL-3
Maintainer : [email protected]
A sample of operations with different types.
-}
module Main where
-- |'soma' sums two integer values
soma :: Integer -> Integer -> Integer
soma x y = x + y
-- |'aurea' defines the golden number
aurea = (1 + sqrt 5) / 2.0
-- |'bissexto' returns whether 'ano' is a leap year (ugly version)
bissexto ano = (ano `rem` 400 == 0) || ((ano `rem` 4 == 0) && (ano `rem` 100 /= 0))
-- |'main' executa programa principal
main :: IO ()
main = do
print (soma 1 3)
print aurea
print (bissexto 2018)
| folivetti/BIGDATA | 02 - Básico/Types.hs | mit | 685 | 0 | 10 | 151 | 160 | 87 | 73 | 10 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Compiler.Types where
import Constants
import Control.Monad (mzero)
import CoreTypes
import Data.Aeson (FromJSON (..), ToJSON (..), Value (..), object,
(.:), (.=))
import Language.Types
import Monad
import Types
data Deployment = Put
{ deployment_srcs :: [FilePath]
, deployment_dst :: FilePath
, deployment_kind :: DeploymentKind
} deriving Eq
instance Show Deployment where
show dep = unwords $ srcs ++ [k,dst]
where
srcs = map quote $ deployment_srcs dep
k = case deployment_kind dep of
LinkDeployment -> linkKindSymbol
CopyDeployment -> copyKindSymbol
dst = quote $ deployment_dst dep
quote = (\s -> "\"" ++ s ++ "\"")
instance FromJSON Deployment where
parseJSON (Object o)
= Put <$> o .: "sources"
<*> o .: "destination"
<*> o .: "deployment kind"
parseJSON _ = mzero
instance ToJSON Deployment where
toJSON depl
= object
[ "sources" .= deployment_srcs depl
, "destination" .= deployment_dst depl
, "deployment kind" .= deployment_kind depl
]
type CompilerPrefix = [PrefixPart]
data PrefixPart
= Literal String
| Alts [String]
deriving (Show, Eq)
data CompilerState = CompilerState
{ state_deployment_kind_override :: Maybe DeploymentKind
, state_into :: Directory
, state_outof_prefix :: CompilerPrefix
} deriving (Show, Eq)
type PrecompileError = String
type ImpureCompiler = ExceptT CompileError (ReaderT SparkConfig IO)
type PureCompiler = ExceptT CompileError (ReaderT SparkConfig Identity)
type Precompiler = WriterT [PrecompileError] Identity
type InternalCompiler = StateT CompilerState (WriterT ([Deployment], [CardReference]) PureCompiler)
| badi/super-user-spark | src/Compiler/Types.hs | mit | 1,955 | 0 | 11 | 577 | 482 | 273 | 209 | 50 | 0 |
-- Traits type class
-- ref: https://wiki.haskell.org/Traits_type_class
-- ref: https://wiki.haskell.org/Reified_type
-- blog: http://augustss.blogspot.nl/2007/04/overloading-haskell-numbers-part-3.html
-- Occasionally you want to associate information with a type, not just a value. An example is the standard Bounded class:
class Bounded a where
minBound :: a
maxBound :: a
-- However, this technique does not work if the information which you want to extract doesn't have the type in its signature. One example is floating point format information, such as:
class FloatTraits a where
-- This one is fine
epsilon :: a
-- This one is not
mantissaDigits :: Int
-- etc
-- The problem is that there is simply no way to tell Haskell which version of mantissaDigits you want, because the Type parameter a does not appear in its type signature anywhere.
-- The solution is to pass a Reified type as a phantom argument:
class FloatTraits a where
mantissaDigits :: a -> Int
instance FloatTraits Float where
mantissaDigits _ = 24
instance FloatTraits Double where
mantissaDigits _ = 53
-- This technique works well in conjunction with Functional dependencies. For example, there may be some float types for which an Int may not be sufficient to express the number of digits in the mantissa:
class (Integral i) => FloatTraits a i | a -> i where
mantissaDigits :: a -> i
instance FloatTraits Float Int where
mantissaDigits _ = 24
instance FloatTraits ArbitraryPrecisionFloat Integer where
mantissaDigits x = {- detail omitted -}
-- You can also use this technique as an alternative to Higher order functions in cases where you need several functions which work together.
-- Consider, for example, converting strings from upper case to lower case and back again. This in general depends on the language that you are operating in. The lower case version of 'A', for example, is different in English than in Greek. You can wrap this up in a typeclass parameterised on language:
class CaseConvert language where
toUpperCase :: language -> String -> String
toLowerCase :: language -> String -> String
data EnglishLanguage = EnglishLanguage
instance CaseConvert EnglishLanguage where
toUpperCase _ s = {- etc -}
toLowerCase _ s = {- etc -}
data GreekLanguage = GreekLanguage
instance CaseConvert GreekLanguage where
toUpperCase _ s = {- etc -}
toLowerCase _ s = {- etc -}
-- Reified type
{-
To "reify" something is to take something that is abstract and regard it as material. A classic example is the way that the ancients took abstract concepts (e.g. "victory") and turned them into deities (e.g. Nike, the Greek goddess of victory).
A reified type is a value that represents a type. Using reified types instead of real types means that you can do any manipulations with them that you can do with values.
In Haskell, the value undefined is a member of every (boxed) type, so that is often a good value to use to represent a type, assuming you don't need to break it apart.
-} | Airtnp/Freshman_Simple_Haskell_Lib | Idioms/Traits-type-class.hs | mit | 3,073 | 2 | 7 | 601 | 277 | 152 | 125 | -1 | -1 |
module Debug.Debug (
DebugShow,
debug_show,
) where
class DebugShow a where
debug_show :: a -> String
| quintenpalmer/fresh | haskell/src/Debug/Debug.hs | mit | 115 | 0 | 7 | 29 | 33 | 19 | 14 | 5 | 0 |
-- Convert string to camel case
-- http://www.codewars.com/kata/517abf86da9663f1d2000003/
module CamelCase where
import Data.Char (toUpper)
import Data.List.Split (split, dropDelims, oneOf)
toCamelCase :: String -> String
toCamelCase str = f . split (dropDelims $ oneOf "-_") $ str
where f [] = []
f [x] = x
f (x:xs) = x ++ concatMap g xs
g [] = []
g (x:xs) = toUpper x : xs
| gafiatulin/codewars | src/5 kyu/CamelCase.hs | mit | 422 | 0 | 10 | 111 | 154 | 83 | 71 | 10 | 4 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ViewPatterns #-}
module Hpack.Render.Hints (
FormattingHints (..)
, sniffFormattingHints
#ifdef TEST
, extractFieldOrder
, extractSectionsFieldOrder
, sanitize
, unindent
, sniffAlignment
, splitField
, sniffIndentation
, sniffCommaStyle
#endif
) where
import Data.Char
import Data.Maybe
import Data.List
import Control.Applicative
import Hpack.Render.Dsl
data FormattingHints = FormattingHints {
formattingHintsFieldOrder :: [String]
, formattingHintsSectionsFieldOrder :: [(String, [String])]
, formattingHintsAlignment :: Maybe Alignment
, formattingHintsRenderSettings :: RenderSettings
} deriving (Eq, Show)
sniffFormattingHints :: [String] -> FormattingHints
sniffFormattingHints (sanitize -> input) = FormattingHints {
formattingHintsFieldOrder = extractFieldOrder input
, formattingHintsSectionsFieldOrder = extractSectionsFieldOrder input
, formattingHintsAlignment = sniffAlignment input
, formattingHintsRenderSettings = sniffRenderSettings input
}
sanitize :: [String] -> [String]
sanitize = filter (not . isPrefixOf "cabal-version:") . filter (not . null) . map stripEnd
stripEnd :: String -> String
stripEnd = reverse . dropWhile isSpace . reverse
extractFieldOrder :: [String] -> [String]
extractFieldOrder = map fst . catMaybes . map splitField
extractSectionsFieldOrder :: [String] -> [(String, [String])]
extractSectionsFieldOrder = map (fmap extractFieldOrder) . splitSections
where
splitSections input = case break startsWithSpace input of
([], []) -> []
(xs, ys) -> case span startsWithSpace ys of
(fields, zs) -> case reverse xs of
name : _ -> (name, unindent fields) : splitSections zs
_ -> splitSections zs
startsWithSpace :: String -> Bool
startsWithSpace xs = case xs of
y : _ -> isSpace y
_ -> False
unindent :: [String] -> [String]
unindent input = map (drop indentation) input
where
indentation = minimum $ map (length . takeWhile isSpace) input
sniffAlignment :: [String] -> Maybe Alignment
sniffAlignment input = case nub . catMaybes . map indentation . catMaybes . map splitField $ input of
[n] -> Just (Alignment n)
_ -> Nothing
where
indentation :: (String, String) -> Maybe Int
indentation (name, value) = case span isSpace value of
(_, "") -> Nothing
(xs, _) -> (Just . succ . length $ name ++ xs)
splitField :: String -> Maybe (String, String)
splitField field = case span isNameChar field of
(xs, ':':ys) -> Just (xs, ys)
_ -> Nothing
where
isNameChar = (`elem` nameChars)
nameChars = ['a'..'z'] ++ ['A'..'Z'] ++ "-"
sniffIndentation :: [String] -> Maybe Int
sniffIndentation input = sniffFrom "library" <|> sniffFrom "executable"
where
sniffFrom :: String -> Maybe Int
sniffFrom section = case findSection . removeEmptyLines $ input of
_ : x : _ -> Just . length $ takeWhile isSpace x
_ -> Nothing
where
findSection = dropWhile (not . isPrefixOf section)
removeEmptyLines :: [String] -> [String]
removeEmptyLines = filter $ any (not . isSpace)
sniffCommaStyle :: [String] -> Maybe CommaStyle
sniffCommaStyle input
| any startsWithComma input = Just LeadingCommas
| any (startsWithComma . reverse) input = Just TrailingCommas
| otherwise = Nothing
where
startsWithComma = isPrefixOf "," . dropWhile isSpace
sniffRenderSettings :: [String] -> RenderSettings
sniffRenderSettings input = RenderSettings indentation fieldAlignment commaStyle
where
indentation = fromMaybe (renderSettingsIndentation defaultRenderSettings) (sniffIndentation input)
fieldAlignment = renderSettingsFieldAlignment defaultRenderSettings
commaStyle = fromMaybe (renderSettingsCommaStyle defaultRenderSettings) (sniffCommaStyle input)
| haskell-tinc/hpack | src/Hpack/Render/Hints.hs | mit | 3,834 | 63 | 18 | 740 | 1,134 | 614 | 520 | 77 | 4 |
{-# LANGUAGE FlexibleContexts #-}
{-
Copyright (C) 2012 Kacper Bak <http://gsd.uwaterloo.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-}
module Language.Clafer.Intermediate.ResolverInheritance where
import Control.Applicative
import Control.Monad
import Control.Monad.Error
import Control.Monad.State
import Data.Maybe
import Data.Graph
import Data.Tree
import Data.List
import qualified Data.Map as Map
import Language.ClaferT
import Language.Clafer.Common
import Language.Clafer.Front.Absclafer
import Language.Clafer.Intermediate.Intclafer
import Language.Clafer.Intermediate.ResolverName
-- | Resolve Non-overlapping inheritance
resolveNModule :: (IModule, GEnv) -> Resolve (IModule, GEnv)
resolveNModule (imodule, genv') =
do
let decls' = _mDecls imodule
decls'' <- mapM (resolveNElement decls') decls'
return (imodule{_mDecls = decls''}, genv' {sClafers = bfs toNodeShallow $ toClafers decls''})
resolveNClafer :: [IElement] -> IClafer -> Resolve IClafer
resolveNClafer declarations clafer =
do
super' <- resolveNSuper declarations $ _super clafer
elements' <- mapM (resolveNElement declarations) $ _elements clafer
return $ clafer {_super = super',
_elements = elements'}
resolveNSuper :: [IElement] -> ISuper -> Resolve ISuper
resolveNSuper declarations x = case x of
ISuper False [PExp _ pid' pos' (IClaferId _ id' isTop')] ->
if isPrimitive id' || id' == "clafer"
then return x
else do
r <- resolveN pos' declarations id'
id'' <- case r of
Nothing -> throwError $ SemanticErr pos' $ "No superclafer found: " ++ id'
Just m -> return $ fst m
return $ ISuper False [idToPExp pid' pos' "" id'' isTop']
_ -> return x
resolveNElement :: [IElement] -> IElement -> Resolve IElement
resolveNElement declarations x = case x of
IEClafer clafer -> IEClafer <$> resolveNClafer declarations clafer
IEConstraint _ _ -> return x
IEGoal _ _ -> return x
resolveN :: Span -> [IElement] -> String -> Resolve (Maybe (String, [IClafer]))
resolveN pos' declarations id' =
findUnique pos' id' $ map (\x -> (x, [x])) $ filter _isAbstract $ bfsClafers $
toClafers declarations
-- | Resolve overlapping inheritance
resolveOModule :: (IModule, GEnv) -> Resolve (IModule, GEnv)
resolveOModule (imodule, genv') =
do
let decls' = _mDecls imodule
decls'' <- mapM (resolveOElement (defSEnv genv' decls')) decls'
return (imodule {_mDecls = decls''}, genv' {sClafers = bfs toNodeShallow $ toClafers decls''})
resolveOClafer :: SEnv -> IClafer -> Resolve IClafer
resolveOClafer env clafer =
do
super' <- resolveOSuper env {context = Just clafer} $ _super clafer
elements' <- mapM (resolveOElement env {context = Just clafer}) $ _elements clafer
return $ clafer {_super = super', _elements = elements'}
resolveOSuper :: SEnv -> ISuper -> Resolve ISuper
resolveOSuper env x = case x of
ISuper True exps' -> do
exps'' <- mapM (resolvePExp env) exps'
let isOverlap = not (length exps'' == 1 && isPrimitive (getSuperId exps''))
return $ ISuper isOverlap exps''
_ -> return x
resolveOElement :: SEnv -> IElement -> Resolve IElement
resolveOElement env x = case x of
IEClafer clafer -> IEClafer <$> resolveOClafer env clafer
IEConstraint _ _ -> return x
IEGoal _ _ -> return x
-- | Resolve inherited and default cardinalities
analyzeModule :: (IModule, GEnv) -> IModule
analyzeModule (imodule, genv') =
imodule{_mDecls = map (analyzeElement (defSEnv genv' decls')) decls'}
where
decls' = _mDecls imodule
analyzeClafer :: SEnv -> IClafer -> IClafer
analyzeClafer env clafer =
clafer' {_elements = map (analyzeElement env {context = Just clafer'}) $
_elements clafer'}
where
clafer' = clafer {_gcard = analyzeGCard env clafer,
_card = analyzeCard env clafer}
-- only for non-overlapping
analyzeGCard :: SEnv -> IClafer -> Maybe IGCard
analyzeGCard env clafer = gcard' `mplus` (Just $ IGCard False (0, -1))
where
gcard'
| _isOverlapping $ _super clafer = _gcard clafer
| otherwise = listToMaybe $ mapMaybe _gcard $
findHierarchy getSuper (clafers env) clafer
analyzeCard :: SEnv -> IClafer -> Maybe Interval
analyzeCard env clafer = _card clafer `mplus` Just card'
where
card'
| _isAbstract clafer = (0, -1)
| (isJust $ context env) && pGcard == (0, -1)
|| (isTopLevel $ _cinPos clafer) = (1, 1)
| otherwise = (0, 1)
pGcard = _interval $ fromJust $ _gcard $ fromJust $ context env
isTopLevel (Span (Pos _ c) _) = c==1
analyzeElement :: SEnv -> IElement -> IElement
analyzeElement env x = case x of
IEClafer clafer -> IEClafer $ analyzeClafer env clafer
IEConstraint _ _ -> x
IEGoal _ _ -> x
-- | Expand inheritance
resolveEModule :: (IModule, GEnv) -> (IModule, GEnv)
resolveEModule (imodule, genv') = (imodule{_mDecls = decls''}, genv'')
where
decls' = _mDecls imodule
(decls'', genv'') = runState (mapM (resolveEElement []
(unrollableModule imodule)
False decls') decls') genv'
-- -----------------------------------------------------------------------------
unrollableModule :: IModule -> [String]
unrollableModule imodule = getDirUnrollables $
mapMaybe unrollabeDeclaration $ _mDecls imodule
unrollabeDeclaration :: IElement -> Maybe (String, [String])
unrollabeDeclaration x = case x of
IEClafer clafer -> if _isAbstract clafer
then Just (_uid clafer, unrollableClafer clafer)
else Nothing
IEConstraint _ _ -> Nothing
IEGoal _ _ -> Nothing
unrollableClafer :: IClafer -> [String]
unrollableClafer clafer
| _isOverlapping $ _super clafer = []
| getSuper clafer == "clafer" = deps
| otherwise = getSuper clafer : deps
where
deps = (toClafers $ _elements clafer) >>= unrollableClafer
getDirUnrollables :: [(String, [String])] -> [String]
getDirUnrollables dependencies = (filter isUnrollable $ map (map v2n) $
map flatten (scc graph)) >>= map fst3
where
(graph, v2n, _) = graphFromEdges $map (\(c, ss) -> (c, c, ss)) dependencies
isUnrollable (x:[]) = fst3 x `elem` trd3 x
isUnrollable _ = True
-- -----------------------------------------------------------------------------
resolveEClafer :: MonadState GEnv m => [String] -> [String] -> Bool -> [IElement] -> IClafer -> m IClafer
resolveEClafer predecessors unrollables absAncestor declarations clafer = do
sClafers' <- gets sClafers
clafer' <- renameClafer absAncestor clafer
let predecessors' = _uid clafer' : predecessors
(sElements, super', superList) <-
resolveEInheritance predecessors' unrollables absAncestor declarations
(findHierarchy getSuper sClafers' clafer)
let sClafer = Map.fromList $ zip (map _uid superList) $ repeat [predecessors']
modify (\e -> e {stable = Map.delete "clafer" $
Map.unionWith ((nub.).(++)) sClafer $
stable e})
elements' <-
mapM (resolveEElement predecessors' unrollables absAncestor declarations)
$ _elements clafer
return $ clafer' {_super = super', _elements = elements' ++ sElements}
renameClafer :: MonadState GEnv m => Bool -> IClafer -> m IClafer
renameClafer False clafer = return clafer
renameClafer True clafer = renameClafer' clafer
renameClafer' :: MonadState GEnv m => IClafer -> m IClafer
renameClafer' clafer = do
let claferIdent = _ident clafer
identCountMap' <- gets identCountMap
let count = Map.findWithDefault 0 claferIdent identCountMap'
modify (\e -> e { identCountMap = Map.alter (\_ -> Just (count+1)) claferIdent identCountMap' } )
return $ clafer { _uid = genId claferIdent count }
genId :: String -> Int -> String
genId id' count = concat ["c", show count, "_", id']
resolveEInheritance :: MonadState GEnv m => [String] -> [String] -> Bool -> [IElement] -> [IClafer] -> m ([IElement], ISuper, [IClafer])
resolveEInheritance predecessors unrollables absAncestor declarations allSuper
| _isOverlapping $ _super clafer = return ([], _super clafer, [clafer])
| otherwise = do
let superList = (if absAncestor then id else tail) allSuper
let unrollSuper = filter (\s -> _uid s `notElem` unrollables) $ tail allSuper
elements' <-
mapM (resolveEElement predecessors unrollables True declarations) $
unrollSuper >>= _elements
let super' = if (getSuper clafer `elem` unrollables)
then _super clafer
else ISuper False [idToPExp "" noSpan "" "clafer" False]
return (elements', super', superList)
where
clafer = head allSuper
resolveEElement :: MonadState GEnv m => [String] -> [String] -> Bool -> [IElement] -> IElement -> m IElement
resolveEElement predecessors unrollables absAncestor declarations x = case x of
IEClafer clafer -> if _isAbstract clafer then return x else IEClafer `liftM`
resolveEClafer predecessors unrollables absAncestor declarations clafer
IEConstraint _ _ -> return x
IEGoal _ _ -> return x
| juodaspaulius/clafer-old-customBNFC | src/Language/Clafer/Intermediate/ResolverInheritance.hs | mit | 10,166 | 1 | 18 | 2,168 | 2,994 | 1,522 | 1,472 | 180 | 4 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Cilia.Config where
import Prelude
import Data.Maybe(fromMaybe)
import qualified Data.Text as T
import Data.Yaml( FromJSON(..)
, (.:)
, (.:?)
, decodeFileEither)
import qualified Data.Yaml as Y
import Lens.Micro.TH(makeLenses)
data DefaultSection =
DefaultSection { _refreshInterval :: Int
}deriving(Eq, Show)
instance FromJSON DefaultSection where
parseJSON (Y.Object o) = DefaultSection <$>
fmap (fromMaybe 10) (o .:? "refreshInterval")
parseJSON _ = error "Expected travis section"
makeLenses ''DefaultSection
data TravisSection =
TravisSection { _userName :: T.Text
}deriving(Eq, Show)
instance FromJSON TravisSection where
parseJSON (Y.Object o) = TravisSection <$>
o .: "userName"
parseJSON _ = error "Expected travis section"
makeLenses ''TravisSection
data Config =
Config { _defaultSection :: DefaultSection
, _travis :: TravisSection
}deriving(Eq, Show)
instance FromJSON Config where
parseJSON (Y.Object o) = Config <$>
o .: "default" <*>
o .: "travis"
parseJSON _ = fail "Expected configuration object"
makeLenses ''Config
readConfig :: T.Text -> IO Config
readConfig configFileName =
either (error . show) id <$>
decodeFileEither (T.unpack configFileName) | bbiskup/cilia | src-lib/Cilia/Config.hs | mit | 1,446 | 0 | 9 | 364 | 385 | 209 | 176 | 42 | 1 |
module Y2017.M01.D02.Exercise where
import Data.List
import Data.Set (Set)
{--
Happy New Year, Haskellers.
Dr. Paul Coxon claims 2017 will be less divisive than 2016.
He is correct, but let's prove it.
1. What are the unique divisors of last year and this year?
--}
type Year = Int
uniqueFactors :: Year -> Set Int
uniqueFactors yr = undefined
{--
So:
uniqueFactors 2017 will get you {1,2017}
uniqueFactors 2016 will get you {1,4,7,8,9}
2. What are the unique prime factors of each of these years?
--}
primeFactors :: Year -> Set Int
primeFactors = undefined
{--
So:
primeFactors 2017 ~> {2017}
primeFactors 2016 ~> {2,3,7}
Question:
1. What years AD 2 - AD 2017 are prime?
--}
primeYears :: [Year] -> Set Year
primeYears yrs = undefined
-- 2. Order those years (AD 2 - AD 2017) by the number of their factors
-- 2a. Which year(s) had the most unique factors
-- 2b (or not 2b) (I love writing that) Which years had the most prime factors?
orderedYears :: (Year -> Set Int) -> [Year] -> [(Year, Set Int)]
orderedYears factoringFn years = undefined
-- Hint: you may wish to use Data.List.sortBy and Data.List.group to answer 2.
| geophf/1HaskellADay | exercises/HAD/Y2017/M01/D02/Exercise.hs | mit | 1,147 | 0 | 9 | 218 | 144 | 83 | 61 | 12 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Utils.Password
( Password (Password)
, PasswordHash
, verifyPassword
, createPasswordHash
, writePasswordHashToFile
, readPasswordHashFromFile
)where
import Data.String (IsString(..))
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Crypto.Hash (Digest, SHA256(..), hash, digestToHexByteString)
newtype Password =
Password { getPwd :: Text }
instance IsString Password where
fromString = Password . fromString
newtype PasswordHash =
PasswordHash { getHash :: ByteString }
deriving Eq
verifyPassword :: PasswordHash -> Password -> Bool
verifyPassword hash pwd =
hash == createPasswordHash pwd
createPasswordHash :: Password -> PasswordHash
createPasswordHash =
PasswordHash .
digestToHexByteString .
(hash :: ByteString -> Digest SHA256) .
encodeUtf8 .
getPwd
writePasswordHashToFile :: FilePath -> Password -> IO ()
writePasswordHashToFile path =
B.writeFile path . getHash . createPasswordHash
readPasswordHashFromFile :: FilePath -> IO PasswordHash
readPasswordHashFromFile path =
PasswordHash <$> B.readFile path
| CarstenKoenig/MyWebSite | src/Utils/Password.hs | mit | 1,215 | 0 | 10 | 200 | 294 | 170 | 124 | 40 | 1 |
-- Smallest multiple
-- Problem 5
-- 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
-- What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
main = do
print (getSmallestN)
getSmallestN =
head [x | x <- [2520,2540..], all (isDivisibleBy x) [11..19]]
isDivisibleBy x y =
x `mod` y == 0
| BrunoRB/haskell-problems | euler/euler5.hs | mit | 404 | 0 | 10 | 90 | 84 | 46 | 38 | 6 | 1 |
module GHCJS.DOM.MediaKeyEvent (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/MediaKeyEvent.hs | mit | 43 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
module Main where
import Servant.Server
import Network.Wai.Handler.Warp
import Api
--------------------------------------------------------------------------------
main :: IO ()
main = do
run 3000 (serve api server)
| sigrlami/servant-examples | servant-auth-basic/src/Main.hs | mit | 222 | 0 | 9 | 28 | 51 | 29 | 22 | 7 | 1 |
module Parser.Expression where
import Text.Parsec
import Text.Parsec.String
import Text.Parsec.Char
import Types
import Parser.Common
-- CALL --
call :: Parser Call
call = do
pos <- getPosition
name <- identifier
openParen
args <- expr `sepBy` (char ',')
closeParen
return $ Call pos name args
-- EXPRESSION --
expr :: Parser Expr
expr = do
spaces
intLit <|> charLit <|> boolLit <|> (try callExpr) <|> var
callExpr :: Parser Expr
callExpr = do
c <- call
return $ CallExpr c
var :: Parser Expr
var = do
pos <- getPosition
name <- identifier
return $ ExprVar $ Var pos name
intLit :: Parser Expr
intLit = do
pos <- getPosition
str <- (string "0") <|> do
a <- satisfy $ \c -> c `elem` ['1' .. '9']
b <- many digit
return $ a:b
let val = (read str) :: Int
return $ IntLitExpr $ IntLit pos val
charLit :: Parser Expr
charLit = do
pos <- getPosition
char '\''
c <- newLineChar <|> anyChar
char '\''
return $ CharLitExpr $ CharLit pos c
newLineChar :: Parser Char
newLineChar = do
char '\\'
char 'n'
return '\n'
boolLit :: Parser Expr
boolLit = do
spaces
pos <- getPosition
stringValue <- (string "true") <|> (string "false")
let value = stringValue == "true"
return $ BoolLitExpr $ BoolLit pos value
| PelleJuul/popl | src/Parser/Expression.hs | mit | 1,279 | 0 | 15 | 301 | 498 | 240 | 258 | 55 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.