Clojure Variable assignment

928 views Asked by At

Iam another Clojure-newbi!

How can i assign a vector containing some values to another one? I want to do:

[a b] >>> [b (+ a b)] so that afterwards b has the value of (a+b) and a that of b.

1

There are 1 answers

5
Mark Fisher On

It looks like you're trying to do a fibonacci sequence.

user=> (def fibseq (map first (iterate (fn [[a b]] [b (+ a b)]) [1 1])))
#'user/fibseq
user=> (take 10 fibseq)
(1 1 2 3 5 8 13 21 34 55)

What you've got to remember in clojure is immutability, so you don't change a and b to be the new values. So something like:

user=> (defn next-fib [[a b]]
         (let [na b
               nb (+ a b)]
           [na nb]))
user=> (next-fib [1 2])
[2 3]

would produce a function next-fib that would return the next 2 values from your input. During the function, a and b cannot be changed, they are immutable, hence assignment to new values.

Here, i'm using destructuring to immediately break the elements of the input vector into values a and b, which are then used to calculate the next element, and is the same as how the 1 liner at the top of my answer works.

Or if you're doing looping, you can recur with values that get substitute over their previous iteration, this is not changing a and b (during any iteration their values are fixed and still immutable), but redoing the entire stack with new values in their place, subtle difference. See articles on tail recursion.

user=> (loop [a 1 b 1]
         (if (< a 20)
           (recur b (+ a b))
           [a b]))
[21 34]

Here's a simple version of the Fibonacci Sequence using recur, it returns the first n numbers.

(defn fib-recur [n]
  (loop [fib [] x n a 0 b 1]
    (if (zero? x)
      fib
      (recur (conj fib b) (dec x) b (+ a b)))))

It works by starting with an empty array of numbers it's building, then recurs by decrementing the counter (x) from n to 0, each iteration changes a and b to be new values as part of the recursion, and it adds the latest number to the array fib returning that when the counter gets to zero.