Skip to content

Instantly share code, notes, and snippets.

@veverkap
Created December 5, 2017 17:06
Show Gist options
  • Save veverkap/25aae419e2436d4dc8b6b7793f345a0c to your computer and use it in GitHub Desktop.
Save veverkap/25aae419e2436d4dc8b6b7793f345a0c to your computer and use it in GitHub Desktop.
defmodule Flatten do
@moduledoc """
Documentation for Flatten.
"""
@doc """
Flattens an arbitrarily sized list
## Examples
iex> Flatten.flatten([])
[]
iex> Flatten.flatten([[1,2,[3]],4])
[1,2,3,4]
iex> Flatten.flatten([[[1],[2],[3]],4, 5, 6, 10, "apple"])
[1,2,3,4, 5, 6, 10, "apple"]
# This test shows that this implementation is the same as the built-in List.flatten/1 method
iex> large_range = Enum.reduce(0..10000, [], fn(x, acc) -> acc ++ [x] end)
...> flattened = List.flatten(large_range)
...> flattened == Flatten.flatten(large_range)
true
"""
def flatten([]), do: []
def flatten([head|tail]), do: flatten(head) ++ flatten(tail)
def flatten(item) when not is_list(item), do: [item]
end
defmodule FlattenTest do
use ExUnit.Case
doctest Flatten
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment