Be concise.
Be useful.
All contributions dictatorially edited by webmasters to match personal tastes.
Please do not paste any copyright violating material.
Please try to avoid dependencies to third-party libraries and frameworks.
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
}
}
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 );
}
m = Hash.new{|hash, key| hash[key] = f(key)}