Skip to content

Instantly share code, notes, and snippets.

@davenportw15
Created August 11, 2015 04:00
Show Gist options
  • Save davenportw15/a4ec816eab46239ca30a to your computer and use it in GitHub Desktop.
Save davenportw15/a4ec816eab46239ca30a to your computer and use it in GitHub Desktop.
A general method to traverse neighboring elements in lists.
-- This module demonstrates two key principles:
-- 1. A general method of traversing neighboring elements in lists
-- 2. Appropriate and understandable abstractions are always your friends
module ReferenceSurroundings where
-- | Returns sublists from xs of length `size`
-- i.e. chunkIntoSize 3 [1..5] ==
-- [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
chunkInto :: Int -> [b] -> [[b]]
chunkInto size xs
| size >= length xs = [xs]
| otherwise = take size xs : chunkInto size (tail xs)
-- | Example usage
main = do
-- Adds [1, 2, 3], [2, 3, 4] ... [8, 9, 10]
print $ map sum $ chunkInto 3 [1..10]
-- Adds chunks in [1..10] for every chunk size less than 10
mapM_ (print . sumOfChunks) [1..10]
where sumOfChunks size = map sum $ chunkInto size [1..10]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment