0

I'm playing with Clojure's lazy sequences and I have interesting observation. When I execute following code:

(first (filter (fn [x] (do (println x) (= x 2))) (range 1000)))

I got output:

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
=> 2

So, it seems that pred was called against first 32 elements of seq. Two questions occurs: why 32, and why pred was executed at all after second element?

Cœur
  • 37,241
  • 25
  • 195
  • 267
gaczm
  • 75
  • 5
  • Also see the blog post http://blog.fogus.me/2010/01/22/de-chunkifying-sequences-in-clojure/ – Charles Duffy Jan 11 '18 at 21:11
  • ...this is also duplicative of [map not quite lazy?](https://stackoverflow.com/questions/39957310/map-not-quite-lazy) – Charles Duffy Jan 11 '18 at 21:12
  • Yes, that answers my question, thank you. Anyway, thats a pity that such behavior is a default... – gaczm Jan 11 '18 at 21:23
  • Performing well by default is important, and in most cases, chunking is a substantial net gain. It *wasn't* a default in Clojure 1.0, and when chunking was introduced in 1.1, it was widely considered a win by people actually using the language at the time. – Charles Duffy Jan 11 '18 at 21:26
  • ...keep in mind that one of the goals of writing good software in a functional language is that side effects should be contained and explicit -- so if you have a sequence that actually changes something in the outside world as it's realized, that's typically an indication of bad design. (By contrast, if you're running really expensive operations where chunking costs more than it saves, that's a different kind of corner case -- see links above). – Charles Duffy Jan 11 '18 at 21:32
  • Being intuitive is important too ;) – gaczm Jan 11 '18 at 21:35
  • And yes, in my case I have expensive operation (http call) so I have to get rid of chunking – gaczm Jan 11 '18 at 21:37
  • In the last seven years writing clojure full time, i think i've needed to de-chunk to avoid side effects only once or twice, so it does come up from time to time. – Arthur Ulfeldt Jan 12 '18 at 19:30

0 Answers0