Swaroop, > Just started learning clojure recently - initial examples were easy to > understand, until I found this example > > fibonacci sequence using lazy-cat : > (def fibs (lazy-cat [0 1] (map + fibs (rest fibs)))) > > I am trying to understand how this works ..not sure i fully comprehend > it. > > Can anyone please explain how clojure evaluates this. > 1. so if we call (take 5 fibs) for example, what does fibs initially > refer to? > 2. how does lazy-cat exactly work over here? > > Apologize if this has already been asked earlier.
Welcome to the fantastic world of Clojure! The implementation of the fibonacci sequence that you cited above is a really neat example of recursion over data (or corecursion) and lazy eavaluation. This is possible because we are generating a lazy sequence using the macro `lazy-cat'. What `lazy-cat' actually does is that it first calls `lazy-seq' on all the forms provided to it and then calls `concat' on all of them together. So in this example, it eventually becomes something like this - (def fibs (concat (lazy-seq [0 1]) (lazy-seq (map + fibs (rest fibs))))) Now, how does this work? Let's take an example. When you do a (take 1 fibs) it doesn't need to run the `map' function as the first two elements of `fibs' is already provided in the first lazy-seq. Ditto for (take 2 fibs). Now what if you do (take 3 fibs)? We need the third fibonacci number and for that, we need to execute the map function which runs like this - (map + [0 1] [1]) Why? you say. Well this is Corecursion :) The value of fibs which is known till then is [0 1] and that's the value which is used inside the map function, and with every call of map the value is changed to the latest known value of fibs. In case of (take 5 fibs), these are the steps in which the values are calculated: [0 1] -> [0 1] [0 1] + (map + [0 1] [1]) -> [0 1 1] [0 1] + (map + [0 1 1] [1 1]) -> [0 1 1 2] [0 1] + (map + [0 1 1 2] [1 1 2]) -> [0 1 1 2 3] And so on. This is really cool, isn't it? Regards, BG -- Baishampayan Ghose <b.gh...@ocricket.com> oCricket.com
signature.asc
Description: OpenPGP digital signature