func memoize[T comparable, U any](f func(T) U) func(T) U {
memory := make(map[T]U)
return func(t T) U {
if u, seen := memory[t]; seen {
return u
}
u := f(t)
memory[t] = u
return u
}
}
type
TCache = specialize TFPGMap<TKey, TData>;
var
Cache: TCache;
...
function m(Key: TKey): TData;
begin
if not Assigned(Cache) then
Cache := TCache.Create;
if not Cache.TryGetData(Key, Result) then
begin
Result := f(Key);
Cache.Add(Key, Result);
end;
end;
my %cache;
sub fib {
my $n = shift;
return $cache{$n} if exists $cache{$n};
return $cache{$n} = $n if $n < 2;
return $cache{$n} = fib($n-1) + fib($n-2);
}
print "\n\nCustom memoized implementation\n";
foreach my $n ( 1..10 ) {
print ' ' . fib( $n );
}
func memoize[T comparable, U any](f func(T) U) func(T) U {
memory := make(map[T]U)
return func(t T) U {
if u, seen := memory[t]; seen {
return u
}
u := f(t)
memory[t] = u
return u
}
}
type
TCache = specialize TFPGMap<TKey, TData>;
var
Cache: TCache;
...
function m(Key: TKey): TData;
begin
if not Assigned(Cache) then
Cache := TCache.Create;
if not Cache.TryGetData(Key, Result) then
begin
Result := f(Key);
Cache.Add(Key, Result);
end;
end;