Ok so in C# I could write:
public class Memorizer<K,TRes>
{
private Dictionary<K,TRes> _mem;
private Func<K,TRes> _function
public Memorizer (Func<K,TRes> function)
{
_function = function;
_mem= new Dictionary<K,TRes>();
}
public TRes Call(K arg)
{
if (mem.ContainsKey(arg)
{
return _mem[arg];
}
else
{
TRes ret=_function(arg);
_mem[arg] = ret;
return ret;
}
}
}
Which could be made use of for obvious gains:
public class FactorialCalculator()
{
private Memorizer<ushort, ulong> _memorizedFactorial;
public FactorialCalculator()
{
_memorizedFactorial = new Memorizer<ushort, ulong> (innerFactorial);
}
private ulong innerFactorial(ushort x)
{
return (x=0) ? 1 : x*Factorial(x-1)
}
public ulong factorial(ushort x)
{
_memorizedFactorial.Call(x);
}
}
I’m sure it could be made more general and elegant.
And I know I’ll have overflow exceptions if x>20.
(And I may have typecast errors in there too)
BUt hopefully I made my point: i can create a class that can furful the needs for memoisation of pure mathematical functions (I.e. deterministic, side-effect free functions)
and get wonderful performance gains.
How can I accomplish a similar thing in Java?
You can’t pass functions as data types in java. To fix this, use an interface.
Now you can set innerFactorial to a data type.
This lets you pass
innerFactorialas a data type:And to call the function you write this:
Also, in Java don’t capitalize field or method names. It’s not standard and makes the code harder to read.