cartesian_product_rec.pl 686 B

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 23 April 2017
  4. # https://github.com/trizen
  5. # Recursive algorithm for computing the Cartesian product.
  6. # Algorithm from Math::Cartesian::Product
  7. # https://metacpan.org/pod/Math::Cartesian::Product
  8. use 5.016;
  9. use warnings;
  10. sub cartesian(&@) {
  11. my ($callback, @C) = @_;
  12. my (@c, @r);
  13. sub {
  14. if (@c < @C) {
  15. for my $item (@{$C[@c]}) {
  16. CORE::push(@c, $item);
  17. __SUB__->();
  18. CORE::pop(@c);
  19. }
  20. }
  21. else {
  22. $callback->(@c);
  23. }
  24. }
  25. ->();
  26. }
  27. cartesian {
  28. say "@_";
  29. } (['a', 'b'], ['c', 'd', 'e'], ['f', 'g']);