Skip to content

Instantly share code, notes, and snippets.

@edubkendo
Created January 7, 2015 23:29
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 edubkendo/b2daf1fc23ca3752cd17 to your computer and use it in GitHub Desktop.
Save edubkendo/b2daf1fc23ca3752cd17 to your computer and use it in GitHub Desktop.
defmodule Recursive do
def naive_fac(0), do: 1
def naive_fac(n) when n > 0, do: n * naive_fac(n - 1)
def tail_fac(n), do: _tail_fac(n,1)
defp _tail_fac(0, acc), do: acc
defp _tail_fac(n, acc), do: _tail_fac(n - 1, n*acc)
def naive_len([]), do: 0
def naive_len([_|t]), do: 1 + naive_len(t)
def tail_len(arr), do: _tail_len(arr, 0)
defp _tail_len([], acc), do: acc
defp _tail_len([_|t], acc), do: _tail_len(t, acc + 1)
def duplicate(0, _), do: []
def duplicate(n, term) when n > 0 do
[term|duplicate(n - 1, term)]
end
def tail_duplicate(n, term), do: _tail_duplicate(n, term, [])
defp _tail_duplicate(0, _, list), do: list
defp _tail_duplicate(n, term, list) do
_tail_duplicate(n-1, term, [term|list])
end
def reverse([]), do: []
def reverse([h|t]), do: reverse(t) ++ [h]
def tail_reverse(l), do: _tail_reverse(l, [])
defp _tail_reverse([], acc), do: acc
defp _tail_reverse([h|t], acc), do: _tail_reverse(t, [h|acc])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment