Created
June 25, 2014 07:23
-
-
Save mwotton/15e49f60677d8b55df1a to your computer and use it in GitHub Desktop.
This file contains 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
module Net.LambdaSpider.RollingSum (RollingSum, new, current, add) where | |
import Data.Foldable (fold) | |
import Data.Monoid | |
import Data.Sequence | |
import Prelude hiding (length) | |
data RollingSum a b = RollingSum Int (Seq a) (a -> Int -> b) | |
instance Show a => Show (RollingSum a b) where | |
show (RollingSum c s n) = show ("rollingsum", c, s) | |
new :: Monoid a => Int -> (a -> Int -> b) -> RollingSum a b | |
new capacity divider | |
| capacity < 1 = error "oh get stuffed" | |
| otherwise = RollingSum capacity empty divider | |
current :: Monoid a => RollingSum a b -> b | |
current (RollingSum _ queue divider) = divider (fold queue) (length queue) | |
add :: RollingSum a b -> a -> RollingSum a b | |
add (RollingSum capacity queue f) el | |
| length queue < capacity = RollingSum capacity (el <| queue) f | |
| otherwise = case viewr queue of | |
EmptyR -> error "this can never happen" | |
(stripped :> _) -> RollingSum capacity (el <| stripped) f | |
instance Monoid Int where | |
mempty=0 | |
mappend=(+) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment