From f81b48cebc6b0b6f53204699e5fb28a325e652db Mon Sep 17 00:00:00 2001 From: WhiteBlackGoose Date: Sat, 18 Jun 2022 20:11:27 +0300 Subject: [PATCH] Recursor --- HonkSharp/Functional/Recursor.cs | 34 +++++++++++++++++++++++++++++++ Tests/Functional/RecursorTests.cs | 34 +++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+) create mode 100644 HonkSharp/Functional/Recursor.cs create mode 100644 Tests/Functional/RecursorTests.cs diff --git a/HonkSharp/Functional/Recursor.cs b/HonkSharp/Functional/Recursor.cs new file mode 100644 index 0000000..ad40409 --- /dev/null +++ b/HonkSharp/Functional/Recursor.cs @@ -0,0 +1,34 @@ +using HonkSharp.Fluency; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; + +namespace HonkSharp.Functional +{ + public static class Recursors + { + public static Func prec(Func, TOut> recInfo) + { + TOut Inner(TIn arg) + { + return recInfo(arg, i => Inner(i)); + } + return Inner; + } + + public static Func mrec(Func, TOut> recInfo) + { + var dict = new Dictionary(); + TOut Inner(TIn arg) + { + if (dict.TryGetValue(arg, out var res)) + return res; + res = recInfo(arg, i => Inner(i)); + dict[arg] = res; + return res; + } + return Inner; + } + } +} \ No newline at end of file diff --git a/Tests/Functional/RecursorTests.cs b/Tests/Functional/RecursorTests.cs new file mode 100644 index 0000000..dd6eae9 --- /dev/null +++ b/Tests/Functional/RecursorTests.cs @@ -0,0 +1,34 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using FluentAssertions; +using HonkSharp.Fluency; +using HonkSharp.Functional; +using Xunit; +using static HonkSharp.Functional.Recursors; + +namespace Tests +{ + public class RecursorTests + { + [Fact] + public void Factorial() + { + Assert.Equal(120, + prec((i, fact) => i switch { + 0 => 1, + var n => n * fact(n - 1) + })(5)); + } + + [Fact] + public void Fibonacci() + { + Assert.Equal(1318412525, + mrec((i, fib) => i switch { + 0 or 1 => 1, + var n => fib(n - 1) + fib(n - 2) + })(1000)); + } + } +} \ No newline at end of file