Skip to content

Instantly share code, notes, and snippets.

@beastaugh
Created July 15, 2010 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save beastaugh/476778 to your computer and use it in GitHub Desktop.
Save beastaugh/476778 to your computer and use it in GitHub Desktop.
Partition a list into sublists of length n in various languages.
-- | The 'partition' function splits a list into sublists of length n.
partition :: Int -> [a] -> [[a]]
partition n = unfoldr step
where
step :: [a] -> Maybe ([a], [a])
step [] = Nothing
step xs = Just (take n xs, drop n xs)
// Partition a list into sublists of length n.
function partition(n, list) {
return list.reduce(function(acc, item) {
var current = acc[acc.length - 1];
if (current.length === n) {
current = [];
acc.push(current);
}
current.push(item);
return acc;
}, [[]]);
}
def partition(n, list):
"""Partition a list into sublists of length n."""
def step(acc, item):
current = acc[-1]
if len(current) == n:
current = []
acc.append(current)
current.append(item)
return acc
return reduce(step, list, [[]])
# Partition a list into sublists of length n.
def partition(n, list)
list.inject([[]]) {|acc, item|
current = acc.last
if current.length == n
current = []
acc << current
end
current << item
acc
}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment