1

I'm trying to write a function to check whether a string is a palindrome, and using this example, I'm trying to reverse the string using a recursive anonymous function:

static Boolean checkPalindromeAnonRec(string str)
{
    str = str.ToLower().Replace(" ", String.Empty);
    Func<string, string> revStr = null;
    revStr = delegate(string s) 
      { 
        if (s.Length > 1) 
          { return revStr(s) + s[0]; } 
        else 
        { return s; } 
      };

    return (str == revStr(str));
}

But every time I run it I get a StackOverflowException. It's not obvious to me why, any ideas?

Community
  • 1
  • 1
Jellezilla
  • 3,950
  • 1
  • 15
  • 15

1 Answers1

5

Well this is the problem:

if (s.Length > 1) 
  { return revStr(s) + s[0]; } 

Aside from the odd bracing style, that's just recursing with the original string - so it will keep going forever. I suspect you meant to use Substring somewhere so that it recursed using a shorter string...

I would actually try writing it as a simple non-anonymous (but still recursive) method to start with - so work out how you would recursively write:

static string Reverse(string input)

... then if you still want to inline that into your CheckPalindrome method, you can do so.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • How embarassing. Should have been `return revStr(s.Substring(1)) + s[0]` all along. – Jellezilla Jul 12 '13 at 19:07
  • Just tried it out. It actually performs better with a named function than with the anonymous function – Jellezilla Jul 12 '13 at 19:16
  • +1. And when you are done with fixing code make it properly anonymous recursion: [Anonymous Recursion in C#](http://blogs.msdn.com/b/wesdyer/archive/2007/02/02/anonymous-recursion-in-c.aspx) – Alexei Levenkov Jul 12 '13 at 19:17