Skip to content

Instantly share code, notes, and snippets.

@celsojr
Last active July 30, 2021 02:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celsojr/40092146be288c3243b18accb05a20ce to your computer and use it in GitHub Desktop.
Save celsojr/40092146be288c3243b18accb05a20ce to your computer and use it in GitHub Desktop.
Factorial operation with csharp 8 in a functional style (no Tail Call, no TCO)
using System;
using static System.Console;
namespace Snippets
{
static class Program
{
static void Main()
{
static long Fact(long x)
{
static long SelfCall(long x, Func<long> f) =>
x switch
{
0 => f(),
_ => SelfCall(x - 1, () => x * f())
};
return SelfCall(x, () => 1);
}
(0..10).ForEach(i => WriteLine($"{i:d2}! = {Fact(i)}"));
}
public static void ForEach(this Range range, Action<int> action)
{
if (range.Start.IsFromEnd || range.End.IsFromEnd)
{
throw new ArgumentException(null, nameof(range));
}
int start = range.Start.Value;
int end = range.End.Value;
if (start == end)
{
throw new ArgumentException(null, nameof(range));
}
if (start < end)
{
while(start <= end)
{
action(start);
start++;
}
}
else
{
while(start >= end)
{
action(start);
start--;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment