Commits

Sergei Vavinov  committed f30e322

hashmap-based memoization

  • Participants
  • Parent commits d2b40eb

Comments (0)

Files changed (4)

File src/main/java/ru/yandex/bolts/function/Function.java

 
 import fj.F;
 
+import ru.yandex.bolts.collection.Cf;
+import ru.yandex.bolts.collection.MapF;
 import ru.yandex.bolts.function.forhuman.Comparator;
 
 
         };
     }
 
+    public Function<A, R> memoize() {
+        return new Function<A, R>() {
+            private final MapF<A, R> cache = Cf.hashMap();
+            public R apply(A a) {
+                return cache.getOrElseUpdate(a, Function.this);
+            }
+        };
+    }
+
 } //~

File src/main/java/ru/yandex/bolts/function/Function0.java

 package ru.yandex.bolts.function;
 
+import ru.yandex.bolts.collection.Cf;
+import ru.yandex.bolts.collection.MapF;
+import ru.yandex.bolts.collection.Option;
+import ru.yandex.bolts.collection.SetF;
+
 
 /**
  * @author Stepan Koltsov
             }
         };
     }
+
+    public Function0<R> memoize() {
+        return new Function0<R>() {
+            private boolean haveValue = false;
+            private R cached;
+            public R apply() {
+                if (haveValue) return cached;
+                cached = Function0.this.apply();
+                haveValue = true;
+                return cached;
+            }
+        };
+    }
+
 } //~

File src/main/java/ru/yandex/bolts/function/Function2.java

 public abstract class Function2<A, B, R> {
     public abstract R apply(A a, B b);
 
+
+
     /** Bind first param to the given value */
     public Function<B, R> bind1(final A a) {
         return new Function<B, R>() {
         return (Function2<A1, B1, R1>) this;
     }
 
+    public Function2<A, B, R> memoize() {
+        return new Function2<A, B, R>() {
+            private final Function<Tuple2<A, B>, R> f = asFunction().memoize();
+            public R apply(A a, B b) {
+                return f.apply(Tuple2.tuple(a, b));
+            }
+        };
+    }
 
 } //~

File src/main/java/ru/yandex/bolts/function/Function3.java

         return (Function3<A1, B1, C1, R1>) this;
     }
 
+    public Function3<A, B, C, R> memoize() {
+        return new Function3<A, B, C, R>() {
+            private final Function<Tuple3<A, B, C>, R> f = asFunction().memoize();
+            public R apply(A a, B b, C c) {
+                return f.apply(Tuple3.tuple(a, b, c));
+            }
+        };
+    }
+
 } //~