You know you're starting to think in O'Caml when...

robin on 2002-05-25T14:57:14

You write Perl code like this:

sub gron {
  my ($f, $total, $width) = @_;
  my $veet;
  $veet = sub {
    my ($partial, $subtotal, $n) = @_;
    my $rem = $total - $subtotal;
    if ($n+1 == $width) {
      $f->($rem, @$partial);
    }
    else {
      $veet->([$_, @$partial], $subtotal+$_, $n+1) for 0..$rem;
    }
  };
  $veet->([], 0, 0);
}

gron(sub {print($_ ? $_ : " ") for @_; print "\n"}, 3, 27);
I'm fairly sure that the idea of using a recursive closure in Perl has never crossed my mind before. Notice the disguised conses as well :-)


Recursive closures

Simon on 2002-05-25T15:38:08

See B::Utils for a doubly-recursive closure. That broke my brane.

Recursive closures

TorgoX on 2002-05-25T19:45:04

I think I use a bunch of recursive closures in HTML::Element. The trick is that (unless you use a Y-operator, which is fiendish) once you define this:

my $x; $x = sub { ... $x->(...) ... };

...you've just defined a circular data structure. So once you're finished with the whole excursion of calling $x, you have to undef $x or the sub-object doesn't get destroyed -- at least last I checked.

Re:Recursive closures

koschei on 2002-05-25T21:08:53

Do you happen to have an example of the use of one of these fiendish Y operators in Perl? (If you don't, don't feel compelled to write one if you don't want to, I'm mostly only curious for curiosity's sake.)

Y Operator in Perl

TorgoX on 2002-05-25T23:26:00

http://www.speech.cs.cmu.edu/user/sburke/pub/y_operator.pl

Re: Y Operator in Perl

robin on 2002-05-26T12:32:46

That reminds me of a staggering bit of obfuscated Haskell programming.