2
votes

The code I'm trying to understand is made up of two functions:

(defn fib-step [[a b]]
  [b (+ a b)])

I'm pretty sure I've got this figured out. It uses a macro (defn) to create a named function (fib-step) which takes n number of arguments. It then destructures these arguments into two variables, a and b. It returns a vector comprised of b in the first place, and the addition of a and b together in the second place.

I'm now trying to work through this function:

(defn fib-seq []
  (map first (iterate fib-step [0 1])))

Again, it uses a macro to create a named function fib-seq. I think I understand the iterate function being seeded with the [0 1] vector but I'm confused around the map and first functions.

I understand that map needs to take a function along with a sequence, so why have they used "first"?

Why can't I just write

(take 5 (iterate fib-step [0 1]))

To get the first 5 numbers in the lazy sequence? What's the purpose of the map and first?

Sorry for such a basic question :(

1

1 Answers

2
votes

Use the REPL:

(take 5 (iterate fib-step [0 1]))
;=> ([0 1] [1 1] [1 2] [2 3] [3 5])

Is that what you wanted? No, with input of [f_n f_{n+1}] the output of fib-step is [f_{n+1} f_{n+2}]. The f_{n+1} term has been repeated. Furthermore, the output is in pairs.

What you really want is the first of each of these pairs.

How do get the first? first

How do you do that over the sequence of pairs? map