Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I generate the Fibonacci sequence using Clojure?

(ns src.helloworld)

(defn fibonacci[a b] (println a b (fibonacci (+ b 1) a + b)))

(fibonacci 0 1)

I'm new to Functional Programming and decided to start learning Clojure as it's very different from C#. I'd like to broaden my horizons.

Here's the error I get:

Clojure 1.2.0
java.lang.IllegalArgumentException:
Wrong number of args (4) passed to:
helloworld$fibonacci
(helloworld.clj:0) 1:1 user=>
#<Namespace src.helloworld> 1:2 src.helloworld=>

Math problems never were my strong suit and I never really made anything that manipulated numbers like this, so I would like any guidance you can give.

Please don't give me the entire solution.

Preferably I would like some good hints and maybe a skeleton of how it should look like.

like image 232
Only Bolivian Here Avatar asked Jan 20 '23 23:01

Only Bolivian Here


2 Answers

(fibonacci (+ b 1) a + b)

Here you're calling the function fibonacci with four arguments: The result of (+ b 1), the value of the variable a, the function + and the value of the variable b. Since fibonacci was defined to only take two arguments, you get the error you do.

Once you fix this, you'll get a stack overflow error without seeing any output. This is because you put the recursive call to fibonacci as the argument to println. So it will try to execute the recursive call before executing println. Since the recursion is infinite, the call to println will never happen. What you should do is first print the number and then call fibonacci recursively.

Once you do this the programm will print a lot of numbers, but the stack will still overflow eventually. This is because clojure does not optimize away tail-calls, so even when using tail recursion, infinite recursion will cause a stack overflow. To prevent this use the recur form instead of normal recursion.

In addition to these points, your program will print the wrong numbers as you implemented the Fibonacci sequence wrongly.

like image 124
sepp2k Avatar answered Jan 22 '23 12:01

sepp2k


Here is a hint about why you got the error you did. You passed the following four arguments to fibonacci:

  • (+ b 1)
  • a
  • +
  • b.

That still won't give you a working function, and here's one hint about that: what will ever cause the code to stop executing and return a value to the user?

like image 43
dfan Avatar answered Jan 22 '23 12:01

dfan