Created
October 9, 2016 13:27
-
-
Save meditans/1f30baef0f8ddaef8d79c0b700fb2b4b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE ViewPatterns #-} | |
import Control.Monad | |
import Control.Monad.Trans.State.Strict | |
import Data.Sequence | |
import Pipes | |
import Pipes.Lift | |
import qualified Pipes.Prelude as P | |
import Prelude hiding (length) | |
mean :: Monad m => Int -> Pipe Double Double (StateT (Seq Double) m) () | |
mean n = forever $ do | |
r <- await | |
rs <- lift get | |
let rs' = r <| (if length rs < n then rs else seqInit rs) | |
lift $ put rs' | |
yield $ sum rs' / fromIntegral (length rs') | |
-- unsafe, ma per questo esempio non mi interessa | |
seqInit :: Seq a -> Seq a | |
seqInit (viewr -> rs :> r) = rs | |
exampleUsage :: IO () | |
exampleUsage = runEffect $ | |
P.readLn | |
>-> evalStateP (singleton 0) (mean 2) | |
>-> P.map show | |
>-> P.stdoutLn |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment