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.
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.
It looks like you're trying to do a fibonacci sequence.
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:
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.
Here's a simple version of the Fibonacci Sequence using recur, it returns the first
nnumbers.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
fibreturning that when the counter gets to zero.