pure function

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

以上文章节录自 http://perl.plover.com/yak/hw-dcpm/

1 comment

Leave a Reply

Your email address will not be published.

*