Created
August 17, 2018 14:09
-
-
Save jdfrens/379fc389c7d60827a46461dad5f8df22 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
defmodule GenericTransform do | |
# Example: transform(list, &list_to_set/1) | |
@spec transform(map | list | term, (term -> term)) :: map | list | term | |
def transform(map, fun) when is_map(map) do | |
Enum.reduce(map, %{}, fn {k, v}, acc -> | |
acc | |
|> Map.put(k, transform(v, fun)) | |
|> fun.() | |
end) | |
end | |
def transform(list, fun) when is_list(list) do | |
list | |
|> Enum.map(&transform(&1, fun)) | |
|> fun.() | |
end | |
def transform(term, fun), do: fun.(term) | |
def list_to_set(list) when is_list(list) do | |
MapSet.new(list) | |
end | |
def list_to_set(term), do: term | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment