0

Clojure rest and next report

 2 years ago
source link: https://www.codesd.com/item/clojure-rest-and-next-report.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Clojure rest and next report

advertisements

I was following The Joy of Clojure and I am puzzled with these 2 statements

(def very-lazy (-> (iterate #(do (print \.) (inc %)) 1) rest rest rest))

(def less-lazy (-> (iterate #(do (print \.) (inc %)) 1) next next next))

accordingly, the output was

(println (first very-lazy)) ; .4

(println (first less-lazy)) ; 4

The book continued to explain that

Grabbing the first element in a lazy seq built with rest causes a realization as expected. But the same doesn’t happen for a seq built with next because it’s already been previously realized. Using next causes a lazy seq to be one element less lazy, which might not be desired if the cost of realization is expensive.

My burning question is why there is an extra dot for 'very-lazy'? My thought was 'print' would print its argument when invoked regardless if next or rest.

Thanks


You're missing something important. Count the dots:

user> (def very-lazy (-> (iterate #(do (print \.) (inc %)) 1) rest rest rest))
..#'user/very-lazy

user> (def less-lazy (-> (iterate #(do (print \.) (inc %)) 1) next next next))
...#'user/less-lazy

It always helps to run the code for real instead of just reading a book.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK