Posts

Showing posts with the label recursion

Avoid infinite recursion in destructor

7 1 As part of an exercise my university has tasked me with, I have written a small Graph implementation, following this header. class Node { private: std::string name; std::vector<Node*> children; public: Node(const std::string& name=""); virtual ~Node(); } When writing code for the destructor ~Node() , I noticed that my implementation fails when the graph contains a cycle. This is my implementation so far, which obviously doesn't work if the graph contains a cycle. Node::~Node() { for (Node* n : children) { delete n; n = NULL; } children.clear(); } I am uncertain as to how I would most elegantly write a destructor that can handle cycles in the graph? Please note that I was specifically tasked ...

Why doesn't Haskell need Trampolining?

18 5 As Scala developer learning the IO Monad, and therefore technicalities of Trampolining in general that are necessary for recursion where tail call optimization is not possible, I wonder how Haskell seems to natively avoid it. I get that Haskell is a lazy language, however I wonder if someone could elaborate a bit further. For instance, why doesn't ForeverM stackoverflow in scala? Well, I can answer for trampoline, and I can find the actual code that does that in libraries and blogs. I actually implemented a basic trampoline myself to learn. How does it happens in Haskell? Is there a way to unpack the laziness a bit, give some pointers, and maybe documentation that would help in understanding it better? sealed trait IO[A] { ..... def flatMap[B](f: A =...