Skip to content

Instantly share code, notes, and snippets.

@blackode
Last active March 1, 2018 17:19
Show Gist options
  • Save blackode/d60ba4b8962cef6647c1ae60760ed32c to your computer and use it in GitHub Desktop.
Save blackode/d60ba4b8962cef6647c1ae60760ed32c to your computer and use it in GitHub Desktop.
The flatten function implementation in Elixir
# Elixir V1.6
defmodule Array do
@moduledoc """
A collective data module with some helpful functions
"""
@doc """
Flattens the given list of nested lists. By default it gives out the unique list of items by removing the duplicates
inside.
To get the complete list of items with out removing the duplicates, you have to pass an atom
`:no_uniq` as second parameter. The option is `:uniq` by default.
This defintion takes the advantage of Recursive function calling to achieve flat nested array.
## Examples
iex> Array.flatten([1,2,3])
[1,2,3]
iex> Array.flatten [1,2,3,[4],5,6,7, [8],[9, [8,[9,[10]]]]]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
iex> Array.flatten([1,2,3, [4,3,2]])
[1,2,3,4]
iex> Array.flatten([1,2,3, [4,3,2]], :no_unique)
[1,2,3,4,3,2]
iex> Array.flatten([1,2,3,[4,5]])
[1,2,3,4,5]
iex> Array.flatten([])
[]
"""
def flatten(array, flag \\ :uniq) do
case flag do
:uniq ->
array
|> flat
|> uniq
:no_uniq ->
array |> flat
_ ->
array |> flat
end
end
defp flat([head | tail]) when is_list(head) do
flat(head) ++ flat(tail)
end
defp flat([head | tail]) do
[head | flat(tail)]
end
defp flat(item), do: item
@doc """
Gives unique list of elements in the given list by removing the duplicates
## Examples
iex> Array.uniq([1,2,3])
[1,2,3]
iex> Array.uniq [1,2,3,3,1,4]
[1, 2, 3, 4]
iex> Array.uniq []
[]
"""
def uniq(list) do
uniq(list, MapSet.new())
end
def uniq([item | rest], list) do
if MapSet.member?(list, item) do
uniq(rest, list)
else
[item | uniq(rest, MapSet.put(list, item))]
end
end
def uniq([], _) do
[]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment