Tail Call Optimization in C #

I have a very recursive function that should theoretically work well even at high costs. The problem at the time of writing. I forgot that C # doesn’t optimize tail optimization very well, if at all, so I get StackOverflowExceptionfor any fairly complex input. The main structure of the method consists of two large methods, each of which calls the other.

public object Simplify(object param) {
    if (IsSimple(param))
        return param;
    else
        return Expand(param);
}

private object Expand(object param) {
    return Simplify(ProcessExpansion(param));
}

Both IsSimpleand ProcessExpansionare relatively fixed depth of the stack - the only problem is recursion between Simplify and Expand. How could you reduce the stack depth here?

I was thinking about returning delegates who would count the result, but that seems redundant - there should be an easier way. This is my thought about the solution (it is not very polished, because I continue to think that I should do something terribly wrong here):

public object Simplify(object param) {
    object result = () => SimplifyInternal(param);
    while (result is Func<object>)
        result = ((Func<object>)result)();
    return result;
}

private object SimplifyInternal(object param) {
    if (IsSimple(param))
        return param;
    else
        return Expand(param);
}

private object Expand(object param) {
    return () => SimplifyInternal(ProcessExpansion(param));
}

So my two questions:

  • What is terribly bad with this solution?
  • Can you think of a better one?
+3
source share
1 answer

Isn't it easy

while(!IsSimple(param))
    param = ProcessExpansion(param);
return param;

?

+8
source

Source: https://habr.com/ru/post/1764084/


All Articles