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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How embarassing. Should have been return revStr(s.Substring(1)) + s[0] all along.
Just tried it out. It actually performs better with a named function than with the anonymous function
+1. And when you are done with fixing code make it properly anonymous recursion: Anonymous Recursion in C#

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.