defmodule Tr do @moduledoc """ functions to sum the numbers 0..n both tail recursively and not tail recursively created: Oct 2022, gtowell """ @doc """ A tail recursive summ function. Uses a private version of the summ to introduce the extra variable needed for tail recursion. """ def sumtr(b) do sumto(b,0) end #defp creates a function that is only accessible from within a module defp sumto(0,a) do a end defp sumto(b,a) do if rem(b,100 000 000)==0 do IO.puts b end sumto(b-1, a+b) end @doc """ A non tail-recursive version of the summing function """ def sumntr(a) do psumntr(a,a) end defp psumntr(0,_b) do 0 end #note b is not really important. I is used only to # to make the IO look better defp psumntr(a,b) do if rem(a,10000000)==0 do IO.puts b-a end a+psumntr(a-1,b) end end defmodule Main do def main do limt = 100000000 IO.puts Benchmark.measure(fn -> Tr.sumtr(limt) end ) IO.puts Benchmark.measure(fn -> Tr.sumntr(limt) end ) end end defmodule Benchmark do @moduledoc """ Time a function """ def measure(function) do function |> :timer.tc |> elem(0) |> Kernel./(1_000_000) end end Main.main()