Created
June 24, 2019 15:54
-
-
Save jeffrade/8dfab2c44a3bc80c5adda7f5de308c9f to your computer and use it in GitHub Desktop.
Tail recursive implementaion of doubling every other number in a list.
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 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