Skip to content

Instantly share code, notes, and snippets.

@lambda-fairy
Created May 22, 2013 00:45
Show Gist options
  • Save lambda-fairy/5624430 to your computer and use it in GitHub Desktop.
Save lambda-fairy/5624430 to your computer and use it in GitHub Desktop.
Definitely not statistics
import qualified Data.Sequence as S
import Data.Foldable (toList)
movingMean :: Int -> [Double]
slices :: Int -> [a] -> [[a]]
slices k ys = case takeMaybe k xs of
Nothing -> []
Just start -> start : loop (S.fromList start) ys
where
loop _ [] = []
loop acc (x:xs) =
let acc' = seqTail acc S.|> x
in toList acc' : loop acc' xs
seqTail :: S.Seq a -> S.Seq a
seqTail xs = case S.viewl xs of
S.EmptyL -> error "seqTail: empty sequence"
_ S.:< xs' -> xs'
-- | Split the input list into chunks of size @k@. The last chunk may be
-- shorter than the other chunks, depending on the length of the input.
-- Exammples:
--
-- > chunksOf 2 [1..6] == [[1, 2], [3, 4], [5, 6]]
-- > chunksOf 3 "Hello, world!" == ["Hel", "lo,", " wo", "rld", "!"]
--
chunksOf :: Int -> [a] -> [[a]]
chunksOf k = unfoldr $ \xs -> case xs of
[] -> Nothing
_ -> Just (splitAt k xs)
takeMaybe :: Int -> [a] -> Maybe [a]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment