Skip to content

Instantly share code, notes, and snippets.

@jcoglan
Forked from beastaugh/partition.hs
Created July 22, 2010 13:25
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 jcoglan/485958 to your computer and use it in GitHub Desktop.
Save jcoglan/485958 to your computer and use it in GitHub Desktop.
-- | The 'partition' function splits a list into sublists of length n.
partition :: Int -> [a] -> [[a]]
partition n xs = unfoldr step xs
where step :: [a] -> Maybe ([a], [a])
step [] = Nothing
step ys = Just (take n ys, drop n ys)
var unfoldr = function(step, input) {
var list = [], pair;
while (pair = step(input)) {
list.push(pair[0]);
input = pair[1];
}
return list;
};
var take = function(n, xs) {
return xs.slice(0,n);
};
var drop = function(n, xs) {
return xs.slice(n);
};
// Partition a list into sublists of length n.
var partition = function(n, xs) {
var step = function(ys) {
return ys.length === 0
? null
: [take(n, ys), drop(n, ys)];
};
return unfoldr(step, xs);
};
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