Last active
July 8, 2020 19:41
-
-
Save lyninx/674a04488425a69abe8c7c853ca808d4 to your computer and use it in GitHub Desktop.
elixir function for splitting lists into equal sized chunks, written using recursion
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/2` splits a list into smaller lists of a given size, using recursion! | |
# | |
# usage: | |
# list = [:one, :two, :three, :four, :five] | |
# partition(list, 2) | |
# > [[:one, :two], [:three, :four], [:five]] | |
def partition(list, partition_size) | |
when is_list(list) | |
and is_integer(partition_size) | |
and partition_size > 0 | |
do Enum.reverse(part(list, partition_size)) | |
end | |
defp part(list, p_size, acc \\ []) | |
defp part([], _, acc) do | |
acc | |
end | |
defp part(list, p_size, acc) do | |
[current | rest] = list | |
case acc do | |
[] -> part(rest, p_size, [current]) | |
[head | tail] when is_list(head) -> | |
chunk = part([current], p_size, head) | |
case chunk do | |
[h | _] when is_list(h) -> part(rest, p_size, chunk ++ tail) | |
_ -> part(rest, p_size, [chunk | tail]) | |
end | |
p when length(p) < p_size -> part(rest, p_size, p ++ [current]) | |
p -> part(rest, p_size, [[current], p]) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment