Skip to content

Instantly share code, notes, and snippets.

@jcomellas
Created May 21, 2015 11:44
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcomellas/732cb5ddacb1ccdfa349 to your computer and use it in GitHub Desktop.
Save jcomellas/732cb5ddacb1ccdfa349 to your computer and use it in GitHub Desktop.
Elixir tuple map function
# 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