I’m wondering if the https://github.com/clojure/clojure/blob/59b65669860a1f33825775494809e5d500c19c63/src/clj/clojure/zip.clj#L231-L233 for clojure.zip/next
could be misleading to some, it reads:
> Moves to the next loc in the hierarchy, depth-first. When reaching the end, returns a distinguished loc detectable via end? If already at the end, stays there.
Some people might assume, without more guidance, that the end of the zipper is the last node in the zipper and that calling next
at that point will leave the zipper located at the last node.
As far I understand it (which may be not far), the Clojure zipper end state is hit when you’ve called next
after the last node in the zipper, after which:
• the zipper is no longer navigable or updatable.
• you can still call root
(or node
which at this point is equivalent to root
), next
and end?
but otherwise, I think, it is game over.
(require '[clojure.zip :as czip])
(->> [1 2 3]
czip/vector-zip
(iterate czip/next)
(take 10)
(map (juxt czip/node czip/end?)))
;; => ([[1 2 3] false]
;; [1 false]
;; [2 false]
;; [3 false]
;; [[1 2 3] true]
;; [[1 2 3] true]
;; [[1 2 3] true]
;; [[1 2 3] true]
;; [[1 2 3] true]
;; [[1 2 3] true])
The next
docstring might want to talk more about what “end” is and what reaching the end state means. Maybe something like:
> Moves to the next loc in the hierarchy, depth-first.
> When reaching the end, which is after the last node, returns a distinguished loc detectable via end?. If already at the end, stays there.
> When at end, valid calls are end?, next and root.
If the docstring is not the right place, https://clojure.org/reference/other_libraries#_zippers_functional_tree_editing_clojure_zip?
If this makes any sense, I am happy to re-raise this as a JIRA, or post it over at ask.clojure, or work on a clojure-site update. Lemme know.perfect question for ask.clojure
Thanks @ghadi, I shall post it up on ask.clojure.
and yes, I believe you are correct
pretty sure I wrestled with some kind of change around this in the past
This came up for me while digging into a change for rewrite-clj. Its comment/whitespace skipping next
and end?
treat the last node as end.
This could be an appropriate decision the original rewrite-clj authors made, need to think about it a bit - but it lead me to the clojure.zip/next
docstring and made me utter “huh!“.