The Wiert Corner – irregular stream of stuff

Jeroen W. Pluimers on .NET, C#, Delphi, databases, and personal interests

  • My badges

  • Twitter Updates

  • My Flickr Stream

  • Pages

  • All categories

  • Enter your email address to subscribe to this blog and receive notifications of new posts by email.

    Join 1,860 other subscribers

Not sure I like this without tail recursion

Posted by jpluimers on 2024/05/07

A while ago Andy Gocke posted this bit of C# 11 code:

[Wayback/Archive] Andy Gocke on Twitter: “Can’t believe none of that “C# is turning into F#” people have noted that this is legal code in C# 11″

with code referenced from [Wayback/Archive] Andy Gocke on Twitter: “@evntdrvn Oops, here you go”.

A day later he posted this important addition:

[Wayback/Archive] Andy Gocke on Twitter: “PSA: please don’t actually use recursion to sum an array, use a loop or LINQ. Recursion is best for recursive data structures (like trees)

In [Wayback/Archive] SharpLab you can see the syntactic C# sugar

    int Sum(Span s) => s switch
    {
        [] => 0,
        [var x, .. var xs] => x + Sum(xs)
    };

is converted into this C# code:

    private int Sum(Span s)
    {
        int length = s.Length;
        if (length != 0)
        {
            int num = s[0];
            Span s2 = s.Slice(1, length - 1);
            return num + Sum(s2);
        }
        return 0;
    }

The compiler could convert this tail recursion into an iteration. Hopefully one day it does.

–jeroen

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.