Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Recursor #26

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions HonkSharp/Functional/Recursor.cs
Original file line number Diff line number Diff line change
@@ -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<TIn, TOut> prec<TIn, TOut>(Func<TIn, Func<TIn, TOut>, TOut> recInfo)
{
TOut Inner(TIn arg)
{
return recInfo(arg, i => Inner(i));
}
return Inner;
}

public static Func<TIn, TOut> mrec<TIn, TOut>(Func<TIn, Func<TIn, TOut>, TOut> recInfo)
{
var dict = new Dictionary<TIn, TOut>();
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;
}
}
}
34 changes: 34 additions & 0 deletions Tests/Functional/RecursorTests.cs
Original file line number Diff line number Diff line change
@@ -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<int, int>((i, fact) => i switch {
0 => 1,
var n => n * fact(n - 1)
})(5));
}

[Fact]
public void Fibonacci()
{
Assert.Equal(1318412525,
mrec<int, int>((i, fib) => i switch {
0 or 1 => 1,
var n => fib(n - 1) + fib(n - 2)
})(1000));
}
}
}