Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The foreach loop only works with the yield return, and you don't have a yield return on your GetSequences() command in the GetSequences() method; whatever it returns doesn't get stored or returned. It is like you are doing this: It's like you are doing this:</p> <pre><code>static IEnumerable&lt;string&gt; GetSequences(string a) { GetSequences(a + "&gt;"); } </code></pre> <p>which of course doesn't have a return statement (it wouldn't compile, but you knew that). After toying around with this for a little while, if you want to use recursion I would recommend you don't use an enumerable, particularly because loops and recursion are meant to serve separate purposes, and the foreach with IEnumerable works best with collections that have already been enumerated. The loop suggested above, as is, just enables endless recursion, and implementing an escape of the recursion like this:</p> <pre><code> static IEnumerable&lt;string&gt; GetSequences(string a) { if(a.Length &gt; 100) yield return a; else foreach (var n in GetSequences(a + "&gt;")) yield return n; } </code></pre> <p>yields this output: <code>&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;,</code> (maybe to scale, I didn't want to count) By implementing it like this I was able to get the output you wanted:</p> <pre><code> static string GetSequences(string a, int len) { if (a.Length &lt; len) { return GetSequences(a + "&gt;", len); } else return a; } static void Main(string[] args) { for (int i = 1; i &lt; 5; i++) { Console.Write(GetSequences("&gt;", i) + ","); } Console.Read(); } </code></pre> <p>Of course, my integers are arbitrary, it will work with any length.</p> <p>EDIT: I knew there was a way to do it the way abatishchev was saying, but I couldn't figure it out. After racking my brain, here is what I got:</p> <pre><code> static IEnumerable&lt;string&gt; GetSequences(string a) { if (a.Length &lt; 100) { yield return a; foreach (var n in GetSequences(a + "&gt;")) yield return n; }else yield break; } </code></pre> <p>This has the output you want, although I still think using recursion with loops is a little funny.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload