-1

How to achieve this using Clojure atom on the Fibonacci series.

(def x 0)
(def y 0)
(def z 1)
(defn problem [] 
    (def a (atom 0))
    (while (< @a 10 )
    (do 
      ;logic code need to write to achieve the output
      ; how can I add b,c == c,b???????.)
     (swap! a inc)))

(problem)

output should be 0 1 1 2 3 5 8 13 21 34 55

Gowtham ns
  • 40
  • 3
  • The `problem` function just seems to be incrementing the atom from 0 to 9. Instead of the comment you have, try `(println @a)`. That should help you figure out what you're doing wrong. – dorab Jan 06 '22 at 17:53
  • At the least you'll need to add an output statement, as noted. But doesn't `inc` just increment a value by `1`? That doesn't seem particularly Fibonacci-ish. – Dave Newton Jan 07 '22 at 03:59
  • 2
    You are battling against an imperative programming mindset in an immutable/functional programming language. Atoms are an advanced topic no beginner should look at when learning the language, yet it's a thing beginners grasp for familiarity. The hardest part learning Clojure is not remembering to place the parens on the left side, but immutability and FP if that's not your background. If you have gotten this assignment or approach to the solution from a source, that claims to to teach clojure, ditch this source. – cfrick Jan 07 '22 at 12:36

2 Answers2

1

As mentioned in the comments, defining and using an atom in a function is a totally non-clojure way of solving the question which makes it all the more difficult to solve. You should get familiar with the concept of immutability and higher order functions like map, filter, reduce, etc.

The code below gives you what you want.

(def fib1
  (fn [n]
    (cond
      (= n 0) 1
      (= n 1) 1
      :else (+ (fib1 (dec n)) (fib1 (- n 2))))))

since this gives you just nth Fibonacci number, you should take + map with it if you want to get what you want.

(take 10 (map fib1 (range))) => (1 1 2 3 5 8 13 21 34 55)

take a look at this beautiful solution I found on internet.

(def fib-seq-iterate (map first (iterate (fn [[n m]] [m (+ n m)]) [0 1])))

This returns a lazy sequence, which can be called with

(take 5 fib-seq-iterate) => (0 1 1 2 3)
Sanghyun Kim
  • 161
  • 1
  • 12
0
(def x 0)
(def y 0)
(def z 1)
(defn problem [] 
    (def a (atom 0))
    (while (< @a 10 )
    (do 
    (println x)
      (def x (+ y z))
      (def y z)
      (def z x)
      
     (swap! a inc))))

(problem)

Output: 0 1 2 3 5 8 13 21 34 55

Gowtham ns
  • 40
  • 3