From 967e1e32661a53f896dcd07c832cdd5e205c6be3 Mon Sep 17 00:00:00 2001
From: Suzanne Soy <env@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<A,Func<B,Func<C,D>>> Curry<A,B,C,D>(this Func<A,B,C,D> f) {
     return a => b => c => f(a, b, c);
   }
+
+  public static Func<A, B> Memoize<A, B>(this Func<A, B> f) where A : IEquatable<A> {
+    var d = new Dictionary<A, B>();
+    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