lang
stringclasses
10 values
seed
stringlengths
5
2.12k
haskell
deriving ( Eq , Show , Read , Ord , Functor , Foldable , Traversable , Data
haskell
<gh_stars>0 fibs :: [Integer] fibs = 1 : 1 : (zipWith (+) fibs (tail fibs)) main :: IO () main = do print $ sum $ filter (\x -> x `mod` 2 == 0) (takeWhile (<4000000) fibs)
haskell
----------------------------------------------------------------------------- -- | Build archives from a pattern, grouped by date formated in the fmt pattern buildArchives :: (MonadMetadata m, Functor m) => String -> Pattern -> (String -> Identifier) -> m Archives buildArchives fmt pattern = (Archives <$>) .
haskell
safeDiv (Left e) _ = Left e safeDiv _ (Left e) = Left e safeDiv (Right i) (Right j) | j == 0 = Left "Illegal Operation: Division by Zero" safeDiv (Right i) (Right j) = Right (i `div` j) main :: IO () main = do let i = Right 10 :: Either String Int j = Right 2 :: Either String Int z = Right 0 :: Either String Int putStrLn $ "Safe division : 10 / 2 = " ++ (show $ safeDiv i j) putStrLn $ "Safe division : 10 / 0 = " ++ (show $ safeDiv i z)
haskell
lastNode Leaf = Leaf lastNode dl = until (isLeaf.next) next dl traverse _ Leaf = [] traverse True (Node l v Leaf) = v : v : traverse False l traverse dir (Node l v r) = v : traverse dir (if dir then r else l)
haskell
check player s = all (\(x,y) -> not y || x == player || x == 'T' ) s won player s = any (check player . zip s) pos antwort sa = let s = concat sa in if won 'O' s then "O won" else if won 'X' s then "X won" else if all ('.'/=) s then "Draw"
haskell
module Arkmonoid.Power.PowerSystem where import Control.Monad import Control.Monad.Random import Control.Lens import Data.Ecstasy import Data.Foldable import qualified Graphics.Gloss.Data.Color as G import Linear.V2
haskell
evnts = Set.elems alphabet cache = Map.fromSet (uncurry oracle) $ Set.fromList [ (x, y) | x <- evnts, y <- evnts, x <= y ] co a b = cache Map.! (min a b, max a b) putStr "Found concurrent pairs: " let foundPairs = [ (decode x, decode y) | (x:xs) <- tails evnts, y <- xs, x `co` y ] print foundPairs if expPairs /= foundPairs
haskell
state <- getLine let search = T.intercalate "+" ["US", addrr, (T.pack state)] -- todo: get address, state, zip from user and use to construct lat/lng request latLng <- LL.fetchLatLong search -- "US+Glen+Elder+State+Park+KS" case latLng of Nothing -> print "Failed to get latitude / longitude for request" Just (LL.LatLong lat lng) -> do weatherPoints <- P.fetchWeatherPoints lat lng case weatherPoints of
haskell
noBadStrings input = all (not . flip isInfixOf input) badstrings where badstrings = ["ab", "cd", "pq", "xy"] hasPalindromeTriplet :: String -> Bool hasPalindromeTriplet = any isPalindrome . triplets where isPalindrome = (==) <*> reverse triplets input = take (length input - 3 + 1) $ map (take 3) $ tails input repeatedPair :: String -> Bool repeatedPair = any repeatedPrefixPair . takeWhile ((>=4) . length) . tails where repeatedPrefixPair input = take 2 input `isInfixOf` drop 2 input applyRules :: [String -> Bool] -> String -> Bool applyRules rules string = and $ sequence rules string
haskell
prop (Node r ts) = (ds, doms M.! r == ds && and bs) where (ss, bs) = unzip $ prop <$> ts ds = S.insert r $ unions ss {-# INLINABLE prop_dominationTreeDefn #-}
haskell
} deriving (Show) data Type = Int | Float | V2 | V3 | V4 | M4 | Texture
haskell
, randomST ) where import Control.Monad.State (MonadState (get, put), State) import Gimlight.Prelude
haskell
--- --- Syntax helpers ---
haskell
-- Find out whether a list is a palindrome isPalindrome :: Eq a => [a] -> Bool isPalindrome xs = xs == reverse xs -- *Main> isPalindrome [1,2,3] -- o/p : False -- *Main> isPalindrome "madamimadam" -- o/p : True -- *Main> isPalindrome [1,2,4,8,16,8,4,2,1]
haskell
-- | Read a character from the input stream. If one cannot be read (e.g. -- we are out of characters), fail parsing. readChar :: Parser Char readChar = do s <- get case s of c:rest -> put rest >> return c _ -> failParse -- | Read a character from the input stream and fail parsing if it is -- not the specified character. expectChar :: Char -> Parser ()
haskell
-- Note that it is the kth smallest element in the sorted order, not the kth distinct element. module KthSmallest2 ( kthSmallest ) where import Data.List ( sort ) kthSmallest :: (Ord a) => Matrix a -> Int -> a kthSmallest matrix k = (!! (k - 1)) . sort $ foldr (<>) mempty matrix type Matrix a = [[a]]
haskell
utcFormat = "%Y-%m-%dT%H:%M:%SZ" utcFormats :: [String] utcFormats = [ "%Y-%m-%dT%H:%M:%S%z" , "%Y-%m-%dT%H:%M:%S%Z" , "%Y-%m-%dT%H:%M%Z" , "%Y-%m-%dT%H:%M:%S%QZ" , utcFormat ] mkUTC' :: UTCTime -> T.Text mkUTC' = T.pack . mkUTC_
haskell
| otherwise = oneof [ return AES128_WRAP_PAD , return AES192_WRAP_PAD , return AES256_WRAP_PAD , RC2_WRAP <$> choose (1, 1024) ] arbitraryDHParams = oneof [ arbitraryCredNamedEC , arbitraryCredX25519 , arbitraryCredX448 ]
haskell
| SPrint Exp | SWhile Exp Stmt | SAssign Ident AssignOp Exp | SIter Ident IterOp | SCompound [Stmt] | SProcCall Ident [Arg] deriving (Eq,Ord,Show) data AssignOp = Assign | AssignMul | AssignDiv | AssignAdd | AssignSub
haskell
{-# LANGUAGE DeriveGeneric #-} module Config ( Config(..) ) where import GHC.Generics (Generic) import Data.Aeson (FromJSON) data Config = Config { channel :: String, secret :: String, host :: String, port :: Int, obs_host :: String, obs_port :: Int, update_repo :: Maybe String } deriving (Show, Generic) instance FromJSON Config
haskell
cribObject :: [Char] cribObject = " C " obstacleObject :: [Char] obstacleObject = " O " -- data Kid = Kid { -- xKid :: Int, -- yKid :: Int -- }
haskell
module Compiler.Html ( tidyHtml ) where import Data.List (intercalate) import Text.XML.HXT.Core import Hakyll
haskell
{-# LANGUAGE DuplicateRecordFields #-} module T11167_ambiguous_fixity where import T11167_ambiguous_fixity_A import T11167_ambiguous_fixity_B x a = (a :: A) `foo` 0
haskell
:: HiddenClock dom => String -- ^ busAddr -> Signal dom Bool -- ^ sbrwi -> Signal dom Bool -- ^ sbstbi -> Signal dom (BitVector 8) -- ^ sbadri
haskell
withCString "get_point_path" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_point_path :: (AStar2D :< cls, Object :< cls) => cls -> Int -> Int -> IO PoolVector2Array get_point_path cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2]
haskell
put (MACAddr m) = putByteString m -- | 2-byte EtherType, specifies the protocol of the frame. newtype EtherType = EtherType Word16 deriving (Show, Eq, Num) -- | Simple Binary instance to get/put a Word16 in big endian instance Serialize EtherType where get = EtherType <$> getWord16be put (EtherType e) = putWord16be e -- | 2-byte VLAN tag data VLANTag = VLANTag { tpid :: Word16
haskell
groupMembers1 :: IsString s => [s] groupMembers1 = ["CureStar", "CureMilky", "CureSoleil", "CureSelene"] groupMembers2 :: IsString s => [s] groupMembers2 = groupMembers1 ++ ["CureCosmo"] groupMembersTwinkleStyle :: IsString s => [s] groupMembersTwinkleStyle = ["CureStar_TwinkleStyle", "CureMilky_TwinkleStyle", "CureSoleil_TwinkleStyle", "CureSelene_TwinkleStyle", "CureCosmo_TwinkleStyle"] starColorPendantColorCharge = ["スターカラーペンダント!", "カラーチャージ!"] transformationSong = [ "きーらーめーくー♪" , "ほーしーの力でー♪"
haskell
module CallByName.CPS, module CallByName.Evaluate ) where import CallByName.CPS import CallByName.Evaluate
haskell
tupped (Just n, Just g) = Just (n, g) tupped _ = Nothing form :: MonadWidget t m => (NoteResponse, [GroupShallow]) -> m (Event t JunksState) form (n, gs) = M.elTitleCardContainer "Edit Note" $ do let mGroup = find (\g -> g ^. id == n ^. groupId) gs evPb <- delay 0.1 =<< getPostBuild rec _ <- el "div" $ flashWidgetEv flashConfig (whenError evDec) el "h5" $ text $ maybe "!!! Invalid Group ID !!!" (untag . L.view name) mGroup
haskell
, getGlobalVolume , setListenerPosition , getListenerPosition , setListenerDirection , getListenerDirection , setListenerUpVector , getListenerUpVector ) where import SFML.System.Vector3
haskell
-- Drei data Drei a b c = Drei a b c deriving (Eq, Show) instance Bifunctor (Drei a) where bimap f g (Drei a b c) = Drei a (f b) (g c) -- SuperDrei data SuperDrei a b c = SuperDrei a b deriving (Eq, Show)
haskell
( module Language.HTML.AST , module Language.HTML.Codegen ) where import Language.HTML.AST
haskell
localIO $ JQuery.hide "#dependencyMessage" return newState _update (ToolbarAction action) appState = do newToolbarState <- Toolbar.update action (toolbarState appState) let cs = compilationState appState let newCompilationState = cs { Compilation.projectPath = Toolbar.projectPath newToolbarState } return appState { compilationState = newCompilationState, toolbarState = newToolbarState } readAtRemote :: FilePath -> Cloud (Either String String) readAtRemote path = atRemote . localIO $ maybeRead path
haskell
import qualified Graphics.Rendering.OpenGL as GL import Control.Monad import Data.Char (ord) import Graphics.Rendering.OpenGL (vertex, renderPrimitive, PrimitiveMode(LineStrip)) import Utils.Chars (chars)
haskell
import RIO import Data.Extensible import qualified Data.Yaml as Y type Config = Record '[ "repositories" >: [Text] -- expect owner/name ]
haskell
throwError (GithubE "length of pieces were not the same") pure (mkItems titles links dates) fetch (Reddit (Keyword subreddit)) = do let url = "https://www.reddit.com/r/" <> subreddit <> "/new/.json" json <- httpGet url let results = json ^.. key "data" . key "children" . values . key "data" titles = results ^.. traversed . key "title" . _String links
haskell
import Polysemy.Trace import Polysemy.Internal import Polysemy.Internal.Union -- | Trace calls to some effect, requires `Show` instance for the effect data type. debugTraceEffect :: forall e r a . ( Members '[e, Trace] r , forall m x. Show (e m x) ) => Sem r a -> Sem r a
haskell
assert True _ = Right () parseDebitCsv :: Text -> Either Text ([TxnRaw], Int) parseDebitCsv csv = do let debitCsvs = T.splitOn "\r\n\r\n" csv assert (length debitCsvs == 2) "Scraper.Bofa: length debitCsvs /= 2" let balanceCsv = debitCsvs !! 0 let txnCsv = debitCsvs !! 1 assert (length (T.lines txnCsv) > 1) "Scraper.Bofa: debitCsvText is empty" assert ("Beginning balance as of " `T.isInfixOf` ((T.lines txnCsv) !! 1)) "Scraper.Bofa: First debit csv txn not \"Beginning balance as of...\"" bal <- parseDebitBalance balanceCsv lTxnRaws <- goTxns parseDebitTxn $ T.unlines $ drop2nd $ T.lines txnCsv
haskell
case t of Just t -> Just (ZonedTime t tz) otherwise -> Nothing delayUntil :: ZonedTime -> IO () delayUntil time = do
haskell
main = app =<< getArgs -- | App's body app :: [String] -> IO () app ["insert", msg] = insertMessage $ Text.pack msg app ["list"] = undefined app [] = error "This program needs specifying startup target" app xs = error $ "Got the unknowned arguments: " ++ show xs
haskell
module UCap.Coord.Map where
haskell
temporaryRedirect = textual 307 badRequest = textual 400
haskell
import Data.ASN1.OID import qualified Data.ByteString as B import Data.Maybe (fromMaybe) import Data.X509 import Data.X509.EC import Crypto.Number.Basic (numBits, numBytes) import Crypto.Number.Serialize (i2ospOf_) import Crypto.PubKey.ECC.Prim import Crypto.PubKey.ECC.Types
haskell
-- | Mapping nick name and file path type PlaceMap = Map String FilePath -- | Throwable IOException with the message data HereisIOException = HereisIOException String deriving (Show) instance Exception HereisIOException
haskell
gdkCursorNewFromSurface (GdkDisplay d) (toCairoSurfaceT -> CairoSurfaceT fs) x y = withForeignPtr fs \s -> do c_cairo_surface_reference s mkGdkCursor' (c_cairo_surface_destroy s) =<< c_gdk_cursor_new_from_surface d s x y foreign import ccall "cairo_surface_reference" c_cairo_surface_reference :: Ptr (CairoSurfaceT s ps) -> IO ()
haskell
import Servant.Auth.Server import Servant.Server import Server.DB import Server.Helpers import Server.Types getPrivateProfile :: AuthResult AuthenticatedUser -> HandlerT ProfileInfo getPrivateProfile (Authenticated (AUser uuid)) = do log <- asks _logFn liftIO $ log $ "Viewing private profile of uuid:" <> toLogStr (show uuid) getProfileBy $ UniqueUUID uuid getPrivateProfile _ = reportHandlerError err401 "Unauthorized profile edit attempt"
haskell
<*> (option auto (long "index" <> help "Index of ambiguous parse" <> showDefault <> value 0 <> metavar "INT")) <*> (flag' Pretty (long "pretty" <> help "Pretty-print output") <|> flag' Tree (long "tree" <> help "Print the output as an abstract syntax tree") <|> pure Plain) <*> optional (strArgument ( metavar "FILE" <> help "Dart file to parse")) mode :: Parser GrammarMode mode = CompilationUnitMode <$ switch (long "compilation-unit") <|> DeclarationMode <$ switch (long "statement") <|> ExpressionMode <$ switch (long "expression") main' :: Opts -> IO () main' opts@Opts{..} =
haskell
(_, (rows, cols)) = bounds grid go !acc (i, j) = if i > rows then acc else go acc' (i + down, j + right) where acc' = acc + case grid ! (i, j `mod` (cols + 1)) of Tree -> 1; Open -> 0 ------------ PART B ------------ partB :: Input -> OutputB partB grid = foldMap
haskell
make :: b -> a data Cont a = Cont a deriving (Show, Eq) instance Container (Cont a) a where make x = Cont x instance (Container a b, Show a, Eq a, Num b) => Num a where fromInteger x = make (fromInteger x)
haskell
bpPlayAction = playTapeWithStrictness initGuts flags measure, bpRoot = ActionSeqEnd, bpIsDeterministic = True} -- inliningPayoff :: ModGuts -> DynFlags -> CountMeasure -> ActionSpec SearchTapeElement -> IO Float inliningPayoff guts dflags measure tape =
haskell
-- TODO: test case where there are 3 nodes, but log is only committed on leader -- + 1 node. Leader should NOT apply log to statemachine testRequestVoteReq :: Spec testRequestVoteReq = do let mkNode = mkServerState s1 [s2] 10 10 req cTerm lTerm lIndex = RVReq RequestVoteReq { _candidateTerm = cTerm , _from = s2
haskell
import GHCJS.DOM (currentWindowUnchecked) import GHCJS.DOM.Window (getLocalStorage) import Reflex.Dom.Core import Tapaw.Storage.KV (StoreKey, getKVAll, putKV, runKVStoreTStorage) main :: IO () main = run 3000 $ mainWidget $ do storage <- getLocalStorage =<< currentWindowUnchecked runKVStoreTStorage @User storage "users" $ do eIns <- button "Insert" eDel <- button "Delete" putKV ((UserId 5, Just User) <$ eIns)
haskell
return $ case m_outPath of Nothing -> Left noOutErr Just outPath -> Right $ unpack outPath where opts = defaults & header "Accept" .~ ["application/json"] & auth .~ m_creds noOutErr = "Latest build of job " ++ uri ++ " has no output named 'out'." latestUri = uri ++ "/latest" isTransientError e = case e of InvalidUrlException _ _ -> Nothing _ -> Just e
haskell
Traversable (traverse, sequenceA), for, fmapDefault, foldMapDefault, -- * Data.Traversable.WithIndex TraversableWithIndex (..), ifor, -- * Data.Type.Equality (:~:) (..), -- * Data.Universe.Class Universe (..), Finite (..), -- * Data.UUID.Types UUID, -- * Data.Void Void, absurd, -- * Data.Word
haskell
import Language.ECMAScript3.Parser.State import Text.Parsec import Control.Monad.Identity -- | The parser type, parametrised by the stream type @s@ and the -- return value @a@
haskell
do { sequence (map (inferK2 env star) ts) ; unifyKind hint star ; return star } (HsTyApp f x) -> do { a <- newVarK Sort ; inferK2 env (S(Kfun a hint)) f ; inferK2 env a x ; return hint } (HsTyVar nm) ->
haskell
env1 <- extvars (tybound (q++q')) env TSchema l <$> kchkQBinds env1 (q++q') <*> kexp KType env1 t where ambig = qualbound q \\ closeDepVarsQ (tyfree t) q kchkQBinds env [] = return [] kchkQBinds env (Quant v us : q) = do us <- kchkBounds env us q <- kchkQBinds env q return $ Quant v us : q kchkBounds env [] = return []
haskell
module Main where import Tennis main :: IO () main = do print newGame
haskell
wv <- input WK2.webViewLoadUri wv url getInitialStateT GoForward -> do wv <- input #goForward wv getInitialStateT
haskell
transparent, yellow1, yellow2, green1, green2, taffyBlue :: (Double, Double, Double, Double) transparent = (0.0, 0.0, 0.0, 0.0) yellow1 = (0.9453125, 0.63671875, 0.2109375, 1.0) yellow2 = (0.9921875, 0.796875, 0.32421875, 1.0) green1 = (0, 1, 0, 1) green2 = (1, 0, 1, 0.5) taffyBlue = (0.129, 0.588, 0.953, 1)
haskell
, price :: !Price } | Purchase { price :: Price } | UpdatePrice { price :: Price } | GetPrice { callback :: Address } | GetHeldToken { callback :: Address } | GetWallet { callback :: Address } | GetWantedToken { callback :: Address } -- | Parse a natural number argument, given its field name parseNatural :: String -> Opt.Parser Natural parseNatural name = Opt.option Opt.auto $
haskell
IR1.BindingDecl b -> Just (B b) IR1.TypeAnnDecl ta -> Just (TA ta) _ -> Nothing in checkConflicts path relevantDecls declName :: BindingOrTypeAnn -> Id declName = \case B (IR1.Binding _ name _) -> name TA (IR1.TypeAnn _ name _) -> name checkConflicts :: FilePath -> [BindingOrTypeAnn] -> ValidationResult [SAError] checkConflicts path decls = foldMap g $ foldr' f Map.empty decls where f decl = case decl of
haskell
withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QUndoCommand_mergeWith_h cobj_x0 cobj_x1 instance Qredo (QUndoCommand ()) (()) where redo x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QUndoCommand_redo_h cobj_x0
haskell
-- -- 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 KindSignatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeInType #-}
haskell
import Data.UUID.V4 (nextRandom) import Data.Either (either) import GHC.Generics (Generic) import qualified Language as L import Expression.Expr expressionScenario :: String -> L.Flow (Maybe Val) expressionScenario fileName = do jsonRequest <- L.runIO $ readFile fileName let eRes = do precExpr <- eitherDecode $ BCL.pack jsonRequest eval precExpr case eRes of
haskell
resultInfectionAttacks `shouldBe` expectedInfectionAttacks describe "dealDamage" $ do context "given attacking group deals 79 damage to defending group of 10units * 10hp" $ do it "defending group loses 7 units " $ do let attackingGroup = Group 0 Infection 1 10 [] [] "fire" 79 1 let defGroup = Group 0 ImmuneSystem 10 10 [] [] "fire" 9 1 let result = dealDamage attackingGroup defGroup amountOfUnits result `shouldBe` 3 context "given attacking group deals 80 damage to defending group of 10units * 10hp" $ do it "defending group loses 8 units" $ do let attackingGroup = Group 0 Infection 1 10 [] [] "fire" 80 1 let defGroup = Group 0 ImmuneSystem 10 10 [] [] "fire" 9 1 let result = dealDamage attackingGroup defGroup
haskell
import Data.ExponentialFamily.Density import Data.ExponentialFamily.ThetaEta import Numeric.SpecFunctions (choose) -- | Binomial distribution, where you conduct n trials with probability p. data Binomial = Binomial { _n :: Int , _p :: Double } deriving (Show, Eq) instance ProbDensity Binomial where
haskell
<gh_stars>0 import System.IO main = do withFile "girlfriend.txt" ReadMode (\handle -> do contents <- hGetContents handle putStr contents)
haskell
-- | Find the number of elements of a list. module P01_10_Lists.P04 where import Test.HUnit.Base main04 :: IO ()
haskell
(evaluate (sexpr2expr expression) >>= liftIO . print) (liftIO . print) Left x -> liftIO . print $ x ) >> repl
haskell
asyncClass :: Parser Types.AsyncClass asyncClass = try (string "stopped" >> pure Types.Stopped) <|> try (string "thread-group-added" >> pure Types.ThreadGroupAdded) <|> try (string "thread-group-started" >> pure Types.ThreadGroupStarted) <|> try (string "thread-created" >> pure Types.ThreadCreated) <|> try (string "running" >> pure Types.AsyncClassRunning) <|> try (string "thread-group-exited" >> pure Types.ThreadGroupExited) <|> try (string "thread-exited" >> pure Types.ThreadExited) <|> try (string "breakpoint-modified" >> pure Types.BreakpointModified) <|> try (string "library-loaded" >> pure Types.LibraryLoaded) streamRecord :: Parser Types.StreamRecord streamRecord
haskell
newtype UniqT m a = UniqT { runUniqT :: StateT (Map.Map Text Int) m a} deriving (Functor, Applicative, Monad, MonadTrans) class Monad m => MonadUnique m where unique :: Text -> m Text instance Monad m => MonadUnique (UniqT m) where unique t = do st <- UniqT get case Map.lookup t st of Just cnt -> do UniqT (put $ Map.insert t (cnt + 1) st)
haskell
) import Bank.Probability ( Probability , probability , getProb )
haskell
= FoundWorkMatch { foundWorkMatchInx :: {-# UNPACK #-} !CHRConstraintInx , foundWorkMatchChr :: !(StoredCHR c g bp p) , foundWorkMatchWorkInx :: ![WorkInx] , foundWorkMatchSlvMatch :: !(Maybe (FoundSlvMatch c g bp p s)) }
haskell
resolve :: Integer resolve = toInteger $ f 20 20 f :: Integral t => t -> t -> t f x y = fact (x + y) `div` (fact x * fact y)
haskell
smallestSpread2 ((x0 : x1 : x2 : []) : (y0 : y1 : y2 : []) : ys) = if compareSpread (readInt x1) (readInt x2) (readInt y1) (readInt y2) then smallestSpread ((x0 : x1 : x2 : []) : ys) else smallestSpread ((y0 : y1 : y2 : []) : ys) smallestSpread2 [x] = head x
haskell
module Data.Functor.Product (module Exports) where import "base" Data.Functor.Product as Exports
haskell
hflip arr = let (low, high) = bounds arr mapping (y, x) = (y, snd high - x) in ixmap (low, high) mapping arr -- | vertical flip of a 2D array
haskell
pattern Var1 :: Raw a (S (S n)) pattern Var1 = Var V1 pattern Var2 :: Raw a (S (S (S n))) pattern Var2 = Var V2 ------------------------------------------------------------------------------- -- Value ------------------------------------------------------------------------------- -- | Applications, Forcing terms, 'Let' and 'Error' are not values. -- -- Unsaturated applications of builtins are also values. --
haskell
| child `elem` vertices = acc ++ [parent] | otherwise = acc children :: [Int] -> [Int] children vertices = foldr go [] e where go (parent, child) acc | parent `elem` vertices = acc ++ [child] | otherwise = acc main :: IO () main = print
haskell
import qualified Language.C.Types as C import qualified Data.Map as Map data Context contextCntx :: C.Context contextCntx = mempty { C.ctxTypesTable = Map.fromList [ (C.TypeName "Context", [t| Context |]) ]
haskell
import GHC.Generics (Generic) import Linear (V2, V3) data AnimationData scalar fs = AnimationData { animationFramerate :: Double , textureRGBData :: Maybe RGBGrid , meshSequence :: MeshSequence scalar fs } deriving (Generic, Show, Store)
haskell
mconcat (map (formatOutcome (indent <> " ")) coDependents) formatResult :: Text -> CheckResult a -> Text formatResult _ (Success _) = ": " <> color Red "OK" <> "\n" formatResult indent Skipped = ": " <> color Yellow "Skipped" <> "\n" formatResult indent (Failure msg) = ": " <> color Red "Failure" <> "\n" <> indent <> " " <> msg <> "\n" formatResult indent (Error err) = ": " <> color Red "ERROR" <> "\n" <> indent <> " " <> err <> "\n"
haskell
$ "MATCH x=shortestPath((p:Person)-[*]-(j:Job))" `shouldParseMatchQuery` Match [ MatchFunctionWrappedPattern (Just "x") (Function "shortestPath" [ Node personLabelledNode M.empty , ConnectorDirection NoDirection , Relationship EmptyPatternComponentType (Just AnyHops) M.empty , ConnectorDirection NoDirection , Node (LabelledPatternComponentType
haskell
. fmap (compositeValue *>) getNonNullable {-# INLINE getRowNullValue #-} getRowNullValue = CompositeValue . fmap (compositeValue *>) getNullable {-# INLINE runRowDecoder #-} runRowDecoder = unCompositeValue instance (PrimField a1, PrimField a2, PrimField a3) => PrimField (a1, a2, a3) where
haskell
module TestUtils where import Test.HUnit testSuite :: [Assertion] -> Test testSuite = TestList . map TestCase
haskell
{- look for https://gist.github.com/Icelandjack/aecf49b75afcfcee9ead29d27cc234d5 and https://gist.github.com/Icelandjack/02069708bc75f4284ac625cd0e2ec81f/6cb8f671d5bbc8592557e5c7a5a5c224a9663973 and https://functional.works-hub.com/learn/yo-yoneda-a2965 -}
haskell
import Data.List (intersperse) import Data.Monoid (mconcat, mappend, mempty) import Data.Text (Text) import qualified Data.Text as T import Text.Blaze.Html import Text.Blaze.Html5 (a)
haskell
import Prelude (Either (Left, Right), fail, fromIntegral, pure) oneOf :: List (Parser a) -> Parser a oneOf = asum parse :: Parser a -> Text -> Result Text a parse parser input =
haskell
important $ backgroundColor "#1b2238" cl W3DropdownContent ? do important $ maxHeightPx 500 overflow auto cl ServiceName ? do fontSizePct 120 important $ color "#bcbcbc" paddingTopPx 12
haskell
-- $usage:interface -- We call a record type whose fields are methods as an interface. -- -- In the following example, @UserRepo@ is an interface. -- -- Dependency to an interface @F@ is represented as type constraint @Has1 F env@, -- methods of the interface can be invoked inside @'runIF'@. -- -- @ -- data UserRepo env = UserRepo { -- _createUser :: UserName -> RIO env UserId, -- _setPassword :: UserId -> Password -> RIO env () -- } -- makeLenses ''UserRepo
haskell
module Data.Functor2 where import Control.Category import Data.Functor.Contravariant (Op (..)) import Prelude hiding (id, (.), Functor (..)) type Hask = (->) type (:<-) = Op
haskell
) where import Foreign.Ptr ( Ptr ) import Graphics.Rendering.OpenGL.GL.BasicTypes ( GLenum ) import Graphics.Rendering.OpenGL.GL.DataType ( DataType, marshalDataType ) import Graphics.Rendering.OpenGL.GL.PixelFormat ( PixelFormat, marshalPixelFormat )
haskell
module State.GetACodingJobWithOneWierdTrick.FizzbuzzDifferentlySpec where import Test.Hspec import State.GetACodingJobWithOneWierdTrick.FizzbuzzDifferently spec :: Spec spec = do describe "Test fizzbuzzFromTo" $ do it "fizzbuzzFromTo 1 15" $ do fizzbuzzFromTo 1 15 `shouldBe` ["1", "2", "Buzz", "4", "Fizz", "Buzz", "7", "8", "Buzz", "Fizz", "11", "Buzz", "13", "14", "FizzBuzz"]
haskell
bigStack0 s = program & runReader n & execState s & run bigStack1 :: Int -> Int bigStack1 s = program & runReader n & runIdentity & execState s & run bigStack5 :: Int -> Int bigStack5 s =
haskell
allocate, label ) where import Rosterium.Types import Rosterium.Setup import Text.Render
haskell
showInSum :: Expr -> String -- If an expression consists of an addition with NO coefficient and no power then it is included in the original set of parentheses defined by 'show (Add x y)' -- If the coeff of the second term is negative then a minus sign is shown as the connector showInSum (Atom 1 (Add x y@(Atom c _ _)) 1) | c < 0 = showInSum x ++ " - " ++ showInSum (Expr.Add.negate y) -- Since we are showing a "-" sign we negate the second argument before we show it | otherwise = showInSum x ++ " + " ++ showInSum y
haskell
where top = head $ drop 1 $ lines line bottom = last $ lines line right = map last $ drop 1 $lines line left = map head $ drop 1 $lines line makeTileId line = readToInt $ fromJust $ matchDigits $ head $ lines line isCornerTile :: [[String]] -> [String] -> Bool isCornerTile tilelist tile = (length . filter notMatching) tile == 2 where
haskell
module Main where import Prelude import qualified Strelka.Demo.Route as A import qualified Strelka.Demo.Resource as B import qualified Strelka.Demo.Effect as C import qualified Strelka.WAI as D main = do resource <- B.new D.strelkaServer 3000 (fmap Right . flip C.run resource) A.top