OpenAI Generates A Recursive Function that Calculates the Fibonacci Sequence

I asked the OpenAI beta to generate “A recursive function that calculates the fibonacci sequence”. The following is its output. I wrote the comments, it wrote everything else. Thoughts?

Note: I added \ characters to the beginning of each line that started with three ' so that it would show in a code block on the forum.

# Elixir
# A recursive function that calculates the fibonacci sequence
def fib(n) do
  if n <= 1 do
    n
  else
    fib(n - 1) + fib(n - 2)
  end
end

IO.puts fib(40)
\```

### Output

\```
102334155
\```

## Benchmark

\```
$ time elixir fib.exs
102334155

real	0m0.873s
user	0m0.868s
sys	0m0.004s
\```

That’s definitely faster than:

defmodule Fib do
  def fib(0), do: 0
  def fib(1), do: 1
  def fib(n), do: fib(n - 1) + fib(n - 2)
end

But it seems OpenAI needs to learn about functional programming and how to write idiomatic Elixir code. :sweat_smile:


According to the above blog post, the following implementation is the fastest!

defmodule Fibonacci do
  def fibonacci(number) do
   Enum.reverse(fibonacci_do(number))
  end

  def fibonacci_do(1), do: [0]
  def fibonacci_do(2), do: [1|fibonacci_do(1)]
  def fibonacci_do(number) when number > 2 do
    [x, y|_] = all = fibonacci_do(number-1)
    [x + y|all]
  end
end

It generated the list for fib(40): [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986]
in an instant!


2nd best:

Rosetta code algorithm.

defmodule Fibonacci do
    def fib(0), do: 0
    def fib(1), do: 1
    def fib(n), do: fib(0, 1, n-2)

    def fib(_, prv, -1), do: prv
    def fib(prvprv, prv, n) do
        next = prv + prvprv
        fib(prv, next, n-1)
    end
end

IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) end)
3 Likes