A pure function:
Has no side effects
Return value depends only on arguments
Example:
sub factorial {
my $n = shift;
$n == 0 ? 1 : $n * factorial($n-1);
}
cache 只对 pure function 有意义。
这可以思考,查询一个档案的修改时间的这种 function,他并非一个 pure function,所以,对非 pure function 做 cache 是没有意义的,这里有一个例子:
Highly Recursive Functions
sub fib {
my ($n) = @_;
return $n if $n ==0 || $n == 1;
return fib($n-2) + fib($n-1);
}
This function is very very slow!
Caching Fixes Recursion
Solution: Caching
@fib = (0, 1);
sub fib {
my ($n) = @_;
return $fib[$n] if defined $fib[$n];
return $fib[$n] = fib($n-1) + fib($n-2);
}
fib(20) computes fib(18) and fib(19)
fib(19) goes to compute fib(18)
But it is already in $fib[18]
Function is now very fast,Almost as fast as a pure iterative version,
Unlike the iterative version, this version required no ingenuity
学习一下函数式编程会更有帮助