0

This code:

(first (map (fn [d] 
              (apply * (repeat d 10)))
            (range)))

yealds an integer overflow exception, while this code:

(first (map (fn [d] 
              (apply * (repeat d 10)))
            (range 0 1)))

yealds 1.

Both codes should yeald 1 but for some reason the laziness of range has a strange behaviour. It seems to get chuncks of data instead of only one at a time. Is it possible to make range behave in the desired way?

Carlos Nunes
  • 1,929
  • 2
  • 16
  • 20
  • Ok, I have just realized that my question is duplicated. But, anyway, I think it should be accepted because it is more straightforward. It is better as a reference than the other one. – Carlos Nunes Feb 24 '15 at 19:50

1 Answers1

3

range is chunked, as a performance optimization. There are a few ways to fix this including using (iterate inc 0) or unchunk (there are a few versions, this one is copied from math.combinatorics)

(defn unchunk
  [s]
  (lazy-seq
    (when (seq s)
      (cons (first s)
            (unchunk (rest s))))))
user=> (first (map (fn [d]
                     (apply * (repeat d 10)))
                   (unchunk (range)))
1
cfrick
  • 35,203
  • 6
  • 56
  • 68
noisesmith
  • 20,076
  • 2
  • 41
  • 49