-
-
Save jcoglan/485958 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 xs = unfoldr step xs | |
where step :: [a] -> Maybe ([a], [a]) | |
step [] = Nothing | |
step ys = Just (take n ys, drop n ys) |
This file contains hidden or 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
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); | |
}; |
This file contains hidden or 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 hidden or 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