Last active
July 30, 2021 02:29
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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