【问题标题】:Java: Implement recursive cached from cached Function and cached BiFunctionJava:从缓存的函数和缓存的 BiFunction 实现递归缓存
【发布时间】:2021-01-17 08:19:29
【问题描述】:

TLDR:如何实现这个功能?

public static <T, R> Function<T, R> cachedRecursive(final BiFunction<T, Function<T,R>, R> bifunc) {
        
    }

我需要以某种方式从 BiFunction 中提取第二个参数,以便为该函数返回正确的结果。

这个项目是为了学习目的,虽然我被困在我任务的最后一部分。

任务的第一部分是创建一个从 LinkedHashMap 扩展的 Cache 类,这是我的实现:

public class Cache<K,V> extends LinkedHashMap<K, V> {


    private static int MaxSize;
    
    public Cache (int maxSize) {
        super(maxSize,1f,false);
        MaxSize = maxSize;
    }
    
    public Cache () {
        super();
    }
    
    public int getMaximalCacheSize () {
        return MaxSize;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > MaxSize;
    }
}

至于第二部分,是创建一个将为其添加函数定义的类:

public class FunctionCache {
    
    private static class Pair<T, U> {
        private T stored_t;
        private U stored_u;
        
        public Pair(T t, U u) {
            stored_t = t;
            stored_u = u;
        }
        
        public boolean equals(Object t) {
            
            if (t == this) {
                return true;
            }
            
            return t == stored_t;
        }
        
        public int hashCode () {
            return stored_t.hashCode();
        }
        
        public T get_first() {
            return stored_t;
        }
        
        public U get_second() {
            return stored_u;
        }
    }
    
    private final static int DEFAULT_CACHE_SIZE = 10000;
    
    public static <T, R> Function<T, R> cached(final Function<T, R> func, int maximalCacheSize) {
        Cache<T, R> cache = new Cache<T,R>(maximalCacheSize);
        return input -> cache.computeIfAbsent(input, func);
    }

    public static <T, R> Function<T, R> cached(final Function<T, R> func) {
        Cache<T, R> cache = new Cache<T,R>(DEFAULT_CACHE_SIZE);
        return input -> cache.computeIfAbsent(input, func);
    }
    
    public static <T, U, R> BiFunction<T, U, R> cached(BiFunction<T, U, R> bifunc, int maximalCacheSize) {
        Cache<T, R> cache = new Cache<T, R>(maximalCacheSize);
        
        return (t, u) -> {
            Pair<T,U> pairKey = new Pair<T,U>(t,u);
            
            Function<Pair<T,U>, R> something = input -> {
                return bifunc.apply(input.get_first(), input.get_second());
            };
            
            if (!cache.containsKey(pairKey.get_first())) {
                R result = something.apply(pairKey);
                cache.put(pairKey.get_first(), result);
                
                return result;
            } else {
                return cache.get(pairKey.get_first());
            }
        };
    }
    
    public static <T, U, R> BiFunction<T, U, R> cached(BiFunction<T, U, R> bifunc) {
        Cache<T, R> cache = new Cache<T, R>(DEFAULT_CACHE_SIZE);
        
        return (t, u) -> {
            Pair<T,U> pairKey = new Pair<T,U>(t,u);
            
            Function<Pair<T,U>, R> something = input -> {
                return bifunc.apply(input.get_first(), input.get_second());
            };
            
            
            if (!cache.containsKey(pairKey.get_first())) {
                R result = something.apply(pairKey);
                cache.put(pairKey.get_first(), result);
                
                return result;
            } else {
                return cache.get(pairKey.get_first());
            }
        };
    }
    
    public static <T, R> Function<T, R> cachedRecursive(final BiFunction<T, Function<T,R>, R> bifunc) {
        
    }
}

这是我的问题:

public static <T, R> Function<T, R> cachedRecursive(final BiFunction<T, Function<T,R>, R> bifunc) {
        
    }

我完全不知道如何实现 cachedRecursive 函数,之前的函数可以完美地处理一个简单的斐波那契测试,但是这个任务的目标是实现 cachedRecursive 函数,该函数将 BiFunction 与第一个参数作为输入第二个参数是一个函数。只是为了补全代码,这是我用来测试的主类:

public class cachedFunction extends FunctionCache {


public static void main(String[] args) {
        
        @SuppressWarnings({ "rawtypes", "unchecked" })
        BiFunction<BigInteger, BiFunction, BigInteger> fibHelper = cached((n, f) -> {
            if (n.compareTo(BigInteger.TWO) <= 0) return BigInteger.ONE;
            
            return ((BigInteger) (f.apply(n.subtract(BigInteger.ONE), f)))
                    .add((BigInteger)f.apply(n.subtract(BigInteger.TWO), f));
        }, 50000);
        
        Function<BigInteger, BigInteger> fib = cached((n) -> fibHelper.apply(n,fibHelper));
        
        System.out.println(fib.apply(BigInteger.valueOf(1000L)));
    }
}

【问题讨论】:

  • 只是一个提示,这是一种快速毕业的方法;)

标签: java memoization generic-lambda


【解决方案1】:

你的代码有很多缺点和错误:

  • static 在不同缓存实例之间共享的大小变量(因此破坏它);
  • 代码重复;
  • 不正确的equals/hashCode合约执行;
  • 抑制应该修复而不是抑制的内容;
  • 代码过于臃肿;
  • 和一些次要的(如_-包含小写名称等)。

如果你不介意,我简化一下:

final class Functions {

    private Functions() {
    }

    // memoize a simple "unknown" function -- simply delegates to a private encapsulated method
    static <T, R> Function<T, R> memoize(final Function<? super T, ? extends R> f, final int maxSize) {
        return createCacheFunction(f, maxSize);
    }

    // memoize a recursive function
    // note that the bi-function can be converted to an unary function and vice versa
    static <T, R> Function<T, R> memoize(final BiFunction<? super T, ? super Function<? super T, ? extends R>, ? extends R> f, final int maxSize) {
        final Function<UnaryR<T, Function<T, R>>, R> memoizedF = memoize(unaryR -> f.apply(unaryR.t, unaryR.r), maxSize);
        return new Function<T, R>() {
            @Override
            public R apply(final T t) {
                // this is the "magic"
                return memoizedF.apply(new UnaryR<>(t, this));
            }
        };
    }

    private static <T, R> Function<T, R> createCacheFunction(final Function<? super T, ? extends R> f, final int maxSize) {
        final Map<T, R> cache = new LinkedHashMap<T, R>(maxSize, 1F, false) {
            @Override
            protected boolean removeEldestEntry(final Map.Entry eldest) {
                return size() > maxSize;
            }
        };
        return t -> cache.computeIfAbsent(t, f);
    }

    // these annotations generate proper `equals` and `hashCode`, and a to-string implementation to simplify debugging
    @EqualsAndHashCode
    @ToString
    private static final class UnaryR<T, R> {

        @EqualsAndHashCode.Include
        private final T t;

        @EqualsAndHashCode.Exclude
        private final R r;

        private UnaryR(final T t, final R r) {
            this.t = t;
            this.r = r;
        }

    }

}

以及测试结果和记忆合同的测试(“如果记忆了,则不重新计算”):

public final class FunctionsTest {

    @Test
    public void testMemoizeRecursive() {
        final BiFunction<BigInteger, Function<? super BigInteger, ? extends BigInteger>, BigInteger> fib = (n, f) -> n.compareTo(BigInteger.valueOf(2)) <= 0 ? BigInteger.ONE : f.apply(n.subtract(BigInteger.ONE)).add(f.apply(n.subtract(BigInteger.valueOf(2))));
        @SuppressWarnings("unchecked")
        final BiFunction<BigInteger, Function<? super BigInteger, ? extends BigInteger>, BigInteger> mockedFib = Mockito.mock(BiFunction.class, AdditionalAnswers.delegatesTo(fib));
        final Function<BigInteger, BigInteger> memoizedFib = Functions.memoize(mockedFib, 1000);
        final BigInteger memoizedResult = memoizedFib.apply(BigInteger.valueOf(120));
        Mockito.verify(mockedFib, Mockito.times(120))
                .apply(Matchers.any(), Matchers.any());
        Assertions.assertEquals("5358359254990966640871840", memoizedResult.toString());
        Assertions.assertEquals(memoizedResult, memoizedFib.apply(BigInteger.valueOf(120)));
        Mockito.verifyNoMoreInteractions(mockedFib);
    }

}

【讨论】:

  • @DominickNavarro 嗯,确实如此。你看到// this is the "magic" 行了吗?它明确回答了您的 TL;DR 中的问题。
猜你喜欢
  • 2011-11-23
  • 1970-01-01
  • 2015-07-19
  • 2012-05-08
  • 1970-01-01
  • 2018-09-26
  • 2011-03-04
  • 2018-10-14
  • 2013-07-31
相关资源
最近更新 更多