GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing raganwald.com — Anamorphisms in JavaScript Unfolded, © 2011 Regulla, Some rights reserved preamble: unfolds and foldsAnamorphisms are functions that map from some object to a more complex structure containing the type of the object. For example, mapping from an integer to a list of integers. Here’s an anamorphism: An integer is our object, and the array containing integers is our “structure containing integers.” Maps from integers to arrays of integers are anamorphisms. “Anamorphism” is a very long word, and using it implies that we are going to be strict about following category theory. So let’s use a simpler word that has some poetic value: Unfold. Anamorphisms “unfold” values into more complex structures containing those values.
So we’ll use the word “unfold” from now on. Unfolds (or anamorphisms) are the dual—a fancy word for complement—of Catamorphisms, functions that map from some complex structure containing values down to values. Here’s a catamorphism: “Catamorphism” is another long word that implies that we are going to be strict about following category theory. So let’s call these things folds instead. We can think of folding and unfolding with generatorsUnfolding a number into a list is questionable practice. It takes up a lot of space, and we just want to iterate over it, as we did above with Remember our Folding and unfolding work very well with iterators. generalizing foldsWe know that there is a very handy way to fold arrays, we can use the The two problems we have with Here we create a A variation uses the first element of the iterable as the seed, then iterates over the remainder. This is adequate for many purposes, including For historical reasons, generalizing unfoldsOur What will this function look like? The opposite of the function we used to fold, in that it will take a value as its argument, and return the next value, an element to yield, and whether it is done. Naturally, we’ll use destructuring to extract multiple return values: For a moment, let’s close our eyes very tightly, plug our ears with our fingers, and murmur “la-la-la-la-la” at the thought of performance costs or implementation limits. Ready? Ok: If we didn’t have a looping construct like It works just the same up until JavaScript’s stack overflows.
Although it may be impractical for working at scale, what is interesting about the recursive unfold is that it encodes very directly how to do an unfold using linear recursion: Given a structure, turn it into part of the result and a structure representing the rest of the work to do. In the case of unfolding, we take a structure, and return an element and a structure representing the part we haven’t unfolded yet. We then yield the element and the result of unfolding the rest of the structure. Divide-and-conquer algorithms all have this structure: Break the problem into parts, apply the algorithm to each part, then glue the results back together. Recursive divide-and-conquer applies the exact same algorithm at finer and finer scale until a simple case is reached. Linear recursion is a special case of divide-and-conquer, where we break the simple case off, solve it, and recursively apply our algorithm to the remainder of the input. traversing lists, trees and forestsA traversal, or path, is a function that takes a structure and returns its elements as an iterator. JavaScript gives us built-in traversals for returning the values in arrays, we just iterate over them. But sometimes we want to iterate in another order. For that, we need a traversal. One handy use for unfolds is to use them to express traversals. We can do that with an array. Here’s one that uses our This is simple, but it makes successive copies of the array, and in JavaScript, this is expensive. It would be easier if we used the original array, but managed a cursor to keep track of our position in the array. We can easily write this with a Consider this binary tree: Image © Sam Gavis-Hughson, Coding Interview Question: Balanced Binary Tree This tree can be represented as a nested POJO: Let’s write a traversal for it: Note that the form of this traversal is almost identical to the form of our recursive linear unfold. The big difference is that we start with one element, but the “remainder” of our work is multiple elements. We can unify them. A tree is a divergent graph with a single root node. If we have a collection of root nodes, it’s called a forest. The second-simplest possible forest is a collection with just root, and that’s just like a tree. So if we write a traversal for forests, we also get one for trees. We’ll give this a more descriptive name: This looks more familiar! We can express this as a linear recursion unfold: All this work brings us to this: Just as we can express forward and backwards traverses through a list, we can express different kinds of traversals through more complex structures, like trees or forests. Here is a breadth-first traversal of a forest: Notice how it looks almost exactly identical to the depth-first expression. This tells us that we have exploited the symmetry between the various paths we can take through a forest. A right-to-left breadth-first search is likewise easy to code: Writing traversals illustrates that not only can we can separate the way to iterate over a particular data structure from the things we do with its elements, but we can decompose the algorithm of traversing or unfolding such that we hide away questions like whether we are looping or recursing and focus on the traverse or unfold’s pertinent logic. unfolds, wrapped upWhen working with data structures, we often want to provide certain common operations on their elements. For example, questions like “What is the set of unique elements of this collection?” or “What is the sum of the numbers in this collection?” If we write a traversal for the collection, we turn it into an iterator, and we can write a single generic And it works with forests as easily as it works with lists: Writing traversals separates the concern of how to iterate over a data structure from the concern of what to do with the elements of the data structure. You often hear the advice to write code in small functions, to avoid putting too many lines in one method. Obviously, we can break big methods up by extracting “helper” methods, and that will satisfy Building blocks like have your sayHave an observation? Spot an error? You can open an issue, discuss this on reddit, or even edit this post yourself! |
| You are visitor 01402809 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |