Wiggins has asked for the wisdom of the Perl Monks concerning the following question:
Page 36 of "Higher Order Perl" contains a function called "find_share", as part of a solution to the partitioning problem.
The accompanying text says:sub find_share { my ($target, $treasures) = @_; return [] if $target == 0; # return 0 if $target == 0; #my code experiment # return '' if $target == 0; #my code experiment # return '0' if $target == 0; #my code experiment # return () if $target == 0; #my code experiment # return undef if $target == 0;#my code experiment return if $target < 0 || @$treasures == 0; my ($first, @rest) = @$treasures; my $solution = find_share($target-$first, \@rest); return [$first, @$solution] if $solution; return find_share($target , \@rest); } sub partition { my $total = 0; my $share_2; for my $treasure (@_) { $total += $treasure; } my $share_1 = find_share($total/2, [@_]); return unless defined $share_1; my %in_share_1; for my $treasure (@$share_1) { ++$in_share_1{$treasure}; } for my $treasure (@_) { if ($in_share_1{$treasure}) { --$in_share_1{$treasure}; } else { push @$share_2, $treasure; } } ## My code to run samples my ($rslt1,$rslt2) = partition ( 1,5,3,1,6,2 ); if ($rslt1){ printf "rslt1= %s\n",join ',',@$rslt1; printf "rslt2= %s\n",join ',',@$rslt2; }
We take care of some trivial cases first. If the target amount is exactly zero, then it's easy to produce a list of treasures that total the target amount: the empty list is sure to have value zero, so we return that right away.? return the 'empty list' right away? Wouldn't that be ()?
The closer I look, the more puzzling things are. But I think they all revolve around the use of the Anonymous Array Composer to passing references rather than data.
The calling sequence is:
which passes as argument 2, I am hoping; the parameter array and re-encapsulates it in an anonymous array and passes the reference to the encapsulation to find_share.my $share_1 = find_share($total/2, [@_]);
The number 0, the strings '0' and '', the empty list "()", and "undef" are all false in a boolean context. All other values are true.None of those values worked in place of [] (the commented lines). So what type and value is $solution???
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: A new FALSEness
by tilly (Archbishop) on Mar 03, 2009 at 20:56 UTC | |
Re: A new FALSEness
by ikegami (Patriarch) on Mar 03, 2009 at 20:57 UTC | |
Re: A new FALSEness
by kyle (Abbot) on Mar 03, 2009 at 21:07 UTC | |
by AnomalousMonk (Archbishop) on Mar 03, 2009 at 22:31 UTC | |
by Anomynous Monk (Scribe) on Mar 04, 2009 at 03:12 UTC | |
Re: A new FALSEness
by hbm (Hermit) on Mar 04, 2009 at 14:22 UTC |