Urgent.News

What's breaking now, across thousands of outlets.

Tech

Understanding Zippers

When working with tree-structured data, we often need to navigate to a specific node and modify it. In imperative languages, this is usually straightforward thanks to mutable state and parent pointers. In functional languages, however, immutability makes this pattern less obvious. In this post, we’ll explore how to navigate and modify tree structures efficiently in functional languages using a…

When working with tree-structured data, navigating to a specific node and modifying it can be straightforward in imperative languages due to mutable state and parent pointers. However, in functional languages, immutability makes this pattern less obvious. Zippers provide a technique to efficiently navigate and modify tree structures in functional languages.

A simple JSON query language allows accessing and modifying values in a JSON object with four operations: set path = value, get path, query | query, and at path { query }. In an imperative setting, the JSON can be represented as a tree with parent pointers. In Haskell, a functional language, parent pointers are generally avoided due to maintenance difficulties under immutability.

Consider the following JSON object: { a :{ b :{ x :1, y :2 } } }. Two queries, set .a.b.x = 42 | set .a.b.y = 43, can be implemented differently. The first approach involves accessing the target nodes and modifying them individually, requiring O(depth(node)) new nodes per modification. The second approach utilizes zippers, a technique for efficiently navigating and modifying persistent data structures like trees.

Zippers allow going to a parent node or specific child node without always returning to the root. The at query can be implemented using zippers, creating a focus on a specific node in the tree and executing queries relative to that node. This method is more efficient, particularly when modifications are close to each other, as it avoids redundant modifications.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Saturday 22 August →