Skip to content

Instantly share code, notes, and snippets.

@jeffrade
Created June 24, 2019 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffrade/8dfab2c44a3bc80c5adda7f5de308c9f to your computer and use it in GitHub Desktop.
Save jeffrade/8dfab2c44a3bc80c5adda7f5de308c9f to your computer and use it in GitHub Desktop.
Tail recursive implementaion of doubling every other number in a list.
defmodule ListFun do
def double_every_other([], acc), do: acc
def double_every_other([head | nil], acc) do
new_acc = [head * 2 | acc]
double_every_other([], new_acc)
end
def double_every_other([head | tail], acc) when length(tail) == 0 do
new_acc = [head * 2 | acc]
double_every_other([], new_acc)
end
def double_every_other([head | tail], acc) do
new_acc = [head * 2 | acc]
[_skip | new_tail] = tail
double_every_other(new_tail, new_acc)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment