in reply to Re^2: Recursion problem
in thread Recursion problem

for $target == 0 any list fulfills the condition

Que? If the target is 0 and the list 1, how does that meet the condition?


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
"Too many [] have been sedated by an oppressive environment of political correctness and risk aversion."

Replies are listed 'Best First'.
Re^4: Recursion problem
by moritz (Cardinal) on May 25, 2008 at 10:40 UTC
    Just pick zero elements of that list, they sum up to zero.

      Hm. A mathemeatically correct degenerate case I suppose, but given that the list can contain negative numbers, which makes a zero target a legitimate non-degenerate possibility, I can't see a useful case for returning an empty list and calling it success.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        I think you can argue both ways.

        My point was just that sometimes the base case for a recursion sometimes is much simpler than it seems. Your original code does roughly for both base case and recursive case (it iterates over the list and returns true if some condition holds), which is usually a sign that the base case could be chosen simpler.

        I frequently fell into that trap, resulting in longer and error-prone code, so I'd thought it's best to point out.

        Usually I'd handle such a case like that:

        sub sumTo { return 0 if $_[0] == 0 && @_ > 1; _sumTo(@_); # or &_sumTo if you want to be cryptic } sub _sumTo { my ($target, @list) = @_; return 1 if $target == 0; return 0 if @list == 0; # here goes the recursive call to _sumTo }

        If you don't like wrapper functions you can use caller to determine if the current call is recursive.