16 ms·
Finger Trees: A Simple General-Purpose Data Structure (2006)
- DanWaterworth 10y agoThe problem with using lazy data structures for storing things is that deletes don't necessarily free up storage. Fingertrees are fine when you need to store a collection in order to implement some algorithm (and being persistent makes it useful if this algorithm has to backtrack), but they aren't so good for backing a collection that changes over time, like the set of currently connected sockets in a network service.
- wyager 10y agoLooking at Haskell's Data.Sequence, it looks like it's strict in its elements. So a delete does free up memory as long as the deleted object isn't being used somewhere else.
- DanWaterworth 10y agoIt needs to be spine strict for that to work, but the amortization for finger trees doesn't work without laziness
- harpocrates 10y agoThis is a fun data structure to implement in Haskell, and I've always been curious about how one would do it in C++, largely due to the fact that data FingerTree a = Empty | Single a | Deep (Digit a) (FingerTree (Node a)) (Digit a) Has polymorphic recursion in the last case. What would be the C++ approach for dealing with this sort of thing? Pass in a compile time integer to represent the level of nesting?
- paulgb 10y agoI think you'd have to use a pointer and allocate on the heap. Under the hood I think that's essentially what the compiled Haskell code would do.
- deleted 10y ago[deleted]
- hedora 10y agoWhen traversing the tree, I think you'll need at least one branch/virtual method dispatch to determine the type of the child node. Given that, you could create a templated subclass for each type in the grammar, then instantiate it with the number of children. Eg: template<N> class Node : TODO { type 'N'; int const count N; Node a[N]; } Allocating Node<2> is a single malloc. You can add static asserts to get things like Node<4> to fail at compile time, change the c style array to std::array<Node, N> to get bounds checks, and so on. At that point, you can get arbitrarily fancy with custom allocators, inlining the type to be stored in the tree, etc. [edit: Note that my solution kinda sucks, because you need to pay for a virtual method dispatch to run code that has N compiled in, and I also rolled my own reflection with instance variables, so I'm bloating each node by two words instead of one, and also breaking constant propagation in the caller code. Removing the implicit vtable or the extra instance variables is an exercise left to the reader.]
- skishore 10y agoThe polymorphic recursion allows for compile-time checking of the invariant that "the left and right wings at depth n are 2-3 trees of depth n". In C++, I think you would forgo a compile-time check of that invariant and just write code that maintains it instead.
- zerofan 10y agoI've written this several times in several ways using C++ (and I'll probably write it at least once more to make it better). In an early version I used an integer level as you came to, but it made the compiler very unhappy as it recursively tried to expand nested types at compile time (it couldn't figure out the recursive types would terminate in practice). Max template recursion of 256 if I remember correctly, even though you'd never instantiate past 45 or so on any machine in the world. In a later version, I implemented the specializations as inheritance on the abstract FingerTree base class (verbose, but it works), and I added Leafs and Nodes. Leafs are FingerTrees that hold your data, and Nodes are FingerTrees that point to other FingerTree instance. This dodges the recursive types problem. I don't know much Haskell, but I think it would be the C++ equivalent of: data FingerTree a = EmptyLeaf | SingleLeaf a | DoubleLeaf a a | TripleLeaf a a a | EmptyNode | SingleNode (FingerTree a) | DoulbeNode (FingerTree a) (FingerTree a) | TripleNode (FingerTree a) (FingerTree a) (FingerTree a) | FingerSpine (FingerTree a) (FingerTree a) (FingerTree a) Virtual methods on each specialization took the place of pattern matching. Not super elegant.
- harpocrates 10y agoGiven the number of comments about the inefficiency of finger trees: yes they usually have a high constant factor (for their otherwise reasonable asymptotic complexity) due to cache misses. However, they are immutable and persistent, which means they have efficient sharing, which in turn makes them good candidates for * use in multiple threads at once * code that needs to be proven correct (I believe the Haskell Data.Sequence implementation is a translated from Coq)
- traviswatkins 10y agoFinger trees are an example of a truly elegant functional data structure that can be used for just about everything. The problem is they don't match the memory model of real hardware so for all of their elegance and theoretical performance in reality they're too slow to be useful.
- jstimpfle 10y agoIs this true? How is this more true for finger trees than for red-black trees, etc?
- stuckagain 10y agoRed-black trees are pretty much terrible for performance as well. I spend most of my work days trying to eradicate std::map and std::set for performance reasons. Academics are always concerned about bounds, but practitioners are always concerned about cache misses.
- optionalparens 10y agoI generally agree with this and most of the time it's hard to justify using a red-black tree if you care about performance. You can use one if you have other concerns perhaps or performance isn't one of them. I also concur cache misses are vital and sometimes don't get enough attention since people pass hand wave them away as micro-benchmarking which isn't true often for critical code paths. I'll add that again, this is why testing on your target hardware is important. You may think you know, but often you don't. I've seen too much stupid stuff where someone wrote code that performs great on their development desktop and awful on a server or a game console because of different CPU architecture and cache design or sizes. Maybe someone can dig it up, but I've seen some of the sub-variants of red-black trees have dramatically better performance than I thought possible (or worse, ex: left-leaning), and the results can vary across runtimes. In addition to cache misses, there can be some other considerations for wanting to use a red-black tree like concurrent or parallel programming. In these cases, some of the cousin data structures like AVL trees can swing you for or against a red-black tree or other backing structure. I had this come up recently when selecting an interval tree that needed to be accessed between threads for instance. Selecting a data structure is harder than most people make it out to be. There's just a lot of considerations at work, so you need to balance use-cases, performance (against those cases and raw), access patterns, allocations, and so on to come to a decision. Sometimes if you add up the total cost of doing something like replacing a red-black tree with other methods that are more cache friendly or have some other characteristic that is better, the overall performance cost can end up being worse in aggregate. So the answer is the same as always, "it depends" and the follow-up, "try it." Parent is definitely right that academic and practical concerns of those of us in the trenches being different. That's why arguing with pure textbook evidence is stupid and you should challenge anyone who does it. Textbooks are a starting point for making and justifying a conclusion, not a shortcut.
- rohmbus 10y agoCould someone give an example where this data structure would be useful?
- willtim 10y agoYou can create a persistent ordered container that has both prepend and append in amortised constant time; and concatenate in log time.
- geocar 10y agoCaching isn't great though. Pagetables are a trie, so it's max log log log time to prepend, append, or concatenate, and usually constant small for two of them (but admittedly: you usually have to pick if you don't know how many arrays you want).
- greydius 10y agoThey can be used to implement an immutable deque.
- ianleeclark 10y agoThey're used in a distributed hash table implementation called chord (https://en.wikipedia.org/wiki/Chord_(peer-to-peer) https://en.wikipedia.org/wiki/Chord_(peer-to-peer)
- markc 10y agoThere are several use-case examples in the Readme for this Clojure finger tree implementation: https://github.com/clojure/data.finger-tree https://github.com/clojure/data.finger-tree
- KingMob 10y agoJust want to add that the data structure behind all of Clojure's default data types are finger trees.
- KingMob 10y agoThey're excellent general purpose structures for data sharing of immutable data (e.g., a slightly-changed copy shares much of the same data as the original). Clojure uses them extensively, since immutable data has the nice property of being thread-safe by default.
- magaman69 10y agointeresting...how can this be implemented in a db table queriable with sql?
- sctb 10y agoThis account has been posting a lot of unsubstantive, off-topic comments. Please stop and read the guidelines: https://news.ycombinator.com/newswelcome.html https://news.ycombinator.com/newswelcome.html https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html
- magaman69 10y agoor is this more applicable to a object store db?
- raphlinus 10y agoI looked at finger trees as a possible basis for the string representation in xi-editor, but ended up going with a simpler b-tree based approach. The better asymptotic bounds for doing manipulations at the ends are appealing in theory, but I never saw an actual problem with the O(log n) cost in practice, and it is possible to optimize the common append-only case a lot (I have a "builder" API but the current implementation is not as heavily optimized as it might be). I _believe_ that the polymorphic recursive type, easily expressible in Haskell, cannot be expressed in Rust. You'd fake it by just using trees and having the shape as an invariant maintained by the library (just as the min and max child count constraint is maintained in a B-tree). I personally think that's fine, Rust wouldn't be a better language if its type system was made even more rich, but it's interesting to have examples so you know where the edges are. (there's also the possibility someone will find a way to encode it anyway)
- keith_analog 10y agoA few years ago, our research group published a data structure, called Chunked Sequence, that is similar to the Finger Tree. In short, Chunked Sequence features the same asymptotic profile as does Finger Tree (neglecting persistence) and, in addition, offers strong guarantees with respect to constant factors. Very roughly speaking, Chunked Sequence is to Finger Tree what b-tree is to red-black tree. We've implemented Chunked Sequences as a package of C++ header files and provided source code on github. To the client, Chunked Sequence looks like STL deque, but with additional methods to allow split at a specified position and concatenate, both in logarithmic time. The operations which push and pop on the ends of the Chunked Sequence are approximately as fast as those of STL deque, and in certain use patterns much faster. http://deepsea.inria.fr/chunkedseq/ http://deepsea.inria.fr/chunkedseq/
- osivertsson 10y agoCool. But please provide clear licensing information (preferably a permissive free software license). Right now I can't find anything at all about what terms you are releasing this source code under. Therefore most people will be unable to use it, which is a shame.
- keith_analog 10y agoThanks for the comment! We are using the MIT license. I've updated the source code in the git repository accordingly.
- davexunit 10y agoWhich MIT license?
- keith_analog 10y agoThanks again! We're using the Expat license.
- pmarreck 10y ago