Would someone be willing to provide some alternate solution to the removal of duplicate values from a List (X) using Functional Programming and Elixir Constructs?
X = [1,26,3,40,5,6,6,7] # the 6 being the duplicate
The stock solution in my mind for solving this problem, would be to iterate the list (X), and add to a new list (Y) where the key doesn't already exist.
Thank you
Thanks to the Enum module, in Elixir we can trivially remove duplicates from a list. In the following example, we take a list of integers and pass it to the Enum. uniq/1 function which removes duplicates from the list without altering the original order of the remaining elements.
You can either do [head | tail]. = list (If you need the first element, head, as well) or tail = tl(list) (if you don't need the head) to get the tail of a list, then just map over that.
The length() function returns the length of the list that is passed as a parameter.
Lists are a basic data type in Elixir for holding a collection of values. Lists are immutable, meaning they cannot be modified. Any operation that changes a list returns a new list. Lists implement the Enumerable protocol, which allows the use of Enum and Stream module functions.
Enum.uniq
does what you want, for example:
iex(6)> Enum.uniq([1,26,3,40,5,6,6,7]) [1, 26, 3, 40, 5, 6, 7]
In terms of how you'd implement it you could write a recursive function like so:
defmodule Test do def uniq(list) do uniq(list, MapSet.new) end defp uniq([x | rest], found) do if MapSet.member?(found, x) do uniq(rest, found) else [x | uniq(rest, MapSet.put(found, x))] end end defp uniq([], _) do [] end end iex(3)> Test.uniq([1, 1, 2, 3, 4, 4, 1]) [1, 2, 3, 4]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With