From 967e1e32661a53f896dcd07c832cdd5e205c6be3 Mon Sep 17 00:00:00 2001 From: Suzanne Soy Date: Wed, 19 Aug 2020 02:27:39 +0000 Subject: [PATCH] Simple function memoization --- Utils/Func.cs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/Utils/Func.cs b/Utils/Func.cs index 5572467..19e942a 100644 --- a/Utils/Func.cs +++ b/Utils/Func.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Linq; public static class Func { @@ -26,4 +27,17 @@ public static class Func { public static Func>> Curry(this Func f) { return a => b => c => f(a, b, c); } + + public static Func Memoize(this Func f) where A : IEquatable { + var d = new Dictionary(); + return a => { + if (d.TryGetValue(a, out var b)) { + return b; + } else { + var calcB = f(a); + d.Add(a, calcB); + return calcB; + } + }; + } } \ No newline at end of file