Skip to content

Instantly share code, notes, and snippets.

@mwotton
Created June 25, 2014 07:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwotton/15e49f60677d8b55df1a to your computer and use it in GitHub Desktop.
Save mwotton/15e49f60677d8b55df1a to your computer and use it in GitHub Desktop.
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