kyle_burton ([info]kyle_burton) wrote,
@ 2008-06-18 09:14:00
Previous Entry  Add to memories!  Tell a Friend  Next Entry
Entry tags:perl programming functional-programming

Idempotency or Singleton Memoization

sub makeDoOnce {
  my($sub) = @_;
  my $alreadyDone = undef;
  my @result      = undef;
  my $exception   = undef;
  return sub {
    die $exception if $exception;
    if ($alreadyDone) {return wantarray ? @result : $result[0];}

    eval {
      my $w = wantarray;
      if (not defined $w) {             $sub->(@_)}
      if ($w)             {@result    = $sub->(@_)}
      else                {$result[0] = $sub->(@_)}
    };
    $exception = $@ if $@;
    die $exception if $exception;
    $alreadyDone = 1;
    return wantarray ? @result : $result[0];
  };
}



Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…