Skip to content

Instantly share code, notes, and snippets.

@coltfred
Forked from pchiusano/Window.hs
Last active August 29, 2015 14:06
Show Gist options
  • Save coltfred/e6056b4b9aef92e4af61 to your computer and use it in GitHub Desktop.
Save coltfred/e6056b4b9aef92e4af61 to your computer and use it in GitHub Desktop.
module Window where
import Data.Monoid
data Window a = Window [a] a [a] deriving (Show,Read)
null :: Window a -> Bool
null (Window [] _ []) = True
null _ = False
queue :: Monoid a => a -> Window a -> Window a
queue r (Window fs s rs) = Window fs (s `mappend` r) (r:rs)
dequeueSum :: Monoid a => Window a -> Maybe (a, Window a)
dequeueSum (Window (b:bs) a rs) = Just (mappend b a, Window bs a rs)
dequeueSum (Window [] _ []) = Nothing
dequeueSum (Window [] a rs) = Just (a, Window ss mempty []) where
ss = tail $ scanr1 mappend $ reverse rs
empty :: Monoid a => Window a
empty = Window [] mempty []
@coltfred
Copy link
Author

O(1) sliding window with just a Monoid, not a Group. Via Edward Kmett, copied from http://lpaste.net/88182 for posterity. -- Cloned so I can find it later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment