Clojure Zippers (2021)

111 pointsposted 3 months ago
by prydt

8 Comments

wry_discontent

3 months ago

I've used zippers a couple times.

Once for navigating a collection of deeply nested routes in a webapp, and once for navigating deeply nested xml to grab very particular data.

Both times it was pretty pleasant and nice to use.

I wouldn't reach for them in most normal situations cause they're more complicated to get right than simple looping (or `clojure.walk/prewalk`), but if you have large semi-predictable data structures, you can do cool stuff with zippers.

0_gravitas

3 months ago

I've been using Clojure for a few years now and zippers have always been a blindspot (had no idea even _when_ they would be useful), this is a remarkable tutorial!

ngruhn

3 months ago

I'm not sure if I get it. But I don't know Clojure syntax too well. Say I want to represent a slideshow state. I could do it with

    { 
      slides: List<Slide>, 
      current_index: Int
    }
Or alternatively:

    {
      left_slides: List<Slide>,
      current: Slide,
      right_slides: List<Slide>
    }
Is it fair to call the latter a Zipper?

shakadak

3 months ago

Yes, although it's usually defined as:

    {
      slides_shown: List<Slide>,
      slides_left: List<Slide>
    }
Where the head of slides_left is the current slide. Pretty much any recursive data structure can be derived into a zipper.

laszlokorte

3 months ago

Yes if List is immutable and the interface for stepping through the slides ist designed accordingly

clem

3 months ago

I've used zippers to edit parse trees. Very useful API, if a little user unfriendly.

avbanks

3 months ago

This tutorial was extremely helpful, I was having a hard time grokking the power of zippers.