Elad Benda
Elad Benda

Reputation: 36656

is && enough for tail recursion?

does the .net compiler knows to produce a tail recursion fromt the followin code? (meaning it knows that no backtracking should be made, because of the && ?)

public bool DeleteLocation(Guid locationId)
{

    return ((_mLocationDal.Save(locationRes) != null) && 
             locationRes.ChildrenIds.Aggregate(true, 
                        (succeededSoFar, next) => succeededSoFar && 
                                                  DeleteLocation(next)));
}

Upvotes: 1

Views: 120

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

Even if C# compiler supported tail recursion optimization (which it does not) it wouldn't detect it in case of your program, because DeleteLocation does not call itself directly. A functor that it uses calls DeleteLocation, but that is not enough to optimize a recursive tail call.

On a side note, All provides a more compact replacement for Aggregate in your case:

public bool DeleteLocation(Guid locationId) {
        return (_mLocationDal.Save(locationRes) != null) && 
            locationRes.ChildrenIds.All(next => DeleteLocation(next));
    }

Upvotes: 2

Wiktor Zychla
Wiktor Zychla

Reputation: 48230

The C# compiler doesn't support the tail recursion at all, if by "tail" you mean calling methods with the CIL's .tail prefix which does not leave a frame on the stack.

Upvotes: 1

Matthew Strawbridge
Matthew Strawbridge

Reputation: 20600

Boolean expressions are evaluated lazily; e.g. in A && B, B is never evaluated if A is false. This is why it's safe to do things like if (thing != null && thing.DoSomething()).

Upvotes: 1

Related Questions