Recursion in Csharp

Hi All,

Does anyone have experience with recursion? I’m trying to implement a simple procedure in Csharp that recursively fragments a mesh.

A Tree datastructure is used because nested lists returned errors. However, when I feed a data stream back to itself, it returns :

  1. Recursive data stream found, this component depends on itself

Might anyone have advice on this? Are datatrees the way to go? Is it possible to do this in a single Csharp component? The purpose is this exercise is pure curiosity: I want to learn how to implement recursion in Csharp.

Attached is a clean file with a “hacked” version that works and the broken component…

STD - recursion - clean.gh(15.5 KB)

Thanks in advance for any pointers.

cheers,
Lenn!

I have no way to see whats in the file attached, but a tree data structure should have a way to determine if it has child nodes (i.e. is it a leaf or not). Then, if you do recursion, you test if the tree is a leaf or not. If it is, stop recursing, if it’s not, keep going further.

class Tree
{
public ICollection<Tree> Children 
{ 
  get { return _children ?? (_children = new List<Tree>()); }
}
public bool IsLeaf 
{
  get { return Children.Count == 0; }
}

public void Recurse()
{
  if (IsLeaf) return;
  foreach(Tree child in Children)
    child.Recurse();
}
}

Hallo,

Recursion is basically impossible to achieve using standard Grasshopper networks.

David Rutten

However, I took a quick glance at your script and it looks like the recursion happens between 3 c# script components. So theoretically, it should be possible to combine the code in these 3 components into a single c# component and perform the recursion inside it, if you catch my drift.
Let me know if you need help with this.

Cheers,
Sridevi

Hi,

Sorry for the super late reply. This is a great idea! never thought to use trees this way. In a sense, it becomes its own “counter”? Have you used this yourself?

Thanks for the idea

yes, you’re right. its a simple hack at the moment of copy-paste. I think what i will try next is to turn it into a class and then work from there. This is your drift, yes?

Yes, I use it all the time. It is an implementation of the Depth First Search for a special type of graph, the tree. http://en.wikipedia.org/wiki/Tree_traversal

Hey llennardd,

I have not gone through the code in your gh script in detail, so I am not sure if you need to make a class (maybe you do?). What I was thinking was more along the lines of just copying the code from each of the 3 c# components into a single c# component and modifying it so that the recursion happens within the c# component.

So something like, say, giving the original mesh, the number of cycles, etc. etc. as inputs into the c# component, which on completing all the cycles, gives the final mesh as output.

Cheers,
Sridevi