Created
July 15, 2010 10:28
-
-
Save beastaugh/476778 to your computer and use it in GitHub Desktop.
Partition a list into sublists of length n in various languages.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- | 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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}, [[]]); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, [[]]) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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