Idiomatic lazy atoms in clojure

I play a little with atoms in clojure. I have a atompointing to lazy-seq. In another bit of code I want to update the value of the atom to the execution result nextin the sequence, but with the proviso that both swap!and reset!return the updated value, execution is never ending. I found that I could always transfer the call swap!, reset!in the do statement and then return nil, but I wonder how it is idiomatic or there is an alternative solution for this.

Doesn't end:

(def x (atom (range)))
(swap! x next)

Completes

(def x (atom (range)))
(do (swap! x next) nil)
(first @x) ;1
(do (swap! x next) nil)
(first @x) ;2
+4
source share
2 answers

Clojure, , . swap! , , repl , , . , Clojure , (set! *print-length* 10). , REPL, .

" ", :

  • swap! , - .
  • , , , (swap! x inc), .
+8

, ! :

(def x (atom (range)))
(first (swap! x next))
(first (swap! x next))

, , . , :

(def x (atom 0))
(swap! x inc)
(swap! x inc)
+1

Source: https://habr.com/ru/post/1584921/


All Articles