3 ms·
> Apply functional programming idioms and use immutable data structures if you can. How would you implement efficient and flexible graph algorithms using these
by amelius 10y ago
> Apply functional programming idioms and use immutable data structures if you can.
How would you implement efficient and flexible graph algorithms using these techniques? E.g., considering that edges need to be traversed quickly, updated quickly, etc., and graphs are arbitrarily complicated (not just trees or DAGs).
- winstonewert 10y agoCurious: what kind of graph structures do you typically find yourself writing? Maybe I'm just doing different stuff, but I find myself with tree or DAGs in almost all cases.
- wyager 10y agoIndirect the graph connections. This is almost always a better design anyway. Instead of storing pointers from one graph node to another, give each node an identifier and store a map from identifiers to nodes. Each node then has a set (or other collection) of identifiers it's connected to. You can use either a mutable or immutable map for this construction.
- the8472 10y agoThat's basically the "don't keep references into a Vec, keep indices" advise. I don't really like that because references explicitly encode the dependency in the type system. When you start juggling indices you're basically implementing poor man's malloc. You need to make sure you don't lose track of any of them. I think owned objects should have lifetimes and a "points to non-moving memory" property. E.g. a vec can be moved and must outlive all the objects that take references from it. That way it would be possible to keep an owned object and refs to it in the same struct and pass the whole bundle around.
- wyager 10y ago> You need to make sure you don't lose track of any of them. This is a fair point, but note that in any memory management scheme except garbage collected, you run the risk of having a dangling reference if you use direct pointers to other nodes. At least with node identifiers, you can safely check that the other node still exists, in any memory management scheme.
- civility 10y agoStore your graph as an adjacency matrix, using either a 2D array of edges (if your problem is small enough), or as a sparse matrix (hash table or similar).
- nbouscal 10y agoThere's a decent amount of research into functional graph algorithms. The right approach depends on the application, but two interesting ones are inductive graphs[1] and zippers[2]. I also agree with other commenters that you should make certain you actually need your arbitrarily complicated graph, though. [1]: http://web.engr.oregonstate.edu/~erwig/papers/InductiveGraphs_JFP01.pdf http://web.engr.oregonstate.edu/~erwig/papers/InductiveGraph... [2]: https://www.cs.tufts.edu/~nr/pubs/zipcfg.pdf https://www.cs.tufts.edu/~nr/pubs/zipcfg.pdf