Created
May 21, 2015 11:44
-
-
Save jcomellas/732cb5ddacb1ccdfa349 to your computer and use it in GitHub Desktop.
Elixir tuple map function
This file contains 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
# Map over a tuple in normal order | |
def tuple_map1(tuple, function), do: | |
tuple_map(tuple, function, 0, []) | |
def tuple_map1(tuple, function, index, acc) when index < tuple_size(tuple) do | |
item = function.(elem(tuple, index)) | |
tuple_map1(tuple, function, index + 1, [item | acc]) | |
end | |
def tuple_map1(tuple, function, index, acc) do | |
Enum.reverse(acc) | |
end | |
# Map over a tuple in inverse order to avoid reversing the list | |
def tuple_map2(tuple, function), do: | |
tuple_map(tuple, function, tuple_size(tuple), []) | |
def tuple_map2(tuple, function, index, acc) when index > 0 do | |
item = function.(:erlang.element(index, tuple)) | |
tuple_map2(tuple, function, index - 1, [item | acc]) | |
end | |
def tuple_map2(tuple, function, index, acc) do | |
acc | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment