Skip to content

Instantly share code, notes, and snippets.

@bitemyapp
Forked from erewok/Main.hs
Created November 6, 2015 03:30
Show Gist options
  • Save bitemyapp/2088377d14d7c89f0eba to your computer and use it in GitHub Desktop.
Save bitemyapp/2088377d14d7c89f0eba to your computer and use it in GitHub Desktop.
Moving Average Test: Uses Haskell Conduits
module Main where
import Control.Applicative ((<$>), (<*>))
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.State (StateT)
import Data.Conduit (($$), (=$=), (=$)
, Conduit, Sink, Source
, await, yield)
import qualified Data.Conduit.List as CL
import qualified Data.Vector.Unboxed as V
averageV :: V.Vector Int -> Int
averageV vector = (fromIntegral total) `div` (fromIntegral $ V.length vec)
where total = V.sum vec :: Int
vec = V.slice idx 10 vector
idx = V.length vector - 10
source :: Source IO Int
source = CL.sourceList [1..1000]
conduit :: V.Vector Int -> Conduit Int IO Int
conduit vector = do
val <- await
case val of
Nothing -> return ()
Just n -> do
let newvector = V.snoc vector n
if V.length newvector < 10 then conduit newvector else do
yield $ averageV newvector
conduit newvector
sink :: Sink Int IO ()
sink = do
val <- await
case val of
Nothing -> return ()
Just n -> do
liftIO $ print n
sink
main :: IO ()
main = do
let initial = V.fromList []
source $$ conduit initial =$ sink
name: conduit-test
version: 0.1.0.0
synopsis: Initial project template from stack
description: Please see README.md
homepage: https://gist.github.com/pellagic-puffbomb/9239cb57834789886f5c
license: BSD3
license-file: LICENSE
author: Erik Aker
maintainer: your.address@example.com
-- copyright:
category: Web
build-type: Simple
-- extra-source-files:
cabal-version: >=1.10
library
hs-source-dirs: src
exposed-modules: Lib
build-depends: base >= 4.7 && < 5
, conduit
, conduit-combinators
, transformers
, mtl
, resourcet
, vector
default-language: Haskell2010
executable conduit-test
hs-source-dirs: src
main-is: Main.hs
ghc-options: -threaded -rtsopts -with-rtsopts=-N
build-depends: base
, transformers
, mtl
, conduit
, conduit-combinators
, resourcet
, vector
default-language: Haskell2010
test-suite new-template-test
type: exitcode-stdio-1.0
hs-source-dirs: test
main-is: Spec.hs
build-depends: base
, conduit
, conduit-combinators
, transformers
, mtl
, resourcet
, vector
ghc-options: -threaded -rtsopts -with-rtsopts=-N
default-language: Haskell2010
source-repository head
type: git
location: https://gist.github.com/pellagic-puffbomb/9239cb57834789886f5c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment