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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DeriveAnyClass, GeneralizedNewtypeDeriving #-}
module T15839a () where
class C a
newtype T a = MkT a deriving C
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T15839a.hs | bsd-3-clause | 127 | 0 | 5 | 22 | 27 | 17 | 10 | -1 | -1 |
{-# LANGUAGE CPP #-}
-- |
-- Module: Data.Aeson.Internal.Time
-- Copyright: (c) 2015 Bryan O'Sullivan
-- License: Apache
-- Maintainer: Bryan O'Sullivan <bos@serpentine.com>
-- Stability: experimental
-- Portability: portable
module Data.Aeson.Internal.Time
(
TimeOfDay64(..)
, fromPico
, toPico
, diffTimeOfDay64
, toTimeOfDay64
) where
import Data.Fixed (Pico)
import Data.Int (Int64)
import Data.Time
import Unsafe.Coerce (unsafeCoerce)
#if MIN_VERSION_base(4,7,0)
import Data.Fixed (Fixed(MkFixed))
toPico :: Integer -> Pico
toPico = MkFixed
fromPico :: Pico -> Integer
fromPico (MkFixed i) = i
#else
toPico :: Integer -> Pico
toPico = unsafeCoerce
fromPico :: Pico -> Integer
fromPico = unsafeCoerce
#endif
-- | Like TimeOfDay, but using a fixed-width integer for seconds.
data TimeOfDay64 = TOD {-# UNPACK #-} !Int
{-# UNPACK #-} !Int
{-# UNPACK #-} !Int64
diffTimeOfDay64 :: DiffTime -> TimeOfDay64
diffTimeOfDay64 t = TOD (fromIntegral h) (fromIntegral m) s
where (h,mp) = fromIntegral pico `quotRem` 3600000000000000
(m,s) = mp `quotRem` 60000000000000
pico = unsafeCoerce t :: Integer
toTimeOfDay64 :: TimeOfDay -> TimeOfDay64
toTimeOfDay64 (TimeOfDay h m s) = TOD h m (fromIntegral (fromPico s))
| abbradar/aeson | Data/Aeson/Internal/Time.hs | bsd-3-clause | 1,332 | 0 | 9 | 296 | 280 | 163 | 117 | 26 | 1 |
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE FlexibleInstances #-}
module Foo (A(P,Q)) where
data A a = A a
pattern P :: Show a => a -> A a
pattern P a = A a
pattern Q :: (A ~ f) => a -> f a
pattern Q a = A a
| tjakway/ghcjvm | testsuite/tests/patsyn/should_compile/poly-export2.hs | bsd-3-clause | 213 | 0 | 8 | 54 | 101 | 54 | 47 | 11 | 0 |
module T1735_Help.State where
import Control.Applicative (Applicative(..))
import Control.Monad (ap, liftM)
newtype StateT s m a = StateT { runStateT :: s -> m (a,s) }
instance Monad m => Monad (StateT s m) where
return a = StateT $ \s -> return (a, s)
m >>= k = StateT $ \s -> do
~(a, s') <- runStateT m s
runStateT (k a) s'
fail str = StateT $ \_ -> fail str
instance Monad m => Functor (StateT s m) where
fmap = liftM
instance Monad m => Applicative (StateT s m) where
pure = return
(<*>) = ap
get :: Monad m => StateT s m s
get = StateT $ \s -> return (s, s)
put :: Monad m => s -> StateT s m ()
put s = StateT $ \_ -> return ((), s)
| beni55/ghcjs | test/ghc/typecheck/T1735_Help/State.hs | mit | 719 | 0 | 12 | 218 | 342 | 182 | 160 | 19 | 1 |
{-# OPTIONS_GHC -XImpredicativeTypes -fno-warn-deprecated-flags #-}
-- Sept 16: now scraping through with -XImpredicateTypes
module Main where
data Foo x y = Foo {foo1 :: x, foo2 :: y}
instance Functor (Foo x) where
fmap f (Foo x y) = Foo x (f y)
bar :: a -> Foo (forall s. s) a
bar a = Foo undefined a
main = print (foo2 (fmap (*2) (bar 2)))
| ezyang/ghc | testsuite/tests/boxy/T2193.hs | bsd-3-clause | 353 | 0 | 11 | 76 | 139 | 76 | 63 | -1 | -1 |
{-# LANGUAGE TypeOperators #-}
module GTL.Game.TwoPlayer.RockPaperScissors ( module GTL.Game.TwoPlayer
, Action1(..), Signal1, u1
, Action2(..), Signal2, u2
, Actions, Signals
) where
import GTL.Game.TwoPlayer
import GTL.Data.Utility (UtilityAS)
import Data.Ix (Ix)
import Data.HList (HNil, (:*:))
data Action1 = R1 | P1 | S1 deriving (Show, Bounded, Ix, Eq, Ord)
type Signal1 = Action2
data Action2 = R2 | P2 | S2 deriving (Show, Bounded, Ix, Eq, Ord)
type Signal2 = Action1
u1 :: UtilityAS Action1 Signal1
u1 R1 S2 = 1
u1 P1 R2 = 1
u1 S1 P2 = 1
u1 R1 R2 = 0
u1 P1 P2 = 0
u1 S1 S2 = 0
u1 _ _ = -1
u2 :: UtilityAS Action2 Signal2
u2 R2 S1 = 1
u2 P2 R1 = 1
u2 S2 P1 = 1
u2 R2 R1 = 0
u2 P2 P1 = 0
u2 S2 S1 = 0
u2 _ _ = -1
type Actions = Action1 :*: Action2 :*: HNil
type Signals = Signal1 :*: Signal2 :*: HNil
| dudebout/game-theoretic-learning | GTL/Game/TwoPlayer/RockPaperScissors.hs | isc | 995 | 0 | 6 | 353 | 368 | 208 | 160 | 31 | 1 |
module ProjectEuler.Problem117
( problem
) where
import ProjectEuler.Types
import Data.Monoid
import Data.MemoTrie (memoFix)
problem :: Problem
problem = pureProblem 117 Solved result
{-
Despite that this problem is based on Problem116,
I doubt how much code we can reuse, as now tiles of
diffferent lengths are allowed to mix.
`ballsInBins` could still be useful,
but if we were to use it, we need to find all ways
of constructing up to n tiles using tiles of length 2,3,4,
and then fill in spaces...
Let's forget about it and try the same method as Problem114.
Let f(i) be the ways to occupy from 1 to i (inclusive),
and all these ways has to:
- at least have one block in it.
- the last block must end at position i.
f(0) = 0
f(1) = 0
f(2) = 1
[XX]
f(3) = 2
[_XX]
or [XXX]
f(4) = 4
[__XX]
or [_XXX]
or [XXXX]
or [XX|XX]
starting from f(5), there's always 3 "nothing but last block" cases,
they cannot be passed down from any previous f(?).
(In fact, the purpose of listing values from f(0) to f(4) is to avoid
conditioning on cases where some shorter block can fit but longer ones can't)
Now let length of last block be l, and the total length is i
we need to find all ways to occupy from block 1 to block (i-l),
f(i) = 3 + sum of f(j), where l = 2..4, j = 1..i-l
-}
f :: Int -> Integer
f = memoFix f'
where
f' pf i = case i of
0 -> 0
1 -> 0
2 -> 1
3 -> 2
4 -> 4
_ -> 3 + getSum (foldMap Sum [pf j | l <- [2..4], j <- [1..i-l]])
result :: Integer
result = 1 + getSum (foldMap (Sum . f) [1..50])
| Javran/Project-Euler | src/ProjectEuler/Problem117.hs | mit | 1,645 | 0 | 18 | 453 | 206 | 110 | 96 | 18 | 6 |
module Main where
import Cycles.Maxcy
import Cycles.Findcy
import Cycles.IO
import Cycles.Aux
import Cycles.Reap
--import Data.GList
import Control.Exception (catch, SomeException, throwIO)
import Control.Monad
import Data.List (sort, group)
import Test.Hspec
import Test.QuickCheck
import Test.QuickCheck.Gen
import Test.QuickCheck.Monadic
import System.Directory
import System.IO
import System.IO.Error ( isDoesNotExistError )
-- This is the test suite. Use "*y and "*p to copy between files.
-- Add a "print current options" feature for prop_goodShuttleGraphNumCyShuffled ->> run it alone until you get a memory blowup and then debug.
-- | Because the number of cycles and edges tried by quickcheck can blow up quickly, these are the ranges allowable for (reasonably) fast tests
-- Tested on Macbook Pro 15", Late 2011, 8 GB RAM, 2.5 GHZ Intel Core i7, 64-bit
maxNumCyForTest = completeGraphNumCy 6
-- | See 'maxNumCyForTest'
maxNumEdgesForTest = 100
-- | This tests the readInt function in Cycles.IO (notice the little endian interpretation)
prop_readInt :: Int -> Property
prop_readInt n = property $ (readInt . reverse . show . abs) n == abs n
-- | This tests the readIntList function in Cycles.IO (similar to \s->read s :: [Int], but faster)
prop_readIntList :: [Int] -> Property
prop_readIntList list = property $ readIntList (show posList) == posList
where
posList = map abs list
-- | This function sorts an [[Ord a]] on both levels (because FindCy and MaxCy both use ordered lists for undirected graphs)
sort2 lists = sort $ map sort lists
-- | This function takes a string and char and returns everything up to (but not including) that char
cutUntoChar :: String -> Char -> String
cutUntoChar [] _ = []
cutUntoChar (x:xs) char
| x == char = []
| otherwise = x : cutUntoChar xs char
-- | This function converts a string like "0101010101001010" into a list of Ints
readBins :: String -> [Int]
readBins [] = []
readBins ('0':xs) = 0 : readBins xs
readBins ('1':xs) = 1 : readBins xs
readBins (_:xs) = error "list passed not composed of 0's and 1's"
-- | This function converts a solution string (such as "[10101010, 2384]") to a (list of bins, number)
solutionStrToTup :: String -> ([Int], Int)
solutionStrToTup str = (readBins bins, read num)
where
bins = cutUntoChar (tail str) ','
num = reverse $ cutUntoChar (reverse $ trim str) ','
-- -- | This function takes a list of directions encoded as '1's and '0's ('0' is forward, i.e. [a,b] -> a<b) and a graph and returns a digraph
-- orientGraph :: (Ord a1, Num a1, Num a, Eq a) => [a] -> [[a1]] -> [[a1]] -- '0' forward (a<b)
-- orientGraph directions graph = if good then map (\tup ->if fst tup then snd tup else reverse $ snd tup) edgeTupList else error "bad graph or directions"
-- where
-- edgeTupList = zip (map (==0) directions) graph
-- good = sameLen && orderedEdges && orderedGraph
-- sameLen = length directions == length graph
-- orderedEdges = foldl (\prev next ->prev && (head next < last next)) True graph
-- orderedGraph = fst $ foldl (\prev next -> if fst prev then (snd prev < next, next) else (False, [0,0])) (True, [0,0]) graph
-- | This is the first level of the pipe 'strSolutionPipe'
strSolutionPipe1 :: String -> [[Int]] -> (([Int], Int), [[Int]])
strSolutionPipe1 string graph = (solutionStrToTup string, graph)
-- | This is the second level of the pipe 'strSolutionPipe'
strSolutionPipe2 :: (([Int], Int), [[Int]]) -> ([[Int]], Int)
strSolutionPipe2 ((binList, number), graph) = (orientGraph binList graph, number)
-- | This is the third level of the pipe 'strSolutionPipe'
strSolutionPipe3 :: ([[Int]], Int) -> IO Bool
strSolutionPipe3 (digraph, number) = do
ioNum <- graphToNumCycles digraph True
let supposedNum = number
return $ ioNum == supposedNum
-- | This function takes a solution string and a graph and returns whether the solution agrees with the graphToNumCycles interpretation
strSolutionPipe :: String -> [[Int]] -> IO Bool
strSolutionPipe string graph = strSolutionPipe3 $ strSolutionPipe2 $ strSolutionPipe1 string graph
-- | This function takes a file (path) and checks each solution against the graphToNumCycles interpretation
checkMaxCySolution :: FilePath -> IO Bool
checkMaxCySolution file = do
handle <- openFile file ReadMode
solutionFile <- catch (readFile file) handler
--goodFile <- return (finished $ lines solutionFile) -- && (good_graph solutionFile)
let graph = read $ head $ lines solutionFile
let solutionsStr = trim $ lines solutionFile
print graph
-- here, need to write function converting a single solution into (binary list, number)->(digraph, number)->(number from graphToNumCycles, number)->(fst %) == (snd %)
-- Solutions are of the form "[01010101001,6784765]"
whichValid <- mapM (\str -> return $ strSolutionPipe str graph) solutionsStr :: IO [IO Bool]
let whichValidTups = zip whichValid (map return [0..])
invalidTups <- filterM trueFst whichValidTups
invalid <- mapM snd invalidTups :: IO [Int]
-- putStrLn "[Begin failures]"
-- (putStrLn . show) invalid
-- putStrLn "[End failures]"
let allGood = null invalid
return $ allGood && finished (lines solutionFile)
where
trueFst x0 = do
first <- fst x0
return $ not first
finished list = last list == "FINISHED."
handler :: SomeException -> IO String
handler _ = error "The results have disappeared under my nose."
-- | This is the cycleGraph $C_n$, composed of a single undirected cycle
cycleGraph :: Int -> [[Int]]
cycleGraph n = sort2 $ [0,n-1] : [[i-1, i] | i <- [1..n-1]]
-- | This function returns the complete graph with 'n' vertices
completeGraph :: Int -> [[Int]] --Integral a => a -> [[a]]
completeGraph n = sort2 [[a,b] | a <- [0..n-1], b <- [0..n-1], a<b]
-- | This function returns the number of undirected cycles in (completeGraph n)
-- The formula is divided by 'k' because with cycles of size k, there are k orientation of each cycle.
-- cycles size k require three choices: n possibilities, n-1, n-2 etc.
-- Sum[Product[(i - k + n)/2 k, {i, 1, k}], {k, 3, n}] (Undirected cycles, '/2' removed for directed cycles)
completeGraphNumCy :: Int -> Int --Integral a => a -> a
completeGraphNumCy n = if good then sum [div (product [i - k + n | i <- [1..k]]) k | k <- [3..n]] else 10^12
where
good = n < 20
-- | This function returns the shuttle graph of size n, which looks like <|=|=|=|>
-- The following shows how the formula was derived:
-- 3->1,4
-- 4->2,3
-- 5->3,6
-- 6->4,5
-- n->n - 2, n - 1 + 2 * (mod n 2)
-- The shuttle graph is good for debugging because of the following property:
-- There are (n+1) cycles that are a cap or middle square (units)
-- There are (n+0) cycles that are an adjacent pair of units
-- There are (n-1) cycles that are an adjacent triple of units
-- etc.
-- Because of this property, this graph has exactly (2 + 3 n + n^2)/2 cycles (equal to TriangularNumber(n+1)).
-- This graph has 8 + 3*n edges
shuttleGraph :: Int -> [[Int]] --Integral a => a -> [[a]]
shuttleGraph n = sort2 $ [0,1] : [0,2] : [1,2] : [2*n-1, 2*n+1] : [2*n, 2*n+1] : [[m, m - 2] | m <- [3..2*n]] ++ [[m, m+1] | m <- [3,5..2*n-1]]
-- | Returns the number of undirected cycles in (shuttleGraph n)
shuttleGraphNumCy :: Int -> Int --Integral a => a -> a
shuttleGraphNumCy n = 2 + 3*n + n^2 -- modified from div (2 + 3*n + n^2) 2, because undirected, not directed cycles found
-- | This function returns the wheel graph of size n
-- Constructed by making the spokes from '0', adding all but one of the outer cycle, then adding the final edge
-- This graph has 2*(n+1) edges
wheelGraph :: Int -> [[Int]] --Integral a => a -> [[a]]
wheelGraph n = sort2 $ [[0, i] | i <- [1..(n-1)]] ++ [[j, j+1] | j <- [1..(n-2)]] ++ [[1, n-1]]
-- | For the wheel graph, starting with n == 4 (by mathematica's definition, isomorphic to K4),
-- The nth graph is (n-1) triangles joined at a common central vertex and each joined to the
-- next in a wheel. The number of cycles may be found as follows:
-- ( 1 ) There are (n-1) 1-triangle cycles
-- ( 2 ) There are (n-1) 2-triangle cycles
-- ( . ) ...
-- (n-2) There are (n-1) (n-2)-triangle cycles
-- With the addition of the single cycle of all the triangles, this gives that there is a total
-- of (n-1)*(n-2) + 1 cycles
wheelGraphNumCy :: Int -> Int --Integral a => a -> a
wheelGraphNumCy n = 2*((n - 1)*(n - 2) + 1) -- 2*\x added because undirected, not directed cycles are found
-- | This function resizes an input for "sane" use in testing, based on facts about the graph given
resizeN :: Int -> Int -> Int
resizeN n whichGraph = bringDown $ bringUpToMin (abs n)
where
bringDown x = if lessThanMax x then x else 4 + mod x 5 -- this gives a range of [4..8]
bringUpToMin x = if x < minsize then minsize else x
lessThanMax x = (maxNumCyForTest >= numCy x) && (maxNumEdgesForTest >= numEd x)
minsize = [3, 3, 4, 4] !! whichGraph
graph = [cycleGraph, completeGraph, shuttleGraph, wheelGraph] !! whichGraph
numCy = [const 2, completeGraphNumCy, shuttleGraphNumCy, wheelGraphNumCy] !! whichGraph
numEd = [id, \m ->div (n*(n-1)) 2, \m ->8 + 3*m, \m ->2*(m+1)] !! whichGraph
-- | Taken from <http://stackoverflow.com/questions/16108714/haskell-removing-duplicates-from-a-list>
rmdups :: (Ord a) => [a] -> [a]
rmdups = map head . group . sort
-- | This function takes a list and the two first elements (if they exist) from 'swaps' and swaps the elements at those indices, or those indices mod (the length of the list)
listSwap :: [Int] -> [Int] -> [Int]
listSwap list swaps = if (length list < 1) || (length swaps < 2) then list else map switch list
where
switch x
| x == a1 = b1
| x == b1 = a1
| otherwise = x
len = length list
a0 = head swaps
b0 = swaps !! 1
a1 = rerange a0
b1 = rerange a1
rerange x = mod (x-1) len + 1 -- this moves x into the range [1..len]
-- | This tests that 'listSwap' is its own inverse for lists without duplicates
prop_listSwapReversible :: [Int] -> [Int] -> Property
prop_listSwapReversible inlist seeds = property ( listSwap (listSwap list (take 2 seeds)) (reverse (take 2 seeds)) == list )
where
list = rmdups inlist
-- | This function performs 'listSwap' on the list using the first two (if they exist) elements of 'seeds', removes the first element of 'seeds' and repeats.
-- Thus, it can take a list of seeds to permute the list in any fashion (as any permutation is the composition of some list of transpositions)
permuteList :: [Int] -> [Int] -> [Int]
permuteList list seeds
| (length list < 1) || (length seeds < 2) = list
| otherwise = permuteList (listSwap list (take 2 seeds)) (tail seeds)
-- | This function uses a list of seeds to shuffle the vertex labels (indices) in a graph
shuffleGraph :: [[Int]] -> [Int] -> [[Int]]
shuffleGraph graph seeds = map (map (\v ->permuted !! v)) graph
where
permuted = permuteList [0..(maximum $ map maximum graph)] seeds
-- | This is a general monadic tester for the 'graphToNumCycles' function, using a known result for the number of cycles
--testNumCyShuffled :: [[Int]] -> Int -> [Int] -> Property
testNumCyShuffled graph result seeds = monadicIO $ do
-- run $ putStrLn $ "graph: " ++ show graph ++ "; seeds: " ++ show seeds
resultFromC <- run $ graphToNumCycles graph False
let resultKnown = result
assert (resultFromC == resultKnown)
-- | This property takes a graph and a known result for the number of undirected cycles to test 'graphToNumCycles'
testNumCy :: [[Int]] -> Int -> Property
testNumCy graph result = monadicIO $ do
resultFromC <- run $ graphToNumCycles graph False
-- resultKnown <- return result
assert (resultFromC == result)
-- | This property checks that a cycle graph of any valid size has two (directed) cycles
prop_goodCycleGraphNumCy :: Int -> Property
prop_goodCycleGraphNumCy n = testNumCy graph 2
where
graph = cycleGraph nGood
nGood = resizeN n 0
-- | This property check that a cycle graph of any valid size and permutation of vertex labels has two (directed) cycles
prop_goodCycleGraphNumCyShuffled :: Int -> [Int] -> Property
prop_goodCycleGraphNumCyShuffled n = testNumCyShuffled graph 2
where
graph = cycleGraph nGood
nGood = resizeN n 0
-- | This function returns a complete graph with resized input
goodCompleteGraph :: Int -> [[Int]]
goodCompleteGraph n = completeGraph $ resizeN n 1
-- | This property performs as 'prop_goodCycleGraphNumCy', except for complete graphs
prop_goodCompleteGraphNumCy :: Int -> Property
prop_goodCompleteGraphNumCy n = testNumCy (goodCompleteGraph n) result
where
result = completeGraphNumCy nGood
nGood = resizeN n 1
-- | This property performs as 'prop_goodCycleGraphNumCyShuffled', except for complete graphs
prop_goodCompleteGraphNumCyShuffled :: Int -> [Int] -> Property
prop_goodCompleteGraphNumCyShuffled n = testNumCyShuffled (goodCompleteGraph n) result
where
result = completeGraphNumCy nGood
nGood = resizeN n 1
-- | This property performs as 'prop_goodCycleGraphNumCy', except for shuttle graphs
prop_goodShuttleGraphNumCy :: Int -> Property
prop_goodShuttleGraphNumCy n = testNumCy (shuttleGraph nGood) result
where
result = shuttleGraphNumCy nGood
nGood = resizeN n 2
-- | This property performs as 'prop_goodCycleGraphNumCyShuffled', except for shuttle graphs
prop_goodShuttleGraphNumCyShuffled :: Int -> [Int] -> Property
prop_goodShuttleGraphNumCyShuffled n = testNumCyShuffled graph result
where
graph = shuttleGraph nGood
result = shuttleGraphNumCy nGood
nGood = resizeN n 2
-- | This property performs as 'prop_goodCycleGraphNumCy', except for wheel graphs
prop_goodWheelGraphNumCy :: Int -> Property
prop_goodWheelGraphNumCy n = testNumCy (wheelGraph nGood) result
where
result = wheelGraphNumCy nGood
nGood = resizeN n 3
-- | This property performs as 'prop_goodCycleGraphNumCyShuffled', except for wheel graphs
prop_goodWheelGraphNumCyShuffled :: Int -> [Int] -> Property
prop_goodWheelGraphNumCyShuffled n = testNumCyShuffled graph result
where
graph = wheelGraph nGood
result = wheelGraphNumCy nGood
nGood = resizeN n 3
-- | This function allows one to randomly trim a list of any size, given an arbitrary seed (here called 'moddedsize')
trimByLenMod :: [a] -> Int -> [a]
trimByLenMod list moddedsize = take thisMany list
where
thisMany = if len > 0 then mod (abs moddedsize) len + 1 else 0
len = length list
-- | This is the non-property form of 'testMaxCy'
testMaxCy' :: [[Int]] -> Int -> Int -> IO Bool
testMaxCy' graph splitbits seed = do
graphToMaxcyCode graph splitbits foldername "maxcy_testing"
compileAllInDir foldername
runAllInDir foldername
files <- getDirectoryContents foldername :: IO [FilePath]
let txtFile file = (last file == 't') && (last (init file) == 'x') && (last (init $ init file) == 't') && (last (init $ init $ init file) == '.')
text_files_untrimmed <- return $ filter txtFile files :: IO [FilePath]
let text_files = trimByLenMod text_files_untrimmed seed
checked <- mapM checkMaxCySolution text_files :: IO [Bool]
let checkedTups = zip (map return checked) (map return [0..])
invalidTups <- filterM trueFst checkedTups
invalid <- mapM snd invalidTups :: IO [Int]
-- putStrLn "[Begin failures]"
-- (putStrLn . show) invalid
-- putStrLn "[End failures]"
let allGood = null invalid
when allGood (removeDirIfExists foldername)
return allGood
where
trueFst x0 = do
first <- fst x0
return $ not first
foldername = "testMaxCy"
-- | This is a general monadic tester for the 'graphToMaxCyCode' function, using 'graphToNumCycles' to check a random subset of its results
testMaxCy :: [[Int]] -> Int -> Int -> Property
testMaxCy graph splitbits seed = monadicIO $ run $ testMaxCy' graph splitbits seed
-- | This value should be kept small; it will generate 2^maxsplitbits MaxCy code pieces,
-- each of which will generate an exponential (by back of a napkin calculation) number of possible solutions,
-- each of which will be checked by 'graphToNumCycles'.
maxsplitbits = 5 + 1 :: Int
-- | This property checks the 'graphToMaxcyCode' function for complete graphs of reasonable and valid size
prop_goodCompleteGraphMaxCy :: Int -> Int -> Int -> Property
prop_goodCompleteGraphMaxCy n splitbits = testMaxCy graph splitbitsGood
where
graph = completeGraph nGood
splitbitsGood = if (abs splitbits >= 0) && (abs splitbits < maxsplitbits) then abs splitbits else 0
nGood = resizeN n 1
-- | This property checks the 'graphToMaxcyCode' function for shuttle graphs of reasonable and valid size
prop_goodShuttleGraphMaxCy :: Int -> Int -> Int -> Property
prop_goodShuttleGraphMaxCy n splitbits = testMaxCy graph splitbitsGood
where
graph = shuttleGraph nGood
splitbitsGood = if (abs splitbits >= 0) && (abs splitbits < maxsplitbits) then abs splitbits else 0
nGood = resizeN n 2
-- | This property checks the 'graphToMaxcyCode' function for wheel graphs of reasonable and valid size
prop_goodWheelGraphMaxCy :: Int -> Int -> Int -> Property
prop_goodWheelGraphMaxCy n splitbits = testMaxCy graph splitbitsGood
where
graph = wheelGraph nGood
splitbitsGood = if (abs splitbits >= 0) && (abs splitbits < maxsplitbits) then abs splitbits else 0
nGood = resizeN n 3
makeMaxcyForAll :: [(String,[[Int]])] -> IO ()
makeMaxcyForAll listofgraphs = do
let tupList = filter (\x ->length (snd x) > 31) $ enum strippedList -- strippedList
mapM_ makeCode tupList
putStrLn "Done."
where
strippedList = map snd listofgraphs
-- goodlist = filter (\l ->length l > 31) strippedList
makeCode :: (Int, [[Int]]) -> IO String
makeCode graphTup = do
print graphNum
graphToMaxcyCode graph splitbits foldername filename
where
graphNum = fst graphTup
graph = snd graphTup
splitbits = if length graph > 31 then length graph - 31 else 0 -- 31 is size of largest "managable" maxcy c program (by experiment)
foldername = "graphNum_" ++ show (length graph) ++ "_" ++ show graphNum
filename = foldername
-- | Checks all properties with HSpec
main' :: IO ()
main' = hspec $ do
describe "splitAt" $ do
context "when used with arbitrary chars/strings" $ do
it "is is invertible" $ property $
prop_splitAtInvertible
describe "collectBy" $ do
context "when used with arbitrary inputs" $ do
it "is invertible" $ property $
prop_splitAtInvertible
describe "readInt" $ do
context "when used with a show Int" $ do
it "returns the Int" $ property $
prop_readInt
describe "readIntList" $ do
context "when used with a show [Int]" $ do
it "returns the [Int]" $ property $
prop_readIntList
describe "listSwap" $ do
context "when used with a pairs of [Int]'s" $ do
it "is its own inverse" $ property $
prop_listSwapReversible
describe "graphToNumCycles" $ do
context "when used with a simple cycle" $ do
it "has 2 cycles" $ property $
prop_goodCycleGraphNumCy
context "when used with a simple cycle (shuffled)" $ do
it "has 2 cycles" $ property $
prop_goodCycleGraphNumCyShuffled
context "when used with complete graphs" $ do
it "has Sum[Product[(i - k + n)/k, {i, 1, k}], {k, 3, n}] cycles" $ property $
prop_goodCompleteGraphNumCy
context "when used with complete graphs (shuffled)" $ do
it "has Sum[Product[(i - k + n)/k, {i, 1, k}], {k, 3, n}] cycles" $ property $
prop_goodCompleteGraphNumCyShuffled
context "when used with shuttle graphs" $ do
it "has (2 + 3*n + n^2) cycles" $ property $
prop_goodShuttleGraphNumCy
context "when used with shuttle graphs (shuffled)" $ do
it "has (2 + 3*n + n^2) cycles" $ property $
prop_goodShuttleGraphNumCyShuffled
context "when used with wheel graphs" $ do
it "has 2*((n-1)*(n-2) + 1) cycles" $ property $
prop_goodWheelGraphNumCy
context "when used with wheel graphs (shuffled)" $ do
it "has 2*((n-1)*(n-2) + 1) cycles" $ property $
prop_goodWheelGraphNumCyShuffled
describe "graphToMaxCyCode" $ do
context "when used with complete graphs" $ do
it "agrees in its solutions with graphToNumCycles" $ property $
prop_goodCompleteGraphMaxCy
context "when used with shuttle graphs" $ do
it "agrees in its solutions with graphToNumCycles" $ property $
prop_goodShuttleGraphMaxCy
context "when used with wheel graphs" $ do
it "agrees in its solutions with graphToNumCycles" $ property $
prop_goodWheelGraphMaxCy
prop_splitAtInvertible :: Char -> String -> Property
prop_splitAtInvertible c str = property $ (joined == filtered) || (length filtered < 1)
where
split = Cycles.Reap.splitAt c str
joined = concat split
filtered = filter (/= c) str
prop_collectByInvertible f list = property $ sorted == remade
where
sorted = sort list
collected = collectBy f list
trues = fst collected
falses = snd collected
remade = sort $ trues ++ falses
prop_collectByCollectsAll f list = property $ goodTrues && goodFalses
where
collected = collectBy f list
trues = fst collected
goodTrues = null [x | x <- trues, not (f x)]
falses = snd collected
goodFalses = null [x | x <- falses, f x]
main'' = hspec $ do
describe "splitAt" $ do
context "when used with arbitrary chars/strings" $ do
it "is is invertible" $ property $
prop_splitAtInvertible
describe "collectBy" $ do
context "when used with arbitrary inputs" $ do
it "is invertible" $ property $
prop_splitAtInvertible
-- describe "collectBy (2)" $ do
-- context "when used as above" $ do
-- it "collects everything" $ property $
-- prop_collectByCollectsAll
main :: IO ()
main = main'
-- main''
-- reapAllResults "." "allout.txt"
--mainDone <- main'
--makeMaxcyForAll gList
-- trimAllResults "."
-- trimResult "graphNum_33_1075_2_4_out.txt"
-- 33+
| michaeljklein/HCy2C | Main.hs | mit | 22,161 | 0 | 17 | 4,562 | 4,872 | 2,525 | 2,347 | 302 | 3 |
fib 0 = 0
fib 1 = 0
fib 2 = 1
fib n = fib (n - 1) + fib (n - 2)
| ariedov/AwesomeHaskellApp | fib.hs | mit | 64 | 0 | 8 | 24 | 57 | 28 | 29 | 4 | 1 |
data Tree a = Empty | Node (Tree a) a (Tree a)
find :: Ord a => Tree a -> a -> Bool
find Empty _ = False
find (Node lhs val rhs) needle
| val == needle = True
| val > needle = find lhs needle
| val < needle = find rhs needle
insert :: Ord a => Tree a -> a -> Tree a
insert Empty item = (Node Empty item Empty)
insert (Node lhs val rhs) item
| val == item = (Node lhs val rhs) -- Already in tree
| val > item = (Node (insert lhs item) val rhs)
| val < item = (Node lhs val (insert rhs item))
toList :: Ord a => Tree a -> [a]
toList Empty = []
toList (Node lhs val rhs) = (toList lhs) ++ [val] ++ (toList rhs)
toString :: Show a => Tree a -> [Char]
toString Empty = ""
toString (Node lhs val rhs) = "(" ++ toString lhs ++ " " ++ show val ++ " " ++ toString rhs ++ ")"
| WesleyAC/toybox | functional/tree.hs | mit | 794 | 0 | 11 | 208 | 432 | 210 | 222 | 19 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-
The time-machine app transformer
-}
module Blaze.React.Examples.TimeMachine
( withTimeMachine
) where
import Blaze.React
import Control.Applicative
import Control.Lens (makeLenses, view, (.=), (%=), use, (+=))
import Control.Monad
import Control.Monad.Trans.Writer (tell)
import Data.List (foldl')
import Data.Typeable (Typeable)
import Prelude hiding (div)
import qualified Text.Blaze.Event as E
import qualified Text.Blaze.Html5 as H
import qualified Text.Blaze.Html5.Attributes as A
import Text.Show.Pretty (ppShow)
-------------------------------------------------------------------------------
-- Time Machine
-------------------------------------------------------------------------------
-- state
--------
data TMState state action = TMState
{ _tmsInternalState :: !state
, _tmsActionHistory :: [WithWindowActions action]
-- ^ List of actions, from earliest to latest
, _tmsActiveAction :: !Int
-- ^ Index of the current position in the action list. 1-indexed,
-- where 0 indicates that the app is in the initial state.
, _tmsPaused :: !Bool
, _tmsActionBuffer :: [WithWindowActions action]
-- ^ This is where async internal actions go while the app is paused
} deriving (Show)
makeLenses ''TMState
-- state transitions
--------------------
type TMAction action = WithWindowActions (TMAction' action)
data TMAction' action
= TogglePauseAppA
| ClearAppHistoryA
| RevertAppHistoryA Int
| InternalA (WithWindowActions action)
| AsyncInternalA (WithWindowActions action)
deriving (Eq, Ord, Read, Show, Typeable)
applyTMAction
:: forall s a.
s
-> (WithWindowActions a -> Transition s (WithWindowActions a))
-> TMAction a
-> Transition (TMState s a) (TMAction a)
applyTMAction initialInternalState applyInternalAction action =
runTransitionM $ case action of
PathChangedTo path -> do
paused <- use tmsPaused
unless paused $ applyInternalAction' $ PathChangedTo path
AppAction TogglePauseAppA -> do
paused <- use tmsPaused
when paused flushActionBuffer
tmsPaused %= not
AppAction ClearAppHistoryA -> do
tmsActionHistory .= []
tmsInternalState .= initialInternalState
tmsActiveAction .= 0
AppAction (RevertAppHistoryA idx) -> do
history' <- take idx <$> use tmsActionHistory
let internalState' = foldl' (\st act -> fst $ applyInternalAction act st)
initialInternalState history'
tmsInternalState .= internalState'
tmsActiveAction .= idx
AppAction (AsyncInternalA action') -> do
paused <- use tmsPaused
if paused
then tmsActionBuffer %= (++ [action'])
else applyInternalAction' action'
AppAction (InternalA action') -> do
paused <- use tmsPaused
unless paused $ applyInternalAction' action'
where
flushActionBuffer :: TransitionM (TMState s a) (TMAction a)
flushActionBuffer = do
buffer <- use tmsActionBuffer
sequence_ $ map applyInternalAction' buffer
tmsActionBuffer .= []
-- | Apply an internal action to the internal state, adding it to the
-- history, bumping the active action pointer, and possibly truncating
-- the history first.
applyInternalAction'
:: WithWindowActions a
-> TransitionM (TMState s a) (TMAction a)
applyInternalAction' act = do
history <- use tmsActionHistory
activeAction <- use tmsActiveAction
tmsActionHistory .= take activeAction history ++ [act]
(internalState', (reqs, _shouldUpdate)) <- applyInternalAction act <$> use tmsInternalState
tmsInternalState .= internalState'
tell $ fmap (AppAction . AsyncInternalA) <$> reqs
tmsActiveAction += 1
-- rendering
------------
renderTMState
:: (Show a, Show s)
=> (s -> WindowState (WithWindowActions a))
-> TMState s a
-> WindowState (TMAction a)
renderTMState renderInternalState state =
let (WindowState internalBody internalPath) =
renderInternalState (view tmsInternalState state)
in WindowState
{ _wsPath = internalPath
, _wsBody = renderBody internalBody state
}
renderBody
:: (Show a, Show s)
=> H.Html (WithWindowActions a)
-> TMState s a
-> H.Html (TMAction a)
renderBody internalBody state = do
H.div H.! A.class_ "tm-time-machine" $ do
H.h1 "Time machine"
H.span H.! A.class_ "tm-button" H.! E.onClick' (AppAction TogglePauseAppA) $
if (_tmsPaused state) then "Resume app" else "Pause app"
H.span H.! A.class_ "tm-button" H.! E.onClick' (AppAction ClearAppHistoryA) $
"Clear history"
renderHistoryBrowser
renderAppStateBrowser
H.div H.! A.class_ "tm-internal-app" $
E.mapActions (AppAction . InternalA) $ internalBody
where
actionsWithIndices :: [(Int, String)]
actionsWithIndices = reverse $
(0, "Initial state") : (zip [1..] $ map show $ _tmsActionHistory state)
renderHistoryBrowser = do
H.h2 "Events"
H.div H.! A.class_ "tm-history-browser" $ do
H.ol $ forM_ actionsWithIndices $ \(idx, action) ->
H.li H.! A.value (H.toValue $ idx + 1)
H.! E.onMouseEnter (\_ -> AppAction $ RevertAppHistoryA idx)
H.!? (idx == view tmsActiveAction state, A.class_ "tm-active-item")
$ H.toHtml action
renderAppStateBrowser = do
H.h2 "Application state"
H.div H.! A.class_ "tm-app-state-browser" $ H.pre $
H.toHtml $ ppShow $ view tmsInternalState state
-- the application transformer
------------------------------
withTimeMachine
:: (Show a, Show s)
=> App s (WithWindowActions a)
-> App (TMState s a) (TMAction a)
withTimeMachine innerApp = App
{ appInitialState = initialTMState initialInnerState
, appInitialRequests = fmap (AppAction . AsyncInternalA) <$> initialInnerReqs
, appApplyAction = applyTMAction initialInnerState applyInnerAction
, appRender = renderTMState renderInner
}
where
App initialInnerState initialInnerReqs applyInnerAction renderInner = innerApp
initialTMState :: s -> TMState s a
initialTMState internalState = TMState
{ _tmsInternalState = internalState
, _tmsActionHistory = []
, _tmsActiveAction = 0 -- 0 indicates the initial state.
, _tmsPaused = False
, _tmsActionBuffer = []
}
| LumiGuide/blaze-react | src/Blaze/React/Examples/TimeMachine.hs | mit | 6,825 | 0 | 22 | 1,723 | 1,661 | 857 | 804 | 149 | 7 |
module Cook.Util where
import Cook.Types
import Control.Monad
import Control.Monad.Trans
import Control.Retry
import System.Exit
import System.IO
import System.Log.Formatter
import System.Log.Handler hiding (setLevel)
import System.Log.Handler.Simple
import System.Log.Logger
import System.Process (system, rawSystem, readProcessWithExitCode)
import qualified Crypto.Hash.SHA1 as SHA1
import qualified Data.ByteString as BS
quickHash :: [BS.ByteString] -> SHA1
quickHash bsList =
SHA1 $ SHA1.finalize (SHA1.updates SHA1.init bsList)
concatHash :: [SHA1] -> SHA1
concatHash sha1List = quickHash $ map unSha1 sha1List
initLoggingFramework :: Priority -> IO ()
initLoggingFramework prio =
do myStreamHandler <- streamHandler stdout prio
let myStreamHandler' = setFormatter myStreamHandler (simpleLogFormatter "[$prio $time $loggername] $msg")
root <- getRootLogger
saveGlobalLogger (setLevel DEBUG $ setHandlers [myStreamHandler'] root)
logInfo :: MonadIO m => String -> m ()
logInfo = liftIO . infoM "cook"
logDebug :: MonadIO m => String -> m ()
logDebug = liftIO . debugM "cook"
logWarn :: MonadIO m => String -> m ()
logWarn = liftIO . warningM "cook"
logError :: MonadIO m => String -> m ()
logError = liftIO . errorM "cook"
readProcessWithExitCode' :: String -> [String] -> String -> IO (ExitCode, String, String)
readProcessWithExitCode' cmd args procIn =
do logDebug ("$ " ++ cmd ++ " " ++ unwords args)
readProcessWithExitCode cmd args procIn
systemStream :: Maybe FilePath -> String -> (BS.ByteString -> IO ()) -> IO ExitCode
systemStream mDir cmd _onOutput =
let realCmd =
case mDir of
Just dir -> "(cd " ++ dir ++ "; " ++ cmd ++ ")"
Nothing -> cmd
in do logDebug ("$ " ++ realCmd)
system realCmd
compressFilesInDir :: Bool -> FilePath -> FilePath -> [FilePath] -> IO ()
compressFilesInDir shouldRetry tarName dirFp files =
do ecTar <-
retrying (constantDelay microsec <> limitRetries 5) checkRetry sysAction
unless (ecTar == ExitSuccess) $
fail ("Error creating tar:\n" ++ tarCmd ++ " " ++ unwords tarArgs)
where
microsec =
12 * 1000 * 1000
checkRetry _ ec =
return (shouldRetry && ec /= ExitSuccess)
sysAction _ =
rawSystem tarCmd tarArgs
tarCmd =
"/usr/bin/env"
tarArgs =
["tar", "cjf", tarName, "-C", dirFp] ++ files
| factisresearch/dockercook | src/lib/Cook/Util.hs | mit | 2,456 | 0 | 15 | 555 | 771 | 396 | 375 | 61 | 2 |
--import Data.List
--import Data.Maybe
--import Data.Set as S
--import Data.List.Split
--pentagon :: Int -> Int
pentagon n = (n * (3*n-1)) `div` 2
triangle n = (n * (n+1)) `div` 2
hexagonal n = n * (2*n-1)
pentagon_pos 1 = 1
pentagon_pos pn = (1 + sqrt (1 + 24 * pn)) / 6
trianglePos tn = (-1 + sqrt (1 + 8*tn))/2
hexagonalPos hn = ( 1 + sqrt (1 + 8*hn) ) / 4
--penta_series = [(n * (3*n-1)) `div` 2 | n <- [1..5000]]
is_int n = (fromIntegral $ truncate n) == n
is_pentagon = is_int . pentagon_pos
is_triangle = is_int . trianglePos
is_hexagon = is_int . hexagonalPos
ans = head $ [x | x <- map triangle [1..], is_pentagon x, is_hexagon x] | stefan-j/ProjectEuler | q44.hs | mit | 676 | 0 | 11 | 162 | 290 | 155 | 135 | 12 | 1 |
-- | Various types for the Checkpage utility.
module Checkpage.Types (
Config (..)
, Comparison (..)
, URL
, HTML
) where
import Data.ByteString (ByteString)
-- | Program configuration.
data Config = Config {
loginURL :: Maybe String
-- ^ URL of the page to log in with, if any.
, configFile :: Maybe String
-- ^ Path to a file with login configuration.
}
-- | Data type representing possibilies when comparing two pages.
data Comparison = Unchanged
| Changed {deltas :: [(ByteString, ByteString)]}
deriving (Read, Show, Eq)
-- | Convenience types
type URL = String
type HTML = ByteString
| nathyong/checkpage | src/Checkpage/Types.hs | mit | 673 | 0 | 10 | 185 | 125 | 79 | 46 | 14 | 0 |
-- Problems/Problem023Spec.hs
module Problems.Problem023Spec (main, spec) where
import Test.Hspec
import Problems.Problem023
main :: IO()
main = hspec spec
spec :: Spec
spec = describe "Problem 23" $
it "Should evaluate to 4179871" $
p23 `shouldBe` 4179871
| Sgoettschkes/learning | haskell/ProjectEuler/tests/Problems/Problem023Spec.hs | mit | 272 | 0 | 8 | 51 | 73 | 41 | 32 | 9 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
module Yesod.Auth.OAuth2.Exception
( YesodOAuth2Exception(..)
) where
import Control.Exception.Safe
import Data.ByteString.Lazy (ByteString)
import Data.Text (Text)
data YesodOAuth2Exception
= OAuth2Error Text ByteString
-- ^ HTTP error during OAuth2 handshake
--
-- Plugin name and JSON-encoded @OAuth2Error@ from @hoauth2@.
--
| JSONDecodingError Text String
-- ^ User profile was not as expected
--
-- Plugin name and Aeson parse error message.
--
| GenericError Text String
-- ^ Other error conditions
--
-- Plugin name and error message.
--
deriving (Show, Typeable)
instance Exception YesodOAuth2Exception
| thoughtbot/yesod-auth-oauth2 | src/Yesod/Auth/OAuth2/Exception.hs | mit | 724 | 0 | 6 | 162 | 100 | 65 | 35 | 12 | 0 |
-- |
-- Copyright : (c) 2013-2014 Sam Truzjan
-- License : MIT
-- Maintainer : pxqr.sta@gmail.com
-- Stability : expermental
-- Portability : portable
--
-- Basic backward raytracer.
--
{-# LANGUAGE RecordWildCards #-}
module Graphics.Tracy.Render
( -- * Environment
Samples
, randomNormals
, vacuumIx
, Env (..)
-- * Raytracer
, View(..)
, tracePixel
) where
import Control.Applicative
import Control.Monad
import Control.Monad.Reader
import Data.List as L
import System.Random
import Graphics.Tracy.Color
import Graphics.Tracy.Light
import Graphics.Tracy.Material
import Graphics.Tracy.Object
import Graphics.Tracy.Scene
import Graphics.Tracy.V3
{-----------------------------------------------------------------------
-- Viewport
-----------------------------------------------------------------------}
data View = View
{ width :: Int
, height :: Int
, focus :: Double
}
-- | the first ray we shoot from the eye into the scene
primaryRay :: View -> Int -> Int -> Ray
primaryRay (View w h f) x y = ray orig (normalize dir)
where
orig = V3 0 0 f
dir = V3 ((fromIntegral $ x - div w 2) / fromIntegral s)
((fromIntegral $ div h 2 - y) / fromIntegral s)
(negate f)
s = max w h
{-----------------------------------------------------------------------
-- Env map
-----------------------------------------------------------------------}
type Samples = [V3]
randomNormals :: Int -> IO Samples
randomNormals n = replicateM (n * 3) (normalize <$> randomV3)
where
randomV3 = liftM3 V3 f f f
f = (\x -> 2 * x - 1) <$> randomIO
shrink :: Samples -> Samples
shrink s = take newCount s
where
newCount = floor $ sqrt $ ((fromIntegral (L.length s)) :: Double)
-- | Skip computing ray with dot product less that threshold
skipThreshold :: Double
skipThreshold = 0.2
{-----------------------------------------------------------------------
-- Environment
-----------------------------------------------------------------------}
type Hops = Int
-- TODO current index autodetection
data Env = Env
{ curIndex :: !RefractiveIndex
, indirectLimit :: !Hops
, curSamples :: !Samples
, envScene :: !Scene
}
nextIndirect :: Env -> Env
nextIndirect e = e
{ indirectLimit = pred (indirectLimit e)
}
type Render = Reader Env
nextHop :: Render Color -> Render Color
nextHop action = do
n <- asks indirectLimit
if n == 0
then asks (ambientColor . envScene)
else local nextIndirect action
withBackgroundColor :: Color -> Render a -> Render a
withBackgroundColor clr = local (\ e -> e {envScene = setBgColor clr (envScene e)})
where
setBgColor c s = s { backgroundColor = c }
-- | Set refractive index.
withCurrentIndex :: RefractiveIndex -> Render a -> Render a
withCurrentIndex ix = local (\ e -> e { curIndex = ix })
getCurrentIndex :: Render RefractiveIndex
getCurrentIndex = asks curIndex
-- | Intersect a ray with all scene objects.
getIntersections :: Ray -> Render [Intersection Object]
getIntersections r = asks (sortedIntersections r . objects . envScene)
-- | Throw a bunch of rays from the given patch. Used for Monte-Carlo methods.
emitRays :: Patch -> Render [Ray]
emitRays (pos, normal) = do
samples <- asks curSamples
return $ [ ray (pos + (eps .* normal)) sample
| sample <- samples
, (sample .*. normal) > skipThreshold]
where
eps = 0.001
reflectedRay :: Ray -> Patch -> Ray
reflectedRay Ray {..} (pos, normal) = ray (pos + (0.001 .* normal)) refl
where
refl = reflectionNorm normal direction
--refractedRay :: Ray -> Patch -> RefractiveIndex -> Render (Maybe Ray)
refractedRay Ray {..} (pos, normal) n2 = do
n1 <- getCurrentIndex
let eta = n2 / n1 -- FIXME
c1 = - (direction .*. normal)
cs2 = 1.0 - eta * eta * (1.0 - c1 * c1)
tdir = eta .* direction + (eta * c1 - sqrt cs2) .* normal
return $ if cs2 < 0 then Nothing else Just $ ray (pos - normal) (-normal)
{-----------------------------------------------------------------------
-- Components
-----------------------------------------------------------------------}
-- TODO transparency: compute distance of ray in object
ambient :: Material -> Render Color
ambient Material {..} = do
scene <- asks envScene
return $ Color (ambientK .* clr (ambientColor scene))
-- | Find direction and intensity of point light source in patch.
lightFlow :: Light -> Patch -> Maybe (Direction, V3)
lightFlow (Light intensity sourcePos lightDiffuse) (target, normal)
| cosA > 0 = Just (lightDir, (intensity * recDist * cosA) .* clr lightDiffuse)
| otherwise = Nothing
where
lightDir = normalize (sourcePos - target)
cosA = lightDir .*. normal
recDist = 1 / distance sourcePos target
directLight :: Ray -> Patch -> Light -> Render Color
directLight r patch @ (pos, _) source
| Just (dir, flow) <- lightFlow source patch = do
xs <- getIntersections (ray pos dir) -- TODO negate direction?
{- FIXME blend color of object with light source color -}
withBackgroundColor (Color flow) $ compose r xs
| otherwise = return black
diffuseColor :: Ray -> Patch -> Material -> Render Color
diffuseColor r patch Material {..} = do
sources <- asks (lightSources . envScene)
comps <- mapM (directLight r patch) sources
return $ Color $ diffuseK .* (clr diffuse * sum (L.map clr comps))
specularColor :: Ray -> Patch -> Material -> Render Color
specularColor = undefined
reflectionColor :: Ray -> Patch -> Material -> Render Color
reflectionColor r p Material {..} = do
Color color <- raytrace (reflectedRay r p)
return $ Color $ specularK .* degrees color shiness
where
degrees (V3 a b c) s = V3 (a ** s) (b ** s) (c ** s)
refractionColor :: Ray -> Patch -> Material -> Render Color
refractionColor r p m
| Just nbody <- refrIndex m = do
mray <- refractedRay r p nbody
case mray of
Nothing -> return gray
Just rr -> withCurrentIndex nbody $ raytrace rr
| otherwise = return gray
indirectLight :: Patch -> Material -> Render Color
indirectLight p Material {..} = do
rs <- emitRays p
cs <- mapM raytrace rs
let coeff = let n = L.length rs in if n == 0 then 0 else 1.0 / fromIntegral n
return $ Color $ (coeff * ambientK) .* sum (L.map clr cs)
{-----------------------------------------------------------------------
-- Raytracing
-----------------------------------------------------------------------}
shade :: Ray -> Patch -> Material -> Render Color
shade r p m = do
amb <- ambient m
ambI <- indirectLight p m
diff <- diffuseColor r p m
spec <- specularColor r p m
refl <- reflectionColor r p m
refr <- refractionColor r p m
{-
case transparent m of
Nothing -> return $ Color $ clr () + clr diff
Just alpha -> return $ Color $ clr (luminosity m) + clr refr
-}
return $ luminosity m + amb + ambI + diff + refl
compose :: Ray -> [Intersection Object] -> Render Color
compose _ [] = asks (backgroundColor . envScene)
compose r ((Object {..}, patch) : xs)
| Just alpha <- transparent mat
= do
c <- shade r patch mat
cs <- compose r xs
return $ blending alpha c cs
| otherwise = shade r patch mat
raytrace :: Ray -> Render Color
raytrace r = nextHop $ getIntersections r >>= compose r
type PixelIx = (Int, Int)
tracePixel :: Env -> View -> PixelIx -> Color
tracePixel env view (x, y) = runReader (raytrace (primaryRay view x y)) env
| pxqr/tracy | src/Graphics/Tracy/Render.hs | mit | 7,540 | 2 | 15 | 1,667 | 2,298 | 1,180 | 1,118 | 157 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-privateipadd.html
module Stratosphere.ResourceProperties.EC2LaunchTemplatePrivateIpAdd where
import Stratosphere.ResourceImports
-- | Full data type definition for EC2LaunchTemplatePrivateIpAdd. See
-- 'ec2LaunchTemplatePrivateIpAdd' for a more convenient constructor.
data EC2LaunchTemplatePrivateIpAdd =
EC2LaunchTemplatePrivateIpAdd
{ _eC2LaunchTemplatePrivateIpAddPrimary :: Maybe (Val Bool)
, _eC2LaunchTemplatePrivateIpAddPrivateIpAddress :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToJSON EC2LaunchTemplatePrivateIpAdd where
toJSON EC2LaunchTemplatePrivateIpAdd{..} =
object $
catMaybes
[ fmap (("Primary",) . toJSON) _eC2LaunchTemplatePrivateIpAddPrimary
, fmap (("PrivateIpAddress",) . toJSON) _eC2LaunchTemplatePrivateIpAddPrivateIpAddress
]
-- | Constructor for 'EC2LaunchTemplatePrivateIpAdd' containing required
-- fields as arguments.
ec2LaunchTemplatePrivateIpAdd
:: EC2LaunchTemplatePrivateIpAdd
ec2LaunchTemplatePrivateIpAdd =
EC2LaunchTemplatePrivateIpAdd
{ _eC2LaunchTemplatePrivateIpAddPrimary = Nothing
, _eC2LaunchTemplatePrivateIpAddPrivateIpAddress = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-privateipadd.html#cfn-ec2-launchtemplate-privateipadd-primary
ecltpiaPrimary :: Lens' EC2LaunchTemplatePrivateIpAdd (Maybe (Val Bool))
ecltpiaPrimary = lens _eC2LaunchTemplatePrivateIpAddPrimary (\s a -> s { _eC2LaunchTemplatePrivateIpAddPrimary = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-launchtemplate-privateipadd.html#cfn-ec2-launchtemplate-privateipadd-privateipaddress
ecltpiaPrivateIpAddress :: Lens' EC2LaunchTemplatePrivateIpAdd (Maybe (Val Text))
ecltpiaPrivateIpAddress = lens _eC2LaunchTemplatePrivateIpAddPrivateIpAddress (\s a -> s { _eC2LaunchTemplatePrivateIpAddPrivateIpAddress = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EC2LaunchTemplatePrivateIpAdd.hs | mit | 2,123 | 0 | 12 | 205 | 264 | 151 | 113 | 27 | 1 |
{-# LANGUAGE OverloadedStrings, NoMonomorphismRestriction, FlexibleContexts, ScopedTypeVariables, DeriveDataTypeable, DeriveFunctor, GADTs #-}
module EZCouch.ReadAction where
import Prelude ()
import ClassyPrelude.Conduit
import EZCouch.Action
import EZCouch.Entity
import EZCouch.Types
import EZCouch.Parsing
import EZCouch.View
import EZCouch.Logging
import EZCouch.Crash
import qualified EZCouch.Encoding as Encoding
import qualified Database.CouchDB.Conduit.View.Query as CC
import qualified System.Random as Random
import qualified EZCouch.Base62 as Base62
import qualified Network.HTTP.Conduit as HTTP
import qualified Network.HTTP.Types as HTTP
import Data.Aeson.Types
data KeysSelection k
= KeysSelectionAll
| KeysSelectionRange k k
| KeysSelectionRangeStart k
| KeysSelectionRangeEnd k
| KeysSelectionList [k]
deriving (Show, Eq)
readAction :: (MonadAction m, Entity a, ToJSON k)
=> View a k -- ^ View
-> KeysSelection k -- ^ Keys selection mode
-> Int -- ^ Skip
-> Maybe Int -- ^ Limit
-> Bool -- ^ Descending
-> Bool -- ^ Include docs
-> m Value -- ^ An unparsed response body JSON
readAction view mode skip limit desc includeDocs = do
result <- action path qps body
case result of
ResponseNotFound -> do
logLn 2 $ "View "
++ fromMaybe (crash "Unnamed view") (viewGeneratedName view)
++ " does not exist. Generating."
createOrUpdateView view
action path qps body >>= \r -> case r of
ResponseNotFound -> crash "readAction keeps getting a ResponseNotFound"
ResponseOk json -> return json
ResponseOk json -> return json
where
action = case mode of
KeysSelectionList {} -> postAction
_ -> getAction
path = viewPath view
qps = catMaybes [
includeDocsQP includeDocs,
startKeyQP view mode,
endKeyQP view mode,
descQP desc,
limitQP limit,
skipQP skip
]
body = case mode of
KeysSelectionList keys -> Encoding.keysBody keys
_ -> ""
startKeyQP _ (KeysSelectionRange start end) = Just $ CC.QPStartKey start
startKeyQP _ (KeysSelectionRangeStart start) = Just $ CC.QPStartKey start
startKeyQP _ (KeysSelectionList {}) = Nothing
startKeyQP view@ViewById _ = Just $ CC.QPStartKey $ viewDocType view ++ "-"
startKeyQP _ _ = Nothing
endKeyQP _ (KeysSelectionRange start end) = Just $ CC.QPEndKey end
endKeyQP _ (KeysSelectionRangeEnd end) = Just $ CC.QPEndKey end
endKeyQP _ (KeysSelectionList {}) = Nothing
endKeyQP view@ViewById _ = Just $ CC.QPEndKey $ viewDocType view ++ "."
endKeyQP _ _ = Nothing
limitQP limit = CC.QPLimit <$> limit
skipQP skip = if skip /= 0 then Just $ CC.QPSkip skip else Nothing
descQP desc = if desc then Just CC.QPDescending else Nothing
includeDocsQP True = Just CC.QPIncludeDocs
includeDocsQP False = Nothing
readKeys :: (MonadAction m, Entity a, ToJSON k, FromJSON k)
=> View a k -- ^ View
-> KeysSelection k -- ^ Keys selection mode
-> m [k]
readKeys view mode = fmap (map fst . filter snd) $ readKeysExist view mode
readCount :: (MonadAction m, Entity a, ToJSON k, FromJSON k)
=> View a k -- ^ View
-> KeysSelection k -- ^ Keys selection mode
-> m Int
readCount view mode = fmap length $ readKeys view mode
readKeysExist :: (MonadAction m, Entity a, ToJSON k, FromJSON k)
=> View a k -- ^ View
-> KeysSelection k -- ^ Keys selection mode
-> m [(k, Bool)]
-- ^ An associative list of `Bool` values by keys designating the existance of appropriate entities
readKeysExist view mode =
readAction view mode 0 Nothing False False
>>= runParser (rowsParser1 >=> mapM keyExistsParser . toList)
readEntities :: (MonadAction m, Entity a, ToJSON k)
=> View a k -- ^ View
-> KeysSelection k -- ^ Keys selection mode
-> Int -- ^ Skip
-> Maybe Int -- ^ Limit
-> Bool -- ^ Descending
-> m [Persisted a]
readEntities view mode skip limit desc =
readAction view mode skip limit desc True
>>= runParser (rowsParser1 >=> mapM persistedParser . toList)
>>= return . catMaybes
readEntity :: (MonadAction m, Entity a, ToJSON k)
=> View a k -- ^ View
-> KeysSelection k -- ^ Keys selection mode
-> Int -- ^ Skip
-> Bool -- ^ Descending
-> m (Maybe (Persisted a))
readEntity view mode skip desc =
listToMaybe <$> readEntities view mode skip (Just 1) desc
readRandomEntities :: (MonadAction m, Entity a)
=> Maybe Int -- ^ Limit
-> m [Persisted a]
readRandomEntities limit = do
startKey :: Double <- liftIO $ Random.randomRIO (0.0, 1.0)
readEntities
(ViewByKeys1 ViewKeyRandom)
(KeysSelectionRangeStart startKey)
0
limit
False
| nikita-volkov/ez-couch | src/EZCouch/ReadAction.hs | mit | 4,637 | 0 | 17 | 991 | 1,387 | 716 | 671 | -1 | -1 |
{-# LANGUAGE CPP #-}
module Import.NoFoundation
( module Import
) where
import ClassyPrelude.Yesod as Import
import Settings as Import
import Settings.StaticFiles as Import
import Yesod.Core.Types as Import (loggerSet)
import Yesod.Default.Config2 as Import
| random-j-farmer/hs-little-helper | Import/NoFoundation.hs | mit | 288 | 0 | 5 | 62 | 53 | 38 | 15 | 8 | 0 |
module Handler.Home where
import Import
getHomeR :: Handler ()
getHomeR = redirect $ StaticR index_html
| Dridus/alexandria | server/Handler/Home.hs | mit | 107 | 0 | 6 | 18 | 31 | 17 | 14 | 4 | 1 |
{-# LANGUAGE Arrows #-}
{-# LANGUAGE RankNTypes #-}
module Haskeroids.FRP.Game where
import Control.Arrow
import Control.Coroutine
import Control.Coroutine.FRP
import Control.Coroutine.FRP.Collections
import Data.Maybe
import Haskeroids.Geometry
import Haskeroids.Keyboard
import Haskeroids.FRP.Asteroid
import Haskeroids.FRP.Body
import Haskeroids.FRP.Bullet
import Haskeroids.FRP.Collisions
import Haskeroids.FRP.Draw
import Haskeroids.FRP.Particles
import Haskeroids.FRP.Ship
type PlayerCollision = Asteroid
type AsteroidCollision = Asteroid
type BulletCollision = Bullet
game :: Coroutine Keyboard Scene
game = proc kb -> do
rec
~(ship, newBlts, thrust) <- playerShip -< (kb, plCollisions)
blts <- bullets -< (newBlts, bltCollisions)
(asts, breaks) <- asteroids -< astCollisions
(plCollisions, bltCollisions, astCollisions) <- collider -< (ship, blts, asts)
dead <- edge -< isJust ship
shipDeath <- tagE <<< first (arr fromJust <<< delay Nothing) -< (ship, dead)
let bulletParticles = map bulletHitParticles bltCollisions
asteroidParticles = map asteroidBreakParticles breaks
deathParticles = map shipDeathParticles shipDeath
thrustParticles = map engineParticles thrust
ptcls <- particles -< concat
$ bulletParticles
++ thrustParticles
++ asteroidParticles
++ deathParticles
returnA -< draw (maybeToList ship)
:+: draw (untag blts)
:+: draw (untag asts)
:+: draw ptcls
collider :: Coroutine
(Maybe Ship, [Tagged Bullet], [Tagged Asteroid])
(Event PlayerCollision, TEvent BulletCollision, TEvent AsteroidCollision)
collider = proc (ship, bullets, asteroids) -> do
let plCollisions = case ship of
Nothing -> []
Just ship -> filter (collides ship) $ untag asteroids
(astCollisions, bltCollisions) = unzip $ collisions asteroids bullets
returnA <<< delay ([],[],[]) -< (plCollisions, bltCollisions, astCollisions)
bulletHitParticles :: Tagged Bullet -> [NewParticle]
bulletHitParticles (_, b) = replicate 5 NewParticle
{ npPosition = position body
, npRadius = 3
, npDirection = emitDir
, npSpread = pi/2
, npSpeed = (2.0, 5.0)
, npLifeTime = (5, 15)
, npSize = (1,2)
} where
body = bulletBody b
emitDir = angle body + pi
asteroidBreakParticles :: Break -> [NewParticle]
asteroidBreakParticles (Break (Asteroid b sz _)) = replicate n NewParticle
{ npPosition = position b
, npRadius = radius sz / 2.0
, npDirection = 0
, npSpread = 2*pi
, npSpeed = (3.0, 6.0)
, npLifeTime = (15, 40)
, npSize = (1,3)
} where
n = round $ radius sz
shipDeathParticles :: Ship -> [NewParticle]
shipDeathParticles ship = replicate 40 NewParticle
{ npPosition = position $ shipBody ship
, npRadius = shipSize / 2.0
, npDirection = 0
, npSpread = 2*pi
, npSpeed = (2.0, 8.0)
, npLifeTime = (15, 50)
, npSize = (2,4)
}
engineParticles :: Body -> [NewParticle]
engineParticles body = replicate 2 $ NewParticle
{ npPosition = position body /+/ polar (shipSize/3.0) emitDir
, npRadius = 0
, npDirection = emitDir
, npSpread = pi/6.0
, npSpeed = (1.0, 4.0)
, npLifeTime = (5, 15)
, npSize = (1,1)
} where emitDir = angle body + pi
| shangaslammi/haskeroids-frp | Haskeroids/FRP/Game.hs | mit | 3,452 | 2 | 17 | 880 | 1,055 | 587 | 468 | 91 | 2 |
import Graphics.Gloss
win = InWindow "" (400, 300) (10, 10)
main = animate win white draw
draw t = Pictures (map f [1..20])
where f n = Rotate (t*n*5) blob
blob = Translate 100 0 (Color c (ThickCircle 10 20))
c = withAlpha 0.3 azure
| dominicprior/gloss-demo | demo3.hs | mit | 235 | 1 | 9 | 47 | 133 | 67 | 66 | 7 | 1 |
module Main where
import System.Environment
import System.Directory
import System.FilePath
import System.Posix.Files
import System.Posix.Types
import System.Console.Terminfo.Base
-- System.Console.Terminfo.Color
import System.Console.Terminfo.Cursor
import Data.List
import Data.Maybe
main :: IO ()
main = do
term <- setupTermFromEnv
let height = fromMaybe 0 (getCapability term termLines)
width = fromMaybe 0 (getCapability term termColumns)
args <- getArgs
let recurse = (elem "-R" args)
let targets = filter (not . (== "-R")) args
let dirs = if null targets then ["."] else targets
-- let cr = getCapability term (carriageReturn :: (Capability TermOutput))
-- let up = getCapability term (moveUp :: (Capability (Int -> TermOutput)))
runTermOutput term (termText (" \tTargets: "++(show dirs)++"\n"))
runTermOutput term (termText (" \tRecurse: "++(show recurse)++"\n"))
runTermOutput term (termText (" \tTerminal size: "++("("++(show height)++" / "++(show width)++")")++"\n"))
-- runTermOutput term (termText (" Sample header: "++(show (formatList sampleOutput 82 True))++"\n"))
-- runTermOutput term (termText (" Sample no header thin: "++(show (formatList sampleOutput 5 False))++"\n"))
-- runTermOutput term (termText (foldr (++) "\n" (formatList sampleOutput width recurse)))
_ <- sequence (map (flip displayOutput term) (formatList sampleOutput width recurse))
-- runTermOutput term (termText (" Output: \n"++unlines (formatList (dropMaybe fileLists) width showHeader)))
-- runTermOutput term ((fromMaybe (\_ -> termText "") up) 7)
-- runTermOutput term (termText ("#\n"))
return ()
displayOutput :: String -> Terminal -> IO ()
displayOutput str term = runTermOutput term (termText (str++"\n"))
sampleOutput :: [(FilePath,[String])]
sampleOutput = [(".",["FileUtils.hs", "Hls.hs~", "pedantic.log", "Hls.hs", "old-Hls.hs", "SuidFinder.hs"]),("/",["bin", "home", "lost+found", "proc", "selinux", "usr", "boot", "initrd.img", "media", "root", "srv", "var", "dev", "initrd.img.old", "mnt", "run", "sys", "vmlinuz", "etc", "lib", "opt", "sbin", "tmp", "vmlinuz.old"])]
getFiles :: [FilePath] -> [(FilePath, (IO [String]))]
getFiles [dir] = [getFilesFromDir dir]
getFiles (dir:otherDirs) = (getFilesFromDir dir):(getFiles otherDirs)
getFiles [] = []
--sequence not correct, default should be alpha top-down then left-right
--current is all over the shop
--now sorted, but going l2r then u2d... want transpose?!?!
getFilesFromDir :: FilePath -> (FilePath, IO [String])
getFilesFromDir dir = (dir, getDirectoryContents dir)
--need to work out spacing before knowing list numbers and orders
--use trial and error
--assume 1 row
--calculate min width using 1 row <--|
--if row width > screenWidth |
-- increment row count ------------|
--else pad & display
-- input display try-rows rows
calculateRowCount :: [String] -> Int -> Int -> Int
calculateRowCount list rows displayWidth = if calculateLength list < displayWidth
then rows
else calculateRowCount list (rows+1) displayWidth
columnBufferWidth :: Int
columnBufferWidth = 2
calculateLength :: [String] -> Int
calculateLength [] = 0
calculateLength (x:xs) = ((length x)+columnBufferWidth)+(calculateLength xs)
-- Width showHeader
formatList :: [(FilePath, [String])] -> Int -> Bool -> [String]
formatList [] _width _header = []
formatList ((path, listing):rest) width header = if header
then ((path++":"):formattedEntries)++(formatList rest width header)
else formattedEntries++(formatList rest width header)
where entryMaxWidth = (widestFilename listing)+1
sortedEntries = sort listing
formattedEntries = formatListing sortedEntries entryMaxWidth width
formatListing :: [String] -> Int -> Int -> [String]
formatListing [] _entryMaxWidth _width = []
formatListing listing entryMaxWidth width
| entriesPerRow < 2 = listing
| (length listing) < entriesPerRow = (foldr ((++)) "" (paddedEntries)):[]
| otherwise = foldr (++) "" (take entriesPerRow paddedEntries) : (formatListing (drop entriesPerRow listing) entryMaxWidth width)
where entriesPerRow = width `div` entryMaxWidth
paddedEntries = map ((flip padDisplayString) entryMaxWidth) listing
widestFilename :: [String] -> Int
widestFilename [] = 0
widestFilename list = max ((length . head) list) (widestFilename (tail list))
padDisplayString :: String -> Int -> String
padDisplayString input targetLength | (length input) >= targetLength = input
| otherwise = input ++ take (targetLength-(length input)) (repeat '_')
--getListings :: [FilePath] -> LsOptions -> [(FilePath, (IO [String]))]
--getListings [target] opts = getListing target opts
--getListings (target:others) opts = (getListing target opts)++(getListings others opts)
--getListing :: FilePath -> LsOptions -> [(FilePath, (IO [String]))]
--getListing target opts = [(target, getDirectoryContents target)]
--getFileInfo :: FilePath -> LsOptions -> IO FileInfo
--getFileInfo path opts = do status <- getFileStatus path
-- let isPipe = (isNamedPipe status)
-- if(isPipe) then return FileInfo{ base = takeBaseName path, fileType = FifoType }
-- else return FileInfo{ base = takeBaseName path, extention = path }
dropBase :: FilePath -> String
dropBase path | baseLength < totalLength = drop (baseLength+1) path
| otherwise = ""
where baseLength = length (takeBaseName path)
totalLength = length path
getFileInfo :: FilePath -> LsOptions -> IO FileInfo
getFileInfo path _opts = do thisStatus <- getFileStatus path
thisType <- getFileType thisStatus
thisTarget <- readSymbolicLink path
-- thisLinkType <-
return FileInfo { base = takeBaseName path
, extention = (dropBase path)
, fileType = thisType
, inode = fileID thisStatus
, linkTarget = thisTarget
, linkType = NoLink
, hasCapability = False
, linkOk = False
, containsFiles = []
}
getFileTypes :: FileStatus -> IO [Maybe FileType]
getFileTypes status = do
return [ if (isNamedPipe status) then Just FifoType else Nothing
, if (isCharacterDevice status) then Just CharDevType else Nothing
, if (isDirectory status) then Just DirectoryType else Nothing
, if (isBlockDevice status) then Just BlockDevType else Nothing
, if (isRegularFile status) then Just NormalType else Nothing
, if (isSymbolicLink status) then Just SymbolicLinkType else Nothing
, if (isSocket status) then Just SockType else Nothing
]
getFileType :: FileStatus -> IO FileType
getFileType status = do maybeTypes <- getFileTypes status
let justTypes = (catMaybes (maybeTypes))
if length justTypes > 1
then return UnknownType
else return (head justTypes)
-- | otherwise =
--linkTarget :: FilePath
--hasCapability :: Bool
--linkType :: LinkType --links only
--linkOk :: Bool --links only
--containsFiles :: [FileInfo] --directories only
--add fileExist guard
-- status --iNode
--getSymbolicLinkStatus
--fileMode
--fileOwner
--fileGroup
--fileSize
--accessTime
--modificationTime
--statusChangeTime
--
--
--
--
--
--
--
--
data LsOptions = LsOptions { listAll :: Bool
, listAlmostAll :: Bool
, listBackups :: Bool
, listRecursive :: Bool
, showInode :: Bool
, showSize :: Bool
, showClassifier :: Bool
, showIndicatorStyle :: IndicatorStyle
, showControlChars :: Bool
, showTime :: Bool
, showColor :: Bool
, showContext :: Bool
, showAuthor :: Bool
-- hideOptions ::
, hideGroup :: Bool
, hideControlChars :: Bool
, format :: FormatStyle
-- formatTime ::
-- timeFull ::
, tabSize :: Int
, wideListing :: Bool
, sortReverse :: Bool
, sortType :: SortType
, groupDirectories :: Bool
, escape :: Bool
, directory :: Bool
, dired :: Bool
, useHumanReadable :: Bool
, useKilobytes :: Bool
, useNumericIds :: Bool
-- si ::
-- derefCommand :: Bool
-- derefCommandSymlink :: Bool
-- ignoreCommand ::
-- dereference :: Bool
-- literal :: Bool
-- quote :: Bool
-- quoteStyle ::
-- blockSize ::
}
data IndicatorStyle = NoIndicator
| SlashIndicator
| TypeIndicator
| ClassifyIndicator
data FormatStyle = LongFormat
| WithCommasFormat
| HorizontalFormat
| ManyPerLineFormat
| OnePerLine
data SortType = NoSort
| NameSort
| ExtensionSort
| SizeSort
| VersionSort
| TimeSort
data FileInfo = FileInfo { base :: String
, extention :: String
, inode :: FileID
, linkTarget :: FilePath
, hasCapability :: Bool
-- , fileStatus :: FileStatus --this is what i'm culling
, fileType :: FileType
, linkType :: LinkType --links only
, linkOk :: Bool --links only
, containsFiles :: [FileInfo] --directories only
--, accessControlList ::
--, securityContext ::
--, stat ::
}
data FileType = UnknownType
| FifoType
| CharDevType
| DirectoryType
| BlockDevType
| NormalType
| SymbolicLinkType
| SockType
deriving (Show, Eq)
-- | WhiteoutType --no unionfs support for now
-- | ArgDirectoryType --couldn't even find this one
data LinkType = NoLink | HardLink | SoftLink
colorArguments :: [String]
colorArguments = ["always", "yes", "force", "never", "no", "none", "auto", "tty", "if-tty"]
timeArguments :: [String]
timeArguments = ["atime", "access", "use", "ctime", "status"]
data TimeTypes = MTime | CTime | ATime
sortArguments :: [String]
sortArguments = ["none", "time", "size", "extension", "version"]
formatArguments :: [String]
formatArguments = ["verbose", "long", "commas", "horizontal", "across", "vertical", "single-column"]
| PuZZleDucK/Hls | Hls.hs | gpl-3.0 | 12,049 | 0 | 19 | 4,229 | 2,289 | 1,308 | 981 | 168 | 8 |
module Logistic.Logistic where
import System.IO
import Data.List
import Control.Monad
import Data.Text
import System.IO.Unsafe
num_iter=2
readI::String ->Int
readI=read
readIList []=[]
readIList x=Data.List.map (readI . unpack) (splitOn (pack "\t") (pack x))
readD::String ->Double
readD=read
readDList []=[]
readDList x=Data.List.map (readD . unpack) (splitOn (pack "\t") (pack x))
getData []=[]
getData (x:xs)=[(readDList x!!0,[(show $ readDList x!!2, readDList x!!1)])]++getData xs
readData file = do
handle <- openFile file ReadMode
contents <- hGetContents handle
let !list = Data.List.lines contents
--print "Input Data"
--print list
hClose handle
return (getData list)
{-
main= do
x<-readData "logisticRegression.txt"
print x
-}
dataF=unsafePerformIO $ readData "logisticRegression.txt"
--main=print dataF
--emptyDict= const Nothing
--add :: Eq a => (a -> Maybe b) -> a -> b -> (a -> Maybe b)
--add dict key value = \x -> if x == key
-- then Just value
-- else dict x
--remove dict key = \x -> if x == key
-- then Nothing
-- else dict x
type Feature=[(String, Double)]
--class LogisticRegression l where
-- rate :: l -> Double
-- weight :: l -> Feature
-- train :: l -> [(Int,Feature)] -> IO()
-- classify :: l -> Feature -> Double
--instance LogisticRegression l where
rate=0.01
--weight=[]
addToOld [] k1 val=[]
addToOld ((k,v):xs) k1 val|(k1==k)=[(k,v+val)]++ xs
| otherwise=[(k,v)]++ addToOld xs k1 val
add dict k new=dict++[(k,new)]
lookUp k []=False
lookUp k ((k1,v):xs)|(k1==k) = True
| otherwise = lookUp k xs
findVal k []=0
findVal k ((k1,v):xs)|(k1==k) = v
| otherwise = findVal k xs
someIterate weight []=0
someIterate weight ((k,v):xs)|lookUp k weight = 0+(findVal k weight)*v+ someIterate weight xs
| otherwise = 0+someIterate weight xs
classify feature weight= 1.0/(1.0+exp(-logit)) where
logit= someIterate weight feature
someIterateTrain [] x weight = return weight
someIterateTrain ((k,v):xs) x weight|(lookUp k weight)= someIterateTrain xs x (addToOld weight k new) where
new=rate*(x-(classify ((k,v):xs) weight))*v
someIterateTrain ((k,v):xs) x weight| otherwise=someIterateTrain xs x (add weight k (rate* update)) where
update= (x-(classify ((k,v):xs) weight))*v
train 0 _ weight=return weight
train n [] weight=return weight
train n ((x,feature):xs) weight = do newWeight<-someIterateTrain feature x weight;
--print newWeight
nextWeight<-train n xs newWeight;
--print newWeight
--print ("Done "++(show n));
train (n-1) ((x,feature):xs) nextWeight;
printList []=print "Regression Over"
printList ((d,i):xs)= do
print ("Probabilistic Weight of class"++(show d)++" is "++(show i))
printList xs
--main = do x<-(train num_iter dataF ([]))
-- printList x
| rahulaaj/ML-Library | src/Logistic/Logistic.hs | gpl-3.0 | 3,445 | 0 | 15 | 1,145 | 1,153 | 604 | 549 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( getApplicationDev
, appMain
, develMain
, makeFoundation
, makeLogWare
-- * for DevelMain
, getApplicationRepl
, shutdownApp
-- * for GHCI
, handler
, db
) where
import Control.Monad.Logger (liftLoc, runLoggingT)
import Database.Persist.Postgresql (createPostgresqlPool, pgConnStr, pgPoolSize, runSqlPool)
import Database.Persist.Sqlite (createSqlitePool)
import Import
import Language.Haskell.TH.Syntax (qLocation)
import Network.Wai (Middleware)
import Network.Wai.Middleware.Autohead
import Network.Wai.Middleware.AcceptOverride
import Network.Wai.Middleware.RequestLogger
import Network.Wai.Middleware.Gzip
import Network.Wai.Middleware.Cors
import Network.Wai.Middleware.MethodOverride
import Network.Wai.Handler.Warp (Settings, defaultSettings,
defaultShouldDisplayException,
runSettings, setHost,
setOnException, setPort, getPort)
import Network.Wai.Middleware.RequestLogger (Destination (Logger),
IPAddrSource (..),
OutputFormat (..), destination,
mkRequestLogger, outputFormat)
import System.Log.FastLogger (defaultBufSize, newStdoutLoggerSet,
toLogStr)
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Handler.Common
import Handler.Home
import Handler.Info
import Handler.Chapter
import Handler.Book
import Handler.User
import Handler.Command
import Handler.Hashed
import Handler.Register
import Handler.Rule
import Handler.Instuctor
import Handler.Admin
import Handler.Assignment
import Handler.Document
import Handler.Review
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- | This function allocates resources (such as a database connection pool),
-- performs initialization and returns a foundation datatype value. This is also
-- the place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeFoundation :: AppSettings -> IO App
makeFoundation appSettings = do
-- Some basic initializations: HTTP connection manager, logger, and static
-- subsite.
appHttpManager <- newManager
appLogger <- newStdoutLoggerSet defaultBufSize >>= makeYesodLogger
appStatic <-
(if appMutableStatic appSettings then staticDevel else static)
(appStaticDir appSettings)
-- We need a log function to create a connection pool. We need a connection
-- pool to create our foundation. And we need our foundation to get a
-- logging function. To get out of this loop, we initially create a
-- temporary foundation without a real connection pool, get a log function
-- from there, and then create the real foundation.
let mkFoundation appConnPool = App {..}
-- The App {..} syntax is an example of record wild cards. For more
-- information, see:
-- https://ocharles.org.uk/blog/posts/2014-12-04-record-wildcards.html
tempFoundation = mkFoundation $ error "connPool forced in tempFoundation"
logFunc = messageLoggerSource tempFoundation appLogger
--Create the database connection pool
pool <- flip runLoggingT logFunc $
if appSqlite appSettings
then createSqlitePool (pack (appDataRoot appSettings </> "sqlite.db")) 10
else createPostgresqlPool
(pgConnStr $ appDatabaseConf appSettings)
(pgPoolSize $ appDatabaseConf appSettings)
-- Perform database migration using our application's logging settings.
runLoggingT (runSqlPool (runMigration migrateAll) pool) logFunc
-- Return the foundation
return $ mkFoundation pool
-- | Convert our foundation to a WAI Application by calling @toWaiAppPlain@ and
-- applying some additional middlewares.
makeApplication :: App -> IO Application
makeApplication foundation = do
logWare <- makeLogWare foundation
let datadir = appDataRoot (appSettings foundation)
zipsettings = if appDevel (appSettings foundation)
then GzipIgnore
else GzipPreCompressed (GzipCacheFolder (datadir </> "gzcache/"))
-- Create the WAI application and apply middlewares
appPlain <- toWaiAppPlain foundation
return $ logWare . acceptOverride . autohead . gzip (def {gzipFiles = zipsettings }) . methodOverride . simpleCors $ appPlain
makeLogWare :: App -> IO Middleware
makeLogWare foundation =
mkRequestLogger def
{ outputFormat =
if appDetailedRequestLogging $ appSettings foundation
then Detailed True
else Apache
(if appIpFromHeader $ appSettings foundation
then FromFallback
else FromHeader)
, destination = Logger $ loggerSet $ appLogger foundation
}
-- | Warp settings for the given foundation value.
-- behind https.
warpSettings :: App -> Settings
warpSettings foundation =
setPort (appPort $ appSettings foundation)
$ setHost (appHost $ appSettings foundation)
$ setOnException (\_req e ->
when (defaultShouldDisplayException e) $ messageLoggerSource
foundation
(appLogger foundation)
$(qLocation >>= liftLoc)
"yesod"
LevelError
(toLogStr $ "Exception from Warp: " ++ show e))
defaultSettings
-- | For yesod devel, return the Warp settings and WAI Application.
getApplicationDev :: IO (Settings, Application)
getApplicationDev = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app <- makeApplication foundation
return (wsettings, app)
getAppSettings :: IO AppSettings
getAppSettings = loadYamlSettings [configSettingsYml] [] useEnv
-- | main function for use by yesod devel
develMain :: IO ()
develMain = develMainHelper getApplicationDev
-- | The @main@ function for an executable running this site.
appMain :: IO ()
appMain = do
-- Get the settings from all relevant sources
settings <- loadYamlSettingsArgs
-- fall back to compile-time values, set to [] to require values at runtime
[configSettingsYmlValue]
-- allow environment variables to override
useEnv
-- Generate the foundation from the settings
foundation <- makeFoundation settings
-- Generate a WAI Application from the foundation
app <- makeApplication foundation
-- Run the application with Warp
runSettings (warpSettings foundation) app
--------------------------------------------------------------
-- Functions for DevelMain.hs (a way to run the app from GHCi)
--------------------------------------------------------------
getApplicationRepl :: IO (Int, App, Application)
getApplicationRepl = do
settings <- getAppSettings
foundation <- makeFoundation settings
wsettings <- getDevSettings $ warpSettings foundation
app1 <- makeApplication foundation
return (getPort wsettings, foundation, app1)
shutdownApp :: App -> IO ()
shutdownApp _ = return ()
---------------------------------------------
-- Functions for use in development with GHCi
---------------------------------------------
-- | Run a handler
handler :: Handler a -> IO a
handler h = getAppSettings >>= makeFoundation >>= flip unsafeHandler h
-- | Run DB queries
db :: ReaderT SqlBackend (HandlerT App IO) a -> IO a
db = handler . runDB
| opentower/carnap | Carnap-Server/Application.hs | gpl-3.0 | 8,016 | 0 | 15 | 1,991 | 1,286 | 699 | 587 | -1 | -1 |
import Control.DeepSeq
import Control.Monad
import System.Environment
import System.IO
import System.Random
import Args
import GetKey
import Prompts
import Pwgen
import Storage
import XOut
version :: String
version = "2.0.2"
getDB :: Options -> String -> IO (String, DB)
getDB opt loc =
case optKey opt of
Nothing -> getDB' unlockPrompt loc
Just k ->
do dbm <- openDB k loc
case dbm of
Nothing -> error "Incorrect password."
Just db -> return (k, db)
where getDB' p dblocat =
do k <- getKey p
dbm <- openDB k dblocat
case dbm of
Nothing -> getDB' tryAgainPrompt dblocat
Just db -> return (k, db)
main :: IO ()
main = do
args <- getArgs
home <- getEnv "HOME"
(opts_precursor, _) <- compilerOpts args home
let opts = force opts_precursor
let dblocat = optDBlocat opts
when (optShowVersion opts) $ print version
when (optShowLicense opts) $ print "GPLv3"
case optAction opts of
Nothing -> return ()
Just List ->
do (_, db) <- getDB opts dblocat
entries <- listEntries db
putStrLn entries
Just Lookup ->
do (_, db) <- getDB opts dblocat
entry <- get db (optSelector opts) (optService opts) (optUser opts)
let entry' = maybe "No entry found." showdbent entry
let pword = case entry of Nothing -> ""; Just (_, _, p) -> p
if optXOut opts then gen ":0" (optDelay opts) (optConfirm opts)
(optReturn opts) pword
else putStrLn entry'
Just Create ->
do (key, db) <- getDB opts dblocat
sname <- case optService opts of Just k -> return k
Nothing -> do putStr "Service: "
hFlush stdout
getLine
r <- newStdGen
uname <- case optUser opts of
Just k -> return k
Nothing -> case optGenUser opts of
Just i -> return $ fst $ pwgen r i
Nothing -> do putStr "Username: "
hFlush stdout
getLine
r' <- newStdGen
pword <- case optPassword opts of
Just k -> return k
Nothing -> case optGenPw opts of
Just i -> return $ fst $ pwgen r' i
Nothing -> do putStr "Password: "
hFlush stdout
getLine
b <- add key dblocat db sname uname pword
case b of True -> putStrLn "Added, overwriting existing entry."
False -> putStrLn "Added."
Just Delete ->
do (key, db) <- getDB opts dblocat
killp <- del key dblocat db (optSelector opts) (optService opts)
(optUser opts)
case killp of True -> putStrLn "Deleted."
False -> putStrLn "No entries matched to delete."
Just Rekey ->
do (_, db) <- getDB opts dblocat
newKey1 <- getKey newPasswordPrompt
newKey2 <- getKey confirmPasswordPrompt
if newKey1 == newKey2
then writeDB newKey2 db dblocat
else putStrLn $ "Sorry, new passwords did not match. "
++ "No action performed."
Just MakeDB ->
do key <- getKey newPasswordPrompt
makeDB key dblocat
| frozencemetery/haskey | src/Main.hs | gpl-3.0 | 3,622 | 2 | 21 | 1,524 | 1,046 | 488 | 558 | 93 | 17 |
{-# LANGUAGE NoImplicitPrelude, TemplateHaskell, GeneralizedNewtypeDeriving #-}
module Graphics.UI.Bottle.WidgetsEnvT
( WidgetEnvT, runWidgetEnvT
, mapWidgetEnvT
, readCursor, subCursor, isSubCursor
, Env(..), envCursor, envTextStyle
, readEnv
, localEnv
, envAssignCursor, envAssignCursorPrefix
, assignCursor, assignCursorPrefix
, readTextStyle, setTextStyle
, setTextColor
) where
import qualified Control.Lens as Lens
import Control.Lens.Operators
import Control.Monad.Trans.Class (MonadTrans(..))
import Control.Monad.Trans.Reader (ReaderT, runReaderT)
import qualified Control.Monad.Trans.Reader as Reader
import Data.Maybe (isJust)
import Data.Vector.Vector2 (Vector2)
import qualified Graphics.DrawingCombinators as Draw
import Graphics.UI.Bottle.Animation (AnimId)
import qualified Graphics.UI.Bottle.Animation as Anim
import qualified Graphics.UI.Bottle.Widget as Widget
import qualified Graphics.UI.Bottle.Widgets.TextEdit as TextEdit
import qualified Graphics.UI.Bottle.Widgets.TextView as TextView
import Prelude.Compat
data Env = Env
{ _envCursor :: Widget.Id
, _envTextStyle :: TextEdit.Style
, layerInterval :: Anim.Layer
, stdSpacing :: Vector2 Double
}
Lens.makeLenses ''Env
newtype WidgetEnvT m a = WidgetEnvT
{ _widgetEnvT :: ReaderT Env m a
} deriving (Functor, Applicative, Monad, MonadTrans)
Lens.makeLenses ''WidgetEnvT
runWidgetEnvT ::
Monad m => Env -> WidgetEnvT m a -> m a
runWidgetEnvT env (WidgetEnvT action) = runReaderT action env
mapWidgetEnvT
:: Monad m
=> (m a -> n a)
-> WidgetEnvT m a
-> WidgetEnvT n a
mapWidgetEnvT = (widgetEnvT %~) . Reader.mapReaderT
readEnv :: Monad m => WidgetEnvT m Env
readEnv = WidgetEnvT Reader.ask
readCursor :: Monad m => WidgetEnvT m Widget.Id
readCursor = readEnv <&> (^. envCursor)
subCursor :: Monad m => Widget.Id -> WidgetEnvT m (Maybe AnimId)
subCursor folder = readCursor <&> Widget.subId folder
isSubCursor :: Monad m => Widget.Id -> WidgetEnvT m Bool
isSubCursor = fmap isJust . subCursor
readTextStyle :: Monad m => WidgetEnvT m TextEdit.Style
readTextStyle = readEnv <&> (^. envTextStyle)
setTextStyle :: Monad m => TextEdit.Style -> WidgetEnvT m a -> WidgetEnvT m a
setTextStyle style = localEnv (envTextStyle .~ style)
envAssignCursor
:: Widget.Id -> Widget.Id -> Env -> Env
envAssignCursor src dest =
envCursor %~ replace
where
replace cursor
| cursor == src = dest
| otherwise = cursor
envAssignCursorPrefix
:: Widget.Id -> (AnimId -> Widget.Id) -> Env -> Env
envAssignCursorPrefix srcFolder dest =
envCursor %~ replace
where
replace cursor =
case Widget.subId srcFolder cursor of
Nothing -> cursor
Just suffix -> dest suffix
assignCursor ::
Monad m => Widget.Id -> Widget.Id ->
WidgetEnvT m a -> WidgetEnvT m a
assignCursor x y = localEnv $ envAssignCursor x y
assignCursorPrefix ::
Monad m => Widget.Id -> (AnimId -> Widget.Id) ->
WidgetEnvT m a -> WidgetEnvT m a
assignCursorPrefix x y = localEnv $ envAssignCursorPrefix x y
localEnv :: Monad m => (Env -> Env) -> WidgetEnvT m a -> WidgetEnvT m a
localEnv = (widgetEnvT %~) . Reader.local
setTextColor :: Draw.Color -> Env -> Env
setTextColor color =
envTextStyle . TextEdit.sTextViewStyle . TextView.styleColor .~ color
| da-x/lamdu | bottlelib/Graphics/UI/Bottle/WidgetsEnvT.hs | gpl-3.0 | 3,461 | 0 | 10 | 738 | 1,001 | 545 | 456 | -1 | -1 |
module Problems54Athru60 where
import ADT.Tree
import Control.Monad (replicateM)
import Problems21thru28 (combinations)
import Util (powerOf2, flg)
-- Problem 55
--
-- (**) Construct completely balanced binary trees
--
-- In a completely balanced binary tree, the following property holds for
-- every node: The number of nodes in its left subtree and the number of
-- nodes in its right subtree are almost equal, which means their difference
-- is not greater than one.
--
-- Write a function cbal-tree to construct completely balanced binary trees
-- for a given number of nodes. The predicate should generate all solutions
-- via backtracking. Put the letter 'x' as information into all nodes of the
-- tree.
-- | Given a number of nodes, construct all possible completely balanced binary
-- trees directly without backtracking by first constructing the largest
-- perfect tree and then inserting sets of leaf nodes.
cbalTreeDirect :: Int -> [Tree Char]
cbalTreeDirect n
| extra == 0 = [baseTree]
| otherwise = map (foldl insertAt baseTree) allNodePaths
where
baseSize = 2 ^ flg (n + 1) - 1
baseHeight = flg (baseSize + 1) - 1
baseTree = mkPerfectTree baseSize
extra = n - baseSize
allNodePaths = combinations extra $ replicateM (baseHeight + 1) [L,R]
data Branch = L | R deriving Eq
type Path = [Branch]
-- | Given a number of nodes, make a perfect tree, if possible.
mkPerfectTree :: Int -> Tree Char
mkPerfectTree n
| n == 0 = Nil
| not $ powerOf2 (n + 1) = error "Not enough nodes."
| otherwise = foldl insertAt Nil nodePaths
where
height = flg (n + 1) - 1
nodePaths = concatMap (flip replicateM [L,R]) [0 .. height]
-- | Given a tree and a valid path, insert a new leaf node at the path.
insertAt :: Tree Char -> Path -> Tree Char
insertAt Nil [] = leaf 'x'
insertAt Nil (x:xs) = error "One or more ancestors are missing."
insertAt (Node l v r) [] = error "The path collides with an existing node."
insertAt (Node l v r) (x:xs) = case x of
L -> Node (insertAt l xs) v r
R -> Node l v (insertAt r xs)
-- Problem 56
--
-- (**) Symmetric binary trees
--
-- Let us call a binary tree symmetric if you can draw a vertical line
-- through the root node and then the right subtree is the mirror image of
-- the left subtree. Write a predicate symmetric/1 to check whether a given
-- binary tree is symmetric. Hint: Write a predicate mirror/2 first to check
-- whether one tree is the mirror image of another. We are only interested in
-- the structure, not in the contents of the nodes.
symmetric :: Tree a -> Bool
symmetric Nil = True
symmetric (Node l x r) = mirror l r
mirror :: Tree a -> Tree a -> Bool
mirror Nil Nil = True
mirror Nil _ = False
mirror _ Nil = False
mirror t1 t2 = mirror (left t1) (right t2) && mirror (right t1) (left t2)
-- Problem 57
--
-- (**) Binary search trees (dictionaries)
--
-- Use the predicate add/3, developed in chapter 4 of the course, to write a
-- predicate to construct a binary search tree from a list of integer numbers.
construct :: Ord a => [a] -> Tree a
construct = foldl add Nil
add :: Ord a => Tree a -> a -> Tree a
add Nil x = leaf x
add (Node l v r) x
| x == v = Node l v r
| x < v = Node (add l x) v r
| x > v = Node l v (add r x)
-- Problem 58
--
-- (**) Generate-and-test paradigm
--
-- Apply the generate-and-test paradigm to construct all symmetric,
-- completely balanced binary trees with a given number of nodes.
symCbalTrees :: Int -> [Tree Char]
symCbalTrees = filter symmetric . cbalTreeDirect
-- Problem 59
--
-- (**) Construct height-balanced binary trees
--
-- In a height-balanced binary tree, the following property holds for every
-- node: The height of its left subtree and the height of its right subtree
-- are almost equal, which means their difference is not greater than one.
--
-- Construct a list of all height-balanced binary trees with the given
-- element and the given maximum height.
hbalTree :: a -> Int -> [Tree a]
hbalTree x h = concatMap (hbalTree' x) [-1 .. h]
where
hbalTree' _ (-1) = [Nil]
hbalTree' x 0 = [leaf x]
hbalTree' x h = [Node l x r | (hl, hr) <- [(h-1, h-2), (h-1, h-1), (h-2, h-1)]
, l <- hbalTree' x hl, r <- hbalTree' x hr]
| zcesur/h99 | src/Problems54Athru60.hs | gpl-3.0 | 4,305 | 0 | 12 | 975 | 1,060 | 562 | 498 | 54 | 3 |
{-# 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.GamesConfiguration.LeaderboardConfigurations.Insert
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Insert a new leaderboard configuration in this application.
--
-- /See:/ <https://developers.google.com/games/ Google Play Game Services Publishing API Reference> for @gamesConfiguration.leaderboardConfigurations.insert@.
module Network.Google.Resource.GamesConfiguration.LeaderboardConfigurations.Insert
(
-- * REST Resource
LeaderboardConfigurationsInsertResource
-- * Creating a Request
, leaderboardConfigurationsInsert
, LeaderboardConfigurationsInsert
-- * Request Lenses
, lciXgafv
, lciUploadProtocol
, lciAccessToken
, lciUploadType
, lciPayload
, lciApplicationId
, lciCallback
) where
import Network.Google.GamesConfiguration.Types
import Network.Google.Prelude
-- | A resource alias for @gamesConfiguration.leaderboardConfigurations.insert@ method which the
-- 'LeaderboardConfigurationsInsert' request conforms to.
type LeaderboardConfigurationsInsertResource =
"games" :>
"v1configuration" :>
"applications" :>
Capture "applicationId" Text :>
"leaderboards" :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :>
ReqBody '[JSON] LeaderboardConfiguration :>
Post '[JSON] LeaderboardConfiguration
-- | Insert a new leaderboard configuration in this application.
--
-- /See:/ 'leaderboardConfigurationsInsert' smart constructor.
data LeaderboardConfigurationsInsert =
LeaderboardConfigurationsInsert'
{ _lciXgafv :: !(Maybe Xgafv)
, _lciUploadProtocol :: !(Maybe Text)
, _lciAccessToken :: !(Maybe Text)
, _lciUploadType :: !(Maybe Text)
, _lciPayload :: !LeaderboardConfiguration
, _lciApplicationId :: !Text
, _lciCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LeaderboardConfigurationsInsert' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lciXgafv'
--
-- * 'lciUploadProtocol'
--
-- * 'lciAccessToken'
--
-- * 'lciUploadType'
--
-- * 'lciPayload'
--
-- * 'lciApplicationId'
--
-- * 'lciCallback'
leaderboardConfigurationsInsert
:: LeaderboardConfiguration -- ^ 'lciPayload'
-> Text -- ^ 'lciApplicationId'
-> LeaderboardConfigurationsInsert
leaderboardConfigurationsInsert pLciPayload_ pLciApplicationId_ =
LeaderboardConfigurationsInsert'
{ _lciXgafv = Nothing
, _lciUploadProtocol = Nothing
, _lciAccessToken = Nothing
, _lciUploadType = Nothing
, _lciPayload = pLciPayload_
, _lciApplicationId = pLciApplicationId_
, _lciCallback = Nothing
}
-- | V1 error format.
lciXgafv :: Lens' LeaderboardConfigurationsInsert (Maybe Xgafv)
lciXgafv = lens _lciXgafv (\ s a -> s{_lciXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
lciUploadProtocol :: Lens' LeaderboardConfigurationsInsert (Maybe Text)
lciUploadProtocol
= lens _lciUploadProtocol
(\ s a -> s{_lciUploadProtocol = a})
-- | OAuth access token.
lciAccessToken :: Lens' LeaderboardConfigurationsInsert (Maybe Text)
lciAccessToken
= lens _lciAccessToken
(\ s a -> s{_lciAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
lciUploadType :: Lens' LeaderboardConfigurationsInsert (Maybe Text)
lciUploadType
= lens _lciUploadType
(\ s a -> s{_lciUploadType = a})
-- | Multipart request metadata.
lciPayload :: Lens' LeaderboardConfigurationsInsert LeaderboardConfiguration
lciPayload
= lens _lciPayload (\ s a -> s{_lciPayload = a})
-- | The application ID from the Google Play developer console.
lciApplicationId :: Lens' LeaderboardConfigurationsInsert Text
lciApplicationId
= lens _lciApplicationId
(\ s a -> s{_lciApplicationId = a})
-- | JSONP
lciCallback :: Lens' LeaderboardConfigurationsInsert (Maybe Text)
lciCallback
= lens _lciCallback (\ s a -> s{_lciCallback = a})
instance GoogleRequest
LeaderboardConfigurationsInsert
where
type Rs LeaderboardConfigurationsInsert =
LeaderboardConfiguration
type Scopes LeaderboardConfigurationsInsert =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient LeaderboardConfigurationsInsert'{..}
= go _lciApplicationId _lciXgafv _lciUploadProtocol
_lciAccessToken
_lciUploadType
_lciCallback
(Just AltJSON)
_lciPayload
gamesConfigurationService
where go
= buildClient
(Proxy ::
Proxy LeaderboardConfigurationsInsertResource)
mempty
| brendanhay/gogol | gogol-games-configuration/gen/Network/Google/Resource/GamesConfiguration/LeaderboardConfigurations/Insert.hs | mpl-2.0 | 5,774 | 0 | 19 | 1,310 | 786 | 457 | 329 | 120 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.DeleteTags
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Deletes the specified set of tags from the specified set of resources. This
-- call is designed to follow a 'DescribeTags' request.
--
-- For more information about tags, see <http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html Tagging Your Resources> in the /AmazonElastic Compute Cloud User Guide/.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DeleteTags.html>
module Network.AWS.EC2.DeleteTags
(
-- * Request
DeleteTags
-- ** Request constructor
, deleteTags
-- ** Request lenses
, dt1DryRun
, dt1Resources
, dt1Tags
-- * Response
, DeleteTagsResponse
-- ** Response constructor
, deleteTagsResponse
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data DeleteTags = DeleteTags
{ _dt1DryRun :: Maybe Bool
, _dt1Resources :: List "resourceId" Text
, _dt1Tags :: List "item" Tag
} deriving (Eq, Read, Show)
-- | 'DeleteTags' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dt1DryRun' @::@ 'Maybe' 'Bool'
--
-- * 'dt1Resources' @::@ ['Text']
--
-- * 'dt1Tags' @::@ ['Tag']
--
deleteTags :: DeleteTags
deleteTags = DeleteTags
{ _dt1DryRun = Nothing
, _dt1Resources = mempty
, _dt1Tags = mempty
}
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have the
-- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'.
dt1DryRun :: Lens' DeleteTags (Maybe Bool)
dt1DryRun = lens _dt1DryRun (\s a -> s { _dt1DryRun = a })
-- | The ID of the resource. For example, ami-1a2b3c4d. You can specify more than
-- one resource ID.
dt1Resources :: Lens' DeleteTags [Text]
dt1Resources = lens _dt1Resources (\s a -> s { _dt1Resources = a }) . _List
-- | One or more tags to delete. If you omit the 'value' parameter, we delete the
-- tag regardless of its value. If you specify this parameter with an empty
-- string as the value, we delete the key only if its value is an empty string.
dt1Tags :: Lens' DeleteTags [Tag]
dt1Tags = lens _dt1Tags (\s a -> s { _dt1Tags = a }) . _List
data DeleteTagsResponse = DeleteTagsResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'DeleteTagsResponse' constructor.
deleteTagsResponse :: DeleteTagsResponse
deleteTagsResponse = DeleteTagsResponse
instance ToPath DeleteTags where
toPath = const "/"
instance ToQuery DeleteTags where
toQuery DeleteTags{..} = mconcat
[ "DryRun" =? _dt1DryRun
, "ResourceId" `toQueryList` _dt1Resources
, "Tag" `toQueryList` _dt1Tags
]
instance ToHeaders DeleteTags
instance AWSRequest DeleteTags where
type Sv DeleteTags = EC2
type Rs DeleteTags = DeleteTagsResponse
request = post "DeleteTags"
response = nullResponse DeleteTagsResponse
| romanb/amazonka | amazonka-ec2/gen/Network/AWS/EC2/DeleteTags.hs | mpl-2.0 | 4,026 | 0 | 10 | 886 | 482 | 296 | 186 | 56 | 1 |
-- Copyright 2017 Lukas Epple
--
-- This file is part of likely music.
--
-- likely music is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- likely music 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 Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with likely music. If not, see <http://www.gnu.org/licenses/>.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeOperators #-}
module Api where
import Data.Aeson
import Data.ByteString.Lazy (ByteString ())
import Data.Monoid ((<>))
import Data.Ratio
import Data.Text (Text ())
import GHC.Generics
import Servant.API
import Sound.Likely
type LikelyApi = "interpretation" :> Capture "format" OutputFormat
:> ReqBody '[JSON] GraphWithParams
:> Post '[OctetStream] ByteString
:<|> "seed" :> Get '[JSON] Int
:<|> Raw
data OutputFormat = Midi | Wav
deriving (Show, Eq, Ord)
instance FromHttpApiData OutputFormat where
parseUrlPiece "mid" = Right Midi
parseUrlPiece "wav" = Right Wav
parseUrlPiece x = Left $ "Couldn't match " <> x <> " with {mid, wav}"
data GraphWithParams
= GraphWithParams
{ gpParams :: Params
, gpGraph :: Graph
} deriving (Show, Eq, Ord)
instance FromJSON GraphWithParams where
parseJSON = withObject "GraphWithParams" $ \v ->
GraphWithParams <$> v .: "params"
<*> v .: "graph"
data Params
= Params
{ pMaxHops :: Int
, pStartingNode :: Node
, pSeed :: Int
} deriving (Show, Eq, Ord)
instance FromJSON Params where
parseJSON = withObject "Params" $ \v ->
Params <$> v .: "maxhops"
<*> v .: "starting_node"
<*> v .: "seed"
| sternenseemann/likely-music | backend/Api.hs | agpl-3.0 | 2,211 | 0 | 13 | 549 | 396 | 226 | 170 | 44 | 0 |
--------------------------------------------------------------------------------
-- $Id: SwishScript.hs,v 1.10 2004/02/09 22:22:44 graham Exp $
--
-- Copyright (c) 2003, G. KLYNE. All rights reserved.
-- See end of this file for licence information.
--------------------------------------------------------------------------------
-- |
-- Module : SwishScript
-- Copyright : (c) 2003, Graham Klyne
-- License : GPL V2
--
-- Maintainer : Graham Klyne
-- Stability : provisional
-- Portability : H98
--
-- This module implements the Swish script processor: it parses a script
-- from a supplied string, and returns a list of Swish state transformer
-- functions whose effect, when applied to a state value, is to implement
-- the supplied script.
--
-- The script syntax is based loosely on Notation3, and the script parser is an
-- extension of the Notation3 parser in module N3Parser.hs.
--
--------------------------------------------------------------------------------
module Swish.HaskellRDF.SwishScript
( parseScriptFromString
)
where
import Swish.HaskellRDF.SwishMonad
( SwishStateIO
, modGraphs, findGraph, findFormula
, modRules, findRule
, modRulesets, findRuleset
, findOpenVarModify, findDatatype
, setInfo, setError, setExitcode
, NamedGraph(..)
)
import Swish.HaskellRDF.RDFDatatype
( RDFDatatype )
import Swish.HaskellRDF.RDFRuleset
( RDFFormula, RDFRule
, RDFRuleset
, makeRDFClosureRule
)
import Swish.HaskellRDF.RDFProof
( RDFProofStep, makeRDFProof, makeRDFProofStep )
import Swish.HaskellRDF.RDFVarBinding
( RDFVarBindingModify
)
import Swish.HaskellRDF.RDFGraphShowM()
import Swish.HaskellRDF.RDFGraph
( RDFGraph, RDFLabel(..)
, emptyRDFGraph
, NamespaceMap
, setNamespaces
, merge, add
)
import Swish.HaskellRDF.N3Parser
( parseAnyfromString
, N3Parser, N3State(..)
, whiteSpace, symbol, eof, identLetter
, defaultPrefix, namedPrefix
, document, subgraph, uriRef2, varid, lexUriRef
, newBlankNode
)
import Swish.HaskellRDF.N3Formatter
( formatGraphAsShowS )
import Swish.HaskellRDF.Datatype
( typeMkRules )
import Swish.HaskellRDF.Proof
( explainProof, showsProof )
import Swish.HaskellRDF.Ruleset
( makeRuleset, getRulesetRule, getMaybeContextRule )
import Swish.HaskellRDF.Rule
( Formula(..), Rule(..) -- , RuleMap
)
import Swish.HaskellRDF.VarBinding
( composeSequence )
import Swish.HaskellUtils.Namespace
( ScopedName(..) )
import Swish.HaskellUtils.LookupMap
( mapReplaceOrAdd )
import Swish.HaskellUtils.ListHelpers
( equiv, flist )
import Swish.HaskellUtils.ErrorM
( ErrorM(..) )
import Text.ParserCombinators.Parsec
( (<?>), (<|>)
, many, manyTill, option, sepBy, between, try, notFollowedBy
, string, char, anyChar
, getState
)
import Control.Monad.State
( modify, gets, lift
-- , StateT(..), execStateT
)
import Control.Monad
( when, liftM )
{- WNH
import System.IO
( IOMode(..), hPutStr
, IOError, try, ioeGetErrorString
)
import qualified System.IO
( IOMode(..), hPutStr
, IOError, try, ioeGetErrorString
)
import Directory
( doesFileExist )
-}
import qualified System.IO.Error as IO
import System.Exit
( ExitCode(ExitFailure) )
------------------------------------------------------------
-- Parser for Swish script processor
------------------------------------------------------------
--
-- The parser is based on the Notation3 parser, and uses many
-- of the same syntax productions, but the top-level productions used
-- are quite different.
parseScriptFromString :: Maybe String -> String -> ErrorM [SwishStateIO ()]
parseScriptFromString base inp =
case parseAnyfromString script base inp of
Left err -> Error err
Right scs -> Result scs
----------------------------------------------------------------------
-- Syntax productions
----------------------------------------------------------------------
script :: N3Parser [SwishStateIO ()]
script =
do { whiteSpace
; scs <- many command
; eof
; return scs
}
command :: N3Parser (SwishStateIO ())
command =
do { try $ symbol "@prefix"
; ( defaultPrefix <|> namedPrefix )
; return $ return ()
}
<|> nameItem
<|> readGraph
<|> writeGraph
<|> mergeGraphs
<|> compareGraphs
<|> assertEquiv
<|> assertMember
<|> defineRule
<|> defineRuleset
<|> defineConstraints
<|> checkProofCmd
<|> fwdChain
<|> bwdChain
<?>
"script command"
nameItem :: N3Parser (SwishStateIO ())
nameItem =
-- name :- graph
-- name :- ( graph* )
do { u <- uriRef2
; symbol ":-"
; g <- graphOrList
; return $ ssAddGraph u g
}
readGraph :: N3Parser (SwishStateIO ())
readGraph =
-- @read name [ <uri> ]
do { commandName "@read"
; n <- uriRef2
; u <- option "" lexUriRef
; return $ ssRead n (if null u then Nothing else Just u)
}
writeGraph :: N3Parser (SwishStateIO ())
writeGraph =
-- @write name [ <uri> ] ; Comment
do { commandName "@write"
; n <- uriRef2
; let gs = ssGetList n :: SwishStateIO (Either String [RDFGraph])
; u <- option "" lexUriRef
; symbol ";"
; c <- restOfLine
; let muri = if null u then Nothing else Just u
; return $ ssWriteList muri gs c
}
mergeGraphs :: N3Parser (SwishStateIO ())
mergeGraphs =
-- @merge ( name* ) => name
do { commandName "@merge"
; gs <- graphList
; symbol "=>"
; n <- uriRef2
; return $ ssMerge n gs
}
compareGraphs :: N3Parser (SwishStateIO ())
compareGraphs =
-- @compare name name
do { commandName "@compare"
; n1 <- uriRef2
; n2 <- uriRef2
; return $ ssCompare n1 n2
}
assertEquiv :: N3Parser (SwishStateIO ())
assertEquiv =
-- @asserteq name name ; Comment
do { commandName "@asserteq"
; n1 <- uriRef2
; n2 <- uriRef2
; symbol ";"
; c <- restOfLine
; return $ ssAssertEq n1 n2 c
}
assertMember :: N3Parser (SwishStateIO ())
assertMember =
-- @assertin name name ; Comment
do { commandName "@assertin"
; n1 <- uriRef2
; n2 <- uriRef2
; symbol ";"
; c <- restOfLine
; return $ ssAssertIn n1 n2 c
}
defineRule :: N3Parser (SwishStateIO ())
defineRule =
-- @rule name :- ( name* ) => name [ | ( (name var*)* ) ]
do { commandName "@rule"
; rn <- uriRef2
; symbol ":-"
; ags <- graphOrList
; symbol "=>"
; cg <- graphExpr
; vms <- option [] varModifiers
; return $ ssDefineRule rn ags cg vms
}
defineRuleset :: N3Parser (SwishStateIO ())
defineRuleset =
-- @ruleset name :- ( name* ) ; ( name* )
do { commandName "@ruleset"
; sn <- uriRef2
; symbol ":-"
; ags <- nameList
; symbol ";"
; rns <- nameList
; return $ ssDefineRuleset sn ags rns
}
defineConstraints :: N3Parser (SwishStateIO ())
defineConstraints =
-- @constraints pref :- ( name* ) | ( name* )
do { commandName "@constraints"
; sn <- uriRef2
; symbol ":-"
; cgs <- graphOrList
; symbol "|"
; cns <- nameOrList
; return $ ssDefineConstraints sn cgs cns
}
checkProofCmd :: N3Parser (SwishStateIO ())
checkProofCmd =
-- @proof name ( name* )
-- @input name
-- @step name ( name* ) => name # rule-name, antecedents, consequent
-- @result name
do { commandName "@proof"
; pn <- uriRef2
; sns <- nameList
; commandName "@input"
; igf <- formulaExpr
; sts <- many checkStep
; commandName "@result"
; rgf <- formulaExpr
; return $ ssCheckProof pn sns igf sts rgf
}
checkStep ::
N3Parser (Either String [RDFRuleset]
-> SwishStateIO (Either String RDFProofStep))
checkStep =
do { commandName "@step"
; rn <- uriRef2
; agfs <- formulaList
; symbol "=>"
; cgf <- formulaExpr
; return $ ssCheckStep rn agfs cgf
}
fwdChain :: N3Parser (SwishStateIO ())
fwdChain =
-- # ruleset rule (antecedents) => result
-- @fwdchain pref name ( name* ) => name
do { commandName "@fwdchain"
; sn <- uriRef2
; rn <- uriRef2
; ags <- graphOrList
; symbol "=>"
; cn <- uriRef2
; s <- getState :: N3Parser N3State
; let prefs = prefixUris s :: NamespaceMap
; return $ ssFwdChain sn rn ags cn prefs
}
bwdChain :: N3Parser (SwishStateIO ())
bwdChain =
-- # ruleset rule consequent <= (antecedent-alts)
-- @bwdchain pref name graph <= name
do { commandName "@bwdchain"
; sn <- uriRef2
; rn <- uriRef2
; cg <- graphExpr
; symbol "<="
; an <- uriRef2
; s <- getState :: N3Parser N3State
; let prefs = prefixUris s :: NamespaceMap
; return $ ssBwdChain sn rn cg an prefs
}
----------------------------------------------------------------------
-- Syntax clause helpers
----------------------------------------------------------------------
commandName :: String -> N3Parser ()
commandName cmd = try $
do { string cmd
; notFollowedBy identLetter
; whiteSpace
}
restOfLine :: N3Parser String
restOfLine =
do { s <- manyTill anyChar (char '\n')
; whiteSpace
; return s
}
nameList :: N3Parser [ScopedName]
nameList =
do { symbol "("
; ns <- many uriRef2
; symbol ")"
; return ns
}
nameOrList :: N3Parser [ScopedName]
nameOrList =
do { n <- uriRef2
; return $ [n]
}
<|>
nameList
<?>
"Name, or list of names"
graphExpr :: N3Parser (SwishStateIO (Either String RDFGraph))
graphExpr =
graphOnly
<|>
do { f <- formulaExpr
; return $ liftM (liftM formExpr) f
}
<?>
"Graph expression, graph name or named graph definition"
graphOnly :: N3Parser (SwishStateIO (Either String RDFGraph))
graphOnly =
do { symbol "{"
; b <- newBlankNode
; g <- subgraph b :: N3Parser RDFGraph
; symbol "}"
; s <- getState
; let gp = setNamespaces (prefixUris s) g
; return $ return (Right gp)
}
graphList :: N3Parser [SwishStateIO (Either String RDFGraph)]
graphList = between (symbol "(") (symbol ")") (many graphExpr)
<?>
"List of graphs"
graphOrList :: N3Parser [SwishStateIO (Either String RDFGraph)]
graphOrList =
do { g <- graphExpr
; return $ [g]
}
<|>
graphList
<?>
"Graph, or list of graphs"
formulaExpr :: N3Parser (SwishStateIO (Either String RDFFormula))
formulaExpr =
do { n <- uriRef2
; namedGraph n
}
<?> "Formula (name or named graph)"
namedGraph :: ScopedName -> N3Parser (SwishStateIO (Either String RDFFormula))
namedGraph n =
do { symbol ":-"
; g <- graphOnly
; return $ ssAddReturnFormula n g
}
<|>
return (ssGetFormula n)
formulaList :: N3Parser [SwishStateIO (Either String RDFFormula)]
formulaList = between (symbol "(") (symbol ")") (many formulaExpr)
<?>
"List of formulae (names or named graphs)"
varModifiers :: N3Parser [(ScopedName,[RDFLabel])]
varModifiers =
do { symbol "|"
; varModList
}
varModList :: N3Parser [(ScopedName,[RDFLabel])]
varModList =
do { symbol "("
; vms <- sepBy varMod (symbol ",")
; symbol ")"
; return vms
}
<|>
do { vm <- varMod
; return [vm]
}
varMod :: N3Parser (ScopedName,[RDFLabel])
varMod =
do { rn <- uriRef2
; vns <- many varid
; return (rn,vns)
}
----------------------------------------------------------------------
-- SwishState helper functions
----------------------------------------------------------------------
--
-- The functions below operate in the SwishStateIO monad, and are used
-- to assemble an executable version of the parsed script.
ssAddReturnFormula ::
ScopedName -> SwishStateIO (Either String RDFGraph)
-> SwishStateIO (Either String RDFFormula)
ssAddReturnFormula nam gf =
do { egr <- gf
; ssAddGraph nam [return egr]
; return $ liftM (Formula nam) egr
}
ssAddGraph ::
ScopedName -> [SwishStateIO (Either String RDFGraph)]
-> SwishStateIO ()
ssAddGraph nam gf =
let errmsg = "Graph/list not added: "++show nam++"; "
in
do { esg <- sequence gf -- [Either String RDFGraph]
; let egs = sequence esg -- Either String [RDFGraph]
; let fgs = case egs of
Left er -> setError (errmsg++er)
Right gs -> modGraphs (mapReplaceOrAdd (NamedGraph nam gs))
; modify fgs
}
ssGetGraph :: ScopedName -> SwishStateIO (Either String RDFGraph)
ssGetGraph nam =
do { grs <- ssGetList nam
; return $ liftM head grs
}
ssGetFormula :: ScopedName -> SwishStateIO (Either String RDFFormula)
ssGetFormula nam = gets find
where
find st = case findFormula nam st of
Nothing -> Left ("Formula not present: "++show nam)
Just gr -> Right $ gr
ssGetList :: ScopedName -> SwishStateIO (Either String [RDFGraph])
ssGetList nam = gets find
where
find st = case findGraph nam st of
Nothing -> Left ("Graph or list not present: "++show nam)
Just grs -> Right $ grs
ssRead :: ScopedName -> Maybe String -> SwishStateIO ()
ssRead nam muri = ssAddGraph nam [ssReadGraph muri]
ssReadGraph :: Maybe String -> SwishStateIO (Either String RDFGraph)
ssReadGraph muri =
do { inp <- getResourceData muri
; return $ gf inp
}
where
gf inp = case inp of
Left es -> Left es
Right is -> parseAnyfromString document muri is
ssWriteList ::
Maybe String -> SwishStateIO (Either String [RDFGraph]) -> String
-> SwishStateIO ()
ssWriteList muri gf comment =
do { esgs <- gf
; case esgs of
Left er -> modify $ setError ("Cannot write list: "++er)
Right [gr] -> ssWriteGraph muri gr comment
Right grs -> sequence_ writegrs where
writegrs = if null grs
then [putResourceData Nothing ("+ Swish: Writing empty list"++)]
else map writegr (zip [0..] grs)
writegr (n,gr) = ssWriteGraph (murin muri n) gr
("["++show n++"] "++comment)
murin Nothing _ = Nothing
murin (Just uri) n = Just (inituri++show n++lasturi)
where
splituri1 = splitBy (=='/') uri
splituri2 = splitBy (=='.') (lastseg splituri1)
inituri = concat (initseg splituri1 ++ initseg splituri2)
lasturi = lastseg splituri2
}
splitBy :: (a->Bool) -> [a] -> [[a]]
splitBy _ [] = []
splitBy p (s0:str) = let (s1,sr) = break p str in
(s0:s1):splitBy p sr
lastseg :: [[a]] -> [a]
lastseg [] = []
lastseg [as] = []
lastseg ass = last ass
initseg :: [[a]] -> [[a]]
initseg [] = []
initseg [as] = [as]
initseg ass = init ass
ssWrite ::
Maybe String -> SwishStateIO (Either String RDFGraph) -> String
-> SwishStateIO ()
ssWrite muri gf comment =
do { esg <- gf
; case esg of
Left er -> modify $ setError ("Cannot write graph: "++er)
Right gr -> ssWriteGraph muri gr comment
}
ssWriteGraph :: Maybe String -> RDFGraph -> String -> SwishStateIO ()
ssWriteGraph muri gr comment =
putResourceData muri ((c++) . (formatGraphAsShowS gr))
where
c = "# "++comment++"\n"
ssMerge ::
ScopedName -> [SwishStateIO (Either String RDFGraph)]
-> SwishStateIO ()
ssMerge nam gfs =
let errmsg = "Graph merge not defined: "++show nam++"; "
in
do { esg <- sequence gfs -- [Either String RDFGraph]
; let egs = sequence esg -- Either String [RDFGraph]
; let fgs = case egs of
Left er -> setError (errmsg++er)
Right [] -> setError (errmsg++"No graphs to merge")
Right gs -> modGraphs (mapReplaceOrAdd (NamedGraph nam [g]))
where g = foldl1 merge gs
; modify fgs
}
ssCompare :: ScopedName -> ScopedName -> SwishStateIO ()
ssCompare n1 n2 =
do { g1 <- ssGetGraph n1
; g2 <- ssGetGraph n2
; when (g1 /= g2) (modify $ setExitcode (ExitFailure 1))
}
ssAssertEq :: ScopedName -> ScopedName -> String -> SwishStateIO ()
ssAssertEq n1 n2 comment =
let er1 = ":\n Graph or list compare not performed: invalid graph/list."
in
do { g1 <- ssGetList n1
; g2 <- ssGetList n2
; case (g1,g2) of
(Left er,_) -> modify $ setError (comment++er1++"\n "++er)
(_,Left er) -> modify $ setError (comment++er1++"\n "++er)
(Right gr1,Right gr2) ->
when (not $ equiv gr1 gr2) $ modify $
setError (comment++":\n Graph "++show n1
++" differs from "++show n2++".")
}
ssAssertIn :: ScopedName -> ScopedName -> String -> SwishStateIO ()
ssAssertIn n1 n2 comment =
let er1 = ":\n Membership test not performed: invalid graph."
er2 = ":\n Membership test not performed: invalid list."
in
do { g1 <- ssGetGraph n1
; g2 <- ssGetList n2
; case (g1,g2) of
(Left er,_) -> modify $ setError (comment++er1++"\n "++er)
(_,Left er) -> modify $ setError (comment++er2++"\n "++er)
(Right gr,Right gs) ->
when (not $ elem gr gs) $ modify $
setError (comment++":\n Graph "++show n1
++" not a member of "++show n2)
}
-- Note: this is probably incomplete, though it should work in simple cases.
-- A complete solution would have the binding modifiers subject to
-- re-arrangement to suit the actual bound variables encountered.
-- See VarBinding.findCompositions and VarBinding.findComposition
--
-- This code should be adequate if variable bindings are always used
-- in combinations consisting of a single modifier followed by any number
-- of filters.
--
ssDefineRule ::
ScopedName
-> [SwishStateIO (Either String RDFGraph)]
-> (SwishStateIO (Either String RDFGraph))
-> [(ScopedName,[RDFLabel])]
-> SwishStateIO ()
ssDefineRule rn agfs cgf vmds =
let errmsg1 = "Rule definition error in antecedent graph(s): "
errmsg2 = "Rule definition error in consequent graph: "
errmsg3 = "Rule definition error in variable modifier(s): "
errmsg4 = "Incompatible variable binding modifier sequence"
in
do { aesg <- sequence agfs -- [Either String RDFGraph]
; let ags = sequence aesg :: Either String [RDFGraph]
; cg <- cgf -- Either String RDFGraph
; let vmfs = map ssFindVarModify vmds
; evms <- sequence vmfs -- [Either String RDFVarBindingModify]
; let vms = sequence evms :: Either String [RDFVarBindingModify]
; let frl = case (ags,cg,vms) of
(Left er,_,_) -> setError (errmsg1++er)
(_,Left er,_) -> setError (errmsg2++er)
(_,_,Left er) -> setError (errmsg3++er)
(Right agrs,Right cgr,Right vbms) ->
let
newRule vm = makeRDFClosureRule rn agrs cgr vm
in
case composeSequence vbms of
Just vm -> modRules (mapReplaceOrAdd (newRule vm))
Nothing -> setError errmsg4
; modify frl
}
ssFindVarModify ::
(ScopedName,[RDFLabel]) -> SwishStateIO (Either String RDFVarBindingModify)
ssFindVarModify (nam,lbs) = gets $ findVarMod nam lbs
where
findVarMod nam lbs st = case findOpenVarModify nam st of
Just ovbm -> Right (ovbm lbs)
Nothing -> Left ("Undefined modifier: "++show nam)
ssDefineRuleset ::
ScopedName
-> [ScopedName]
-> [ScopedName]
-> SwishStateIO ()
ssDefineRuleset sn ans rns =
let errmsg1 = "Error in ruleset axiom(s): "
errmsg2 = "Error in ruleset rule(s): "
in
do { let agfs = sequence $ map ssGetFormula ans
:: SwishStateIO [(Either String RDFFormula)]
; aesg <- agfs -- [Either String RDFFormula]
; let eags = sequence aesg :: Either String [RDFFormula]
; let erlf = sequence $ map ssFindRule rns
:: SwishStateIO [(Either String RDFRule)]
; rles <- erlf -- [Either String RDFRule]
; let erls = sequence rles :: (Either String [RDFRule])
; let frs = case (eags,erls) of
(Left er,_) -> setError (errmsg1++er)
(_,Left er) -> setError (errmsg2++er)
(Right ags,Right rls) ->
modRulesets (mapReplaceOrAdd rs)
where
rs = makeRuleset (snScope sn) ags rls
; modify frs
}
ssFindRule :: ScopedName -> SwishStateIO (Either String RDFRule)
ssFindRule nam = gets $ find
where
find st = case findRule nam st of
Nothing -> Left ("Rule not found: "++show nam)
Just rl -> Right rl
ssDefineConstraints ::
ScopedName
-> [SwishStateIO (Either String RDFGraph)]
-> [ScopedName]
-> SwishStateIO ()
ssDefineConstraints sn cgfs dtns =
let errmsg1 = "Error in constraint graph(s): "
errmsg2 = "Error in datatype(s): "
in
do { cges <- sequence cgfs -- [Either String RDFGraph]
; let ecgs = sequence cges :: Either String [RDFGraph]
; let ecgr = case ecgs of
Left er -> Left er
Right [] -> Right $ emptyRDFGraph
Right grs -> Right $ foldl1 merge grs
; edtf <- sequence $ map ssFindDatatype dtns
-- [Either String RDFDatatype]
; let edts = sequence edtf :: Either String [RDFDatatype]
; let frs = case (ecgr,edts) of
(Left er,_) -> setError (errmsg1++er)
(_,Left er) -> setError (errmsg2++er)
(Right cgr,Right dts) ->
modRulesets (mapReplaceOrAdd rs)
where
rs = makeRuleset (snScope sn) [] rls
rls = concatMap (flip typeMkRules cgr) dts
; modify frs
}
ssFindDatatype :: ScopedName -> SwishStateIO (Either String RDFDatatype)
ssFindDatatype nam = gets $ find
where
find st = case findDatatype nam st of
Nothing -> Left ("Datatype not found: "++show nam)
Just dt -> Right dt
ssCheckProof ::
ScopedName -- proof name
-> [ScopedName] -- ruleset names
-> SwishStateIO (Either String RDFFormula) -- input formula
-> [Either String [RDFRuleset] -- proof step from rulesets
-> SwishStateIO (Either String RDFProofStep)]
-> SwishStateIO (Either String RDFFormula) -- result formula
-> SwishStateIO ()
ssCheckProof pn sns igf stfs rgf =
let
infmsg1 = "Proof satisfied: "
errmsg1 = "Error in proof ruleset(s): "
errmsg2 = "Error in proof input: "
errmsg3 = "Error in proof step(s): "
errmsg4 = "Error in proof goal: "
errmsg5 = "Proof not satisfied: "
proofname = " (Proof "++show pn++")"
in
do { let rs1 = map ssFindRuleset sns :: [SwishStateIO (Either String RDFRuleset)]
; rs2 <- sequence $ rs1 -- [Either String RDFRuleset]
; let erss = sequence rs2 :: Either String [RDFRuleset]
; eig <- igf -- Either String RDFFormula
; let st1 = sequence $ flist stfs erss :: SwishStateIO [Either String RDFProofStep]
; st2 <- st1 -- [Either String RDFProofStep]
; let ests = sequence st2 :: Either String [RDFProofStep]
; erg <- rgf -- Either String RDFFormula
; let proof = case (erss,eig,ests,erg) of
(Left er,_,_,_) -> Left (errmsg1++er++proofname)
(_,Left er,_,_) -> Left (errmsg2++er++proofname)
(_,_,Left er,_) -> Left (errmsg3++er++proofname)
(_,_,_,Left er) -> Left (errmsg4++er++proofname)
(Right rss, Right ig, Right sts, Right rg) ->
Right (makeRDFProof rss ig rg sts)
; when False $ case proof of
(Left er) -> return ()
(Right pr) -> putResourceData Nothing $
(("Proof "++show pn++"\n")++)
. showsProof "\n" pr
; let checkproof = case proof of
(Left er) -> setError er
(Right pr) ->
case explainProof pr of
Nothing -> setInfo (infmsg1++show pn)
Just ex -> setError (errmsg5++show pn++", "++ex)
{-
if not $ checkProof pr then
setError (errmsg5++show pn)
else
setInfo (infmsg1++show pn)
-}
; modify $ checkproof
}
ssCheckStep ::
ScopedName -- rule name
-> [SwishStateIO (Either String RDFFormula)] -- antecedent graph formulae
-> SwishStateIO (Either String RDFFormula) -- consequent graph formula
-> Either String [RDFRuleset] -- rulesets
-> SwishStateIO (Either String RDFProofStep) -- resulting proof step
ssCheckStep _ _ _ (Left er) = return $ Left er
ssCheckStep rn eagf ecgf (Right rss) =
let
errmsg1 = "Rule not in proof step ruleset(s): "
errmsg2 = "Error in proof step antecedent graph(s): "
errmsg3 = "Error in proof step consequent graph: "
in
do { let mrul = getMaybeContextRule rn rss :: Maybe RDFRule
; esag <- sequence $ eagf -- [Either String RDFFormula]]
; let eags = sequence $ esag :: Either String [RDFFormula]
; ecg <- ecgf -- Either String RDFFormula
; let est = case (mrul,eags,ecg) of
(Nothing,_,_) -> Left (errmsg1++show rn)
(_,Left er,_) -> Left (errmsg2++er)
(_,_,Left er) -> Left (errmsg3++er)
(Just rul,Right ags,Right cg) ->
Right $ makeRDFProofStep rul ags cg
; return est
}
ssFwdChain ::
ScopedName -- ruleset name
-> ScopedName -- rule name
-> [SwishStateIO (Either String RDFGraph)] -- antecedent graphs
-> ScopedName -- consequent graph name
-> NamespaceMap -- prefixes for new graph
-> SwishStateIO ()
ssFwdChain sn rn agfs cn prefs =
let
errmsg1 = "FwdChain rule error: "
errmsg2 = "FwdChain antecedent error: "
in
do { erl <- ssFindRulesetRule sn rn
; aesg <- sequence agfs -- [Either String RDFGraph]
; let eags = sequence aesg :: Either String [RDFGraph]
; let fcr = case (erl,eags) of
(Left er,_) -> setError (errmsg1++er)
(_,Left er) -> setError (errmsg2++er)
(Right rl,Right ags) ->
modGraphs (mapReplaceOrAdd (NamedGraph cn [cg]))
where
cg = case fwdApply rl ags of
[] -> emptyRDFGraph
grs -> setNamespaces prefs $ foldl1 add grs
; modify fcr
}
ssFindRulesetRule ::
ScopedName -> ScopedName -> SwishStateIO (Either String RDFRule)
ssFindRulesetRule sn rn = gets $ find
where
find st = case findRuleset sn st of
Nothing -> Left ("Ruleset not found: "++show sn)
Just rs -> find1 rs
find1 rs = case getRulesetRule rn rs of
Nothing -> Left ("Rule not in ruleset: "++show sn++": "++show rn)
Just rl -> Right rl
ssFindRuleset ::
ScopedName -> SwishStateIO (Either String RDFRuleset)
ssFindRuleset sn = gets $ find
where
find st = case findRuleset sn st of
Nothing -> Left ("Ruleset not found: "++show sn)
Just rs -> Right rs
ssBwdChain ::
ScopedName -- ruleset name
-> ScopedName -- rule name
-> SwishStateIO (Either String RDFGraph) -- consequent graphs
-> ScopedName -- antecedent alts name
-> NamespaceMap -- prefixes for new graphs
-> SwishStateIO ()
ssBwdChain sn rn cgf an prefs =
let
errmsg1 = "BwdChain rule error: "
errmsg2 = "BwdChain goal error: "
in
do { erl <- ssFindRulesetRule sn rn
; ecg <- cgf -- Either String RDFGraph
; let fcr = case (erl,ecg) of
(Left er,_) -> setError (errmsg1++er)
(_,Left er) -> setError (errmsg2++er)
(Right rl,Right cg) ->
modGraphs (mapReplaceOrAdd (NamedGraph an ags))
where
ags = map mergegr (bwdApply rl cg)
mergegr grs = case grs of
[] -> emptyRDFGraph
_ -> setNamespaces prefs $ foldl1 add grs
; modify fcr
}
-- Temporary implementation: just read local file WNH
-- (Add logic to separate filenames from URIs, and
-- attempt HTTP GET, or similar.)
getResourceData :: Maybe String -> SwishStateIO (Either String String)
getResourceData muri =
case muri of
Nothing -> fromStdin
Just uri -> fromUri uri
where
fromStdin =
do { dat <- lift getContents
; return $ Right dat
}
fromUri uri =
do { -- WNH b <- lift $ doesFileExist uri
-- WNH; if not b then
-- WNH return $ Left ("File not found: "++uri)
-- WNHelse
fromFile uri
}
fromFile uri =
do { dat <- lift $ readFile uri
; return $ Right dat
}
-- Temporary implementation: just write local file
-- (Need to add logic to separate filenames from URIs, and
-- attempt HTTP PUT, or similar.)
putResourceData :: Maybe String -> ShowS -> SwishStateIO ()
putResourceData muri gsh =
do { ios <- lift $ IO.try $
case muri of
Nothing -> toStdout
Just uri -> toUri uri
; case ios of
Left ioe -> modify $ setError
("Error writing graph: "++
IO.ioeGetErrorString ioe)
Right a -> return a
}
where
toStdout = putStrLn gstr
toUri uri = writeFile uri gstr
gstr = gsh ""
--------------------------------------------------------------------------------
--
-- Copyright (c) 2003, G. KLYNE. All rights reserved.
--
-- This file is part of Swish.
--
-- Swish is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- Swish 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 Swish; if not, write to:
-- The Free Software Foundation, Inc.,
-- 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
--------------------------------------------------------------------------------
-- $Source: /file/cvsdev/HaskellRDF/SwishScript.hs,v $
-- $Author: graham $
-- $Revision: 1.10 $
-- $Log: SwishScript.hs,v $
-- Revision 1.10 2004/02/09 22:22:44 graham
-- Graph matching updates: change return value to give some indication
-- of the extent match achieved in the case of no match.
-- Added new module GraphPartition and test cases.
-- Add VehicleCapcity demonstration script.
--
-- Revision 1.9 2004/01/07 19:49:13 graham
-- Reorganized RDFLabel details to eliminate separate language field,
-- and to use ScopedName rather than QName.
-- Removed some duplicated functions from module Namespace.
--
-- Revision 1.8 2003/12/19 15:51:41 graham
-- Sync minor edits
--
-- Revision 1.7 2003/12/12 14:12:01 graham
-- Add comment about parser structure to SwishScript.hs
--
-- Revision 1.6 2003/12/11 19:11:07 graham
-- Script processor passes all initial tests.
--
-- Revision 1.5 2003/12/10 14:43:00 graham
-- Backup.
--
-- Revision 1.4 2003/12/10 03:48:58 graham
-- SwishScript nearly complete: BwdChain and PrrofCheck to do.
--
-- Revision 1.3 2003/12/08 23:55:36 graham
-- Various enhancements to variable bindings and proof structure.
-- New module BuiltInMap coded and tested.
-- Script processor is yet to be completed.
--
-- Revision 1.2 2003/12/05 02:31:32 graham
-- Script parsing complete.
-- Some Swish script functions run successfully.
-- Command execution to be completed.
--
-- Revision 1.1 2003/12/04 02:53:28 graham
-- More changes to LookupMap functions.
-- SwishScript logic part complete, type-checks OK.
--
| amccausl/Swish | Swish/HaskellRDF/SwishScript.hs | lgpl-2.1 | 37,023 | 0 | 24 | 13,822 | 8,454 | 4,381 | 4,073 | 681 | 8 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
module Main where
import GHC.Generics ( Generic1 )
import Dyno.Vectorize
import Dyno.SimpleOcp
-- state
data X a = X { xTheta :: a, xOmega :: a }
deriving (Functor, Generic1, Show)
instance Applicative X where {pure = vpure; (<*>) = vapply}
instance Vectorize X
-- controls
data U a = U { uTorque :: a }
deriving (Functor, Generic1, Show)
instance Applicative U where {pure = vpure; (<*>) = vapply}
instance Vectorize U
pendOde :: Floating a => X a -> U a -> X a
pendOde (X theta omega) (U torque) = X thetaDot omegaDot
where
thetaDot = omega
omegaDot = torque + 9.8 * sin theta
ocp :: SimpleOcp X U
ocp =
SimpleOcp
{ ode = pendOde
, objective = \(X _ omega) (U torque) -> omega * omega + torque * torque
, xBounds = X (-pi, pi) (-5, 5)
, uBounds = U (-50, 50)
, xInitial = X {xTheta = pi/2, xOmega = 0}
, xFinal = X {xTheta = 0, xOmega = 0}
, endTime = 1
, initialGuess = \t -> X ((1-t) * pi/2) (pi/1)
}
main :: IO ()
main = do
result <- solveOcp ocp
case result of
Left msg -> putStrLn $ "failed with " ++ msg
Right xus -> print xus
| ghorn/dynobud | dynobud/examples/ToyOcp.hs | lgpl-3.0 | 1,192 | 0 | 13 | 295 | 496 | 278 | 218 | 36 | 2 |
{-# LANGUAGE FlexibleInstances, DeriveGeneric, DeriveAnyClass #-}
import FPPrac.Trees -- Contains now also the function toRoseTree. Re-install it!
import GHC.Generics -- Necessary for correct function of FPPrac
import FP_Grammar
import FP_TypesEtc -- Extend the file TypesEtc with your own alphabet
import FP_ParserGen (parse) -- Touching this file leaves you at your own devices
import Tokenizer
--Exercise 3
data Tree = Node Alphabet [Tree]
| Leaf (Alphabet,String)
deriving (Eq,Show,Generic,ToRoseTree)
{-
data ParseTree = PLeaf Token
| PNode Alphabet [ParseTree]
| PError ParseTree [Alphabet] Alphabet String Int
deriving (Eq,Show,Generic,ToRoseTree)
-}
ppt :: ParseTree -> Tree
ppt (PLeaf token) = Leaf token
ppt (PNode alpha [t1]) = ppt t1
ppt (PNode alpha trees) = Node alpha (map ppt trees)
pp :: Tree -> RoseTree
pp (Leaf (a,b)) = RoseNode (show b) []
pp (Node alpha trees) = RoseNode (show alpha) (map pp trees)
showppt str = showRoseTree $ toRoseTree $ ppt $ parse grammar Expr (tokenizer str)
showpp str = showRoseTree $ pp $ ppt $ parse grammar Stmnt (tokenizer str)
--Exercise 4
{- 4b
Calc EQ -> returns 0/1
na condition -> before begin of 'then' -> skip to else JUMP
before begin of 'else -> skip to remainder CONDJUMP
when conditions are met for the jump, it will either only increase PC by one, or by
enough to skip the entire desired segment.
-}
| Pieterjaninfo/PP | FP/block3s6.hs | unlicense | 1,524 | 0 | 8 | 382 | 312 | 162 | 150 | 19 | 1 |
{-
Copyright 2015 Tristan Aubrey-Jones
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-|
Copyright : (c) Tristan Aubrey-Jones, 2015
License : Apache-2
Maintainer : developer@flocc.net
Stability : experimental
For more information please see <http://www.flocc.net/>
-}
module Compiler.Back.Maps.VTemplates where
import Data.Maybe (fromMaybe)
import Control.Monad.State.Strict (gets)
import Control.Monad.Catch
import Compiler.Front.Common (ShowP(..))
import Compiler.Back.Graph
import Compiler.Back.GenDecls
import Compiler.Back.Gen
import Compiler.Back.Generators
import Compiler.Back.Templates
import Compiler.Back.Helper
import Compiler.Back.CartTopology
-- sorted vector templates
vmapTemplates :: (Monad m, MonadCatch m) => [(Id, Template m)]
vmapTemplates = [
("readVMap", t01),
("saveVMap", t02),
("sortVMap", t03),
("repartVMap4", t04),
("mirrVMap", t08),
("maxVMap", t05),
("minVMap", t06),
("crossVMaps11", t07),
("unionVMaps1", t09),
--("unionVMaps2", t10),
("unionVMaps3", t13),
("countVMap", t11),
("countVMapMirr", t12)
]
-- |readVMap template
t01 :: (Monad m, MonadCatch m) => Template m
t01 (Lf (LfTy "DMap" [mode1, kt1, vt1, ordF1, parF1, parD1, mirD1]) :->
Lf (LfTy "DMap" [mode2, kt2, vt2, ordF2, parF2, parD2, mirD2]))
(LFun _ inN outN)
| mode1 == nameTy "Vec" && mode2 == nameTy "Stm" &&
kt1 == kt2 && vt1 == vt2 = do
-- check in and out dists are same
-- assertM (return $ parF1 == parF2) $ "ERROR: dVecMapToDStreamLocal: par funs don't match:\n" ++ (show parF1) ++ "\n" ++ (show parF2)
assertM (return $ parD1 == parD2) "par dims don't match"
assertM (return $ mirD1 == mirD2) "mirror dims don't match"
-- get input var name
getVar (Lf "inVec") inN outVarName
(VarV _ (Lf inVecNam)) <- getLocalVal "inVec"
-- declare loop iterator and end iterator
vecmapTyMb <- getValMaybe inN "vecmapType"
let iterTy = maybe (Lf $ LfTy "TypeOf" [nameTy $ inVecNam ++ "->csbegin()"]) (\ty -> Lf $ LfTy "ConstIter" [fromTyVal "readVMap" ty]) vecmapTyMb
newVar (Lf "it") iterTy
newVar (Lf "end") iterTy
varExp "itBegin" "inVec" "<v>->csbegin()" iterTy
varExp "itEnd" "inVec" "<v>->csend()" iterTy
runGenV "declareVarInit" "decIt" [Lf "it", Lf "itBegin"]
runGenV "declareVarInit" "decEnd" [Lf "end", Lf "itEnd"]
-- declare stream var
varExp "itKey" "it" "<v>->v0" kt1
varExp "itVal" "it" "<v>->v1" vt1
setVar outN "streamVar" $ Tup [Lf "itKey", Lf "itVal"]
-- if we know the maps size, pass it on
ifVarExists "count" inN "count" (setVar outN "count" $ Lf "count") (return ())
-- when gen is called, generate loop
setFun outN "gen" nt (\_ -> do
-- gen consumers
callAll outN "genConsumers" nt
ifVarsExist [("init", outN, "initStream"), ("fin", outN, "finStream"), ("consume", outN, "consumers")] (do
-- local data pred
genHasDataPred "hasData" parD1 mirD1
-- output code
outMain $
"<init>\n"++
"if (<hasData>) {\n"++
"<decIt><decEnd>\n"++
"for (; <it> != <end>; <it>++) {\n"++
" <consume>\n"++
"}\n"++
"}\n"++
"<fin>\n"
) (return ())
return ())
t01 t n = terr' t n
-- |saveVMap template
t02 :: (Monad m, MonadCatch m) => Template m
t02 ((Lf (LfTy "DMap" [mode1, keyT1, valT1, ordF1, parF1, parD1, mirD1])) :->
(Lf (LfTy "DMap" [mode2, keyT2, valT2, ordF2, parF2, parD2, mirD2])))
(LFun _ inN outN)
| keyT1 == keyT2 && valT1 == valT2 &&
mode1 == nameTy "Stm" && mode2 == nameTy "Vec" = do
-- check in and out dims are the same
assertM (return $ parD1 == parD2) $ "par dims don't match"
assertM (return $ mirD1 == mirD2) $ "mirror dims don't match"
-- get input stream vars
getVar (Lf "svar") inN "streamVar"
-- declare output element struct
-- TODO only copy if svar is not a struct...
newStructVar (Lf "el") $ Tup [keyT1, valT1]
runGenV "declareVar" "decEl" [Lf "el"]
runGenV "assignVar" "appCopy" [Lf "el", Lf "svar"]
-- declare output vec var
let (Lf (FunTy ordFun)) = ordF1
(ordDomTy :-> ordRanTy) <- getGraphTy ordFun
projFunTy <- genStaticFun ordFun (Just $ Tup [keyT1, valT1]) Nothing "inline static"
let outTy = Lf $ LfTy "VecMap" [Tup [keyT1, valT1], keyT1, ordRanTy, projFunTy]
tn <- getTemplateName
outmapTyName <- genTypeName outTy >>= (return . (fromMaybe (error $ "Templates:" ++ tn ++ " can't get type name of " ++ (show outTy))))
varExp "newVecmap" "" ("new " ++ outmapTyName) (Lf $ LfTy "Ptr" [outTy])
ifnVarInit "decOut" outVarName (Lf "outVec") (Lf $ LfTy "SPtr" [outTy]) (Just $ Tup [Lf "newVecmap"])
-- pass along vector type to consumers
setVal outN "vecmapType" (TyV outTy)
-- if we know the maps size, pass it on
ifVarExists "count" inN "count" (setVar outN "count" $ Lf "count") (return ())
-- when gen is called, generate loop
setFun outN "genConsumers" nt (\_ -> do
-- add blocks to stream producer
outputDecl outN "// begin <tem> decl\n<decOut>// end <tem> decl\n"
addCode inN "initStream" {-"<decOut>"-} "<decEl>"
addCode inN "consumers" $ "// BEGIN <tem> consume:\n<appCopy>\n<outVec>->push_back(<el>);\n// END <tem> consume\n"
addCode inN "finStream" "<outVec>->setDistinct();\n<outVec>->setSecondarySorted();\n"
return ())
t02 t n = terr' t n
-- |sortVMap template
t03 :: (Monad m, MonadCatch m) => Template m
t03 (Lf (LfTy "DMap" [mode1, kt1, vt1, ordF1, parF1, parD1, mirD1]) :->
Lf (LfTy "DMap" [mode2, kt2, vt2, ordF2, parF2, parD2, mirD2]))
(LFun _ inN outN)
| mode1 == nameTy "Vec" && mode2 == nameTy "Vec" &&
kt1 == kt2 && vt1 == vt2 = do
-- check in and out dists are same
assertM (return $ parD1 == parD2) "par dims don't match"
assertM (return $ mirD1 == mirD2) "mirror dims don't match"
-- generate proj function class for ordF2
let (Lf (FunTy ordFun)) = ordF2
(ordDomTy :-> ordRanTy) <- getGraphTy ordFun
projFunTy <- genStaticFun ordFun (Just $ Tup [kt2, vt2]) Nothing "inline static"
-- get input and output var names
getVar (Lf "inVec") inN outVarName
let outTy = Lf $ LfTy "VecMap" [Tup [kt1, vt1], kt1, ordRanTy, projFunTy] -- TODO change second kt1 to return type of orodF1
tn <- getTemplateName
outmapTyName <- genTypeName outTy >>= (return . (fromMaybe (error $ "Templates:" ++ tn ++ " can't get type name of " ++ (show outTy))))
varExp "newVecmap" "" ("new " ++ outmapTyName) (Lf $ LfTy "Ptr" [outTy])
ifnVarInit "decOut" outVarName (Lf "outVec") (Lf $ LfTy "SPtr" [outTy]) (Just $ Tup [Lf "newVecmap"])
-- pass along vector type to consumers
setVal outN "vecmapType" (TyV outTy)
-- if we know the maps size, pass it on
ifVarExists "count" inN "count" (setVar outN "count" $ Lf "count") (return ())
-- make dbgval msgs
dbgMsg1 <- dbgVal "beforeCount" "<inVec>->size()"
dbgMsg2 <- dbgVal "afterCount" "<outVec>->size()"
-- when gen is called, generate loop
setFun outN "gen" nt (\_ -> do
-- local data pred
genHasDataPred "hasData" parD1 mirD1
-- output code
outputDecl outN "// begin <tem> decl\n<decOut>// end <tem> decl\n"
outMain $
"// sort sec key type: "++ (show ordRanTy) ++ "\n"++
"if (<hasData>) {\n"++
dbgMsg1 ++ "\n" ++
"<outVec>->assign(<inVec>);"++
dbgMsg2 ++ "\n" ++
"}\n"
return ())
t03 t n = terr' t n
-- TODO change so maintains same mirroring.
-- |repartVMap4 template - does an alltoallv to redistribute using fst (output unsorted)
t04 :: (Monad m, MonadCatch m) => Template m
t04 (Lf (LfTy "DMap" [mode1, kt1, vt1, ordF1, parF1, parD1, mirD1]) :->
Lf (LfTy "DMap" [mode2, kt2, vt2, ordF2, parF2@(Lf (FunTy parG)), parD2, mirD2]))
(LFun _ inN outN)
| kt1 == kt2 && vt1 == vt2 &&
mode1 == nameTy "Stm" && mode2 == nameTy "Vec" = do
tn <- getTemplateName
-- check in and out dims are the same
assertM (return $ parD1 == parD2) "par dims don't match"
--assertM (return $ mirD1 == mirD2) "mirror dims don't match"
-- create local cart comm
genSubCartV "localComm" "localRanks" parD1 -- use part dim, as alltoallv goes along part dims
varExp "localCommPtr" "localComm" "&(<v>)" intTy
-- get input stream vars
getVar (Lf "svar") inN "streamVar"
-- copy to struct for storage
newStructVar (Lf "structVar") $ Tup [kt1, vt1]
runGenV "declareVar" "decStructVar" [Lf "structVar"]
runGenV "assignVar" "packVar" [Lf "structVar", Lf "svar"]
-- declare proj function, for the vecmap
let (Lf (FunTy ordFun)) = ordF2
--error $ "repartVMap part fun:\n" ++ (show parG) ++ "\n\nord fun:\n" ++ (show ordFun)
(ordDomTy :-> ordRanTy) <- getGraphTy ordFun
projFunTy <- genStaticFun ordFun (Just $ Tup [kt2, vt2]) Nothing "inline static"
-- NOTE: output vec map will be sorted in same way as input, so pass this info to vecmap constructor...
-- TODO ...
-- declare vecmap output and alltoall stream
let outTy = Lf $ LfTy "VecMap" [Tup [kt2, vt2], kt2, ordRanTy, projFunTy]
setVal outN "vecmapType" (TyV outTy)
outmapTyName <- genTypeName outTy >>= (return . (fromMaybe (error $ "Templates:" ++ tn ++ " can't get type name of " ++ (show outTy))))
varExp "newVecmap" "" ("new " ++ outmapTyName) (Lf $ LfTy "Ptr" [outTy])
ifnVarInit "decOut" outVarName (Lf "outmap") (Lf $ LfTy "SPtr" [outTy]) (Just $ Tup [Lf "newVecmap"])
newVar (Lf "repart") (Lf $ LfTy "Reparter" [Tup [kt2, vt2], outTy])
runGenV "declareVarInit" "decRedist" [Lf "repart", Tup [Lf "localCommPtr", Lf "outmap"]]
-- apply output part function (fst), and hash it to get rank should live on
(parInTy :-> parOutTy) <- getGraphTy parG
newVar (Lf "pval") parOutTy
runGenV "declareVar" "decPval" [Lf "pval"]
genTyFunV "appPf" parF2 (Lf "svar") n0 (Lf "pval")
newVar (Lf "rank") intTy
runGenV "declareVar" "decRank" [Lf "rank"]
varToNodeRankV "getRank" (Lf "pval") "rank" parD1 parD1 mirD1
-- make dbgval msg
dbgMsg1 <- dbgVal "count" "<repart>.getConsumer()->size()"
-- when gen is called, generate redist code
setFun outN "genConsumers" nt (\_ -> do
-- add consumers to producer
outputDecl outN "// begin <tem> decl\n<decOut>// end <tem> decl\n"
addCode inN "initStream" $ "// BEGIN <tem> init\n<decStructVar>" ++ -- <decOut>" ++
-- "<outmap>->setSecondarySorted();\n" ++ -- as stream is sorted already
"<decRedist>\n// END <tem> init\n"
addCode inN "finStream" $
"// BEGIN <tem> fin\n<repart>.finish();\n"++dbgMsg1++
"\n// END <tem> fin\n"
addCode inN "consumers" $
"// BEGIN <tem> consume\n<packVar>\n<decPval>\n"++
"// App part fun:\n<appPf>\n// App part fun end\n<decRank>\n<getRank>\n"
++"<repart>.push_back(<rank>, <structVar>);\n//END <tem> consume\n"
return ())
t04 t n = terr' t n
-- |mirrVMap template -- TODO another version that merges sorted subvectors
-- |basically does an allGather
t08 :: (Monad m, MonadCatch m) => Template m
t08 (Lf (LfTy "DMap" [mode1, kt1, vt1, ordF1, parF1, parD1, mirD1]) :->
Lf (LfTy "DMap" [mode2, kt2, vt2, ordF2, parF2, parD2, mirD2]))
(LFun _ inN outN)
| mode1 == nameTy "Vec" && mode2 == nameTy "Vec" &&
kt1 == kt2 && vt1 == vt2 = do
-- check in and out dists are DIFFERENT
--assertM (return $ parD1 /= parD2) "par dims match!"
--assertM (return $ mirD1 /= mirD2) "mirror dims match!"
-- generate proj function class for ordF2
let (Lf (FunTy ordFun)) = ordF2
(ordDomTy :-> ordRanTy) <- getGraphTy ordFun
projFunTy <- genStaticFun ordFun (Just $ Tup [kt2, vt2]) Nothing "inline static"
-- get input and output var names
getVar (Lf "inVec") inN outVarName
(VarV _ (Lf inVecNam)) <- getLocalVal "inVec"
-- (can't pass along TYPEOF(vec) because if consumer does TYPEOF(vec)::iterator it won't work)
ifVarExists "vecmapType" inN "vecmapType" (setVar outN "vecmapType" $ Lf "vecmapType") (return ())
-- declare output vecmap
vecmapTyMb <- getValMaybe inN "vecmapType"
let outTy = maybe (Lf $ LfTy "TypeOf" [nameTy inVecNam]) (fromTyVal "mirrVMap") vecmapTyMb
tn <- getTemplateName
outmapTyName <- genTypeName outTy >>= (return . (fromMaybe (error $ "Templates:" ++ tn ++ " can't get type name of " ++ (show outTy))))
varExp "newVecmap" "" ("new " ++ outmapTyName) (Lf $ LfTy "Ptr" [outTy])
ifnVarInit "decOut" outVarName (Lf "outVec") (Lf $ LfTy "SPtr" [outTy]) (Just $ Tup [Lf "newVecmap"])
-- if we know the map's size
ifVarExists "count" inN "count"
-- then pass it on
(setVar outN "count" $ Lf "count")
-- otherwise get it (since local size now = global size)
(do varExp "count" "outVec" "<v>->size()" intTy;
setVar outN "count" $ Lf "count")
-- make dbgval msgs
dbgMsg1 <- dbgVal "beforeCount" "<inVec>->size()"
dbgMsg2 <- dbgVal "afterCount" "<outVec>->size()"
-- when gen is called, generate loop
setFun outN "gen" nt (\_ -> do
-- local data pred
genHasDataPred "hasData" parD1 mirD1
genSubCartV "localComm" "localRanks" parD1
-- output code
outputDecl outN "// begin <tem> decl\n<decOut>\n// end <tem> decl"
outMain $
"// mirrvmap sec key type: "++ (show ordRanTy) ++ "\n"++
"if (<hasData>) {\n"++
(if parD1 == nullTy && mirD2 == nullTy
then (
"// pass through unchanged \n"++
"<outVec> = <inVec>;\n"
)
else (
dbgMsg1 ++ "\n" ++
" flocc::allGatherVecs(<inVec>->inner(), <outVec>->inner(), &<localComm>);\n"++
-- TODO do fast merge, rather than complete re-sort
" <outVec>->setDistinct();\n"++
" <outVec>->setUnsorted();\n"++
dbgMsg2 ++ "\n")) ++
"}\n"
return ())
t08 t n = terr' t n
-- gatherVMap :: DMap Vec k v of pf d m -> DMap Vec k v FNull FNull () ()
-- allgatherVMap :: DMap Vec k v of pf d m -> DMap Vec k v FNull FNull () (d,m)
-- it would be good to be able to say above pf => restriction of pf
-- and instead of d => (), d => d - d1
-- e.g. DMap Vec k v of pf d m -> DMap Vec k v FNull (pf - pf1(d1)) (d - d1) (m + d1)
-- bcastVMap :: DMap Vec k v of pf () () -> DMap Vec k v of FNull () m
-- scattVMap :: DMap Vec k v of pf () () -> DMap Vec k v of pf2 d () -- does of mean order of local parts, or order of whole?
-- mirrVMap :: DMap Vec k v of pf d m1 -> DMap Vec k v of pf d (m1,m2)
-- |countHVMap template
t11 :: (Monad m, MonadCatch m) => Template m
t11 (Lf (LfTy "DMap" [mode, kt, vt, sf, pf, pd, md]) :-> numTy)
(LFun _ inN outN)
| (mode == nameTy "Vec" || mode == nameTy "Hsh") && numTy == intTy = do
-- get input var name
getVar (Lf "inVec") inN outVarName
-- create output var if doesn't already exist
ifnVar "decOut" outVarName (Lf "cv") intTy
newVar (Lf "tmp") intTy
-- when gen is called, generate loop
setFun outN "gen" nt (\_ -> do
-- local data pred
genHasDataPred "hasData" pd md
-- if we know the list's length
ifVarExists "count" inN "count" (
-- then use listCount from producers
outMain $ "// <tem>\n<decOut><cv> = <count>;\n") (
-- else add code to count lists
outMain $
"// <tem>\n<decOut>\nint <tmp> = 0;"++
"if (<hasData>) <tmp> = <inVec>->size();\n"++
"MPI::COMM_WORLD.Allreduce(&<tmp>, &<cv>, 1, MPI::INT, MPI::SUM);\n")
return ())
t11 t n = terr' t n
-- |countHVMapMirr template
t12 :: (Monad m, MonadCatch m) => Template m
t12 (Lf (LfTy "DMap" [mode, kt, vt, sf, pf, pd, md]) :-> numTy)
(LFun _ inN outN)
| (mode == nameTy "Vec" || mode == nameTy "Hsh") && numTy == intTy = do
-- get input var name
getVar (Lf "inVec") inN outVarName
-- create output var if doesn't already exist
ifnVar "decOut" outVarName (Lf "cv") intTy
-- when gen is called, generate loop
setFun outN "gen" nt (\_ -> do
-- local data pred
genHasDataPred "hasData" pd md
-- if we know the list's length
ifVarExists "count" inN "count" (
-- then use listCount from producers
outMain $ "// <tem>\n<decOut><cv> = <count>;\n") (
-- else add code to count lists
outMain $ "// <tem>\n<decOut>\n<cv> = <inVec>->size();\n")
return ())
t12 t n = terr' t n
-- |maxVMap template
t05 :: (Monad m, MonadCatch m) => Template m
t05 (Tup [Tup [kt1, vt1] :-> wt1, Tup [wt2, wt3] :-> wt4, wt5,
Lf (LfTy "DMap" [mode1, kt2, vt2, ordF1, parF1, parD1, mirD1])] :-> wt6)
(LFun _ (LTup _ [projN, combineN, w0N, inN]) outN)
| mode1 == nameTy "Vec" && match wt1 [wt2,wt3,wt4,wt5,wt6] &&
kt1 == kt2 && vt1 == vt2 = do
-- get input var name
getVar (Lf "inVec") inN outVarName
getVar (Lf "val0") w0N outVarName
-- create output var
ifnVar "decOut" outVarName (Lf "outVal") wt3
-- create temp vars
newStructVar (Lf "val1") wt1
runGenV "declareVarInit" "decVal1" [Lf "val1", Lf "val0"]
newStructVar (Lf "val2") wt1
runGenV "declareVarInit" "decVal2" [Lf "val2", Lf "val0"]
newVar (Lf "ptr") $ namedTy "Ptr" [Tup [kt1, vt1]]
runGenV "declareVar" "decPtr" [Lf "ptr"]
runGenV "assignVar" "copyToOut" [Lf "outVal", Lf "val2"]
-- create projection function app
varExp "el" "ptr" "(*<v>)" $ Tup [kt1, vt1]
genFunV "appProjFun" projN (Lf "el") w0N (Lf "val1")
-- declare AllReduce Op
combineFun <- getFun combineN
genTrace "maxVMap:got combineFun"
runGen "reduceFun" "redFunName" [TyV wt1, combineFun]
genTrace "maxVMap:generated reduceFun"
newVar (Lf "redOp") intTy
output "decls" "MPI::Op <redOp>;\n\n"
output "init" "<redOp>.Init(&<redFunName>, true);\n\n"
-- generate code
setFun outN "gen" nt (\_ -> do
-- prep for allreduce
resTyNameMb <- genTypeName wt1
tn <- getTemplateName
let resTyName = fromMaybe (error $ tn ++ ": can't get result type name!") resTyNameMb
setLocalVal "resTyName" $ IdV resTyName
-- local data for this dist
genHasDataPred "hasData" parD1 mirD1
genSubCartV "localComm" "localRanks" parD1
-- output code
outputDecl outN "// begin <tem> decl\n<decOut>// end <tem> decl"
outMain $
"// begin <tem>\n"++
"<decVal2>\n"++
"if (<hasData>) {\n"++
-- get local max
" <decVal1>\n<decPtr>\n"++
" <ptr> = <inVec>->last();\n"++
" if (<ptr>) { <appProjFun> }\n"++
-- allreduce it to find global max
" <localComm>.Allreduce(&<val1>, &<val2>, sizeof(<resTyName>), MPI::BYTE, <redOp>);\n"++
"}\n"++
-- if local comm isn't the global one, broadcast to any remaining ones
"if (<localComm> != cartComm) {\n"++
" cartComm.Bcast(&<val2>, sizeof(<resTyName>), MPI::BYTE, rootRank);\n" ++
"}\n"++
"<copyToOut>\n"++
"// end <tem>\n"
return ())
t05 t n = terr' t n
-- |minVMap template
t06 :: (Monad m, MonadCatch m) => Template m
t06 (Tup [Tup [kt1, vt1] :-> wt1, Tup [wt2, wt3] :-> wt4, wt5,
Lf (LfTy "DMap" [mode1, kt2, vt2, ordF1, parF1, parD1, mirD1])] :-> wt6)
(LFun _ (LTup _ [projN, combineN, w0N, inN]) outN)
| mode1 == nameTy "Vec" && match wt1 [wt2,wt3,wt4,wt5,wt6] &&
kt1 == kt2 && vt1 == vt2 = do
-- get input var name
getVar (Lf "inVec") inN outVarName
getVar (Lf "val0") w0N outVarName
-- create output var
ifnVar "decOut" outVarName (Lf "outVal") wt3
-- create temp vars
newStructVar (Lf "val1") wt1
runGenV "declareVarInit" "decVal1" [Lf "val1", Lf "val0"]
newStructVar (Lf "val2") wt1
runGenV "declareVarInit" "decVal2" [Lf "val2", Lf "val0"]
newVar (Lf "ptr") $ namedTy "Ptr" [Tup [kt1, vt1]]
runGenV "declareVar" "decPtr" [Lf "ptr"]
runGenV "assignVar" "copyToOut" [Lf "outVal", Lf "val2"]
-- create projection function app
varExp "el" "ptr" "(*<v>)" $ Tup [kt1, vt1]
genFunV "appProjFun" projN (Lf "el") w0N (Lf "val1")
-- declare AllReduce Op
combineFun <- getFun combineN
genTrace "maxVMap:got combineFun"
runGen "reduceFun" "redFunName" [TyV wt1, combineFun]
genTrace "maxVMap:generated reduceFun"
newVar (Lf "redOp") intTy
output "decls" "MPI::Op <redOp>;\n\n"
output "init" "<redOp>.Init(&<redFunName>, true);\n\n"
-- generate code
setFun outN "gen" nt (\_ -> do
-- prep for allreduce
resTyNameMb <- genTypeName wt1
tn <- getTemplateName
let resTyName = fromMaybe (error $ tn ++ ": can't get result type name!") resTyNameMb
setLocalVal "resTyName" $ IdV resTyName
-- local data for this dist
genHasDataPred "hasData" parD1 mirD1
genSubCartV "localComm" "localRanks" parD1
-- output code
outputDecl outN "// begin <tem> decl\n<decOut>// end <tem> decl\n"
outMain $
"// begin <tem>\n"++
"<decVal2>\n"++
"if (<hasData>) {\n"++
-- get local max
" <decVal1>\n<decPtr>\n"++
" <ptr> = <inVec>->first();\n"++
" if (<ptr>) { <appProjFun> }\n"++
-- allreduce it to find global max
" <localComm>.Allreduce(&<val1>, &<val2>, sizeof(<resTyName>), MPI::BYTE, <redOp>);\n"++
"}\n"++
-- if local comm isn't the global one, broadcast to any remaining ones
"if (<localComm> != cartComm) {\n"++
" cartComm.Bcast(&<val2>, sizeof(<resTyName>), MPI::BYTE, rootRank);\n" ++
"}\n"++
"<copyToOut>\n"++
"// end <tem>\n"
return ())
t06 t n = terr' t n
-- |crossVMaps11 template
t07 :: (Monad m, MonadCatch m) => Template m
t07 (Tup [Lf (LfTy "DMap" [mode1, kt1, vt1, ordF1, parF1, parD1, mirD1]),
Lf (LfTy "DMap" [mode2, ity1, wt1, ordF2, parF2, parD2, mirD2])] :->
Lf (LfTy "DMap" [mode3, Tup [kt2, ity2], Tup [vt2, wt2], ordF3, parF3, parD3, mirD3]))
(LFun _ (LTup _ [inN1, inN2]) outN)
| mode1 == nameTy "Stm" && mode2 == nameTy "Vec" && mode3 == nameTy "Stm" &&
kt1 == kt2 && vt1 == vt2 && ity1 == ity2 && wt1 == wt2= do
-- check in and out dists are same
assertM (return $ match parD1 [parD1, mirD2, parD3]) "par/mirr dims don't match"
--assertM (return $ match mirD1 [mirD2, mirD3]) "mirror dims don't match"
-- get input var names
getVar (Tup [Lf "k1", Lf "v1"]) inN1 "streamVar"
getVar (Lf "inV2") inN2 outVarName
(VarV _ (Lf inV2Nam)) <- getLocalVal "inV2"
-- declare loop iterator and end iterator
vecmapTyMb <- getValMaybe inN2 "vecmapType"
let iterTy = maybe (Lf $ LfTy "TypeOf" [nameTy $ inV2Nam ++ "->csbegin()"]) (\ty -> Lf $ LfTy "ConstIter" [fromTyVal "crossVMaps11" ty]) vecmapTyMb
newVar (Lf "it2") iterTy
newVar (Lf "end2") iterTy
varExp "itBegin2" "inV2" "<v>->csbegin()" iterTy
varExp "itEnd2" "inV2" "<v>->csend()" iterTy
runGenV "declareVarInit" "decIt2" [Lf "it2", Lf "itBegin2"]
runGenV "declareVarInit" "decEnd2" [Lf "end2", Lf "itEnd2"]
-- declare stream var
varExp "i2" "it2" "<v>->v0" ity1
varExp "w2" "it2" "<v>->v1" wt1
setVar outN "streamVar" $ Tup [Tup [Lf "k1", Lf "i2"], Tup [Lf "v1", Lf "w2"]]
-- if we know the maps sizes, pass it on
ifVarExists "count1" inN1 "count" (
ifVarExists "count2" inN2 "count" (do
countExp <- expandTem "crossVMaps11:countExp:" "(<count1>) * (<count2>)" ;
varExp "count" "" countExp intTy ;
setVar outN "count" $ Lf "count"
) (return ())) (return ())
-- when gen is called, generate loop
setFun outN "genConsumers" nt (\_ -> do
-- gen consumers
callAll outN "genConsumers" nt
ifVarsExist [("init", outN, "initStream"), ("fin", outN, "finStream"), ("consume", outN, "consumers")] (do
-- local data pred
genHasDataPred "hasData" parD2 mirD2
-- output code
addCode inN1 "initStream" "// begin <tem> init\n<init>\n// end <tem> init\n"
addCode inN1 "consumers" $
"// BEGIN <tem> consume:\n"++
"if (<hasData>) {\n"++
" <decIt2><decEnd2>\n"++
" for (; <it2> != <end2>; <it2>++) {\n"++
" <consume>\n"++
" }\n"++
"}\n"++
"// END <tem> consume\n"
addCode inN1 "finStream" "<fin>"
) (return ())
return ())
t07 t n = terr' t n
-- |unionVMaps1 template
t09 :: (Monad m, MonadCatch m) => Template m
t09 (Tup [Lf (LfTy "DMap" [mode1, kt1, vt1, ordF1, parF1, parD1, mirD1]),
Lf (LfTy "DMap" [mode2, kt2, vt2, ordF2, parF2, parD2, mirD2])] :->
Lf (LfTy "DMap" [mode3, kt3, vt3, ordF3, parF3, parD3, mirD3]))
(LFun _ (LTup _ [inN1, inN2]) outN)
| mode1 == nameTy "Stm" && mode2 == nameTy "Vec" && mode3 == nameTy "Stm" &&
match kt1 [kt2,kt3] && match vt1 [vt2, vt3] = do
-- check in and out dists are same
assertM (return $ match parD1 [parD2, parD3]) "par dims don't match"
assertM (return $ match mirD1 [mirD2, mirD3]) "mirror dims don't match"
-- get input var names
getVar (Tup [Lf "k1", Lf "v1"]) inN1 "streamVar"
getVar (Lf "inV2") inN2 outVarName
(VarV _ (Lf inV2Nam)) <- getLocalVal "inV2"
-- declare loop iterator and end iterator
vecmapTyMb <- getValMaybe inN2 "vecmapType"
let iterTy = maybe (Lf $ LfTy "TypeOf" [nameTy $ inV2Nam ++ "->cpbegin()"]) (\ty -> Lf $ LfTy "ConstIter" [fromTyVal "unionVMaps1" ty]) vecmapTyMb
newVar (Lf "it2") iterTy
newVar (Lf "end2") iterTy
varExp "itBegin2" "inV2" "<v>->cpbegin()" iterTy
varExp "itEnd2" "inV2" "<v>->cpend()" iterTy
runGenV "declareVarInit" "decIt2" [Lf "it2", Lf "itBegin2"]
runGenV "declareVarInit" "decEnd2" [Lf "end2", Lf "itEnd2"]
varExp "k2" "it2" "<v>->v0" kt1
varExp "v2" "it2" "<v>->v1" vt1
-- declare comparisons
runGenV "ltVar" "pred1Lt2" [Lf "k1", Lf "k2"]
runGenV "ltVar" "pred2Lt1" [Lf "k2", Lf "k1"]
runGenV "eqVar" "pred1Eq2" [Lf "k1", Lf "k2"]
-- declare stream var
newVar (Tup [Lf "outK", Lf "outV"]) $ Tup [kt1, vt1]
runGenV "assignVar" "copy1" [Tup [Lf "outK", Lf "outV"], Tup [Lf "k1", Lf "v1"]]
runGenV "assignVar" "copy2" [Tup [Lf "outK", Lf "outV"], Tup [Lf "k2", Lf "v2"]]
setVar outN "streamVar" $ Tup [Lf "outK", Lf "outV"]
runGenV "declareVar" "decOut" [Tup [Lf "outK", Lf "outV"]]
-- we can't know the result count, so can't pass it on
-- when gen is called, generate loop
setFun outN "genConsumers" nt (\_ -> do
-- gen consumers (TODO could we call genConsumers twice, with different stream vars???)
callAll outN "genConsumers" nt
ifVarsExist [("init", outN, "initStream"), ("fin", outN, "finStream"), ("consume", outN, "consumers")] (do
-- output code
addCode inN1 "initStream" "// begin <tem> init\n<init><decIt2><decEnd2><decOut>// end <tem> init\n"
addCode inN1 "consumers" $
"// BEGIN <tem> consume:\n"++
"while (<it2> != <end2> && (<pred2Lt1>)) {\n"++
" // emit 2, inc 2\n"++
" <copy2>\n<consume>\n<it2>++;\n"++
"}\n"++
"// emit 1, inc 1\n"++
"<copy1>\n<consume>\n"++
"if (<it2> != <end2> && (<pred1Eq2>)) { // inc 2 aswell\n"++
" <it2>++;\n"++
"}\n"++
"// END <tem> consume\n"
addCode inN1 "finStream" $
"// BEGIN <tem> fin\n"++
"// emit any vals remaining from input 2\n"++
"while (<it2> != <end2>) {\n"++
" // emit val from input 2, and progress input 2\n"++
" <copy2>\n<consume>\n<it2>++;\n"++
"}\n"++
"<fin>\n"++
"// END <tem> fin\n"
) (do output "main" "// <tem> not used so not generated.\n"; return ())
return ())
t09 t n = terr' t n
-- |unionVMaps3 template
t13 :: (Monad m, MonadCatch m) => Template m
t13 (Tup [Lf (LfTy "DMap" [mode1, kt1, vt1, ordF1, parF1, parD1, mirD1]),
Lf (LfTy "DMap" [mode2, kt2, vt2, ordF2, parF2, parD2, mirD2])] :->
Lf (LfTy "DMap" [mode3, kt3, vt3, ordF3, parF3, parD3, mirD3]))
(LFun _ (LTup _ [inN1, inN2]) outN)
| mode1 == nameTy "Vec" && mode2 == nameTy "Stm" && mode3 == nameTy "Stm" &&
match kt1 [kt2,kt3] && match vt1 [vt2, vt3] = do
-- check in and out dists are same
assertM (return $ match parD1 [parD2, parD3]) "par dims don't match"
assertM (return $ match mirD1 [mirD2, mirD3]) "mirror dims don't match"
-- get input var names
getVar (Tup [Lf "k2", Lf "v2"]) inN2 "streamVar"
getVar (Lf "inV1") inN1 outVarName
(VarV _ (Lf inV1Nam)) <- getLocalVal "inV1"
-- declare loop iterator and end iterator
vecmapTyMb <- getValMaybe inN1 "vecmapType"
let iterTy = maybe (Lf $ LfTy "TypeOf" [nameTy $ inV1Nam ++ "->cpbegin()"]) (\ty -> Lf $ LfTy "ConstIter" [fromTyVal "unionVMaps3" ty]) vecmapTyMb
newVar (Lf "it1") iterTy
newVar (Lf "end1") iterTy
varExp "itBegin1" "inV1" "<v>->cpbegin()" iterTy
varExp "itEnd1" "inV1" "<v>->cpend()" iterTy
runGenV "declareVarInit" "decIt1" [Lf "it1", Lf "itBegin1"]
runGenV "declareVarInit" "decEnd1" [Lf "end1", Lf "itEnd1"]
varExp "k1" "it1" "<v>->v0" kt1
varExp "v1" "it1" "<v>->v1" vt1
-- declare comparisons
runGenV "ltVar" "pred2Lt1" [Lf "k2", Lf "k1"]
runGenV "ltVar" "pred1Lt2" [Lf "k1", Lf "k2"]
runGenV "eqVar" "pred1Eq2" [Lf "k2", Lf "k1"]
-- declare stream var
newVar (Tup [Lf "outK", Lf "outV"]) $ Tup [kt1, vt1]
runGenV "assignVar" "copy1" [Tup [Lf "outK", Lf "outV"], Tup [Lf "k1", Lf "v1"]]
runGenV "assignVar" "copy2" [Tup [Lf "outK", Lf "outV"], Tup [Lf "k2", Lf "v2"]]
setVar outN "streamVar" $ Tup [Lf "outK", Lf "outV"]
runGenV "declareVar" "decOut" [Tup [Lf "outK", Lf "outV"]]
-- we can't know the result count, so can't pass it on
-- when gen is called, generate loop
setFun outN "genConsumers" nt (\_ -> do
-- gen consumers (TODO could we call genConsumers twice, with different stream vars???)
callAll outN "genConsumers" nt
ifVarsExist [("init", outN, "initStream"), ("fin", outN, "finStream"), ("consume", outN, "consumers")] (do
-- output code
addCode inN1 "initStream" "// begin <tem> init\n<init><decIt1><decEnd1><decOut>// end <tem> init\n"
addCode inN1 "consumers" $
"// BEGIN <tem> consume:\n"++
"while (<it1> != <end1> && (<pred1Lt2>)) {\n"++
" // emit 1, inc 1\n"++
" <copy1>\n<consume>\n<it1>++;\n"++
"}\n"++
"// emit 2, inc 2\n"++
"<copy2>\n<consume>\n"++
"if (<it1> != <end1> && (<pred1Eq2>)) { // inc 1 aswell\n"++
" <it1>++;\n"++
"}\n"++
"// END <tem> consume\n"
addCode inN1 "finStream" $
"// BEGIN <tem> fin\n"++
"// emit any vals remaining from input 2\n"++
"while (<it1> != <end1>) {\n"++
" // emit val from input 2, and progress input 2\n"++
" <copy1>\n<consume>\n<it1>++;\n"++
"}\n"++
"<fin>\n"++
"// END <tem> fin\n"
) (do output "main" "// <tem> not used so not generated.\n"; return ())
return ())
t13 t n = terr' t n
-- |unionVMaps2 template
t10 :: (Monad m, MonadCatch m) => Template m
t10 (Tup [Lf (LfTy "DMap" [mode1, kt1, vt1, ordF1, parF1, parD1, mirD1]),
Lf (LfTy "DMap" [mode2, kt2, vt2, ordF2, parF2, parD2, mirD2])] :->
Lf (LfTy "DMap" [mode3, kt3, vt3, ordF3, parF3, parD3, mirD3]))
(LFun _ (LTup _ [inN1, inN2]) outN)
| mode1 == nameTy "Vec" && mode2 == nameTy "Vec" && mode3 == nameTy "Vec" &&
match kt1 [kt2,kt3] && match vt1 [vt2, vt3] = do
-- check in and out dists are same
assertM (return $ match parD1 [parD2, parD3]) "par dims don't match"
assertM (return $ match mirD1 [mirD2, mirD3]) "mirror dims don't match"
-- get input var names
getVar (Lf "inV1") inN1 outVarName
getVar (Lf "inV2") inN2 outVarName
(VarV _ (Lf inV1Nam)) <- getLocalVal "inV1"
-- declare output vecmap
ifVarExists "vecmapType" inN2 "vecmapType" (setVar outN "vecmapType" $ Lf "vecmapType") (return ())
vecmapTyMb <- getValMaybe inN1 "vecmapType"
let vecmapTy = maybe (Lf $ LfTy "TypeOf" [nameTy inV1Nam]) (fromTyVal "unionVMaps2") vecmapTyMb
tn <- getTemplateName
vecmapTyName <- genTypeName vecmapTy >>= (return . (fromMaybe (error $ "Templates:" ++ tn ++ " can't get type name of " ++ (show vecmapTy))))
varExp "size1" "inV1" "<v>->size()" intTy
varExp "size2" "inV2" "<v>->size()" intTy
varExp "newVecmap" "" ("new " ++ vecmapTyName ++ "(<size1>+<size2>)") (Lf $ LfTy "Ptr" [vecmapTy])
ifnVarInit "decOut" outVarName (Lf "outVec") (Lf $ LfTy "SPtr" [vecmapTy]) (Just $ Tup [Lf "newVecmap"])
-- declare loop iterator and end iterator
let iterTy = Lf $ LfTy "ConstIter" [vecmapTy]
newVar (Lf "resIt") iterTy
runGenV "declareVar" "decResIt" [Lf "resIt"]
newVar (Lf "outBegin") iterTy
runGenV "declareVar" "decOutBegin" [Lf "outBegin"]
varExp "itBegin2" "inV2" "<v>->cpbegin()" iterTy
varExp "itEnd2" "inV2" "<v>->cpend()" iterTy
-- we can't know the result count, so can't pass it on
-- generate code
setFun outN "gen" nt (\_ -> do
outputDecl outN "// begin <tem> decl\n<decOut>\n// end <tem> decl\n"
output "main" $
"<decResIt>\n<decOutBegin>\n"++
"<outBegin> = <outVec>->cpbegin();\n "++
"<resIt> = <inV1>->setUnion(<inV2>->cpbegin(), <inV2>->cpend(), <outBegin>);\n"++
"<outVec>->resize(<resIt>-<outBegin>); // reduce size to whats needed for union\n"
return ())
t10 t n = terr' t n
| flocc-net/flocc | v0.1/Compiler/Back/Maps/VTemplates.hs | apache-2.0 | 34,951 | 0 | 28 | 9,017 | 9,548 | 4,764 | 4,784 | 542 | 2 |
{-# LANGUAGE UnicodeSyntax #-}
import Options.Applicative (fullDesc,progDesc)
import LogicGrowsOnTrees.Parallel.Main
import LogicGrowsOnTrees.Parallel.Adapter.Threads
import LogicGrowsOnTrees.Utils.WordSum
import LogicGrowsOnTrees.Examples.Queens
main :: IO ()
main =
mainForExploreTree
driver
board_size_parser
(fullDesc <> progDesc "count the number of n-queens solutions for a given board size")
(\_ (RunOutcome _ termination_reason) → do
case termination_reason of
Aborted _ → error "search aborted"
Completed (WordSum count) → print count
Failure _ message → error $ "error: " ++ message
)
nqueensCount
| gcross/LogicGrowsOnTrees | LogicGrowsOnTrees/examples/count-all-nqueens-solutions.hs | bsd-2-clause | 732 | 0 | 15 | 187 | 150 | 79 | 71 | 18 | 3 |
{- This isn't a lexer in the sense that it provides a JavaScript token-stream.
- This module provides character-parsers for various JavaScript tokens.
-}
module BrownPLT.TypedJS.Lexer(lexeme,identifier,reserved,operator,
reservedOp,charLiteral, stringLiteral,natural,integer,float,naturalOrFloat,
decimal,hexadecimal,octal,symbol,whiteSpace,parens,angles,
braces,brackets,squares,semi,comma,colon,dot, identifierStart) where
import Prelude hiding (lex)
import Text.ParserCombinators.Parsec
import qualified Text.ParserCombinators.Parsec.Token as T
identifierStart = (letter <|> oneOf "$_")
javascriptDef =
T.LanguageDef "/*"
"*/"
"//"
False -- no nested comments
{- Adapted from syntax/regexps.ss in Dave's code. -}
identifierStart
(alphaNum <|> oneOf "$_") -- identifier rest
(oneOf "{}<>()~.,?:|&^=!+-*/%!@") -- operator start
(oneOf "=<>|&+@:") -- operator rest
["break", "case", "catch", "const", "continue", "debugger",
"default", "delete", "do", "else", "enum", "false", "finally",
"for", "function", "if", "instanceof", "in", "let", "new",
"null", "return", "switch", "this", "throw", "true", "try",
"typeof", "var", "void", "while", "with","forall", "rec",
"any", "sealed", "readonly", "pack", "unpack", "exists",
"prototype" ]
["|=", "^=", "&=", "<<=", ">>=", ">>>=", "+=", "-=", "*=", "/=",
"%=", "=", ";", ",", "?", ":", "||", "&&", "|", "^", "&",
"===", "==", "=", "!==", "!=", "<<", "<=", "<", ">>>", ">>",
">=", ">", "++", "--", "+", "-", "*", "/", "%", "!", "~", ".",
"[", "]", "{", "}", "(", ")","</","instanceof","<:"]
True -- case-sensitive
lex = T.makeTokenParser javascriptDef
-- everything but commaSep and semiSep
identifier = T.identifier lex
reserved = T.reserved lex
operator = T.operator lex
reservedOp = T.reservedOp lex
charLiteral = T.charLiteral lex
stringLiteral = T.stringLiteral lex
natural = T.natural lex
integer = T.integer lex
float = T.float lex
naturalOrFloat = T.naturalOrFloat lex
decimal = T.decimal lex
hexadecimal = T.hexadecimal lex
octal = T.octal lex
symbol = T.symbol lex
whiteSpace = T.whiteSpace lex
parens = T.parens lex
braces = T.braces lex
angles = T.angles lex
squares = T.squares lex
semi = T.semi lex
comma = T.comma lex
colon = T.colon lex
dot = T.dot lex
brackets = T.brackets lex
lexeme = T.lexeme lex
| brownplt/strobe-old | src/BrownPLT/TypedJS/Lexer.hs | bsd-2-clause | 2,656 | 2 | 8 | 683 | 728 | 435 | 293 | 56 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QDirModel.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:35
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Enums.Gui.QDirModel (
Roles, eFileIconRole, eFilePathRole, eFileNameRole
)
where
import Qtc.Classes.Base
import Qtc.ClassTypes.Core (QObject, TQObject, qObjectFromPtr)
import Qtc.Core.Base (Qcs, connectSlot, qtc_connectSlot_int, wrapSlotHandler_int)
import Qtc.Enums.Base
import Qtc.Enums.Classes.Core
data CRoles a = CRoles a
type Roles = QEnum(CRoles Int)
ieRoles :: Int -> Roles
ieRoles x = QEnum (CRoles x)
instance QEnumC (CRoles Int) where
qEnum_toInt (QEnum (CRoles x)) = x
qEnum_fromInt x = QEnum (CRoles x)
withQEnumResult x
= do
ti <- x
return $ qEnum_fromInt $ fromIntegral ti
withQEnumListResult x
= do
til <- x
return $ map qEnum_fromInt til
instance Qcs (QObject c -> Roles -> IO ()) where
connectSlot _qsig_obj _qsig_nam _qslt_obj _qslt_nam _handler
= do
funptr <- wrapSlotHandler_int slotHandlerWrapper_int
stptr <- newStablePtr (Wrap _handler)
withObjectPtr _qsig_obj $ \cobj_sig ->
withCWString _qsig_nam $ \cstr_sig ->
withObjectPtr _qslt_obj $ \cobj_slt ->
withCWString _qslt_nam $ \cstr_slt ->
qtc_connectSlot_int cobj_sig cstr_sig cobj_slt cstr_slt (toCFunPtr funptr) (castStablePtrToPtr stptr)
return ()
where
slotHandlerWrapper_int :: Ptr fun -> Ptr () -> Ptr (TQObject c) -> CInt -> IO ()
slotHandlerWrapper_int funptr stptr qobjptr cint
= do qobj <- qObjectFromPtr qobjptr
let hint = fromCInt cint
if (objectIsNull qobj)
then do when (stptr/=ptrNull)
(freeStablePtr (castPtrToStablePtr stptr))
when (funptr/=ptrNull)
(freeHaskellFunPtr (castPtrToFunPtr funptr))
else _handler qobj (qEnum_fromInt hint)
return ()
eFileIconRole :: Roles
eFileIconRole
= ieRoles $ 1
eFilePathRole :: Roles
eFilePathRole
= ieRoles $ 33
eFileNameRole :: Roles
eFileNameRole
= ieRoles $ 34
| uduki/hsQt | Qtc/Enums/Gui/QDirModel.hs | bsd-2-clause | 2,345 | 0 | 18 | 530 | 606 | 309 | 297 | 54 | 1 |
module Utils where
import qualified Data.UUID as U -- UUID
import qualified Data.UUID.V4 as U4 -- UUID
import Data.Word
import Data.List.Split
import Control.Concurrent
import Data.Time
import System.Socket
import System.Socket.Family.Inet
import System.Socket.Type.Stream
import System.Socket.Protocol.TCP
genUUID :: IO String
genUUID = do
x <- U4.nextRandom
return $ U.toString x
atomicPutStrLn :: MVar () -> String -> IO ()
atomicPutStrLn lock str = withMVar lock (\_ -> putStrLn str)
-- | Check whether a string starts with a certain prefix
startsWith' :: String -> String -> Bool
startsWith' _ [] = True
startsWith' [] _ = False
startsWith' (x:xs) (y:ys)
| x == y = startsWith' xs ys
| otherwise = False
-- | Utility function for ClientUI, decide how many lines will a string be split
getLineNumber :: String -> Int -> Int
getLineNumber str col = case col of
0 -> 3
_ -> quot (length str) col + 3
-- | convert list of 4 elements to tuple
-- return tuple of 4 0's when number of elements is not 4
tupify4 :: [a] -> Maybe (a, a, a, a)
tupify4 [w, x, y, z] = Just (w, x, y, z)
tupify4 _ = Nothing
-- | convert string of address to tuple of 8-bit unsigned integer type
stringToAddrTuple :: String -> Maybe (Word8, Word8, Word8, Word8)
stringToAddrTuple str = let segs = splitOn "." str in -- assume valid input here
tupify4
(foldr
(\ x res ->
let num = read x :: Integer in
if num > 0 && num <= 255 then fromInteger num : res else 0 : res)
[]
segs)
-- | create a socket and connect to it by remote IP address and port
constructSocket :: InetAddress -> InetPort -> IO (Socket Inet Stream TCP)
constructSocket _ _ = do
sock <- socket :: IO (Socket Inet Stream TCP)
setSocketOption sock (ReuseAddress True)
return sock
-- | get zoned time IO string
getTimeStringIO :: IO String
getTimeStringIO = do
t <- getZonedTime
let timeStr = formatTime defaultTimeLocale "%T, %F (%Z)" t
return timeStr
-- | break long string into several lines based on column number
breakStringIntoLines :: String -> Int -> String
breakStringIntoLines str 0 = str
breakStringIntoLines str n =
aux str n 0 0 "" where
aux s col cnt idx res
| length s == cnt = res
| idx == col = aux s col cnt 0 (res ++ "\n")
| otherwise = aux s col (cnt + 1) (idx + 1) (res ++ [s !! cnt]) | weihu816/Adagio | src/Utils.hs | bsd-3-clause | 2,425 | 0 | 17 | 600 | 767 | 402 | 365 | 57 | 2 |
module HasOffers.API.Brand.AdManager
where
import Data.Text
import GHC.Generics
import Data.Aeson
import Control.Applicative
import Network.HTTP.Client
import qualified Data.ByteString.Char8 as BS
import HasOffers.API.Common
--------------------------------------------------------------------------------
addCreative params =
Call "AdManager"
"addCreative"
"POST"
[ Param "campaign_id" True $ getParam params 0 -- Required
, Param "data" True $ getParam params 1 -- Required, An associative array of fields to the values that will be created.
]
createCampaign params =
Call "AdManager"
"createCampaign"
"POST"
[ Param "data" True $ getParam params 0 -- Required, -- Required, An associative array of fields to the values that will be created.
, Param "return_object" True $ getParam params 1 -- boolean
]
findAllCampaigns params =
Call "AdManager"
"findAllCampaigns"
"GET"
[ Param "filters" False $ getParam params 0
, Param "sort" False $ getParam params 1
, Param "limit" False $ getParam params 2
, Param "page" False $ getParam params 3
, Param "fields" False $ getParam params 4
, Param "contain" False $ getParam params 5
]
findAllCreatives params =
Call "AdManager"
"findAllCreatives"
"GET"
[ Param "filters" False $ getParam params 0
, Param "sort" False $ getParam params 1
, Param "limit" False $ getParam params 2
, Param "page" False $ getParam params 3
, Param "fields" False $ getParam params 4
, Param "contain" False $ getParam params 5
]
findCampaignById params =
Call "AdManager"
"findCampaignById"
"GET"
[ Param "id" False $ getParam params 0
, Param "fields" False $ getParam params 1
, Param "contain" False $ getParam params 2
]
findCreativeById params =
Call "AdManager"
"findCreativeById"
"GET"
[ Param "id" False $ getParam params 0
, Param "fields" False $ getParam params 1
, Param "contain" False $ getParam params 2
]
getActiveNetworkCampaignCount params =
Call "AdManager"
"getActiveNetworkCampaignCount"
"GET"
[ Param "affiliate_access" True $ getParam params 0
]
| kelecorix/api-hasoffers | src/HasOffers/API/Brand/AdManager.hs | bsd-3-clause | 2,438 | 0 | 8 | 737 | 564 | 278 | 286 | 59 | 1 |
{-# LANGUAGE TupleSections, OverloadedStrings, QuasiQuotes, TemplateHaskell, TypeFamilies, RecordWildCards,
DeriveGeneric ,MultiParamTypeClasses ,FlexibleInstances #-}
module Protocol.ROC.PointTypes.PointType40 where
import GHC.Generics
import qualified Data.ByteString as BS
import Data.Word
import Data.Binary
import Data.Binary.Get
import Protocol.ROC.Float
data PointType40 = PointType40 {
pointType40SensorTag :: !PointType40SensorTag
,pointType40SensorAddress :: !PointType40SensorAddress
,pointType40SensorCFG :: !PointType40SensorCFG
,pointType40PollMode :: !PointType40PollMode
,pointType40InterfaceRev :: !PointType40InterfaceRev
,pointType40SensorStatus1 :: !PointType40SensorStatus1
,pointType40SensorStatus2 :: !PointType40SensorStatus2
,pointType40SensorVoltage :: !PointType40SensorVoltage
,pointType40DPReading :: !PointType40DPReading
,pointType40StatisPressAPReading :: !PointType40StatisPressAPReading
,pointType40TemperaturePTReading :: !PointType40TemperaturePTReading
,pointType40DPReverseFlow :: !PointType40DPReverseFlow
,pointType40StatisPressEffect :: !PointType40StatisPressEffect
,pointType40DPMinCalibValue :: !PointType40DPMinCalibValue
,pointType40DPCalibMidPnt1 :: !PointType40DPCalibMidPnt1
,pointType40DPCalibMidPnt2 :: !PointType40DPCalibMidPnt2
,pointType40DPCalibMidPnt3 :: !PointType40DPCalibMidPnt3
,pointType40DPMaxCalibValue :: !PointType40DPMaxCalibValue
,pointType40APMinCalibValue :: !PointType40APMinCalibValue
,pointType40APCalibMidPnt1 :: !PointType40APCalibMidPnt1
,pointType40APCalibMidPnt2 :: !PointType40APCalibMidPnt2
,pointType40APCalibMidPnt3 :: !PointType40APCalibMidPnt3
,pointType40APMaxCalibValue :: !PointType40APMaxCalibValue
,pointType40PTMinCalibValue :: !PointType40PTMinCalibValue
,pointType40PTCalibMidPnt1 :: !PointType40PTCalibMidPnt1
,pointType40PTCalibMidPnt2 :: !PointType40PTCalibMidPnt2
,pointType40PTCalibMidPnt3 :: !PointType40PTCalibMidPnt3
,pointType40PTMaxCalibValue :: !PointType40PTMaxCalibValue
,pointType40CalibCommand :: !PointType40CalibCommand
,pointType40CalibType :: !PointType40CalibType
,pointType40CalibSetValue :: !PointType40CalibSetValue
,pointType40ManualDP :: !PointType40ManualDP
,pointType40ManualAP :: !PointType40ManualAP
,pointType40ManualPT :: !PointType40ManualPT
,pointType40DPMode :: !PointType40DPMode
,pointType40DPAlarmCode :: !PointType40DPAlarmCode
,pointType40DPLowAlarm :: !PointType40DPLowAlarm
,pointType40DPHighAlarm :: !PointType40DPHighAlarm
,pointType40DPDeadband :: !PointType40DPDeadband
,pointType40DPAlarmFaultValue :: !PointType40DPAlarmFaultValue
,pointType40APMode :: !PointType40APMode
,pointType40APAlarmCode :: !PointType40APAlarmCode
,pointType40APLowAlarm :: !PointType40APLowAlarm
,pointType40APHighAlarm :: !PointType40APHighAlarm
,pointType40APDeadband :: !PointType40APDeadband
,pointType40APAlarmFaultValue :: !PointType40APAlarmFaultValue
,pointType40PTMode :: !PointType40PTMode
,pointType40PTAlarmCode :: !PointType40PTAlarmCode
,pointType40PTLowAlarm :: !PointType40PTLowAlarm
,pointType40PTHighAlarm :: !PointType40PTHighAlarm
,pointType40PTDeadband :: !PointType40PTDeadband
,pointType40PTFaultValue :: !PointType40PTFaultValue
,pointType40PTBias :: !PointType40PTBias
,pointType40APOffset :: !PointType40APOffset
} deriving (Read,Eq, Show, Generic)
type PointType40SensorTag = BS.ByteString
type PointType40SensorAddress = Word8
type PointType40SensorCFG = Word8
type PointType40PollMode = Word8
type PointType40InterfaceRev = Word8
type PointType40SensorStatus1 = Word8
type PointType40SensorStatus2 = Word8
type PointType40SensorVoltage = Float
type PointType40DPReading = Float
type PointType40StatisPressAPReading = Float
type PointType40TemperaturePTReading = Float
type PointType40DPReverseFlow = Float
type PointType40StatisPressEffect = Float
type PointType40DPMinCalibValue = Float
type PointType40DPCalibMidPnt1 = Float
type PointType40DPCalibMidPnt2 = Float
type PointType40DPCalibMidPnt3 = Float
type PointType40DPMaxCalibValue = Float
type PointType40APMinCalibValue = Float
type PointType40APCalibMidPnt1 = Float
type PointType40APCalibMidPnt2 = Float
type PointType40APCalibMidPnt3 = Float
type PointType40APMaxCalibValue = Float
type PointType40PTMinCalibValue = Float
type PointType40PTCalibMidPnt1 = Float
type PointType40PTCalibMidPnt2 = Float
type PointType40PTCalibMidPnt3 = Float
type PointType40PTMaxCalibValue = Float
type PointType40CalibCommand = Word8
type PointType40CalibType = Word8
type PointType40CalibSetValue = Float
type PointType40ManualDP = Float
type PointType40ManualAP = Float
type PointType40ManualPT = Float
type PointType40DPMode = Word8
type PointType40DPAlarmCode = Word8
type PointType40DPLowAlarm = Float
type PointType40DPHighAlarm = Float
type PointType40DPDeadband = Float
type PointType40DPAlarmFaultValue = Float
type PointType40APMode = Word8
type PointType40APAlarmCode = Word8
type PointType40APLowAlarm = Float
type PointType40APHighAlarm = Float
type PointType40APDeadband = Float
type PointType40APAlarmFaultValue = Float
type PointType40PTMode = Word8
type PointType40PTAlarmCode = Word8
type PointType40PTLowAlarm = Float
type PointType40PTHighAlarm = Float
type PointType40PTDeadband = Float
type PointType40PTFaultValue = Float
type PointType40PTBias = Float
type PointType40APOffset = Float
pointType40Parser :: Get PointType40
pointType40Parser = do
sensorTag <- getByteString 10
sensorAddress <- getWord8
sensorCFG <- getWord8
pollMode <- getWord8
interfaceRev <- getWord8
sensorStatus1 <- getWord8
sensorStatus2 <- getWord8
sensorVoltage <- getIeeeFloat32
dPReading <- getIeeeFloat32
statisPressAPReading <- getIeeeFloat32
temperaturePTReading <- getIeeeFloat32
dPReverseFlow <- getIeeeFloat32
statisPressEffect <- getIeeeFloat32
dPMinCalibValue <- getIeeeFloat32
dPCalibMidPnt1 <- getIeeeFloat32
dPCalibMidPnt2 <- getIeeeFloat32
dPCalibMidPnt3 <- getIeeeFloat32
dPMaxCalibValue <- getIeeeFloat32
aPMinCalibValue <- getIeeeFloat32
aPCalibMidPnt1 <- getIeeeFloat32
aPCalibMidPnt2 <- getIeeeFloat32
aPCalibMidPnt3 <- getIeeeFloat32
aPMaxCalibValue <- getIeeeFloat32
pTMinCalibValue <- getIeeeFloat32
pTCalibMidPnt1 <- getIeeeFloat32
pTCalibMidPnt2 <- getIeeeFloat32
pTCalibMidPnt3 <- getIeeeFloat32
pTMaxCalibValue <- getIeeeFloat32
calibCommand <- getWord8
calibType <- getWord8
calibSetValue <- getIeeeFloat32
manualDP <- getIeeeFloat32
manualAP <- getIeeeFloat32
manualPT <- getIeeeFloat32
dPMode <- getWord8
dPAlarmCode <- getWord8
dPLowAlarm <- getIeeeFloat32
dPHighAlarm <- getIeeeFloat32
dPDeadband <- getIeeeFloat32
dPAlarmFaultValue <- getIeeeFloat32
aPMode <- getWord8
aPAlarmCode <- getWord8
aPLowAlarm <- getIeeeFloat32
aPHighAlarm <- getIeeeFloat32
aPDeadband <- getIeeeFloat32
aPAlarmFaultValue <- getIeeeFloat32
pTMode <- getWord8
pTAlarmCode <- getWord8
pTLowAlarm <- getIeeeFloat32
pTHighAlarm <- getIeeeFloat32
pTDeadband <- getIeeeFloat32
pTFaultValue <- getIeeeFloat32
pTBias <- getIeeeFloat32
aPOffset <- getIeeeFloat32
return $ PointType40 sensorTag sensorAddress sensorCFG pollMode interfaceRev sensorStatus1 sensorStatus2 sensorVoltage dPReading statisPressAPReading temperaturePTReading
dPReverseFlow statisPressEffect dPMinCalibValue dPCalibMidPnt1 dPCalibMidPnt2 dPCalibMidPnt3 dPMaxCalibValue aPMinCalibValue aPCalibMidPnt1 aPCalibMidPnt2 aPCalibMidPnt3
aPMaxCalibValue pTMinCalibValue pTCalibMidPnt1 pTCalibMidPnt2 pTCalibMidPnt3 pTMaxCalibValue calibCommand calibType calibSetValue manualDP manualAP manualPT dPMode
dPAlarmCode dPLowAlarm dPHighAlarm dPDeadband dPAlarmFaultValue aPMode aPAlarmCode aPLowAlarm aPHighAlarm aPDeadband aPAlarmFaultValue pTMode pTAlarmCode pTLowAlarm
pTHighAlarm pTDeadband pTFaultValue pTBias aPOffset
| jqpeterson/roc-translator | src/Protocol/ROC/PointTypes/PointType40.hs | bsd-3-clause | 13,989 | 0 | 9 | 6,967 | 1,286 | 705 | 581 | 288 | 1 |
module Json.Moves.Deserialization
(deserialize)
where
import Text.Parsec
import Text.Parsec.String
deserialize:: String -> String
deserialize _ = "Bammmm"
| rubilnikas/haskell2 | src/Json/Deserialization.hs | bsd-3-clause | 161 | 0 | 5 | 22 | 40 | 24 | 16 | 6 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE UnicodeSyntax #-}
{-|
Module : Reflex.Dom.HTML5.Component.Tree.Common
Description : Common helpers to build tree-based components.
Copyright : (c) gspia 2018 -
License : BSD
Maintainer : gspia
= Tree.Common
About names: SF is for sub forest.
-}
module Reflex.Dom.HTML5.Component.Tree.Common
( isLeaf
, ElemUse (..)
, elemUseUlLi
, elemUseDivA
, elemUseNavDiv
, elemUseDivDiv
, elemUseDivButton
, elemUseNoneDiv
, elemUseNoneA
, defALeafNodeAttrF
, defLiLeafNodeAttrF
, defDivLeafNodeAttrF
, defUlSFWrapAttrF
, defDivSFWrapAttrF
, defNavSFWrapAttrF
) where
import Data.Text (Text)
-- import qualified Data.Text as T
import Data.Tree (Tree,subForest)
-- import Language.Javascript.JSaddle
import Reflex (Dynamic,Reflex)
-- import Reflex.Dom.Core
import qualified Reflex.Dom.HTML5.Attrs as A
import qualified Reflex.Dom.HTML5.Elements as E
import Reflex.Dom.HTML5.Component.Tree.ActNode (ActNode,
ActiveState, defActivationAttrF)
--------------------------------------------------------------------------------
-- | This can be used to define the wrapper-container -structure, e.g. ul
-- and li-elements.
data ElemUse = ElemUse
{ _euSFWrap ∷ Text
-- ^ A html element as a text given to elDynAttr.
-- This wraps nodes in a given level, like "ul".
, _euLeafNode ∷ Text
-- ^ A html element as a text given to elDynAttr.
-- This is for each node in a given level, like "li".
}
-- | To be used with 'LevelNFuns'.
elemUseUlLi ∷ ElemUse
elemUseUlLi = ElemUse "ul" "li"
-- | To be used with 'RootFuns' and LevelNFuns.
elemUseDivA ∷ ElemUse
elemUseDivA = ElemUse "div" "a"
-- | To be used with 'RootFuns'.
elemUseNavDiv ∷ ElemUse
elemUseNavDiv = ElemUse "nav" "div"
-- | To be used with 'RootFuns'.
elemUseDivDiv ∷ ElemUse
elemUseDivDiv = ElemUse "div" "div"
-- | To be used with 'RootFuns'.
elemUseDivButton ∷ ElemUse
elemUseDivButton = ElemUse "div" "button"
-- | To be used with 'RootFuns' and LevelNFuns.
-- Note that this doesn't use wrapper meaning that the list
-- is output directly.
elemUseNoneDiv ∷ ElemUse
elemUseNoneDiv = ElemUse "" "div"
-- | To be used with 'RootFuns' and LevelNFuns.
-- Note that this doesn't use wrapper meaning that the list
-- is output directly.
elemUseNoneA ∷ ElemUse
elemUseNoneA = ElemUse "" "a"
--------------------------------------------------------------------------------
-- | A method that implements the active-activable logic and applies the
-- attributes correspondingly.
defALeafNodeAttrF ∷ forall t r. Reflex t
⇒ ActiveState t ActNode r → Dynamic t A.Attr
defALeafNodeAttrF ast = A.attrMap <$> defActivationAttrF E.defA ast
-- TODO is this right module for the above function?
-- | A method that implements the active-activable logic and applies the
-- attributes correspondingly.
defLiLeafNodeAttrF ∷ forall t r. Reflex t
⇒ ActiveState t ActNode r → Dynamic t A.Attr
defLiLeafNodeAttrF ast = A.attrMap <$> defActivationAttrF E.defLi ast
-- | A method that implements the active-activable logic and applies the
-- attributes correspondingly.
defDivLeafNodeAttrF ∷ forall t r. Reflex t
⇒ ActiveState t ActNode r → Dynamic t A.Attr
defDivLeafNodeAttrF ast = A.attrMap <$> defActivationAttrF E.defDiv ast
-- | A method that implements the active-activable logic and applies the
-- attributes correspondingly.
defUlSFWrapAttrF ∷ forall t r. Reflex t
⇒ Dynamic t (ActiveState t ActNode r) → ActNode → Dynamic t A.Attr
defUlSFWrapAttrF _ _ = pure $ A.attrMap E.defUl
-- | A method that implements the active-activable logic and applies the
-- attributes correspondingly.
defDivSFWrapAttrF ∷ forall t r. Reflex t
⇒ Dynamic t (ActiveState t ActNode r) → ActNode → Dynamic t A.Attr
defDivSFWrapAttrF _ _ = pure $ A.attrMap E.defDiv
-- | A method that implements the active-activable logic and applies the
-- attributes correspondingly.
defNavSFWrapAttrF ∷ forall t r. Reflex t
⇒ Dynamic t (ActiveState t ActNode r) → ActNode → Dynamic t A.Attr
defNavSFWrapAttrF _ _ = pure $ A.attrMap E.defNav
--------------------------------------------------------------------------------
-- | Helper.
isLeaf ∷ Tree a → Bool
isLeaf = null . subForest
| gspia/reflex-dom-htmlea | lib/src/Reflex/Dom/HTML5/Component/Tree/Common.hs | bsd-3-clause | 4,537 | 0 | 10 | 926 | 701 | 400 | 301 | 63 | 1 |
module Main where
import Data.Holumn.ExperimentSerial
main = putStrLn "let the tests begin!"
| SamRoberts/holumn-experimental | Main.hs | bsd-3-clause | 95 | 0 | 5 | 14 | 18 | 11 | 7 | 3 | 1 |
module Main where
import Control.Monad (forever, when)
import Data.List (intercalate)
import Data.Traversable (traverse)
import Lib
import Morse (morseToChar, stringToMorse)
import System.Environment (getArgs)
import System.Exit (exitFailure, exitSuccess)
import System.IO (hGetLine, hIsEOF, stdin)
convertToMorse :: IO ()
convertToMorse = forever $ do
weAreDone <- hIsEOF stdin
when weAreDone exitSuccess
line <- hGetLine stdin
convertLine line
where
convertLine line = do
let morse = stringToMorse line
case morse of
Just str -> putStrLn $ unwords str
Nothing -> do
putStrLn $ "ERROR: " ++ line
exitFailure
convertFromMorse :: IO ()
convertFromMorse = forever $ do
weAreDone <- hIsEOF stdin
when weAreDone exitSuccess
line <- hGetLine stdin
convertLine line
where
convertLine line = do
let decoded :: Maybe String
decoded = traverse morseToChar (words line)
case decoded of
Just s -> putStrLn s
Nothing -> do
putStrLn $ "ERROR: " ++ line
exitFailure
main :: IO ()
main = do
mode <- getArgs
case mode of
[arg] ->
case arg of
"from" -> convertFromMorse
"to" -> convertToMorse
_ -> argError
_ -> argError
where
argError = do
putStrLn "Please specify the first argument \
\as being 'from' or 'to' morse,\
\ such as: morse to"
exitFailure
| vasily-kirichenko/haskell-book | app/Main.hs | bsd-3-clause | 1,589 | 2 | 18 | 545 | 420 | 206 | 214 | 49 | 4 |
module Doukaku.Poker2013 (solve) where
import Data.List (sort, group, tails)
import Data.Char (intToDigit)
solve :: String -> String
solve input
| 'T' `elem` (map fst cards) && 'A' `elem` (map fst cards) &&
samesuit cards == 5 && ordered cards == 5 = "RF"
| samesuit cards == 5 && ordered cards == 5 = "SF"
| samesuit cards == 5 = "FL"
| ordered cards == 5 = "ST"
| any (\cs -> samesuit cs == 4 && ordered cs == 4) card4s = "4SF"
| samesuit cards == 4 = "4F"
| ordered cards == 4 = "4S"
| otherwise = "-"
where
card4s = map (\c -> filter (/= c) cards) cards
cards = parse input
samesuit, ordered :: [(Char, Char)] -> Int
samesuit = maximum . map length . group . sort . map snd
ordered hs = maximum . map (contains (map fst hs)) . tails $ numberorder
contains _ [] = 0
contains hs (x:xs)
| x `elem` hs = 1 + contains hs xs
| otherwise = 0
parse :: String -> [(Char, Char)]
parse ('1':'0':s:cs) = ('T', s) : parse cs
parse (n:s:cs) = (n, s) : parse cs
parse _ = []
numberorder :: [Char]
numberorder = 'A' : map intToDigit [2 .. 9] ++ "TJQKA"
| hiratara/doukaku-past-questions-advent-2013 | src/Doukaku/Poker2013.hs | bsd-3-clause | 1,133 | 0 | 16 | 306 | 562 | 288 | 274 | 29 | 2 |
module Problem18
( maxTrianglePathSum
, maxTrianglePathSum'
, leftSubTriangle
, rightSubTriangle
, weight
, bigTriangle
) where
bigTriangle :: [[Int]]
bigTriangle = [ [ 75 ]
, [ 95, 64 ]
, [ 17, 47, 82 ]
, [ 18, 35, 87, 10 ]
, [ 20, 04, 82, 47, 65 ]
, [ 19, 01, 23, 75, 03, 34 ]
, [ 88, 02, 77, 73, 07, 63, 67 ]
, [ 99, 65, 04, 28, 06, 16, 70, 92 ]
, [ 41, 41, 26, 56, 83, 40, 80, 70, 33 ]
, [ 41, 48, 72, 33, 47, 32, 37, 16, 94, 29 ]
, [ 53, 71, 44, 65, 25, 43, 91, 52, 97, 51, 14 ]
, [ 70, 11, 33, 28, 77, 73, 17, 78, 39, 68, 17, 57 ]
, [ 91, 71, 52, 38, 17, 14, 91, 43, 58, 50, 27, 29, 48 ]
, [ 63, 66, 04, 68, 89, 53, 67, 30, 73, 16, 69, 87, 40, 31 ]
, [ 04, 62, 98, 27, 23, 09, 70, 98, 73, 93, 38, 53, 60, 04, 23 ] ]
maxTrianglePathSum :: [[Int]] -> (Int, [Int])
maxTrianglePathSum [] = (0, [])
maxTrianglePathSum xss@(xs:_) =
let left = leftSubTriangle xss
right = rightSubTriangle xss
elem = head xs
(subElem, subPath) = max (maxTrianglePathSum left) (maxTrianglePathSum right)
in (elem + subElem, elem : subPath)
maxTrianglePathSum' :: [[Int]] -> (Int, [Int])
maxTrianglePathSum' [] = (0, [])
maxTrianglePathSum' xss =
let left = leftSubTriangle xss
right = rightSubTriangle xss
leftWeight = weight left
rightWeight = weight right
sub = if leftWeight > rightWeight then left else right
(subElem, subPath) = maxTrianglePathSum' sub
elem = head.head $ xss
in (elem + subElem, elem : subPath)
-- in (head.head $ xss) + maxTrianglePathSum' sub
-- |Weight of a triangle is sum of all of its items
weight :: [[Int]] -> Int
weight xss = foldl addRow 0 xss
where addRow acc row = acc + sum row
leftSubTriangle :: [[Int]] -> [[Int]]
leftSubTriangle xss = map init $ tail xss
rightSubTriangle :: [[Int]] -> [[Int]]
rightSubTriangle xss = map tail $ tail xss
| candidtim/euler | src/Problem18.hs | bsd-3-clause | 2,045 | 0 | 11 | 643 | 852 | 516 | 336 | 49 | 2 |
--
-- HTTP types for use with io-streams and pipes
--
-- Copyright © 2012-2014 Operational Dynamics Consulting, Pty Ltd and Others
--
-- The code in this file, and the program it is a part of, is
-- made available to you by its authors as open source software:
-- you can redistribute it and/or modify it under the terms of
-- the BSD licence.
--
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK hide #-}
module Network.Http.RequestBuilder (
RequestBuilder,
buildRequest,
buildRequest1,
http,
setHostname,
setAccept,
setAccept',
setAuthorizationBasic,
setContentType,
setContentLength,
setExpectContinue,
setTransferEncoding,
setHeader,
setContentMultipart
) where
import Blaze.ByteString.Builder (Builder)
import qualified Blaze.ByteString.Builder as Builder (fromByteString,
toByteString)
import qualified Blaze.ByteString.Builder.Char8 as Builder (fromShow,
fromString)
import Control.Monad.State
import Data.ByteString (ByteString)
import qualified Data.ByteString.Base64 as BS64
import Data.ByteString.Char8 ()
import qualified Data.ByteString.Char8 as S
import Data.Int (Int64)
import Data.List (intersperse)
import Network.Http.Internal
--
-- | The RequestBuilder monad allows you to abuse do-notation to
-- conveniently setup a 'Request' object.
--
newtype RequestBuilder α = RequestBuilder (State Request α)
deriving (Functor, Applicative, Monad, MonadState Request)
--
-- | Run a RequestBuilder, yielding a Request object you can use on the
-- given connection.
--
-- > let q = buildRequest1 $ do
-- > http POST "/api/v1/messages"
-- > setContentType "application/json"
-- > setHostname "clue.example.com" 80
-- > setAccept "text/html"
-- > setHeader "X-WhoDoneIt" "The Butler"
--
-- Obviously it's up to you to later actually /send/ JSON data.
--
buildRequest1 :: RequestBuilder α -> Request
buildRequest1 mm = do
let (RequestBuilder s) = (mm)
let q = Request {
qHost = Nothing,
qMethod = GET,
qPath = "/",
qBody = Empty,
qExpect = Normal,
qHeaders = emptyHeaders,
qBoundary = emptyBoundary
}
execState s q
--
-- | Run a RequestBuilder from within a monadic action.
--
-- Older versions of this library had 'buildRequest' in IO; there's
-- no longer a need for that, but this code path will continue to
-- work for existing users.
--
-- > q <- buildRequest $ do
-- > http GET "/"
--
buildRequest :: Monad ν => RequestBuilder α -> ν Request
buildRequest = return . buildRequest1
{-# INLINE buildRequest #-}
--
-- | Begin constructing a Request, starting with the request line.
--
http :: Method -> ByteString -> RequestBuilder ()
http m p' = do
q <- get
let h1 = qHeaders q
let h2 = updateHeader h1 "Accept-Encoding" "gzip"
let e = case m of
PUT -> Chunking
POST -> Chunking
_ -> Empty
let h3 = case e of
Chunking -> updateHeader h2 "Transfer-Encoding" "chunked"
_ -> h2
put q {
qMethod = m,
qPath = p',
qBody = e,
qHeaders = h3
}
--
-- | Set the [virtual] hostname for the request. In ordinary conditions
-- you won't need to call this, as the @Host:@ header is a required
-- header in HTTP 1.1 and is set directly from the name of the server
-- you connected to when calling 'Network.Http.Connection.openConnection'.
--
setHostname :: Hostname -> Port -> RequestBuilder ()
setHostname h' p = do
q <- get
put q {
qHost = Just v'
}
where
v' :: ByteString
v' = if p == 80
then h'
else Builder.toByteString $ mconcat
[Builder.fromByteString h',
Builder.fromString ":",
Builder.fromShow p]
--
-- | Set a generic header to be sent in the HTTP request. The other
-- methods in the RequestBuilder API are expressed in terms of this
-- function, but we recommend you use them where offered for their
-- stronger types.
--
setHeader :: ByteString -> ByteString -> RequestBuilder ()
setHeader k' v' = do
q <- get
let h0 = qHeaders q
let h1 = updateHeader h0 k' v'
put q {
qHeaders = h1
}
deleteHeader :: ByteString -> RequestBuilder ()
deleteHeader k' = do
q <- get
let h0 = qHeaders q
let h1 = removeHeader h0 k'
put q {
qHeaders = h1
}
{-# INLINE setEntityBody #-}
setEntityBody :: EntityBody -> RequestBuilder ()
setEntityBody e = do
q <- get
put q {
qBody = e
}
{-# INLINE setExpectMode #-}
setExpectMode :: ExpectMode -> RequestBuilder ()
setExpectMode e = do
q <- get
put q {
qExpect = e
}
--
-- | Indicate the content type you are willing to receive in a reply
-- from the server. For more complex @Accept:@ headers, use
-- 'setAccept''.
--
setAccept :: ByteString -> RequestBuilder ()
setAccept v' = do
setHeader "Accept" v'
--
-- | Indicate the content types you are willing to receive in a reply
-- from the server in order of preference. A call of the form:
--
-- > setAccept' [("text/html", 1.0),
-- > ("application/xml", 0.8),
-- > ("*/*", 0)]
--
-- will result in an @Accept:@ header value of
-- @text\/html; q=1.0, application\/xml; q=0.8, \*\/\*; q=0.0@ as you
-- would expect.
--
setAccept' :: [(ByteString,Float)] -> RequestBuilder ()
setAccept' tqs = do
setHeader "Accept" v'
where
v' = Builder.toByteString v
v = mconcat $ intersperse (Builder.fromString ", ") $ map format tqs
format :: (ByteString,Float) -> Builder
format (t',q) =
mconcat
[Builder.fromByteString t',
Builder.fromString "; q=",
Builder.fromShow q]
--
-- | Set username and password credentials per the HTTP basic
-- authentication method.
--
-- > setAuthorizationBasic "Aladdin" "open sesame"
--
-- will result in an @Authorization:@ header value of
-- @Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==@.
--
-- Basic authentication does /not/ use a message digest function to
-- encipher the password; the above string is only base-64 encoded and
-- is thus plain-text visible to any observer on the wire and all
-- caches and servers at the other end, making basic authentication
-- completely insecure. A number of web services, however, use SSL to
-- encrypt the connection that then use HTTP basic authentication to
-- validate requests. Keep in mind in these cases the secret is still
-- sent to the servers on the other side and passes in clear through
-- all layers after the SSL termination. Do /not/ use basic
-- authentication to protect secure or user-originated privacy-sensitve
-- information.
--
{-
This would be better using Builder, right?
-}
setAuthorizationBasic :: ByteString -> ByteString -> RequestBuilder ()
setAuthorizationBasic user' passwd' = do
setHeader "Authorization" v'
where
v' = S.concat ["Basic ", msg']
msg' = BS64.encode str'
str' = S.concat [user', ":", passwd']
--
-- | Set the MIME type corresponding to the body of the request you are
-- sending. Defaults to @\"text\/plain\"@, so usually you need to set
-- this if 'PUT'ting.
--
setContentType :: ContentType -> RequestBuilder ()
setContentType v' = do
setHeader "Content-Type" v'
--
-- | If sending multipart form data (RFC 7578), you need to set the MIME type
-- to @\"multipart/form-data\"@ and specify the boundary separator that will
-- be used.
--
-- This function is special: you must subsequently use
-- 'Network.Http.Client.multipartFormBody' to sequence the individual body
-- parts. When sending the request it will separate the individual parts by
-- the boundary value set by this function.
--
setContentMultipart :: Boundary -> RequestBuilder ()
setContentMultipart boundary = do
setHeader "Content-Type" (S.append "multipart/form-data; boundary=" (unBoundary boundary))
setBoundary boundary
setBoundary :: Boundary -> RequestBuilder ()
setBoundary boundary = do
q <- get
put q {
qBoundary = boundary
}
--
-- | Specify the length of the request body, in bytes.
--
-- RFC 2616 requires that we either send a @Content-Length@ header or
-- use @Transfer-Encoding: chunked@. If you know the exact size ahead
-- of time, then call this function; the body content will still be
-- streamed out by @io-streams@ in more-or-less constant space.
--
-- This function is special: in a PUT or POST request, @http-streams@
-- will assume chunked transfer-encoding /unless/ you specify a content
-- length here, in which case you need to ensure your body function
-- writes precisely that many bytes.
--
--
setContentLength :: Int64 -> RequestBuilder ()
setContentLength n = do
deleteHeader "Transfer-Encoding"
setHeader "Content-Length" (S.pack $ show n)
setEntityBody $ Static n
--
-- | Override the default setting about how the entity body will be sent.
--
-- This function is special: this explicitly sets the @Transfer-Encoding:@
-- header to @chunked@ and will instruct the library to actually tranfer the
-- body as a stream ("chunked transfer encoding"). See 'setContentLength' for
-- forcing the opposite. You /really/ won't need this in normal operation, but
-- some people are control freaks.
--
setTransferEncoding :: RequestBuilder ()
setTransferEncoding = do
deleteHeader "Content-Length"
setEntityBody Chunking
setHeader "Transfer-Encoding" "chunked"
--
-- | Specify that this request should set the expectation that the
-- server needs to approve the request before you send it.
--
-- This function is special: in a PUT or POST request, @http-streams@
-- will wait for the server to reply with an HTTP/1.1 100 Continue
-- status before sending the entity body. This is handled internally;
-- you will get the real response (be it successful 2xx, client error,
-- 4xx, or server error 5xx) in 'receiveResponse'. In theory, it
-- should be 417 if the expectation failed.
--
-- Only bother with this if you know the service you're talking to
-- requires clients to send an @Expect: 100-continue@ header and will
-- handle it properly. Most servers don't do any precondition checking,
-- automatically send an intermediate 100 response, and then just read
-- the body regardless, making this a bit of a no-op in most cases.
--
setExpectContinue :: RequestBuilder ()
setExpectContinue = do
setHeader "Expect" "100-continue"
setExpectMode Continue
| afcowie/http-common | lib/Network/Http/RequestBuilder.hs | bsd-3-clause | 10,692 | 0 | 13 | 2,488 | 1,482 | 838 | 644 | 149 | 4 |
-- | Instances of the 'MonadIO' class for 'StateT', 'WriterT', 'ReaderT', 'ExcT',
-- 'ContT', and 'ListT'.
--
-- Re-exports "Control.Monad.IO.Class" for convenience.
module Control.Monatron.IO (module Control.Monad.IO.Class) where
import Control.Monatron.Monatron (MonadT(..), Monoid, StateT, WriterT, ReaderT, ExcT, ContT, ListT)
import Control.Monad.IO.Class
instance MonadIO m => MonadIO (StateT z m) where
liftIO = lift . liftIO
instance (MonadIO m, Monoid z) => MonadIO (WriterT z m) where
liftIO = lift . liftIO
instance MonadIO m => MonadIO (ReaderT z m) where
liftIO = lift . liftIO
instance MonadIO m => MonadIO (ExcT z m) where
liftIO = lift . liftIO
instance MonadIO m => MonadIO (ContT r m) where
liftIO = lift . liftIO
instance MonadIO m => MonadIO (ListT m) where
liftIO = lift . liftIO
| TobBrandt/Monatron-IO | Control/Monatron/IO.hs | bsd-3-clause | 824 | 0 | 7 | 147 | 262 | 145 | 117 | 15 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Network.HTTP.Date.Parser (parseHTTPDate) where
import Control.Applicative
import Control.Monad
import Data.Attoparsec.ByteString
import Data.Attoparsec.ByteString.Char8
import Data.ByteString
import Data.Char
import Network.HTTP.Date.Types
----------------------------------------------------------------
-- |
-- Parsing HTTP Date. Currently only RFC1123 style is supported.
--
-- >>> parseHTTPDate "Tue, 15 Nov 1994 08:12:31 GMT"
-- Just (HTTPDate {hdYear = 1994, hdMonth = 11, hdDay = 15, hdHour = 8, hdMinute = 12, hdSecond = 31, hdWkday = 2})
parseHTTPDate :: ByteString -> Maybe HTTPDate
parseHTTPDate bs = case parseOnly rfc1123Date bs of
Right ut -> Just ut
_ -> Nothing
rfc1123Date :: Parser HTTPDate
rfc1123Date = do
w <- wkday
void $ string ", "
(y,m,d) <- date1
sp
(h,n,s) <- time
sp
-- RFC 2616 defines GMT only but there are actually ill-formed ones such
-- as "+0000" and "UTC" in the wild.
void $ string "GMT" <|> string "+0000" <|> string "UTC"
return $ defaultHTTPDate {
hdYear = y
, hdMonth = m
, hdDay = d
, hdHour = h
, hdMinute = n
, hdSecond = s
, hdWkday = w
}
wkday :: Parser Int
wkday = 1 <$ string "Mon"
<|> 2 <$ string "Tue"
<|> 3 <$ string "Wed"
<|> 4 <$ string "Thu"
<|> 5 <$ string "Fri"
<|> 6 <$ string "Sat"
<|> 7 <$ string "Sun"
date1 :: Parser (Int,Int,Int)
date1 = do
d <- day
sp
m <- month
sp
y <- year
return (y,m,d)
where
day = digit2
year = digit4
sp :: Parser ()
sp = () <$ char ' '
time :: Parser (Int,Int,Int)
time = do
h <- digit2
void $ char ':'
m <- digit2
void $ char ':'
s <- digit2
return (h,m,s)
month :: Parser Int
month = 1 <$ string "Jan"
<|> 2 <$ string "Feb"
<|> 3 <$ string "Mar"
<|> 4 <$ string "Apr"
<|> 5 <$ string "May"
<|> 6 <$ string "Jun"
<|> 7 <$ string "Jul"
<|> 8 <$ string "Aug"
<|> 9 <$ string "Sep"
<|> 10 <$ string "Oct"
<|> 11 <$ string "Nov"
<|> 12 <$ string "Dec"
digit2 :: Parser Int
digit2 = do
x1 <- toInt <$> digit
x2 <- toInt <$> digit
return $ x1 * 10 + x2
digit4 :: Parser Int
digit4 = do
x1 <- toInt <$> digit
x2 <- toInt <$> digit
x3 <- toInt <$> digit
x4 <- toInt <$> digit
return $ x1 * 1000 + x2 * 100 + x3 * 10 + x4
toInt :: Char -> Int
toInt c = ord c - ord '0'
| kazu-yamamoto/http-date | Network/HTTP/Date/Parser.hs | bsd-3-clause | 2,483 | 0 | 28 | 718 | 822 | 415 | 407 | 85 | 2 |
{-# LANGUAGE Arrows #-}
module
Types.LoopSpec
where
import Data.Functor
import Control.Arrow
import Test.Hspec
import Control.Arrow.Machine as P
import Control.Monad.Trans (liftIO)
import Data.IORef
import Common.RandomProc
doubler = arr (fmap $ \x -> [x, x]) >>> P.fork
spec =
do
it "is possible that value by `dHold` or `dAccum` can refer at upstream." $
do
ref <- newIORef ([] :: [Int])
let
pa :: ProcessT IO (Event Int) (Event ())
pa = proc evx ->
do
rec
P.fire print -< y <$ evx
P.fire putStr -< "" <$ evx -- side effect
evx2 <- doubler -< evx
y <- P.dAccum 0 -< (+) <$> evx2
fire (\x -> modifyIORef ref (x:)) -< y <$ evx
liftIO $ P.runT_ pa [1, 2, 3]
ret <- readIORef ref
reverse ret `shouldBe` [0, 1+1, 1+1+2+2]
it "can be used with rec statement(pure)" $
let
a = proc ev ->
do
x <- hold 0 -< ev
rec l <- returnA -< x:l
returnA -< l <$ ev
result = fst $ stateProc a [2, 5]
in
take 3 (result!!1) `shouldBe` [5, 5, 5]
it "the last value is valid." $
do
let
mc = repeatedly $
do
x <- await
yield x
yield (x*2)
pa = proc x ->
do
rec y <- mc -< (+z) <$> x
z <- dHold 0 -< y
returnA -< y
run pa [1, 10] `shouldBe` [1, 2, 12, 24]
it "carries no events to upstream." $
do
let
pa = proc ev ->
do
rec r <- dHold True -< False <$ ev2
ev2 <- fork -< [(), ()] <$ ev
returnA -< r <$ ev
run pa [1, 2, 3] `shouldBe` [True, True, True]
| as-capabl/machinecell | test/Types/LoopSpec.hs | bsd-3-clause | 1,929 | 4 | 33 | 880 | 703 | 354 | 349 | 61 | 1 |
{-# LANGUAGE CPP #-}
import Control.Monad (forM_, when)
import Distribution.Simple
import Distribution.Simple.InstallDirs (InstallDirs(..), fromPathTemplate, toPathTemplate)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..))
import Distribution.Simple.Setup (ConfigFlags(..), fromFlag, fromFlagOrDefault)
import System.FilePath ((</>))
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
import System.Directory (copyFile)
#else
import System.Directory (doesFileExist, removeFile)
import System.Posix.Files (createSymbolicLink)
#endif
main :: IO ()
main = defaultMainWithHooks simpleUserHooks {
-- Uses a postCopy hook because postInst is not working.
postCopy = postInstall}
where postInstall _ _ _ buildInfo = do
let dirs = configInstallDirs $ configFlags buildInfo
dir = (fromPathTemplate . fromFlag $ prefix dirs) </> (fromPathTemplate . fromFlagOrDefault (toPathTemplate "bin") $ bindir dirs)
#if defined(mingw32_HOST_OS) || defined(__MINGW32__)
mapM_ (copyFile "redo.exe") $ map (dir </>) ["redo-ifchange", "redo-ifcreate", "redo-iftouch", "redo-status"]
#else
makeSymlinks "redo" $ map (dir </>) ["redo-ifchange", "redo-ifcreate", "redo-iftouch", "redo-status"]
#endif
makeSymlinks :: FilePath -> [FilePath] -> IO ()
makeSymlinks src links = forM_ links $ \symlink -> do
exists <- doesFileExist symlink
when exists $ removeFile symlink
createSymbolicLink src symlink
| comatose/redo | Setup.hs | bsd-3-clause | 1,441 | 0 | 16 | 207 | 321 | 177 | 144 | 21 | 1 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -Wno-orphans #-}
{-# OPTIONS_GHC -Wno-missing-signatures #-}
-- | The nix expression type and supporting types.
module Nix.Expr.Types where
#ifdef MIN_VERSION_serialise
import Codec.Serialise ( Serialise )
import qualified Codec.Serialise as Ser
#endif
import Control.Applicative
import Control.DeepSeq
import Control.Monad
import Data.Aeson
import Data.Aeson.TH
import Data.Binary ( Binary )
import qualified Data.Binary as Bin
import Data.Data
import Data.Eq.Deriving
import Data.Fix
import Data.Functor.Classes
import Data.Hashable
#if MIN_VERSION_hashable(1, 2, 5)
import Data.Hashable.Lifted
#endif
import Data.List ( inits
, tails
)
import Data.List.NonEmpty ( NonEmpty(..) )
import qualified Data.List.NonEmpty as NE
import Data.Maybe ( fromMaybe )
import Data.Ord.Deriving
import Data.Text ( Text
, pack
, unpack
)
import Data.Traversable
import GHC.Exts
import GHC.Generics
import Language.Haskell.TH.Syntax
import Lens.Family2
import Lens.Family2.TH
import Nix.Atoms
import Nix.Utils
import Text.Megaparsec.Pos
import Text.Read.Deriving
import Text.Show.Deriving
#if MIN_VERSION_base(4, 10, 0)
import Type.Reflection ( eqTypeRep )
import qualified Type.Reflection as Reflection
#endif
type VarName = Text
hashAt :: VarName -> Lens' (AttrSet v) (Maybe v)
hashAt = flip alterF
-- unfortunate orphans
#if MIN_VERSION_hashable(1, 2, 5)
instance Hashable1 NonEmpty
#endif
#if !MIN_VERSION_base(4, 10, 0)
instance Eq1 NonEmpty where
liftEq eq (a NE.:| as) (b NE.:| bs) = eq a b && liftEq eq as bs
instance Show1 NonEmpty where
liftShowsPrec shwP shwL p (a NE.:| as) = showParen (p > 5) $
shwP 6 a . showString " :| " . shwL as
#endif
#if !MIN_VERSION_binary(0, 8, 4)
instance Binary a => Binary (NE.NonEmpty a) where
get = fmap NE.fromList Bin.get
put = Bin.put . NE.toList
#endif
-- | The main nix expression type. This is polymorphic so that it can be made
-- a functor, which allows us to traverse expressions and map functions over
-- them. The actual 'NExpr' type is a fixed point of this functor, defined
-- below.
data NExprF r
= NConstant !NAtom
-- ^ Constants: ints, bools, URIs, and null.
| NStr !(NString r)
-- ^ A string, with interpolated expressions.
| NSym !VarName
-- ^ A variable. For example, in the expression @f a@, @f@ is represented
-- as @NSym "f"@ and @a@ as @NSym "a"@.
| NList ![r]
-- ^ A list literal.
| NSet ![Binding r]
-- ^ An attribute set literal, not recursive.
| NRecSet ![Binding r]
-- ^ An attribute set literal, recursive.
| NLiteralPath !FilePath
-- ^ A path expression, which is evaluated to a store path. The path here
-- can be relative, in which case it's evaluated relative to the file in
-- which it appears.
| NEnvPath !FilePath
-- ^ A path which refers to something in the Nix search path (the NIX_PATH
-- environment variable. For example, @<nixpkgs/pkgs>@.
| NUnary !NUnaryOp !r
-- ^ Application of a unary operator to an expression.
| NBinary !NBinaryOp !r !r
-- ^ Application of a binary operator to two expressions.
| NSelect !r !(NAttrPath r) !(Maybe r)
-- ^ Dot-reference into an attribute set, optionally providing an
-- alternative if the key doesn't exist.
| NHasAttr !r !(NAttrPath r)
-- ^ Ask if a set contains a given attribute path.
| NAbs !(Params r) !r
-- ^ A function literal (lambda abstraction).
| NLet ![Binding r] !r
-- ^ Evaluate the second argument after introducing the bindings.
| NIf !r !r !r
-- ^ If-then-else statement.
| NWith !r !r
-- ^ Evaluate an attribute set, bring its bindings into scope, and
-- evaluate the second argument.
| NAssert !r !r
-- ^ Assert that the first returns true before evaluating the second.
| NSynHole !VarName
-- ^ Syntactic hole, e.g. @^foo@ , @^hole_name@
deriving (Ord, Eq, Generic, Generic1, Typeable, Data, Functor,
Foldable, Traversable, Show, NFData, Hashable)
#if MIN_VERSION_hashable(1, 2, 5)
instance Hashable1 NExprF
#endif
#if MIN_VERSION_deepseq(1, 4, 3)
instance NFData1 NExprF
#endif
#ifdef MIN_VERSION_serialise
instance Serialise r => Serialise (NExprF r)
#endif
-- | We make an `IsString` for expressions, where the string is interpreted
-- as an identifier. This is the most common use-case...
instance IsString NExpr where
fromString = Fix . NSym . fromString
#if MIN_VERSION_base(4, 10, 0)
instance Lift (Fix NExprF) where
lift = dataToExpQ $ \b ->
case Reflection.typeOf b `eqTypeRep` Reflection.typeRep @Text of
Just HRefl -> Just [| pack $(liftString $ unpack b) |]
Nothing -> Nothing
#else
instance Lift (Fix NExprF) where
lift = dataToExpQ $ \b -> case cast b of
Just t -> Just [| pack $(liftString $ unpack t) |]
Nothing -> Nothing
#endif
-- | The monomorphic expression type is a fixed point of the polymorphic one.
type NExpr = Fix NExprF
#ifdef MIN_VERSION_serialise
instance Serialise NExpr
#endif
-- | A single line of the bindings section of a let expression or of a set.
data Binding r
= NamedVar !(NAttrPath r) !r !SourcePos
-- ^ An explicit naming, such as @x = y@ or @x.y = z@.
| Inherit !(Maybe r) ![NKeyName r] !SourcePos
-- ^ Using a name already in scope, such as @inherit x;@ which is shorthand
-- for @x = x;@ or @inherit (x) y;@ which means @y = x.y;@. The
-- unsafeGetAttrPos for every name so inherited is the position of the
-- first name, whether that be the first argument to this constructor, or
-- the first member of the list in the second argument.
deriving (Generic, Generic1, Typeable, Data, Ord, Eq, Functor,
Foldable, Traversable, Show, NFData, Hashable)
#if MIN_VERSION_hashable(1, 2, 5)
instance Hashable1 Binding
#endif
#if MIN_VERSION_deepseq(1, 4, 3)
instance NFData1 Binding
#endif
#ifdef MIN_VERSION_serialise
instance Serialise r => Serialise (Binding r)
#endif
-- | @Params@ represents all the ways the formal parameters to a
-- function can be represented.
data Params r
= Param !VarName
-- ^ For functions with a single named argument, such as @x: x + 1@.
| ParamSet !(ParamSet r) !Bool !(Maybe VarName)
-- ^ Explicit parameters (argument must be a set). Might specify a name to
-- bind to the set in the function body. The bool indicates whether it is
-- variadic or not.
deriving (Ord, Eq, Generic, Generic1, Typeable, Data, Functor, Show,
Foldable, Traversable, NFData, Hashable)
#if MIN_VERSION_hashable(1, 2, 5)
instance Hashable1 Params
#endif
#if MIN_VERSION_deepseq(1, 4, 3)
instance NFData1 Params
#endif
#ifdef MIN_VERSION_serialise
instance Serialise r => Serialise (Params r)
#endif
-- This uses an association list because nix XML serialization preserves the
-- order of the param set.
type ParamSet r = [(VarName, Maybe r)]
instance IsString (Params r) where
fromString = Param . fromString
-- | 'Antiquoted' represents an expression that is either
-- antiquoted (surrounded by ${...}) or plain (not antiquoted).
data Antiquoted (v :: *) (r :: *) = Plain !v | EscapedNewline | Antiquoted !r
deriving (Ord, Eq, Generic, Generic1, Typeable, Data, Functor, Foldable,
Traversable, Show, Read, NFData, Hashable)
#if MIN_VERSION_hashable(1, 2, 5)
instance Hashable v => Hashable1 (Antiquoted v)
instance Hashable2 Antiquoted where
liftHashWithSalt2 ha _ salt (Plain a) = ha (salt `hashWithSalt` (0 :: Int)) a
liftHashWithSalt2 _ _ salt EscapedNewline = salt `hashWithSalt` (1 :: Int)
liftHashWithSalt2 _ hb salt (Antiquoted b) =
hb (salt `hashWithSalt` (2 :: Int)) b
#endif
#if MIN_VERSION_deepseq(1, 4, 3)
instance NFData v => NFData1 (Antiquoted v)
#endif
#ifdef MIN_VERSION_serialise
instance (Serialise v, Serialise r) => Serialise (Antiquoted v r)
#endif
-- | An 'NString' is a list of things that are either a plain string
-- or an antiquoted expression. After the antiquotes have been evaluated,
-- the final string is constructed by concating all the parts.
data NString r
= DoubleQuoted ![Antiquoted Text r]
-- ^ Strings wrapped with double-quotes (") can contain literal newline
-- characters, but the newlines are preserved and no indentation is stripped.
| Indented !Int ![Antiquoted Text r]
-- ^ Strings wrapped with two single quotes ('') can contain newlines, and
-- their indentation will be stripped, but the amount stripped is
-- remembered.
deriving (Eq, Ord, Generic, Generic1, Typeable, Data, Functor, Foldable,
Traversable, Show, Read, NFData, Hashable)
#if MIN_VERSION_hashable(1, 2, 5)
instance Hashable1 NString
#endif
#if MIN_VERSION_deepseq(1, 4, 3)
instance NFData1 NString
#endif
#ifdef MIN_VERSION_serialise
instance Serialise r => Serialise (NString r)
#endif
-- | For the the 'IsString' instance, we use a plain doublequoted string.
instance IsString (NString r) where
fromString "" = DoubleQuoted []
fromString string = DoubleQuoted [Plain $ pack string]
-- | A 'KeyName' is something that can appear on the left side of an
-- equals sign. For example, @a@ is a 'KeyName' in @{ a = 3; }@, @let a = 3;
-- in ...@, @{}.a@ or @{} ? a@.
--
-- Nix supports both static keynames (just an identifier) and dynamic
-- identifiers. Dynamic identifiers can be either a string (e.g.:
-- @{ "a" = 3; }@) or an antiquotation (e.g.: @let a = "example";
-- in { ${a} = 3; }.example@).
--
-- Note: There are some places where a dynamic keyname is not allowed.
-- In particular, those include:
--
-- * The RHS of a @binding@ inside @let@: @let ${"a"} = 3; in ...@
-- produces a syntax error.
-- * The attribute names of an 'inherit': @inherit ${"a"};@ is forbidden.
--
-- Note: In Nix, a simple string without antiquotes such as @"foo"@ is
-- allowed even if the context requires a static keyname, but the
-- parser still considers it a 'DynamicKey' for simplicity.
data NKeyName r
= DynamicKey !(Antiquoted (NString r) r)
| StaticKey !VarName
deriving (Eq, Ord, Generic, Typeable, Data, Show, Read, NFData, Hashable)
#ifdef MIN_VERSION_serialise
instance Serialise r => Serialise (NKeyName r)
instance Serialise Pos where
encode x = Ser.encode (unPos x)
decode = mkPos <$> Ser.decode
instance Serialise SourcePos where
encode (SourcePos f l c) = Ser.encode f <> Ser.encode l <> Ser.encode c
decode = SourcePos <$> Ser.decode <*> Ser.decode <*> Ser.decode
#endif
instance Hashable Pos where
hashWithSalt salt x = hashWithSalt salt (unPos x)
instance Hashable SourcePos where
hashWithSalt salt (SourcePos f l c) =
salt `hashWithSalt` f `hashWithSalt` l `hashWithSalt` c
instance Generic1 NKeyName where
type Rep1 NKeyName = NKeyName
from1 = id
to1 = id
#if MIN_VERSION_deepseq(1, 4, 3)
instance NFData1 NKeyName where
liftRnf _ (StaticKey !_ ) = ()
liftRnf _ (DynamicKey (Plain !_) ) = ()
liftRnf _ (DynamicKey EscapedNewline) = ()
liftRnf k (DynamicKey (Antiquoted r)) = k r
#endif
-- | Most key names are just static text, so this instance is convenient.
instance IsString (NKeyName r) where
fromString = StaticKey . fromString
instance Eq1 NKeyName where
liftEq eq (DynamicKey a) (DynamicKey b) = liftEq2 (liftEq eq) eq a b
liftEq _ (StaticKey a) (StaticKey b) = a == b
liftEq _ _ _ = False
#if MIN_VERSION_hashable(1, 2, 5)
instance Hashable1 NKeyName where
liftHashWithSalt h salt (DynamicKey a) =
liftHashWithSalt2 (liftHashWithSalt h) h (salt `hashWithSalt` (0 :: Int)) a
liftHashWithSalt _ salt (StaticKey n) =
salt `hashWithSalt` (1 :: Int) `hashWithSalt` n
#endif
-- Deriving this instance automatically is not possible because @r@
-- occurs not only as last argument in @Antiquoted (NString r) r@
instance Show1 NKeyName where
liftShowsPrec sp sl p = \case
DynamicKey a -> showsUnaryWith
(liftShowsPrec2 (liftShowsPrec sp sl) (liftShowList sp sl) sp sl)
"DynamicKey"
p
a
StaticKey t -> showsUnaryWith showsPrec "StaticKey" p t
-- Deriving this instance automatically is not possible because @r@
-- occurs not only as last argument in @Antiquoted (NString r) r@
instance Functor NKeyName where
fmap = fmapDefault
-- Deriving this instance automatically is not possible because @r@
-- occurs not only as last argument in @Antiquoted (NString r) r@
instance Foldable NKeyName where
foldMap = foldMapDefault
-- Deriving this instance automatically is not possible because @r@
-- occurs not only as last argument in @Antiquoted (NString r) r@
instance Traversable NKeyName where
traverse f = \case
DynamicKey (Plain str) -> DynamicKey . Plain <$> traverse f str
DynamicKey (Antiquoted e ) -> DynamicKey . Antiquoted <$> f e
DynamicKey EscapedNewline -> pure $ DynamicKey EscapedNewline
StaticKey key -> pure (StaticKey key)
-- | A selector (for example in a @let@ or an attribute set) is made up
-- of strung-together key names.
type NAttrPath r = NonEmpty (NKeyName r)
-- | There are two unary operations: logical not and integer negation.
data NUnaryOp = NNeg | NNot
deriving (Eq, Ord, Enum, Bounded, Generic, Typeable, Data, Show, Read,
NFData, Hashable)
#ifdef MIN_VERSION_serialise
instance Serialise NUnaryOp
#endif
-- | Binary operators expressible in the nix language.
data NBinaryOp
= NEq -- ^ Equality (==)
| NNEq -- ^ Inequality (!=)
| NLt -- ^ Less than (<)
| NLte -- ^ Less than or equal (<=)
| NGt -- ^ Greater than (>)
| NGte -- ^ Greater than or equal (>=)
| NAnd -- ^ Logical and (&&)
| NOr -- ^ Logical or (||)
| NImpl -- ^ Logical implication (->)
| NUpdate -- ^ Joining two attribute sets (//)
| NPlus -- ^ Addition (+)
| NMinus -- ^ Subtraction (-)
| NMult -- ^ Multiplication (*)
| NDiv -- ^ Division (/)
| NConcat -- ^ List concatenation (++)
| NApp -- ^ Apply a function to an argument.
deriving (Eq, Ord, Enum, Bounded, Generic, Typeable, Data, Show, Read,
NFData, Hashable)
#ifdef MIN_VERSION_serialise
instance Serialise NBinaryOp
#endif
-- | Get the name out of the parameter (there might be none).
paramName :: Params r -> Maybe VarName
paramName (Param n ) = Just n
paramName (ParamSet _ _ n) = n
#if !MIN_VERSION_deepseq(1, 4, 3)
instance NFData NExpr
#endif
$(deriveEq1 ''NExprF)
$(deriveEq1 ''NString)
$(deriveEq1 ''Binding)
$(deriveEq1 ''Params)
$(deriveEq1 ''Antiquoted)
$(deriveEq2 ''Antiquoted)
$(deriveOrd1 ''NString)
$(deriveOrd1 ''Params)
$(deriveOrd1 ''Antiquoted)
$(deriveOrd2 ''Antiquoted)
$(deriveRead1 ''NString)
$(deriveRead1 ''Params)
$(deriveRead1 ''Antiquoted)
$(deriveRead2 ''Antiquoted)
$(deriveShow1 ''NExprF)
$(deriveShow1 ''NString)
$(deriveShow1 ''Params)
$(deriveShow1 ''Binding)
$(deriveShow1 ''Antiquoted)
$(deriveShow2 ''Antiquoted)
-- $(deriveJSON1 defaultOptions ''NExprF)
$(deriveJSON1 defaultOptions ''NString)
$(deriveJSON1 defaultOptions ''Params)
-- $(deriveJSON1 defaultOptions ''Binding)
$(deriveJSON1 defaultOptions ''Antiquoted)
$(deriveJSON2 defaultOptions ''Antiquoted)
instance (Binary v, Binary a) => Binary (Antiquoted v a)
instance Binary a => Binary (NString a)
instance Binary a => Binary (Binding a)
instance Binary Pos where
put x = Bin.put (unPos x)
get = mkPos <$> Bin.get
instance Binary SourcePos
instance Binary a => Binary (NKeyName a)
instance Binary a => Binary (Params a)
instance Binary NAtom
instance Binary NUnaryOp
instance Binary NBinaryOp
instance Binary a => Binary (NExprF a)
instance (ToJSON v, ToJSON a) => ToJSON (Antiquoted v a)
instance ToJSON a => ToJSON (NString a)
instance ToJSON a => ToJSON (Binding a)
instance ToJSON Pos where
toJSON x = toJSON (unPos x)
instance ToJSON SourcePos
instance ToJSON a => ToJSON (NKeyName a)
instance ToJSON a => ToJSON (Params a)
instance ToJSON NAtom
instance ToJSON NUnaryOp
instance ToJSON NBinaryOp
instance ToJSON a => ToJSON (NExprF a)
instance ToJSON NExpr
instance (FromJSON v, FromJSON a) => FromJSON (Antiquoted v a)
instance FromJSON a => FromJSON (NString a)
instance FromJSON a => FromJSON (Binding a)
instance FromJSON Pos where
parseJSON = fmap mkPos . parseJSON
instance FromJSON SourcePos
instance FromJSON a => FromJSON (NKeyName a)
instance FromJSON a => FromJSON (Params a)
instance FromJSON NAtom
instance FromJSON NUnaryOp
instance FromJSON NBinaryOp
instance FromJSON a => FromJSON (NExprF a)
instance FromJSON NExpr
$(makeTraversals ''NExprF)
$(makeTraversals ''Binding)
$(makeTraversals ''Params)
$(makeTraversals ''Antiquoted)
$(makeTraversals ''NString)
$(makeTraversals ''NKeyName)
$(makeTraversals ''NUnaryOp)
$(makeTraversals ''NBinaryOp)
-- $(makeLenses ''Fix)
class NExprAnn ann g | g -> ann where
fromNExpr :: g r -> (NExprF r, ann)
toNExpr :: (NExprF r, ann) -> g r
ekey
:: NExprAnn ann g
=> NonEmpty Text
-> SourcePos
-> Lens' (Fix g) (Maybe (Fix g))
ekey keys pos f e@(Fix x) | (NSet xs, ann) <- fromNExpr x = case go xs of
((v, [] ) : _) -> fromMaybe e <$> f (Just v)
((v, r : rest) : _) -> ekey (r :| rest) pos f v
_ -> f Nothing <&> \case
Nothing -> e
Just v ->
let entry = NamedVar (NE.map StaticKey keys) v pos
in Fix (toNExpr (NSet (entry : xs), ann))
where
go xs = do
let keys' = NE.toList keys
(ks, rest) <- zip (inits keys') (tails keys')
case ks of
[] -> empty
j : js -> do
NamedVar ns v _p <- xs
guard $ (j : js) == (NE.toList ns ^.. traverse . _StaticKey)
return (v, rest)
ekey _ _ f e = fromMaybe e <$> f Nothing
stripPositionInfo :: NExpr -> NExpr
stripPositionInfo = transport phi
where
phi (NSet binds ) = NSet (map go binds)
phi (NRecSet binds ) = NRecSet (map go binds)
phi (NLet binds body) = NLet (map go binds) body
phi x = x
go (NamedVar path r _pos) = NamedVar path r nullPos
go (Inherit ms names _pos) = Inherit ms names nullPos
nullPos :: SourcePos
nullPos = SourcePos "<string>" (mkPos 1) (mkPos 1)
| jwiegley/hnix | src/Nix/Expr/Types.hs | bsd-3-clause | 19,389 | 0 | 21 | 4,394 | 4,480 | 2,323 | 2,157 | -1 | -1 |
module YOLP.Weather.Result (
getWeathers,
Weather (..),
isForecast,
isObserved
) where
import YOLP.Weather.Result.Internal
| lesguillemets/rainfall-vim-hs | src/YOLP/Weather/Result.hs | bsd-3-clause | 140 | 0 | 5 | 29 | 32 | 22 | 10 | 6 | 0 |
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.SmallCheck
import Lib (inc)
main :: IO ()
main = defaultMain $ testGroup "all-tests" tests
tests :: [TestTree]
tests =
[ testGroup "SmallCheck" scTests
, testGroup "Unit tests" huTests
]
scTests :: [TestTree]
scTests =
[ testProperty "inc == succ" prop_succ
, testProperty "inc . negate == negate . pred" prop_pred
]
huTests :: [TestTree]
huTests =
[ testCase "Increment below TheAnswer" case_inc_below
, testCase "Decrement above TheAnswer" case_dec_above
]
prop_succ :: Int -> Bool
prop_succ n = inc n == succ n
prop_pred :: Int -> Bool
prop_pred n = inc (negate n) == negate (pred n)
case_inc_below :: Assertion
case_inc_below = inc 41 @?= (42 :: Int)
case_dec_above :: Assertion
case_dec_above = negate (inc (negate 43)) @?= (42 :: Int)
| mihaimaruseac/test-stack-templates | src-test/Main.hs | isc | 828 | 0 | 10 | 154 | 261 | 140 | 121 | 26 | 1 |
module Pos.DB.Ssc
( module Pos.DB.Ssc.GState
, module Pos.DB.Ssc.Logic
, module Pos.DB.Ssc.SecretStorage
, module Pos.DB.Ssc.State
) where
import Pos.DB.Ssc.GState
import Pos.DB.Ssc.Logic
import Pos.DB.Ssc.SecretStorage
import Pos.DB.Ssc.State
| input-output-hk/pos-haskell-prototype | db/src/Pos/DB/Ssc.hs | mit | 320 | 0 | 5 | 100 | 69 | 50 | 19 | 9 | 0 |
-- (c) 2000-2005 by Martin Erwig [see file COPYRIGHT]
-- | Breadth-First Search Algorithms
module Data.Graph.Inductive.Query.BFS(
-- * BFS Node List
bfs, bfsn, bfsWith, bfsnWith,
-- * Node List With Depth Info
level, leveln,
-- * BFS Edges
bfe, bfen,
-- * BFS Tree
bft, lbft, RTree,
-- * Shortest Path (Number of Edges)
esp, lesp
) where
import Data.Graph.Inductive.Graph
import Data.Graph.Inductive.Internal.Queue
import Data.Graph.Inductive.Internal.RootPath
-- bfs (node list ordered by distance)
--
bfsnInternal :: (Graph gr) => (Context a b -> c) -> Queue Node -> gr a b -> [c]
bfsnInternal f q g | queueEmpty q || isEmpty g = []
| otherwise =
case match v g of
(Just c, g') -> f c:bfsnInternal f (queuePutList (suc' c) q') g'
(Nothing, g') -> bfsnInternal f q' g'
where (v,q') = queueGet q
bfsnWith :: (Graph gr) => (Context a b -> c) -> [Node] -> gr a b -> [c]
bfsnWith f vs = bfsnInternal f (queuePutList vs mkQueue)
bfsn :: (Graph gr) => [Node] -> gr a b -> [Node]
bfsn = bfsnWith node'
bfsWith :: (Graph gr) => (Context a b -> c) -> Node -> gr a b -> [c]
bfsWith f v = bfsnInternal f (queuePut v mkQueue)
bfs :: (Graph gr) => Node -> gr a b -> [Node]
bfs = bfsWith node'
-- level (extension of bfs giving the depth of each node)
--
level :: (Graph gr) => Node -> gr a b -> [(Node,Int)]
level v = leveln [(v,0)]
suci :: Context a b -> Int -> [(Node, Int)]
suci c i = zip (suc' c) (repeat i)
leveln :: (Graph gr) => [(Node,Int)] -> gr a b -> [(Node,Int)]
leveln [] _ = []
leveln _ g | isEmpty g = []
leveln ((v,j):vs) g = case match v g of
(Just c,g') -> (v,j):leveln (vs++suci c (j+1)) g'
(Nothing,g') -> leveln vs g'
-- bfe (breadth first edges)
-- remembers predecessor information
--
bfenInternal :: (Graph gr) => Queue Edge -> gr a b -> [Edge]
bfenInternal q g | queueEmpty q || isEmpty g = []
| otherwise =
case match v g of
(Just c, g') -> (u,v):bfenInternal (queuePutList (outU c) q') g'
(Nothing, g') -> bfenInternal q' g'
where ((u,v),q') = queueGet q
bfen :: (Graph gr) => [Edge] -> gr a b -> [Edge]
bfen vs = bfenInternal (queuePutList vs mkQueue)
bfe :: (Graph gr) => Node -> gr a b -> [Edge]
bfe v = bfen [(v,v)]
outU :: Context a b -> [Edge]
outU c = map toEdge (out' c)
-- bft (breadth first search tree)
-- here: with inward directed trees
--
-- bft :: Node -> gr a b -> IT.InTree Node
-- bft v g = IT.build $ map swap $ bfe v g
-- where swap (x,y) = (y,x)
--
-- sp (shortest path wrt to number of edges)
--
-- sp :: Node -> Node -> gr a b -> [Node]
-- sp s t g = reverse $ IT.rootPath (bft s g) t
-- faster shortest paths
-- here: with root path trees
--
bft :: (Graph gr) => Node -> gr a b -> RTree
bft v = bf (queuePut [v] mkQueue)
bf :: (Graph gr) => Queue Path -> gr a b -> RTree
bf q g | queueEmpty q || isEmpty g = []
| otherwise =
case match v g of
(Just c, g') -> p:bf (queuePutList (map (:p) (suc' c)) q') g'
(Nothing, g') -> bf q' g'
where (p@(v:_),q') = queueGet q
esp :: (Graph gr) => Node -> Node -> gr a b -> Path
esp s t = getPath t . bft s
-- lesp is a version of esp that returns labeled paths
-- Note that the label of the first node in a returned path is meaningless;
-- all other nodes are paired with the label of their incoming edge.
--
lbft :: (Graph gr) => Node -> gr a b -> LRTree b
lbft v g = case out g v of
[] -> [LP []]
(v',_,l):_ -> lbf (queuePut (LP [(v',l)]) mkQueue) g
lbf :: (Graph gr) => Queue (LPath b) -> gr a b -> LRTree b
lbf q g | queueEmpty q || isEmpty g = []
| otherwise =
case match v g of
(Just c, g') ->
LP p:lbf (queuePutList (map (\v' -> LP (v':p)) (lsuc' c)) q') g'
(Nothing, g') -> lbf q' g'
where (LP (p@((v,_):_)),q') = queueGet q
lesp :: (Graph gr) => Node -> Node -> gr a b -> LPath b
lesp s t = getLPath t . lbft s
| antalsz/hs-to-coq | examples/graph/graph/Data/Graph/Inductive/Query/BFS.hs | mit | 4,151 | 0 | 19 | 1,231 | 1,734 | 913 | 821 | 72 | 2 |
{-# LANGUAGE ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Window (
module Generated
, js_openDatabase
, openDatabase
) where
import Control.Monad.IO.Class (MonadIO(..))
import GHCJS.Types (JSString)
import GHCJS.DOM.Types
import GHCJS.DOM.JSFFI.Generated.Window as Generated hiding (js_openDatabase, openDatabase)
foreign import javascript interruptible
"(function(db) { if(db) $c(db) })($1[\"openDatabase\"]($2, $3, $4, $5, function(d) { $c(d) }));" js_openDatabase ::
Window -> JSString -> JSString -> JSString -> Word -> IO Database
-- | <https://developer.mozilla.org/en-US/docs/Web/API/Window.openDatabase Mozilla Window.openDatabase documentation>
openDatabase :: (MonadIO m, ToJSString name, ToJSString version, ToJSString displayName) =>
Window -> name -> version -> displayName -> Word -> m Database
openDatabase self name version displayName estimatedSize = liftIO $
js_openDatabase
self
(toJSString name)
(toJSString version)
(toJSString displayName)
estimatedSize
| manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Window.hs | mit | 1,087 | 14 | 8 | 197 | 215 | 122 | 93 | -1 | -1 |
{-# LANGUAGE MultiParamTypeClasses, TypeSynonymInstances, FlexibleInstances #-}
{- |
Module : ./Comorphisms/CASL2VSEImport.hs
Description : embedding from CASL to VSE, plus wrapping procedures
with default implementations
Copyright : (c) M.Codescu, DFKI Bremen 2008
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Mihai.Codescu@dfki.de
Stability : provisional
Portability : non-portable (imports Logic.Logic)
The embedding comorphism from CASL to VSE.
-}
module Comorphisms.CASL2VSEImport (CASL2VSEImport (..)) where
import Logic.Logic
import Logic.Comorphism
import CASL.Logic_CASL
import CASL.Sublogic as SL
import CASL.Sign
import CASL.AS_Basic_CASL
import CASL.Morphism
import VSE.Logic_VSE
import VSE.As
import VSE.Ana
import Common.AS_Annotation
import Common.Id
import Common.ProofTree
import Common.Result
import qualified Common.Lib.MapSet as MapSet
import qualified Data.Set as Set
import qualified Data.Map as Map
-- | The identity of the comorphism
data CASL2VSEImport = CASL2VSEImport deriving (Show)
instance Language CASL2VSEImport -- default definition is okay
instance Comorphism CASL2VSEImport
CASL CASL_Sublogics
CASLBasicSpec CASLFORMULA SYMB_ITEMS SYMB_MAP_ITEMS
CASLSign
CASLMor
Symbol RawSymbol ProofTree
VSE ()
VSEBasicSpec Sentence SYMB_ITEMS SYMB_MAP_ITEMS
VSESign
VSEMor
Symbol RawSymbol () where
sourceLogic CASL2VSEImport = CASL
sourceSublogic CASL2VSEImport = SL.cFol
targetLogic CASL2VSEImport = VSE
mapSublogic CASL2VSEImport _ = Just ()
map_theory CASL2VSEImport = mapCASLTheory
map_morphism CASL2VSEImport = return . mapMor
map_sentence CASL2VSEImport _ = return . mapFORMULA
map_symbol CASL2VSEImport = error "nyi"
-- check these 3, but should be fine
has_model_expansion CASL2VSEImport = True
is_weakly_amalgamable CASL2VSEImport = True
isInclusionComorphism CASL2VSEImport = True
mapCASLTheory :: (CASLSign, [Named CASLFORMULA]) ->
Result (VSESign, [Named Sentence])
mapCASLTheory (sig, n_sens) =
let (tsig, genAx) = mapSig sig
tsens = map (mapNamed mapFORMULA) n_sens
in if not $ null $ checkCases tsig (tsens ++ genAx)
then fail "case error in signature"
else return (tsig, tsens ++ genAx)
mkIfProg :: FORMULA () -> Program
mkIfProg f =
mkRanged $ If f (mkRanged $ Return aTrue) $ mkRanged $ Return aFalse
mapSig :: CASLSign -> (VSESign, [Named Sentence])
mapSig sign =
let wrapSort (procsym, axs) s = let
restrName = gnRestrName s
eqName = gnEqName s
sProcs = [(restrName, Profile [Procparam In s] Nothing),
(eqName,
Profile [Procparam In s, Procparam In s]
(Just uBoolean))]
sSens = [makeNamed ("ga_restriction_" ++ show s) $ ExtFORMULA $
mkRanged
(Defprocs
[Defproc Proc restrName [xVar]
(mkRanged (Block [] (mkRanged Skip)))
nullRange])
, makeNamed ("ga_equality_" ++ show s) $ ExtFORMULA $
mkRanged
(Defprocs
[Defproc Func eqName (map mkSimpleId ["x", "y"])
(mkRanged (Block [] (mkIfProg (mkStEq
(Qual_var (mkSimpleId "x") s nullRange)
(Qual_var (mkSimpleId "y") s nullRange)
))))
nullRange])
]
in
(sProcs ++ procsym, sSens ++ axs)
(sortProcs, sortSens) = foldl wrapSort ([], []) $
Set.toList $ sortSet sign
wrapOp (procsym, axs) (i, opTypes) = let
funName = mkGenName i
fProcs = map (\ profile ->
(funName,
Profile
(map (Procparam In) $ opArgs profile)
(Just $ opRes profile))) opTypes
fSens = map (\ (OpType fKind w s) -> let vars = genVars w in
makeNamed "" $ ExtFORMULA $ Ranged
(Defprocs
[Defproc
Func funName (map fst vars)
( Ranged (Block []
(Ranged
(Block
[Var_decl [yVar] s nullRange]
(Ranged
(Seq
(Ranged
(Assign
yVar
(Application
(Qual_op_name i
(Op_type fKind w s nullRange)
nullRange )
(map (\ (v, ss) ->
Qual_var v ss nullRange) vars)
nullRange))
nullRange)
(Ranged
(Return
(Qual_var yVar s nullRange))
nullRange)
) -- end seq
nullRange)
) -- end block
nullRange) -- end procedure body
) nullRange)
nullRange]
)
nullRange
) opTypes
in
(procsym ++ fProcs, axs ++ fSens)
(opProcs, opSens) = foldl wrapOp ([], []) $
MapSet.toList $ opMap sign
wrapPred (procsym, axs) (i, predTypes) = let
procName = mkGenName i
pProcs = map (\ profile -> (procName,
Profile
(map (Procparam In) $ predArgs profile)
(Just uBoolean))) predTypes
pSens = map (\ (PredType w) -> let vars = genVars w in
makeNamed "" $ ExtFORMULA $ mkRanged
(Defprocs
[Defproc
Func procName (map fst vars)
(mkRanged (Block [] (mkIfProg
(Predication
(Qual_pred_name
i
(Pred_type w nullRange)
nullRange)
(map (\ (v, ss) ->
Qual_var v ss nullRange) vars)
nullRange))))
nullRange]
)
) predTypes
in
(procsym ++ pProcs, axs ++ pSens)
(predProcs, predSens) = foldl wrapPred ([], []) $
MapSet.toList $ predMap sign
procs = Procs $ Map.fromList (sortProcs ++ opProcs ++ predProcs)
newPreds = procsToPredMap procs
newOps = procsToOpMap procs
in (sign { opMap = addOpMapSet (opMap sign) newOps,
predMap = addMapSet (predMap sign) newPreds,
extendedInfo = procs,
sentences = [] }, sortSens ++ opSens ++ predSens)
mapMor :: CASLMor -> VSEMor
mapMor m = let
(om, pm) = vseMorExt m
in m
{ msource = fst $ mapSig $ msource m
, mtarget = fst $ mapSig $ mtarget m
, op_map = Map.union om $ op_map m
, pred_map = Map.union pm $ pred_map m
, extended_map = emptyMorExt
}
| spechub/Hets | Comorphisms/CASL2VSEImport.hs | gpl-2.0 | 7,904 | 0 | 46 | 3,577 | 1,802 | 946 | 856 | 163 | 2 |
module CO4.Thesis.LoopStandalone
where
import Prelude hiding (elem)
import CO4.Prelude.Nat
data Pair a b = Pair a b deriving Show
data List a = Nill | Conss a (List a) deriving Show
data Term = Var Nat
| Node Nat (List Term)
deriving (Show)
data Unary = Z | S Unary deriving Show
data Step = Step Term
(Pair Term Term) -- Rule
(List Unary) -- Position
(List (Pair Nat Term)) -- Substitution
Term
deriving Show
data LoopingDerivation = LoopingDerivation (List Step) -- Derivation
(List Unary) -- Position
(List (Pair Nat Term)) -- Substitution
deriving Show
constraint :: List (Pair Term Term) -> LoopingDerivation -> Bool
constraint trs deriv = isLoopingDerivation trs deriv
isLoopingDerivation :: List (Pair Term Term) -> LoopingDerivation -> Bool
isLoopingDerivation trs loopDeriv = case loopDeriv of
LoopingDerivation deriv pos sub ->
case deriv of
Nill -> False
Conss step _ -> case step of
Step t0 _ _ _ _ ->
let last = deriveTerm trs t0 deriv
subLast = getSubterm pos last
t0' = applySubstitution sub t0
in
eqTerm t0' subLast
deriveTerm :: List (Pair Term Term) -> Term -> (List Step) -> Term
deriveTerm trs term deriv = case deriv of
Nill -> term
Conss step steps -> case isValidStep trs step of
False -> undefined
True -> case step of
Step t0 rule pos sub t1 -> case eqTerm term t0 of
False -> undefined
True -> deriveTerm trs t1 steps
isValidStep :: List (Pair Term Term) -> Step -> Bool
isValidStep trs step = case step of
Step t0 rule pos sub t1 ->
and2 (isValidRule trs rule)
(case rule of
Pair lhs rhs ->
let subT0 = getSubterm pos t0
lhs' = applySubstitution sub lhs
rhs' = applySubstitution sub rhs
result = putSubterm t0 pos rhs'
in
and2 (eqTerm subT0 lhs')
(eqTerm result t1)
)
isValidRule :: List (Pair Term Term) -> Pair Term Term -> Bool
isValidRule trs rule = elem eqRule rule trs
getSubterm :: (List Unary) -> Term -> Term
getSubterm pos term = case pos of
Nill -> term
Conss p pos' -> case term of
Var v -> undefined
Node f ts -> getSubterm pos' (at p ts)
putSubterm :: Term -> (List Unary) -> Term -> Term
putSubterm term pos term' = case pos of
Nill -> term'
Conss p pos' -> case term of
Var v -> undefined
Node f ts -> Node f (replace p ts (putSubterm (at p ts) pos' term'))
applySubstitution :: List (Pair Nat Term) -> Term -> Term
applySubstitution subs term = case term of
Var v -> applySubstitutionToVar subs v
Node f ts -> Node f (map' (\t -> applySubstitution subs t) ts)
applySubstitutionToVar :: List (Pair Nat Term) -> Nat -> Term
applySubstitutionToVar sub v = case sub of
Nill -> Var v -- ??
Conss s ss -> case s of
Pair name term -> case eqNat v name of
False -> applySubstitutionToVar ss v
True -> term
at :: Unary -> List a -> a
at u xs = case xs of
Nill -> undefined
Conss y ys -> case u of
Z -> y
S u' -> at u' ys
replace :: Unary -> List a -> a -> List a
replace u xs x = case xs of
Nill -> undefined
Conss y ys -> case u of
Z -> Conss x ys
S u' -> Conss y (replace u' ys x)
eqRule :: Pair Term Term -> Pair Term Term -> Bool
eqRule x y = case x of
Pair xLhs xRhs -> case y of
Pair yLhs yRhs -> and2 (eqTerm xLhs yLhs) (eqTerm xRhs yRhs)
elem :: (a -> a -> Bool) -> a -> List a -> Bool
elem eq x xs = case xs of
Nill -> False
Conss y ys -> or2 (eq x y) (elem eq x ys)
eqTerm :: Term -> Term -> Bool
eqTerm x y = case x of
Var xV -> case y of
Var yV -> eqNat xV yV
Node g ts -> False
Node f ss -> case y of
Var yV -> False
Node g ts -> and2 (eqNat f g) (eqList eqTerm ss ts)
eqList :: (a -> a -> Bool) -> List a -> List a -> Bool
eqList eq xs ys = case xs of
Nill -> case ys of
Nill -> True
Conss y ys' -> False
Conss x xs' -> case ys of
Nill -> False
Conss y ys' -> and2 (eq x y) (eqList eq xs' ys')
or2 :: Bool -> Bool -> Bool
or2 x y = case x of
True -> True
False -> y
and2 :: Bool -> Bool -> Bool
and2 x y = case x of
False -> False
True -> y
map' :: (a -> b) -> List a -> List b
map' f xs = case xs of
Nill -> Nill
Conss y ys -> Conss (f y) (map' f ys)
| abau/co4 | test/CO4/Thesis/LoopStandalone.hs | gpl-3.0 | 4,629 | 0 | 18 | 1,552 | 1,850 | 913 | 937 | 126 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ElastiCache.DescribeReplicationGroups
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- The /DescribeReplicationGroups/ action returns information about a
-- particular replication group. If no identifier is specified,
-- /DescribeReplicationGroups/ returns information about all replication
-- groups.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_DescribeReplicationGroups.html AWS API Reference> for DescribeReplicationGroups.
--
-- This operation returns paginated results.
module Network.AWS.ElastiCache.DescribeReplicationGroups
(
-- * Creating a Request
describeReplicationGroups
, DescribeReplicationGroups
-- * Request Lenses
, drgsMarker
, drgsMaxRecords
, drgsReplicationGroupId
-- * Destructuring the Response
, describeReplicationGroupsResponse
, DescribeReplicationGroupsResponse
-- * Response Lenses
, drgrsMarker
, drgrsReplicationGroups
, drgrsResponseStatus
) where
import Network.AWS.ElastiCache.Types
import Network.AWS.ElastiCache.Types.Product
import Network.AWS.Pager
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | Represents the input of a /DescribeReplicationGroups/ action.
--
-- /See:/ 'describeReplicationGroups' smart constructor.
data DescribeReplicationGroups = DescribeReplicationGroups'
{ _drgsMarker :: !(Maybe Text)
, _drgsMaxRecords :: !(Maybe Int)
, _drgsReplicationGroupId :: !(Maybe Text)
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeReplicationGroups' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'drgsMarker'
--
-- * 'drgsMaxRecords'
--
-- * 'drgsReplicationGroupId'
describeReplicationGroups
:: DescribeReplicationGroups
describeReplicationGroups =
DescribeReplicationGroups'
{ _drgsMarker = Nothing
, _drgsMaxRecords = Nothing
, _drgsReplicationGroupId = Nothing
}
-- | An optional marker returned from a prior request. Use this marker for
-- pagination of results from this action. If this parameter is specified,
-- the response includes only records beyond the marker, up to the value
-- specified by /MaxRecords/.
drgsMarker :: Lens' DescribeReplicationGroups (Maybe Text)
drgsMarker = lens _drgsMarker (\ s a -> s{_drgsMarker = a});
-- | The maximum number of records to include in the response. If more
-- records exist than the specified 'MaxRecords' value, a marker is
-- included in the response so that the remaining results can be retrieved.
--
-- Default: 100
--
-- Constraints: minimum 20; maximum 100.
drgsMaxRecords :: Lens' DescribeReplicationGroups (Maybe Int)
drgsMaxRecords = lens _drgsMaxRecords (\ s a -> s{_drgsMaxRecords = a});
-- | The identifier for the replication group to be described. This parameter
-- is not case sensitive.
--
-- If you do not specify this parameter, information about all replication
-- groups is returned.
drgsReplicationGroupId :: Lens' DescribeReplicationGroups (Maybe Text)
drgsReplicationGroupId = lens _drgsReplicationGroupId (\ s a -> s{_drgsReplicationGroupId = a});
instance AWSPager DescribeReplicationGroups where
page rq rs
| stop (rs ^. drgrsMarker) = Nothing
| stop (rs ^. drgrsReplicationGroups) = Nothing
| otherwise =
Just $ rq & drgsMarker .~ rs ^. drgrsMarker
instance AWSRequest DescribeReplicationGroups where
type Rs DescribeReplicationGroups =
DescribeReplicationGroupsResponse
request = postQuery elastiCache
response
= receiveXMLWrapper "DescribeReplicationGroupsResult"
(\ s h x ->
DescribeReplicationGroupsResponse' <$>
(x .@? "Marker") <*>
(x .@? "ReplicationGroups" .!@ mempty >>=
may (parseXMLList "ReplicationGroup"))
<*> (pure (fromEnum s)))
instance ToHeaders DescribeReplicationGroups where
toHeaders = const mempty
instance ToPath DescribeReplicationGroups where
toPath = const "/"
instance ToQuery DescribeReplicationGroups where
toQuery DescribeReplicationGroups'{..}
= mconcat
["Action" =:
("DescribeReplicationGroups" :: ByteString),
"Version" =: ("2015-02-02" :: ByteString),
"Marker" =: _drgsMarker,
"MaxRecords" =: _drgsMaxRecords,
"ReplicationGroupId" =: _drgsReplicationGroupId]
-- | Represents the output of a /DescribeReplicationGroups/ action.
--
-- /See:/ 'describeReplicationGroupsResponse' smart constructor.
data DescribeReplicationGroupsResponse = DescribeReplicationGroupsResponse'
{ _drgrsMarker :: !(Maybe Text)
, _drgrsReplicationGroups :: !(Maybe [ReplicationGroup])
, _drgrsResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DescribeReplicationGroupsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'drgrsMarker'
--
-- * 'drgrsReplicationGroups'
--
-- * 'drgrsResponseStatus'
describeReplicationGroupsResponse
:: Int -- ^ 'drgrsResponseStatus'
-> DescribeReplicationGroupsResponse
describeReplicationGroupsResponse pResponseStatus_ =
DescribeReplicationGroupsResponse'
{ _drgrsMarker = Nothing
, _drgrsReplicationGroups = Nothing
, _drgrsResponseStatus = pResponseStatus_
}
-- | Provides an identifier to allow retrieval of paginated results.
drgrsMarker :: Lens' DescribeReplicationGroupsResponse (Maybe Text)
drgrsMarker = lens _drgrsMarker (\ s a -> s{_drgrsMarker = a});
-- | A list of replication groups. Each item in the list contains detailed
-- information about one replication group.
drgrsReplicationGroups :: Lens' DescribeReplicationGroupsResponse [ReplicationGroup]
drgrsReplicationGroups = lens _drgrsReplicationGroups (\ s a -> s{_drgrsReplicationGroups = a}) . _Default . _Coerce;
-- | The response status code.
drgrsResponseStatus :: Lens' DescribeReplicationGroupsResponse Int
drgrsResponseStatus = lens _drgrsResponseStatus (\ s a -> s{_drgrsResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-elasticache/gen/Network/AWS/ElastiCache/DescribeReplicationGroups.hs | mpl-2.0 | 6,975 | 0 | 15 | 1,395 | 920 | 544 | 376 | 106 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Functor.Algebra.Elgot
-- Copyright : (C) 2008 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <ekmett@gmail.com>
-- Stability : experimental
-- Portability : non-portable (rank-2 polymorphism)
--
-- Elgot algebras, and their obvious dual, based on:
-- <http://www.iti.cs.tu-bs.de/~milius/research/elgot_lmcs.pdf>
--
-- Elgot algebras given you a shortcircuitable hylomorphism where you
-- can directly return a sub-answer to the catamorphism.
--
-- Elgot coalgebras are defined in:
-- <http://comonad.com/reader/2008/elgot-coalgebras/>
----------------------------------------------------------------------------
module Control.Functor.Algebra.Elgot
( elgot
, coelgot
) where
import Control.Arrow ((|||),(&&&))
import Control.Functor.Algebra
-- | Elgot algebra
elgot :: Functor f => Algebra f a -> (b -> Either a (f b)) -> b -> a
elgot phi psi = h where h = (id ||| phi . fmap h) . psi
-- | Elgot coalgebra
coelgot :: Functor f => ((a, f b) -> b) -> Coalgebra f a -> a -> b
coelgot phi psi = h where h = phi . (id &&& fmap h . psi)
| urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav | Control/Functor/Algebra/Elgot.hs | apache-2.0 | 1,205 | 4 | 12 | 198 | 226 | 132 | 94 | -1 | -1 |
{-# OPTIONS_GHC -fno-implicit-prelude #-}
-----------------------------------------------------------------------------
-- |
-- Module : Foreign.Marshal.Error
-- Copyright : (c) The FFI task force 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : ffi@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- Routines for testing return values and raising a 'userError' exception
-- in case of values indicating an error state.
--
-----------------------------------------------------------------------------
module Foreign.Marshal.Error (
throwIf, -- :: (a -> Bool) -> (a -> String) -> IO a -> IO a
throwIf_, -- :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
throwIfNeg, -- :: (Ord a, Num a)
-- => (a -> String) -> IO a -> IO a
throwIfNeg_, -- :: (Ord a, Num a)
-- => (a -> String) -> IO a -> IO ()
throwIfNull, -- :: String -> IO (Ptr a) -> IO (Ptr a)
-- Discard return value
--
void -- IO a -> IO ()
) where
import Foreign.Ptr
#ifdef __GLASGOW_HASKELL__
#ifdef __HADDOCK__
import Data.Bool
import System.IO.Error
#endif
import GHC.Base
import GHC.Num
import GHC.IOBase
#endif
-- exported functions
-- ------------------
-- |Execute an 'IO' action, throwing a 'userError' if the predicate yields
-- 'True' when applied to the result returned by the 'IO' action.
-- If no exception is raised, return the result of the computation.
--
throwIf :: (a -> Bool) -- ^ error condition on the result of the 'IO' action
-> (a -> String) -- ^ computes an error message from erroneous results
-- of the 'IO' action
-> IO a -- ^ the 'IO' action to be executed
-> IO a
throwIf pred msgfct act =
do
res <- act
(if pred res then ioError . userError . msgfct else return) res
-- |Like 'throwIf', but discarding the result
--
throwIf_ :: (a -> Bool) -> (a -> String) -> IO a -> IO ()
throwIf_ pred msgfct act = void $ throwIf pred msgfct act
-- |Guards against negative result values
--
throwIfNeg :: (Ord a, Num a) => (a -> String) -> IO a -> IO a
throwIfNeg = throwIf (< 0)
-- |Like 'throwIfNeg', but discarding the result
--
throwIfNeg_ :: (Ord a, Num a) => (a -> String) -> IO a -> IO ()
throwIfNeg_ = throwIf_ (< 0)
-- |Guards against null pointers
--
throwIfNull :: String -> IO (Ptr a) -> IO (Ptr a)
throwIfNull = throwIf (== nullPtr) . const
-- |Discard the return value of an 'IO' action
--
void :: IO a -> IO ()
void act = act >> return ()
| alekar/hugs | packages/base/Foreign/Marshal/Error.hs | bsd-3-clause | 2,601 | 16 | 12 | 646 | 445 | 259 | 186 | 27 | 2 |
-- | ISO 8601 Week Date format
module Data.Time.Calendar.WeekDate where
import Data.Time.Calendar.OrdinalDate
import Data.Time.Calendar.Days
import Data.Time.Calendar.Private
-- | convert to ISO 8601 Week Date format. First element of result is year, second week number (1-53), third day of week (1 for Monday to 7 for Sunday).
-- Note that \"Week\" years are not quite the same as Gregorian years, as the first day of the year is always a Monday.
-- The first week of a year is the first week to contain at least four days in the corresponding Gregorian year.
toWeekDate :: Day -> (Integer,Int,Int)
toWeekDate date@(ModifiedJulianDay mjd) = (y1,fromInteger (w1 + 1),fromInteger (mod d 7) + 1) where
(y0,yd) = toOrdinalDate date
d = mjd + 2
foo :: Integer -> Integer
foo y = bar (toModifiedJulianDay (fromOrdinalDate y 6))
bar k = (div d 7) - (div k 7)
w0 = bar (d - (toInteger yd) + 4)
(y1,w1) = if w0 == -1
then (y0 - 1,foo (y0 - 1))
else if w0 == 52
then if (foo (y0 + 1)) == 0
then (y0 + 1,0)
else (y0,w0)
else (y0,w0)
-- | convert from ISO 8601 Week Date format. First argument is year, second week number (1-52 or 53), third day of week (1 for Monday to 7 for Sunday).
-- Invalid week and day values will be clipped to the correct range.
fromWeekDate :: Integer -> Int -> Int -> Day
fromWeekDate y w d = ModifiedJulianDay (k - (mod k 7) + (toInteger (((clip 1 (if longYear then 53 else 52) w) * 7) + (clip 1 7 d))) - 10) where
k = toModifiedJulianDay (fromOrdinalDate y 6)
longYear = case toWeekDate (fromOrdinalDate y 365) of
(_,53,_) -> True
_ -> False
-- | convert from ISO 8601 Week Date format. First argument is year, second week number (1-52 or 53), third day of week (1 for Monday to 7 for Sunday).
-- Invalid week and day values will return Nothing.
fromWeekDateValid :: Integer -> Int -> Int -> Maybe Day
fromWeekDateValid y w d = do
d' <- clipValid 1 7 d
let
longYear = case toWeekDate (fromOrdinalDate y 365) of
(_,53,_) -> True
_ -> False
w' <- clipValid 1 (if longYear then 53 else 52) w
let
k = toModifiedJulianDay (fromOrdinalDate y 6)
return (ModifiedJulianDay (k - (mod k 7) + (toInteger ((w' * 7) + d')) - 10))
-- | show in ISO 8601 Week Date format as yyyy-Www-d (e.g. \"2006-W46-3\").
showWeekDate :: Day -> String
showWeekDate date = (show4 (Just '0') y) ++ "-W" ++ (show2 (Just '0') w) ++ "-" ++ (show d) where
(y,w,d) = toWeekDate date
| jwiegley/ghc-release | libraries/time/Data/Time/Calendar/WeekDate.hs | gpl-3.0 | 2,418 | 12 | 18 | 494 | 780 | 420 | 360 | 39 | 4 |
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Control.Monad.ST.Strict (module M) where
import "base" Control.Monad.ST.Strict as M
| Ye-Yong-Chi/codeworld | codeworld-base/src/Control/Monad/ST/Strict.hs | apache-2.0 | 761 | 0 | 4 | 136 | 27 | 21 | 6 | 4 | 0 |
-- HLint configuration file
module HLint.HLint where
-- mimic default HLint.hs
-- https://github.com/ndmitchell/hlint/blob/master/data/HLint.hs
import "hint" HLint.Default
import "hint" HLint.Builtin.All
ignore "Use fewer imports" =
System.Process.Read -- Related to 'Hide post-AMP warnings' comment
Stack.Exec -- ifdef for System.Process.Read
-- Related to 'explicit pattern matching is clearer' comment
ignore "Use fromMaybe" =
Stack.Types.Config.explicitSetupDeps
-- For clarity (related to do syntax)
ignore "Reduce duplication" =
Network.HTTP.Download.VerifiedSpec
Stack.PackageDumpSpec
Stack.Types.StackT
Stack.Docker
-- Not considered useful hints
ignore "Redundant do"
ignore "Use section"
ignore "Use camelCase"
ignore "Use list comprehension"
ignore "Redundant if"
ignore "Avoid lambda"
ignore "Eta reduce"
ignore "Use fmap" -- specific to GHC 7.8 compat
ignore "Parse error" -- we trust the compiler over HLint
ignore "Use ==" -- Creates infinite loops in `EQ` using expressions
ignore "Evaluate"
| AndreasPK/stack | HLint.hs | bsd-3-clause | 1,032 | 0 | 6 | 149 | 150 | 75 | 75 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE TypeFamilies #-}
module T17566a where
import Data.Kind
class C1 (f :: k -> Type) z where
type T1 (x :: f a) :: f a
data D1 (x :: f a)
class C2 f z where
type T2 (x :: f a) :: f a
data D2 (x :: f a)
| sdiehl/ghc | testsuite/tests/typecheck/should_compile/T17566a.hs | bsd-3-clause | 315 | 0 | 8 | 76 | 109 | 64 | 45 | 12 | 0 |
<?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="sr-SP">
<title>Front-End Scanner | 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> | thc202/zap-extensions | addOns/frontendscanner/src/main/javahelp/org/zaproxy/zap/extension/frontendscanner/resources/help_sr_SP/helpset_sr_SP.hs | apache-2.0 | 978 | 78 | 67 | 159 | 417 | 211 | 206 | -1 | -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="ro-RO">
<title>Sequence Scanner | 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> | thc202/zap-extensions | addOns/sequence/src/main/javahelp/org/zaproxy/zap/extension/sequence/resources/help_ro_RO/helpset_ro_RO.hs | apache-2.0 | 977 | 78 | 66 | 159 | 413 | 209 | 204 | -1 | -1 |
module Main where
import Test.HUnit
import System.IO
import qualified System.Cmd as System
import System.Exit
import System.Environment
import Data.List
data TestCases = TestCases {cacheCmd::String
,refactorCmd::String
,positive::[([String],([String], [String]) )]
,negative::[([String],([String], [String]) )]}
deriving (Show,Read)
createNewFileName str fileName
=let (name, posfix)=span (/='.') fileName
in (name++str++posfix)
positiveTest system pfeCmd cacheCmd refactorCmd args
=TestCase (do let inputFiles=fst args
tokExpOutputFiles=map (createNewFileName "_TokOut") inputFiles
--astExpOutputFiles=map (createNewFileName "_AstOut") inputFiles
--astActOutputFiles=map (createNewFileName "AST") inputFiles
tempFiles = map (createNewFileName "_temp") inputFiles
keepFiles = map (createNewFileName "_refac") inputFiles -- ++AZ++
paramsCache =cacheCmd: ((head inputFiles) : (fst (snd args)))
paramsRefac =refactorCmd: ((head inputFiles) : (snd (snd args)))
inputTemps =zip inputFiles tempFiles
inputOutputs1=zip inputFiles tokExpOutputFiles
--inputOutputs2=zip astActOutputFiles astExpOutputFiles
mapM (createTempFile system) inputTemps
system ("echo " ++ concatMap (\t->t ++ " ") paramsCache ++ " |" ++ pfeCmd)
system ("echo " ++ concatMap (\t->t ++ " ") paramsRefac ++ " |" ++ pfeCmd)
mapM (keepResult system) $ zip inputFiles keepFiles -- ++AZ++
results1<-mapM (compareResult system) inputOutputs1
--results2<-mapM (compareResult system) inputOutputs2
mapM (recoverFiles system) inputTemps
mapM (rmTempFiles system) tempFiles
-- mapM (rmTempFiles system) astActOutputFiles
assertEqual (show (refactorCmd,args)) True (all (==ExitSuccess) (results1)) -- ++results2))
)
negativeTest system pfeCmd cacheCmd refactorCmd args
=TestCase (do let inputFiles = fst args
tokExpOutputFiles=map (createNewFileName "_TokOut") inputFiles
tempFiles = map (createNewFileName "_temp") inputFiles
params =refactorCmd: ((head inputFiles) : (snd (snd args)))
inputTemps =zip inputFiles tempFiles
inputOutputs=zip inputFiles tokExpOutputFiles
mapM (createTempFile system) inputTemps
system ("echo " ++ concatMap (\t->t ++ " ") params ++ " |" ++ pfeCmd)
results<-mapM (compareResult system) inputOutputs
mapM (recoverFiles system) inputTemps
mapM (rmTempFiles system) tempFiles
assertEqual (show (refactorCmd,args)) True (all (==ExitSuccess) results)
)
createTempFile system (input, temp)=system ("cp "++ input++ " "++temp)
keepResult system (input, keep)=system ("cp "++ input++ " "++keep)
-- compareResult system (input,output)=system ("diff "++input++ " " ++ output)
compareResult system (input,output)=system ("diff --strip-trailing-cr "++input++ " " ++ output) -- ++AZ++
recoverFiles system (input ,temp)= system ("cp " ++ temp ++ " " ++input)
rmTempFiles system temp = system ("rm "++temp)
testCases system pfeCmd cacheCmd refactorCmd positiveTests negativeTests
=TestList ((map (positiveTest system pfeCmd cacheCmd refactorCmd) positiveTests)
++ (map (negativeTest system pfeCmd cacheCmd refactorCmd) negativeTests))
runTesting system hare cacheCmd refactorCmd positiveTests negativeTests
=do let files=concatMap (\t->t++" ") $ nub (concatMap fst positiveTests ++ concatMap fst negativeTests)
system ("echo new |" ++ hare)
system ("echo add " ++ files ++ " |" ++ hare)
system ("echo chase ../HaskellLibraries/ |" ++ hare)
system ("echo chase . |" ++ hare)
runTestTT (testCases system hare cacheCmd refactorCmd positiveTests negativeTests)
main = do
[bash,hare] <- getArgs
f <- readFile "UTest.data"
let testcases = read f::TestCases
runTesting (system bash) hare
(cacheCmd testcases)
(refactorCmd testcases)
(positive testcases)
(negative testcases)
system bash cmd = --(hPutStrLn stderr cmd')>>
(System.system cmd')
where
-- cmd' = cmd
cmd' = bash++" -c \""++cmd++" >> log.txt 2>>log.txt\""
| RefactoringTools/HaRe | old/testing/introThreshold/UTestCache.hs | bsd-3-clause | 4,826 | 0 | 18 | 1,494 | 1,303 | 670 | 633 | 72 | 1 |
module T15527 where
f :: (Int -> Int) -> (Int -> Int) -> (Int -> Int)
f = (.) @Int
| sdiehl/ghc | testsuite/tests/typecheck/should_fail/T15527.hs | bsd-3-clause | 85 | 0 | 8 | 22 | 50 | 29 | 21 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
import TestUtils
import qualified Data.Generics as SYB
import qualified GHC.SYB.Utils as SYB
import qualified Bag as GHC
import qualified FastString as GHC
import qualified GHC as GHC
import qualified GhcMonad as GHC
import qualified Name as GHC
import qualified NameSet as GHC
import qualified OccName as GHC
import qualified Outputable as GHC
import qualified RdrName as GHC
import qualified SrcLoc as GHC
import qualified Module as GHC
import qualified UniqSet as GHC
import Control.Monad.State
import Data.Maybe
import Language.Haskell.Refact.Utils
-- import Language.Haskell.Refact.Utils.GhcUtils
import Language.Haskell.Refact.Utils.LocUtils
import Language.Haskell.Refact.Utils.Monad
import Language.Haskell.Refact.Utils.MonadFunctions
import Language.Haskell.Refact.Utils.TokenUtils
import Language.Haskell.Refact.Utils.TokenUtilsTypes
import Language.Haskell.Refact.Utils.TypeSyn
import Language.Haskell.Refact.Utils.TypeUtils
import Data.List
import Data.Generics.Strafunski.StrategyLib.StrategyLib
-- ---------------------------------------------------------------------
main :: IO ()
main = pp
pp :: IO ()
pp = do
-- (t, _toks) <- parsedFileDeclareSGhc
(t, _toks) <- parsedFileLiftWhereIn1Ghc
let renamed = fromJust $ GHC.tm_renamed_source t
putStrLn $ "GHC AST:" ++ (SYB.showData SYB.Renamer 0 renamed)
-- r <- traverseTU2 renamed
let rl = tu2l renamed
let rm = tu2m renamed
let re = tu2e renamed
-- ri <- tu2i renamed
-- putStrLn $ "(rm)=" ++ (show (rm))
-- putStrLn $ "(rm,re,rl)=" ++ (show (rm,re,rl))
putStrLn $ "(rm,re)=" ++ (show (rm,re))
-- putStrLn $ "(rm,ri)=" ++ (show (rm,ri))
-- ---------------------------------------------------------------------
tu2i :: (SYB.Data t) => t -> IO [String]
tu2i = traverseTU2
tu2m :: (SYB.Data t) => t -> Maybe [String]
tu2m = traverseTU2
tu2l :: (SYB.Data t) => t -> [] [String]
tu2l = traverseTU2
tu2e :: (SYB.Data t) => t -> Either String [String]
tu2e = traverseTU2
traverseTU2 :: (SYB.Data t, MonadPlus m) => t -> m [String]
traverseTU2 t = do
-- applyTU (full_tdTUGhc (failTU
-- applyTU (full_tdTUGhc ((constTU [])
-- applyTU (stop_tdTUGhc ((constTU ["start"])
-- applyTU (stop_tdTUGhc (failTU
applyTU (stop_tdTUGhc (failTU
`adhocTU` lit
-- `adhocTU` expr
-- `adhocTU` mg
-- applyTU (full_tdTUGhc (failTU `adhocTU` ff
-- applyTU (full_tdTUGhc (gg `adhocTU` ff
)) t
lit :: (MonadPlus m) => GHC.HsLit -> m [String]
lit (GHC.HsChar n) = return (["lit",[n]])
-- lit _ = return ["foo"]
-- lit _ = return mzero
expr :: (MonadPlus m) => GHC.HsExpr GHC.Name -> m [String]
expr (GHC.HsVar n) = return (["var",GHC.showPpr n])
expr _ = return []
mg :: (MonadPlus m) => GHC.MatchGroup GHC.Name -> m [String]
-- mg (GHC.MatchGroup _ _) = return ["mg"]
-- mg (GHC.MatchGroup _ _) = return mzero
mg (GHC.MatchGroup _ _) = do
-- s <- mzero :: (MonadPlus m) => m [String]
-- return [show s]
return ["show s"]
-- mg _ = return ["nmg"]
-- ---------------------------------------------------------------------
-- ---------------------------------------------------------------------
-- | Top-down type-unifying traversal that is cut of below nodes
-- where the argument strategy succeeds.
stop_tdTUGhc :: (MonadPlus m, Monoid a) => TU a m -> TU a m
-- stop_tdTUGhc s = ifTU checkItemRenamer' (const s) (s `choiceTU` (allTUGhc' (stop_tdTUGhc s)))
-- stop_tdTUGhc s = ifTU checkItemRenamer' (const failTU) (s `choiceTU` (allTUGhc' (stop_tdTUGhc s)))
stop_tdTUGhc s = (s `choiceTU` (allTUGhc' (stop_tdTUGhc s)))
{-
-- | Top-down type-unifying traversal that is cut of below nodes
-- where the argument strategy succeeds.
stop_tdTU :: (MonadPlus m, Monoid a) => TU a m -> TU a m
stop_tdTU s = s `choiceTU` (allTU' (stop_tdTU s))
-}
-- | Full type-unifying traversal in top-down order.
full_tdTUGhc :: (MonadPlus m, Monoid a) => TU a m -> TU a m
full_tdTUGhc s = op2TU mappend s (allTUGhc' (full_tdTUGhc s))
allTUGhc :: (MonadPlus m) => (a -> a -> a) -> a -> TU a m -> TU a m
allTUGhc op2 u s = ifTU checkItemRenamer' (const $ constTU u) (allTU op2 u s)
{- This one works, but we cannot use MkTU
allTUGhc :: (Monad m, Monoid a) => (a -> a -> a) -> a -> TU a m -> TU a m
allTUGhc op2 u s = MkTU (\x -> case (checkItemRenamer x) of
True -> do return (u) -- `op2` s)
False -> fold (gmapQ (applyTU s) x)
)
where
fold l = foldM op2' u l
op2' x c = c >>= \y -> return (x `op2` y)
-- Original -----
allTU :: Monad m => (a -> a -> a) -> a -> TU a m -> TU a m
allTU op2 u s = MkTU (\x -> fold (gmapQ (applyTU s) x))
where
fold l = foldM op2' u l
op2' x c = c >>= \y -> return (x `op2` y)
class Typeable a => Data a where
...
gmapQ :: (forall d. Data d => d -> u) -> a -> [u]
...
-}
-- MatchGroup [LMatch id] PostTcType
-- gmapQ f (GHC.MatchGroup matches ptt) = [f matches]
{-
-- gmapQ :: (forall d. SYB.Data d => d -> u) -> a -> [u]
instance SYB.Data GHC.NameSet where
gmapQ f (x::GHC.NameSet) = []
instance SYB.Data GHC.PostTcType where
gmapQ f (x::GHC.PostTcType) = []
instance SYB.Data GHC.Fixity where
gmapQ f (x::GHC.Fixity) = []
-}
allTUGhc' :: (MonadPlus m, Monoid a) => TU a m -> TU a m
allTUGhc' = allTUGhc mappend mempty
{-
-- | If 'c' succeeds, pass its value to the then-clause 't',
-- otherwise revert to the else-clause 'e'.
ifS :: StrategyPlus s m => TU u m -> (u -> s m) -> s m -> s m
ifS c t e = ((c `passTU` (constTU . Just)) `choiceTU` constTU Nothing)
`passS`
maybe e t
-- | If 'c' succeeds, pass its value to the then-clause 't',
-- otherwise revert to the else-clause 'e'.
ifTU :: MonadPlus m => TU u m -> (u -> TU u' m) -> TU u' m -> TU u' m
ifTU = ifS
choiceTU :: MonadPlus m => TU a m -> TU a m -> TU a m
choiceTU f g = MkTU ((unTU f) `mchoice` (unTU g))
newtype Monad m =>
TU a m =
MkTU (forall x. Data x => x -> m a)
unTU (MkTU f) = f
paraTU :: Monad m => (forall t. t -> m a) -> TU a m
paraTU f = MkTU f
-- | Type-unifying failure. Always fails, independent of the incoming
-- term. Uses 'MonadPlus' to model partiality.
failTU :: MonadPlus m => TU a m
failTU = paraTU (const mzero)
applyTU :: (Monad m, Data x) => TU a m -> x -> m a
applyTU = unTU
-- | Parallel combination of two type-unifying strategies with a binary
-- combinator. In other words, the values resulting from applying the
-- type-unifying strategies are combined to a final value by applying
-- the combinator 'o'.
op2TU :: Monad m => (a -> b -> c) -> TU a m -> TU b m -> TU c m
op2TU o s s' = s `passTU` \a ->
s' `passTU` \b ->
constTU (o a b)
passTU :: Monad m => TU a m -> (a -> TU b m) -> TU b m
passTU f g = MkTU ((unTU f) `mlet` (\y -> unTU (g y)))
-- | Sequential composition with value passing; a kind of monadic let.
mlet :: Monad m => (a -> m b) -> (b -> a -> m c) -> a -> m c
f `mlet` g = \x -> f x >>= \y -> g y x
-- | Choice combinator for monadic functions
mchoice :: MonadPlus m => (a -> m b) -> (a -> m b) -> a -> m b
f `mchoice` g = \x -> (f x) `mplus` (g x)
adhocTU :: (Monad m, Data t) => TU a m -> (t -> m a) -> TU a m
adhocTU s f = MkTU (unTU s `extQ` f)
-- | Extend a generic query by a type-specific case
extQ :: ( Typeable a
, Typeable b
)
=> (a -> q) -- existing query, starting from mkQ, extended via extQ
-> (b -> q) -- the new part to be added on
-> a
-> q
extQ f g a = maybe (f a) g (cast a)
-- maybe :: b -> (a -> b) -> Maybe a -> b
-- takes default, fn to apply if Just
-- | Make a generic query;
-- start from a type-specific case;
-- return a constant otherwise
--
mkQ :: ( Typeable a
, Typeable b
)
=> r
-> (b -> r)
-> a
-> r
(r `mkQ` br) a = case cast a of
Just b -> br b
Nothing -> r
-- Type-safe cast
-- The type-safe cast operation
cast :: (Typeable a, Typeable b) => a -> Maybe b
-}
checkItemStage' :: forall m. (MonadPlus m) => SYB.Stage -> TU () m
checkItemStage' stage = failTU `adhocTU` postTcType `adhocTU` fixity `adhocTU` nameSet
where nameSet = (const (guard $ stage `elem` [SYB.Parser,SYB.TypeChecker])) :: GHC.NameSet -> m ()
postTcType = (const (guard $ stage < SYB.TypeChecker )) :: GHC.PostTcType -> m ()
fixity = (const (guard $ stage < SYB.Renamer )) :: GHC.Fixity -> m ()
checkItemRenamer' :: (MonadPlus m) => TU () m
checkItemRenamer' = checkItemStage' SYB.Renamer
-- checkItemRenamer' = failTU
{-
-- fixity :: (MonadPlus m) => SYB.Stage -> a -> GHC.Fixity -> m ()
fixity :: (MonadPlus m) => SYB.Stage -> a -> GHC.Fixity -> m a
fixity stage u _x = do
guard (stage < SYB.Renamer)
return u
postTcType :: (MonadPlus m) => SYB.Stage -> a -> GHC.PostTcType -> m a
postTcType stage u _x = do
guard $ stage < SYB.TypeChecker
return u
nameSet :: (MonadPlus m) => SYB.Stage -> a -> GHC.NameSet -> m a
nameSet stage u _x = do
guard $ stage `elem` [SYB.Parser,SYB.TypeChecker]
return u
-}
-- ---------------------------------------------------------------------
parsedFileDeclareSGhc :: IO (ParseResult,[PosToken])
parsedFileDeclareSGhc = parsedFileGhc "./test/testdata/FreeAndDeclared/DeclareS.hs"
parsedFileLiftWhereIn1Ghc :: IO (ParseResult,[PosToken])
parsedFileLiftWhereIn1Ghc = parsedFileGhc "./test/testdata/LiftToToplevel/WhereIn1.hs"
| RefactoringTools/HaRe | experiments/AzStrafunskiPlay.hs | bsd-3-clause | 9,884 | 11 | 13 | 2,414 | 1,281 | 730 | 551 | 83 | 1 |
-- In this example, make the used items explicit in the first import decl.
module B1 (myFringe)where
import D1 ()
import D1 (fringe)
import C1 hiding (myFringe)
myFringe:: Tree a -> [a]
myFringe (Leaf x ) = [x]
myFringe (Branch left right) = myFringe right
sumSquares (x:xs)= x^2 + sumSquares xs
sumSquares [] =0
| kmate/HaRe | old/testing/mkImpExplicit/B1_TokOut.hs | bsd-3-clause | 325 | 0 | 7 | 65 | 120 | 66 | 54 | 9 | 1 |
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings #-}
import Yesod.Core
import Yesod.WebSockets
import qualified Data.Text.Lazy as TL
import Control.Monad (forever)
import Control.Monad.Trans.Reader
import Control.Concurrent (threadDelay)
import Data.Time
import Conduit
import Data.Monoid ((<>))
import Control.Concurrent.STM.Lifted
import Data.Text (Text)
data App = App (TChan Text)
instance Yesod App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]
chatApp :: WebSocketsT Handler ()
chatApp = do
sendTextData ("Welcome to the chat server, please enter your name." :: Text)
name <- receiveData
sendTextData $ "Welcome, " <> name
App writeChan <- getYesod
readChan <- atomically $ do
writeTChan writeChan $ name <> " has joined the chat"
dupTChan writeChan
race_
(forever $ atomically (readTChan readChan) >>= sendTextData)
(sourceWS $$ mapM_C (\msg ->
atomically $ writeTChan writeChan $ name <> ": " <> msg))
getHomeR :: Handler Html
getHomeR = do
webSockets chatApp
defaultLayout $ do
[whamlet|
<div #output>
<form #form>
<input #input autofocus>
|]
toWidget [lucius|
\#output {
width: 600px;
height: 400px;
border: 1px solid black;
margin-bottom: 1em;
p {
margin: 0 0 0.5em 0;
padding: 0 0 0.5em 0;
border-bottom: 1px dashed #99aa99;
}
}
\#input {
width: 600px;
display: block;
}
|]
toWidget [julius|
var url = document.URL,
output = document.getElementById("output"),
form = document.getElementById("form"),
input = document.getElementById("input"),
conn;
url = url.replace("http:", "ws:").replace("https:", "wss:");
conn = new WebSocket(url);
conn.onmessage = function(e) {
var p = document.createElement("p");
p.appendChild(document.createTextNode(e.data));
output.appendChild(p);
};
form.addEventListener("submit", function(e){
conn.send(input.value);
input.value = "";
e.preventDefault();
});
|]
main :: IO ()
main = do
chan <- atomically newBroadcastTChan
warp 3000 $ App chan
| ygale/yesod | yesod-websockets/chat.hs | mit | 2,570 | 0 | 17 | 909 | 363 | 191 | 172 | 39 | 1 |
module Main where
foreign import ccall "power2" power2 :: Int -> Int
main = print $ power2 4
| sdiehl/ghc | testsuite/tests/rts/linker/T11223/power.hs | bsd-3-clause | 95 | 0 | 6 | 20 | 32 | 18 | 14 | 3 | 1 |
-- @Author: Zeyuan Shang
-- @Date: 2016-07-28 23:49:48
-- @Last Modified by: Zeyuan Shang
-- @Last Modified time: 2016-07-29 20:35:29
data Graph a = Graph [a] [(a, a)]
deriving (Show, Eq)
depthfirst :: (Eq a) => Graph a -> a -> [a]
depthfirst graph src = depthfirst' graph [src]
depthfirst' :: (Eq a) => Graph a -> [a] -> [a]
depthfirst' (Graph [] _) _ = []
depthfirst' (Graph _ _) [] = []
depthfirst' (Graph vs es) (x:xs) = if elem x vs then x : depthfirst' (Graph vs' es) (xs' ++ xs)
else depthfirst' (Graph vs' es) (xs' ++ xs)
where vs' = filter (x /=) vs
xs' = [b | (a, b) <- es, a == x, elem b vs] ++ [a | (a, b) <- es, b == x, elem a vs]
connectedcomponents :: (Eq a) => Graph a -> [[a]]
connectedcomponents (Graph [] _) = []
connectedcomponents (Graph vs es) = component : connectedcomponents (Graph vs' es)
where component = depthfirst (Graph vs es) (head vs)
vs' = filter (\x -> not (elem x component)) vs
main = do
print $ connectedcomponents (Graph [1,2,3,4,5,6,7] [(1,2),(2,3),(1,4),(3,4),(5,2),(5,4),(6,7)]) | zeyuanxy/haskell-playground | ninety-nine-haskell-problems/vol9/88.hs | mit | 1,101 | 0 | 12 | 270 | 576 | 315 | 261 | 18 | 2 |
import System.Random
fb_starts = ["Zygo", "Prepro", "Mutually ", "Lazy "]
fb_middles = ["histomorphic ", "semi-recursive ", "monadic co-generator ", "tail call transflecting "]
fb_qualifiers = ["quasi-typed ", "union typed ", "non-lambda typed ", "duck typed ", "zermelo franklin typed ", "secretly ML "]
fb_finishadj = ["eigen-", "trans-", "hapto-", "lepto-", "carne-asado-"]
fb_finishes = ["matrix.", "combinator.", "comonoid.", "antisecant.", "thunk."]
fb_rand top = getStdRandom $ randomR(1, top)
fb_randl list = do
idx <- (fb_rand $ length list)
putStr(list !! (idx - 1))
main = do
fb_randl fb_starts
fb_randl fb_middles
fb_randl fb_qualifiers
fb_randl fb_finishadj
fb_randl fb_finishes
putStrLn "" | StoneCypher/forest_belton | forest_belton.hs | mit | 750 | 0 | 11 | 140 | 210 | 114 | 96 | 17 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
module Data.Frame.Internal (
HDataFrame(..),
Block(..),
IxRep,
--Index,
_filterKeys,
_alterKeys,
Columnable,
Indexable(..),
Default(..),
Result(..),
resultEither,
blockType,
-- ** Lenses
_Data,
_Index,
-- ** Prisms
_DBlock,
_IBlock,
_BBlock,
_MBlock,
_SBlock,
_NBlock
) where
import Data.Foldable
import Data.Traversable
import qualified Data.Vector as VB
import qualified Data.Vector.Unboxed as VU
import qualified Data.HashMap.Strict as M
import Data.Data
import Data.Monoid
import Control.DeepSeq (NFData(..))
-- import Data.DateTime
import Data.Hashable (Hashable(..))
import Data.Text (Text, pack, empty)
import Control.Monad
import Control.Applicative
import Control.Lens (lens, prism, Lens', Prism', makePrisms)
import Control.DeepSeq (NFData(..))
-------------------------------------------------------------------------------
-- Indexes and Columns
-------------------------------------------------------------------------------
-- type Index i = V.Vector i
type family IxRep (s :: *) :: *
type instance IxRep Int = Int
type instance IxRep String = String
type instance IxRep Double = Double
type instance IxRep Float = Float
type instance IxRep Bool = Bool
-- type instance IxRep DateTime = Int
class (Eq k, Show k, Hashable k) => Columnable k where
class (Ord i, Show i, VU.Unbox (IxRep i), Default i) => Indexable i where
ixto :: i -> IxRep i
ixfrom :: IxRep i -> i
instance Columnable Int where
instance Columnable String
instance Columnable Text
instance Columnable Bool
instance Indexable Int where
ixto = id
ixfrom = id
instance Indexable Double where
ixto = id
ixfrom = id
instance Indexable Float where
ixto = id
ixfrom = id
instance Indexable Bool where
ixto = id
ixfrom = id
--instance Indexable DateTime where
-- -- maxint(64) is 21 times the age of the unvierse, so we should be good for a while
-- ixto = fromIntegral . toSeconds
-- ixfrom = fromSeconds . fromIntegral
-------------------------------------------------------------------------------
-- Frame
-------------------------------------------------------------------------------
-- The heterogeneously typed dataframe.
data HDataFrame i k = HDataFrame
{ _hdfdata :: !(M.HashMap k Block)
, _hdfindex :: !(VB.Vector i)
} deriving (Eq)
instance NFData k => NFData (HDataFrame i k) where
rnf (HDataFrame dt _) = rnf dt
_Index :: Lens' (HDataFrame i k) (VB.Vector i)
_Index = lens _hdfindex (\f new -> f { _hdfindex = new })
_Data :: Lens' (HDataFrame i k) (M.HashMap k Block)
_Data = lens _hdfdata (\f new -> f { _hdfdata = new })
-- does a deep copy
_alterKeys ::(Eq b, Hashable b) => (a -> b) -> M.HashMap a v -> M.HashMap b v
_alterKeys f xs = M.fromList $ [(f a,b) | (a,b) <- M.toList xs]
-- O(n)
_filterKeys :: (k -> Bool) -> M.HashMap k v -> M.HashMap k v
_filterKeys f xs = M.filterWithKey (\k _ -> f k) xs
-------------------------------------------------------------------------------
-- Default Values
-------------------------------------------------------------------------------
class Default a where
def :: a
instance Default Int where
def = 0
instance Default Bool where
def = False
instance Default Double where
def = 0.0
instance Default Float where
def = 0.0
instance Default Text where
def = pack ""
--instance Default DateTime where
-- def = startOfTime
instance Default (Maybe a) where
def = Nothing
-------------------------------------------------------------------------------
-- Blocks
-------------------------------------------------------------------------------
data Block
= DBlock !(VU.Vector Double)
| IBlock !(VU.Vector Int)
| BBlock !(VU.Vector Bool)
| MBlock {
_mdata :: !Block
, _bitmap :: !(VU.Vector Bool)
}
| SBlock !(VB.Vector Text)
| NBlock
deriving (Eq, Show, Data, Typeable)
instance NFData Block where
rnf (MBlock dat _) = rnf dat
rnf _ = ()
_DBlock :: Prism' Block (VU.Vector Double)
_DBlock = prism remit review
where
remit a = DBlock a
review (DBlock a) = Right a
review a = Left a
_IBlock :: Prism' Block (VU.Vector Int)
_IBlock = prism remit review
where
remit a = IBlock a
review (IBlock a) = Right a
review a = Left a
_BBlock :: Prism' Block (VU.Vector Bool)
_BBlock = prism remit review
where
remit a = BBlock a
review (BBlock a) = Right a
review a = Left a
_MBlock :: Prism' Block (Block, VU.Vector Bool)
_MBlock
= prism remit review
where
remit (a, b) = MBlock a b
review (MBlock a b) = Right (a, b)
review a = Left a
_SBlock :: Prism' Block (VB.Vector Text)
_SBlock = prism remit review
where
remit a = SBlock a
review (SBlock a) = Right a
review a = Left a
_NBlock :: Prism' Block ()
_NBlock = prism remit review
where
remit () = NBlock
review NBlock = Right ()
review a = Left a
-------------------------------------------------------------------------------
-- Block Type
-------------------------------------------------------------------------------
-- ref: https://www.haskell.org/pipermail/libraries/2011-July/016548.html
#if MIN_VERSION_base(4,7,0)
mkTyCon = mkTyCon3 "frame" "Data.Frame.Internal"
#endif
blockType :: Block -> TypeRep
blockType (DBlock _) = typeOf (0.0 :: Double)
blockType (IBlock _) = typeOf (1 :: Int)
blockType (BBlock _) = typeOf False
blockType (SBlock _) = typeOf (Data.Text.empty)
blockType (MBlock a _) = mkTyConApp (mkTyCon "Maybe") [blockType a]
blockType NBlock = typeOf ()
-------------------------------------------------------------------------------
-- Result
-------------------------------------------------------------------------------
data Result a
= Error String
| Success a
deriving (Eq, Show, Typeable)
instance (NFData a) => NFData (Result a) where
rnf (Success a) = rnf a
rnf (Error err) = rnf err
instance Functor Result where
fmap f (Success a) = Success (f a)
fmap _ (Error err) = Error err
{-# INLINE fmap #-}
instance Monad Result where
return = Success
{-# INLINE return #-}
Success a >>= k = k a
Error err >>= _ = Error err
{-# INLINE (>>=) #-}
instance Applicative Result where
pure = return
{-# INLINE pure #-}
(<*>) = ap
{-# INLINE (<*>) #-}
instance MonadPlus Result where
mzero = fail "mzero"
{-# INLINE mzero #-}
mplus a@(Success _) _ = a
mplus _ b = b
{-# INLINE mplus #-}
instance Monoid (Result a) where
mempty = fail "mempty"
{-# INLINE mempty #-}
mappend = mplus
{-# INLINE mappend #-}
instance Alternative Result where
empty = mzero
{-# INLINE empty #-}
(<|>) = mplus
{-# INLINE (<|>) #-}
resultEither :: Result b -> Either String b
resultEither (Error x) = Left x
resultEither (Success x) = Right x
| houshuang/frame | src/Data/Frame/Internal.hs | mit | 7,237 | 0 | 12 | 1,407 | 2,077 | 1,124 | 953 | -1 | -1 |
module DrvDiffToString where
import DrvDiff
import Derivation
import Data.List
import Data.Maybe
drvDiffToString :: DrvDiff -> String
drvDiffToString (DrvDiff l r) =
(drvPartToString "- " l) ++
(drvPartToString "+ " r)
drvPartToString :: String -> DrvPart -> String
drvPartToString prefix p =
joinLines prefix (
(fmap drvOutputToString (drvPartOutputs p)) ++
(fmap drvInputToString (drvPartInputs p)) ++
(fmap drvSourceToString (drvPartSources p)) ++
maybeToList (fmap drvSystemToString (drvPartSystem p)) ++
maybeToList (fmap drvBuilderToString (drvPartBuilder p)) ++
maybeToList (fmap drvArgsToString (drvPartArgs p)) ++
(fmap drvEnvVarToString (drvPartEnv p))
)
joinLines :: String -> [String] -> String
joinLines prefix ls = intercalate "" (map (\x -> prefix ++ x ++ "\n") ls)
setDiffToString :: ([String], [String]) -> String
setDiffToString (l, r) = (joinLines "- " l) ++ (joinLines "+ " r)
drvOutputToString :: DerivationOutput -> String
drvOutputToString (DerivationOutput name path _ _) =
"Output: " ++ name ++ ": " ++ path
drvInputToString :: DerivationInput -> String
drvInputToString (DerivationInput path names) =
"Input: " ++ path ++ " " ++ (intercalate "," names)
drvSourceToString :: String -> String
drvSourceToString s = "source: " ++ s
drvSystemToString :: String -> String
drvSystemToString s = "system: " ++ s
drvBuilderToString :: String -> String
drvBuilderToString b = "builder: " ++ b
drvArgsToString :: [String] -> String
drvArgsToString args = "args: " ++ intercalate " " args
drvEnvVarToString :: DerivationEnvVar -> String
drvEnvVarToString (DerivationEnvVar name value) = "env: " ++ name ++ " = " ++ (show value)
| DavidEGrayson/drvdiff | src/DrvDiffToString.hs | mit | 1,695 | 0 | 16 | 289 | 558 | 290 | 268 | 39 | 1 |
{-# LANGUAGE OverloadedStrings, TypeApplications #-}
module Main where
import MockAPI
import Servant
import Network.Wai.Handler.Warp
import Data.Text (Text)
import Control.Concurrent (threadDelay)
import Control.Monad.IO.Class
import qualified Data.Map as M
import Network.Wai.Middleware.Gzip
server :: Server MockApi
server = authenticate :<|> serveAssets :<|> serveJS
where
serveAssets = serveDirectory "../mockClient/assets"
serveJS = serveDirectory "../mockClient/js/"
authenticate :: (Monad m, MonadIO m) => User -> m Text
authenticate u
| correctInfo = liftIO (threadDelay 1000000) >> return "Authenticated"
| userPresent = liftIO (threadDelay 1000000) >> return "Wrong password"
| otherwise = liftIO (threadDelay 1000000) >> return "Not Authenticated"
where
users = M.fromList [ ("user1@gmail.com", "pass1")
, ("user2@gmail.com", "pass2")
, ("user3@gmail.com", "pass3")
]
correctInfo = M.lookup (userMail u) users == Just (userPassword u)
userPresent = userMail u `elem` M.keys users
main :: IO ()
main = run 8081 (gzip gzipSettings $ serve (Proxy @MockApi) server)
-- main = run 8081 (serve (Proxy @MockApi) server)
where
gzipSettings = def { gzipFiles = GzipCompress }
| vacationlabs/haskell-webapps | UI/ReflexFRP/mockLoginPage/mockServer/Main.hs | mit | 1,290 | 0 | 11 | 267 | 354 | 190 | 164 | 27 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE MultiWayIf #-}
module Text.Docvim.Printer.Vim (vimHelp) where
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative ((<$>))
#endif
import Control.Arrow
import Control.Monad
import Control.Monad.Reader
import Control.Monad.State
import Data.Char
import Data.List
import Data.List.Split
import Data.Maybe
import Data.Tuple
import Text.Docvim.AST
import Text.Docvim.Parse
import Text.Docvim.Visitor.Plugin
-- TODO: add indentation here (using local, or just stick it in Context)
-- Instead of building up a [Char], we build up a list of operations, which
-- allows us a mechanism of implementing rollback and therefore hard-wrapping
-- (eg. append whitespace " ", then on next node, realize that we will exceed
-- line length limit, so rollback the " " and instead append "\n" etc).
data Operation = Append String
| Delete Int -- unconditional delete count of Char
| Slurp String -- delete string if present
data Metadata = Metadata { pluginName :: Maybe String }
data Context = Context { lineBreak :: String
, partialLine :: String
}
type Env = ReaderT Metadata (State Context) [Operation]
textwidth :: Int
textwidth = 78
vimHelp :: Node -> String
vimHelp n = if null suppressTrailingWhitespace
then ""
else suppressTrailingWhitespace ++ "\n"
where metadata = Metadata (getPluginName n)
context = Context defaultLineBreak ""
operations = evalState (runReaderT (node n) metadata) context
output = foldl reduce "" operations
reduce acc (Append atom) = acc ++ atom
reduce acc (Delete count) = take (length acc - count) acc
reduce acc (Slurp atom) = if atom `isSuffixOf` acc
then take (length acc - length atom) acc
else acc
suppressTrailingWhitespace = rstrip $ intercalate "\n" (map rstrip (splitOn "\n" output))
-- | Helper function that appends and updates `partialLine` context,
-- hard-wrapping if necessary to remain under `textwidth`.
append :: String -> Env
append string = append' string textwidth
-- | Helper function that appends and updates `partialLine` context
-- uncontitionally (no hard-wrapping).
appendNoWrap :: String -> Env
appendNoWrap string = append' string (maxBound :: Int)
append' :: String -> Int -> Env
append' string width = do
context <- get
-- TODO obviously tidy this up
let (ops, line) = if renderedWidth (partialLine context) + renderedWidth leading >= width
then ( [ Delete (length $ snd $ hardwrap $ partialLine context)
, Slurp " "
, Append (lineBreak context)
, Append (snd $ hardwrap $ partialLine context)
, Append string
]
, lineBreak context ++ snd (hardwrap $ partialLine context) ++ string
)
else ([Append string], partialLine context ++ string)
put (Context (lineBreak context) (end line))
return ops
where
leading = takeWhile (/= '\n') string
end l = reverse $ takeWhile (/= '\n') (reverse l)
-- http://stackoverflow.com/a/9723976/2103996
mapTuple :: (b -> c) -> (b, b) -> (c, c)
mapTuple = join (***)
-- Given a string, hardwraps it into two parts by splitting it at the rightmost
-- whitespace.
hardwrap :: String -> (String, String)
hardwrap str = swap $ mapTuple reverse split'
where
split' = break isSpace (reverse str)
-- Helper function to conditionally remove a string if it appears at the end of
-- the output.
slurp :: String -> Env
slurp str = do
context <- get
put (Context (lineBreak context) (partial context))
return [Slurp str]
where
-- eg. (partialLine context) | str | result
-- ----------------------|------------|-------
-- "" | "\n" | ""
-- "foo" | "\n" | "foo"
-- "foo" | "bar" | "foo"
-- "abc" | "bc" | "a"
-- "abc" | "foo\nabc" | ""
--
-- Note: That last one is unsafe, because we can't guarantee that "foo" is
-- there. Caveat emptor!
partial context = if str `isSuffixOf` partialLine context
then take (length (partialLine context) - length str) (partialLine context)
else partialLine context
defaultLineBreak :: String
defaultLineBreak = "\n"
nodes :: [Node] -> Env
nodes ns = concat <$> mapM node ns
node :: Node -> Env
node n = case n of
Blockquote b -> blockquote b >>= nl >>= nl
BreakTag -> breaktag
Code c -> append $ "`" ++ c ++ "`"
CommandAnnotation {} -> command n
CommandsAnnotation -> heading "commands"
DocBlock d -> nodes d
Fenced f -> fenced f
FunctionAnnotation {} -> function n
FunctionDeclaration {} -> nodes $ functionBody n
FunctionsAnnotation -> heading "functions"
HeadingAnnotation h -> heading h
Link l -> append $ link l
LinkTargets l -> linkTargets l True
List ls -> nodes ls >>= nl
ListItem l -> listitem l
MappingAnnotation m -> mapping m
MappingsAnnotation -> heading "mappings"
OptionAnnotation {} -> option n
OptionsAnnotation -> heading "options"
Paragraph p -> nodes p >>= nl >>= nl
Plaintext p -> plaintext p
PluginAnnotation name desc -> plugin name desc
Project p -> nodes p
Separator -> append $ "---" ++ "\n\n"
SubheadingAnnotation s -> append $ s ++ " ~\n\n"
TOC t -> toc t
Unit u -> nodes u
Whitespace -> whitespace
_ -> append ""
plugin :: String -> String -> Env
plugin name desc = appendNoWrap $
center filename desc (target normalized) " " " " ++ "\n\n"
where
filename = "*" ++ normalized ++ ".txt*"
normalized = map toLower name
center a b c s1 s2 =
if | renderedWidth str >= textwidth -> str
| odd $ renderedWidth str -> center a b c (s1 ++ " ") s2
| otherwise -> center a b c s1 (s2 ++ " ")
where
str = a ++ s1 ++ b ++ s2 ++ c
-- | Append a newline.
nl :: [Operation] -> Env
nl os = liftM2 (++) (return os) (append "\n")
breaktag :: Env
breaktag = do
context <- get
append $ lineBreak context
listitem :: [Node] -> Env
listitem l = do
context <- get
-- TODO: consider using lenses to modify records
put (Context customLineBreak (partialLine context))
item <- liftM2 (++) (append "- ") (nodes l) >>= nl
put (Context defaultLineBreak (partialLine context))
return item
where
customLineBreak = "\n "
toc :: [String] -> Env
toc t = do
metadata <- ask
toc' $ fromJust $ pluginName metadata
where
toc' p = do
h <- heading "contents"
entries <- append $ intercalate "\n" format ++ "\n\n"
return (h ++ entries)
where
format = map pad numbered
longest = maximum (map (length . snd) numbered )
numbered = map prefix number
number = zip3 [(1 :: Integer)..] t (map (\x -> normalize $ p ++ "-" ++ x) t)
prefix (num, desc, l) = (show num ++ ". " ++ desc ++ " ", l)
pad (lhs, rhs) = lhs ++ replicate (longest - length lhs) ' ' ++ link rhs
-- TODO: consider doing this for markdown format too
command :: Node -> Env
command (CommandAnnotation name params) = do
target' <- linkTargets [":" ++ name] False
lhs <- append $ concat [":", name, " ", fromMaybe "" params]
trailing <- append " ~\n\n"
return $ concat [target', lhs, trailing]
-- TODO indent what follows until next annotation...
-- will require us to hoist it up inside CommandAnnotation
-- (and do similar for other sections)
-- once that is done, drop the extra newline above
command _ = invalidNode
function :: Node -> Env
function (FunctionAnnotation name) = do
target' <- linkTargets [name ++ "()"] False
lhs <- append $ name ++ "()"
trailing <- append " ~\n\n"
return $ concat [target', lhs, trailing]
-- TODO indent what follows
function _ = invalidNode
mapping :: String -> Env
mapping name = linkTargets [name] True
option :: Node -> Env
option (OptionAnnotation n t d) = do
targets <- linkTargets [n] True
opt <- appendNoWrap $ link n
ws <- appendNoWrap " "
context <- get
meta <- appendNoWrap $ aligned context
return $ concat [targets, opt, ws, meta]
where
aligned context = rightAlign context rhs
rhs = t ++ " (default: " ++ fromMaybe "none" d ++ ")\n\n"
option _ = invalidNode
whitespace :: Env
whitespace = append " "
blockquote :: [Node] -> Env
blockquote ps = do
context <- get
put (Context customLineBreak (partialLine context))
ps' <- mapM paragraph ps
put (Context defaultLineBreak (partialLine context))
liftM2 (++) (append " ") (liftM2 intercalate customParagraphBreak (return ps'))
where
-- Strip off trailing newlines from each paragraph.
paragraph p = fmap trim (node p)
trim contents = take (length contents - 2) contents
customLineBreak = "\n "
customParagraphBreak = append "\n\n "
plaintext :: String -> Env
plaintext = append
fenced :: [String] -> Env
fenced f = do
cut <- slurp "\n"
prefix <- append ">\n"
body <- if null f
then append ""
else appendNoWrap $ " " ++ intercalate "\n " f ++ "\n"
suffix <- append "<\n"
return $ concat [cut, prefix, body, suffix]
heading :: String -> Env
heading h = do
metadata <- ask
heading' <- appendNoWrap $ map toUpper h ++ " "
targ <- maybe (append "\n") (\x -> linkTargets [target' x] False) (pluginName metadata)
trailing <- append "\n"
return $ concat [heading', targ, trailing]
where
target' x = normalize $ x ++ "-" ++ h
normalize :: String -> String
normalize = map (toLower . sanitize)
sanitize :: Char -> Char
sanitize x = if isSpace x then '-' else x
link :: String -> String
link l = "|" ++ l ++ "|"
target :: String -> String
target t = "*" ++ t ++ "*"
-- TODO: be prepared to wrap these if there are a lot of them
-- TODO: fix code smell of passing in `wrap` bool here
linkTargets :: [String] -> Bool -> Env
linkTargets ls wrap = do
context <- get
if wrap
then append $ aligned context
else appendNoWrap $ aligned context
where
aligned context = rightAlign context (targets ++ "\n")
targets = unwords (map linkify $ sort ls)
linkify l = "*" ++ l ++ "*"
rightAlign :: Context -> String -> String
rightAlign context string = align (partialLine context)
where
align used = replicate (count used string) ' ' ++ string
count used xs = maximum [textwidth - renderedWidth xs - renderedWidth used, 0]
-- Crude approximation for calculating rendered width, that does so by not
-- counting the relatively rare |, *, ` and "\n" -- all of which usually get
-- concealed in the rendered output.
renderedWidth :: String -> Int
renderedWidth = foldr reduce 0
where reduce char acc = if char `elem` "\n|*`"
then acc
else acc + 1
| wincent/docvim | lib/Text/Docvim/Printer/Vim.hs | mit | 11,436 | 0 | 17 | 3,357 | 3,242 | 1,646 | 1,596 | 229 | 29 |
module Holyhaskell.Swallow.Test
(swallowSuite)
where
import Test.Tasty (testGroup, TestTree)
import Test.Tasty.HUnit
import Holyhaskell.Swallow
swallowSuite :: TestTree
swallowSuite = testGroup "Swallow"
[testCase "swallow test" testSwallow]
testSwallow :: Assertion
testSwallow = "something" @=? swallow "some" "thing"
| duikboot/holyhaskell | test/Holyhaskell/Swallow/Test.hs | mit | 330 | 0 | 7 | 43 | 78 | 45 | 33 | 10 | 1 |
module GraphDB.Util.TH.Parsers where
import GraphDB.Util.Prelude
import qualified Language.Haskell.TH as T
import qualified Text.Parsec as P
import qualified Data.Char as Char
import qualified GraphDB.Util.TH.Type as Type
type Parse = P.ParsecT String ()
runParse :: (Monad m) => String -> Parse m r -> m r
runParse content p = do
P.runParserT p () "runParse parser" content
>>= either (fail . ("Parse failed: " <>) . show) return
type Instance = (T.Name, [T.Type])
-- |
-- N.B.: works only on instances with a /where/ clause and concrete parameters.
instances :: Parse T.Q [Instance]
instances = p
where
p = P.sepBy (optional (P.try getInstance) <* P.skipMany (P.noneOf "\n\r")) skipEOL |>
fmap catMaybes
skipEOL = P.skipMany1 (P.oneOf "\n\r")
skipSpace = P.skipMany1 P.space
getInstance = do
P.string "instance"
skipSpace
optional $ P.try skipConstraints *> skipSpace
className <- getTypeName
skipSpace
params <- P.sepEndBy1 (getParamType) skipSpace
P.string "where"
return (className, params)
getParamType =
P.try (inBraces app) <|>
P.try nonApp <|>
inBraces getParamType
where
nonApp =
con <|>
P.try var <|>
P.try tuple <|>
P.try list <|>
inBraces nonApp
var = T.VarT . T.mkName <$> getLowerIdentifier
con = T.ConT <$> getTypeName
tuple = Type.tuple <$> itemsP
where
itemsP =
P.char '(' *> optional skipSpace *>
P.sepBy getParamType (optional skipSpace *> P.char ',' <* optional skipSpace) <*
optional skipSpace <* P.char ')'
list =
T.AppT T.ListT <$>
(P.char '[' *> optional skipSpace *> getParamType <* optional skipSpace <* P.char ']')
app = do
a <- getParamType
skipSpace
b <- P.try app <|> getParamType
return $ case b of
T.AppT b1 b2 -> T.AppT (T.AppT a b1) b2
_ -> T.AppT a b
inBraces p = P.char '(' *> p <* P.char ')'
skipConstraints =
(P.try skipConstraintClause <|> skipAnythingInBraces) *>
P.skipMany P.space *>
P.string "=>" *> pure ()
where
skipAnythingInBraces =
P.char '(' *> P.manyTill skip (P.char ')') *> pure ()
where
skip = skipAnythingInBraces <|> P.skipMany (P.noneOf "()")
skipConstraintClause =
void $ P.sepEndBy1 (void getParamType <|> skipAnythingInBraces) P.spaces
getTypeName = do
identifier <- P.sepBy1 getUpperIdentifier (P.char '.') |> fmap (intercalate ".")
T.lookupTypeName identifier |> lift >>= \case
Just n -> return n
Nothing -> lift $ fail $ "Type not found: " <> identifier
getUpperIdentifier = do
head <- P.satisfy Char.isUpper
tail <- many (P.satisfy (\c -> Char.isAlphaNum c || c `elem` ['_', '\'']))
return $ head : tail
getLowerIdentifier = do
head <- P.satisfy Char.isLower
tail <- many (P.satisfy (\c -> Char.isAlphaNum c || c `elem` ['_', '\'']))
let i = head : tail
if elem i ["where"]
then empty
else return i
| nikita-volkov/graph-db | library/GraphDB/Util/TH/Parsers.hs | mit | 3,220 | 0 | 19 | 972 | 1,092 | 544 | 548 | -1 | -1 |
module NetHack.Control.More
(skipMores)
where
import Data.Foldable hiding(any, concat)
import Control.Monad(when)
import NetHack.Monad.NHAction
import NetHack.Control.Screen
import qualified Regex as R
harmlessMores :: [NHAction Bool]
harmlessMores = [itIsWrittenInTheBook, welcomeBackToNetHack]
questionify :: Answerable a => NHAction Bool -> a -> NHAction Bool
questionify question myAnswer = do
result <- question
if result then answer myAnswer >> return True
else return False
questions :: [NHAction Bool]
questions = map (\(f,ans) -> questionify f ans)
[(doYouWantToKeepSaveFile, 'n'),
(doYouWantYourPossessionsIdentified, 'q'),
(optionalDie, 'n')]
skipMores :: NHAction ()
skipMores = do
pleaseRepeat <-
foldlM (\result ac -> do test <- ac
when test $ answer ' '
if result then return True else ac)
False $ concat [harmlessMores,
questions]
when pleaseRepeat skipMores
skipHarmlessMessages
isHarmlessMessage :: String -> Bool
isHarmlessMessage str
| R.match "^(.+) miss(es)? (.+)$" str = True
| R.match "^(.+) hits!" str = True -- TODO: rethink which monster around
-- is peaceful or something else
| R.match "^(.+) bites!" str = True
| R.match "^(.+) stings!" str = True
| R.match "^(.+) butts!" str = True
| R.match "^(.+) bites (.+)\\.$" str = True
| R.match "^(.+) stings (.+)\\.$" str = True
| R.match "^(.+) butts (.+)\\.$" str = True
| R.match "^(Unknown command ' ')\\.$" str = True
| R.match "^You displaced (.+)\\.$" str = True
| R.match "^You hear bubbling water\\.$" str = True
| R.match "^You hear a door open\\.$" str = True
| R.match "^You hear some noises in the distance\\.$" str = True
| str == "" = True
| otherwise = True -- every message is safe for now.
skipHarmlessMessages :: NHAction ()
skipHarmlessMessages = do
messages <- getMessagesM
when (any (not . isHarmlessMessage) messages) $
error $ "Scary message! Current messages: " ++ show messages
hasMorePrompt <- morePrompt
when hasMorePrompt $ do answer ' '
skipMores
| Noeda/Megaman | src/NetHack/Control/More.hs | mit | 2,243 | 5 | 17 | 589 | 483 | 269 | 214 | 54 | 2 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module DBPnet.Correlation
( cisCorMat
, transCorMat
) where
import Bio.Data.Bed
import Conduit
import Lens.Micro
import Control.Monad
import qualified Data.ByteString.Char8 as B
import Data.List.Split
import qualified Data.Matrix.Unboxed as MU
import qualified Data.Matrix.Unboxed.Mutable as MUM
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import Statistics.Correlation (spearman)
import DBPnet.Utils (readLoops)
cisCorMat :: [(String, FilePath)]
-> IO ([B.ByteString], MU.Matrix Double)
cisCorMat dat = do
counts <- fmap V.fromList $ forM dat $ \(i, fl) -> do
beds <- readBed fl
return (i, U.fromList $ map (^.bdgValue) beds)
let l = V.length counts
header = map B.pack $ V.toList $ fst . V.unzip $ counts
mat :: MU.Matrix Double
mat = MU.create $ do
m <- MUM.new (l,l)
forM_ [0..l-1] $ \i -> do
let (_, tfA) = counts V.! i
forM_ [0..l-1] $ \j -> case () of
_ | j < i -> MUM.read m (j,i) >>= MUM.write m (i,j)
| otherwise -> do
let (_, tfB) = counts V.! j
vec = U.filter (\(a,b) -> a /= 0 || b /= 0) $ U.zip tfA tfB
cor | U.length vec < 500 = 0
| otherwise = spearman vec
MUM.write m (i,j) cor
return m
return (header, mat)
transCorMat :: [(String, FilePath)] -> FilePath
-> IO ([B.ByteString], MU.Matrix Double)
transCorMat dat hic = do
loops <- concatMap (\(a,b) -> [a,b]) <$> readLoops hic
counts <- fmap V.fromList $ forM dat $ \(i,fl) -> do
beds <- readBed fl :: IO [BEDGraph]
let rs = runIdentity $ runConduit $ yieldMany loops .|
intersectBedWith fn beds .| sinkList
fn _ [] = 0
fn _ x = maximum $ map (^.bdgValue) x
return (i, U.fromList $ map (\[a,b] -> (a,b)) $ chunksOf 2 rs)
let l = V.length counts
header = map B.pack $ V.toList $ fst . V.unzip $ counts
mat :: MU.Matrix Double
mat = MU.create $ do
m <- MUM.new (l,l)
forM_ [0..l-1] $ \i -> do
let (_, tfA) = counts V.! i
forM_ [0..l-1] $ \j -> case () of
_ | j < i -> MUM.read m (j,i) >>= MUM.write m (i,j)
| otherwise -> do
let (_, tfB) = counts V.! j
vec = U.filter (\(a,b) -> a /= 0 || b /= 0) $ U.zipWith f tfA tfB
cor | U.length vec < 500 = 0
| otherwise = spearman vec
MUM.write m (i,j) cor
return m
return (header, mat)
where
f (x1,x2) (y1,y2) | x1 > x2 = (x1, y2)
| otherwise = (x2, y1)
| kaizhang/DBPnet | src/DBPnet/Correlation.hs | mit | 3,118 | 0 | 34 | 1,278 | 1,240 | 645 | 595 | 70 | 2 |
module Examples.Addition where
import Test.Scher
test = forAll "i" \(i :: Int) ->
forAll "j" \(j :: Int) ->
i + j == j + i
| m-alvarez/scher | Examples/Addition.hs | mit | 139 | 0 | 11 | 42 | 62 | 34 | 28 | -1 | -1 |
module Eval (alpha, beta, freeVariables) where
import Types
alpha target replacement body@(V _) | target == body = replacement
| otherwise = body
alpha target replacement (L param body) = L (alpha target replacement param) (alpha target replacement body)
alpha target replacement (A app arg) = A (alpha target replacement app) (alpha target replacement arg)
beta (E symbol binding body, environment) = beta (body, (symbol, binding) : environment)
beta (S name, environment) = (desymbolize (S name) environment, environment)
beta ((A (L param body) arg), environment) = (replace param arg (desymbolize body environment), environment)
beta ((A (V name) arg), environment) = (A (V name) (fst $ beta (arg, environment)), environment)
beta ((A app arg), environment) = (A (fst $ beta (app, environment)) arg, environment)
beta (application, environment) = (application, environment)
desymbolize (S name) environment = case lookup (S name) environment of
Nothing -> error $ "Unbound symbol " ++ name
Just body -> body
desymbolize (L param body) environment = L param (desymbolize body environment)
desymbolize (A app arg) environment = A (desymbolize app environment) (desymbolize arg environment)
desymbolize (V label) environment = V label
replace (V target) replacement (V body) | target == body = replacement
| otherwise = V body
replace target replacement (A app arg) = A (replace target replacement app) (replace target replacement arg)
replace target replacement (L param body) | target == param = L param body
| any (== param) (freeVariables replacement) = replace target replacement renamedLambda
| otherwise = L param (replace target replacement body)
where renamedLambda = alpha param newVariable (L param body)
newVariable = (availableVariable $ freeVariables body ++ freeVariables replacement)
availableVariable takenVariables = head $ filter notTaken $ variableNames 'a' 1
where notTaken = not . (`elem` takenVariables)
variableNames 'z' repetition = variableNames 'a' $ repetition + 1
variableNames letter repetition = makeVar letter repetition : variableNames (succ letter) repetition
makeVar letter repetition = V $ take repetition $ repeat letter
freeVariables (V a) = [V a]
freeVariables (L param body) = filter (/= param) $ freeVariables body
freeVariables (A app arg) = freeVariables app ++ freeVariables arg
freeVariables (S _) = []
freeVariables (E _ _ _) = []
| MichaelBaker/lambda-calculus | src/Eval.hs | mit | 2,894 | 0 | 10 | 875 | 999 | 502 | 497 | 36 | 2 |
{-# htermination (fromDoubleRatio :: Double -> Ratio MyInt) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Double = Double MyInt MyInt ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data Ordering = LT | EQ | GT ;
data Ratio a = CnPc a a;
fromIntMyInt :: MyInt -> MyInt
fromIntMyInt x = x;
primNegInt :: MyInt -> MyInt;
primNegInt (Pos x) = Neg x;
primNegInt (Neg x) = Pos x;
negateMyInt :: MyInt -> MyInt
negateMyInt = primNegInt;
absReal0 x MyTrue = negateMyInt x;
otherwise :: MyBool;
otherwise = MyTrue;
absReal1 x MyTrue = x;
absReal1 x MyFalse = absReal0 x otherwise;
primCmpNat :: Nat -> Nat -> Ordering;
primCmpNat Zero Zero = EQ;
primCmpNat Zero (Succ y) = LT;
primCmpNat (Succ x) Zero = GT;
primCmpNat (Succ x) (Succ y) = primCmpNat x y;
primCmpInt :: MyInt -> MyInt -> Ordering;
primCmpInt (Pos Zero) (Pos Zero) = EQ;
primCmpInt (Pos Zero) (Neg Zero) = EQ;
primCmpInt (Neg Zero) (Pos Zero) = EQ;
primCmpInt (Neg Zero) (Neg Zero) = EQ;
primCmpInt (Pos x) (Pos y) = primCmpNat x y;
primCmpInt (Pos x) (Neg y) = GT;
primCmpInt (Neg x) (Pos y) = LT;
primCmpInt (Neg x) (Neg y) = primCmpNat y x;
compareMyInt :: MyInt -> MyInt -> Ordering
compareMyInt = primCmpInt;
esEsOrdering :: Ordering -> Ordering -> MyBool
esEsOrdering LT LT = MyTrue;
esEsOrdering LT EQ = MyFalse;
esEsOrdering LT GT = MyFalse;
esEsOrdering EQ LT = MyFalse;
esEsOrdering EQ EQ = MyTrue;
esEsOrdering EQ GT = MyFalse;
esEsOrdering GT LT = MyFalse;
esEsOrdering GT EQ = MyFalse;
esEsOrdering GT GT = MyTrue;
not :: MyBool -> MyBool;
not MyTrue = MyFalse;
not MyFalse = MyTrue;
fsEsOrdering :: Ordering -> Ordering -> MyBool
fsEsOrdering x y = not (esEsOrdering x y);
gtEsMyInt :: MyInt -> MyInt -> MyBool
gtEsMyInt x y = fsEsOrdering (compareMyInt x y) LT;
absReal2 x = absReal1 x (gtEsMyInt x (fromIntMyInt (Pos Zero)));
absReal x = absReal2 x;
absMyInt :: MyInt -> MyInt
absMyInt = absReal;
primEqNat :: Nat -> Nat -> MyBool;
primEqNat Zero Zero = MyTrue;
primEqNat Zero (Succ y) = MyFalse;
primEqNat (Succ x) Zero = MyFalse;
primEqNat (Succ x) (Succ y) = primEqNat x y;
primEqInt :: MyInt -> MyInt -> MyBool;
primEqInt (Pos (Succ x)) (Pos (Succ y)) = primEqNat x y;
primEqInt (Neg (Succ x)) (Neg (Succ y)) = primEqNat x y;
primEqInt (Pos Zero) (Neg Zero) = MyTrue;
primEqInt (Neg Zero) (Pos Zero) = MyTrue;
primEqInt (Neg Zero) (Neg Zero) = MyTrue;
primEqInt (Pos Zero) (Pos Zero) = MyTrue;
primEqInt xv xw = MyFalse;
esEsMyInt :: MyInt -> MyInt -> MyBool
esEsMyInt = primEqInt;
stop :: MyBool -> a;
stop MyFalse = stop MyFalse;
error :: a;
error = stop MyTrue;
primMinusNatS :: Nat -> Nat -> Nat;
primMinusNatS (Succ x) (Succ y) = primMinusNatS x y;
primMinusNatS Zero (Succ y) = Zero;
primMinusNatS x Zero = x;
primDivNatS0 x y MyTrue = Succ (primDivNatS (primMinusNatS x y) (Succ y));
primDivNatS0 x y MyFalse = Zero;
primGEqNatS :: Nat -> Nat -> MyBool;
primGEqNatS (Succ x) Zero = MyTrue;
primGEqNatS (Succ x) (Succ y) = primGEqNatS x y;
primGEqNatS Zero (Succ x) = MyFalse;
primGEqNatS Zero Zero = MyTrue;
primDivNatS :: Nat -> Nat -> Nat;
primDivNatS Zero Zero = error;
primDivNatS (Succ x) Zero = error;
primDivNatS (Succ x) (Succ y) = primDivNatS0 x y (primGEqNatS x y);
primDivNatS Zero (Succ x) = Zero;
primQuotInt :: MyInt -> MyInt -> MyInt;
primQuotInt (Pos x) (Pos (Succ y)) = Pos (primDivNatS x (Succ y));
primQuotInt (Pos x) (Neg (Succ y)) = Neg (primDivNatS x (Succ y));
primQuotInt (Neg x) (Pos (Succ y)) = Neg (primDivNatS x (Succ y));
primQuotInt (Neg x) (Neg (Succ y)) = Pos (primDivNatS x (Succ y));
primQuotInt wz xu = error;
quotMyInt :: MyInt -> MyInt -> MyInt
quotMyInt = primQuotInt;
primModNatS0 x y MyTrue = primModNatS (primMinusNatS x (Succ y)) (Succ (Succ y));
primModNatS0 x y MyFalse = Succ x;
primModNatS :: Nat -> Nat -> Nat;
primModNatS Zero Zero = error;
primModNatS Zero (Succ x) = Zero;
primModNatS (Succ x) Zero = error;
primModNatS (Succ x) (Succ Zero) = Zero;
primModNatS (Succ x) (Succ (Succ y)) = primModNatS0 x y (primGEqNatS x (Succ y));
primRemInt :: MyInt -> MyInt -> MyInt;
primRemInt (Pos x) (Pos (Succ y)) = Pos (primModNatS x (Succ y));
primRemInt (Pos x) (Neg (Succ y)) = Pos (primModNatS x (Succ y));
primRemInt (Neg x) (Pos (Succ y)) = Neg (primModNatS x (Succ y));
primRemInt (Neg x) (Neg (Succ y)) = Neg (primModNatS x (Succ y));
primRemInt wx wy = error;
remMyInt :: MyInt -> MyInt -> MyInt
remMyInt = primRemInt;
gcd0Gcd'0 x y = gcd0Gcd' y (remMyInt x y);
gcd0Gcd'1 MyTrue x xx = x;
gcd0Gcd'1 xy xz yu = gcd0Gcd'0 xz yu;
gcd0Gcd'2 x xx = gcd0Gcd'1 (esEsMyInt xx (fromIntMyInt (Pos Zero))) x xx;
gcd0Gcd'2 yv yw = gcd0Gcd'0 yv yw;
gcd0Gcd' x xx = gcd0Gcd'2 x xx;
gcd0Gcd' x y = gcd0Gcd'0 x y;
gcd0 x y = gcd0Gcd' (absMyInt x) (absMyInt y);
gcd1 MyTrue yx yy = error;
gcd1 yz zu zv = gcd0 zu zv;
gcd2 MyTrue yx yy = gcd1 (esEsMyInt yy (fromIntMyInt (Pos Zero))) yx yy;
gcd2 zw zx zy = gcd0 zx zy;
gcd3 yx yy = gcd2 (esEsMyInt yx (fromIntMyInt (Pos Zero))) yx yy;
gcd3 zz vuu = gcd0 zz vuu;
gcd yx yy = gcd3 yx yy;
gcd x y = gcd0 x y;
reduce2D vuv vuw = gcd vuv vuw;
reduce2Reduce0 vuv vuw x y MyTrue = CnPc (quotMyInt x (reduce2D vuv vuw)) (quotMyInt y (reduce2D vuv vuw));
reduce2Reduce1 vuv vuw x y MyTrue = error;
reduce2Reduce1 vuv vuw x y MyFalse = reduce2Reduce0 vuv vuw x y otherwise;
reduce2 x y = reduce2Reduce1 x y x y (esEsMyInt y (fromIntMyInt (Pos Zero)));
reduce x y = reduce2 x y;
gtMyInt :: MyInt -> MyInt -> MyBool
gtMyInt x y = esEsOrdering (compareMyInt x y) GT;
signumReal0 x MyTrue = fromIntMyInt (Neg (Succ Zero));
signumReal1 x MyTrue = fromIntMyInt (Pos (Succ Zero));
signumReal1 x MyFalse = signumReal0 x otherwise;
signumReal2 x MyTrue = fromIntMyInt (Pos Zero);
signumReal2 x MyFalse = signumReal1 x (gtMyInt x (fromIntMyInt (Pos Zero)));
signumReal3 x = signumReal2 x (esEsMyInt x (fromIntMyInt (Pos Zero)));
signumReal x = signumReal3 x;
signumMyInt :: MyInt -> MyInt
signumMyInt = signumReal;
primPlusNat :: Nat -> Nat -> Nat;
primPlusNat Zero Zero = Zero;
primPlusNat Zero (Succ y) = Succ y;
primPlusNat (Succ x) Zero = Succ x;
primPlusNat (Succ x) (Succ y) = Succ (Succ (primPlusNat x y));
primMulNat :: Nat -> Nat -> Nat;
primMulNat Zero Zero = Zero;
primMulNat Zero (Succ y) = Zero;
primMulNat (Succ x) Zero = Zero;
primMulNat (Succ x) (Succ y) = primPlusNat (primMulNat x (Succ y)) (Succ y);
primMulInt :: MyInt -> MyInt -> MyInt;
primMulInt (Pos x) (Pos y) = Pos (primMulNat x y);
primMulInt (Pos x) (Neg y) = Neg (primMulNat x y);
primMulInt (Neg x) (Pos y) = Neg (primMulNat x y);
primMulInt (Neg x) (Neg y) = Pos (primMulNat x y);
srMyInt :: MyInt -> MyInt -> MyInt
srMyInt = primMulInt;
pc x y = reduce (srMyInt x (signumMyInt y)) (absMyInt y);
doubleToRatio (Double x y) = pc (fromIntMyInt x) (fromIntMyInt y);
fromDoubleRatio :: Double -> Ratio MyInt
fromDoubleRatio = doubleToRatio;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/fromDouble_1.hs | mit | 7,013 | 0 | 11 | 1,415 | 3,324 | 1,734 | 1,590 | 170 | 1 |
module Verba.Dictionary where
import Data.Map (Map)
import Data.Maybe (fromMaybe)
import qualified Data.Map as Map
import System.IO
import Paths_Verba
import Data.Foldable (foldrM)
type Dictionary = Map Int [String]
-- Pushes a word in the right bucket
-- based on its length.
insertWord :: String -> Dictionary -> Dictionary
insertWord w = Map.alter fn (length w)
where fn Nothing = Just [w]
fn (Just lst) = Just $ w : lst
empty :: Dictionary
empty = Map.empty
-- Takes a string representing the name of
-- the language ("it" for "Italian", "en" for "English")
-- and the length of the words you want to load and loads
-- those words in the dictionary.
load :: String -> Int -> Dictionary -> IO Dictionary
load lang len dict = do
fileName <- getDataFileName $ "dict/" ++ lang ++ "/" ++ lang ++ "-" ++ show len ++ ".dict"
words <- readFile fileName >>= (return . words)
return $ Map.insert len words dict
loadAll :: String -> [Int] -> IO Dictionary
loadAll lang lns = foldrM (load lang) empty lns
-- Gets all the words with a certain length.
wordsWithLength :: Int -> Dictionary -> [String]
wordsWithLength n = fromMaybe [] . Map.lookup n
| Jefffrey/Verba | src/Verba/Dictionary.hs | mit | 1,172 | 0 | 14 | 233 | 344 | 182 | 162 | 23 | 2 |
{- Basic Window Setup and Display -}
{-# LANGUAGE OverloadedStrings #-}
module Lesson01 where
--
import qualified SDL
import Linear.V4 (V4(..))
--
import Control.Concurrent (threadDelay)
--
import qualified Config
--
lesson01 :: IO ()
lesson01 = do
SDL.initialize [SDL.InitVideo]
window <- SDL.createWindow "Lesson01" Config.winConfig
SDL.showWindow window
-- get surface from given window
gSurface <- SDL.getWindowSurface window
-- fill the global surface with black
SDL.surfaceFillRect gSurface Nothing $
-- setting color with R-G-B-A
V4 maxBound maxBound minBound maxBound
-- update the surface for a specific window
SDL.updateWindowSurface window
--
threadDelay 2000000
--
SDL.destroyWindow window
SDL.quit
| jaiyalas/sdl2-examples | src/Lesson01.hs | mit | 766 | 0 | 9 | 149 | 162 | 85 | 77 | 18 | 1 |
--and the exceedingly quick way
main = print (sum [x | x <- [1..1000-1], x `mod` 3 == 0 || x `mod` 5 == 0])
| beforan/project-euler | Problem-0001/Haskell/short.hs | mit | 108 | 0 | 14 | 25 | 64 | 35 | 29 | 1 | 1 |
module Main (main) where
import CabalFull (projectName)
main :: IO ()
main = putStrLn ("Tests for " ++ projectName)
| vrom911/hs-init | summoner-cli/examples/cabal-full/test/Spec.hs | mit | 119 | 0 | 7 | 22 | 42 | 24 | 18 | 4 | 1 |
-- solveRPN :: (Num a, Read a) => String -> a
-- solveRPN input = head . foldl foldingFunc [] (words input)
-- where foldingFunc (x:y:ys) "*" = (x*y):ys
-- foldingFunc (x:y:ys) "+" = (x+y):ys
-- foldingFunc (x:y:ys) "-" = (x-y):ys
-- foldingFunc xs number = read number:xs
--
-- LHR to London problem
import Data.List
-- each section is an algebraic data type, composed of three integers (3 roads)
data Section = Section {getA :: Int, getB :: Int, getC :: Int} deriving (Show)
-- a type synonim, saying that RoadSystem is a list of sections
type RoadSystem = [Section]
data Label = A | B | C deriving (Show)
type Path = [(Label, Int)]
heathrowToLondon :: RoadSystem
heathrowToLondon = [Section 50 10 30,
Section 5 90 20,
Section 40 2 25,
Section 10 8 0]
roadStep :: (Path, Path) -> Section -> (Path, Path)
roadStep (pathA, pathB) (Section a b c) =
let priceA = sum $ map snd pathA
priceB = sum $ map snd pathB
forwardPriceToA = priceA + a
crossPriceToA = priceB + b + c
forwardPriceToB = priceB + b
crossPriceToB = priceA + a + c
newPathToA = if forwardPriceToA <= crossPriceToA
then (A,a):pathA
else (C,c):(B,c):pathB
newPathToB = if forwardPriceToB <= crossPriceToB
then (B,a):pathB
else (C,c):(A,a):pathA
in (newPathToA, newPathToB)
groupsOf :: Int -> [a] -> [[a]]
groupsOf 0 _ = undefined
groupsOf _ [] = []
groupsOf n xs = take n xs : groupsOf n (drop n xs)
optimalPath :: RoadSystem -> Path
optimalPath roadSystem =
let (bestAPath, bestBPath) = foldl roadStep ([], []) roadSystem
in if sum (map snd bestAPath) <= sum (map snd bestBPath)
then bestAPath
else bestBPath
main = do
let b = optimalPath heathrowToLondon
print b | adizere/nifty-tree | playground/functionally.hs | mit | 1,955 | 0 | 12 | 614 | 560 | 311 | 249 | 38 | 3 |
-----------------------------------------------------------------------------
-- |
-- Module : Lisper.Compiler
--
-- Public interface of lisper
-----------------------------------------------------------------------------
module Lisper.Compiler (Scheme, Env, read, evaluate, compile, exec)
where
import Prelude hiding (read)
import Lisper.Core (Env, Scheme)
import Lisper.Eval (evaluate)
import Lisper.Macro (compile)
import Lisper.Parser (read)
-- | Compile and evaluate a string and return result
--
exec :: String -> Either String Scheme
exec str = do
ast <- read str
(source, _env) <- compile ast
(val, _env) <- evaluate source
return val
| jaseemabid/lisper | src/Lisper/Compiler.hs | mit | 672 | 0 | 8 | 107 | 156 | 90 | 66 | 12 | 1 |
import Graphics.UI.Gtk hiding (Settings)
import Graphics.Rendering.Cairo
import Data.Time.Clock.POSIX
import Data.Time
import System.Directory
import Control.Exception
import System.Locale (defaultTimeLocale)
import Data.IORef
import Control.Monad (when,forM)
import Data.List
import Text.Printf
iDuration = 30
rDuration = 120
amountOfIntervals = rDuration `div` iDuration
data Result = Result {
rDate :: String,
rMrks, rRank, rErrs :: Int
} deriving (Read, Show)
instance Eq Result where
(Result date1 mrks1 rnk1 errs1) == (Result date2 mrks2 rnk2 errs2) =
mrks1 == mrks2 && date1 == date2
instance Ord Result where
compare = fasterFst
fasterFst (Result date1 mrks1 rnk1 errs1) (Result date2 mrks2 rnk2 errs2) =
if mrks1 /= mrks2
then mrks2 `compare` mrks1
else date1 `compare` date2
zeroResult = Result {
rDate = "0000-00-00 00:00:00",
rMrks = 0, rRank = 0, rErrs = 0 }
data Timing = Timing {
sSession :: String, sTotal :: Int,
sSecsLeft :: Int, sSpeed :: Double
} deriving Show
zeroTiming = Timing {
sSession = "00:00", sTotal = 0,
sSecsLeft = iDuration, sSpeed = 0.0 }
data Interval = Interval {
iNum, iMrks, iErrs :: Int
} deriving Show
zeroInterval = Interval {
iNum = -1, iMrks = 0, iErrs = 0 }
data GUI = NotCreated | GUI {
gErrorCanvas :: DrawingArea,
gEntry :: Entry,
gLabel1, gLabel2 :: Label,
gStatusbar :: Label,
gStyle :: Style,
gModelR :: ListStore Result,
gModelS :: ListStore Timing,
gModelI :: ListStore Interval
}
data GameStatus = Error | Correct | Back | NotStarted
deriving (Eq, Show)
data State = State {
homeDirectory :: String,
textLines :: [String],
startTime :: POSIXTime,
oldStatus :: GameStatus,
oldlen :: Int,
lastShownIv :: Int,
oLabelStrs :: [String],
total :: Int,
speedNows :: [(POSIXTime, Int)],
intervals :: [Interval],
results :: [Result],
sessionBest :: Result,
settings :: Settings,
gui :: GUI
}
initState = State {
homeDirectory = "",
textLines = [],
startTime = fromIntegral 0 :: POSIXTime,
oldStatus = NotStarted,
oLabelStrs = ["",""],
oldlen = 0,
total = 0,
speedNows = [],
lastShownIv = -1,
intervals = [],
results = [],
sessionBest = zeroResult,
settings = defaultSettings,
gui = NotCreated
}
data Settings = Settings {
startLine :: Int,
lineLen :: Int,
textfile :: String,
font :: String
} deriving (Read, Show)
defaultSettings = Settings {
startLine = 0,
lineLen = 60,
textfile = "morse.txt",
font = "monospace 10"
}
xxx = replicate (lineLen defaultSettings) 'x'
s gs = settings gs
g gs = gui gs
r gs = results gs
resultsFromFile fname = do
structFromFile fname readRs []
settingsFromFile fname = do
structFromFile fname readSs defaultSettings
structFromFile fname pFunc zero = do
content <- readFile fname `catch`
\(SomeException e) -> return ""
result <- pFunc content `catch`
\(SomeException e) -> return zero
return result
readRs :: String -> IO [Result]
readRs = readIO
readSs :: String -> IO Settings
readSs = readIO
resultsFile = "results.txt"
settingsFile = "settings.txt"
getStartupConfig gsRef = do
gs <- readIORef gsRef
-- directory
homedir <- getHomeDirectory
let dir = homedir ++ "/.hatupist"
createDirectoryIfMissing False (dir)
-- settings
let rname = dir ++ "/" ++ settingsFile
oldSettings <- settingsFromFile rname
putStrLn ("Reading " ++ rname)
putStrLn (show (oldSettings))
-- results
let rname = dir ++ "/" ++ resultsFile
oldResults <- resultsFromFile rname
putStrLn ("Reading " ++ rname ++ ": " ++ show (length (oldResults)) ++ " rows")
listStoreSetValue (gModelR (g gs)) 0 (bestResult oldResults)
-- other
writeIORef gsRef gs {
homeDirectory = dir,
results = oldResults,
settings = oldSettings
}
setFonts gsRef
getLines gsRef = do
gs <- readIORef gsRef
originalText <- readFile (textfile (s gs))
let textLinesss = colLines (collectWords (words (originalText))
(lineLen (s gs)))
textLiness = map (++" ") textLinesss
writeIORef gsRef gs {
textLines = textLiness
}
renewLabels gsRef
quitProgram gsRef = do
print "Quitting."
gs <- readIORef gsRef
-- results
let rname = (homeDirectory gs) ++ "/" ++ resultsFile
writeFile rname (show (r gs))
putStrLn ("Writing " ++ rname)
-- settings
let rname = (homeDirectory gs) ++ "/" ++ settingsFile
writeFile rname (show (s gs))
putStrLn ("Writing " ++ rname)
mainQuit
main = do
gsRef <- newIORef initState
initGUI
createGUI gsRef
getStartupConfig gsRef
getLines gsRef
gs <- readIORef gsRef
setStatusText "Voit aloittaa." (toGtkColor green) gs
mainGUI
setFonts gsRef = do
gs <- readIORef gsRef
let gui = g gs
newFont = font (s gs)
srcfont <- fontDescriptionFromString newFont
widgetModifyFont (gLabel1 gui) (Just srcfont)
widgetModifyFont (gLabel2 gui) (Just srcfont)
widgetModifyFont (gEntry gui) (Just srcfont)
getStatus :: String -> String -> Int -> GameStatus
getStatus written goal oldlen
| a == b && c < d = Correct
| a == b = Back
| otherwise = Error
where
a = written
b = commonPrefix written goal
c = oldlen
d = length written
commonPrefix (x:xs) (y:ys)
| x == y = x : commonPrefix xs ys
| otherwise = []
commonPrefix _ _ = []
rInitModel = replicate 3 zeroResult
rColTitles = ["Päiväys", "Tulos", "Sija", "Virheitä" ]
rColFuncs = [ rDate, rSpeed . rMrks, rShowRank, rErrorPros]
sInitModel = [zeroTiming]
sColTitles = ["Istunto", "Yhteensä", "Jäljellä", "Nopeus"]
sColFuncs = [ sSession, show . sTotal, show . sSecsLeft, f01 . sSpeed]
iInitModel = replicate amountOfIntervals zeroInterval
iColTitles = ["Alkoi", "Päättyi", "Nopeus", "Virheitä" ]
iColFuncs = [ iStarts . iNum, iEnds . iNum, iSpeed . iMrks, iErrorPros]
createGUI gsRef = do
gs <- readIORef gsRef
window <- windowNew
style <- widgetGetStyle window
onDestroy window (quitProgram gsRef)
extrmVBox <- vBoxNew False 0
outerHBox <- hBoxNew False 0
outerVBox <- vBoxNew False 0
middleHBox <- hBoxNew False 0
innerVBox1 <- vBoxNew False 0
innerVBox2 <- vBoxNew False 0
menubar <- createMenuBar menuBarDescr gsRef
boxPackStart extrmVBox menubar PackNatural 0
rModel <- setupView rInitModel rColTitles rColFuncs innerVBox1
sModel <- setupView sInitModel sColTitles sColFuncs innerVBox1
iModel <- setupView iInitModel iColTitles iColFuncs innerVBox2
boxPackStart middleHBox innerVBox1 PackNatural 0
boxPackStart middleHBox innerVBox2 PackNatural 6
boxPackStart outerVBox middleHBox PackNatural 3
boxPackStart outerHBox outerVBox PackNatural 6
boxPackStart extrmVBox outerHBox PackNatural 0
set window [
containerChild := extrmVBox ]
errorCanvas <- drawingAreaNew
widgetSetSizeRequest errorCanvas 300 40
onExpose errorCanvas (
drawErrorCanvas gsRef errorCanvas)
boxPackStart outerVBox errorCanvas PackGrow 0
label1 <- labelNew (Just xxx)
miscSetAlignment label1 0 0
boxPackStart outerVBox label1 PackNatural 0
label2 <- labelNew (Just xxx)
miscSetAlignment label2 0 0
boxPackStart outerVBox label2 PackNatural 0
entry <- entryNew
entrySetHasFrame entry False
boxPackStart outerVBox entry PackNatural 3
onEditableChanged entry (
whenEntryChanged gsRef)
statusbar <- labelNew Nothing
miscSetAlignment statusbar 0 0
miscSetPadding statusbar 6 0
eventbox <- eventBoxNew
containerAdd eventbox statusbar
boxPackEnd extrmVBox eventbox PackNatural 0
widgetShowAll window
writeIORef gsRef gs {
gui = GUI {
gErrorCanvas = errorCanvas,
gEntry = entry,
gLabel1 = label1, gLabel2 = label2,
gStatusbar = statusbar,
gStyle = style,
gModelR = rModel, gModelS = sModel, gModelI = iModel }}
toWord x = round (x*65535.0)
toGtkColor (r,g,b) = Color (toWord r) (toWord g) (toWord b)
toGtkColors xs = [toGtkColor x | x <- xs]
blue = (0.200, 0.400, 1.000)
green = (0.451, 0.824, 0.086)
red = (1.000, 0.200, 0.400)
yellow = (0.988, 0.914, 0.310)
black = (0.000, 0.000, 0.000)
gray = (0.502, 0.502, 0.502)
white = (1.000, 1.000, 1.000)
brkRed = (0.886, 0.031, 0.000)
drawStatusText gsRef = do
gs <- readIORef gsRef
if (oldStatus gs) /= Error
then setStatusText "" (toGtkColor white) gs
else setStatusText "Korjaa virheet!" (toGtkColor red) gs
drawEmptyPicture canvas = do
return True
drawErrorCanvas gsRef widget _evt = do
gs <- readIORef gsRef
drawWin <- widgetGetDrawWindow widget
(wInt,hInt) <- widgetGetSize widget
let (w,h) = (intToDouble wInt, intToDouble hInt)
if (oldStatus gs) /= Error
then drawEmptyPicture widget
else renderWithDrawable drawWin (drawErrorPicture w h)
return True
relPolygon (x,y) points (r,g,b) = do
moveTo x y
mapM (\(x,y) -> relLineTo x y) points
closePath
setSourceRGB r g b
fill
drawErrorPicture w h = do
let c = h
r = 15
mapM
( \(x,y,points,color) -> relPolygon (x,y) points color)
[(x,0,[((-c),h),(r,0),(c,(-h))],
color) | (x,color) <- zip [0,r..w+c] (cycle [blue,red])]
return True
setupView initModel titles funcs parent = do
model <- listStoreNew (initModel)
view <- treeViewNewWithModel model
mapM
( \(title, func) -> newcol view model title func )
( zip titles funcs )
set view [ widgetCanFocus := False ]
boxPackStart parent view PackNatural 3
return model
where
newcol view model title func = do
renderer <- cellRendererTextNew
col <- treeViewColumnNew
cellLayoutPackStart col renderer True
cellLayoutSetAttributes col renderer model (
\row -> [ cellText := func row])
treeViewColumnSetTitle col title
treeViewAppendColumn view col
modify parent color text gs = do
if (text == "")
then do
bg <- styleGetBackground (gStyle (g gs)) StateNormal
widgetModifyBg parent StateNormal bg
else widgetModifyBg parent StateNormal color
setStatusText text color gs = do
let label = gStatusbar (g gs)
labelSetText label text
parent <- widgetGetParent label
case parent of
Nothing -> print "No parent"
Just parent -> modify parent color text gs
return ()
menuBarDescr =
[("_Tiedosto",
[("gtk-open", openFile),
("gtk-select-font", openFont),
("gtk-preferences", setPreferences),
("gtk-about", noop),
("gtk-quit", quitProgram)])
]
createMenuBar descr gsRef = do
bar <- menuBarNew
mapM_ (createMenu bar) descr
return bar
where
createMenu bar (name,items) = do
menu <- menuNew
item <- menuItemNewWithLabelOrMnemonic name
menuItemSetSubmenu item menu
menuShellAppend bar item
mapM_ (createMenuItem menu) items
createMenuItem menu (stock,action) = do
item <- imageMenuItemNewFromStock stock
menuShellAppend menu item
onActivateLeaf item (do action gsRef)
menuItemNewWithLabelOrMnemonic name
| elem '_' name = menuItemNewWithMnemonic name
| otherwise = menuItemNewWithLabel name
noop gsRef = do
return ()
setPreferences gsRef = do
gs <- readIORef gsRef
result <- chooseLineLen "Rivinpituus" (lineLen (s gs))
case result of
Just newLineLen -> do
writeIORef gsRef gs {
settings = (s gs) {
lineLen = newLineLen,
startLine = 0 }}
getLines gsRef
otherwise -> return ()
chooseLineLen prompt oldLineLen = do
dialog <- dialogNew
set dialog [ windowTitle := prompt ]
dialogAddButton dialog stockCancel ResponseCancel
dialogAddButton dialog stockOk ResponseOk
nameLabel <- labelNew $ Just "Rivinpituus (merkkiä):"
adjustment <- adjustmentNew (fromIntegral oldLineLen) 1 250 5 1 0
spinbutton <- spinButtonNew adjustment 1.0 0
upbox <- dialogGetUpper dialog
boxPackStart upbox nameLabel PackNatural 0
boxPackStart upbox spinbutton PackNatural 0
widgetShowAll upbox
response <- dialogRun dialog
print response
widgetDestroy dialog
case response of
ResponseOk -> do
value <- spinButtonGetValueAsInt spinbutton
widgetDestroy dialog
return (Just value)
ResponseCancel -> do
widgetDestroy dialog
return Nothing
ResponseDeleteEvent -> do
widgetDestroy dialog
return Nothing
_ -> return Nothing
openFont gsRef = do
gs <- readIORef gsRef
result <- chooseFont "Valitse kirjasin" (font (s gs))
case result of
Just newFont -> do
writeIORef gsRef gs {
settings = (s gs) {
font = newFont }}
setFonts gsRef
otherwise -> return ()
chooseFont prompt oldFont = do
dialog <- fontSelectionDialogNew prompt
fontSelectionDialogSetFontName dialog oldFont
widgetShow dialog
response <- dialogRun dialog
print response
case response of
ResponseOk -> do
fn <- fontSelectionDialogGetFontName dialog
widgetDestroy dialog
return fn
ResponseCancel -> do
widgetDestroy dialog
return Nothing
ResponseDeleteEvent -> do
widgetDestroy dialog
return Nothing
_ -> return Nothing
openFile gsRef = do
gs <- readIORef gsRef
result <- chooseFile "Valitse teksti"
case result of
Just newTextFile -> do
writeIORef gsRef gs {
settings = (s gs) {
textfile = newTextFile,
startLine = 0 }}
getLines gsRef
otherwise -> return ()
chooseFile prompt = do
dialog <- fileChooserDialogNew (Just prompt) Nothing
FileChooserActionOpen
[("gtk-cancel",ResponseCancel),
("gtk-open", ResponseAccept)]
fileChooserSetCurrentFolder dialog "."
widgetShow dialog
response <- dialogRun dialog
case response of
ResponseAccept -> do
fn <- fileChooserGetFilename dialog
widgetDestroy dialog
return fn
ResponseCancel -> do
widgetDestroy dialog
return Nothing
ResponseDeleteEvent -> do
widgetDestroy dialog
return Nothing
_ -> return Nothing
rShowRank rR =
showRank (rRank rR)
rErrorPros rR =
f02p (errorPros (rErrs rR) (rMrks rR))
iErrorPros iV =
f02p (errorPros (iErrs iV) (iMrks iV))
errorPros errs mrks
| total == 0 = 0.0
| otherwise = 100.0 * (intToDouble errs) / (intToDouble total)
where
total = mrks + errs
f01 :: Double -> String
f01 = printf "%.1f"
f02p :: Double -> String
f02p = printf "%.2f%%"
speed mrks t =
(intToDouble mrks) * 60.0 / (max t 1.0)
iSpeed mrks =
f01 (speed mrks (intToDouble iDuration))
rSpeed mrks =
f01 (speed mrks (intToDouble rDuration))
iStarts n
| n <= 0 = "00:00"
| otherwise = mmss (fromIntegral (n*iDuration) :: Double)
iEnds n = iStarts (n+1)
iNumber t =
floor t `div` iDuration
iLeft t =
iDuration - (floor t `mod` iDuration)
mmss seconds =
leadingZero (show (floor seconds `div` 60)) ++
":" ++
leadingZero (show (floor seconds `mod` 60))
leadingZero s
| length s < 2 = "0" ++ s
| otherwise = s
secondsFrom startPt endPt =
a - b
where
a = ptToDouble endPt
b = ptToDouble startPt
ptToDouble :: POSIXTime -> Double
ptToDouble t = fromRational (toRational t)
intToDouble :: Int -> Double
intToDouble i = fromRational (toRational i)
blankStart n str =
replicate n ' ' ++ drop n str
renewLabels gsRef = do
gs <- readIORef gsRef
let labelStrs = labelStrings (startLine (settings gs)) (textLines gs)
set (gLabel1 (g gs)) [ labelLabel := labelStrs !! 0 ]
set (gLabel2 (g gs)) [ labelLabel := labelStrs !! 1 ]
writeIORef gsRef gs {
oLabelStrs = labelStrs
}
entrySetText (gEntry (g gs)) ""
labelStrings :: Int -> [String] -> [String]
labelStrings startline textLines =
[textLines !! first] ++ [textLines !! second]
where
first = startline `mod` (length textLines)
second = (startline + 1) `mod` (length textLines)
ivsBetween iMin iMax ivs =
filter (\iv -> iMin <= (iNum iv) && (iNum iv) <= iMax) ivs
ivsFrom iMin ivs =
filter (\iv -> iMin <= (iNum iv)) ivs
ivsAllBetween iMin iMax ivs =
[ivExactly n ivs | n <- [iMin .. iMax]]
ivExactly n ivs =
case find (\iv -> n == (iNum iv)) ivs of
Just x -> x
Nothing -> zeroInterval { iNum = n }
tableRRefreshMs = 500
speedFromMs = 10000
speedCount = speedFromMs `div` tableRRefreshMs
difs speds =
if null speds
then (0.0, 0)
else (secondsFrom (fst start) (fst end), (snd end) - (snd start))
where
start = last speds
end = head speds
renewTableS gs t = do
pt <- getPOSIXTime
let newGs = gs {
speedNows = [(pt, (total gs))] ++ take speedCount (speedNows gs)
}
let s = difs (speedNows newGs)
listStoreSetValue (gModelS (g gs)) 0 Timing {
sSecsLeft = iLeft t,
sSession = mmss t,
sTotal = total gs,
sSpeed = speed (snd s) (fst s)
}
return newGs
bestResult results = if null results
then zeroResult
else head results
timeFormatted :: ZonedTime -> String
timeFormatted = formatTime defaultTimeLocale "%Y-%m-%d %H:%M:%S"
reRank1 (Result { rDate = a, rMrks = b, rRank = c, rErrs = d }, newRank) =
Result { rDate = a, rMrks = b, rRank = newRank, rErrs = d }
reRank rs = map reRank1 (zip rs [1..])
addResult showIvs gs = do
pt <- getPOSIXTime
tz <- getCurrentTimeZone
let newResult0 = zeroResult {
rDate = timeFormatted (utcToZonedTime tz (posixSecondsToUTCTime pt)),
rMrks = sum [iMrks g | g <- showIvs],
rErrs = sum [iErrs g | g <- showIvs]
}
let newResult = newResult0 {
rRank = tellRank newResult0 (results gs)
}
let
newRs = take maxRank (insert newResult (results gs))
new2Rs = reRank newRs
newShownRs = [
bestResult new2Rs,
(sessionBest gs) `min` newResult,
newResult ]
return (new2Rs, newShownRs)
showRank rank
| rank <= maxRank = show rank
| otherwise = ">" ++ show maxRank
tellRank x xs =
case findIndex (x <=) xs of
Just n -> n + 1
Nothing -> length xs + 1
maxRank = 5000
renewTableR gs shownRs = do
mapM
(\(a,b) -> listStoreSetValue (gModelR (g gs)) a b)
(zip [0..] shownRs)
return ()
renewTableI gs iCur = do
mapM
(\(a,b) -> listStoreSetValue (gModelI (g gs)) (amountOfIntervals-a) b)
(zip [1..] showIvs)
(newRs, newShownRs) <- addResult showIvs gs
return (gs {
intervals = newIvs,
lastShownIv = iCur,
results = newRs,
sessionBest = newShownRs !! 1
}, newShownRs)
where
iMaxShow = iCur - 1
infimum = iMaxShow - amountOfIntervals + 1
iMinShow = max 0 infimum
iMinNeed = max 0 (infimum + 1)
newIvs = ivsFrom iMinNeed (intervals gs)
showIvs = reverse (ivsAllBetween iMinShow iMaxShow (intervals gs))
renewSeldomTables gs iCur = do
(newGs, shownRs) <- renewTableI gs iCur
renewTableR newGs shownRs
return newGs
renewTables gs t iCur = do
newGs <- renewTableS gs t
new2Gs <- if (lastShownIv newGs /= iCur) && iCur >= 1
then renewSeldomTables newGs iCur
else return newGs
return new2Gs
onTimeout gsRef = do
gs <- readIORef gsRef
pt <- getPOSIXTime
let t = secondsFrom (startTime gs) pt
iCur = iNumber t
newGs <- renewTables gs t iCur
writeIORef gsRef newGs
return True
whenEntryChanged gsRef = do
pt <- getPOSIXTime
gs <- readIORef gsRef
txt <- entryGetText (gEntry (g gs))
let label1Str = head (oLabelStrs gs)
status = getStatus txt label1Str (oldlen gs)
f = case (status,oldStatus gs) of
(_,NotStarted) -> whenNotStarted status
(Correct,_) -> whenCorrect txt
(Error,Correct) -> whenNewError
otherwise -> whenOther status (oldStatus gs)
cprfix = length (commonPrefix txt label1Str)
newGs <- f pt gsRef gs
set (gLabel1 (g gs)) [
labelLabel := blankStart cprfix label1Str]
writeIORef gsRef newGs {
oldStatus = status,
oldlen = max cprfix (oldlen gs)
}
drawStatusText gsRef
widgetQueueDraw (gErrorCanvas (g gs))
when (label1Str == txt) (advanceLine gsRef newGs)
return ()
whenNotStarted status pt gsRef gs = do
putStrLn ("Started with " ++ (show status))
timeoutAdd (onTimeout gsRef) tableRRefreshMs
return gs {
total = if status == Correct then 1 else 0,
startTime = pt,
intervals = addTime
status
(iNumber 0.0)
(intervals gs)
}
whenCorrect txt pt gsRef gs = do
print "Correct."
return gs {
total = (total gs) + 1,
intervals = addTime
Correct
(iNumber (secondsFrom (startTime gs) pt))
(intervals gs)
}
whenNewError pt gsRef gs = do
print "New Error."
return gs {
intervals = addTime
Error
(iNumber (secondsFrom (startTime gs) pt))
(intervals gs)
}
whenOther status oldStatus pt gsRef gs = do
putStrLn ("Other with " ++ (show (status,oldStatus)))
return gs
latestIvNum ivs = if null ivs then -1 else iNum (head ivs)
addTime status i intervals =
[newHead] ++ tail newIvs
where
newHead = case status of
Correct -> headIv { iMrks = (iMrks headIv) + 1 }
Error -> headIv { iErrs = (iErrs headIv) + 1 }
headIv = head newIvs
newIvs = if null intervals || i /= latestIvNum intervals
then [zeroInterval { iNum = i }] ++ intervals
else intervals
advanceLine gsRef gs = do
gs <- readIORef gsRef
let newStartLine = ((startLine (s gs)) + 1) `mod` (length (textLines gs))
writeIORef gsRef gs {
settings = (s gs) {
startLine = newStartLine},
oldlen = 0
}
renewLabels gsRef
return ()
colLines (xs:xss) =
(unwords xs) : colLines xss
colLines [] = []
collectWords [] n = []
collectWords ys n =
p1 : collectWords p2 n
where
(p1,p2) = splitAt (length (untilLen ys 0 n)) ys
untilLen (t:ts) s n
| s+x<n || s==0 = t : untilLen ts (s+x) n
| otherwise = []
where
x = length t + 1
untilLen [] s n = []
| jsavatgy/hatupist | code/statusbar.hs | gpl-2.0 | 21,728 | 0 | 17 | 5,192 | 7,934 | 3,979 | 3,955 | 681 | 4 |
module HEP.Automation.MadGraph.Dataset.Set20110712set3 where
import HEP.Storage.WebDAV.Type
import HEP.Automation.MadGraph.Model
import HEP.Automation.MadGraph.Machine
import HEP.Automation.MadGraph.UserCut
import HEP.Automation.MadGraph.SetupType
import HEP.Automation.MadGraph.Model.C8S
import HEP.Automation.MadGraph.Dataset.Processes
import HEP.Automation.JobQueue.JobType
processSetup :: ProcessSetup C8S
processSetup = PS {
model = C8S
, process = preDefProcess TTBar0or1J
, processBrief = "TTBar0or1J"
, workname = "710_C8S_TTBar0or1J_LHC"
}
paramSet :: [ModelParam C8S]
paramSet = [ C8SParam { mnp = m, gnpR = g, gnpL = 0 }
| (m,g) <- [ (200,0.5), (200,1.0)
, (400,0.5), (400,1.0), (400,1.5)
, (600,0.5), (600,1.0), (600,1.5), (600,2.0), (600,2.5)
, (800,0.5), (800,1.0), (800,1.5), (800,2.0), (800,2.5), (800,3.0)
, (1000,0.5), (1000,1.0), (1000,1.5), (1000,2.0), (1000,2.5), (1000,3.0), (1000,3.5), (1000,4.0) ] ]
sets :: [Int]
sets = [1]
ucut :: UserCut
ucut = UserCut {
uc_metcut = 15.0
, uc_etacutlep = 2.7
, uc_etcutlep = 18.0
, uc_etacutjet = 2.7
, uc_etcutjet = 15.0
}
eventsets :: [EventSet]
eventsets =
[ EventSet processSetup
(RS { param = p
, numevent = 100000
, machine = LHC7 ATLAS
, rgrun = Fixed
, rgscale = 200.0
, match = MLM
, cut = DefCut
, pythia = RunPYTHIA
, usercut = UserCutDef ucut
, pgs = RunPGS
, jetalgo = AntiKTJet 0.4
, uploadhep = NoUploadHEP
, setnum = num
})
| p <- paramSet , num <- sets ]
webdavdir :: WebDAVRemoteDir
webdavdir = WebDAVRemoteDir "paper3/ttbar_LHC_c8s_pgsscan"
| wavewave/madgraph-auto-dataset | src/HEP/Automation/MadGraph/Dataset/Set20110712set3.hs | gpl-3.0 | 1,947 | 0 | 10 | 637 | 578 | 372 | 206 | 50 | 1 |
module Render where
import Graphics.UI.SDL as SDL
import Graphics.UI.SDL.TTF as TTF
import Graphics.UI.SDL.Image as SDLi
import Dungeon
renderWorld :: GameState -> IO ()
renderWorld gs = do
s <- getVideoSurface
fillRect s (Just $ Rect 0 0 800 600) (Pixel 0)
renderLayer s 0 (gArea gs) (gGx gs)
renderPlayer s (gPlayer gs) (gGx gs)
renderNpcs s (gArea gs) (gGx gs)
SDL.flip s
putStr ""
renderPlayer :: Surface -> Player -> [Surface]-> IO(Bool)
renderPlayer s p ss =
blitSurface
(playerSurface p ss)
(Just $ playerRect p)
s
(Just $ getPlayerDispRect p)
playerSurface :: Player -> [Surface] -> Surface
playerSurface _ surfaces = surfaces !! 1
playerRect :: Player -> Rect
playerRect p
| face == North = Rect 0 (48*3) 32 48
| face == South = Rect 0 0 32 48
| face == West = Rect 0 (48) 32 48
| face == East = Rect 0 (48*2) 32 48
where face = pFacing p
getPlayerDispRect :: Player -> Rect
getPlayerDispRect p = Rect ((fst pos)*32) ((snd pos)*32 - 16) 32 48
where pos = pPos p
renderNpcs :: Surface -> Area -> [Surface] -> IO()
renderNpcs s area (f:fs) =
mapM_ blitNpc (aNpcs area)
where blitNpc npc = blitSurface
f
(Just $ Rect 64 64 32 32)
s
(Just $ Rect (y*dim) (x*dim) dim dim)
where (x, y) = nPos npc
dim = 32
renderLayer :: Surface -> Int -> Area -> [Surface] -> IO()
renderLayer s _ area gx = do
let board = aBoard area
mapM_ (blitTile gx s) board
blitTile :: [Surface] -> Surface -> ((Int, Int), GroundType) -> IO(Bool)
blitTile (f:fs) s ((y, x), t) =
blitSurface
f
(Just $ rectFromGroundType t)
s
(Just $ Rect (y*dim) (x*dim) dim dim)
where dim = 32
rectFromGroundType :: GroundType -> Rect
rectFromGroundType Wall = Rect 0 0 32 32
rectFromGroundType Floor = Rect 0 (11*32) 32 32
rectFromGroundType Door = Rect 0 (2*32) 32 32
| Spacejoker/DDclone | rpg/src/Render.hs | gpl-3.0 | 1,904 | 0 | 12 | 494 | 888 | 453 | 435 | 59 | 1 |
-- Propositional logic
-- THIS VERSION ENCODES NAMES AS INTEGERS, THUS ALLOWING MORE RAPID COMPARISON.
module PropLogicLib (
Form(F, T, Var, Neg, Conj, Disj, Imp, Equiv),
mkVar, encode, decode,
showForm, showName, readsForm, pf,
Theorem(),
projHyps, projForm,
taut, disch, mp,
andIntro, andElimL, andElimR,
orIntroL, orIntroR, orElim,
notIntro, notElim,
trueIntro, falseElim
)
where {
import List;
import Char;
import Parse;
import Set;
data Form = F
| T
| Var Int -- Note that identifiers are coded as integers
| Neg Form
| Conj Form Form
| Disj Form Form
| Imp Form Form
| Equiv Form Form;
-- This function restricts variable names to proper identifiers
mkVar :: String -> Var;
mkVar s = if isIdentifier s then
Var (encode s)
else
error ("PropLogic.mkVar: bad identifer: " ++ s);
isIdentifier s = isAlpha (head s) &&
and (map isAlphaNum (tail s));
base = 100; -- Used for encoding/decoding strings
encode :: String -> Int;
encode = let f = \n ch -> (n * base) + encodeChar ch
in foldl f 0;
encodeChar :: Char -> Int;
encodeChar ch = let n = ord ch - ord '0' -- Crude, but adequate for ordinary ASCII alphamerics
in if (n >= 0) && (n < base) then
n
else
error ("PropLogic.encodeChar: char out of range: " ++ [ch]);
decode :: Int -> String;
decode n = decode' n "";
decode' n rest =
let {d = rem n base;
q = quot n base;
rest' = decodeChar d : rest
} in if q == 0 then rest' else decode' q rest';
decodeChar :: Int -> Char;
decodeChar n = chr (n + ord '0');
instance Equal Form where
eq fm1 fm2 =
case (fm1, fm2) of {
(F, F) -> True;
(T, T) -> True;
(Var s1, Var s2) -> (s1 == s2);
(Neg fm1a, Neg fm2a) -> (eq fm1a fm2a);
(Conj fm1a fm1b, Conj fm2a fm2b) -> eq fm1a fm2a && eq fm1b fm2b;
(Disj fm1a fm1b, Disj fm2a fm2b) -> eq fm1a fm2a && eq fm1b fm2b;
(Imp fm1a fm1b, Imp fm2a fm2b) -> eq fm1a fm2a && eq fm1b fm2b;
(Equiv fm1a fm1b, Equiv fm2a fm2b) -> eq fm1a fm2a && eq fm1b fm2b;
_ -> False
};
instance Show Form where {
shows fm s = showForm fm ++ s;
show fm = showForm fm
};
-- The first arg (fm) is present purely in order so that the dynamic class
-- mechanism can determine which instance to use. It is not used in computing the result.
instance Read Form where
reads fm = readsForm;
-- A convenient "parse form" function
pf :: String -> Form;
pf = unique (exact readsForm);
-- Unparsing functions
showForm :: Form -> String;
showForm fm =
case fm of {
F -> "F";
T -> "T";
Var s -> decode s;
Neg fm -> "~ " ++ showParenForm fm;
Conj fm1 fm2 -> opForm fm1 " & " fm2;
Disj fm1 fm2 -> opForm fm1 " | " fm2;
Imp fm1 fm2 -> opForm fm1 " => " fm2;
Equiv fm1 fm2 -> opForm fm1 " == " fm2
};
opForm fm1 op fm2 = showParenForm fm1 ++ op ++ showParenForm fm2;
-- A formula is deemed to be atomic (for unparsing) if it is a truth value, a Var or a Neg of an atomic formula
isAtomic fm =
case fm of {
F -> True;
T -> True;
Var _ -> True;
Neg fm -> isAtomic fm;
_ -> False
};
-- Apply paretheses unless atomic
showParenForm fm =
if isAtomic fm then
showForm fm
else
"(" ++ showForm fm ++ ")";
-- Parsing functions
readsForm :: Reads Form;
readsForm = readsAtomicForm <> readsBinOpForm;
readsAtomicForm = readsTruthValue <> readsVar <> readsNegForm <> readsBracketedForm;
readsTruthValue = spaced ((char 'F' ~> const F) <> (char 'T' ~> const T));
readsVar = spaced identifier ~> mkVar;
readsNegForm = (spaced (char '~') >> readsAtomicForm) ~> (Neg. snd);
readsBracketedForm = bracketed readsForm;
readsBinOpForm = (readsAtomicForm >> spaced operator >> readsAtomicForm) ~> mkBinForm;
mkBinForm x =
case x of {
((f1, "&" ), f2) -> Conj f1 f2;
((f1, "|" ), f2) -> Disj f1 f2;
((f1, "=>"), f2) -> Imp f1 f2;
((f1, "=="), f2) -> Equiv f1 f2;
((f1, op ), f2) -> error "PropLogic.mkBinForm: unknown operator: " ++ op
};
-- --- Theorems ---------------------------------------------------------------------------------------------
type Name = Int; -- The names of hypotheses are (like Var names) encoded
type Hyp = (Name, Form);
type Hyps = [Hyp];
data Theorem = Thm Hyps Form;
projHyps :: Thm -> Hyps;
projHyps thm = case thm of Thm hyps _ -> hyps;
projForm :: Thm -> Form;
projForm thm = case thm of Thm _ fm -> fm;
instance Show Theorem where {
shows thm s = showThm thm ++ s;
show thm = showThm thm
};
showThm :: Theorem -> String;
showThm thm =
case thm of
Thm hyps conc -> showNames (map fst hyps) ++ " |- " ++ showForm conc;
showNames :: [Name] -> String;
showNames names =
if null names then
""
else
'{' : showName (head names) ++ concat [ ", " ++ (showName name) | name <- tail names] ++ "} ";
showName :: Name -> String;
showName = decode;
-- Natural deduction inference rules ----------------------------------------------------------------------
taut :: Name -> Form -> Thm;
taut name fm = Thm [(name,fm)] fm;
disch :: Name -> Theorem -> Theorem;
disch name thm =
case thm of
Thm hyps conc ->
let { p = \hyp -> fst hyp `eq` name;
hypsPair = partition p hyps;
hyps1 = fst hypsPair;
hyps2 = snd hypsPair
} in case hyps1 of {
[(nm, fm)] -> Thm hyps2 (Imp fm conc);
_ -> error "PropLogic.impIntro: hypothesis not present"
};
mp :: Theorem -> Theorem -> Theorem;
mp thm1 thm2 =
case (thm1, thm2) of {
(Thm hyps1 (Imp fm1a fm1b), Thm hyps2 fm2) ->
let { clashes = isClash hyps1 hyps2;
hyps = hyps1 ++ hyps2
} in if null clashes then
if fm1a `eq` fm2 then
Thm hyps fm1b
else
error "PropLogic.mp: formulae do not match"
else
error ("PropLogic.mp: " ++ showNames clashes);
_ -> error "PropLogic.mp: not an implication"
};
andIntro :: Theorem -> Theorem -> Theorem;
andIntro thm1 thm2 =
case (thm1, thm2) of
((Thm hyps1 conc1), (Thm hyps2 conc2)) ->
Thm (merge hyps1 hyps2) (Conj conc1 conc2);
andElimL, andElimR :: Theorem -> Theorem;
andElimL thm =
case thm of {
Thm hyps (Conj fmL fmR) -> Thm hyps fmL;
_ -> error "PropLogic.andElimL: not a conjunction"
};
andElimR thm =
case thm of {
Thm hyps (Conj fmL fmR) -> Thm hyps fmR;
_ -> error "PropLogic.andElimR: not a conjunction"
};
orIntroL, orIntroR :: Theorem -> Form -> Form;
orIntroL thm fmR =
case thm of
Thm hyps fmL -> Thm hyps (Disj fmL fmR);
orIntroR thm fmL =
case thm of
Thm hyps fmR -> Thm hyps (Disj fmL fmR);
orElim :: Theorem -> Theorem -> Theorem -> Theorem;
orElim thm thm1 thm2 =
case (thm, (thm1, thm2)) of
(Thm hyps fm, (Thm hyps1 fm1, Thm hyps2 fm2)) ->
case fm of {
Disj fmL fmR ->
let { hyps1' = removeForm fmL hyps1;
hyps2' = removeForm fmR hyps2;
hyps' = merge hyps (merge hyps1' hyps2')
} in if eq fm1 fm2 then
Thm hyps' fm1
else
error ("PropLogic.orElim: theorems do not match: " ++ show fm1 ++ ", and " ++ show fm2);
_ -> error ("PropLogic.orElim: not a disjunction: " ++ show fm)
};
notIntro :: Name -> Theorem -> Theorem;
notIntro nm thm =
case thm of
Thm hyps fm ->
let { p = \hyp -> fst hyp `eq` nm;
hypsPair = partition p hyps;
hyps1 = fst hypsPair;
hyps2 = snd hypsPair
} in case hyps1 of {
[(nm,fm)] -> Thm hyps2 (Neg fm);
_ -> error ("PropLogic.notIntro: hyp not present: " ++ (showName nm))
};
notElim :: Theorem -> Theorem -> Theorem;
notElim thm1 thm2 =
case (thm1, thm2) of {
((Thm hyps1 fm1),(Thm hyps2 (Neg fm2))) ->
if (fm1 `eq` fm2) then
Thm (merge hyps1 hyps2) F
else
error "PropLogic.notElim: non-matching formulae";
_ -> error "PropLogic.notElim: not a negation"
};
trueIntro :: Theorem;
trueIntro = Thm [] T;
falseElim :: Theorem -> Form -> Theorem;
falseElim thm fm =
case thm of {
Thm hyps F -> Thm hyps fm;
_ -> error "PropLogic.falseElim: non-false theorem"
};
-- Attempt to merge two list of hypotheses. Throws an error if the same name occurs
-- in each list but associated with a different formula.
merge :: Hyps -> Hyps -> Hyps;
merge hyps1 hyps2 =
let clashes = isClash hyps1 hyps2
in if null clashes then
nub (hyps1 ++ hyps2)
else
error ("PropLogic.merge: " ++ showNames clashes);
-- ---------------------------------------
-- This function compares two sets of hypotheses; it returns a list of the names of any
-- clashes. Thus, the return of an empty list denotes success.
isClash :: [Hyp] -> [Hyp] -> [Name];
isClash hyps1 hyps2 =
case hyps2 of {
[] -> [];
hyp:hyps -> isClash' hyps1 hyp ++ isClash hyps1 hyps
};
isClash' :: [Hyp] -> Hyp -> [Name];
isClash' hyps hyp =
case hyps of {
[] -> [];
hyp1:hyps1 -> isClash'' hyp hyp1 ++ isClash' hyps1 hyp
};
isClash'' :: Hyp -> Hyp -> [Name];
isClash'' hyp1 hyp2 =
case (hyp1, hyp2) of {
((name1, fm1), (name2, fm2)) ->
if (name1 /= name2) || (fm1 `eq` fm2) then
[]
else
[name1];
_ -> hyp1
};
-- This function removes a formula from a list of hypotheses. It fails if the formula is not present
removeForm :: Form -> [Hyp] -> [Hyp];
removeForm fm hyps =
case hyps of {
[] -> error ("PropLogic.removeHyp: formula not found: " ++ show fm);
hyp: hyps -> if eq fm (snd hyp) then
hyps
else
hyp : removeForm fm hyps
}
}
| ckaestne/CIDE | CIDE_Language_Haskell/test/fromviral/PropLogicLib-encoded.hs | gpl-3.0 | 11,347 | 62 | 17 | 4,324 | 3,207 | 1,769 | 1,438 | -1 | -1 |
module WebParsing.PostParser
(addPostToDatabase) where
import qualified Data.Text as T
import Control.Monad.Trans (liftIO)
import Text.HTML.TagSoup
import Text.HTML.TagSoup.Match
import Database.Tables
import Database.Persist.Sqlite (insert_, SqlPersistM)
import Database.Persist (insertUnique)
import qualified Text.Parsec as P
import WebParsing.ParsecCombinators (getCourseFromTag, generalCategoryParser, parseCategory,
postInfoParser)
failedString :: String
failedString = "Failed."
addPostToDatabase :: [Tag T.Text] -> SqlPersistM ()
addPostToDatabase programElements = do
-- TODO: Remove Focuses from programElements
let fullPostName = innerText $ take 1 $ filter isTagText programElements
requirements = last $ sections isRequirementSection programElements
liPartitions = partitions isLiTag requirements
programPrereqs = map getCourseFromTag $ map (fromAttrib "href") $ filter isCourseTag programElements
firstCourse = if (null programPrereqs) then Nothing else (Just (head programPrereqs))
categoryParser requirements fullPostName firstCourse liPartitions
where
isRequirementSection element = tagOpenAttrLit "div" ("class", "field-content") element
isCourseTag tag = tagOpenAttrNameLit "a" "href" (\hrefValue -> T.isInfixOf "/course" hrefValue) tag
isLiTag tag = isTagOpenName "li" tag
addPostCategoriesToDatabase :: [T.Text] -> SqlPersistM ()
addPostCategoriesToDatabase categories = do
mapM_ addCategoryToDatabase (filter isCategory categories)
where
isCategory text =
let infixes = map (containsText text)
["First", "Second", "Third", "suitable", "Core", "Electives"]
in
((T.length text) >= 7) && ((length $ filter (\bool -> bool) infixes) <= 0)
containsText text subtext = T.isInfixOf subtext text
addCategoryToDatabase :: T.Text -> SqlPersistM ()
addCategoryToDatabase category =
insert_ $ PostCategory category (T.pack "")
-- Helpers
categoryParser :: [Tag T.Text] -> T.Text -> Maybe T.Text -> [[Tag T.Text]] -> SqlPersistM ()
categoryParser tags fullPostName firstCourse liPartitions = do
case parsed of
Right (post, categories) -> do
postExist <- insertUnique post
case postExist of
Just _ -> do
addPostCategoriesToDatabase categories
Nothing -> return ()
Left _ -> do
liftIO $ print failedString
return ()
where
parsed = case liPartitions of
[] -> P.parse (generalCategoryParser fullPostName firstCourse) failedString (innerText tags)
partitionResults -> do
let categories = map parseLi partitionResults
post <- P.parse (postInfoParser fullPostName firstCourse) failedString (innerText tags)
return (post, categories)
parseLi :: [Tag T.Text] -> T.Text
parseLi liPartition = do
let parsed = P.parse parseCategory failedString (innerText liPartition)
case parsed of
Right category -> category
Left _ -> ""
| hermish/courseography | app/WebParsing/PostParser.hs | gpl-3.0 | 3,129 | 0 | 17 | 738 | 866 | 441 | 425 | 60 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.